trtc-sdk-v5 5.8.1-beta.9 → 5.8.1-ktv.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/trtc.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TRTC=t()}(this,(function(){function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},i=function(e){try{return!!e()}catch(t){return!0}},r=!i((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),n=r,o=Function.prototype,s=o.call,a=n&&o.bind.bind(s,s),c=n?a:function(e){return function(){return s.apply(e,arguments)}},l=c,d=l({}.toString),u=l("".slice),h=function(e){return u(d(e),8,-1)},p=i,m=h,_=Object,f=c("".split),g=p((function(){return!_("z").propertyIsEnumerable(0)}))?function(e){return"String"===m(e)?f(e,""):_(e)}:_,T=function(e){return null==e},E=T,v=TypeError,y=function(e){if(E(e))throw new v("Can't call method on "+e);return e},S=g,I=y,A=function(e){return S(I(e))},R=function(e){return e&&e.Math===Math&&e},C=R("object"==typeof globalThis&&globalThis)||R("object"==typeof window&&window)||R("object"==typeof self&&self)||R("object"==typeof t&&t)||R("object"==typeof t&&t)||function(){return this}()||Function("return this")(),b={},k={get exports(){return b},set exports(e){b=e}},D=C,N=Object.defineProperty,w=function(e,t){try{N(D,e,{value:t,configurable:!0,writable:!0})}catch(i){D[e]=t}return t},O=C,P=w,M="__core-js_shared__",L=k.exports=O[M]||P(M,{});(L.versions||(L.versions=[])).push({version:"3.38.1",mode:"global",copyright:"© 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.1/LICENSE",source:"https://github.com/zloirock/core-js"});var x,V,U=b,F=function(e,t){return U[e]||(U[e]=t||{})},B=y,H=Object,j=function(e){return H(B(e))},W=j,G=c({}.hasOwnProperty),J=Object.hasOwn||function(e,t){return G(W(e),t)},z=c,K=0,q=Math.random(),Y=z(1..toString),Q=function(e){return"Symbol("+(void 0===e?"":e)+")_"+Y(++K+q,36)},X=C.navigator,$=X&&X.userAgent,Z=$?String($):"",ee=C,te=Z,ie=ee.process,re=ee.Deno,ne=ie&&ie.versions||re&&re.version,oe=ne&&ne.v8;oe&&(V=(x=oe.split("."))[0]>0&&x[0]<4?1:+(x[0]+x[1])),!V&&te&&(!(x=te.match(/Edge\/(\d+)/))||x[1]>=74)&&(x=te.match(/Chrome\/(\d+)/))&&(V=+x[1]);var se=V,ae=se,ce=i,le=C.String,de=!!Object.getOwnPropertySymbols&&!ce((function(){var e=Symbol("symbol detection");return!le(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ae&&ae<41})),ue=de&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,he=F,pe=J,me=Q,_e=de,fe=ue,ge=C.Symbol,Te=he("wks"),Ee=fe?ge.for||ge:ge&&ge.withoutSetter||me,ve=function(e){return pe(Te,e)||(Te[e]=_e&&pe(ge,e)?ge[e]:Ee("Symbol."+e)),Te[e]},ye="object"==typeof document&&document.all,Se=void 0===ye&&void 0!==ye?function(e){return"function"==typeof e||e===ye}:function(e){return"function"==typeof e},Ie=Se,Ae=function(e){return"object"==typeof e?null!==e:Ie(e)},Re=Ae,Ce=String,be=TypeError,ke=function(e){if(Re(e))return e;throw new be(Ce(e)+" is not an object")},De={},Ne=!i((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})),we=Ne&&i((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Oe={},Pe=Ae,Me=C.document,Le=Pe(Me)&&Pe(Me.createElement),xe=function(e){return Le?Me.createElement(e):{}},Ve=xe,Ue=!Ne&&!i((function(){return 7!==Object.defineProperty(Ve("div"),"a",{get:function(){return 7}}).a})),Fe=r,Be=Function.prototype.call,He=Fe?Be.bind(Be):function(){return Be.apply(Be,arguments)},je=C,We=Se,Ge=function(e,t){return arguments.length<2?(i=je[e],We(i)?i:void 0):je[e]&&je[e][t];var i},Je=c({}.isPrototypeOf),ze=Ge,Ke=Se,qe=Je,Ye=Object,Qe=ue?function(e){return"symbol"==typeof e}:function(e){var t=ze("Symbol");return Ke(t)&&qe(t.prototype,Ye(e))},Xe=String,$e=function(e){try{return Xe(e)}catch(t){return"Object"}},Ze=Se,et=$e,tt=TypeError,it=function(e){if(Ze(e))return e;throw new tt(et(e)+" is not a function")},rt=it,nt=T,ot=function(e,t){var i=e[t];return nt(i)?void 0:rt(i)},st=He,at=Se,ct=Ae,lt=TypeError,dt=He,ut=Ae,ht=Qe,pt=ot,mt=function(e,t){var i,r;if("string"===t&&at(i=e.toString)&&!ct(r=st(i,e)))return r;if(at(i=e.valueOf)&&!ct(r=st(i,e)))return r;if("string"!==t&&at(i=e.toString)&&!ct(r=st(i,e)))return r;throw new lt("Can't convert object to primitive value")},_t=TypeError,ft=ve("toPrimitive"),gt=function(e,t){if(!ut(e)||ht(e))return e;var i,r=pt(e,ft);if(r){if(void 0===t&&(t="default"),i=dt(r,e,t),!ut(i)||ht(i))return i;throw new _t("Can't convert object to primitive value")}return void 0===t&&(t="number"),mt(e,t)},Tt=gt,Et=Qe,vt=function(e){var t=Tt(e,"string");return Et(t)?t:t+""},yt=Ne,St=Ue,It=we,At=ke,Rt=vt,Ct=TypeError,bt=Object.defineProperty,kt=Object.getOwnPropertyDescriptor,Dt="enumerable",Nt="configurable",wt="writable";Oe.f=yt?It?function(e,t,i){if(At(e),t=Rt(t),At(i),"function"==typeof e&&"prototype"===t&&"value"in i&&wt in i&&!i[wt]){var r=kt(e,t);r&&r[wt]&&(e[t]=i.value,i={configurable:Nt in i?i[Nt]:r[Nt],enumerable:Dt in i?i[Dt]:r[Dt],writable:!1})}return bt(e,t,i)}:bt:function(e,t,i){if(At(e),t=Rt(t),At(i),St)try{return bt(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Ct("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Ot=Math.ceil,Pt=Math.floor,Mt=Math.trunc||function(e){var t=+e;return(t>0?Pt:Ot)(t)},Lt=Mt,xt=function(e){var t=+e;return t!=t||0===t?0:Lt(t)},Vt=xt,Ut=Math.max,Ft=Math.min,Bt=function(e,t){var i=Vt(e);return i<0?Ut(i+t,0):Ft(i,t)},Ht=xt,jt=Math.min,Wt=function(e){var t=Ht(e);return t>0?jt(t,9007199254740991):0},Gt=Wt,Jt=function(e){return Gt(e.length)},zt=A,Kt=Bt,qt=Jt,Yt=function(e){return function(t,i,r){var n=zt(t),o=qt(n);if(0===o)return!e&&-1;var s,a=Kt(r,o);if(e&&i!=i){for(;o>a;)if((s=n[a++])!=s)return!0}else for(;o>a;a++)if((e||a in n)&&n[a]===i)return e||a||0;return!e&&-1}},Qt={includes:Yt(!0),indexOf:Yt(!1)},Xt={},$t=J,Zt=A,ei=Qt.indexOf,ti=Xt,ii=c([].push),ri=function(e,t){var i,r=Zt(e),n=0,o=[];for(i in r)!$t(ti,i)&&$t(r,i)&&ii(o,i);for(;t.length>n;)$t(r,i=t[n++])&&(~ei(o,i)||ii(o,i));return o},ni=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],oi=ri,si=ni,ai=Object.keys||function(e){return oi(e,si)},ci=Ne,li=we,di=Oe,ui=ke,hi=A,pi=ai;De.f=ci&&!li?Object.defineProperties:function(e,t){ui(e);for(var i,r=hi(t),n=pi(t),o=n.length,s=0;o>s;)di.f(e,i=n[s++],r[i]);return e};var mi,_i=Ge("document","documentElement"),fi=Q,gi=F("keys"),Ti=function(e){return gi[e]||(gi[e]=fi(e))},Ei=ke,vi=De,yi=ni,Si=Xt,Ii=_i,Ai=xe,Ri="prototype",Ci="script",bi=Ti("IE_PROTO"),ki=function(){},Di=function(e){return"<"+Ci+">"+e+"</"+Ci+">"},Ni=function(e){e.write(Di("")),e.close();var t=e.parentWindow.Object;return e=null,t},wi=function(){try{mi=new ActiveXObject("htmlfile")}catch(n){}var e,t,i;wi="undefined"!=typeof document?document.domain&&mi?Ni(mi):(t=Ai("iframe"),i="java"+Ci+":",t.style.display="none",Ii.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(Di("document.F=Object")),e.close(),e.F):Ni(mi);for(var r=yi.length;r--;)delete wi[Ri][yi[r]];return wi()};Si[bi]=!0;var Oi=Object.create||function(e,t){var i;return null!==e?(ki[Ri]=Ei(e),i=new ki,ki[Ri]=null,i[bi]=e):i=wi(),void 0===t?i:vi.f(i,t)},Pi=ve,Mi=Oi,Li=Oe.f,xi=Pi("unscopables"),Vi=Array.prototype;void 0===Vi[xi]&&Li(Vi,xi,{configurable:!0,value:Mi(null)});var Ui,Fi,Bi,Hi=function(e){Vi[xi][e]=!0},ji={},Wi=Se,Gi=C.WeakMap,Ji=Wi(Gi)&&/native code/.test(String(Gi)),zi=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},Ki=Oe,qi=zi,Yi=Ne?function(e,t,i){return Ki.f(e,t,qi(1,i))}:function(e,t,i){return e[t]=i,e},Qi=Ji,Xi=C,$i=Ae,Zi=Yi,er=J,tr=b,ir=Ti,rr=Xt,nr="Object already initialized",or=Xi.TypeError,sr=Xi.WeakMap;if(Qi||tr.state){var ar=tr.state||(tr.state=new sr);ar.get=ar.get,ar.has=ar.has,ar.set=ar.set,Ui=function(e,t){if(ar.has(e))throw new or(nr);return t.facade=e,ar.set(e,t),t},Fi=function(e){return ar.get(e)||{}},Bi=function(e){return ar.has(e)}}else{var cr=ir("state");rr[cr]=!0,Ui=function(e,t){if(er(e,cr))throw new or(nr);return t.facade=e,Zi(e,cr,t),t},Fi=function(e){return er(e,cr)?e[cr]:{}},Bi=function(e){return er(e,cr)}}var lr={set:Ui,get:Fi,has:Bi,enforce:function(e){return Bi(e)?Fi(e):Ui(e,{})},getterFor:function(e){return function(t){var i;if(!$i(t)||(i=Fi(t)).type!==e)throw new or("Incompatible receiver, "+e+" required");return i}}},dr={},ur={},hr={}.propertyIsEnumerable,pr=Object.getOwnPropertyDescriptor,mr=pr&&!hr.call({1:2},1);ur.f=mr?function(e){var t=pr(this,e);return!!t&&t.enumerable}:hr;var _r=Ne,fr=He,gr=ur,Tr=zi,Er=A,vr=vt,yr=J,Sr=Ue,Ir=Object.getOwnPropertyDescriptor;dr.f=_r?Ir:function(e,t){if(e=Er(e),t=vr(t),Sr)try{return Ir(e,t)}catch(i){}if(yr(e,t))return Tr(!fr(gr.f,e,t),e[t])};var Ar={},Rr={get exports(){return Ar},set exports(e){Ar=e}},Cr=Ne,br=J,kr=Function.prototype,Dr=Cr&&Object.getOwnPropertyDescriptor,Nr=br(kr,"name"),wr={EXISTS:Nr,PROPER:Nr&&"something"===function(){}.name,CONFIGURABLE:Nr&&(!Cr||Cr&&Dr(kr,"name").configurable)},Or=Se,Pr=b,Mr=c(Function.toString);Or(Pr.inspectSource)||(Pr.inspectSource=function(e){return Mr(e)});var Lr=Pr.inspectSource,xr=c,Vr=i,Ur=Se,Fr=J,Br=Ne,Hr=wr.CONFIGURABLE,jr=Lr,Wr=lr.enforce,Gr=lr.get,Jr=String,zr=Object.defineProperty,Kr=xr("".slice),qr=xr("".replace),Yr=xr([].join),Qr=Br&&!Vr((function(){return 8!==zr((function(){}),"length",{value:8}).length})),Xr=String(String).split("String"),$r=Rr.exports=function(e,t,i){"Symbol("===Kr(Jr(t),0,7)&&(t="["+qr(Jr(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Fr(e,"name")||Hr&&e.name!==t)&&(Br?zr(e,"name",{value:t,configurable:!0}):e.name=t),Qr&&i&&Fr(i,"arity")&&e.length!==i.arity&&zr(e,"length",{value:i.arity});try{i&&Fr(i,"constructor")&&i.constructor?Br&&zr(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var r=Wr(e);return Fr(r,"source")||(r.source=Yr(Xr,"string"==typeof t?t:"")),e};Function.prototype.toString=$r((function(){return Ur(this)&&Gr(this).source||jr(this)}),"toString");var Zr=Se,en=Oe,tn=Ar,rn=w,nn=function(e,t,i,r){r||(r={});var n=r.enumerable,o=void 0!==r.name?r.name:t;if(Zr(i)&&tn(i,o,r),r.global)n?e[t]=i:rn(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch(s){}n?e[t]=i:en.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},on={},sn=ri,an=ni.concat("length","prototype");on.f=Object.getOwnPropertyNames||function(e){return sn(e,an)};var cn={};cn.f=Object.getOwnPropertySymbols;var ln,dn,un,hn=Ge,pn=on,mn=cn,_n=ke,fn=c([].concat),gn=hn("Reflect","ownKeys")||function(e){var t=pn.f(_n(e)),i=mn.f;return i?fn(t,i(e)):t},Tn=J,En=gn,vn=dr,yn=Oe,Sn=function(e,t,i){for(var r=En(t),n=yn.f,o=vn.f,s=0;s<r.length;s++){var a=r[s];Tn(e,a)||i&&Tn(i,a)||n(e,a,o(t,a))}},In=i,An=Se,Rn=/#|\.prototype\./,Cn=function(e,t){var i=kn[bn(e)];return i===Nn||i!==Dn&&(An(t)?In(t):!!t)},bn=Cn.normalize=function(e){return String(e).replace(Rn,".").toLowerCase()},kn=Cn.data={},Dn=Cn.NATIVE="N",Nn=Cn.POLYFILL="P",wn=Cn,On=C,Pn=dr.f,Mn=Yi,Ln=nn,xn=w,Vn=Sn,Un=wn,Fn=function(e,t){var i,r,n,o,s,a=e.target,c=e.global,l=e.stat;if(i=c?On:l?On[a]||xn(a,{}):On[a]&&On[a].prototype)for(r in t){if(o=t[r],n=e.dontCallGetSet?(s=Pn(i,r))&&s.value:i[r],!Un(c?r:a+(l?".":"#")+r,e.forced)&&void 0!==n){if(typeof o==typeof n)continue;Vn(o,n)}(e.sham||n&&n.sham)&&Mn(o,"sham",!0),Ln(i,r,o,e)}},Bn=!i((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Hn=J,jn=Se,Wn=j,Gn=Bn,Jn=Ti("IE_PROTO"),zn=Object,Kn=zn.prototype,qn=Gn?zn.getPrototypeOf:function(e){var t=Wn(e);if(Hn(t,Jn))return t[Jn];var i=t.constructor;return jn(i)&&t instanceof i?i.prototype:t instanceof zn?Kn:null},Yn=i,Qn=Se,Xn=Ae,$n=qn,Zn=nn,eo=ve("iterator"),to=!1;[].keys&&("next"in(un=[].keys())?(dn=$n($n(un)))!==Object.prototype&&(ln=dn):to=!0);var io=!Xn(ln)||Yn((function(){var e={};return ln[eo].call(e)!==e}));io&&(ln={}),Qn(ln[eo])||Zn(ln,eo,(function(){return this}));var ro={IteratorPrototype:ln,BUGGY_SAFARI_ITERATORS:to},no=Oe.f,oo=J,so=ve("toStringTag"),ao=function(e,t,i){e&&!i&&(e=e.prototype),e&&!oo(e,so)&&no(e,so,{configurable:!0,value:t})},co=ro.IteratorPrototype,lo=Oi,uo=zi,ho=ao,po=ji,mo=function(){return this},_o=function(e,t,i,r){var n=t+" Iterator";return e.prototype=lo(co,{next:uo(+!r,i)}),ho(e,n,!1),po[n]=mo,e},fo=c,go=it,To=Ae,Eo=function(e){return To(e)||null===e},vo=String,yo=TypeError,So=function(e,t,i){try{return fo(go(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},Io=Ae,Ao=y,Ro=function(e){if(Eo(e))return e;throw new yo("Can't set "+vo(e)+" as a prototype")},Co=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=So(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return Ao(i),Ro(r),Io(i)?(t?e(i,r):i.__proto__=r,i):i}}():void 0),bo=Fn,ko=He,Do=Se,No=_o,wo=qn,Oo=Co,Po=ao,Mo=Yi,Lo=nn,xo=ji,Vo=wr.PROPER,Uo=wr.CONFIGURABLE,Fo=ro.IteratorPrototype,Bo=ro.BUGGY_SAFARI_ITERATORS,Ho=ve("iterator"),jo="keys",Wo="values",Go="entries",Jo=function(){return this},zo=function(e,t,i,r,n,o,s){No(i,t,r);var a,c,l,d=function(e){if(e===n&&_)return _;if(!Bo&&e&&e in p)return p[e];switch(e){case jo:case Wo:case Go:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[Ho]||p["@@iterator"]||n&&p[n],_=!Bo&&m||d(n),f="Array"===t&&p.entries||m;if(f&&(a=wo(f.call(new e)))!==Object.prototype&&a.next&&(wo(a)!==Fo&&(Oo?Oo(a,Fo):Do(a[Ho])||Lo(a,Ho,Jo)),Po(a,u,!0)),Vo&&n===Wo&&m&&m.name!==Wo&&(Uo?Mo(p,"name",Wo):(h=!0,_=function(){return ko(m,this)})),n)if(c={values:d(Wo),keys:o?_:d(jo),entries:d(Go)},s)for(l in c)(Bo||h||!(l in p))&&Lo(p,l,c[l]);else bo({target:t,proto:!0,forced:Bo||h},c);return p[Ho]!==_&&Lo(p,Ho,_,{name:n}),xo[t]=_,c},Ko=function(e,t){return{value:e,done:t}},qo=A,Yo=Hi,Qo=ji,Xo=lr,$o=Oe.f,Zo=zo,es=Ko,ts=Ne,is="Array Iterator",rs=Xo.set,ns=Xo.getterFor(is),os=Zo(Array,"Array",(function(e,t){rs(this,{type:is,target:qo(e),index:0,kind:t})}),(function(){var e=ns(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,es(void 0,!0);switch(e.kind){case"keys":return es(i,!1);case"values":return es(t[i],!1)}return es([i,t[i]],!1)}),"values"),ss=Qo.Arguments=Qo.Array;if(Yo("keys"),Yo("values"),Yo("entries"),ts&&"values"!==ss.name)try{$o(ss,"name",{value:"values"})}catch(YF){}var as={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},cs=xe("span").classList,ls=cs&&cs.constructor&&cs.constructor.prototype,ds=ls===Object.prototype?void 0:ls,us=C,hs=as,ps=ds,ms=os,_s=Yi,fs=ao,gs=ve("iterator"),Ts=ms.values,Es=function(e,t){if(e){if(e[gs]!==Ts)try{_s(e,gs,Ts)}catch(YF){e[gs]=Ts}if(fs(e,t,!0),hs[t])for(var i in ms)if(e[i]!==ms[i])try{_s(e,i,ms[i])}catch(YF){e[i]=ms[i]}}};for(var vs in hs)Es(us[vs]&&us[vs].prototype,vs);Es(ps,"DOMTokenList");var ys=C,Ss=Z,Is=h,As=function(e){return Ss.slice(0,e.length)===e},Rs=As("Bun/")?"BUN":As("Cloudflare-Workers")?"CLOUDFLARE":As("Deno/")?"DENO":As("Node.js/")?"NODE":ys.Bun&&"string"==typeof Bun.version?"BUN":ys.Deno&&"object"==typeof Deno.version?"DENO":"process"===Is(ys.process)?"NODE":ys.window&&ys.document?"BROWSER":"REST",Cs="NODE"===Rs,bs=Ar,ks=Oe,Ds=function(e,t,i){return i.get&&bs(i.get,t,{getter:!0}),i.set&&bs(i.set,t,{setter:!0}),ks.f(e,t,i)},Ns=Ge,ws=Ds,Os=Ne,Ps=ve("species"),Ms=function(e){var t=Ns(e);Os&&t&&!t[Ps]&&ws(t,Ps,{configurable:!0,get:function(){return this}})},Ls=Je,xs=TypeError,Vs=function(e,t){if(Ls(t,e))return e;throw new xs("Incorrect invocation")},Us={};Us[ve("toStringTag")]="z";var Fs="[object z]"===String(Us),Bs=Se,Hs=h,js=ve("toStringTag"),Ws=Object,Gs="Arguments"===Hs(function(){return arguments}()),Js=Fs?Hs:function(e){var t,i,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(YF){}}(t=Ws(e),js))?i:Gs?Hs(t):"Object"===(r=Hs(t))&&Bs(t.callee)?"Arguments":r},zs=c,Ks=i,qs=Se,Ys=Js,Qs=Lr,Xs=function(){},$s=Ge("Reflect","construct"),Zs=/^\s*(?:class|function)\b/,ea=zs(Zs.exec),ta=!Zs.test(Xs),ia=function(e){if(!qs(e))return!1;try{return $s(Xs,[],e),!0}catch(YF){return!1}},ra=function(e){if(!qs(e))return!1;switch(Ys(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return ta||!!ea(Zs,Qs(e))}catch(YF){return!0}};ra.sham=!0;var na,oa,sa,aa,ca=!$s||Ks((function(){var e;return ia(ia.call)||!ia(Object)||!ia((function(){e=!0}))||e}))?ra:ia,la=ca,da=$e,ua=TypeError,ha=function(e){if(la(e))return e;throw new ua(da(e)+" is not a constructor")},pa=ke,ma=ha,_a=T,fa=ve("species"),ga=function(e,t){var i,r=pa(e).constructor;return void 0===r||_a(i=pa(r)[fa])?t:ma(i)},Ta=r,Ea=Function.prototype,va=Ea.apply,ya=Ea.call,Sa="object"==typeof Reflect&&Reflect.apply||(Ta?ya.bind(va):function(){return ya.apply(va,arguments)}),Ia=h,Aa=c,Ra=function(e){if("Function"===Ia(e))return Aa(e)},Ca=it,ba=r,ka=Ra(Ra.bind),Da=function(e,t){return Ca(e),void 0===t?e:ba?ka(e,t):function(){return e.apply(t,arguments)}},Na=c([].slice),wa=TypeError,Oa=function(e,t){if(e<t)throw new wa("Not enough arguments");return e},Pa=/(?:ipad|iphone|ipod).*applewebkit/i.test(Z),Ma=C,La=Sa,xa=Da,Va=Se,Ua=J,Fa=i,Ba=_i,Ha=Na,ja=xe,Wa=Oa,Ga=Pa,Ja=Cs,za=Ma.setImmediate,Ka=Ma.clearImmediate,qa=Ma.process,Ya=Ma.Dispatch,Qa=Ma.Function,Xa=Ma.MessageChannel,$a=Ma.String,Za=0,ec={},tc="onreadystatechange";Fa((function(){na=Ma.location}));var ic=function(e){if(Ua(ec,e)){var t=ec[e];delete ec[e],t()}},rc=function(e){return function(){ic(e)}},nc=function(e){ic(e.data)},oc=function(e){Ma.postMessage($a(e),na.protocol+"//"+na.host)};za&&Ka||(za=function(e){Wa(arguments.length,1);var t=Va(e)?e:Qa(e),i=Ha(arguments,1);return ec[++Za]=function(){La(t,void 0,i)},oa(Za),Za},Ka=function(e){delete ec[e]},Ja?oa=function(e){qa.nextTick(rc(e))}:Ya&&Ya.now?oa=function(e){Ya.now(rc(e))}:Xa&&!Ga?(aa=(sa=new Xa).port2,sa.port1.onmessage=nc,oa=xa(aa.postMessage,aa)):Ma.addEventListener&&Va(Ma.postMessage)&&!Ma.importScripts&&na&&"file:"!==na.protocol&&!Fa(oc)?(oa=oc,Ma.addEventListener("message",nc,!1)):oa=tc in ja("script")?function(e){Ba.appendChild(ja("script"))[tc]=function(){Ba.removeChild(this),ic(e)}}:function(e){setTimeout(rc(e),0)});var sc={set:za,clear:Ka},ac=C,cc=Ne,lc=Object.getOwnPropertyDescriptor,dc=function(e){if(!cc)return ac[e];var t=lc(ac,e);return t&&t.value},uc=function(){this.head=null,this.tail=null};uc.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 hc,pc,mc,_c,fc,gc=uc,Tc=/ipad|iphone|ipod/i.test(Z)&&"undefined"!=typeof Pebble,Ec=/web0s(?!.*chrome)/i.test(Z),vc=C,yc=dc,Sc=Da,Ic=sc.set,Ac=gc,Rc=Pa,Cc=Tc,bc=Ec,kc=Cs,Dc=vc.MutationObserver||vc.WebKitMutationObserver,Nc=vc.document,wc=vc.process,Oc=vc.Promise,Pc=yc("queueMicrotask");if(!Pc){var Mc=new Ac,Lc=function(){var e,t;for(kc&&(e=wc.domain)&&e.exit();t=Mc.get();)try{t()}catch(YF){throw Mc.head&&hc(),YF}e&&e.enter()};Rc||kc||bc||!Dc||!Nc?!Cc&&Oc&&Oc.resolve?((_c=Oc.resolve(void 0)).constructor=Oc,fc=Sc(_c.then,_c),hc=function(){fc(Lc)}):kc?hc=function(){wc.nextTick(Lc)}:(Ic=Sc(Ic,vc),hc=function(){Ic(Lc)}):(pc=!0,mc=Nc.createTextNode(""),new Dc(Lc).observe(mc,{characterData:!0}),hc=function(){mc.data=pc=!pc}),Pc=function(e){Mc.head||hc(),Mc.add(e)}}var xc=Pc,Vc=function(e){try{return{error:!1,value:e()}}catch(YF){return{error:!0,value:YF}}},Uc=C.Promise,Fc=C,Bc=Uc,Hc=Se,jc=wn,Wc=Lr,Gc=ve,Jc=Rs,zc=se;Bc&&Bc.prototype;var Kc=Gc("species"),qc=!1,Yc=Hc(Fc.PromiseRejectionEvent),Qc=jc("Promise",(function(){var e=Wc(Bc),t=e!==String(Bc);if(!t&&66===zc)return!0;if(!zc||zc<51||!/native code/.test(e)){var i=new Bc((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((i.constructor={})[Kc]=r,!(qc=i.then((function(){}))instanceof r))return!0}return!(t||"BROWSER"!==Jc&&"DENO"!==Jc||Yc)})),Xc={CONSTRUCTOR:Qc,REJECTION_EVENT:Yc,SUBCLASSING:qc},$c={},Zc=it,el=TypeError,tl=function(e){var t,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw new el("Bad Promise constructor");t=e,i=r})),this.resolve=Zc(t),this.reject=Zc(i)};$c.f=function(e){return new tl(e)};var il,rl,nl,ol=Fn,sl=Cs,al=C,cl=He,ll=nn,dl=Co,ul=ao,hl=Ms,pl=it,ml=Se,_l=Ae,fl=Vs,gl=ga,Tl=sc.set,El=xc,vl=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(YF){}},yl=Vc,Sl=gc,Il=lr,Al=Uc,Rl=$c,Cl="Promise",bl=Xc.CONSTRUCTOR,kl=Xc.REJECTION_EVENT,Dl=Xc.SUBCLASSING,Nl=Il.getterFor(Cl),wl=Il.set,Ol=Al&&Al.prototype,Pl=Al,Ml=Ol,Ll=al.TypeError,xl=al.document,Vl=al.process,Ul=Rl.f,Fl=Ul,Bl=!!(xl&&xl.createEvent&&al.dispatchEvent),Hl="unhandledrejection",jl=function(e){var t;return!(!_l(e)||!ml(t=e.then))&&t},Wl=function(e,t){var i,r,n,o=t.value,s=1===t.state,a=s?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{a?(s||(2===t.rejection&&ql(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),n=!0)),i===e.promise?l(new Ll("Promise-chain cycle")):(r=jl(i))?cl(r,i,c,l):c(i)):l(o)}catch(YF){d&&!n&&d.exit(),l(YF)}},Gl=function(e,t){e.notified||(e.notified=!0,El((function(){for(var i,r=e.reactions;i=r.get();)Wl(i,e);e.notified=!1,t&&!e.rejection&&zl(e)})))},Jl=function(e,t,i){var r,n;Bl?((r=xl.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),al.dispatchEvent(r)):r={promise:t,reason:i},!kl&&(n=al["on"+e])?n(r):e===Hl&&vl("Unhandled promise rejection",i)},zl=function(e){cl(Tl,al,(function(){var t,i=e.facade,r=e.value;if(Kl(e)&&(t=yl((function(){sl?Vl.emit("unhandledRejection",r,i):Jl(Hl,i,r)})),e.rejection=sl||Kl(e)?2:1,t.error))throw t.value}))},Kl=function(e){return 1!==e.rejection&&!e.parent},ql=function(e){cl(Tl,al,(function(){var t=e.facade;sl?Vl.emit("rejectionHandled",t):Jl("rejectionhandled",t,e.value)}))},Yl=function(e,t,i){return function(r){e(t,r,i)}},Ql=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Gl(e,!0))},Xl=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new Ll("Promise can't be resolved itself");var r=jl(t);r?El((function(){var i={done:!1};try{cl(r,t,Yl(Xl,i,e),Yl(Ql,i,e))}catch(YF){Ql(i,YF,e)}})):(e.value=t,e.state=1,Gl(e,!1))}catch(YF){Ql({done:!1},YF,e)}}};if(bl&&(Ml=(Pl=function(e){fl(this,Ml),pl(e),cl(il,this);var t=Nl(this);try{e(Yl(Xl,t),Yl(Ql,t))}catch(YF){Ql(t,YF)}}).prototype,(il=function(e){wl(this,{type:Cl,done:!1,notified:!1,parent:!1,reactions:new Sl,rejection:!1,state:0,value:null})}).prototype=ll(Ml,"then",(function(e,t){var i=Nl(this),r=Ul(gl(this,Pl));return i.parent=!0,r.ok=!ml(e)||e,r.fail=ml(t)&&t,r.domain=sl?Vl.domain:void 0,0===i.state?i.reactions.add(r):El((function(){Wl(r,i)})),r.promise})),rl=function(){var e=new il,t=Nl(e);this.promise=e,this.resolve=Yl(Xl,t),this.reject=Yl(Ql,t)},Rl.f=Ul=function(e){return e===Pl||undefined===e?new rl(e):Fl(e)},ml(Al)&&Ol!==Object.prototype)){nl=Ol.then,Dl||ll(Ol,"then",(function(e,t){var i=this;return new Pl((function(e,t){cl(nl,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete Ol.constructor}catch(YF){}dl&&dl(Ol,Ml)}ol({global:!0,constructor:!0,wrap:!0,forced:bl},{Promise:Pl}),ul(Pl,Cl,!1),hl(Cl);var $l=ji,Zl=ve("iterator"),ed=Array.prototype,td=function(e){return void 0!==e&&($l.Array===e||ed[Zl]===e)},id=Js,rd=ot,nd=T,od=ji,sd=ve("iterator"),ad=function(e){if(!nd(e))return rd(e,sd)||rd(e,"@@iterator")||od[id(e)]},cd=He,ld=it,dd=ke,ud=$e,hd=ad,pd=TypeError,md=function(e,t){var i=arguments.length<2?hd(e):t;if(ld(i))return dd(cd(i,e));throw new pd(ud(e)+" is not iterable")},_d=He,fd=ke,gd=ot,Td=function(e,t,i){var r,n;fd(e);try{if(!(r=gd(e,"return"))){if("throw"===t)throw i;return i}r=_d(r,e)}catch(YF){n=!0,r=YF}if("throw"===t)throw i;if(n)throw r;return fd(r),i},Ed=Da,vd=He,yd=ke,Sd=$e,Id=td,Ad=Jt,Rd=Je,Cd=md,bd=ad,kd=Td,Dd=TypeError,Nd=function(e,t){this.stopped=e,this.result=t},wd=Nd.prototype,Od=function(e,t,i){var r,n,o,s,a,c,l,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),_=Ed(t,d),f=function(e){return r&&kd(r,"normal",e),new Nd(!0,e)},g=function(e){return u?(yd(e),m?_(e[0],e[1],f):_(e[0],e[1])):m?_(e,f):_(e)};if(h)r=e.iterator;else if(p)r=e;else{if(!(n=bd(e)))throw new Dd(Sd(e)+" is not iterable");if(Id(n)){for(o=0,s=Ad(e);s>o;o++)if((a=g(e[o]))&&Rd(wd,a))return a;return new Nd(!1)}r=Cd(e,n)}for(c=h?e.next:r.next;!(l=vd(c,r)).done;){try{a=g(l.value)}catch(YF){kd(r,"throw",YF)}if("object"==typeof a&&a&&Rd(wd,a))return a}return new Nd(!1)},Pd=ve("iterator"),Md=!1;try{var Ld=0,xd={next:function(){return{done:!!Ld++}},return:function(){Md=!0}};xd[Pd]=function(){return this},Array.from(xd,(function(){throw 2}))}catch(YF){}var Vd=function(e,t){try{if(!t&&!Md)return!1}catch(YF){return!1}var i=!1;try{var r={};r[Pd]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(YF){}return i},Ud=Uc,Fd=Xc.CONSTRUCTOR||!Vd((function(e){Ud.all(e).then(void 0,(function(){}))})),Bd=He,Hd=it,jd=$c,Wd=Vc,Gd=Od;Fn({target:"Promise",stat:!0,forced:Fd},{all:function(e){var t=this,i=jd.f(t),r=i.resolve,n=i.reject,o=Wd((function(){var i=Hd(t.resolve),o=[],s=0,a=1;Gd(e,(function(e){var c=s++,l=!1;a++,Bd(i,t,e).then((function(e){l||(l=!0,o[c]=e,--a||r(o))}),n)})),--a||r(o)}));return o.error&&n(o.value),i.promise}});var Jd=Fn,zd=Xc.CONSTRUCTOR,Kd=Uc,qd=Ge,Yd=Se,Qd=nn,Xd=Kd&&Kd.prototype;if(Jd({target:"Promise",proto:!0,forced:zd,real:!0},{catch:function(e){return this.then(void 0,e)}}),Yd(Kd)){var $d=qd("Promise").prototype.catch;Xd.catch!==$d&&Qd(Xd,"catch",$d,{unsafe:!0})}var Zd=He,eu=it,tu=$c,iu=Vc,ru=Od;Fn({target:"Promise",stat:!0,forced:Fd},{race:function(e){var t=this,i=tu.f(t),r=i.reject,n=iu((function(){var n=eu(t.resolve);ru(e,(function(e){Zd(n,t,e).then(i.resolve,r)}))}));return n.error&&r(n.value),i.promise}});var nu=$c;Fn({target:"Promise",stat:!0,forced:Xc.CONSTRUCTOR},{reject:function(e){var t=nu.f(this);return(0,t.reject)(e),t.promise}});var ou=ke,su=Ae,au=$c,cu=function(e,t){if(ou(e),su(t)&&t.constructor===e)return t;var i=au.f(e);return(0,i.resolve)(t),i.promise},lu=Fn,du=Xc.CONSTRUCTOR,uu=cu;Ge("Promise"),lu({target:"Promise",stat:!0,forced:du},{resolve:function(e){return uu(this,e)}});var hu=Se,pu=Ae,mu=Co,_u=function(e,t,i){var r,n;return mu&&hu(r=t.constructor)&&r!==i&&pu(n=r.prototype)&&n!==i.prototype&&mu(e,n),e},fu=Ae,gu=h,Tu=ve("match"),Eu=Js,vu=String,yu=function(e){if("Symbol"===Eu(e))throw new TypeError("Cannot convert a Symbol value to a string");return vu(e)},Su=ke,Iu=function(){var e=Su(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},Au=He,Ru=J,Cu=Je,bu=Iu,ku=RegExp.prototype,Du=i,Nu=C.RegExp,wu=Du((function(){var e=Nu("a","y");return e.lastIndex=2,null!==e.exec("abcd")})),Ou=wu||Du((function(){return!Nu("a","y").sticky})),Pu=wu||Du((function(){var e=Nu("^r","gy");return e.lastIndex=2,null!==e.exec("str")})),Mu={BROKEN_CARET:Pu,MISSED_STICKY:Ou,UNSUPPORTED_Y:wu},Lu=Oe.f,xu=i,Vu=C.RegExp,Uu=xu((function(){var e=Vu(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)})),Fu=i,Bu=C.RegExp,Hu=Fu((function(){var e=Bu("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),ju=Ne,Wu=C,Gu=c,Ju=wn,zu=_u,Ku=Yi,qu=Oi,Yu=on.f,Qu=Je,Xu=function(e){var t;return fu(e)&&(void 0!==(t=e[Tu])?!!t:"RegExp"===gu(e))},$u=yu,Zu=function(e){var t=e.flags;return void 0!==t||"flags"in ku||Ru(e,"flags")||!Cu(ku,e)?t:Au(bu,e)},eh=Mu,th=function(e,t,i){i in e||Lu(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},ih=nn,rh=i,nh=J,oh=lr.enforce,sh=Ms,ah=Uu,ch=Hu,lh=ve("match"),dh=Wu.RegExp,uh=dh.prototype,hh=Wu.SyntaxError,ph=Gu(uh.exec),mh=Gu("".charAt),_h=Gu("".replace),fh=Gu("".indexOf),gh=Gu("".slice),Th=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,Eh=/a/g,vh=/a/g,yh=new dh(Eh)!==Eh,Sh=eh.MISSED_STICKY,Ih=eh.UNSUPPORTED_Y,Ah=ju&&(!yh||Sh||ah||ch||rh((function(){return vh[lh]=!1,dh(Eh)!==Eh||dh(vh)===vh||"/a/i"!==String(dh(Eh,"i"))})));if(Ju("RegExp",Ah)){for(var Rh=function(e,t){var i,r,n,o,s,a,c=Qu(uh,this),l=Xu(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Rh)return e;if((l||Qu(uh,e))&&(e=e.source,d&&(t=Zu(h))),e=void 0===e?"":$u(e),t=void 0===t?"":$u(t),h=e,ah&&"dotAll"in Eh&&(r=!!t&&fh(t,"s")>-1)&&(t=_h(t,/s/g,"")),i=t,Sh&&"sticky"in Eh&&(n=!!t&&fh(t,"y")>-1)&&Ih&&(t=_h(t,/y/g,"")),ch&&(o=function(e){for(var t,i=e.length,r=0,n="",o=[],s=qu(null),a=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=mh(e,r)))t+=mh(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:if(n+=t,"?:"===gh(e,r+1,r+3))continue;ph(Th,gh(e,r+1))&&(r+=2,c=!0),l++;continue;case">"===t&&c:if(""===d||nh(s,d))throw new hh("Invalid capture group name");s[d]=!0,o[o.length]=[d,l],c=!1,d="";continue}c?d+=t:n+=t}return[n,o]}(e),e=o[0],u=o[1]),s=zu(dh(e,t),c?this:uh,Rh),(r||n||u.length)&&(a=oh(s),r&&(a.dotAll=!0,a.raw=Rh(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=mh(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+mh(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Ku(s,"source",""===h?"(?:)":h)}catch(YF){}return s},Ch=Yu(dh),bh=0;Ch.length>bh;)th(Rh,dh,Ch[bh++]);uh.constructor=Rh,Rh.prototype=uh,ih(Wu,"RegExp",Rh,{constructor:!0})}sh("RegExp");var kh=He,Dh=c,Nh=yu,wh=Iu,Oh=Mu,Ph=Oi,Mh=lr.get,Lh=Uu,xh=Hu,Vh=F("native-string-replace",String.prototype.replace),Uh=RegExp.prototype.exec,Fh=Uh,Bh=Dh("".charAt),Hh=Dh("".indexOf),jh=Dh("".replace),Wh=Dh("".slice),Gh=function(){var e=/a/,t=/b*/g;return kh(Uh,e,"a"),kh(Uh,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Jh=Oh.BROKEN_CARET,zh=void 0!==/()??/.exec("")[1];(Gh||zh||Jh||Lh||xh)&&(Fh=function(e){var t,i,r,n,o,s,a,c=this,l=Mh(c),d=Nh(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=kh(Fh,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Jh&&c.sticky,m=kh(wh,c),_=c.source,f=0,g=d;if(p&&(m=jh(m,"y",""),-1===Hh(m,"g")&&(m+="g"),g=Wh(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Bh(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),zh&&(i=new RegExp("^"+_+"$(?!\\s)",m)),Gh&&(r=c.lastIndex),n=kh(Uh,p?i:c,g),p?n?(n.input=Wh(n.input,f),n[0]=Wh(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:Gh&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),zh&&n&&n.length>1&&kh(Vh,n[0],i,(function(){for(o=1;o<arguments.length-2;o++)void 0===arguments[o]&&(n[o]=void 0)})),n&&h)for(n.groups=s=Ph(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=n[a[1]];return n});var Kh=Fh;Fn({target:"RegExp",proto:!0,forced:/./.exec!==Kh},{exec:Kh});var qh=h,Yh=Array.isArray||function(e){return"Array"===qh(e)},Qh=Yh,Xh=ca,$h=Ae,Zh=ve("species"),ep=Array,tp=function(e){var t;return Qh(e)&&(t=e.constructor,(Xh(t)&&(t===ep||Qh(t.prototype))||$h(t)&&null===(t=t[Zh]))&&(t=void 0)),void 0===t?ep:t},ip=Da,rp=g,np=j,op=Jt,sp=function(e,t){return new(tp(e))(0===t?0:t)},ap=c([].push),cp=function(e){var t=1===e,i=2===e,r=3===e,n=4===e,o=6===e,s=7===e,a=5===e||o;return function(c,l,d,u){for(var h,p,m=np(c),_=rp(m),f=op(_),g=ip(l,d),T=0,E=u||sp,v=t?E(c,f):i||s?E(c,0):void 0;f>T;T++)if((a||T in _)&&(p=g(h=_[T],T,m),e))if(t)v[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:ap(v,h)}else switch(e){case 4:return!1;case 7:ap(v,h)}return o?-1:r||n?n:v}},lp={forEach:cp(0),map:cp(1),filter:cp(2),some:cp(3),every:cp(4),find:cp(5),findIndex:cp(6),filterReject:cp(7)},dp=i,up=function(e,t){var i=[][e];return!!i&&dp((function(){i.call(null,t||function(){return 1},1)}))},hp=lp.forEach,pp=up("forEach")?[].forEach:function(e){return hp(this,e,arguments.length>1?arguments[1]:void 0)},mp=C,_p=as,fp=ds,gp=pp,Tp=Yi,Ep=function(e){if(e&&e.forEach!==gp)try{Tp(e,"forEach",gp)}catch(YF){e.forEach=gp}};for(var vp in _p)_p[vp]&&Ep(mp[vp]&&mp[vp].prototype);Ep(fp);var yp=it,Sp=j,Ip=g,Ap=Jt,Rp=TypeError,Cp="Reduce of empty array with no initial value",bp=function(e){return function(t,i,r,n){var o=Sp(t),s=Ip(o),a=Ap(o);if(yp(i),0===a&&r<2)throw new Rp(Cp);var c=e?a-1:0,l=e?-1:1;if(r<2)for(;;){if(c in s){n=s[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw new Rp(Cp)}for(;e?c>=0:a>c;c+=l)c in s&&(n=i(n,s[c],c,o));return n}},kp={left:bp(!1),right:bp(!0)}.left;Fn({target:"Array",proto:!0,forced:!Cs&&se>79&&se<83||!up("reduce")},{reduce:function(e){var t=arguments.length;return kp(this,e,t,t>1?arguments[1]:void 0)}});var Dp=He,Np=nn,wp=Kh,Op=i,Pp=ve,Mp=Yi,Lp=Pp("species"),xp=RegExp.prototype,Vp=c,Up=xt,Fp=yu,Bp=y,Hp=Vp("".charAt),jp=Vp("".charCodeAt),Wp=Vp("".slice),Gp=function(e){return function(t,i){var r,n,o=Fp(Bp(t)),s=Up(i),a=o.length;return s<0||s>=a?e?"":void 0:(r=jp(o,s))<55296||r>56319||s+1===a||(n=jp(o,s+1))<56320||n>57343?e?Hp(o,s):r:e?Wp(o,s,s+2):n-56320+(r-55296<<10)+65536}},Jp={codeAt:Gp(!1),charAt:Gp(!0)},zp=Jp.charAt,Kp=c,qp=j,Yp=Math.floor,Qp=Kp("".charAt),Xp=Kp("".replace),$p=Kp("".slice),Zp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,em=/\$([$&'`]|\d{1,2})/g,tm=He,im=ke,rm=Se,nm=h,om=Kh,sm=TypeError,am=Sa,cm=He,lm=c,dm=function(e,t,i,r){var n=Pp(e),o=!Op((function(){var t={};return t[n]=function(){return 7},7!==""[e](t)})),s=o&&!Op((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[Lp]=function(){return i},i.flags="",i[n]=/./[n]),i.exec=function(){return t=!0,null},i[n](""),!t}));if(!o||!s||i){var a=/./[n],c=t(n,""[e],(function(e,t,i,r,n){var s=t.exec;return s===wp||s===xp.exec?o&&!n?{done:!0,value:Dp(a,t,i,r)}:{done:!0,value:Dp(e,i,t,r)}:{done:!1}}));Np(String.prototype,e,c[0]),Np(xp,n,c[1])}r&&Mp(xp[n],"sham",!0)},um=i,hm=ke,pm=Se,mm=T,_m=xt,fm=Wt,gm=yu,Tm=y,Em=function(e,t,i){return t+(i?zp(e,t).length:1)},vm=ot,ym=function(e,t,i,r,n,o){var s=i+e.length,a=r.length,c=em;return void 0!==n&&(n=qp(n),c=Zp),Xp(o,c,(function(o,c){var l;switch(Qp(c,0)){case"$":return"$";case"&":return e;case"`":return $p(t,0,i);case"'":return $p(t,s);case"<":l=n[$p(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Yp(d/10);return 0===u?o:u<=a?void 0===r[u-1]?Qp(c,1):r[u-1]+Qp(c,1):o}l=r[d-1]}return void 0===l?"":l}))},Sm=function(e,t){var i=e.exec;if(rm(i)){var r=tm(i,e,t);return null!==r&&im(r),r}if("RegExp"===nm(e))return tm(om,e,t);throw new sm("RegExp#exec called on incompatible receiver")},Im=ve("replace"),Am=Math.max,Rm=Math.min,Cm=lm([].concat),bm=lm([].push),km=lm("".indexOf),Dm=lm("".slice),Nm=function(e){return void 0===e?e:String(e)},wm="$0"==="a".replace(/./,"$0"),Om=!!/./[Im]&&""===/./[Im]("a","$0"),Pm=!um((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));dm("replace",(function(e,t,i){var r=Om?"$":"$0";return[function(e,i){var r=Tm(this),n=mm(e)?void 0:vm(e,Im);return n?cm(n,e,r,i):cm(t,gm(r),e,i)},function(e,n){var o=hm(this),s=gm(e);if("string"==typeof n&&-1===km(n,r)&&-1===km(n,"$<")){var a=i(t,o,s,n);if(a.done)return a.value}var c=pm(n);c||(n=gm(n));var l,d=o.global;d&&(l=o.unicode,o.lastIndex=0);for(var u,h=[];null!==(u=Sm(o,s))&&(bm(h,u),d);){""===gm(u[0])&&(o.lastIndex=Em(s,fm(o.lastIndex),l))}for(var p="",m=0,_=0;_<h.length;_++){for(var f,g=gm((u=h[_])[0]),T=Am(Rm(_m(u.index),s.length),0),E=[],v=1;v<u.length;v++)bm(E,Nm(u[v]));var y=u.groups;if(c){var S=Cm([g],E,T,s);void 0!==y&&bm(S,y),f=gm(am(n,void 0,S))}else f=ym(g,s,T,E,y,n);T>=m&&(p+=Dm(s,m,T)+f,m=T+g.length)}return p+Dm(s,m)}]}),!Pm||!wm||Om);var Mm=Qt.includes,Lm=Hi;Fn({target:"Array",proto:!0,forced:i((function(){return!Array(1).includes()}))},{includes:function(e){return Mm(this,e,arguments.length>1?arguments[1]:void 0)}}),Lm("includes");var xm=xt,Vm=yu,Um=y,Fm=RangeError,Bm=c,Hm=Wt,jm=yu,Wm=y,Gm=Bm((function(e){var t=Vm(Um(this)),i="",r=xm(e);if(r<0||Infinity===r)throw new Fm("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i})),Jm=Bm("".slice),zm=Math.ceil,Km=function(e){return function(t,i,r){var n,o,s=jm(Wm(t)),a=Hm(i),c=s.length,l=void 0===r?" ":jm(r);return a<=c||""===l?s:((o=Gm(l,zm((n=a-c)/l.length))).length>n&&(o=Jm(o,0,n)),e?s+o:o+s)}},qm={start:Km(!1),end:Km(!0)},Ym=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Z),Qm=qm.start;Fn({target:"String",proto:!0,forced:Ym},{padStart:function(e){return Qm(this,e,arguments.length>1?arguments[1]:void 0)}});var Xm=Fn,$m=c,Zm=Bt,e_=RangeError,t_=String.fromCharCode,i_=String.fromCodePoint,r_=$m([].join);Xm({target:"String",stat:!0,arity:1,forced:!!i_&&1!==i_.length},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,n=0;r>n;){if(t=+arguments[n++],Zm(t,1114111)!==t)throw new e_(t+" is not a valid code point");i[n]=t<65536?t_(t):t_(55296+((t-=65536)>>10),t%1024+56320)}return r_(i,"")}});var n_=i,o_=Ne,s_=ve("iterator"),a_=!n_((function(){var e=new URL("b?a=1&b=2&c=3","https://a"),t=e.searchParams,i=new URLSearchParams("a=1&a=2&b=3"),r="";return e.pathname="c%20d",t.forEach((function(e,i){t.delete("b"),r+=i+e})),i.delete("a",2),i.delete("b",void 0),!t.size&&!o_||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[s_]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("https://тест").host||"#%D0%B1"!==new URL("https://a#б").hash||"a1c3"!==r||"x"!==new URL("https://x",void 0).host})),c_=nn,l_=function(e,t,i){for(var r in t)c_(e,r,t[r],i);return e},d_=Na,u_=Math.floor,h_=function(e,t){var i=e.length;if(i<8)for(var r,n,o=1;o<i;){for(n=o,r=e[o];n&&t(e[n-1],r)>0;)e[n]=e[--n];n!==o++&&(e[n]=r)}else for(var s=u_(i/2),a=h_(d_(e,0,s),t),c=h_(d_(e,s),t),l=a.length,d=c.length,u=0,h=0;u<l||h<d;)e[u+h]=u<l&&h<d?t(a[u],c[h])<=0?a[u++]:c[h++]:u<l?a[u++]:c[h++];return e},p_=h_,m_=Fn,__=C,f_=dc,g_=Ge,T_=He,E_=c,v_=Ne,y_=a_,S_=nn,I_=Ds,A_=l_,R_=ao,C_=_o,b_=lr,k_=Vs,D_=Se,N_=J,w_=Da,O_=Js,P_=ke,M_=Ae,L_=yu,x_=Oi,V_=zi,U_=md,F_=ad,B_=Ko,H_=Oa,j_=p_,W_=ve("iterator"),G_="URLSearchParams",J_=G_+"Iterator",z_=b_.set,K_=b_.getterFor(G_),q_=b_.getterFor(J_),Y_=f_("fetch"),Q_=f_("Request"),X_=f_("Headers"),$_=Q_&&Q_.prototype,Z_=X_&&X_.prototype,ef=__.TypeError,tf=__.encodeURIComponent,rf=String.fromCharCode,nf=g_("String","fromCodePoint"),of=parseInt,sf=E_("".charAt),af=E_([].join),cf=E_([].push),lf=E_("".replace),df=E_([].shift),uf=E_([].splice),hf=E_("".split),pf=E_("".slice),mf=E_(/./.exec),_f=/\+/g,ff=/^[0-9a-f]+$/i,gf=function(e,t){var i=pf(e,t,t+2);return mf(ff,i)?of(i,16):NaN},Tf=function(e){for(var t=0,i=128;i>0&&e&i;i>>=1)t++;return t},Ef=function(e){var t=null;switch(e.length){case 1:t=e[0];break;case 2:t=(31&e[0])<<6|63&e[1];break;case 3:t=(15&e[0])<<12|(63&e[1])<<6|63&e[2];break;case 4:t=(7&e[0])<<18|(63&e[1])<<12|(63&e[2])<<6|63&e[3]}return t>1114111?null:t},vf=function(e){for(var t=(e=lf(e,_f," ")).length,i="",r=0;r<t;){var n=sf(e,r);if("%"===n){if("%"===sf(e,r+1)||r+3>t){i+="%",r++;continue}var o=gf(e,r+1);if(o!=o){i+=n,r++;continue}r+=2;var s=Tf(o);if(0===s)n=rf(o);else{if(1===s||s>4){i+="�",r++;continue}for(var a=[o],c=1;c<s&&!(++r+3>t||"%"!==sf(e,r));){var l=gf(e,r+1);if(l!=l){r+=3;break}if(l>191||l<128)break;cf(a,l),r+=2,c++}if(a.length!==s){i+="�";continue}var d=Ef(a);null===d?i+="�":n=nf(d)}}i+=n,r++}return i},yf=/[!'()~]|%20/g,Sf={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},If=function(e){return Sf[e]},Af=function(e){return lf(tf(e),yf,If)},Rf=C_((function(e,t){z_(this,{type:J_,target:K_(e).entries,index:0,kind:t})}),G_,(function(){var e=q_(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,B_(void 0,!0);var r=t[i];switch(e.kind){case"keys":return B_(r.key,!1);case"values":return B_(r.value,!1)}return B_([r.key,r.value],!1)}),!0),Cf=function(e){this.entries=[],this.url=null,void 0!==e&&(M_(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===sf(e,0)?pf(e,1):e:L_(e)))};Cf.prototype={type:G_,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,s,a,c=this.entries,l=F_(e);if(l)for(i=(t=U_(e,l)).next;!(r=T_(i,t)).done;){if(o=(n=U_(P_(r.value))).next,(s=T_(o,n)).done||(a=T_(o,n)).done||!T_(o,n).done)throw new ef("Expected sequence with length 2");cf(c,{key:L_(s.value),value:L_(a.value)})}else for(var d in e)N_(e,d)&&cf(c,{key:d,value:L_(e[d])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,n=hf(e,"&"),o=0;o<n.length;)(t=n[o++]).length&&(i=hf(t,"="),cf(r,{key:vf(df(i)),value:vf(af(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],cf(i,Af(e.key)+"="+Af(e.value));return af(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var bf=function(){k_(this,kf);var e=z_(this,new Cf(arguments.length>0?arguments[0]:void 0));v_||(this.size=e.entries.length)},kf=bf.prototype;if(A_(kf,{append:function(e,t){var i=K_(this);H_(arguments.length,2),cf(i.entries,{key:L_(e),value:L_(t)}),v_||this.length++,i.updateURL()},delete:function(e){for(var t=K_(this),i=H_(arguments.length,1),r=t.entries,n=L_(e),o=i<2?void 0:arguments[1],s=void 0===o?o:L_(o),a=0;a<r.length;){var c=r[a];if(c.key!==n||void 0!==s&&c.value!==s)a++;else if(uf(r,a,1),void 0!==s)break}v_||(this.size=r.length),t.updateURL()},get:function(e){var t=K_(this).entries;H_(arguments.length,1);for(var i=L_(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=K_(this).entries;H_(arguments.length,1);for(var i=L_(e),r=[],n=0;n<t.length;n++)t[n].key===i&&cf(r,t[n].value);return r},has:function(e){for(var t=K_(this).entries,i=H_(arguments.length,1),r=L_(e),n=i<2?void 0:arguments[1],o=void 0===n?n:L_(n),s=0;s<t.length;){var a=t[s++];if(a.key===r&&(void 0===o||a.value===o))return!0}return!1},set:function(e,t){var i=K_(this);H_(arguments.length,1);for(var r,n=i.entries,o=!1,s=L_(e),a=L_(t),c=0;c<n.length;c++)(r=n[c]).key===s&&(o?uf(n,c--,1):(o=!0,r.value=a));o||cf(n,{key:s,value:a}),v_||(this.size=n.length),i.updateURL()},sort:function(){var e=K_(this);j_(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=K_(this).entries,r=w_(e,arguments.length>1?arguments[1]:void 0),n=0;n<i.length;)r((t=i[n++]).value,t.key,this)},keys:function(){return new Rf(this,"keys")},values:function(){return new Rf(this,"values")},entries:function(){return new Rf(this,"entries")}},{enumerable:!0}),S_(kf,W_,kf.entries,{name:"entries"}),S_(kf,"toString",(function(){return K_(this).serialize()}),{enumerable:!0}),v_&&I_(kf,"size",{get:function(){return K_(this).entries.length},configurable:!0,enumerable:!0}),R_(bf,G_),m_({global:!0,constructor:!0,forced:!y_},{URLSearchParams:bf}),!y_&&D_(X_)){var Df=E_(Z_.has),Nf=E_(Z_.set),wf=function(e){if(M_(e)){var t,i=e.body;if(O_(i)===G_)return t=e.headers?new X_(e.headers):new X_,Df(t,"content-type")||Nf(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),x_(e,{body:V_(0,L_(i)),headers:V_(0,t)})}return e};if(D_(Y_)&&m_({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return Y_(e,arguments.length>1?wf(arguments[1]):{})}}),D_(Q_)){var Of=function(e){return k_(this,$_),new Q_(e,arguments.length>1?wf(arguments[1]):{})};$_.constructor=Of,Of.prototype=$_,m_({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:Of})}}var Pf={URLSearchParams:bf,getState:K_},Mf=Fn,Lf=Uc,xf=i,Vf=Ge,Uf=Se,Ff=ga,Bf=cu,Hf=nn,jf=Lf&&Lf.prototype;if(Mf({target:"Promise",proto:!0,real:!0,forced:!!Lf&&xf((function(){jf.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Ff(this,Vf("Promise")),i=Uf(e);return this.then(i?function(i){return Bf(t,e()).then((function(){return i}))}:e,i?function(i){return Bf(t,e()).then((function(){throw i}))}:e)}}),Uf(Lf)){var Wf=Vf("Promise").prototype.finally;jf.finally!==Wf&&Hf(jf,"finally",Wf,{unsafe:!0})}var Gf="\t\n\v\f\r                 \u2028\u2029\ufeff",Jf=y,zf=yu,Kf=Gf,qf=c("".replace),Yf=RegExp("^["+Kf+"]+"),Qf=RegExp("(^|[^"+Kf+"])["+Kf+"]+$"),Xf=function(e){return function(t){var i=zf(Jf(t));return 1&e&&(i=qf(i,Yf,"")),2&e&&(i=qf(i,Qf,"$1")),i}},$f={start:Xf(1),end:Xf(2),trim:Xf(3)},Zf=wr.PROPER,eg=i,tg=Gf,ig=$f.trim;Fn({target:"String",proto:!0,forced:function(e){return eg((function(){return!!tg[e]()||"​…᠎"!=="​…᠎"[e]()||Zf&&tg[e].name!==e}))}("trim")},{trim:function(){return ig(this)}});var rg=Fn,ng=Ne,og=c,sg=J,ag=Se,cg=Je,lg=yu,dg=Ds,ug=Sn,hg=C.Symbol,pg=hg&&hg.prototype;if(ng&&ag(hg)&&(!("description"in pg)||void 0!==hg().description)){var mg={},_g=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:lg(arguments[0]),t=cg(pg,this)?new hg(e):void 0===e?hg():hg(e);return""===e&&(mg[t]=!0),t};ug(_g,hg),_g.prototype=pg,pg.constructor=_g;var fg="Symbol(description detection)"===String(hg("description detection")),gg=og(pg.valueOf),Tg=og(pg.toString),Eg=/^Symbol\((.*)\)[^)]+$/,vg=og("".replace),yg=og("".slice);dg(pg,"description",{configurable:!0,get:function(){var e=gg(this);if(sg(mg,e))return"";var t=Tg(e),i=fg?yg(t,7,-1):vg(t,Eg,"$1");return""===i?void 0:i}}),rg({global:!0,constructor:!0,forced:!0},{Symbol:_g})}var Sg=Jp.charAt,Ig=yu,Ag=lr,Rg=zo,Cg=Ko,bg="String Iterator",kg=Ag.set,Dg=Ag.getterFor(bg);Rg(String,"String",(function(e){kg(this,{type:bg,string:Ig(e),index:0})}),(function(){var e,t=Dg(this),i=t.string,r=t.index;return r>=i.length?Cg(void 0,!0):(e=Sg(i,r),t.index+=e.length,Cg(e,!1))}));var Ng,wg=Ne,Og=c,Pg=He,Mg=i,Lg=ai,xg=cn,Vg=ur,Ug=j,Fg=g,Bg=Object.assign,Hg=Object.defineProperty,jg=Og([].concat),Wg=!Bg||Mg((function(){if(wg&&1!==Bg({b:1},Bg(Hg({},"a",{enumerable:!0,get:function(){Hg(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol("assign detection"),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach((function(e){t[e]=e})),7!==Bg({},e)[i]||Lg(Bg({},t)).join("")!==r}))?function(e,t){for(var i=Ug(e),r=arguments.length,n=1,o=xg.f,s=Vg.f;r>n;)for(var a,c=Fg(arguments[n++]),l=o?jg(Lg(c),o(c)):Lg(c),d=l.length,u=0;d>u;)a=l[u++],wg&&!Pg(s,c,a)||(i[a]=c[a]);return i}:Bg,Gg=ke,Jg=Td,zg=Ne,Kg=Oe,qg=zi,Yg=Da,Qg=He,Xg=j,$g=function(e,t,i,r){try{return r?t(Gg(i)[0],i[1]):t(i)}catch(YF){Jg(e,"throw",YF)}},Zg=td,eT=ca,tT=Jt,iT=function(e,t,i){zg?Kg.f(e,t,qg(0,i)):e[t]=i},rT=md,nT=ad,oT=Array,sT=c,aT=2147483647,cT=/[^\0-\u007E]/,lT=/[.\u3002\uFF0E\uFF61]/g,dT="Overflow: input needs wider integers to process",uT=RangeError,hT=sT(lT.exec),pT=Math.floor,mT=String.fromCharCode,_T=sT("".charCodeAt),fT=sT([].join),gT=sT([].push),TT=sT("".replace),ET=sT("".split),vT=sT("".toLowerCase),yT=function(e){return e+22+75*(e<26)},ST=function(e,t,i){var r=0;for(e=i?pT(e/700):e>>1,e+=pT(e/t);e>455;)e=pT(e/35),r+=36;return pT(r+36*e/(e+38))},IT=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=_T(e,i++);if(n>=55296&&n<=56319&&i<r){var o=_T(e,i++);56320==(64512&o)?gT(t,((1023&n)<<10)+(1023&o)+65536):(gT(t,n),i--)}else gT(t,n)}return t}(e);var i,r,n=e.length,o=128,s=0,a=72;for(i=0;i<e.length;i++)(r=e[i])<128&&gT(t,mT(r));var c=t.length,l=c;for(c&&gT(t,"-");l<n;){var d=aT;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>pT((aT-s)/u))throw new uT(dT);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++s>aT)throw new uT(dT);if(r===o){for(var h=s,p=36;;){var m=p<=a?1:p>=a+26?26:p-a;if(h<m)break;var _=h-m,f=36-m;gT(t,mT(yT(m+_%f))),h=pT(_/f),p+=36}gT(t,mT(yT(h))),a=ST(s,u,l===c),s=0,l++}}s++,o++}return fT(t,"")},AT=Fn,RT=Ne,CT=a_,bT=C,kT=Da,DT=c,NT=nn,wT=Ds,OT=Vs,PT=J,MT=Wg,LT=function(e){var t=Xg(e),i=eT(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=Yg(n,r>2?arguments[2]:void 0));var s,a,c,l,d,u,h=nT(t),p=0;if(!h||this===oT&&Zg(h))for(s=tT(t),a=i?new this(s):oT(s);s>p;p++)u=o?n(t[p],p):t[p],iT(a,p,u);else for(a=i?new this:[],d=(l=rT(t,h)).next;!(c=Qg(d,l)).done;p++)u=o?$g(l,n,[c.value,p],!0):c.value,iT(a,p,u);return a.length=p,a},xT=Na,VT=Jp.codeAt,UT=function(e){var t,i,r=[],n=ET(TT(vT(e),lT,"."),".");for(t=0;t<n.length;t++)i=n[t],gT(r,hT(cT,i)?"xn--"+IT(i):i);return fT(r,".")},FT=yu,BT=ao,HT=Oa,jT=Pf,WT=lr,GT=WT.set,JT=WT.getterFor("URL"),zT=jT.URLSearchParams,KT=jT.getState,qT=bT.URL,YT=bT.TypeError,QT=bT.parseInt,XT=Math.floor,$T=Math.pow,ZT=DT("".charAt),eE=DT(/./.exec),tE=DT([].join),iE=DT(1..toString),rE=DT([].pop),nE=DT([].push),oE=DT("".replace),sE=DT([].shift),aE=DT("".split),cE=DT("".slice),lE=DT("".toLowerCase),dE=DT([].unshift),uE="Invalid scheme",hE="Invalid host",pE="Invalid port",mE=/[a-z]/i,_E=/[\d+-.a-z]/i,fE=/\d/,gE=/^0x/i,TE=/^[0-7]+$/,EE=/^\d+$/,vE=/^[\da-f]+$/i,yE=/[\0\t\n\r #%/:<>?@[\\\]^|]/,SE=/[\0\t\n\r #/:<>?@[\\\]^|]/,IE=/^[\u0000-\u0020]+/,AE=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,RE=/[\t\n\r]/g,CE=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)dE(t,e%256),e=XT(e/256);return tE(t,".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,i=1,r=null,n=0,o=0;o<8;o++)0!==e[o]?(n>i&&(t=r,i=n),r=null,n=0):(null===r&&(r=o),++n);return n>i?r:t}(e),i=0;i<8;i++)n&&0===e[i]||(n&&(n=!1),r===i?(t+=i?":":"::",n=!0):(t+=iE(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},bE={},kE=MT({},bE,{" ":1,'"':1,"<":1,">":1,"`":1}),DE=MT({},kE,{"#":1,"?":1,"{":1,"}":1}),NE=MT({},DE,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),wE=function(e,t){var i=VT(e,0);return i>32&&i<127&&!PT(t,e)?e:encodeURIComponent(e)},OE={ftp:21,file:null,http:80,https:443,ws:80,wss:443},PE=function(e,t){var i;return 2===e.length&&eE(mE,ZT(e,0))&&(":"===(i=ZT(e,1))||!t&&"|"===i)},ME=function(e){var t;return e.length>1&&PE(cE(e,0,2))&&(2===e.length||"/"===(t=ZT(e,2))||"\\"===t||"?"===t||"#"===t)},LE=function(e){return"."===e||"%2e"===lE(e)},xE={},VE={},UE={},FE={},BE={},HE={},jE={},WE={},GE={},JE={},zE={},KE={},qE={},YE={},QE={},XE={},$E={},ZE={},ev={},tv={},iv={},rv=function(e,t,i){var r,n,o,s=FT(e);if(t){if(n=this.parse(s))throw new YT(n);this.searchParams=null}else{if(void 0!==i&&(r=new rv(i,!0)),n=this.parse(s,null,r))throw new YT(n);(o=KT(new zT)).bindURL(this),this.searchParams=o}};rv.prototype={type:"URL",parse:function(e,t,i){var r,n,o,s,a,c=this,l=t||xE,d=0,u="",h=!1,p=!1,m=!1;for(e=FT(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=oE(e,IE,""),e=oE(e,AE,"$1")),e=oE(e,RE,""),r=LT(e);d<=r.length;){switch(n=r[d],l){case xE:if(!n||!eE(mE,n)){if(t)return uE;l=UE;continue}u+=lE(n),l=VE;break;case VE:if(n&&(eE(_E,n)||"+"===n||"-"===n||"."===n))u+=lE(n);else{if(":"!==n){if(t)return uE;u="",l=UE,d=0;continue}if(t&&(c.isSpecial()!==PT(OE,u)||"file"===u&&(c.includesCredentials()||null!==c.port)||"file"===c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&OE[c.scheme]===c.port&&(c.port=null));u="","file"===c.scheme?l=YE:c.isSpecial()&&i&&i.scheme===c.scheme?l=FE:c.isSpecial()?l=WE:"/"===r[d+1]?(l=BE,d++):(c.cannotBeABaseURL=!0,nE(c.path,""),l=ev)}break;case UE:if(!i||i.cannotBeABaseURL&&"#"!==n)return uE;if(i.cannotBeABaseURL&&"#"===n){c.scheme=i.scheme,c.path=xT(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=iv;break}l="file"===i.scheme?YE:HE;continue;case FE:if("/"!==n||"/"!==r[d+1]){l=HE;continue}l=GE,d++;break;case BE:if("/"===n){l=JE;break}l=ZE;continue;case HE:if(c.scheme=i.scheme,n===Ng)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=xT(i.path),c.query=i.query;else if("/"===n||"\\"===n&&c.isSpecial())l=jE;else if("?"===n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=xT(i.path),c.query="",l=tv;else{if("#"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=xT(i.path),c.path.length--,l=ZE;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=xT(i.path),c.query=i.query,c.fragment="",l=iv}break;case jE:if(!c.isSpecial()||"/"!==n&&"\\"!==n){if("/"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=ZE;continue}l=JE}else l=GE;break;case WE:if(l=GE,"/"!==n||"/"!==ZT(u,d+1))continue;d++;break;case GE:if("/"!==n&&"\\"!==n){l=JE;continue}break;case JE:if("@"===n){h&&(u="%40"+u),h=!0,o=LT(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!==f||m){var g=wE(f,NE);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n===Ng||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(h&&""===u)return"Invalid authority";d-=LT(u).length+1,u="",l=zE}else u+=n;break;case zE:case KE:if(t&&"file"===c.scheme){l=XE;continue}if(":"!==n||p){if(n===Ng||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(c.isSpecial()&&""===u)return hE;if(t&&""===u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=$E,t)return;continue}"["===n?p=!0:"]"===n&&(p=!1),u+=n}else{if(""===u)return hE;if(s=c.parseHost(u))return s;if(u="",l=qE,t===KE)return}break;case qE:if(!eE(fE,n)){if(n===Ng||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()||t){if(""!==u){var T=QT(u,10);if(T>65535)return pE;c.port=c.isSpecial()&&T===OE[c.scheme]?null:T,u=""}if(t)return;l=$E;continue}return pE}u+=n;break;case YE:if(c.scheme="file","/"===n||"\\"===n)l=QE;else{if(!i||"file"!==i.scheme){l=ZE;continue}switch(n){case Ng:c.host=i.host,c.path=xT(i.path),c.query=i.query;break;case"?":c.host=i.host,c.path=xT(i.path),c.query="",l=tv;break;case"#":c.host=i.host,c.path=xT(i.path),c.query=i.query,c.fragment="",l=iv;break;default:ME(tE(xT(r,d),""))||(c.host=i.host,c.path=xT(i.path),c.shortenPath()),l=ZE;continue}}break;case QE:if("/"===n||"\\"===n){l=XE;break}i&&"file"===i.scheme&&!ME(tE(xT(r,d),""))&&(PE(i.path[0],!0)?nE(c.path,i.path[0]):c.host=i.host),l=ZE;continue;case XE:if(n===Ng||"/"===n||"\\"===n||"?"===n||"#"===n){if(!t&&PE(u))l=ZE;else if(""===u){if(c.host="",t)return;l=$E}else{if(s=c.parseHost(u))return s;if("localhost"===c.host&&(c.host=""),t)return;u="",l=$E}continue}u+=n;break;case $E:if(c.isSpecial()){if(l=ZE,"/"!==n&&"\\"!==n)continue}else if(t||"?"!==n)if(t||"#"!==n){if(n!==Ng&&(l=ZE,"/"!==n))continue}else c.fragment="",l=iv;else c.query="",l=tv;break;case ZE:if(n===Ng||"/"===n||"\\"===n&&c.isSpecial()||!t&&("?"===n||"#"===n)){if(".."===(a=lE(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"===n||"\\"===n&&c.isSpecial()||nE(c.path,"")):LE(u)?"/"===n||"\\"===n&&c.isSpecial()||nE(c.path,""):("file"===c.scheme&&!c.path.length&&PE(u)&&(c.host&&(c.host=""),u=ZT(u,0)+":"),nE(c.path,u)),u="","file"===c.scheme&&(n===Ng||"?"===n||"#"===n))for(;c.path.length>1&&""===c.path[0];)sE(c.path);"?"===n?(c.query="",l=tv):"#"===n&&(c.fragment="",l=iv)}else u+=wE(n,DE);break;case ev:"?"===n?(c.query="",l=tv):"#"===n?(c.fragment="",l=iv):n!==Ng&&(c.path[0]+=wE(n,bE));break;case tv:t||"#"!==n?n!==Ng&&("'"===n&&c.isSpecial()?c.query+="%27":c.query+="#"===n?"%23":wE(n,bE)):(c.fragment="",l=iv);break;case iv:n!==Ng&&(c.fragment+=wE(n,kE))}d++}},parseHost:function(e){var t,i,r;if("["===ZT(e,0)){if("]"!==ZT(e,e.length-1))return hE;if(t=function(e){var t,i,r,n,o,s,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return ZT(e,u)};if(":"===h()){if(":"!==ZT(e,1))return;u+=2,d=++l}for(;h();){if(8===l)return;if(":"!==h()){for(t=i=0;i<4&&eE(vE,h());)t=16*t+QT(h(),16),u++,i++;if("."===h()){if(0===i)return;if(u-=i,l>6)return;for(r=0;h();){if(n=null,r>0){if(!("."===h()&&r<4))return;u++}if(!eE(fE,h()))return;for(;eE(fE,h());){if(o=QT(h(),10),null===n)n=o;else{if(0===n)return;n=10*n+o}if(n>255)return;u++}c[l]=256*c[l]+n,2!=++r&&4!==r||l++}if(4!==r)return;break}if(":"===h()){if(u++,!h())return}else if(h())return;c[l++]=t}else{if(null!==d)return;u++,d=++l}}if(null!==d)for(s=l-d,l=7;0!==l&&s>0;)a=c[l],c[l--]=c[d+s-1],c[d+--s]=a;else if(8!==l)return;return c}(cE(e,1,-1)),!t)return hE;this.host=t}else if(this.isSpecial()){if(e=UT(e),eE(yE,e))return hE;if(t=function(e){var t,i,r,n,o,s,a,c=aE(e,".");if(c.length&&""===c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],r=0;r<t;r++){if(""===(n=c[r]))return e;if(o=10,n.length>1&&"0"===ZT(n,0)&&(o=eE(gE,n)?16:8,n=cE(n,8===o?1:2)),""===n)s=0;else{if(!eE(10===o?EE:8===o?TE:vE,n))return e;s=QT(n,o)}nE(i,s)}for(r=0;r<t;r++)if(s=i[r],r===t-1){if(s>=$T(256,5-t))return null}else if(s>255)return null;for(a=rE(i),r=0;r<i.length;r++)a+=i[r]*$T(256,3-r);return a}(e),null===t)return hE;this.host=t}else{if(eE(SE,e))return hE;for(t="",i=LT(e),r=0;r<i.length;r++)t+=wE(i[r],bE);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return PT(OE,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&PE(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,r=e.password,n=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,l=t+":";return null!==n?(l+="//",e.includesCredentials()&&(l+=i+(r?":"+r:"")+"@"),l+=CE(n),null!==o&&(l+=":"+o)):"file"===t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+tE(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw new YT(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new nv(e.path[0]).origin}catch(YF){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+CE(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(FT(e)+":",xE)},getUsername:function(){return this.username},setUsername:function(e){var t=LT(FT(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=wE(t[i],NE)}},getPassword:function(){return this.password},setPassword:function(e){var t=LT(FT(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=wE(t[i],NE)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?CE(e):CE(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,zE)},getHostname:function(){var e=this.host;return null===e?"":CE(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,KE)},getPort:function(){var e=this.port;return null===e?"":FT(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=FT(e))?this.port=null:this.parse(e,qE))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+tE(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,$E))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=FT(e))?this.query=null:("?"===ZT(e,0)&&(e=cE(e,1)),this.query="",this.parse(e,tv)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=FT(e))?("#"===ZT(e,0)&&(e=cE(e,1)),this.fragment="",this.parse(e,iv)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var nv=function(e){var t=OT(this,ov),i=HT(arguments.length,1)>1?arguments[1]:void 0,r=GT(t,new rv(e,!1,i));RT||(t.href=r.serialize(),t.origin=r.getOrigin(),t.protocol=r.getProtocol(),t.username=r.getUsername(),t.password=r.getPassword(),t.host=r.getHost(),t.hostname=r.getHostname(),t.port=r.getPort(),t.pathname=r.getPathname(),t.search=r.getSearch(),t.searchParams=r.getSearchParams(),t.hash=r.getHash())},ov=nv.prototype,sv=function(e,t){return{get:function(){return JT(this)[e]()},set:t&&function(e){return JT(this)[t](e)},configurable:!0,enumerable:!0}};if(RT&&(wT(ov,"href",sv("serialize","setHref")),wT(ov,"origin",sv("getOrigin")),wT(ov,"protocol",sv("getProtocol","setProtocol")),wT(ov,"username",sv("getUsername","setUsername")),wT(ov,"password",sv("getPassword","setPassword")),wT(ov,"host",sv("getHost","setHost")),wT(ov,"hostname",sv("getHostname","setHostname")),wT(ov,"port",sv("getPort","setPort")),wT(ov,"pathname",sv("getPathname","setPathname")),wT(ov,"search",sv("getSearch","setSearch")),wT(ov,"searchParams",sv("getSearchParams")),wT(ov,"hash",sv("getHash","setHash"))),NT(ov,"toJSON",(function(){return JT(this).serialize()}),{enumerable:!0}),NT(ov,"toString",(function(){return JT(this).serialize()}),{enumerable:!0}),qT){var av=qT.createObjectURL,cv=qT.revokeObjectURL;av&&NT(nv,"createObjectURL",kT(av,qT)),cv&&NT(nv,"revokeObjectURL",kT(cv,qT))}BT(nv,"URL"),AT({global:!0,constructor:!0,forced:!CT,sham:!RT},{URL:nv});var lv="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,dv=xt,uv=Wt,hv=RangeError,pv=function(e){if(void 0===e)return 0;var t=dv(e),i=uv(t);if(t!==i)throw new hv("Wrong length or index");return i},mv=Math.sign||function(e){var t=+e;return 0===t||t!=t?t:t<0?-1:1},_v=mv,fv=Math.abs,gv=2220446049250313e-31,Tv=1/gv,Ev=function(e,t,i,r){var n=+e,o=fv(n),s=_v(n);if(o<r)return s*function(e){return e+Tv-Tv}(o/r/t)*r*t;var a=(1+t/gv)*o,c=a-(a-o);return c>i||c!=c?Infinity*s:s*c},vv=Math.fround||function(e){return Ev(e,1.1920928955078125e-7,34028234663852886e22,11754943508222875e-54)},yv=Array,Sv=Math.abs,Iv=Math.pow,Av=Math.floor,Rv=Math.log,Cv=Math.LN2,bv={pack:function(e,t,i){var r,n,o,s=yv(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?Iv(2,-24)-Iv(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=Sv(e))!=e||Infinity===e?(n=e!=e?1:0,r=c):(r=Av(Rv(e)/Cv),e*(o=Iv(2,-r))<1&&(r--,o*=2),(e+=r+l>=1?d/o:d*Iv(2,1-l))*o>=2&&(r++,o/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*o-1)*Iv(2,t),r+=l):(n=e*Iv(2,l-1)*Iv(2,t),r=0));t>=8;)s[h++]=255&n,n/=256,t-=8;for(r=r<<t|n,a+=t;a>0;)s[h++]=255&r,r/=256,a-=8;return s[h-1]|=128*u,s},unpack:function(e,t){var i,r=e.length,n=8*r-t-1,o=(1<<n)-1,s=o>>1,a=n-7,c=r-1,l=e[c--],d=127&l;for(l>>=7;a>0;)d=256*d+e[c--],a-=8;for(i=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)i=256*i+e[c--],a-=8;if(0===d)d=1-s;else{if(d===o)return i?NaN:l?-Infinity:Infinity;i+=Iv(2,t),d-=s}return(l?-1:1)*i*Iv(2,d-t)}},kv=j,Dv=Bt,Nv=Jt,wv=function(e){for(var t=kv(this),i=Nv(t),r=arguments.length,n=Dv(r>1?arguments[1]:void 0,i),o=r>2?arguments[2]:void 0,s=void 0===o?i:Dv(o,i);s>n;)t[n++]=e;return t},Ov=C,Pv=c,Mv=Ne,Lv=lv,xv=Yi,Vv=Ds,Uv=l_,Fv=i,Bv=Vs,Hv=xt,jv=Wt,Wv=pv,Gv=vv,Jv=bv,zv=qn,Kv=Co,qv=wv,Yv=Na,Qv=_u,Xv=Sn,$v=ao,Zv=lr,ey=wr.PROPER,ty=wr.CONFIGURABLE,iy="ArrayBuffer",ry="DataView",ny="prototype",oy="Wrong index",sy=Zv.getterFor(iy),ay=Zv.getterFor(ry),cy=Zv.set,ly=Ov[iy],dy=ly,uy=dy&&dy[ny],hy=Ov[ry],py=hy&&hy[ny],my=Object.prototype,_y=Ov.Array,fy=Ov.RangeError,gy=Pv(qv),Ty=Pv([].reverse),Ey=Jv.pack,vy=Jv.unpack,yy=function(e){return[255&e]},Sy=function(e){return[255&e,e>>8&255]},Iy=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},Ay=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},Ry=function(e){return Ey(Gv(e),23,4)},Cy=function(e){return Ey(e,52,8)},by=function(e,t,i){Vv(e[ny],t,{configurable:!0,get:function(){return i(this)[t]}})},ky=function(e,t,i,r){var n=ay(e),o=Wv(i),s=!!r;if(o+t>n.byteLength)throw new fy(oy);var a=n.bytes,c=o+n.byteOffset,l=Yv(a,c,c+t);return s?l:Ty(l)},Dy=function(e,t,i,r,n,o){var s=ay(e),a=Wv(i),c=r(+n),l=!!o;if(a+t>s.byteLength)throw new fy(oy);for(var d=s.bytes,u=a+s.byteOffset,h=0;h<t;h++)d[u+h]=c[l?h:t-h-1]};if(Lv){var Ny=ey&&ly.name!==iy;Fv((function(){ly(1)}))&&Fv((function(){new ly(-1)}))&&!Fv((function(){return new ly,new ly(1.5),new ly(NaN),1!==ly.length||Ny&&!ty}))?Ny&&ty&&xv(ly,"name",iy):((dy=function(e){return Bv(this,uy),Qv(new ly(Wv(e)),this,dy)})[ny]=uy,uy.constructor=dy,Xv(dy,ly)),Kv&&zv(py)!==my&&Kv(py,my);var wy=new hy(new dy(2)),Oy=Pv(py.setInt8);wy.setInt8(0,2147483648),wy.setInt8(1,2147483649),!wy.getInt8(0)&&wy.getInt8(1)||Uv(py,{setInt8:function(e,t){Oy(this,e,t<<24>>24)},setUint8:function(e,t){Oy(this,e,t<<24>>24)}},{unsafe:!0})}else uy=(dy=function(e){Bv(this,uy);var t=Wv(e);cy(this,{type:iy,bytes:gy(_y(t),0),byteLength:t}),Mv||(this.byteLength=t,this.detached=!1)})[ny],py=(hy=function(e,t,i){Bv(this,py),Bv(e,uy);var r=sy(e),n=r.byteLength,o=Hv(t);if(o<0||o>n)throw new fy("Wrong offset");if(o+(i=void 0===i?n-o:jv(i))>n)throw new fy("Wrong length");cy(this,{type:ry,buffer:e,byteLength:i,byteOffset:o,bytes:r.bytes}),Mv||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[ny],Mv&&(by(dy,"byteLength",sy),by(hy,"buffer",ay),by(hy,"byteLength",ay),by(hy,"byteOffset",ay)),Uv(py,{getInt8:function(e){return ky(this,1,e)[0]<<24>>24},getUint8:function(e){return ky(this,1,e)[0]},getInt16:function(e){var t=ky(this,2,e,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=ky(this,2,e,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return Ay(ky(this,4,e,arguments.length>1&&arguments[1]))},getUint32:function(e){return Ay(ky(this,4,e,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(e){return vy(ky(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return vy(ky(this,8,e,arguments.length>1&&arguments[1]),52)},setInt8:function(e,t){Dy(this,1,e,yy,t)},setUint8:function(e,t){Dy(this,1,e,yy,t)},setInt16:function(e,t){Dy(this,2,e,Sy,t,arguments.length>2&&arguments[2])},setUint16:function(e,t){Dy(this,2,e,Sy,t,arguments.length>2&&arguments[2])},setInt32:function(e,t){Dy(this,4,e,Iy,t,arguments.length>2&&arguments[2])},setUint32:function(e,t){Dy(this,4,e,Iy,t,arguments.length>2&&arguments[2])},setFloat32:function(e,t){Dy(this,4,e,Ry,t,arguments.length>2&&arguments[2])},setFloat64:function(e,t){Dy(this,8,e,Cy,t,arguments.length>2&&arguments[2])}});$v(dy,iy),$v(hy,ry);var Py={ArrayBuffer:dy,DataView:hy},My=Fn,Ly=Ra,xy=i,Vy=ke,Uy=Bt,Fy=Wt,By=ga,Hy=Py.ArrayBuffer,jy=Py.DataView,Wy=jy.prototype,Gy=Ly(Hy.prototype.slice),Jy=Ly(Wy.getUint8),zy=Ly(Wy.setUint8);My({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:xy((function(){return!new Hy(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(Gy&&void 0===t)return Gy(Vy(this),e);for(var i=Vy(this).byteLength,r=Uy(e,i),n=Uy(void 0===t?i:t,i),o=new(By(this,Hy))(Fy(n-r)),s=new jy(this),a=new jy(o),c=0;r<n;)zy(a,c++,Jy(s,r++));return o}});var Ky,qy,Yy,Qy={},Xy={get exports(){return Qy},set exports(e){Qy=e}},$y=lv,Zy=Ne,eS=C,tS=Se,iS=Ae,rS=J,nS=Js,oS=$e,sS=Yi,aS=nn,cS=Ds,lS=Je,dS=qn,uS=Co,hS=ve,pS=Q,mS=lr.enforce,_S=lr.get,fS=eS.Int8Array,gS=fS&&fS.prototype,TS=eS.Uint8ClampedArray,ES=TS&&TS.prototype,vS=fS&&dS(fS),yS=gS&&dS(gS),SS=Object.prototype,IS=eS.TypeError,AS=hS("toStringTag"),RS=pS("TYPED_ARRAY_TAG"),CS="TypedArrayConstructor",bS=$y&&!!uS&&"Opera"!==nS(eS.opera),kS=!1,DS={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},NS={BigInt64Array:8,BigUint64Array:8},wS=function(e){var t=dS(e);if(iS(t)){var i=_S(t);return i&&rS(i,CS)?i[CS]:wS(t)}},OS=function(e){if(!iS(e))return!1;var t=nS(e);return rS(DS,t)||rS(NS,t)};for(Ky in DS)(Yy=(qy=eS[Ky])&&qy.prototype)?mS(Yy)[CS]=qy:bS=!1;for(Ky in NS)(Yy=(qy=eS[Ky])&&qy.prototype)&&(mS(Yy)[CS]=qy);if((!bS||!tS(vS)||vS===Function.prototype)&&(vS=function(){throw new IS("Incorrect invocation")},bS))for(Ky in DS)eS[Ky]&&uS(eS[Ky],vS);if((!bS||!yS||yS===SS)&&(yS=vS.prototype,bS))for(Ky in DS)eS[Ky]&&uS(eS[Ky].prototype,yS);if(bS&&dS(ES)!==yS&&uS(ES,yS),Zy&&!rS(yS,AS))for(Ky in kS=!0,cS(yS,AS,{configurable:!0,get:function(){return iS(this)?this[RS]:void 0}}),DS)eS[Ky]&&sS(eS[Ky],RS,Ky);var PS={NATIVE_ARRAY_BUFFER_VIEWS:bS,TYPED_ARRAY_TAG:kS&&RS,aTypedArray:function(e){if(OS(e))return e;throw new IS("Target is not a typed array")},aTypedArrayConstructor:function(e){if(tS(e)&&(!uS||lS(vS,e)))return e;throw new IS(oS(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(Zy){if(i)for(var n in DS){var o=eS[n];if(o&&rS(o.prototype,e))try{delete o.prototype[e]}catch(YF){try{o.prototype[e]=t}catch(s){}}}yS[e]&&!i||aS(yS,e,i?t:bS&&gS[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(Zy){if(uS){if(i)for(r in DS)if((n=eS[r])&&rS(n,e))try{delete n[e]}catch(YF){}if(vS[e]&&!i)return;try{return aS(vS,e,i?t:bS&&vS[e]||t)}catch(YF){}}for(r in DS)!(n=eS[r])||n[e]&&!i||aS(n,e,t)}},getTypedArrayConstructor:wS,isView:function(e){if(!iS(e))return!1;var t=nS(e);return"DataView"===t||rS(DS,t)||rS(NS,t)},isTypedArray:OS,TypedArray:vS,TypedArrayPrototype:yS},MS=C,LS=i,xS=Vd,VS=PS.NATIVE_ARRAY_BUFFER_VIEWS,US=MS.ArrayBuffer,FS=MS.Int8Array,BS=!VS||!LS((function(){FS(1)}))||!LS((function(){new FS(-1)}))||!xS((function(e){new FS,new FS(null),new FS(1.5),new FS(e)}),!0)||LS((function(){return 1!==new FS(new US(2),1,void 0).length})),HS=Ae,jS=Math.floor,WS=Number.isInteger||function(e){return!HS(e)&&isFinite(e)&&jS(e)===e},GS=xt,JS=RangeError,zS=function(e){var t=GS(e);if(t<0)throw new JS("The argument can't be less than 0");return t},KS=RangeError,qS=function(e,t){var i=zS(e);if(i%t)throw new KS("Wrong offset");return i},YS=Math.round,QS=Js,XS=gt,$S=TypeError,ZS=function(e){var t=XS(e,"number");if("number"==typeof t)throw new $S("Can't convert number to bigint");return BigInt(t)},eI=Da,tI=He,iI=ha,rI=j,nI=Jt,oI=md,sI=ad,aI=td,cI=function(e){var t=QS(e);return"BigInt64Array"===t||"BigUint64Array"===t},lI=PS.aTypedArrayConstructor,dI=ZS,uI=function(e){var t,i,r,n,o,s,a,c,l=iI(this),d=rI(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=sI(d);if(m&&!aI(m))for(c=(a=oI(d,m)).next,d=[];!(s=tI(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=eI(h,arguments[2])),i=nI(d),r=new(lI(l))(i),n=cI(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?dI(o):+o;return r},hI=Jt,pI=Fn,mI=C,_I=He,fI=Ne,gI=BS,TI=PS,EI=Py,vI=Vs,yI=zi,SI=Yi,II=WS,AI=Wt,RI=pv,CI=qS,bI=function(e){var t=YS(e);return t<0?0:t>255?255:255&t},kI=vt,DI=J,NI=Js,wI=Ae,OI=Qe,PI=Oi,MI=Je,LI=Co,xI=on.f,VI=uI,UI=lp.forEach,FI=Ms,BI=Ds,HI=Oe,jI=dr,WI=function(e,t,i){for(var r=0,n=arguments.length>2?i:hI(t),o=new e(n);n>r;)o[r]=t[r++];return o},GI=_u,JI=lr.get,zI=lr.set,KI=lr.enforce,qI=HI.f,YI=jI.f,QI=mI.RangeError,XI=EI.ArrayBuffer,$I=XI.prototype,ZI=EI.DataView,eA=TI.NATIVE_ARRAY_BUFFER_VIEWS,tA=TI.TYPED_ARRAY_TAG,iA=TI.TypedArray,rA=TI.TypedArrayPrototype,nA=TI.isTypedArray,oA="BYTES_PER_ELEMENT",sA="Wrong length",aA=function(e,t){BI(e,t,{configurable:!0,get:function(){return JI(this)[t]}})},cA=function(e){var t;return MI($I,e)||"ArrayBuffer"===(t=NI(e))||"SharedArrayBuffer"===t},lA=function(e,t){return nA(e)&&!OI(t)&&t in e&&II(+t)&&t>=0},dA=function(e,t){return t=kI(t),lA(e,t)?yI(2,e[t]):YI(e,t)},uA=function(e,t,i){return t=kI(t),!(lA(e,t)&&wI(i)&&DI(i,"value"))||DI(i,"get")||DI(i,"set")||i.configurable||DI(i,"writable")&&!i.writable||DI(i,"enumerable")&&!i.enumerable?qI(e,t,i):(e[t]=i.value,e)};fI?(eA||(jI.f=dA,HI.f=uA,aA(rA,"buffer"),aA(rA,"byteOffset"),aA(rA,"byteLength"),aA(rA,"length")),pI({target:"Object",stat:!0,forced:!eA},{getOwnPropertyDescriptor:dA,defineProperty:uA}),Xy.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=mI[n],c=a,l=c&&c.prototype,d={},u=function(e,t){qI(e,t,{get:function(){return function(e,t){var i=JI(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=JI(e);o.view[s](t*r+o.byteOffset,i?bI(n):n,!0)}(this,t,e)},enumerable:!0})};eA?gI&&(c=t((function(e,t,i,n){return vI(e,l),GI(wI(t)?cA(t)?void 0!==n?new a(t,CI(i,r),n):void 0!==i?new a(t,CI(i,r)):new a(t):nA(t)?WI(c,t):_I(VI,c,t):new a(RI(t)),e,c)})),LI&&LI(c,iA),UI(xI(a),(function(e){e in c||SI(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,n){vI(e,l);var o,s,a,d=0,h=0;if(wI(t)){if(!cA(t))return nA(t)?WI(c,t):_I(VI,c,t);o=t,h=CI(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw new QI(sA);if((s=p-h)<0)throw new QI(sA)}else if((s=AI(n)*r)+h>p)throw new QI(sA);a=s/r}else a=RI(t),o=new XI(s=a*r);for(zI(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new ZI(o)});d<a;)u(e,d++)})),LI&&LI(c,iA),l=c.prototype=PI(rA)),l.constructor!==c&&SI(l,"constructor",c),KI(l).TypedArrayConstructor=c,tA&&SI(l,tA,n);var h=c!==a;d[n]=c,pI({global:!0,constructor:!0,forced:h,sham:!eA},d),oA in c||SI(c,oA,r),oA in l||SI(l,oA,r),FI(n)}):Xy.exports=function(){},Qy("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var hA=wv,pA=ZS,mA=Js,_A=He,fA=i,gA=PS.aTypedArray,TA=PS.exportTypedArrayMethod,EA=c("".slice);TA("fill",(function(e){var t=arguments.length;gA(this);var i="Big"===EA(mA(this),0,3)?pA(e):+e;return _A(hA,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),fA((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var vA=C,yA=He,SA=PS,IA=Jt,AA=qS,RA=j,CA=i,bA=vA.RangeError,kA=vA.Int8Array,DA=kA&&kA.prototype,NA=DA&&DA.set,wA=SA.aTypedArray,OA=SA.exportTypedArrayMethod,PA=!CA((function(){var e=new Uint8ClampedArray(2);return yA(NA,e,{length:1,0:3},1),3!==e[1]})),MA=PA&&SA.NATIVE_ARRAY_BUFFER_VIEWS&&CA((function(){var e=new kA(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));OA("set",(function(e){wA(this);var t=AA(arguments.length>1?arguments[1]:void 0,1),i=RA(e);if(PA)return yA(NA,this,i,t);var r=this.length,n=IA(i),o=0;if(n+t>r)throw new bA("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!PA||MA);var LA=Z.match(/firefox\/(\d+)/i),xA=!!LA&&+LA[1],VA=/MSIE|Trident/.test(Z),UA=Z.match(/AppleWebKit\/(\d+)\./),FA=!!UA&&+UA[1],BA=Ra,HA=i,jA=it,WA=p_,GA=xA,JA=VA,zA=se,KA=FA,qA=PS.aTypedArray,YA=PS.exportTypedArrayMethod,QA=C.Uint16Array,XA=QA&&BA(QA.prototype.sort),$A=!(!XA||HA((function(){XA(new QA(2),null)}))&&HA((function(){XA(new QA(2),{})}))),ZA=!!XA&&!HA((function(){if(zA)return zA<74;if(GA)return GA<67;if(JA)return!0;if(KA)return KA<602;var e,t,i=new QA(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(XA(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));YA("sort",(function(e){return void 0!==e&&jA(e),ZA?XA(this,e):WA(qA(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))}),!ZA||$A),Qy("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var eR=Ms,tR="ArrayBuffer",iR=Py[tR];Fn({global:!0,constructor:!0,forced:C[tR]!==iR},{ArrayBuffer:iR}),eR(tR);var rR=Fn,nR=Yh,oR=c([].reverse),sR=[1,2];rR({target:"Array",proto:!0,forced:String(sR)===String(sR.reverse())},{reverse:function(){return nR(this)&&(this.length=this.length),oR(this)}});var aR=$e,cR=TypeError,lR=Fn,dR=c,uR=it,hR=j,pR=Jt,mR=function(e,t){if(!delete e[t])throw new cR("Cannot delete property "+aR(t)+" of "+aR(e))},_R=yu,fR=i,gR=p_,TR=up,ER=xA,vR=VA,yR=se,SR=FA,IR=[],AR=dR(IR.sort),RR=dR(IR.push),CR=fR((function(){IR.sort(void 0)})),bR=fR((function(){IR.sort(null)})),kR=TR("sort"),DR=!fR((function(){if(yR)return yR<70;if(!(ER&&ER>3)){if(vR)return!0;if(SR)return SR<603;var e,t,i,r,n="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(r=0;r<47;r++)IR.push({k:t+r,v:i})}for(IR.sort((function(e,t){return t.v-e.v})),r=0;r<IR.length;r++)t=IR[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));lR({target:"Array",proto:!0,forced:CR||!bR||!kR||!DR},{sort:function(e){void 0!==e&&uR(e);var t=hR(this);if(DR)return void 0===e?AR(t):AR(t,e);var i,r,n=[],o=pR(t);for(r=0;r<o;r++)r in t&&RR(n,t[r]);for(gR(n,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:_R(t)>_R(i)?1:-1}}(e)),i=pR(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)mR(t,r++);return t}}),(0,PS.exportTypedArrayStaticMethod)("from",uI,BS);let NR=!0,wR=!0;function OR(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function PR(e,t,i){if(!e.RTCPeerConnection)return;const r=e.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return n.apply(this,arguments);const o=e=>{const t=i(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,o),n.apply(this,[e,o])};const o=r.removeEventListener;r.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.apply(this,arguments);const r=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,r])},Object.defineProperty(r,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function MR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(NR=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function LR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(wR=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function xR(){if("object"==typeof window){if(NR)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function VR(e,t){wR&&console.warn(e+" is deprecated, please use "+t+" instead.")}function UR(e){return"[object Object]"===Object.prototype.toString.call(e)}function FR(e){return UR(e)?Object.keys(e).reduce((function(t,i){const r=UR(e[i]),n=r?FR(e[i]):e[i],o=r&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[i]:n})}),{}):e}function BR(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?BR(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{BR(e,e.get(t),i)}))})))}function HR(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((i=>{i.type===r&&i.trackId===t.id&&BR(e,i,n)}))})),n}const jR=xR;function WR(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const r=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const r="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==r.ideal){t.optional=t.optional||[];let e={};"number"==typeof r.ideal?(e[n("min",i)]=r.ideal,t.optional.push(e),e={},e[n("max",i)]=r.ideal,t.optional.push(e)):(e[n("",i)]=r.ideal,t.optional.push(e))}void 0!==r.exact&&"number"!=typeof r.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",i)]=r.exact):["min","max"].forEach((e=>{void 0!==r[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,i)]=r[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=r(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let s=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=r(e.video),jR("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return jR("chrome: "+JSON.stringify(e)),n(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,r){n(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{r&&r(o(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function GR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function JR(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const n=new Event("track");n.track=i.track,n.receiver=r,n.transceiver={receiver:r},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const n=new Event("track");n.track=i,n.receiver=r,n.transceiver={receiver:r},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else PR(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function zR(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let n=i.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function KR(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,r]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const r=function(e){i(o(n(e)))};return t.apply(this,[r,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(o(n(t)))},i])})).then(i,r)}}function qR(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=>HR(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}),PR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>HR(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,r;return this.getSenders().forEach((i=>{i.track===e&&(t?r=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?r=!0:i=t),t.track===e))),r||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function YR(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const r=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(r)&&this._shimmedLocalStreams[i.id].push(r):this._shimmedLocalStreams[i.id]=[i,r],r};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const r=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(r)};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function QR(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return YR(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}r.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const r=[].slice.call(arguments,1);if(1!==r.length||!r[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const n=this._streams[i.id];if(n)n.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const r=new e.MediaStream([t]);this._streams[i.id]=r,this._reverseStreams[r.id]=i,this.addStream(r)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=r[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function XR(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}))}function $R(e,t){PR(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var ZR=Object.freeze({__proto__:null,shimMediaStream:GR,shimOnTrack:JR,shimGetSendersWithDtmf:zR,shimGetStats:KR,shimSenderReceiverGetStats:qR,shimAddTrackRemoveTrackWithNative:YR,shimAddTrackRemoveTrack:QR,shimPeerConnection:XR,fixNegotiationNeeded:$R,shimGetUserMedia:WR,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const r=i.video&&i.video.width,n=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},r&&(i.video.mandatory.maxWidth=r),n&&(i.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function eC(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){VR("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},r&&r.prototype.getSettings){const t=r.prototype.getSettings;r.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(r&&r.prototype.applyConstraints){const t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function tC(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 iC(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,o]=arguments;return r.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(Rb){if("TypeError"!==Rb.name)throw Rb;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,o)}}function rC(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 nC(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}),PR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function oC(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){VR("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function sC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function aC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const r=t.apply(this,arguments);if(i){const{sender:t}=r,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return r})}function cC(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 lC(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 dC(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 uC=Object.freeze({__proto__:null,shimOnTrack:tC,shimPeerConnection:iC,shimSenderGetStats:rC,shimReceiverGetStats:nC,shimRemoveStream:oC,shimRTCDataChannel:sC,shimAddTransceiver:aC,shimGetParameters:cC,shimCreateOffer:lC,shimCreateAnswer:dC,shimGetUserMedia:eC,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 hC(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 pC(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 mC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,i){const r=n.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r};t.setLocalDescription=a,a=function(e,t,i){const r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.setRemoteDescription=a,a=function(e,t,i){const r=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.addIceCandidate=a}function _C(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(fC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function fC(e){return e&&void 0!==e.video?Object.assign({},e,{video:FR(e.video)}):e}function gC(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let r=e.iceServers[i];void 0===r.urls&&r.url?(VR("RTCIceServer.url","RTCIceServer.urls"),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function TC(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 EC(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 vC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var yC=Object.freeze({__proto__:null,shimLocalStreamsAPI:hC,shimRemoteStreamsAPI:pC,shimCallbacksAPI:mC,shimGetUserMedia:_C,shimConstraints:fC,shimRTCIceServerUrls:gC,shimTrackEventTransceiver:TC,shimCreateOfferLegacy:EC,shimAudioContext:vC}),SC={};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let r=8;r<t.length;r+=2)switch(t[r]){case"raddr":i.relatedAddress=t[r+1];break;case"rport":i.relatedPort=parseInt(t[r+1],10);break;case"tcptype":i.tcpType=t[r+1];break;case"ufrag":i.ufrag=t[r+1],i.usernameFragment=t[r+1];break;default:void 0===i[t[r]]&&(i[t[r]]=t[r+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const r=e.substring(e.indexOf(" ")+1).split(";");for(let n=0;n<r.length;n++)i=r[n].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const r=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+i+" "+r.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substring(t+1,r),i.value=e.substring(r+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const r=t.matchPrefix(e+i,"a=ice-ufrag:")[0],n=t.matchPrefix(e+i,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substring(12),password:n.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(" ");i.profile=r[2];for(let o=3;o<r.length;o++){const n=r[o],s=t.matchPrefix(e,"a=rtpmap:"+n+" ")[0];if(s){const r=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+n+" ");switch(r.parameters=o.length?t.parseFmtp(o[0]):{},r.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+n+" ").map(t.parseRtcpFb),i.codecs.push(r),r.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(r.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const n=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{n.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let r="";r+="m="+e+" ",r+=i.codecs.length>0?"9":"0",r+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{r+=t.writeRtpMap(e),r+=t.writeFmtp(e),r+=t.writeRtcpFb(e)}));let n=0;return i.codecs.forEach((e=>{e.maxptime>n&&(n=e.maxptime)})),n>0&&(r+="a=maxptime:"+n+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{r+=t.writeExtmap(e)})),r},t.parseRtpEncodingParameters=function(e){const i=[],r=t.parseRtpParameters(e),n=-1!==r.fecMechanisms.indexOf("RED"),o=-1!==r.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===a&&(c=l[0][1]),r.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),n&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=d}))),i},t.parseRtcpParameters=function(e){const i={},r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=n.length>0,i.compound=0===n.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const r=t.matchPrefix(e,"a=msid:");if(1===r.length)return i=r[0].substring(7).split(" "),{stream:i[0],track:i[1]};const n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return n.length>0?(i=n[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),r=t.matchPrefix(e,"a=max-message-size:");let n;r.length>0&&(n=parseInt(r[0].substring(19),10)),isNaN(n)&&(n=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:n};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,r){let n;const o=void 0!==i?i:2;n=e||t.generateSessionId();return"v=0\r\no="+(r||"thisisadapterortc")+" "+n+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const r=t.splitLines(e);for(let t=0;t<r.length;t++)switch(r[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}({get exports(){return SC},set exports(e){SC=e}});var IC=SC,AC=e({__proto__:null,default:IC},[SC]);function RC(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),r=IC.parseCandidate(e.candidate);for(const e in r)e in i||Object.defineProperty(i,e,{value:r[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,PR(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function CC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||PR(e,"icecandidate",(e=>{if(e.candidate){const t=IC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function bC(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=IC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=IC.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),r=function(e,i){let r=65536;"firefox"===t.browser&&57===t.version&&(r=65535);const n=IC.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?r=parseInt(n[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(r=2147483637),r}(arguments[0],e);let n;n=0===i&&0===r?Number.POSITIVE_INFINITY:0===i||0===r?Math.max(i,r):Math.min(i,r);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>n}),this._sctp=o}return i.apply(this,arguments)}}function kC(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const r=arguments[0],n=r.length||r.size||r.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},PR(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function DC(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 NC(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 wC(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 OC(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 PC=Object.freeze({__proto__:null,shimRTCIceCandidate:RC,shimRTCIceCandidateRelayProtocol:CC,shimMaxMessageSize:bC,shimSendThrowTypeError:kC,shimConnectionState:DC,removeExtmapAllowMixed:NC,shimAddIceCandidateNullOrEmpty:wC,shimParameterlessSetLocalDescription:OC});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=xR,r=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=OR(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=OR(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=OR(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:PC,extractVersion:OR,disableLog:MR,disableWarnings:LR,sdp:AC};switch(r.browser){case"chrome":if(!ZR||!XR||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),n;if(null===r.version)return i("Chrome shim can not determine version, not shimming."),n;i("adapter.js shimming chrome."),n.browserShim=ZR,wC(e,r),OC(e),WR(e,r),GR(e),XR(e,r),JR(e),QR(e,r),zR(e),KR(e),qR(e),$R(e,r),RC(e),CC(e),DC(e),bC(e,r),kC(e),NC(e,r);break;case"firefox":if(!uC||!iC||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=uC,wC(e,r),OC(e),eC(e,r),iC(e,r),tC(e),oC(e),rC(e),nC(e),sC(e),aC(e),cC(e),lC(e),dC(e),RC(e),DC(e),bC(e,r),kC(e);break;case"safari":if(!yC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=yC,wC(e,r),OC(e),gC(e),EC(e),mC(e),hC(e),pC(e),TC(e),_C(e),vC(e),RC(e),CC(e),bC(e,r),kC(e),NC(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var MC,LC=Object.create,xC=Object.defineProperty,VC=Object.defineProperties,UC=Object.getOwnPropertyDescriptor,FC=Object.getOwnPropertyDescriptors,BC=Object.getOwnPropertyNames,HC=Object.getOwnPropertySymbols,jC=Object.getPrototypeOf,WC=Object.prototype.hasOwnProperty,GC=Object.prototype.propertyIsEnumerable,JC=Reflect.get,zC=Math.pow,KC=(e,t,i)=>t in e?xC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,qC=(e,t)=>{for(var i in t||(t={}))WC.call(t,i)&&KC(e,i,t[i]);if(HC)for(var i of HC(t))GC.call(t,i)&&KC(e,i,t[i]);return e},YC=(e,t)=>VC(e,FC(t)),QC=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),XC=(e,t)=>{for(var i in t)xC(e,i,{get:t[i],enumerable:!0})},$C=(e,t,i)=>(i=null!=e?LC(jC(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of BC(t))!WC.call(e,n)&&n!==i&&xC(e,n,{get:()=>t[n],enumerable:!(r=UC(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:xC(i,"default",{value:e,enumerable:!0}),e)),ZC=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?UC(t,i):t,s=e.length-1;s>=0;s--)(n=e[s])&&(o=(r?n(t,i,o):n(o))||o);return r&&o&&xC(t,i,o),o},eb=(e,t,i)=>(KC(e,"symbol"!=typeof t?t+"":t,i),i),tb=(e,t,i)=>JC(jC(e),i,t),ib=(e,t,i)=>new Promise(((r,n)=>{var o=e=>{try{a(i.next(e))}catch(MP){n(MP)}},s=e=>{try{a(i.throw(e))}catch(MP){n(MP)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),rb=QC(((e,t)=>{var i=Object.prototype.hasOwnProperty,r="~";function n(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,i,n,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new o(i,n||e,s),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function c(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),c.prototype.eventNames=function(){var e,t,n=[];if(0===this._eventsCount)return n;for(t in e=this._events)i.call(e,t)&&n.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},c.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,o=i.length,s=new Array(o);n<o;n++)s[n]=i[n].fn;return s},c.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},c.prototype.emit=function(e,t,i,n,o,s){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,d=this._events[a],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,n),!0;case 5:return d.fn.call(d.context,t,i,n,o),!0;case 6:return d.fn.call(d.context,t,i,n,o,s),!0}for(l=1,c=new Array(u-1);l<u;l++)c[l-1]=arguments[l];d.fn.apply(d.context,c)}else{var h,p=d.length;for(l=0;l<p;l++)switch(d[l].once&&this.removeListener(e,d[l].fn,void 0,!0),u){case 1:d[l].fn.call(d[l].context);break;case 2:d[l].fn.call(d[l].context,t);break;case 3:d[l].fn.call(d[l].context,t,i);break;case 4:d[l].fn.call(d[l].context,t,i,n);break;default:if(!c)for(h=1,c=new Array(u-1);h<u;h++)c[h-1]=arguments[h];d[l].fn.apply(d[l].context,c)}}return!0},c.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},c.prototype.removeListener=function(e,t,i,n){var o=r?r+e:e;if(!this._events[o])return this;if(!t)return a(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!n||s.once)&&(!i||s.context===i)&&a(this,o);else{for(var c=0,l=[],d=s.length;c<d;c++)(s[c].fn!==t||n&&!s[c].once||i&&s[c].context!==i)&&l.push(s[c]);l.length?this._events[o]=1===l.length?l[0]:l:a(this,o)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new n,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,void 0!==t&&(t.exports=c)})),nb=QC(((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")}))}))})),ob=QC((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var n=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:n&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=nb(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),sb=QC(((e,t)=>{var i=nb(),r=/%[sdv%]/g,n=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},o=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||s,n=t.innerOrder||a,c=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),ab=QC((e=>{var t=ob(),i=sb();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})),cb=QC(((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")}))}))})),lb=QC((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var n=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:n&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=cb(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),db=QC(((e,t)=>{var i=cb(),r=/%[sdv%]/g,n=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},o=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||s,n=t.innerOrder||a,c=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),ub=QC((e=>{var t=lb(),i=db();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})),hb=$C(rb()),pb=((MC=pb||{})[MC.INVALID_PARAMETER=4096]="INVALID_PARAMETER",MC[MC.INVALID_OPERATION=4097]="INVALID_OPERATION",MC[MC.NOT_SUPPORTED=4098]="NOT_SUPPORTED",MC[MC.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",MC[MC.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",MC[MC.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",MC[MC.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",MC[MC.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",MC[MC.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",MC[MC.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",MC[MC.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",MC[MC.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",MC[MC.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",MC[MC.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",MC[MC.CLIENT_BANNED=16448]="CLIENT_BANNED",MC[MC.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",MC[MC.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",MC[MC.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",MC[MC.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",MC[MC.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",MC[MC.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",MC[MC.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",MC[MC.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",MC[MC.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",MC[MC.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",MC[MC.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",MC[MC.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",MC[MC.API_CALL_ABORTED=16461]="API_CALL_ABORTED",MC[MC.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",MC[MC.UNKNOWN=65535]="UNKNOWN",MC),mb=pb,_b=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=mb.UNKNOWN,extraCode:n=0,constraint:o}=e,s="<".concat(function(e){for(let t in mb)if(mb[t]===e)return t;return"UNKNOWN"}(r)," 0x").concat(r.toString(16),">"),a="".concat(i).concat(o?" constraint: ".concat(o):"").concat(null!=i&&i.includes(s)?"":" ".concat(s));super(a),eb(this,"code"),eb(this,"extraCode"),eb(this,"message"),eb(this,"originMessage"),eb(this,"name"),eb(this,"constraint"),this.code=r,this.extraCode=n,this.name=t,this.message=a,this.constraint=o,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},fb=_b,gb=((new Date).getTime(),0),Tb=function(){return(new Date).getTime()+gb},Eb=function(){let e=new Date;return e.setTime(Tb()),e.toLocaleString()},vb={};XC(vb,{bytes2ms:()=>Ew,convertObjectNumberToInt:()=>lO,copyProperties:()=>Tw,deepClone:()=>$w,deepMerge:()=>Xw,delay:()=>dO,fibonacci:()=>Cw,formatedTime:()=>iO,getAbilityConfigUrl:()=>sw,getConstructorName:()=>Bw,getContainerFromElement:()=>eO,getEnv:()=>dw,getInternalVersion:()=>Jw,getLoggerUrl:()=>hw,getMuteStateFromFlag:()=>qw,getNetworkType:()=>mw,getNumNetworkType:()=>gw,getReconnectionTimeout:()=>bw,getStringByteLength:()=>oO,getTurnServer:()=>Yw,getUint32Version:()=>cO,getValueType:()=>kw,getViewListFromView:()=>Zw,glog:()=>Iw,ipv4ToUint32:()=>Qw,isArray:()=>Lw,isAudioWorkletSupported:()=>Hw,isBoolean:()=>Pw,isConstructor:()=>Fw,isEmpty:()=>Kw,isFunction:()=>Dw,isLangChinese:()=>Aw,isMediaStreamTrack:()=>xw,isNumber:()=>Ow,isObject:()=>Mw,isOverseaSdkAppId:()=>uw,isPlainObject:()=>Rw,isPortrait:()=>sO,isPromise:()=>Uw,isRemoteTrack:()=>Vw,isString:()=>ww,isUndefined:()=>Nw,loadImage:()=>aO,ms2bytes:()=>yw,ms2samples:()=>Sw,performanceNow:()=>Ww,promiseAny:()=>jw,samples2ms:()=>vw,setNetworkType:()=>fw,stringify:()=>rO,stringifyIncludeValue:()=>nO,throttlePromise:()=>uO});var yb={};XC(yb,{AUDIO_MUTE_BIT:()=>ak,AUDIO_STAT_BIT:()=>sk,AUX_STAT_BIT:()=>ok,AUX_STREAM_MSID:()=>dk,BACKEND_ENV:()=>tk,BASE_DOC_URL:()=>Vb,BASE_HOST:()=>Pb,CAPABILITIES_KEYS:()=>tD,CLASS_NAME:()=>jk,CLOUD_CONSOLE_URL:()=>xb,DATA_FREEZE_TIMING:()=>Lk,DOC_URL:()=>Ub,DTLS_STATE_UNKNOWN:()=>vk,ENV_NAME:()=>Wb,EXCHANGE_SDP_TIMEOUT:()=>Nk,INTERVAL:()=>Zk,IS_WORKER:()=>kb,IS_WORKLET:()=>Db,KIBANA_EVENT:()=>bk,LOCAL_STREAM_PUBLISH_STATE:()=>Mk,LOGGER_CMD_TYPE:()=>jb,LOGGER_DOMAIN:()=>Fb,LOGGER_DOMAIN_OVERSEA:()=>Bb,LOG_LEVEL:()=>Gb,LOG_LEVEL_NAME:()=>Kk,MAIN_STREAM_MSID:()=>lk,MICROPHONE_COMMUNICATIONS:()=>zk,MICROPHONE_DEFAULT:()=>Gk,NAME:()=>Zb,NETWORK_TYPE:()=>Kb,NOT_SUPPORTED_H264:()=>Pk,PAUSED_RETRY_COUNT:()=>Wk,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Fk,PEER_CONNECTION_STATE:()=>yk,PEER_LEAVE_REASON:()=>qk,RAF:()=>$k,RECOVER_CAPTURE_INTERVAL:()=>Qk,REMOTE_STREAM_TYPE_AUX:()=>hk,REMOTE_STREAM_TYPE_MAIN:()=>uk,RENDER_FREEZE_TIMING:()=>xk,RIC:()=>Xk,SCHEDULE_DOMAIN:()=>Bk,SCHEDULE_TIMEOUT:()=>Hk,SDP_SEMANTICS_PLAN_B:()=>Ok,SDP_SEMANTICS_UNIFIED_PLAN:()=>wk,SECOND_HOST:()=>Mb,SIGNAL_PING_PONG_INTERVAL:()=>zb,SIGNAL_PING_TIMEOUT:()=>Jb,SIGNAL_RECONNECTION_COUNT:()=>Ck,SMALL_STAT_BIT:()=>nk,SPEAKER_DEFAULT:()=>Jk,STORAGE_EXPIRES_TIME:()=>qb,STREAM_TYPE_BIG:()=>Vk,STREAM_TYPE_SMALL:()=>Uk,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Yk,SYNC_USER_LIST_INTERVAL:()=>kk,Scene:()=>ik,Switch:()=>Yb,THIRD_HOST:()=>Lb,TIMEOUT:()=>eD,TRANSPORT_DIRECTION:()=>ek,TRTC_ERROR_ASSISTANCE:()=>Hb,TRTC_QUALITY_BAD:()=>gk,TRTC_QUALITY_DISCONNECTED:()=>Ek,TRTC_QUALITY_EXCELLENT:()=>mk,TRTC_QUALITY_GOOD:()=>_k,TRTC_QUALITY_POOR:()=>fk,TRTC_QUALITY_UNKNOWN:()=>pk,TRTC_QUALITY_VERY_BAD:()=>Tk,UPDATE_OFFER_TIMEOUT:()=>Dk,VIDEO_MUTE_BIT:()=>ck,VIDEO_STAT_BIT:()=>rk,audioProfileMap:()=>Qb,getRetryCount:()=>Ak,getScriptDir:()=>Nb,innerVersion:()=>Sb,loggerProxy:()=>wb,screenProfileMap:()=>$b,setLoggerProxy:()=>Ob,setRetryCount:()=>Ik,setVersion:()=>Ab,version:()=>Ib,videoProfileMap:()=>Xb});var Sb="4.15.00.1600",Ib="5.0.0";function Ab(e){Ib=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));Sb="".concat(t,".").concat(Math.min(15,i),".").concat(Math.min(15,r),".").concat(i.toString().padStart(2,"0")).concat(r.toString().padStart(2,"0"))}var Rb,Cb,bb,kb="undefined"!=typeof importScripts,Db="undefined"!=typeof registerProcessor,Nb=()=>{let e=kb?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},wb="",Ob=e=>wb=e,Pb="web.sdk.qcloud.com",Mb="web.sdk.tencent.cn",Lb="web.sdk.cloud.tencent.cn",xb="https://console.cloud.tencent.com/trtc",Vb="https://".concat(Pb,"/trtc/webrtc/v5/doc"),Ub="".concat(Vb,"/zh-cn/"),Fb="https://yun.tim.qq.com",Bb="https://apisgp.my-imcloud.com",Hb="trtc_error_assistance",jb={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Wb={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Gb=((bb=Gb||{})[bb.TRACE=0]="TRACE",bb[bb.DEBUG=1]="DEBUG",bb[bb.INFO=2]="INFO",bb[bb.WARN=3]="WARN",bb[bb.ERROR=4]="ERROR",bb[bb.NONE=5]="NONE",bb),Jb=18e3,zb=2e3,Kb={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},qb=6048e5,Yb=((Cb=Yb||{}).USEAINS="useAINS",Cb.ENABLEDEBUG="enableDebug",Cb.USEV2="useV2",Cb.USEWT="useWt",Cb),Qb={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},Xb={"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}},$b={"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}},Zb={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"},ek={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},tk={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},ik=((Rb=ik||{}).LIVE="live",Rb.RTC="rtc",Rb),rk=1,nk=2,ok=4,sk=8,ak=64,ck=16,lk="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",dk="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",uk=Zb.MAIN,hk=Zb.AUXILIARY,pk=0,mk=1,_k=2,fk=3,gk=4,Tk=5,Ek=6,vk="unknown",yk={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Sk=1/0;function Ik(e){Sk=e}function Ak(){return Sk}var Rk,Ck=30,bk={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"},kk=1e4,Dk=1e4,Nk=1e4,wk="unified-plan",Ok="plan-b",Pk=1028,Mk=((Rk=Mk||{})[Rk.UNPUBLISH=-1]="UNPUBLISH",Rk[Rk.PUBLISHING=0]="PUBLISHING",Rk[Rk.PUBLISHED=1]="PUBLISHED",Rk),Lk=500,xk=1e3,Vk=Zb.BIG,Uk=Zb.SMALL,Fk=1e4,Bk={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_OLD:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA_OLD:"schedule-ecdn.rtc.tencentcloud.com"},Hk=2e3,jk={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Wk=5,Gk="default",Jk=Gk,zk="communications",Kk=Object.keys(Gb),qk=["normal leave","timeout leave","kick","role change"],Yk=10,Qk=2e3,Xk="ric",$k="raf",Zk="interval",eD="timeout",tD=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"];function iD(e){let{url:t,body:i,method:r,timeout:n}=e,o=new XMLHttpRequest;return new Promise(((e,s)=>{o.onreadystatechange=()=>{if(4===o.readyState)if(o.status>=200&&o.status<300)try{let t=JSON.parse(o.response);e({data:t})}catch(t){e({data:o.response})}else s({status:o.status,statusText:o.statusText||"request failed!"})},o.timeout=n||5e3,o.open(r||"POST",t,!0),o.send(i)}))}function rD(e){return ib(this,null,(function*(){let t=Ww(),i=JSON.stringify(e);try{if(!CompressionStream||i.length<=2800)return i;let e=new Blob([i],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),r=yield(yield(yield new Response(e)).blob()).arrayBuffer();return TO.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(Ww()-t,"ms")),r}catch(Rk){return i}}))}var nD=1e8,oD={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},sD={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(r,"(), received type: ").concat(kw(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(r,"(), received type: ").concat(kw(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:r,value:n}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(n,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,fnName:r,value:n}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(n,".")},API_CALL_TIMEOUT:e=>"".concat(e.commandDesc||e.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," })."),ERROR_MESSAGE(e){let t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>"exchange sdp failed ".concat(e.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>"'".concat(e,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:e=>"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(e){let{error:t,code:i}=e;return"Failed to join room - ".concat(t," code: ").concat(i)},REJOIN_ROOM_FAILED:e=>"reJoin room: ".concat(e.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:"no permission to publish() under live/".concat("audience",', please call switchRole("',"anchor",'") firstly before publish().'),INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>"duplicate ".concat(e," stream publishing, please unpublish your prev ").concat(e," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(e){let{message:t,userId:i,streamType:r}=e;return"failed to subscribe ".concat(i," ").concat(r," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as ".concat("anchor"," or ","audience","."),INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,"."),CLIENT_BANNED:e=>"client was banned because of ".concat(e.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>"startPublishCDNStream failed, errMsg: ".concat(e.message,"."),STOP_PUBLISH_CDN_FAILED:e=>"stopPublishCDNStream failed, errMsg: ".concat(e.message,"."),INVALID_STREAM_ID:e=>"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>"cannot replace ".concat(e.kind," track because stream has not ").concat(e.kind," track"),NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:e=>"startMixTranscode failed, errMsg: ".concat(e.message,"."),STOP_MIX_TRANSCODE_FAILED:e=>"stopMixTranscode failed, errMsg: ".concat(e.message,"."),MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:e=>"'".concat(e,"' is required and must be between 1 and 15."),MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:e=>{let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE:e=>{let{key:t,fnName:i,type:r}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(r,".")},PLAY_FAILED:e=>"".concat(e.media," play failed,browser exception: ").concat(e.error.toString()),INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:e=>"".concat(e,"Track is not supported on your browser."),NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:e=>"".concat(e.signalResponse," failed, response code is ").concat(e.code," , errMsg: ").concat(e.message,"."),CATCH_HANDLER_ERROR(e){let{name:t,event:i}=e;return"an error was caught in ".concat(t,".on('").concat(i,"', handler), please check your code in 'handler'.")},API_NOT_EXIST(e){let{name:t}=e;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:e=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(e){let{funName:t}=e;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage".concat(!1===e?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:e=>{let{isSize:t,name:i,timesInSecond:r,maxSizeInSecond:n}=e;return"api ".concat(i," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(n," bytes"):r," in a second.")},CONNECTION_ABORTED:e=>"connection aborted due to: ".concat(e),API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(e.userId," ").concat(e.streamType," stream aborted, reason: remote user ").concat(e.userId," unpublished stream."):"API aborted, reason: ".concat(e.message),t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:e=>"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")},aD={};XC(aD,{ANDROID_VERSION:()=>vD,CHROME_MAJOR_VERSION:()=>yN,CHROME_VERSION:()=>SN,EDGE_VERSION:()=>bD,EDG_MAJOR_VERSION:()=>ND,EDG_VERSION:()=>DD,FIREFOX_MAJOR_VERSION:()=>RD,FIREFOX_VERSION:()=>AD,HUAWEI_VERSION:()=>dN,IE_VERSION:()=>HD,IOS_MAIN_VERSION:()=>kN,IOS_VERSION:()=>bN,IPADQQB_VERSION:()=>$D,IS_ANDROID:()=>ED,IS_ANDROID_WEBVIEW:()=>CN,IS_ANY_SAFARI:()=>AN,IS_CHROME:()=>EN,IS_CHROME_OS:()=>iN,IS_CHROMIUM_BASE:()=>TN,IS_EDG:()=>kD,IS_EDGE:()=>CD,IS_ELECTRON:()=>oN,IS_FIREFOX:()=>ID,IS_HEADLESS_CHROME:()=>vN,IS_HUAWEI:()=>lN,IS_HUAWEIBROWSER:()=>cN,IS_IE:()=>BD,IS_IE8:()=>FD,IS_IOS:()=>TD,IS_IOS_13_OR_14:()=>wN,IS_IOS_15_1:()=>NN,IS_IPAD:()=>mD,IS_IPADQQB:()=>XD,IS_IPAD_PRO:()=>_D,IS_IPHONE:()=>fD,IS_IPOD:()=>gD,IS_LINUX:()=>tN,IS_LOCAL:()=>ON,IS_MAC:()=>eN,IS_MACQQB:()=>YD,IS_MIBROWSER:()=>sN,IS_MQQB:()=>JD,IS_NATIVE_ANDROID:()=>SD,IS_OLD_ANDROID:()=>yD,IS_OPPOBROWSER:()=>pN,IS_SAFARI:()=>IN,IS_SAFARI_15_1:()=>DN,IS_SAMSUNGBROWSER:()=>uN,IS_SOGOU:()=>PD,IS_SOGOUM:()=>wD,IS_TBS:()=>LD,IS_UCBROWSER:()=>nN,IS_VIVOBROWSER:()=>_N,IS_WECHAT:()=>jD,IS_WIN:()=>ZD,IS_WQQB:()=>KD,IS_WX:()=>rN,IS_X5MQQB:()=>GD,IS_XWEB:()=>VD,MACQQB_VERSION:()=>QD,MI_VERSION:()=>aN,MQQB_VERSION:()=>zD,OPPO_VERSION:()=>mN,SAFARI_VERSION:()=>RN,SAMSUNG_VERSION:()=>hN,SOGOUM_VERSION:()=>OD,SOGOU_VERSION:()=>MD,TBS_VERSION:()=>xD,UA_DATA_STRING:()=>VN,USER_AGENT:()=>cD,VIVO_VERSION:()=>fN,WECHAT_VERSION:()=>WD,WQQB_VERSION:()=>qD,XWEB_VERSION:()=>UD,browserInfo:()=>MN,getBrowserInfo:()=>LN,getChromeMajorVersion:()=>gN,getDeviceModel:()=>FN,getOSName:()=>HN,getOSString:()=>jN,getOSType:()=>GN,getTerminalType:()=>WN,getUserAgentData:()=>UN,isLocalStorageEnabled:()=>PN});var cD="undefined"==typeof navigator?"":navigator.userAgent,lD=e=>new RegExp(e,"i").test(cD),dD=e=>{if(lD(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=cD.match(t);if(i&&i[1])return i[1]}return""},uD=e=>{if(lD(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=cD.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},hD=/AppleWebKit\/([\d.]+)/i.exec(cD),pD=hD?parseFloat(hD[1]):NaN,mD=lD("iPad"),_D="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&lD("Macintosh"),fD=lD("iPhone")&&!mD,gD=lD("iPod"),TD=fD||mD||gD||_D,ED=lD("Android"),vD=function(){if(ED){let e=cD.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}(),yD=ED&&lD("webkit")&&vD<2.3,SD=ED&&vD<5&&pD<537,ID=lD("Firefox"),AD=dD("Firefox"),RD=uD("Firefox"),CD=lD("Edge"),bD=dD("Edge"),kD=lD("Edg"),DD=dD("Edg"),ND=uD("Edg"),wD=lD("SogouMobileBrowser"),OD=dD("SogouMobileBrowser"),PD=lD("MetaSr\\s"),MD=dD("MetaSr\\s"),LD=lD("TBS"),xD=dD("TBS"),VD=lD("XWEB"),UD=dD("XWEB"),FD=lD("MSIE\\s8\\.0"),BD=lD("MSIE\\/\\d+"),HD=function(){if(BD){let e=/MSIE\s(\d+)\.\d/.exec(cD),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(cD)&&/rv:11.0/.test(cD)&&(t=11),t}return NaN}(),jD=lD("(micromessenger|webbrowser)"),WD=dD("MicroMessenger"),GD=!LD&&lD("MQQBrowser")&&lD("COVC"),JD=!LD&&lD("MQQBrowser")&&!lD("COVC"),zD=JD||GD?dD("MQQBrowser"):"",KD=!LD&&lD(" QQBrowser"),qD=dD(" QQBrowser"),YD=!LD&&lD("QQBrowserLite"),QD=dD("QQBrowserLite"),XD=!LD&&lD("MQBHD"),$D=dD("MQBHD"),ZD=lD("Windows"),eN=!TD&&lD("MAC OS X"),tN=!ED&&lD("Linux"),iN=lD("CrOS"),rN=lD("MicroMessenger"),nN=lD("UCBrowser"),oN=lD("Electron"),sN=lD("MiuiBrowser"),aN=dD("MiuiBrowser"),cN=lD("HuaweiBrowser"),lN=lD("Huawei"),dN=dD("HuaweiBrowser"),uN=lD("SamsungBrowser"),hN=dD("SamsungBrowser"),pN=lD("HeyTapBrowser"),mN=dD("HeyTapBrowser"),_N=lD("VivoBrowser"),fN=dD("VivoBrowser"),gN=()=>uD("Chrome"),TN=lD("Chrome"),EN=!CD&&!PD&&!wD&&!LD&&!VD&&!kD&&!KD&&!sN&&!cN&&!uN&&!pN&&!_N&&TN,vN=lD("HeadlessChrome"),yN=gN(),SN=dD("Chrome"),IN=!TN&&!JD&&!GD&&!YD&&!XD&&lD("Safari"),AN=IN||TD,RN=dD("Version"),CN=/Android.*(wv|.0.0.0)/.test(cD),bN=(()=>{if(_D)return RN;if(TD){let e=cD.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),kN=Number(bN.split(".")[0]),DN="15.1"===RN,NN="15.1"===bN,wN=(()=>{let e=Number(bN.split(".")[0]);return 14===e||13===e})(),ON="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),PN=(()=>{let e;return()=>{if(Nw(e))try{e=!!window.localStorage}catch(xP){e=!1}return e}})(),MN=LN();function LN(){let e=new Map([[ID,["Firefox",AD]],[kD,["Edg",DD]],[EN,["Chrome",SN]],[IN,["Safari",RN]],[LD,["TBS",xD]],[VD,["XWEB",UD]],[jD&&fD,["WeChat",WD]],[KD,["QQ(Win)",qD]],[JD,["QQ(Mobile)",zD]],[GD,["QQ(Mobile X5)",zD]],[YD,["QQ(Mac)",QD]],[XD,["QQ(iPad)",$D]],[sN,["MI",aN]],[cN,["HW",dN]],[uN,["Samsung",hN]],[pN,["OPPO",mN]],[_N,["VIVO",fN]],[CD,["EDGE",bD]],[wD,["SogouMobile",OD]],[PD,["Sogou",MD]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var xN=null,VN="";function UN(){return ib(this,null,(function*(){if(xN)return xN;if(!navigator.userAgentData||!Dw(navigator.userAgentData.getHighEntropyValues))return null;try{return(xN=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!VN&&(VN="UAData: ".concat(xN.platform,"/").concat(xN.platformVersion),xN.architecture&&xN.bitness&&(VN+=" ".concat(xN.architecture,"/").concat(xN.bitness)),xN.mobile&&(VN+=" mobile"),xN.model&&(VN+=" model: ".concat(xN.model)),xN.fullVersionList&&(VN+=" ".concat(xN.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),xN}catch(WF){return null}}))}function FN(){return(null==xN?void 0:xN.model)||""}var BN=new Map([[ED,"Android"],[TD,"iOS"],[ZD,"Windows"],[eN,"MacOS"],[tN,"Linux"],[iN,"ChromeOS"]]),HN=function(){return BN.get(!0)?BN.get(!0):xN?xN.platform:"unknown"},jN=()=>{let e=HN();return e+="/".concat(MN.name,"/").concat(IN?MN.version:MN.version.split(".")[0]),null!=xN&&xN.platformVersion&&(e+="/".concat(xN.platformVersion)),null!=xN&&xN.architecture&&(e+="/".concat(xN.architecture)),e};function WN(){return ED?4:fD?2:mD?3:eN?12:ZD?5:tN?13:1}function GN(){return ED?"Android":fD?"iPhone":mD?"iPad":eN?"Mac":ZD?"Windows":tN?"Linux":"unknown"}var JN=(e,t)=>t?"".concat(Vb,"/").concat(e,"/").concat(t):"".concat(Vb,"/").concat(e,"/index.html"),zN=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let e=null==localStorage?void 0:localStorage.getItem(Hb);if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let i=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:r}}return{}};function KN(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",s="",a="";Dw(sD[t])?o=sD[t](i):ww(sD[t])&&(o=sD[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=zN();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(Dw(l[t])?a=l[t](i):ww(l[t])&&(a=l[t]));let d=o;return Aw()&&(c&&c[t]&&(Dw(c[t])?s=c[t](i):ww(c[t])&&(s=c[t])),s&&(d=n?"".concat(s,"\n请查看文档: ").concat(JN("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(JN("en",a),"\n")),d}var qN,YN=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:n,onRetryFailed:o,onRetrySuccess:s,context:a}=e;return function(){for(var e=arguments.length,c=new Array(e),l=0;l<e;l++)c[l]=arguments[l];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,_=(e,i)=>ib(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<(Dw(d)?d():d)?(h++,m=1,Dw(n)&&n.call(this,h,t),p=window.setTimeout((()=>{p=-1,_(e,i)}),Dw(u)?u(h):u)):(t(),Dw(o)&&o.call(this,f))};Dw(r)?r.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(_)}},QN=new($C(rb(),1).default),XN=((qN=XN||{}).ROOM_DESTROY="1",qN.JOIN_START="21",qN.JOIN_SCHEDULE_SUCCESS="22",qN.JOIN_SIGNAL_CONNECTION_START="23",qN.JOIN_SIGNAL_CONNECTION_END="24",qN.JOIN_SEND_CMD="25",qN.JOIN_RECEIVED_CMD_RES="26",qN.JOIN_SUCCESS="27",qN.JOIN_FAILED="28",qN.LEAVE_START="51",qN.LEAVE_SEND_CMD="52",qN.LEAVE_SUCCESS="53",qN.PUBLISH_START="61",qN.SEND_FIRST_VIDEO_FRAME="62",qN.PUBLISH_FAILED="63",qN.SUBSCRIBE_START="81",qN.SUBSCRIBE_SUCCESS="82",qN.SUBSCRIBE_FAILED="84",qN.UNSUBSCRIBE_SUCCESS="83",qN.LOCAL_TRACK_CAPTURE_START="101",qN.LOCAL_TRACK_CAPTURE_SUCCESS="102",qN.LOCAL_TRACK_CAPTURE_FAILED="103",qN.LOCAL_TRACK_PUBLISHED="104",qN.LOCAL_TRACK_UNPUBLISHED="105",qN.LOCAL_TRACK_REPLACED="106",qN.SWITCH_DEVICE_SUCCESS="107",qN.TRACK_MUTED="108",qN.TRACK_UNMUTED="109",qN.REMOTE_TRACK_SUBSCRIBED="110",qN.REMOTE_TRACK_UNSUBSCRIBED="111",qN.LOCAL_TRACK_RECAPTURE="112",qN.PLAY_TRACK_START="151",qN.PLAYER_STATE_CHANGED="152",qN.VIDEO_LOADED_DATA="153",qN.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",qN.SIGNAL_CONNECTION_STATE_CHANGED="201",qN.PEER_CONNECTION_STATE_CHANGED="202",qN.SINGLE_CONNECTION_STAT="203",qN.SPC_RECONNECTED="204",qN.HEARTBEAT_REPORT="251",qN.RECEIVED_PUBLISHED_USER_LIST="252",qN.REMOTE_PUBLISH_STATE_CHANGED="253",qN.AUDIO_LEVEL_INTERVAL="260",qN.NETWORK_QUALITY="261",qN.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",qN.QUALITY_LIMITATION_CHANGED="263",qN.LOG="264",qN.SEND_SEI_MESSAGE="265",qN),$N=new class{constructor(){this._roomIdMap=new Map,"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:Ib,env:Wb.QCLOUD,browserVersion:MN.name+MN.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:i,userId:r,roomId:n}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=r,this._roomIdMap.set(r,String(n))}logSuccessEvent(e){ON||!TO.isAbleToUpload||this._configs.env===Wb.QCLOUD&&this.uploadEventToKibana(YC(qC({},e),{result:"success"}))}logFailedEvent(e){if(ON||!TO.isAbleToUpload)return;let{eventType:t,code:i,error:r,userId:n}=e,o={roomId:this._roomIdMap.get(n||this._configs.userId),userId:n,eventType:t,result:"failed",code:i||(null==r?void 0:r.extraCode)||(null==r?void 0:r.code)||mb.UNKNOWN};this._configs.env===Wb.QCLOUD&&this.uploadEventToKibana(YC(qC({},o),{error:r}))}uploadEventToKibana(e){let t="stat-".concat(e.eventType,"-").concat(e.result);("delta-join"===e.eventType||"delta-leave"===e.eventType||"delta-publish"===e.eventType)&&(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}uploadEvent(e){let{log:t,userId:i,error:r}=e,n={timestamp:Eb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:Ib,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+="\n".concat(r.stack))),this.sendRequest(hw(this._configs.sdkAppId,jb.LOG),n)}sendRequest(e,t){TO.isAbleToUpload?iD({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},ZN=null,ew=!0;function tw(e){Pw(e)&&e!==ew&&(ew=e,TO.info("setIsNeedToSchedule ".concat(e)))}function iw(e){return ib(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:n,userSig:o,version:s,frameWorkType:a,role:c,latencyLevel:l}=e;return function*(){if(!ew&&ZN)return{isCached:!0,result:ZN};let e={delta:0,count:[1,1],msg:[],detail:[]};try{let d=new FormData;d.append("userId",String(t)),d.append("sdkAppId",String(i)),d.append("isStrGroupId",String(r)),d.append("groupId",String(n)),d.append("sdkVersion",s),d.append("userSig",String(o)),c&&d.append("role",String(c)),l&&d.append("latencyLevel",String(l)),a&&d.append("frameWorkType",String(a));let u=Ww(),h=yield function(e,t,i){return new Promise(((r,n)=>{let o=null;jw([lw((e=>t.count[0]=e+1),(e=>{let{error:r,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[0]=r.message,o||(s>=2&&(a[0]=ow(i,Zb.MAIN,!0)),n())}))(ow(i,Zb.MAIN),e,{get timeout(){return 1e3*Cw(2+t.count[0])}}),lw((e=>t.count[1]=e+1),(e=>{let{error:r,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[1]=r.message,o||(s>=2&&(a[0]=ow(i,Zb.BACKUP,!0)),n())}))(ow(i,Zb.BACKUP),e,{get timeout(){return 1e3*Cw(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}(d,e,i);h.config&&(h.config.loggerDomain&&Ob(h.config.loggerDomain),Pw(h.config.scheduleCache)&&tw(!h.config.scheduleCache)),e.delta=Ww()-u;let p=function(e,t,i){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let n=performance.getEntriesByType("resource"),o=ow(e,Zb.MAIN),s=ow(e,Zb.BACKUP);for(let e of n)if(e.startTime>=i&&(e.name===o||e.name===s)&&e.transferSize>0){let i=e.name===o?Zb.MAIN:Zb.BACKUP,n=Math.round(e.duration),s=Math.round(e.domainLookupStart-e.startTime),a=e.redirectStart>0?Math.round(e.redirectEnd-e.redirectStart):0,c=e.fetchStart>0?Math.round(e.domainLookupStart-e.fetchStart):0,l=Math.round(e.domainLookupEnd-e.domainLookupStart),d=Math.round(e.requestStart-e.secureConnectionStart),u=Math.round(e.secureConnectionStart-e.connectStart),h=Math.round(e.responseStart-e.requestStart),p=Math.round(e.responseEnd-e.responseStart),m=[l,d,u,h,p];$N.uploadEvent({log:"stat-schedule-net:".concat(n,"(").concat(s,"(").concat(a,"->").concat(c,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=YC(qC({},r),{totalCost:n,local:s,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(o){TO.error("getScheduleDetailCost error",o)}return r}(Number(i),t,u);return ZN=h,{isCached:!1,result:h,detailCost:p}}catch(d){let e=Lw(d)?d[0]:d,t=Ow(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),r=new fb({code:mb.SCHEDULE_FAILED,extraCode:t,message:KN({key:oD.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw TO.error(i,t),r}}()}))}document&&document.head.insertAdjacentHTML("beforeend",Object.values(Bk).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),QN.on("28",(()=>tw(!0))),QN.on("63",(()=>tw(!0))),QN.on("84",(()=>tw(!0))),QN.on("201",(e=>{"RECONNECTING"===e.state&&tw(!0)})),QN.on("202",(e=>{"RECONNECTING"===e.state&&tw(!0)}));var rw={main:"",backup:""};function nw(e){Lw(e)?(rw.main=e[0],rw.backup=e[1]):rw.main=e}function ow(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Zb.MAIN,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return"https://".concat(rw[t]||aw(e,t,i),"/api/v1/config")}function sw(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Zb.MAIN;return"https://".concat(rw[t]||aw(e,t),"/api/v1/trtcAutoConf")}function aw(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Zb.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return uw(e)?i===Zb.MAIN?Bk.MAIN_OVERSEA:Bk.BACKUP_OVERSEA:(t=uw(e)?r?i===Zb.MAIN?Bk.MAIN_OVERSEA_OLD:Bk.BACKUP_OVERSEA_OLD:i===Zb.MAIN?Bk.MAIN_OVERSEA:Bk.BACKUP_OVERSEA:i===Zb.MAIN?Bk.MAIN:Bk.BACKUP,t)}function cw(e,t,i){return new Promise(((r,n)=>{iD({url:e,body:t,timeout:i.timeout}).then((e=>{0===e.data.code?r(e.data.data):n({code:e.data.code,message:e.data.msg})})).catch(n)}))}var lw=(e,t)=>YN({retryFunction:cw,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var dw=function(){return new URLSearchParams(location.search).get("trtc_env")||""},uw=e=>Number(e)<14e8,hw=function(e,t){let i;i=wb||(uw(e)?Bb:Fb);let r=Math.floor(Math.random()*zC(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},pw="unknown";function mw(){if("unknown"!==pw)return pw;let{userAgent:e,connection:t}=navigator,i=(e.match(/NetType\/\S+/)||[])[0]||"";i=i.toLowerCase().replace("nettype/",""),"3gnet"===i&&(i="3g");let r=t&&t.type&&t.type.toLowerCase(),n=t&&t.effectiveType&&t.effectiveType.toLowerCase();return"slow-2"===n&&(n="2g"),r&&(pw=_w(r,n)),pw}function _w(e,t){if(Kb[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function fw(e){pw=_w(e)}function gw(){return Kb[mw()]}function Tw(e,t){for(let i of Reflect.ownKeys(t))if("constructor"!==i&&"prototype"!==i&&"name"!==i){let r=Object.getOwnPropertyDescriptor(t,i)||"";Object.defineProperty(e,i,r)}return e}function Ew(e){return vw(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function vw(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function yw(e){return 4*Sw(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function Sw(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var Iw="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},Aw=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},Rw=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 Cw(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:Cw(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function bw(e){return e>8?3e4:1e3*Cw(e)}function kw(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Dw=e=>"function"==typeof e,Nw=e=>void 0===e,ww=e=>"string"==typeof e,Ow=e=>"number"==typeof e,Pw=e=>"boolean"==typeof e,Mw=e=>"object"===kw(e),Lw=e=>"array"===kw(e),xw=e=>kw(e)==="MediaStreamTrack".toLowerCase(),Vw=e=>e.isRemote,Uw=e=>"promise"===kw(e),Fw=e=>Dw(e)&&e.prototype.constructor===e,Bw=e=>Fw(e)?e.prototype.constructor.name:"",Hw="undefined"!=typeof AudioWorkletNode;function jw(e){return new Promise(((t,i)=>{let r=[];e.forEach((n=>{n.then(t).catch((t=>{r.push(t),r.length===e.length&&i(r)}))}))}))}function Ww(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var Gw=e=>+e<10?"0".concat(e):e,Jw=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=Gw(i[1])+Gw(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},zw=Object.prototype.hasOwnProperty;function Kw(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(Rw(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(zw.call(e,t))return!1;return!0}return!1}function qw(e,t){return{userId:t,hasAudio:!!(e&sk),hasVideo:!!(e&rk),hasAuxiliary:!!(e&ok),hasSmall:!!(e&nk),audioMuted:!!(e&ak),videoMuted:!!(e&ck),audioAvailable:!(!(e&sk)||e&ak),videoAvailable:!(!(e&rk)||e&ck)}}function Yw(e){let t={urls:"turn:".concat(e.url)};return!Nw(e.username)&&!Nw(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",Nw(e.credentialType)||(t.credentialType=e.credentialType)),t}function Qw(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!ww(e))return 0;let i=e.split(".");return t?(Number(i[0])<<24|Number(i[1])<<16|Number(i[2])<<8|Number(i[3]))>>>0:(Number(i[3])<<24|Number(i[2])<<16|Number(i[1])<<8|Number(i[0]))>>>0}var Xw=function(e,t,i,r){if(!Mw(e)||!Mw(t))return 0;let n,o=0,s=Object.keys(t);for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(Nw(t[n])||i&&i.includes(n)))if(Mw(e[n])&&Mw(t[n]))o+=Xw(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=$w(t[n]),o+=1)}return o};function $w(e){if(Lw(e)){let t=[];return e.forEach(((e,i)=>{t[i]=$w(e)})),t}if(Mw(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=$w(e[i])})),t}return e}var Zw=e=>{let t=[];if(Lw(e))t=[...e];else if(ww(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},eO=e=>ww(e)?document.getElementById(e):e,tO=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),iO=()=>tO.format(new Date);function rO(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(Lw(e))return"[".concat(e.map((e=>rO(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!Rw(e)||!Lw(i)&&!Lw(r))return JSON.stringify(e);let t={},n=new Set(i),o=new Set(r);return Object.keys(e).forEach((s=>{(0===o.size&&n.has(s)||0===n.size&&!o.has(s))&&(t[s]=Rw(e[s])||Lw(e[s])?JSON.parse(rO(e[s],{keysToExclude:r,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(Rk){return"{}"}}function nO(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=[];return Object.keys(e).forEach((r=>{t===e[r]&&i.push(r)})),rO(e,{keysToInclude:i})}function oO(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var sO=()=>{var e,t,i,r;return null!=(e=window.screen)&&e.orientation?!(null==(r=null==(i=null==(t=window.screen)?void 0:t.orientation)?void 0:i.type)||!r.includes("portrait")):0===window.orientation||180===window.orientation},aO=e=>ib(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(ww(e))r=new Image,r.crossOrigin="anonymous",r.src=e;else if(r=e,r.complete)return void t(r);r.onload=()=>t(r),r.onerror=i}))})),cO=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},lO=e=>(Object.keys(e).forEach((t=>{Ow(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(Rw(e[t])||Lw(e[t]))&&lO(e[t])})),e);function dO(e){return new Promise((t=>setTimeout(t,e)))}var uO=(e,t)=>{let i=null;return function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return i||(i=e.apply(t||this,n),i.finally((()=>i=null)),i)}},hO=Object.prototype.hasOwnProperty,pO=e=>void 0===e;function mO(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(function(e){if(!e||"object"!=typeof e||"[object Object]"!=Object.prototype.toString.call(e))return!1;let t=Object.getPrototypeOf(e);if(null===t)return!0;let i=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof i&&i instanceof i&&Function.prototype.toString.call(i)===Function.prototype.toString.call(Object)}(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(let t in e)if(hO.call(e,t))return!1;return!0}return!1}var _O=class{constructor(e){eb(this,"userId"),eb(this,"remoteUserId"),eb(this,"id"),eb(this,"sdkAppId"),eb(this,"type"),eb(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal="boolean"!=typeof e.isLocal||e.isLocal,this.type=this.isLocal?"":e.type}createChild(e){return Object.setPrototypeOf(e,this)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId;t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(this.id).concat(i?"|".concat(i):"","]")),TO.log(e,t,pO(this.userId)||mO(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=XN,gO=!(TD||ED||vN),TO=new class{constructor(){eb(this,"_isEnableUploadLog",!0),eb(this,"_localJoinedUser",new Map),eb(this,"_queue",[]),eb(this,"_timeoutId",-1),eb(this,"_logLevel",1),eb(this,"_logLevelToUpload",2),!kb&&!Db&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){QN.on(fO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&Gb[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),QN.on(fO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),QN.once(fO.JOIN_FAILED,(()=>{this.startUpload()})),QN.on(fO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.deleteJoinedUser(t.userId)}))}startUpload(){-1===this._timeoutId&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch((()=>{})),this._timeoutId=window.setTimeout((()=>this.uploadInterval()),2e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&0===this._localJoinedUser.size)return e;let t=0;for(;t<this._queue.length&&50!==t;t++){let i=this._queue[t];if(i.forAllJoinedClients)this._localJoinedUser.forEach((t=>{let{userId:r,sdkAppId:n}=t;e.map.has(r)?e.map.get(r).logs.push(i):e.map.set(r,{userId:r,sdkAppId:n,logs:[i]})}));else if(ww(i.userId)&&Ow(i.sdkAppId)){let{userId:t,sdkAppId:r}=i;e.map.has(t)?e.map.get(t).logs.push(i):e.map.set(t,{userId:t,sdkAppId:r,logs:[i]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e}upload(){return ib(this,null,(function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;e<t.length;e++){let{userId:i,sdkAppId:r,logs:n}=t[e];yield this.uploadLogWithRetry(JSON.stringify({timestamp:Eb(),sdkAppId:String(r),userId:i,version:Ib,log:n.map((e=>e.log)).join("\n")}),r),n.forEach((e=>e.uploaded=!0))}}catch(Cb){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return YN({retryFunction:()=>iD({url:hw(t,jb.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(Gb[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){Nw(Gb[e])||(this._logLevel!==e&&this.info("setLogLevel",e),this._logLevel=e)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(e){if(ww(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(Rb){return""}}log(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;var o;t.unshift(this.getPrefix(e));let s={log:t.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:e,userId:r,sdkAppId:n,forAllJoinedClients:i};if(QN.emit(fO.LOG,{log:s}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(s),e<this._logLevel)return;let a=(null==(o=Gb[e])?void 0:o.toLowerCase())||"info";gO?console[a]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...t):console[a](...t)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}createLogger(e){return new _O(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Gb[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}},EO=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)}))},vO=new class{constructor(){eb(this,"_prefix","TRTC"),eb(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){PN()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix)){let t=localStorage.getItem(e);if(!t)return!1;let i=JSON.parse(t);if(i&&i.expiresIn<Date.now())return!0}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(PN())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(xP){TO.warn(xP)}}getItem(e){if(!PN())return null;try{let t=localStorage.getItem(this.getRealKey(e));if(!t)return null;let i=JSON.parse(t);return i&&i.expiresIn>=Date.now()?i.value:null}catch(Rb){TO.warn(Rb)}}setItem(e,t){if(PN())try{let i={expiresIn:Date.now()+qb,value:t};this._queue.set(this.getRealKey(e),i)}catch(Rk){TO.warn(Rk)}}deleteItem(e){if(!PN())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(Rb){return TO.warn(Rb),!1}}clear(){if(PN())try{localStorage.clear()}catch(xP){TO.warn(xP)}}},yO={};XC(yO,{HTTPS_API:()=>UO,IS_GET_CAPABILITIES_SUPPORTED:()=>tP,IS_GET_SETTINGS_SUPPORTED:()=>eP,IS_INSERTABLE_STREAM_SUPPORTED:()=>iP,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>rP,IS_SEI_SUPPORTED:()=>nP,IS_SPC_SUPPORTED:()=>QO,basis:()=>lP,checkSystemRequirementsInternal:()=>MO,decodeSupportStatus:()=>PO,encodeSupportStatus:()=>OO,getBrowserInfo:()=>RO,getDisplayResolution:()=>BO,isAddTransceiverSupported:()=>YO,isBrowserSupported:()=>CO,isGetReceiversSupported:()=>zO,isGetSendersSupported:()=>KO,isGetTransceiversSupported:()=>qO,isGetUserMediaSupported:()=>HO,isMediaDevicesSupported:()=>kO,isMediaSessionSupported:()=>aP,isMediaStreamTrackProcessorSupported:()=>wO,isReplaceTrackSupported:()=>$O,isScreenCaptureApiAvailable:()=>xO,isSelectedCandidatePair:()=>FO,isSetParametersSupported:()=>ZO,isSmallStreamAPISupported:()=>WO,isSmallStreamSupported:()=>GO,isStopTransceiverSupported:()=>XO,isTRTCSupported:()=>LO,isUnifiedPlanDefault:()=>JO,isUsedInHttpProtocol:()=>NO,isWebAudioSupported:()=>jO,isWebCodecSupported:()=>sP,isWebCodecsSupported:()=>bO,isWebRTCSupported:()=>oP,isWebTransportSupported:()=>cP});var SO=$C(ab(),1),IO={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},AO=new Map([[ID,["Firefox",AD]],[kD,["Edg",DD]],[EN,["Chrome",SN]],[IN,["Safari",RN]],[LD,["TBS",xD]],[VD,["XWEB",UD]],[jD&&fD,["WeChat",WD]],[KD,["QQ(Win)",qD]],[JD,["QQ(Mobile)",zD]],[GD,["QQ(Mobile X5)",zD]],[YD,["QQ(Mac)",QD]],[XD,["QQ(iPad)",$D]],[sN,["MI",aN]],[cN,["HW",dN]],[uN,["Samsung",hN]],[pN,["OPPO",mN]],[_N,["VIVO",fN]],[CD,["EDGE",bD]],[wD,["SogouMobile",OD]],[PD,["Sogou",MD]]]);function RO(){let e=AO.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var CO=function(){return!(nN||CD||kD&&ND<80||ID&&RD<56)},bO=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},kO=function(){if(!navigator.mediaDevices)return NO()||TO.error(sD.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},DO=!1;function NO(){return"http:"===location.protocol&&!ON&&(DO||TO.error(KN({key:oD.NOT_SUPPORTED_HTTP})),DO=!0,!0)}var wO=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},OO=function(){return ib(this,null,(function*(){if(IO.detail.isH264EncodeSupported&&IO.detail.isVp8EncodeSupported)return{isH264EncodeSupported:IO.detail.isH264EncodeSupported,isVp8EncodeSupported:IO.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection,n=document.createElement(Zb.CANVAS);n.getContext("2d");let o=n.captureStream(0);return r.addTrack(o.getVideoTracks()[0],o),e=yield r.createOffer(),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),IO.detail.isH264EncodeSupported=t,IO.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:IO.detail.isH264EncodeSupported,isVp8EncodeSupported:IO.detail.isVp8EncodeSupported}}catch(Rk){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},PO=function(){return ib(this,null,(function*(){if(IO.detail.isH264DecodeSupported&&IO.detail.isVp8DecodeSupported)return{isH264DecodeSupported:IO.detail.isH264DecodeSupported,isVp8DecodeSupported:IO.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection;return e=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch(Rk){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},MO=uO((()=>ib(void 0,null,(function*(){if(IO.result&&IO.detail.isH264EncodeSupported&&IO.detail.isVp8EncodeSupported&&IO.detail.isH264DecodeSupported&&IO.detail.isVp8DecodeSupported)return IO;let e=CO(),t=oP(),i=bO(),r=kO(),{isH264EncodeSupported:n,isVp8EncodeSupported:o}=yield OO(),{isH264DecodeSupported:s,isVp8DecodeSupported:a}=yield PO();if(!n||!o){let e=yield OO();TO.warn("detect encode again h264:".concat(n," vp8:").concat(o," result: ").concat(JSON.stringify(e))),n=e.isH264EncodeSupported,o=e.isVp8EncodeSupported}if(n&&s&&(pN||_N||CN)&&!LD&&gN()<79){let{encode:e,decode:t}=yield function(){return ib(this,null,(function*(){return VO||(VO=new Promise((e=>ib(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{TO.warn("detectH264Supported start");let r=document.createElement("canvas"),n=r.getContext("2d");r.width=320,r.height=240;let o=setInterval((()=>{n.fillText("test",Math.floor(320*Math.random()),Math.floor(240*Math.random()))}),66),s=-1,a=-1;i=()=>{clearInterval(s),clearInterval(o),clearTimeout(a),l.close(),d.close(),c.getTracks().forEach((e=>e.stop()))},a=setTimeout((()=>{i(),e(t)}),2e3);let c=r.captureStream(),l=new RTCPeerConnection({}),d=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",(e=>d.addIceCandidate(e.candidate))),d.addEventListener("icecandidate",(e=>l.addIceCandidate(e.candidate))),l.addTrack(c.getVideoTracks()[0],c);let u=yield l.createOffer();yield l.setLocalDescription(u),yield d.setRemoteDescription(u);let h=yield d.createAnswer(),p=SO.default.parse(h.sdp),m=p.media[0].rtp.findIndex((e=>"H264"===e.codec));p.media[0].rtp=[p.media[0].rtp[m]],p.media[0].fmtp=p.media[0].fmtp.filter((e=>e.payload===p.media[0].rtp[0].payload)),p.media[0].rtcpFb&&(p.media[0].rtcpFb=p.media[0].rtcpFb.filter((e=>e.payload===p.media[0].rtp[0].payload))),h.sdp=SO.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval((()=>ib(this,null,(function*(){t.encode&&t.decode&&(i(),e(t));let r=yield l.getSenders()[0].getStats(),n=yield d.getReceivers()[0].getStats();t.encode||r.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===Zb.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===Zb.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(r){i(),TO.warn(r),e(t)}})))).then((e=>((!e.encode||!e.decode)&&TO.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(VN)),e))),VO)}))}();n=e,s=t}return IO.result=e&&t&&r&&(n||o)&&(s||a),IO.detail.isBrowserSupported=e,IO.detail.isWebRTCSupported=t,IO.detail.isWebCodecsSupported=i,IO.detail.isMediaDevicesSupported=r,IO.detail.isScreenShareSupported=xO(),IO.detail.isSmallStreamSupported=GO(),IO.detail.isH264EncodeSupported=n,IO.detail.isVp8EncodeSupported=o,IO.detail.isH264DecodeSupported=s,IO.detail.isVp8DecodeSupported=a,IO.result||TO.error("".concat(navigator.userAgent," ").concat(nO(IO.detail,!1))),vO.setItem(dP,{ua:navigator.userAgent,checkResult:IO}),IO})))),LO=function(){return IO.result},xO=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},VO=null;var UO=(e,t,i)=>{"http:"===location.protocol&&!ON&&(e[t]=()=>{throw new fb({code:mb.INVALID_OPERATION,message:sD.NOT_SUPPORTED_HTTP})})},FO=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(Pw(e.selected)&&!e.selected)};function BO(){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 HO(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function jO(){let e={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let i=0;i<t.length;i++)if(t[i]in window){e.isSupported=!0;break}return e.isSupported}function WO(){return"captureStream"in HTMLCanvasElement.prototype}function GO(){return!(jD||TD||yN&&yN<63)&&!(!CO()||!WO())}var JO=function(){if(Nw(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:wk}),e.addTransceiver(Zb.AUDIO),t=!0}catch(Rb){}return null==e||e.close(),t};function zO(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function KO(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function qO(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function YO(){return 11!==kN&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var QO=!(!YO()||TN&&yN<86);function XO(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function $O(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function ZO(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&KO()}var eP=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,tP=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,iP="createEncodedStreams"in window.RTCRtpSender.prototype&&gN()>=86,rP="RTCRtpScriptTransform"in window,nP="RTCRtpSender"in window&&(iP||rP),oP=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function sP(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return Nw(window.AudioDecoder)||(e.AudioDecoder=!0),Nw(window.AudioEncoder)||(e.AudioEncoder=!0),Nw(window.VideoDecoder)||(e.VideoDecoder=!0),Nw(window.VideoEncoder)||(e.VideoEncoder=!0),Nw(window.ImageDecoder)||(e.ImageDecoder=!0),e}function aP(){return"mediaSession"in navigator&&!Nw(navigator.mediaSession.setActionHandler)}function cP(){return!Nw(window.WebTransport)}function lP(){let e={browser:"".concat(MN.name,"/").concat(MN.version),os:HN(),displayResolution:BO(),isScreenShareSupported:xO(),isWebRTCSupported:oP(),isGetUserMediaSupported:HO(),isWebAudioSupported:jO(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:sP(),isMediaSessionSupported:aP(),isWebTransportSupported:cP()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var dP="checkResult";!function(){NO();let e=vO.getItem(dP);e&&e.ua===navigator.userAgent&&(IO=e.checkResult),MO()}();var uP=$C(rb(),1),hP=Symbol("instance"),pP=Symbol("cacheResult"),mP=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,EP.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},_P=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var fP=new Map;function gP(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,n,o)=>{let s=i.action||n;if(!i.context){let i=fP.get(r)||[];fP.has(r)||fP.set(r,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let r=this;for(var n=arguments.length,o=new Array(n),c=0;c<n;c++)o[c]=arguments[c];if(i.context&&(r=vP.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return i.sync?r[pP]:Promise.resolve(r[pP]);r.state instanceof mP&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof mP&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new _P(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e.join("|")))):e!==r.state&&(l=new _P(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e)));let d=e=>{if(i.fail&&i.fail.call(this,e),i.sync){if(i.ignoreError)return e;throw e}return i.ignoreError?Promise.resolve(e):Promise.reject(e)};if(l)return d(l);let u=r.state,h=new mP(u,t,s);EP.call(r,h);let p=e=>{var n;return r[pP]=e,h.aborted||(EP.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[pP])),e},m=e=>{let t=e instanceof Error?e.message:String(e);return EP.call(r,u,e),d(new _P(r._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(p).catch(m):i.sync?p(e):Promise.resolve(p(e))}catch(_){return m(_)}}}}var TP="undefined"!=typeof window&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:"undefined"!=typeof importScripts?(e,t)=>{postMessage({type:e,payload:t})}:()=>{};function EP(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(vP.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var vP=class extends uP.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=vP.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let r=i[hP];r?this.name=r.name+"-"+r.count++:i[hP]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=fP.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);fP.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?r.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:o})})):n.push({to:i,action:o})})),r.forEach((e=>{let{from:t,to:r,action:n}=e;o.add(t),o.add(r),o.add(n+"ing"),i.add("".concat(t," --\x3e ").concat(n,"ing : ").concat(n)),i.add("".concat(n,"ing --\x3e ").concat(r," : ").concat(n," 🟢")),i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🔴"))})),n.forEach((e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=vP.instances.get(e),t||vP.instances.set(e,t=new vP(e,void 0,Object.create(vP.prototype)))):(t=vP.instances2.get(e),t||vP.instances2.set(e,t=new vP(e.constructor.name,void 0,Object.create(vP.prototype)))),t}static getState(e){var t;return null===(t=vP.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};TP(vP.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){EP.call(this,e)}};vP.STATECHANGED="stateChanged",vP.UPDATEAFSM="updateAFSM",vP.INIT="[*]",vP.ON="on",vP.OFF="off",vP.instances=new Map,vP.instances2=new WeakMap;var yP=(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)},SP=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},IP=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),AP=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eD,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=qC(e===Zk?{delay:2e3,count:0,backgroundTask:!0}:e===Xk?{delay:1e4,count:0}:e===$k?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),Mw(t)&&(i=qC(qC({},i),t)),Dw(e)&&(t=e,e=eD);let r=qC({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i);return this.taskMap.set(r.taskID,r),this[e](r),r.taskID}static interval(e){return e.intervalID=setInterval((()=>{e.callback(),e.loopCount+=1,this.isBreakLoop(e)}),e.delay)}static intervalInWorker(e){e.delay=(1e3/e.fps).toFixed(2);let t=new Worker(URL.createObjectURL(new Blob(["\n let timerID = null;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timerID = setInterval(() => {\n self.postMessage('tick');\n }, ".concat(e.delay,");\n } else if (e.data === 'stop') {\n clearInterval(timerID);\n }\n };\n ")],{type:"application/javascript"})));t.onmessage=i=>{"tick"===i.data&&(e.callback(),e.loopCount+=1,this.isBreakLoop(e)&&t.postMessage("stop"))},e.worker=t,t.postMessage("start")}static timeout(e){let t=()=>{if(e.callback(),e.loopCount+=1,!this.isBreakLoop(e))return e.timeoutID=setTimeout(t,e.delay)};return e.timeoutID=setTimeout(t,e.delay)}static ric(e){let t,i=Ww(),r=()=>{if(t=Ww()-i,t>=e.delay&&(i=Ww()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=yP(r,{timeout:e.delay})};return e.ricID=yP(r,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=Ww(),r=()=>document.hidden&&e.backgroundTask?(t=Ww()-i,i=Ww(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(r,e.delay-Math.floor(t%e.delay))):(t=Ww()-i,t>=e.delay&&(i=Ww()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),this.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(r));if(e.rafID=requestAnimationFrame(r),e.backgroundTask){let t=()=>{if(document.hidden){let t=Ww()-i;t>=e.delay?r():e.timeoutID=setTimeout(r,e.delay-t)}};document.addEventListener("visibilitychange",t),e.onVisibilitychange=t,document.hidden&&t()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:t,timeoutID:i,rafID:r,ricID:n,onVisibilitychange:o,worker:s}=this.taskMap.get(e);return s&&s.terminate(),t&&clearInterval(t),i&&clearTimeout(i),r&&IP(r),n&&SP(n),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.taskMap.has(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};AP.taskMap=new Map,AP.currentTaskID=1;var RP=AP;Zb.SEI_MESSAGE;var CP={LOADED_DATA:Zb.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},bP={};XC(bP,{create:()=>DP,remove:()=>NP});var kP=new WeakMap;function DP(e,t){kP.has(e)||kP.set(e,[]);let i=kP.get(e),r={add:(e,n)=>("addEventListener"in t?(i.push(t.removeEventListener.bind(t,e,n)),t.addEventListener(e,n)):(i.push(t.off.bind(t,e,n)),t.on(e,n)),r)};return r}function NP(e){let t=kP.get(e);t&&(t.forEach((e=>e())),kP.delete(e))}var wP=new WeakMap;function OP(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,s){let a=YN({retryFunction:s.value,settings:t,onError(t){let{error:r,retry:n,reject:s,retryFuncArgs:a}=t;var c;i?i.call(this,r,(()=>{var t;null!=(t=wP.get(e))&&t.has(o)?n():s(r)}),s,a):null!=(c=wP.get(e))&&c.has(o)?n():s(r)},onRetrying(t,i){var n;Dw(r)&&r.call(this,t,i),null!=(n=wP.get(e))&&n.has(o)&&(wP.get(e).get(o).stopRetry=i)},onRetryFailed:n});return s.value=function(){let t=wP.get(e);for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return t?t.set(o,{args:r}):wP.set(e,new Map([[o,{args:r}]])),a.apply(this,r).finally((()=>{var t;return null==(t=wP.get(e))?void 0:t.delete(o)}))},s}}function PP(e){let{fnName:t,callback:i,validateArgs:r=!0}=e;return function(e,n,o){let s=o.value;return o.value=function(){for(var n,o,a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(null!=(n=wP.get(e))&&n.has(t)){let{stopRetry:n,args:s}=wP.get(e).get(t),a=!0;if(r)for(let e of s)if(!c.find((t=>t===e))){a=!1;break}a&&(i&&i.apply(this,c),n&&n(),null==(o=wP.get(e))||o.delete(t))}return s.apply(this,c)},o}}var MP,LP,xP,VP=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.countMap=new Map,this.distributionMap=new Map,this.log=TO.createLogger({id:"kv"}),e&&(QN.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===Zb.AUDIO?jP.START_MICROPHONE:WP.START_CAMERA,cost:i})})),QN.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===Zb.AUDIO?jP.START_MICROPHONE:WP.START_CAMERA,error:i})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:cO(this.version||Ib),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,uint32_count:i}})),stats_distribution:[...this.distributionMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,distribution_items:[...i.entries()].map((e=>{let[t,i]=e;return{uint32_item_key:t,uint32_item_value:i}}))}}))};return this.countMap.clear(),this.distributionMap.clear(),e}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){let t=+String(e).slice(-3);return t>=700&&t<799}isErrorCodeKey(e){let t=+String(e).slice(-3);return t>=600&&t<699}isCountKey(e){let t=+String(e).slice(-3);return t>=0&&t<599}isNumberKey(e){let t=+String(e).slice(-3);return t>=800&&t<899}addCount(e){let{key:t,useUV:i=!1}=e;this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}addEnum(e){let{key:t,value:i,useUV:r=!0}=e;var n;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=(null==(n=this.distributionMap)?void 0:n.get(t))||new Map;o.set(i,(o.get(i)||0)+1),this.distributionMap.set(t,o)}addNumber(e){let{key:t,value:i,split:r=100,useUV:n=!1}=e;var o;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(n&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=(null==(o=this.distributionMap)?void 0:o.get(t))||new Map,a=0;if(Ow(r))a=Math.floor(i/r);else for(let c=r.length-1;c>0;c--)if(i>r[c]){a=c;break}s.set(a,(s.get(a)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent(e){let{key:t,cost:i,timeKey:r,split:n}=e;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),i)){let e=+String(t).slice(-3);e<800&&e>=700?this.addNumber({key:r||t+100,value:i,split:n}):r||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:i}=e;if(!t)return;let r=mb.UNKNOWN;i&&(Ow(i)?r=i:(!Nw(i.extraCode)||!Nw(i.code))&&(r=i.extraCode||i.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:r,useUV:!1})}},UP=((LP=UP||{})[LP.enterRoom=500700]="enterRoom",LP[LP.exitRoom=500701]="exitRoom",LP[LP.switchRole=500702]="switchRole",LP[LP.destroy=500703]="destroy",LP[LP.startLocalAudio=500704]="startLocalAudio",LP[LP.updateLocalAudio=500705]="updateLocalAudio",LP[LP.stopLocalAudio=500706]="stopLocalAudio",LP[LP.startLocalVideo=500707]="startLocalVideo",LP[LP.updateLocalVideo=500708]="updateLocalVideo",LP[LP.stopLocalVideo=500709]="stopLocalVideo",LP[LP.startScreenShare=500710]="startScreenShare",LP[LP.updateScreenShare=500711]="updateScreenShare",LP[LP.stopScreenShare=500712]="stopScreenShare",LP[LP.startRemoteVideo=500713]="startRemoteVideo",LP[LP.updateRemoteVideo=500714]="updateRemoteVideo",LP[LP.stopRemoteVideo=500715]="stopRemoteVideo",LP[LP.muteRemoteAudio=500716]="muteRemoteAudio",LP[LP.setRemoteAudioVolume=500717]="setRemoteAudioVolume",LP[LP.use=500718]="use",LP[LP.sendSEIMessage=5e5]="sendSEIMessage",LP[LP.sendCustomMessage=500001]="sendCustomMessage",LP),FP=((MP=FP||{})[MP.AudioMixer=550700]="AudioMixer",MP[MP.AIDenoiser=551700]="AIDenoiser",MP[MP.VirtualBackground=570700]="VirtualBackground",MP[MP.Beauty=571700]="Beauty",MP[MP.Watermark=572700]="Watermark",MP[MP.BasicBeauty=574700]="BasicBeauty",MP[MP.CDNStreaming=590700]="CDNStreaming",MP[MP.DeviceDetector=591700]="DeviceDetector",MP[MP.Debug=592700]="Debug",MP),BP=(e=>(e[e.AudioMixer=550701]="AudioMixer",e[e.AIDenoiser=551701]="AIDenoiser",e[e.VirtualBackground=570701]="VirtualBackground",e[e.Beauty=571701]="Beauty",e[e.Watermark=572701]="Watermark",e[e.BasicBeauty=574701]="BasicBeauty",e[e.CDNStreaming=590701]="CDNStreaming",e[e.DeviceDetector=591701]="DeviceDetector",e[e.Debug=592701]="Debug",e))(BP||{}),HP=(e=>(e[e.AudioMixer=550702]="AudioMixer",e[e.AIDenoiser=551702]="AIDenoiser",e[e.VirtualBackground=570702]="VirtualBackground",e[e.Beauty=571702]="Beauty",e[e.Watermark=572702]="Watermark",e[e.BasicBeauty=574702]="BasicBeauty",e[e.CDNStreaming=590702]="CDNStreaming",e[e.DeviceDetector=591702]="DeviceDetector",e[e.Debug=592702]="Debug",e))(HP||{}),jP=(e=>(e[e.START_MICROPHONE=501700]="START_MICROPHONE",e[e.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",e[e.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",e))(jP||{}),WP=((xP=WP||{})[xP.START_CAMERA=511700]="START_CAMERA",xP),GP=new VP(!0),JP=new VP(!1),zP=GP,KP=class extends vP{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,eb(this,"id"),eb(this,"element",null),eb(this,"track"),eb(this,"url"),eb(this,"attr"),eb(this,"muted"),eb(this,"_log"),eb(this,"_pausedRetryCount"),eb(this,"_isElementPlayingFired",!1),eb(this,"_interval"),eb(this,"_delayDestroyTimeoutId",0),eb(this,"_isReplayByRecreateMediaStreamIng",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Wk,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){var e;return"PLAYING"===this._state&&!1===(null==(e=this.element)?void 0:e.paused)}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,null!==e&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return ib(this,null,(function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield this.element.play()}catch(Rb){let t=KN({key:oD.PLAY_FAILED,data:{media:this.kind,error:Rb}});if(this.track&&!this.track.muted&&this._log.warn(Rb),t.includes("NotAllowedError"))throw new fb({code:mb.PLAY_NOT_ALLOWED,message:t})}}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this._isElementPlayingFired=!1,this.unbindEvents(),e>0?this._delayDestroyTimeoutId||(this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout((()=>this.destroyElement()),3*e)):this.destroyElement(),this.handleStopped(Zb.ENDED),this._interval>0&&RP.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():NN?this.replay():this.play().catch((()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch((()=>{}))}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return DP(this.element,this.element).add(Zb.PLAYING,e).add(Zb.ENDED,e).add(Zb.PAUSE,e).add(Zb.ERROR,e).add(Zb.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==bP||bP.create(this.track,this.track).add(Zb.ENDED,e).add(Zb.MUTE,e).add(Zb.UNMUTE,e),this.track.readyState===Zb.ENDED&&this.handleTrackEvent({type:Zb.ENDED}),this.track.muted&&this.handleTrackEvent({type:Zb.MUTE})}}bindAutoPlayEvent(){QN.on(fO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&NP(this.track)}unbindEvents(){this.element&&NP(this.element),this.unbindTrackEvents(),QN.off(fO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case Zb.PLAYING:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(Zb.PLAYING),this._interval&&(RP.clearTask(this._interval),this._interval=-1);break;case Zb.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(Zb.ENDED);break;case Zb.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(Zb.PAUSE),TD&&(this._interval=RP.run(eD,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case Zb.ERROR:if(this.element&&this.element.error){this.handlePaused(Zb.ERROR);let{code:e,message:t}=this.element.error;this._log.error("".concat(this.kind," ").concat(this._log.isLocal?"local":"remote"," MediaError code: ").concat(e," message: ").concat(t," userAgent: ").concat(navigator.userAgent)),$N.uploadEvent({log:"stat-".concat(this.kind,"-").concat(bk.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),this.replayByRecreateMediaStream()}break;case Zb.LOADEDDATA:this.kind===Zb.VIDEO&&this.emit(CP.LOADED_DATA)}}replayByRecreateMediaStream(){if(!this._isReplayByRecreateMediaStreamIng)return this._isReplayByRecreateMediaStreamIng=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),$N.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),zP.addSuccessEvent({key:this.kind===Zb.AUDIO?506700:516700})})).catch((()=>{var e,t;this._log.error("replayByRecreateMediaStream failed"),$N.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),zP.addFailedEvent({key:this.kind===Zb.AUDIO?506700:516700,error:null==(e=this.element)?void 0:e.error}),null!=(t=this.element)&&t.error&&this.emit(CP.ERROR,this.element.error)})).finally((()=>{this._isReplayByRecreateMediaStreamIng=!1}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,i)=>{dO(e).then((()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var e,t,r;this._log.warn("element onerror ".concat(null==(t=null==(e=this.element)?void 0:e.error)?void 0:t.code," fired after recreated mediaStream")),i(null==(r=this.element)?void 0:r.error)}),dO(5e3).then((()=>{var e,r;(!this.isPlaying||(null==(e=this.element)?void 0:e.error))&&i(null==(r=this.element)?void 0:r.error),t()}))}))})).finally((()=>{this.element&&(this.element.onerror=null)}))}handleTrackEvent(e){switch(e.type){case Zb.ENDED:this.handleStopped(Zb.ENDED);break;case Zb.MUTE:this.handlePaused(Zb.MUTE);break;case Zb.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(Zb.UNMUTE)}}handlePlaying(e){this.emit(CP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(CP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(CP.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};ZC([OP({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],KP.prototype,"doReplayByRecreateMediaStream",1),ZC([gP([],"PLAYING",{sync:!0})],KP.prototype,"handlePlaying",1),ZC([gP("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],KP.prototype,"handlePaused",1),ZC([gP([],"STOPPED",{sync:!0})],KP.prototype,"handleStopped",1);var qP="trtc_autoplay",YP="".concat(qP,"_mask"),QP="".concat(qP,"_wrapper"),XP="".concat(qP,"_header"),$P="".concat(qP,"_content"),ZP="".concat(qP,"_action_wrapper"),eM="".concat(qP,"_question"),tM="".concat(qP,"_collapse"),iM="".concat(qP,"_action_confirm"),rM="".concat(qP,"_detail"),nM="#2473E8",oM="dialog",sM="".concat(oM,"-show"),aM="".concat(oM,"-1"),cM="".concat(oM,"-2"),lM=!1,dM=()=>!!document.querySelector(".".concat(QP)),uM="".concat(Vb,"/").concat(Aw()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),hM="<br><a href='".concat(uM,"' target='_blank'>").concat(Aw()?"其他方案?":"Any other solution?","</a>"),pM="".concat(Aw()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(hM):"Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ".concat(hM)),mM=class{constructor(){if(eb(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),eb(this,"_dialogNode",null),eb(this,"_bodyPosition",""),eb(this,"_showDetail",!1),eb(this,"_isCollapseClicked",!1),eb(this,"_isQuestionClicked",!1),Aw()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!lM){let e=document.createElement("style");e.innerHTML=".".concat(YP,"{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(YP," div:not(.").concat(ZP,"){display:block !important;}.").concat(QP,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(QP," a{color:").concat(nM,";}.").concat(XP,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat($P,"{margin:8px 0;}.").concat(ZP,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(tM,"{margin-right:auto;cursor:pointer}.").concat(eM,"{height:100%;line-height:16px;cursor:pointer;}.").concat(iM,"{margin-left:8px;color:#fff;background:").concat(nM,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(iM,":hover{opacity:0.9;}.").concat(tM,",.").concat(iM,",.").concat($P,",.").concat(eM,"{font-size:14px;}@media screen and (max-width:750px){.").concat(QP,"{width:80vw;}}"),document.head.appendChild(e),lM=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(YP,"\"><div class='").concat(QP,"'><div class='").concat(XP,"'>").concat(location.host,"</div><div class='").concat($P,"'>").concat(this.content,"</div><div class='").concat(rM,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(pM,"</div><div class='").concat(ZP,"'></div></div></div>").trim();let t=document.createElement("button");t.className=iM,t.innerText=Aw()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=eM,i.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>\n <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>\n <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>\n </svg>\n ',i.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=tM,r.innerText="".concat(Aw()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(ZP));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){dM()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(QP)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",TO.info("show autoplay dialog"),$N.uploadEvent({log:sM}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){TO.warn("confirm clicked, try resume stream"),QN.emit(fO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(rM));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||$N.uploadEvent({log:aM}),this._isCollapseClicked=!0}onQuestionClick(){window.open(uM,"_blank"),this._isQuestionClicked||$N.uploadEvent({log:cM}),this._isQuestionClicked=!0}},_M=class extends KP{constructor(e){super(e,Zb.VIDEO),eb(this,"viewMirror",!1),eb(this,"objectFit"),eb(this,"container"),eb(this,"canvas"),this.container=e.container,this.canvas=e.canvas,Nw(e.viewMirror)||(this.viewMirror=e.viewMirror),Nw(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var e;let t=document.createElement(Zb.VIDEO);this.track&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(Zb.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(Zb.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){var t;super.handleElementEvent(e);let i=e.type;if(i===Zb.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id)),this._pausedRetryCount>0&&!dM()&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--)),this.viewMirror&&this.element){let e=this.element.style.transform;i===Zb.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):i===Zb.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}}setCanvas(e){var t,i;this.canvas!==e&&(null==(t=this.canvas)||t.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e,e&&(null==(i=this.container)||i.appendChild(e)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(t,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;super.stop(e),null==(t=this.canvas)||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(CP.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}};function fM(e,t){return ib(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),TO.info("worklet addModule success")}catch(Rb){throw TO.info("worklet addModule catch error. ".concat(Rb.message)),Rb}}))}"undefined"!=typeof window&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var gM=new window.AudioContext({sampleRate:48e3}),TM=()=>{"suspended"===gM.state?(gM.resume(),document.addEventListener("click",TM)):"interrupted"===gM.state?gM.resume():document.removeEventListener("click",TM)};document.addEventListener("click",TM),gM.onstatechange=()=>{TO.info("context state: ".concat(gM.state)),TM()};var EM=e=>gM,vM=class{constructor(){this.pre=new Set,this.next=new Set,this.connectedNodes=new Set,this._channelCount=1}get channelCount(){return this._channelCount}set channelCount(e){this._channelCount=e,this.node&&(this.node.channelCount=e),this.next.forEach((t=>t.channelCount=e))}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&(null==(e=this.context)||e.reduceMixWeight()),delete this.context}setNode(e){var t;if(!this.node)try{null==(t=this.context)||t.addMixWeight(),this.node=e,this.node.channelCountMode="explicit",this.node.channelCount=this._channelCount,this.preNodeReconnect(),this.reconnect(),zP.addSuccessEvent({key:502701})}catch(Rk){TO.error(Rk),zP.addFailedEvent({key:502701,error:Rk})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),zP.addSuccessEvent({key:502702})}catch(Rb){TO.error(Rb),zP.addFailedEvent({key:502702,error:Rb})}}preNodeReconnect(){this.pre.forEach((e=>{e.node?e.reconnect():e.preNodeReconnect()}))}connectNext(e){this.next.forEach((t=>e._connect(t.node)||t.connectNext(e)))}_connect(e){return!(!this.node||!e)&&(this.node.connect(e),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach((e=>{var t;return null==(t=this.node)?void 0:t.disconnect(e)})),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t.forEach((e=>{this.next.add(e),e.pre.add(this)})),this}},yM=class extends vM{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,this.dataArray=new Uint8Array(0)}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=0,i=0,r="M".concat(t,",").concat(i);for(let n=0;n<e.length;n++)i=e[n]/128*100/2,r+="L".concat(t,",").concat(i),t+=1;return r}},SM=class{constructor(){this.source=new vM,this.gain=new vM,this.destination=new vM}get volume(){var e;return(null==(e=this.gain.node)?void 0:e.gain.value)||1}setVolume(e){1!==e?(this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.deleteNode(),this.source.setNode(function(e){let t=RM.get(e);if(t)return t;let i=EM();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return RM.set(e,t),t}(e))}get track(){var e;return null==(e=this.stream)?void 0:e.getAudioTracks()[0]}get stream(){var e;return null==(e=this.destination.node)?void 0:e.stream}},IM=class extends SM{constructor(e){super(),this.context=e,this.denoiser=new vM,this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){!this.context.inputs.has(this)||(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){1!==e?(this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}},AM=class{constructor(){this.audioContext=EM(),this.destination=this.audioContext.createMediaStreamDestination(),this.inputs=new Set,this.mixWeight=0}addMixWeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.mixWeight+=e,this.mixWeight-1==e+1>>1&&this.mixOnChange()}reduceMixWeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.addMixWeight(-e)}close(){this.inputs.forEach((e=>e.remove()))}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},RM=new WeakMap;var CM=class{constructor(e){eb(this,"_volume",0),eb(this,"_log"),eb(this,"_scriptProcessorNode",null),eb(this,"_audioWorkletNode",null),eb(this,"_interval",200),eb(this,"ready",this.preload());let{log:t}=e;this._log=t,QN.on(fO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return CM.workletReady||(CM.workletReady=fM(CM.audioContext,URL.createObjectURL(new Blob(['\nclass VolumeMeter extends AudioWorkletProcessor{constructor(){super();this.volume=0;this.intervalTime=200;this.tick=this.intervalTime;this.isStop=false;this.cache=[];this.sentFirstInfo1=false;this.unmute=false;this.port.onmessage=(event)=>{const{data}=event;switch(data.name){case"chunk":this.cache.push.apply(this.cache,data.data);if(!this.sentFirstInfo1){this.port.postMessage({cl:data.data.length});this.sentFirstInfo1=true;}\nbreak;case"setIntervalTime":this.intervalTime=data.intervalTime;break;case"unmute":this.unmute=true;break;case"stop":this.isStop=true;break;}};}\nprocess(inputs,outputs){const input=inputs[0];const output=outputs[0];if(!input&&!output){return true;}\nif(this.isStop){return false;}\nconst l=output?output[0].length:0;const cl=this.cache.length;if(cl>l){output[0].set(this.cache.slice(0,l));this.cache=this.cache.slice(l);}else if(this.unmute){output[0].set(input[0]);}\nconst firstChannel=cl>l?output[0]:input[0];if(!firstChannel){return true;}\nlet sum=0;let rms;for(let i=0;i<firstChannel.length;++i){sum+=firstChannel[i]*firstChannel[i];}\nrms=Math.sqrt(sum/firstChannel.length);this.volume=Math.max(rms,this.volume*0.95);this.tick-=firstChannel.length;if(this.tick<0){this.tick+=(this.intervalTime/1000)*sampleRate;this.port.postMessage({volume:this.volume,cacheLen:cl,outputLen:l});}\nreturn true;}}\nregisterProcessor("volume-meter",VolumeMeter);\n'],{type:"application/javascript"})))),CM.workletReady.then((()=>this.initAudioWorklet())).catch((()=>this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(CM.audioContext,"volume-meter");let e=!1;this._audioWorkletNode.port.onmessage=t=>{this._volume=t.data.volume||0,!e&&t.data.cacheLen&&t.data.outputLen&&(this._log.warn("worklet play success"),e=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(xP){$N.logFailedEvent({userId:this._log.userId,eventType:bk.LOAD_WORKLET,error:xP}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=EM().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{let t=e.inputBuffer.getChannelData(0),i=0;for(let r=0;r<t.length;++r)i+=t[r]*t[r];this._volume=Math.sqrt(i/t.length)||0}}catch(xP){this._log.error("volumeMeter init script processor error: ".concat(xP))}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,QN.off(fO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(e){var t;let{interval:i}=e;this._interval=i,null==(t=this._audioWorkletNode)||t.port.postMessage({name:"setIntervalTime",intervalTime:i})}},bM=CM;eb(bM,"audioContext",EM()),eb(bM,"workletReady");var kM=class extends vM{constructor(e){super(),eb(this,"_volumeMeter"),this._volumeMeter=new bM(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return ib(this,null,(function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)}))}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),i=new Float32Array(t>>2);e.copyTo(i,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:i},[i.buffer]),e.close()}}},DM=$C(rb(),1),NM=e=>t=>t.deviceId===e,wM=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";eb(this,"kind"),eb(this,"type"),eb(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&&MM(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(NM(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");TO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(NM(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");TO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},OM=class extends DM.EventEmitter{constructor(){super(),eb(this,"audioInputs",new wM(Zb.AUDIO)),eb(this,"videoInputs",new wM(Zb.VIDEO)),eb(this,"audioOutputs",new wM(Zb.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||RP.run(Zk,(()=>{this.update()}),{delay:1e4}))}init(){LM().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield LM(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},PM=Db||kb?null:new OM;function MM(e){return e.deviceId===e.groupId&&""===e.groupId}function LM(){return ib(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(NO()||!kO())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{MM(e)&&(e.kind===Zb.AUDIO_INPUT?i.audio=!0:e.kind===Zb.VIDEO_INPUT&&(i.video=!0))})),2===e&&(i.audio=!1),1===e&&(i.video=!1),i.audio||i.video){let e;try{e=yield navigator.mediaDevices.getUserMedia(i)}catch(Cb){TO.debug("capture before getDevices failed: ",Cb)}t=yield navigator.mediaDevices.enumerateDevices(),null==e||e.getTracks().forEach((e=>e.stop()))}}return t.map(((e,t)=>{let i={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||"".concat(e.kind,"_").concat(t)};return e.deviceId.length>0&&BM.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function xM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return PM.update(e?1:0).then((e=>e.audioInputs.devices))}function VM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return PM.update(e?2:0).then((e=>e.videoInputs.devices))}var UM=!1;function FM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return ib(this,null,(function*(){return PM.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var BM=new Set;function HM(e,t){return ib(this,null,(function*(){let i=(yield xM()).find((e=>e.deviceId===Gk));return(null==i?void 0:i.groupId)===e&&i.label===t}))}var jM,WM=class extends SM{constructor(e){super(),this.log=e,eb(this,"volumeMeter"),eb(this,"volumeDestination"),eb(this,"analyser",new yM),this.volumeMeter=new kM({log:this.log}),this.volumeDestination=new vM,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},GM=class extends KP{constructor(e){super(e,Zb.AUDIO),eb(this,"_outputDeviceId"),eb(this,"_volume",1),eb(this,"_destination",EM().createMediaStreamDestination()),eb(this,"pipeline"),eb(this,"volumeMeterMode","worklet"),this.pipeline=new WM(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if(("15.2"===bN||"15.3"===bN||"15.4"===bN)&&this.muted)return void this._log.info("audioElement is muted.");let e=jM||new Audio;e.setAttribute("autoplay","autoplay"),e.srcObject=this.getMediaStream(),e.muted=this.muted,this.element=e,e===jM&&(jM=void 0),this.bindElementEvents()}play(){return ib(this,null,(function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(EM().createAnalyser()),this.setVolume(this._volume),function(){ib(this,null,(function*(){try{UM||(UM=!0,TO.info("speakers:".concat((yield FM()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(WF){}}))}(),tb(GM.prototype,this,"play").call(this)}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destory(),super.stop(e)}setSinkId(e){return ib(this,null,(function*(){var t,i;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield null==(i=(t=this.element).setSinkId)?void 0:i.call(t,e))}))}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},JM=class extends GM{constructor(e){super(e),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(e){var t;this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(CP.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this.pipeline.source.channelCount=(null==(t=e.getSettings())?void 0:t.channelCount)||1,this.pipeline.replaceSource(e),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e]))):this.pipeline.source.deleteNode())}setSourceNode(e){!e||this.pipeline.source.node===e||(this.pipeline.replaceSource(e),e instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch((()=>{})),this.setVolume(this._volume)))}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}},zM=class extends GM{constructor(e){super(e),eb(this,"_sourceElement"),this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,i,r;(null==(i=null==(t=this.element)?void 0:t.error)?void 0:i.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(CP.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=(null==(r=e.getSettings())?void 0:r.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?(this.element?this._log.info("set element volume: ".concat(e)):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),NP(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destory();let t=this._sourceElement||this.element;t&&AN&&(jM=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},KM=class extends vP{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:o=(1===r?zM:_M)}=e;var s;super(),eb(this,"id",EO()),eb(this,"userId",""),eb(this,"isRemote"),eb(this,"mediaType"),eb(this,"room"),eb(this,"user"),eb(this,"_log"),eb(this,"_inputTrack"),eb(this,"_outputTrack"),eb(this,"isPlayCalled"),eb(this,"container",null),eb(this,"player"),eb(this,"subVideoPlayerMap"),eb(this,"muted",!1),eb(this,"abortCtrl"),eb(this,"objectFit","cover"),eb(this,"mirror"),eb(this,"isScreen",!1),eb(this,"manager"),eb(this,"trackSettings"),eb(this,"onPlayerError"),this.userId=t||"",this.mediaType=r,this._log=TO.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=n||this.room)?void 0:s.userId,remoteUserId:this instanceof pL?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof pL}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(CP.PLAYER_STATE_CHANGED,(e=>{QN.emit(fO.PLAYER_STATE_CHANGED,qC({track:this},e)),this.emit("player-state-changed",e)})),this.kind===Zb.VIDEO&&(this.player.on(CP.LOADED_DATA,(()=>{QN.emit(fO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(CP.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))}))),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(CP.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||TO}get kind(){return 1===this.mediaType?Zb.AUDIO:Zb.VIDEO}get strMediaType(){return 4===this.mediaType?Zb.VIDEO:2===this.mediaType?Zb.SCREEN:Zb.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&(!this.mediaTrack.muted&&"live"===this.mediaTrack.readyState&&this.mediaTrack.enabled)}play(e,t){return ib(this,null,(function*(){let i=Lw(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!Nw(t.muted)&&this.setPlayerMute(t.muted),t&&!Nw(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof _M&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),Lw(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!Nw(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===Zb.VIDEO)&&this.setPlayerMute(!0),t&&!Nw(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof _M&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof _M&&this.player.setContainer(i)),QN.emit(fO.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(),Lw(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(r){throw this.handleAutoPlayFailed(),this.emit("error",r),r}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==Zb.VIDEO||Nw(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(Pw(this.mirror))return i.setViewMirror(this.mirror),void(r&&(r.mirror=!1));switch(this.mirror){case"view":r&&(r.mirror=!1),i.setViewMirror(!0);break;case"publish":r&&(r.mirror=!0),i.setViewMirror(!0);break;case"both":r&&(r.mirror=!0),i.setViewMirror(!1)}}playSubContainer(e,t){return ib(this,null,(function*(){if(!this._outputTrack||this.kind===Zb.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,i)=>{var r;e.find((e=>i===e))||(t.stop(),null==(r=this.subVideoPlayerMap)||r.delete(i))}));for(let[r,n]of e.entries()){let e=this.subVideoPlayerMap.get(n);e?t&&(Nw(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new _M({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(r+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let e of i)e.setViewMirror(this.player.mirror),yield e.play()}))}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return(null==(e=this.player)?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(Vw(this)?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return ib(this,null,(function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),QN.emit(e?fO.TRACK_MUTED:fO.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){DP(e,e).add(Zb.MUTE,this.onTrackMuted).add(Zb.UNMUTE,this.onTrackUnmuted).add(Zb.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Zb.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){NP(e)}setInputMediaStreamTrack(e){var t;let i=this._inputTrack;if(e!==i)return this._inputTrack=e,this.trackSettings=null==(t=e.getSettings)?void 0:t.call(e),e.enabled=!this.muted,i&&this.uninstallTrackEvent(i),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,i||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(t=e.getSettings)?void 0:t.call(e).deviceId,e.label),this._outputTrack=e,this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled)if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch((()=>this.handleAutoPlayFailed())),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(Vw(this)?this.jitterBufferDelay:0),void this.log.info("playing state updated, stop ".concat(this.kind));this.log.debug("updatePlayingState abort ".concat(this.isPlayCalled," ").concat(e," ").concat(this.player.isStopped))}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new mM;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof _M?this.player.getVideoFrame():""}onTrackMuted(){this._log.warn("".concat(this.kind," track is unable to provide media output"))}onTrackUnmuted(){this._log.info("".concat(this.kind," track is able to provide media output"))}onTrackEnded(){this._log.warn("".concat(this.kind," track ended"))}};ZC([gP([],vP.INIT,{sync:!0})],KM.prototype,"close",1);var qM=Object.prototype.hasOwnProperty;var YM=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(Rw(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(qM.call(e,t))return!1;return!0}return!1},QM=YN({retryFunction:function(e){return ib(this,null,(function*(){let t=function(e){return{audio:$M(e),video:ZM(e)}}(e);TO.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId"];t.audio&&(i=yield xM(),TO.info("microphones: ".concat(rO(i,{keysToInclude:n})))),t.video&&(r=yield VM(),TO.info("cameras: ".concat(rO(r,{keysToInclude:n}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return tP&&e.getTracks().forEach((e=>{TO.info("".concat(e.kind," capabilities: ").concat(rO(e.getCapabilities(),{keysToInclude:tD})))})),e}catch(o){let{message:t}=o;throw"NotFoundError"===o.name&&(e.video&&r&&0===r.length&&(t=KN({key:oD.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(t=KN({key:oD.MICROPHONE_NOT_FOUND}))),new fb({code:mb.INITIALIZE_FAILED,name:o.name,message:t,constraint:o.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,retryFuncArgs:n,retriedCount:o}=e,s=o+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===s?n[0].video&&(n[0].maxResolution=!1,(!IN||n[0].width*n[0].height<=2073600)&&n[0].frameRate&&(n[0].frameRate=n[0].frameRate>10?10:5)):2===s?n[0].useDeviceIdOnly=!0:3===s&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&XM(n[0].microphoneId,!1),n[0].cameraId&&XM(n[0].cameraId,!0)},onRetrying:e=>{TO.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{$N.logFailedEvent({eventType:bk.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{$N.logSuccessEvent({eventType:bk.GET_USER_MEDIA_RETRY}),$N.uploadEvent({log:"stat-".concat(bk.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function XM(e,t){return ib(this,null,(function*(){let i=(t?yield VM():yield xM()).find((t=>t.deviceId===e));i&&Dw(i.getCapabilities)&&TO.warn(rO(i.getCapabilities(),{keysToInclude:tD}))}))}function $M(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!YM(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(Ow(e.channelCount)&&(t.channelCount=e.channelCount),Pw(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),Pw(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),Pw(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!YM(t)||t)}function ZM(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&&!YM(i)?i:(e.width&&(i.width={ideal:e.width},t&&!ID&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!ID&&(i.height.max=e.height)),ID&&eN&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!YM(i)||i)}var eL=QM;function tL(e){return rL(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return ib(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function iL(e){return rL(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return ib(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function rL(e){return function(t,i,r){return r.value=e(r.value,i),r}}var nL=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&TO.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{TO.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),oL=0,sL=class{constructor(){this.log=TO.createLogger({id:"fq".concat(++oL)}),this.isRunning=!1,this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return 0===this.length?null:this.queue[this.length-1]}push(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i,r;let n=qC({},e),o=new Promise(((e,t)=>{n.resolve=e,n.reject=t}));return n.promise=o,t?this.length<=1?this.queue.push(n):null==(r=null==(i=this.lastQueueItem)?void 0:i.promise)||r.then(n.resolve,n.reject):this.queue.push(n),this.log.debug("push ".concat(this.length)),this.isRunning||this.callNext(),o}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length)),e}callNext(){if(this.isRunning||0===this.length)return;this.log.debug("callNext ",this.length);let{fn:e,args:t,context:i,resolve:r,reject:n}=this.queue[0];this.isRunning=!0,e.apply(i,t).then(r,n).finally((()=>{this.isRunning=!1,this.shift(),this.callNext()}))}},aL=new WeakMap,cL=new WeakMap;function lL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return function(t,i,r){let n=r.value;return r.value=function(){let t=aL.get(this)||new sL;for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return aL.set(this,t),t.push({fn:n,args:r,context:this},e)},r}}function dL(e){return function(t,i,r){let n=r.value;return r.value=function(){var t,i,r;let o=[];for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return null==(i=null==(t=aL.get(this))?void 0:t.queue)||i.forEach((e=>o.push(e))),null==(r=cL.get(this))||r.forEach((e=>null==e?void 0:e.queue.forEach((e=>o.push(e))))),o.forEach((t=>{t.reject(new fb({code:mb.API_CALL_ABORTED,message:e}))})),aL.delete(this),cL.delete(this),n.apply(this,a)},r}}function uL(e){return function(t,i,r){let n=r.value,o=t=>e(...t);return r.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=cL.get(this)||new Map,s=r.get(o(t))||new sL;return r.set(o(t),s),cL.set(this,r),s.push({fn:n,args:t,context:this})},r}}var hL=class extends KM{constructor(e,t){super({mediaType:e,PlayerClass:t}),eb(this,"isRemote",!1),eb(this,"deviceId"),eb(this,"groupId",""),eb(this,"label",""),eb(this,"_isRecapturing",!1),eb(this,"_lastRecaptureTime",0),eb(this,"_onMuteTimeoutId",-1),eb(this,"_encodeCheckTimeoutId",-1),eb(this,"profile")}get enableEncodeFrame(){return!1}get isPublished(){return"publish"===this.state}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){DP(e,e).add(Zb.MUTE,this.onTrackMuted).add(Zb.UNMUTE,this.onTrackUnmuted).add(Zb.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Zb.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){NP(e)}setStateToCapture(){}capture(e){return ib(this,null,(function*(){var t;try{let i,r=Ww();QN.emit(fO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield eL(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),QN.emit(fO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Ww()-r}),i}catch(Cb){throw QN.emit(fO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:Cb}),this.log.error("getUserMedia error observed ".concat(Cb)),Cb}}))}setInputMediaStreamTrack(e){return this.state===vP.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),null==(t=this.room)?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),QN.emit(fO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return ib(this,null,(function*(){if(this.mediaTrack&&eP){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return ib(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==Zb.AUDIO||t!==Gk||(yield HM(r,n)))}()}))}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=i,t&&(this.groupId=t),LM().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===Zb.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(Zb.AUDIO_INPUT);return!!BM.has(i)}(this.mediaTrack)||this.kind===Zb.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(Zb.VIDEO_INPUT);return!!BM.has(i)}(this.mediaTrack)||this._isRecapturing||e&&eN&&IN)}onTrackMuted(){if(super.onTrackMuted(),nL(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Qk)return void setTimeout((()=>this.onTrackMuted()),Qk);this._onMuteTimeoutId=setTimeout((()=>ib(this,null,(function*(){var e;if(null!=(e=this.mediaTrack)&&e.muted){if((TD||ED)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return ib(this,null,(function*(){if(tb(hL.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Qk)return void setTimeout((()=>this.onTrackEnded()),Qk);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return ib(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 xM():yield VM()).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}),QN.emit(fO.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),QN.emit(fO.LOCAL_TRACK_RECAPTURE,{track:this,error:e})}))}))}getRecoverCaptureDeviceId(){return ib(this,null,(function*(){let e=this instanceof TL;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(mL.get(t)||0)+1;if(mL.set(t,i),i>=3){let r=e?(yield VM()).find((e=>!mL.has(e.deviceId))):(yield xM()).find((e=>!mL.has(e.deviceId)));r&&(this.log.warn("".concat(t," capture fail ").concat(i," times, change new ").concat(r.deviceId)),t=r.deviceId)}}return t}))}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),null==(e=this.manager)||e.removeInput(this)}},pL=hL;ZC([gP(vP.INIT,"capture",{ignoreError:!0,sync:!0})],pL.prototype,"setStateToCapture",1),ZC([lL()],pL.prototype,"capture",1),ZC([gP("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),QN.emit(fO.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this._encodeCheckTimeoutId=setTimeout((()=>{if(this.isPublished&&this.isMediaTrackActive){let e=this.stat.bytesSent>0;zP[e?"addSuccessEvent":"addFailedEvent"]({key:this.kind===Zb.AUDIO?503700:513702}),e||(this.log.warn("encode failed"),this.emit("6",this))}}),5e3)},fail(e){let t="error",i=e.cause;i.message.includes("timeout")?t="timeout":i.code===mb.API_CALL_ABORTED&&(t="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:i})}})],pL.prototype,"publish",1),ZC([rL((e=>function(){return ib(this,null,(function*(){let t="publish"===this.state?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)}))})),gP([],"capture",{sync:!0})],pL.prototype,"unpublish",1);var mL=new Map;QN.on(fO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&mL.delete(e.track.deviceId)}));var _L=class extends pL{constructor(e){super(1,JM),eb(this,"mediaType",1),eb(this,"volume",0),eb(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),eb(this,"playerMuted",!0),eb(this,"pipeline"),eb(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),this.manager=e,this.pipeline=new IM(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return ib(this,null,(function*(){yield tb(_L.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};zP.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),zP.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),zP.addEnum({key:502700,value:0});let{sampleRate:i,channelCount:r}=t;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:i,channelCount:r}))),this.pipeline.source.channelCount=r||1,this.pipeline.replaceSource(e),this.updatePlayingState(!!e)}))}capture(e){let{deviceId:t,customSource:i,useExactDeviceId:r=!1}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,customSource:i})}switchDevice(e){return ib(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==Gk)return;if(yield HM(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)),QN.emit(fO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(Rk){throw this.log.error("switch microphone failed ".concat(Rk)),this.deviceId&&this.recapture(this.deviceId),Rk}}}))}listenDeviceChange(){PM&&!PM.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&PM.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return ib(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e))),sx(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield xM();t[0]?this.recapture(t[0].deviceId):PM.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return ib(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:n}=e;return function*(){let e=!1;!Nw(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!Nw(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,e=!0),!Nw(n)&&n!==t.profile.autoGainControl&&(t.profile.autoGainControl=n,e=!0),e&&t.deviceId&&(yield t.recapture(t.deviceId))}()}))}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&zP.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch((t=>this._log.warn("".concat(e?"enable":"disable"," ANS failed "),t)))}addDenoiser(e){var t;yN<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(zP.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1))}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),PM.off("audioInputAdded",this.handleMicrophoneAdded,this),PM.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return ib(this,null,(function*(){try{yield tb(_L.prototype,this,"recapture").call(this,e)}catch(Rk){let i=(yield xM()).find((t=>t.deviceId!==e));if(!i)throw Rk;yield tb(_L.prototype,this,"recapture").call(this,i.deviceId)}}))}},fL=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,i=[],r=0;for(let o=e;o<=t;o++){let e=this.dataView.getInt8(o);switch(e){case 0:case 1:case 2:case 3:2===r&&(i.push(3),r=0),0==e?r++:r=0,i.push(e);break;default:r=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],r=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:r++,i.push(this.dataView.getInt8(o));break;case 3:2!==r&&i.push(this.dataView.getInt8(o)),r=0;break;default:i.push(this.dataView.getInt8(o)),r=0}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}get isSEI(){return 6===this.dataView.getUint8(4)}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let n=6;n<this.dataView.buffer.byteLength;n++){let i=this.dataView.getUint8(n);if(t++,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),r=new DataView(i);for(let n=0;n<i.byteLength;n++,t++)r.setInt8(n,this.dataView.getInt8(t));return r}},gL=class{constructor(){eb(this,"_seiMessageList",[]),eb(this,"_smallSeiMessageList",[]),eb(this,"_seiPayloadType",243)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),r=t%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let s=0;s<i;s++)n.push(255);n.push(r);let o=new DataView(e);return n.push(...new Uint8Array(o.buffer)),n.push(128),new fL(new DataView(new Uint8Array(n).buffer),!0)}sendSEI(e,t){null!=t&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),null!=t&&t.small&&this._smallSeiMessageList.push(e)}getNaluCount(e){let t=0,i=0,r=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(r.getUint8(n)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}encode(e,t){let i=t?this._smallSeiMessageList:this._seiMessageList;if(i.length>0&&e.data.byteLength>0){let t=9-this.getNaluCount(e.data);if(t<=0)return 0;let r=i.splice(0,t).reverse().map(this.encodeSEINalu.bind(this)),n=r.reduce(((e,t)=>e+t.dataView.byteLength),0),o=new ArrayBuffer(n+e.data.byteLength),s=new DataView(o),a=new DataView(e.data),c=0;for(let e=0;e<r.length;e++)for(let t=0;t<r[e].dataView.byteLength;t++)s.setInt8(c++,r[e].dataView.getInt8(t));for(let i=0;i<e.data.byteLength;i++)s.setInt8(c++,a.getInt8(i));return e.data=o,r.length}return 0}},TL=class extends pL{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,_M),eb(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),eb(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0}),eb(this,"small"),eb(this,"isNeedToSetBandwidth"),eb(this,"muteImage"),eb(this,"manager"),eb(this,"_seiCodec",new gL),eb(this,"pipeline",[]),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(YC(qC({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",t),this.on("publish",t),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(eP&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}setMute(e){return ib(this,null,(function*(){var t,i,r;if(ww(e)){if(this.muteImage===e)return;yield null==(t=this.manager)?void 0:t.deleteWatermark("mute"),yield null==(i=this.manager)?void 0:i.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,tb(TL.prototype,this,"setMute").call(this,!1)}else yield null==(r=this.manager)?void 0:r.deleteWatermark("mute"),this.muteImage=void 0,tb(TL.prototype,this,"setMute").call(this,e)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:r=!1,customSource:n}=e;return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,customSource:n})}setProfile(e){let t=qC({},e),i=t.width>t.height;t.width*t.height<=19200&&ED&&TN&&(this.log.warn("resolution is ".concat(t.width,"*").concat(t.height,", fallback to 240*180")),t.width=i?240:180,t.height=i?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&wN&&(t.width=i?1280:720,t.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(YC(qC({},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:Zb.VIDEO,videoType:Zb.BIG})})):void 0}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return eP&&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:sO()&&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 ib(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),QN.emit(fO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(Rk){throw this.log.error("switch camera failed ".concat(Rk)),this.deviceId&&this.recapture(this.deviceId),Rk}}))}listenDeviceChange(){PM&&!PM.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&PM.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return ib(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e))),sx(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield VM();t[0]?this.recapture(t[0].deviceId):PM.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return ib(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}encodeFrame(e,t){let i=t?8:this.mediaType;return this.pipeline.reduce(((e,t)=>t?t(e,i):e),e)}get enableEncodeFrame(){return this.pipeline.some((e=>e))}play(e,t){return ib(this,null,(function*(){return Nw(this.mirror)&&!this.isScreen&&this.setMirror("view"),tb(TL.prototype,this,"play").call(this,e,t)}))}close(){PM.off("videoInputAdded",this.handleCameraAdded,this),PM.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return ib(this,null,(function*(){try{yield tb(TL.prototype,this,"recapture").call(this,e)}catch(Rk){let i=(yield VM()).find((t=>t.deviceId!==e));if(!i)throw Rk;yield tb(TL.prototype,this,"recapture").call(this,i.deviceId)}}))}},EL=EO();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:EL,exposeOrigin:!0,permittedOrigins:["*"]})}catch(WF){}var vL,yL=function(e){return ib(this,null,(function*(){let t=null,i=function(e){let t={preferCurrentTab:"current-tab"===e.preferDisplaySurface||!!e.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:IN?{max:e.width}:{ideal:e.width,max:e.width},height:IN?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:e.preferDisplaySurface||"monitor"};if(t.video=i,e.systemAudio){let{echoCancellation:i=!0,noiseSuppression:r=!1,autoGainControl:n=!1}=e;t.audio={echoCancellation:i,noiseSuppression:r,autoGainControl:n,sampleRate:48e3}}return t}(e);TO.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(EN&&yN<74||IN||ID)&&TO.warn("Your browser not support capture system audio");let n=r.getVideoTracks()[0];if(n){if(e.frameRate)try{yield n.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height})}catch(o){TO.warn("screen applyConstraints failed: ".concat(o))}e.captureElement&&(yield function(e,t){return ib(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&Dw(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==EL)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){TO.warn("cropTo target failed ".concat(r))}}))}(n,e.captureElement))}if(e.audio){let i=function(e){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return Nw(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);TO.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},SL=class extends TL{constructor(e){super(e,2),eb(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),eb(this,"objectFit","contain"),eb(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return ib(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:r,echoCancellation:n,noiseSuppression:o,audioTrack:s,videoTrack:a,captureElement:c,preferDisplaySurface:l}=e;return function*(){try{let e;return a||s?(e=new MediaStream,a&&e.addTrack(a),s&&e.addTrack(s)):e=yield yL({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:r,echoCancellation:n,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof fb?e:new fb({code:mb.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return ib(this,null,(function*(){throw new Error("Method not implemented.")}))}},IL=class extends _L{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}};var AL=class extends AM{constructor(e){super(),this.room=e,eb(this,"_localAudioTrack"),eb(this,"_localScreenAudioTrack"),eb(this,"log",TO.createLogger({id:"am"})),eb(this,"denoiser"),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}dump(e){var t,i;if(!this._localAudioTrack)return;let r=[],n=[];null!=(t=this._localAudioPipline)&&t.source.node&&(r.push(this._localAudioPipline.source.node),n.push("mic")),null!=(i=this._localAudioPipline)&&i.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),n.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),n.push("mix")),this.log.info("dump audio track ".concat(n,", duration: ").concat(e));let o=new AbortController,s=[],a=setTimeout((()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")}),1e3*e),c=()=>{for(let e=0;e<n.length;e++){let t=URL.createObjectURL(new Blob(s[e])),i=document.createElement("a");i.href=t,i.download="".concat(n[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(a),o.abort("download")},l=function(e){return ib(this,null,(function*(){let t=EM();vL||(vL=fM(t,URL.createObjectURL(new Blob(["registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});"],{type:"application/javascript"})))),yield vL;let i=new AudioWorkletNode(t,"dumper",{numberOfInputs:e.length,numberOfOutputs:0});return e.forEach(((e,t)=>e.connect(i,0,t))),new ReadableStream({start(e){i.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach((e=>e.disconnect(i))),i.port.close()}})}))}(r).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>s[t]=s[t]?s[t].concat(e[0]):[e[0]]))}}),o).catch((e=>c))));return{then:l.then.bind(l),download:c}}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}changeInput(e){if(e instanceof IL)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof _L)this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof kL)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;null==(e=this._localAudioTrack)||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),null==(t=this._localScreenAudioTrack)||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof IL?delete this._localScreenAudioTrack:e instanceof _L&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,null==(t=this._localAudioTrack)||t.removeDenoiser(e)}destroy(){this.close()}};function RL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return rL(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];return new Promise(((n,s)=>{let a=setTimeout((()=>{let i=new fb({code:mb.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});TO.warn(i),2===t?s(i):1===t&&n()}),1e3*e);i.apply(this,o).then(n,s).finally((()=>{clearTimeout(a)}))}))}))}var CL=class extends KM{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,eb(this,"tinyId"),eb(this,"isRemote",!0),eb(this,"jitterBufferDelay",0),eb(this,"_decodeCheckTimeoutId",-1),this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)}))}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===CL.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," hasFlag: ").concat(this.hasFlag," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},bL=CL;eb(bL,"STATE_SUBSCRIBE","subscribe"),ZC([RL(5,1)],bL.prototype,"waitHasMediaTrack",1),ZC([gP(vP.INIT,bL.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),QN.emit(fO.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),this._decodeCheckTimeoutId=setTimeout((()=>{if(this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let e=this.player.isPlaying||(this.kind===Zb.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0);zP[e?"addSuccessEvent":"addFailedEvent"]({key:this.kind===Zb.AUDIO?504700:514702}),e||this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===Zb.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0)," )"))}}),5e3)},ignoreError:!0})],bL.prototype,"subscribe",1),ZC([gP(bL.STATE_SUBSCRIBE,vP.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),QN.emit(fO.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],bL.prototype,"unsubscribe",1);var kL=class extends bL{constructor(e,t){super(e,t,1),eb(this,"volume",0),eb(this,"mediaType",1),eb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),eb(this,"audioDecoder"),this.manager=e.audioManager}onPlayerError(e){if(this.enableDecodeFrame){this.room.enableInsertableStreams();let e=new AudioDecoder({error:e=>this._log.error(e),output:e=>{this.player.write(e)}});e.configure({codec:"opus",sampleRate:48e3,numberOfChannels:1}),this._log.info("audioDecoder state:".concat(e.state)),this.audioDecoder=e}}get enableDecodeFrame(){var e,t;return(null==(t=null==(e=this.player.element)?void 0:e.error)?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&nP&&sP().AudioDecoder}decodeFrame(e){var t;return"configured"===(null==(t=this.audioDecoder)?void 0:t.state)&&this.audioDecoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"})),e}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}},DL=[-1,-1,1,-1,-1,1,1,1],NL=[0,0,1,0,0,1,1,1],wL=class extends vP{constructor(e,t){if(super(),this.context=e,eb(this,"name"),eb(this,"input"),eb(this,"output"),eb(this,"texture"),eb(this,"ctx2d",null),eb(this,"fbo"),eb(this,"width",0),eb(this,"height",0),eb(this,"x",0),eb(this,"y",0),eb(this,"program"),eb(this,"vertexShader"),eb(this,"fragmentShader"),eb(this,"totalFrames",0),eb(this,"dropFrames",0),eb(this,"matchInputSize",!0),eb(this,"texCoordBuffer"),eb(this,"positionBuffer"),eb(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),eb(this,"cost",0),eb(this,"_canvas",null),eb(this,"_image"),this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof WL){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(NL),this.positionBuffer=this.createBuffer(DL),!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(Cb){this.context.destroy(Cb)}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,i=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,i),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),i}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return e.addInput(this,...i),this.output=e,e}addInput(e){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();return!!(this.context instanceof jL&&this.render(e)||this.context instanceof WL&&this.render2d(e))&&(this.totalFrames++,this.cost=Date.now()-t,!0)}render2d(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&this.draw2d(this.input.image,0,0,this.width,this.height)}disconnect(){for(var e,t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];null==(e=this.output)||e.removeInput(this,...i),delete this.output}removeInput(e){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),null==(e=this.output)||e.removeInput(this),delete this.output,null==(t=this.input)||t.disconnect(),this.context instanceof jL){let e=this.context.ctx;e.deleteBuffer(this.texCoordBuffer),e.deleteBuffer(this.positionBuffer),this.fbo&&e.deleteFramebuffer(this.fbo),this.texture&&e.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&e.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&e.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&e.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures(null==(e=this.input)?void 0:e.texture)}useTextures(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];i.forEach(((t,i)=>{t&&(e.activeTexture(e.TEXTURE0+i),e.bindTexture(e.TEXTURE_2D,t))}))}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),i}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let i=this.context.ctx;i.bindBuffer(i.ARRAY_BUFFER,e),i.bufferData(i.ARRAY_BUFFER,new Float32Array(t),i.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];i.forEach(((t,i)=>{e.enableVertexAttribArray(i),e.bindBuffer(e.ARRAY_BUFFER,t),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0)}))}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(this.width!==e||this.height!==t){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let i=this.context.ctx;i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let i=this.context.ctx;i.drawArrays(i.TRIANGLE_STRIP,0,4)}draw2d(e,t,i,r,n){return!(!this.ctx2d||!e)&&(e instanceof ImageData?this.ctx2d.putImageData(e,t,i):this.ctx2d.drawImage(e,t,i,r,n),!0)}getInfo(){var e;let{totalFrames:t,x:i,y:r,width:n,height:o,name:s,cost:a}=this,c=Date.now(),l=(t-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:t,x:i,y:r,width:n,height:o,timestamp:c,fps:l,name:s,cost:a},qC({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}};ZC([gP(vP.INIT,"connected",{sync:!0})],wL.prototype,"connect",1),ZC([gP("connected",vP.INIT,{ignoreError:!0,sync:!0})],wL.prototype,"disconnect",1),ZC([gP([],"closed",{sync:!0})],wL.prototype,"close",1);var OL=[0,1,1,1,0,0,1,0],PL=class extends wL{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),eb(this,"_intervalId",0),eb(this,"_sequence",0),eb(this,"checkGLError",!1),e instanceof WL?this.ctx2d=e.ctx:e.available&&(null==t?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(OL)}start(e){this._intervalId=RP.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(RP.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof jL){let e=this.context.ctx.getError();e&&this.context.destroy(new Error("".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)))}}),{fps:this.context.frameRate})}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];super.addInput(e,...i),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),RP.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},ML=class extends PL{constructor(e,t){super(e,t),eb(this,"_videoTrack"),eb(this,"_canvasContainer"),Number(RN)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream(e.frameRate).getVideoTracks();let i=e=>{var t;let i=()=>{var t;return null==(t=this._videoTrack)?void 0:t.removeEventListener(e,r)},r=()=>{i(),this.context.destroy(new Error("video track ".concat(e)))};this.once("closed",i),null==(t=this._videoTrack)||t.addEventListener(e,r)};e instanceof jL&&i("mute"),i("ended")}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack,null==(t=this._canvasContainer)||t.remove()}},LL=class extends ML{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},xL=class extends ML{constructor(e,t){super(e,{name:"smallDestination"}),this.resolution=t}resize(e,t){let i,r=e*t,n=this.resolution.width*this.resolution.height;TO.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),r>n?i=r/n:(TO.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(e," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),i=r/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},VL=class extends wL{constructor(e,t){super(e,qC({name:"imageSource"},t)),eb(this,"_lastImage"),eb(this,"_totalFrames",0),eb(this,"_autoResize",!1),this._autoResize=!1!==(null==t?void 0:t.autoResize)}_render(e,t){var i,r;let{width:n,height:o}=this;if(this.image instanceof HTMLVideoElement){if(Dw(this.image.getVideoPlaybackQuality)&&TN){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(!0===(null==(r=null==(i=this.image.srcObject)?void 0:i.getVideoTracks()[0])?void 0:r.muted)||this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}if(({videoWidth:n,videoHeight:o}=this.image),!n||!o)return!1;this.image.width=n,this.image.height=o}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if(({width:n,height:o}=this.image),this.image!==this._lastImage)this._lastImage=this.image;else if(n===this.width&&o===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&(({width:n,height:o}=this.image),this._lastImage=this.image);if(!this._autoResize)return!0;if(this.width===n&&this.height===o&&this.totalFrames){if(t){this.useTexture();let e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,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(n,o)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},UL=class extends VL{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource"}get image(){return this._player.element}},FL=class extends UL{constructor(e,t,i){super(e,new _M({id:i.name,track:t,muted:!0,container:null,objectFit:"contain",log:i.logger}),i),this.name="videoTrackSource",this._player.play()}get image(){return this._player.element}replaceTrack(e){this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},BL=class extends vP{constructor(e){super(),eb(this,"frameRate"),eb(this,"_canvas"),eb(this,"log"),eb(this,"hasAlpha",!1),eb(this,"name"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new FL(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new ML(this,e)}createVideoImageSource(e,t){return new VL(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new UL(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};eb(BL,"_ids",0);var HL={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},jL=class extends BL{constructor(){super(...arguments),eb(this,"defaultProgam"),eb(this,"defaultVShader"),eb(this,"defaultFShader"),eb(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(BL._ids++)),this.ctx=this._canvas.getContext("webgl2",HL),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,"\n// 顶点着色器\nattribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main() {\n gl_Position = a_position;\n v_texCoord = a_texCoord;\n}\n"),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,"\n// 片元着色器\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\n\nvoid main() {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n} "),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",(()=>{this.destroy(new Error("webgl context lost"))})),this.log.info("video context created use webgl")}destroy(e){return this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;null==(t=this.ctx)||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let i=this.ctx,r=i.createShader(e);return i.shaderSource(r,t),i.compileShader(r),r}createProgram(e,t){let i=this.ctx,r=i.createProgram();return i.attachShader(r,e),i.attachShader(r,t),i.linkProgram(r),i.getProgramParameter(r,i.LINK_STATUS)||this.log.error(i.getProgramInfoLog(r)),r}};ZC([gP(vP.INIT,"created",{sync:!0})],jL.prototype,"create",1),ZC([gP("created",vP.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit("unavailable",e),this.removeAllListeners()}})],jL.prototype,"destroy",1);var WL=class extends BL{constructor(){super(...arguments),eb(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(BL._ids++),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()}};ZC([gP(vP.INIT,"created",{sync:!0})],WL.prototype,"create",1),ZC([gP("created",vP.INIT,{ignoreError:!0,sync:!0})],WL.prototype,"destroy",1);var GL=class extends bL{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),eb(this,"mediaType",4),eb(this,"source"),eb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),eb(this,"pipeline",[]),this.manager=e.videoManager}play(e,t){return(Pw(null==t?void 0:t.canvasRender)?t.canvasRender:17===kN)&&!this.source&&this.useCanvasPlayer(),super.play(e,t)}useCanvasPlayer(){if(this.log.info("useCanvasPlayer(), ".concat(!!this.player.element)),!this.player.element)return;let e=new WL({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=e.createVideoPlayerSource(this.player);this.source=t;let i=new PL(e);t.connect(i),this.player.setCanvas(e._canvas),this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this)}updateCanvasPlayerFPS(e){let t=this.decodeFPS,i=(r=t,[15,30,45,60].reduce(((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)));var r;!Ow(t)||t<=0?this.log.debug("updateCanvasPlayerFPS() ignore decoder: ".concat(t," ")):i!==e.frameRate?(this.log.info("updateCanvasPlayerFPS() decoder: ".concat(t,", closest: ").concat(i,", current: ").concat(e.frameRate)),e.frameRate=i):this.log.debug("updateCanvasPlayerFPS() ignore ClosestFPS ".concat(i," == ").concat(e.frameRate))}get decodeFPS(){var e;let{msg_video_status:t}=(null==(e=this.room.heartbeatReport)?void 0:e.msg_down_stream_info.find((e=>e.msg_user_info.str_identifier===this.userId)))||{},i=2===this.mediaType?7:this.isSmall?3:2;if(!t||0===t.length)return 0;let r=t.find((e=>e.uint32_video_stream_type===i));return(null==r?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}get enableDecodeFrame(){return this.manager.configPipeline(this),this.pipeline.some((e=>e))}decodeFrame(e){return this.pipeline.reduce(((e,t)=>t?t(e,this):e),e)}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}},JL=class extends GL{constructor(e,t){super(e,t,2),eb(this,"mediaType",2),eb(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function zL(){}var KL=e=>e(),qL=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,YL=1,QL=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new tx(e,this,this.streamId++);return ix.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},XL=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=zL,this.error=zL,this.next=zL,this.dispose=zL,this.subscribe=zL,this.doDefer()}subscribe(e){return e instanceof QL?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(KL),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}},$L=class extends XL{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 ZL(e,t,i){if(qL()){let r=Object.defineProperties(Object.setPrototypeOf(e,QL.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}});ix.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof QL&&ix.addSource(r,t)}return r}return e}function ex(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var tx=class extends $L{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{ix.defer(this.source,this.id)}))}next(e){ix.next(this.source,this.id,e),this.sink.next(e)}complete(){ix.complete(this.source,this.id),this.sink.complete()}error(e){ix.complete(this.source,this.id,e),this.sink.error(e)}},ix={addSource(e,t){ex("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){ex("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;ex("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){ex("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){ex("defer",{id:e.id,streamId:t})},pipe(e){ex("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){ex("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=YL++),ex("create",{name:e.toString(),id:e.id})}},rx=class extends XL{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 nx=function(e,t){return function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return i=>{if(i instanceof QL){let n=ZL((t=>{let o=new e(t,...r);o.sourceId=n.id,o.subscribe(i)}),t,arguments);return n.source=i,ix.pipe(n),n}return t=>i(new e(t,...r))}}}(class extends $L{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},"map");!function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];i.reduce(((e,t)=>t(e)),e)}(function(e){return ZL((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}(250),nx((()=>performance.now())),function(){return e=>{let t=new rx(e);if(e instanceof QL){let i=ZL((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,ix.pipe(i),i}return ZL(t.add.bind(t),"share",arguments)}}());var ox=new Map;function sx(e,t){let i=YC(qC({},t),{timestamp:Tb()});ox.has(e)?ox.get(e).push(i):ox.set(e,[i])}QN.on(fO.JOIN_SUCCESS,(e=>{let{room:t}=e;sx(t.userId,{eventId:32788})})),QN.on(fO.LEAVE_START,(e=>{let{room:t}=e;sx(t.userId,{eventId:32789})})),QN.on(fO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),sx(t.room.userId,{eventId:e})}})),QN.on(fO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),sx(t.room.userId,{eventId:e})}})),QN.on(fO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Zb.AUDIO?sx(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):sx(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),QN.on(fO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Zb.AUDIO?sx(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):sx(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),QN.on(fO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&sx(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&sx(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&sx(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),QN.on(fO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&sx(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&sx(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&sx(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),QN.on(fO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&sx(t.room.userId,{eventId:t.kind===Zb.VIDEO?32780:32781})})),QN.on(fO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&sx(t.room.userId,{eventId:t.kind===Zb.VIDEO?32782:32783})})),QN.on(fO.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:n}=e;switch(n){case"CONNECTED":t="RECONNECTING"===r?32795:32791;break;case"DISCONNECTED":t="RECONNECTING"===r?32796:32790;break;case"RECONNECTING":t=32794}t&&sx(i.userId,{eventId:t})})),QN.on(fO.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:n,remoteUserId:o}=e,s=!!o;switch(n){case"CONNECTED":t="RECONNECTING"===r?s?32801:32798:s?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===r&&(t=s?32802:32799);break;case"RECONNECTING":t=s?32800:32797}t&&sx(i.userId,{eventId:t,remoteUserId:o})})),QN.on(fO.VIDEO_CODEC_IMPLEMENTATION_CHANGED,(e=>{let{userId:t,remoteUserId:i,codec:r,isHWCodec:n,prevImplementation:o,streamType:s}=e,a=n?1:0;o||(a=n?3:2);let c="h264"===r?0:2,l={eventId:4004,param1:a,param2:c,streamType:s||2};i&&(l.remoteUserId=i,l.eventId=4005),sx(t,l),zP.addEnum({key:i?514701:513701,value:a}),zP.addEnum({key:i?514700:513700,value:c})})),QN.on(fO.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===Zb.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),sx(t.userId,e)}}));var ax=$C(rb(),1),cx=class extends ax.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,eb(this,"userMap",new Map),eb(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:r,role:n}=e;if(this.userMap.has(t))return;let o={userId:i,tinyId:r,role:20===n?"anchor":"audience"};this.userMap.set(t,o),this.emit("1",o)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let r="peer leave [".concat(e,"]");Nw(t)||(r+=":".concat(qk[t])),this._log.info(r);let n=this.remotePublishedUserMap.get(e);if(n){let t=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:t,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",i.userId)}setUserList(e){this.userMap.forEach((t=>{e.findIndex((e=>e[this.key]===t[this.key]))<0&&this.deleteUser(t[this.key],0)})),e.forEach((e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)}))}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach((t=>{let i=t[this.key];if(e.findIndex((e=>e[this.key]===t[this.key]))<0){this._log.info("remote [".concat(i,"] unpublish"));let e=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(i),this.emit("6",{prevMuteState:e,muteState:t.muteState,flag:0})}})),e.forEach((e=>{var t;let i=e[this.key];if(i===this.mySelfId)return;let{flag:r,userId:n,tinyId:o}=e,s=qw(r,n),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==r&&(e.flag=r,this._log.info("remote publish updated: ".concat(JSON.stringify(e.muteState))),this.emit("6",{prevMuteState:a,muteState:s,flag:r}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(s))),this.addUser({userId:n,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:qw(0,n),muteState:s,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function lx(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return rL(((e,n)=>{let o=new Map;return QN.on(fO.ROOM_DESTROY,(e=>{let{room:t}=e;return o.delete(t)})),function(){let s=o.get(this);for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(s||(s={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,s)),0===s.timestamp?s.timestamp=Date.now():Date.now()-s.timestamp>1e3&&(s.timestamp=Date.now(),s.callCountInSecond=0,s.totalSizeInSecond=0),r&&(s.totalSizeInSecond+=r(...c)),0!==s.timestamp&&Date.now()-s.timestamp<1e3&&(s.callCountInSecond>=t||s.totalSizeInSecond>i))throw new fb({code:mb.INVALID_OPERATION,message:KN({key:oD.CALL_FREQUENCY_LIMIT,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>i,name:n,timesInSecond:t,maxSizeInSecond:i}})});s.callCountInSecond++,e.call(this,...c)}}))}var dx,ux=!0,hx={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"},px={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},mx=((dx=mx||{})[dx.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",dx[dx.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",dx[dx.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",dx[dx.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",dx[dx.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",dx[dx.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",dx[dx.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",dx[dx.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",dx[dx.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",dx[dx.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",dx[dx.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",dx[dx.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",dx[dx.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",dx[dx.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",dx[dx.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",dx[dx.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",dx[dx.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",dx[dx.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",dx[dx.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",dx[dx.INVALID_OPERATION=5100]="INVALID_OPERATION",dx[dx.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",dx[dx.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",dx[dx.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",dx[dx.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",dx[dx.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",dx[dx.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",dx[dx.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",dx[dx.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",dx[dx.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",dx[dx.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",dx[dx.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",dx[dx.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",dx[dx.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",dx[dx.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",dx[dx.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",dx[dx.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",dx[dx.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",dx[dx.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",dx[dx.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",dx[dx.DEVICE_ERROR=5300]="DEVICE_ERROR",dx[dx.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",dx[dx.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",dx[dx.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",dx[dx.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",dx[dx.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",dx[dx.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",dx[dx.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",dx[dx.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",dx[dx.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",dx[dx.SERVER_ERROR=5400]="SERVER_ERROR",dx[dx.NEED_TO_BUY=5401]="NEED_TO_BUY",dx[dx.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",dx[dx.OPERATION_FAILED=5500]="OPERATION_FAILED",dx[dx.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",dx[dx.REJOIN_FAILED=5502]="REJOIN_FAILED",dx[dx.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",dx[dx.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",dx[dx.OPERATION_ABORT=5998]="OPERATION_ABORT",dx[dx.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",dx);var _x=YC(qC({},sD),{INVALID_PARAMETER(e){let{fnName:t}=e;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(r,"(), received type: ").concat(kw(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(r,"(), received type: ").concat(kw(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,value:r}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(r,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,value:r}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(r,".")},INVALID_ELEMENT_ID(e){let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE(e){let{key:t,fnName:i,type:r}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(r,".")},INVALID_STREAM_ID(e){let{key:t}=e;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(e){let{key:t}=e;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(e){let{key:t}=e;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(e){let{fnName:t}=e;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(e){let{fnName:t}=e;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing ").concat(i.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(e){let{fnName:t}=e;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the microphone is not turned on.")},INVALID_BUFFER_EMPTY:e=>{let{key:t}=e;return"the buffer size of paramerter '".concat(t,"' cannot be empty")},INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: '".concat("audience","' cannot call this api."),INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:e=>{let{fnName:t}=e;return"you need to call ".concat(t,"() after publish stream.")},ENV_NOT_SUPPORTED(e){let{fnName:t}=e;return"the current browser does not support the capability of the function '".concat(t,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(e){let{fnName:t}=e;return"cannot call ".concat(t," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got device exception").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:i=fx(t),error:r}=e;return"NotFoundError, no ".concat(i," detected, please check your device and the configuration on '").concat(t,"'").concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(e){let{fnName:t,deviceType:i=fx(t),error:r}=e;return"NotAllowedError, you have disabled ".concat(i," access, please allow the current application to use the ").concat(i).concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(e){let{fnName:t,deviceType:i=fx(t),error:r}=e;return"NotReadableError, the ".concat(i," maybe in use by another APP, please check if the device is pre-occupied by another APP.")},DEVICE_OVERCONSTRAINED_ERROR(e){let{fnName:t,deviceType:i=fx(t),error:r}=e;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(e){let{fnName:t,deviceType:i=fx(t),error:r}=e;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(i).concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_SECURITY_ERROR(e){let{fnName:t,deviceType:i=fx(t),error:r}=e;return"SecurityError, check whether the system security policy restricts the use of the ".concat(i,", and it is recommended to turn on the ").concat(i," after the user interacts with the page").concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_ABORT_ERROR(e){let{fnName:t,deviceType:i=fx(t),error:r}=e;return"AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal".concat(r?" error: ".concat(r.toString(),"."):".")},CAMERA_RECOVER_FAILED(e){let{error:t}=e;return"camera recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},MICROPHONE_RECOVER_FAILED(e){let{error:t}=e;return"microphone recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},OPERATION_FAILED(e){let{fnName:t,error:i}=e;return"'".concat(t,"' failed, reason: ").concat(null==i?void 0:i.toString())},FIREWALL_RESTRICTION:()=>"media connection failure due to firewall restrictions, please try to change your network.",EVENT_HANDLER_ERROR(e){let{eventName:t}=e;return"an error was caught on trtc.on('".concat(t,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(e){let{reason:t,error:i}=e;return"video context error ".concat(t," ").concat((null==i?void 0:i.name)||""," ").concat((null==i?void 0:i.message)||"")},SERVER_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got server error: ").concat(null==i?void 0:i.toString(),", please check the SDK documentation.")},NEED_TO_BUY(e){let{value:t,url:i}=e;return"You need to buy packages for ".concat(t,". Refer to: ").concat(i)},ACCOUNT_NO_MONEY:e=>{let{fnParams:t}=e;return"your TRTC account run out of credit, please recharge.".concat(t.sdkAppId?" SDKAppId: ".concat(t.sdkAppId):"")},OPERATION_ABORT(e){let{fnName:t}=e;return"'".concat(t,"' abort")},UNKNOWN_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' throw unknown exception").concat(i?", error: ".concat(i.toString(),"."):".")}});function fx(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var gx=class extends Error{constructor(e){let{code:t,extraCode:i,message:r="",messageParams:n,fnName:o="",originError:s}=e;var a;let c;c=r||function(e){let t,{code:i,params:r,enableDocLink:n=!1}=e,s="",a=mx[i];try{t=_x[a]}catch(o){t=_x.UNKNOWN_ERROR}return Dw(t)?s=t(r):ww(t)&&(s=t),r.fnName&&!s.includes(r.fnName)&&("."!==s[s.length-1]&&(s+="."),s+=" thrown from ".concat(r.fnName,"()")),n&&(s+=" doc:"),s}({code:i||t,params:qC({fnName:o,error:s},n)}),super(c),eb(this,"name","RtcError"),eb(this,"code"),eb(this,"extraCode"),eb(this,"functionName"),eb(this,"message"),eb(this,"handler"),eb(this,"originError"),this.name=mx[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");ZD?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):eN&&(e.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),e.href.length>0&&e.click()})}static convertFrom(e,t,i){let r=e;if(e instanceof fb){let{stack:n}=e,o={code:px.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case mb.INVALID_PARAMETER:o.code=px.INVALID_PARAMETER,o.message=e.message;break;case mb.INVALID_OPERATION:o.code=px.INVALID_OPERATION;break;case mb.NOT_SUPPORTED:case mb.NOT_SUPPORTED_H264:o.code=px.ENV_NOT_SUPPORTED,e.getCode()===mb.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(sD.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case mb.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case mb.SERVER_TIMEOUT:case mb.SWITCH_ROLE_FAILED:o.code=px.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case mb.API_CALL_ABORTED:o.code=px.OPERATION_ABORT;break;case mb.DEVICE_NOT_FOUND:case mb.DEVICE_AUTO_RECOVER_FAILED:case mb.INITIALIZE_FAILED:o.code=5300,e.name&&(o.extraCode=function(e){let t;switch(e){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}(e.name));break;case mb.UNKNOWN:break;default:o.code=px.OPERATION_FAILED}r=new gx(o),n&&(r.stack+=n.substr(n.indexOf("\n")))}else{if(e instanceof gx)return e;r=new gx({code:px.UNKNOWN_ERROR,fnName:t,originError:e})}return r}};var Tx=gx,Ex={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}}},vx={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}}},yx={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(ww(e)&&!document.getElementById(e))throw new Tx({code:px.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},Sx={name:"userId",required:!0,type:"string"},Ix={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[hx.AUDIO_PROFILE_STANDARD,hx.AUDIO_PROFILE_STANDARD_STEREO,hx.AUDIO_PROFILE_HIGH,hx.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Ax(e,t){if(!e)throw new Tx({code:px.INVALID_OPERATION,extraCode:5101,fnName:t})}function Rx(e,t,i){if(!e)throw new Tx({code:px.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var Cx={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 Tx({code:px.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(ww(e.roomId))throw new Tx({code:px.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new Tx({code:px.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new Tx({code:px.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new Tx({code:px.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}})}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:yx,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Ex},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&NO())throw new Tx({code:px.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:YC(qC({},yx),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Ex}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Ix},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&NO())throw new Tx({code:px.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Ix}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:yx,publish:{type:"boolean"},option:vx},validate(e,t,i,r,n){var o;if((null==(o=null==e?void 0:e.option)||!o.videoTrack)&&NO())throw new Tx({code:px.ENV_NOT_SUPPORTED,extraCode:5201});if(!xO())throw new Tx({code:px.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:yx,publish:{type:"boolean"},option:vx}},muteRemoteAudio:[Sx,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Sx,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:yx,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){Ax(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(Rx(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new Tx({code:px.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:YC(qC({},yx),{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){Ax(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(Rx(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new Tx({code:px.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&&Nw(e.streamType))throw new Tx({code:px.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){Ax(this._room.isJoining||this._room.isJoined,i)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(e,t,i,r){if(!nP)throw new Tx({code:px.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new Tx({code:px.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new Tx({code:px.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new Tx({code:px.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});Ax(this._room.isJoined,i)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(e,t,i){if(!e&&!this._room.isMainStreamPublished||e&&!this._room.isAuxStreamPublished)throw new Tx({code:px.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:i})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(e,t,i,r){if(e.byteLength>1e3)throw new Tx({code:px.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new Tx({code:px.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(Ax(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new Tx({code:px.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}}},bx={TRTC:Cx},kx=class extends Error{};function Dx(e,t){let i=$w(e);for(let r=0;r<t.length;r++)Xw(i[r],t[r]);return i}function Nx(e){this._resolve=Promise.resolve(e)}function wx(e){this._reject=Promise.reject(e)}var Ox=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=Dx;let i=Ox.instances.get(e);i?i.set(t,this):Ox.instances.set(e,new Map([[t,this]]))}static get(e,t){if(!t)return;let i=Ox.instances.get(e);return i&&i.get(t)||new Ox(e,t)}static gets(e,t){let i=Ox.instances.get(e),r=[];return i&&i.forEach(((e,i)=>{t.test(i)&&r.push(e)})),r}action(e,t,i){let r=t=>{var i;return 0===e?this.started=!0:3===e&&(this.started=!1),this.ops.shift(),null==(i=this.currentOp)||i.action(),t},n=t=>{var i,r;throw this.ops.shift(),0===e&&2===(null==(i=this.currentOp)?void 0:i.type)&&this.ops.shift().reject(new kx("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:Nx,reject:wx};try{switch(this.state){case 1:if(0===e)throw new kx("already started");break;case 4:if(2===e)throw new kx("not started");break;default:return this.cacheOp(o)}}catch(s){return Promise.reject(s)}return this.ops.push(o),o.promise=t(...o.args).then(r,n)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new kx("already start");break;case 3:switch(e.type){case 2:throw new kx("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new kx("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new kx("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 kx("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new kx("start not allowed after update");case 0:throw new kx("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new kx("keep start")),new kx("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}},Px=Ox;Px.instances=new WeakMap;var Mx=new WeakMap,Lx=(e,t)=>{if(t instanceof kx){let{stack:i}=t;t=new Tx({code:px.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function xx(e,t){return rL(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let a=Px.get(this,"string"==typeof e?e:e.call(this,...o));return a?(t&&(a.startSame=t.bind(this)),a.action(0,i.bind(this),o).catch(Lx.bind(null,r))):i.apply(this,o)}))}function Vx(e,t){let{merge:i,debounce:r}=t||{};return rL(((t,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=Px.get(this,"string"==typeof e?e:e.call(this,...s));if(!c)return t.apply(this,s);if(i&&(c.mergeUpdate=i.bind(this)),r&&r.isNeedToDebounce.apply(this,s)){let{delay:e,getKey:i}=r;return new Promise(((r,o)=>{var a,l;let d=null==(a=Mx.get(this))?void 0:a.get(i(...s));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout((()=>{if(3===c.state||4===c.state)return r();c.action(2,t.bind(this),s).catch(Lx.bind(null,n)).then(r,o)}),e);Mx.has(this)?null==(l=Mx.get(this))||l.set(i(...s),{timeoutId:u,resolve:r}):Mx.set(this,new Map([[i(...s),{timeoutId:u,resolve:r}]]))}))}return c.action(2,t.bind(this),s).catch(Lx.bind(null,n))}))}function Ux(e){return rL(((t,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let s="function"==typeof e?e.call(this,...n):e;if(s instanceof RegExp)return Promise.all(Px.gets(this,s).map((e=>e.action(3,(()=>Promise.resolve()),n)))).then((()=>t.call(this,...n)));let a=Px.get(this,s);return a?a.action(3,t.bind(this),n).catch(Lx.bind(null,i)):t.apply(this,n)}))}var Fx={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message"};function Bx(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function Hx(e){return e===hx.QOS_PREFERENCE_CLEAR?"detail":e===hx.QOS_PREFERENCE_SMOOTH?"motion":""}var jx=class{constructor(){eb(this,"_log"),this._log=TO.createLogger({id:"fd"})}download(e,t){return ib(this,null,(function*(){let{type:i="blob"}=t||{};try{let t,r=Ww();if(t=Dw(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let n=Ww()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(n,"ms")),zP.addSuccessEvent({key:522700,cost:Ww()-r}),t.data}catch(Cb){throw this._log.error("failed to download: ".concat(e,", error: ").concat(Cb)),zP.addFailedEvent({key:522700,error:Cb}),Cb}}))}downloadWithFetch(e,t){return ib(this,null,(function*(){this._log.info("download with fetch: ".concat(e,", return type: ").concat(t));try{let i,r=yield fetch(e);if(!r.ok)throw new Error("network response was not ok");return i="arraybuffer"===t?yield r.arrayBuffer():yield r.blob(),{data:i}}catch(Rk){throw Rk}}))}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType=t,n.onload=()=>{200===n.status||0===n.status&&n.response?i({data:n.response}):r(new Error("XHR failed"))},n.onerror=r,n.send(null)}))}loadWasm(e,t){return ib(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=Ww(),r=null,n=null;if(Dw(WebAssembly.instantiateStreaming)&&!e.startsWith("data:application/octet-stream;base64,")&&!(e=>e.startsWith("file://"))(e)&&Dw(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(bb){n=bb}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(bb){n=bb}if(r){let t=Ww()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),zP.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),zP.addFailedEvent({key:522701,error:n}),n}))}};ZC([OP({settings:{timeout:0,retries:3},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],jx.prototype,"download",1);var Wx=new jx;function Gx(e){let{TRTC:t,room:i,errorModule:r,assetsPath:n}=e;return{TRTC:t,room:i,assetsPath:n,fileDownloader:Wx,innerEmitter:QN,constants:yb,environment:aD,utils:vb,eventLogger:$N,log:this.room.getLogger(),loggerManager:TO,errorModule:r,kvStatManager:zP,trtc:this,clearStarted:(e,t)=>{let i=e.getAlias(),r=Px.instances.get(this);if(r)if(t){let e=r.get(i+t);if(!e)return;e.started=!1}else r.forEach(((e,t)=>{t.startsWith(i)&&(e.started=!1)}))}}}var Jx=new WeakMap;function zx(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return rL(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{qx.call(this,t,n,i,this._name)}catch(Cb){return Promise.reject(Cb)}return e.apply(this,n)}))}function Kx(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return rL(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{qx.call(this,t,n,i,this._name)}catch(Cb){throw Cb}return e.apply(this,n)}))}function qx(e,t,i,r){if(Lw(e))for(let n=0;n<e.length;n++)Yx.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else Yx.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function Yx(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function s(e){return{code:px.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(Nw(i)){if(t.required)throw new Tx(s(5001));if(Nw(t.defaultValue))return void(Dw(t.validate)&&t.validate.call(this,i,r,n,o,this));i=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let r=0;r<t.type.length;r++)null===t.type[r]&&null===i&&(e=!0),Dw(t.type[r])&&i instanceof t.type[r]&&(e=!0),ww(t.type[r])&&kw(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new Tx({code:px.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>Fw(e)?Bw(e):ww(e)?e:kw(e)))},value:i}})}else if(!Nw(t.type)&&kw(i)!==t.type)throw new Tx(s(5002));if(!1===t.allowEmpty){let e=Ow(i)&&(0===i||Number.isNaN(i)),t=ww(i)&&""===i.trim();if(e||t)throw new Tx(s(5003))}if(t.notLessThanZero&&Ow(i)&&i<0)throw new Tx(s(5006));if(!Nw(t.min)&&Ow(i)&&i<t.min)throw new Tx(s(5007));if(!Nw(t.max)&&Ow(i)&&i>t.max)throw new Tx(s(5008));if(ww(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new Tx(s(5004))}else if(Dw(t.instanceOf)&&!(i instanceof t.instanceOf))throw new Tx(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new Tx(s(5005));let{properties:a}=t;Rw(a)&&Mw(i)&&Object.keys(a).forEach((e=>{Yx.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;Rw(c)&&Lw(i)&&i.forEach(((e,t)=>{Yx.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),Dw(t.validate)&&t.validate.call(this,i,r,n,o,this)}function Qx(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r}=e;return rL(((e,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];function c(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...s);if(s[e.argIndex]===t)return e.value}if(t===s||e in s)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(kw(t)):(JSON.stringify(t),t)}catch(n){return"type:".concat(kw(t))}}let l=this._log||TO;s.length>0?l.info("".concat(n,"() ").concat(JSON.stringify(s,((e,t)=>c(e,t,["userSig","privateMapKey"]))))):l.info("".concat(n,"()"));let d=r?r(...s):UP[n];try{let i=e.apply(this,s),r=Ww();return Uw(i)?i.then((e=>(l.info("".concat(n,"() success ").concat(t.call(this,...s))),zP.addSuccessEvent({key:d,cost:Ww()-r}),e))).catch((e=>{throw e=Tx.convertFrom.call(this,e,n,1===s.length?s[0]:s),l.error("".concat(n,"() failed ").concat(t.call(this,...s)," ").concat(e," params: ").concat(JSON.stringify(s,c))),zP.addFailedEvent({key:d,error:e}),e})):(zP.addSuccessEvent({key:d}),i)}catch(u){throw u=Tx.convertFrom.call(this,u,n),l.error("".concat(n,"() failed ").concat(u," params: ").concat(JSON.stringify(s,c))),zP.addFailedEvent({key:d,error:u}),u}}))}var Xx=e=>rL(((t,i)=>function(r,n){return ib(this,null,(function*(){let o=this._plugins.get(r);if(!o)throw this._log.error("plugin ".concat(String(r)," is not found")),new Tx({code:px.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});return qx.call(this,o.getValidateRule(e),[n],i,"TRTC"),t.call(this,o,n)}))})),$x=0,Zx=class{constructor(e,t){eb(this,"player"),eb(this,"publisher"),eb(this,"mixInput"),this.mixInput=new IM(t),e.url?(this.player=new Audio(e.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(e.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(e.track),this.mixInput.connect()}updateSettings(e){!this.player||(Nw(e.volume)||(this.volume=e.volume),Nw(e.loop)||(this.loop=e.loop),Nw(e.playbackRate)||(this.playbackRate=e.playbackRate))}updateListener(e){if(this.player){if(e.onDurationChange){let{onDurationChange:t}=e;this.player.ondurationchange=e=>{t(e.target.duration)}}if(e.onTimeUpdate){let t=e.onTimeUpdate,{player:i}=this;i.ontimeupdate=()=>{t(i.currentTime,i.duration)}}e.onEnded&&(this.player.onended=e.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(e){!this.player||e<0&&e>this.player.duration||(this.player.currentTime=e,this.publisher.currentTime=e)}play(){var e,t;return null==(e=this.publisher)||e.play(),null==(t=this.player)?void 0:t.play()}pause(){var e,t;null==(e=this.player)||e.pause(),null==(t=this.publisher)||t.pause()}stop(){var e;null==(e=this.player)||e.pause(),this.mixInput.disconnect()}setOperation(e){"pause"===e&&this.pause(),"resume"===e&&(this.pause(),this.play()),"stop"===e&&(this.pause(),this.seek(0))}set volume(e){!this.player||!this.publisher||(this.player.volume=e,this.publisher.volume=e)}set loop(e){!this.player||!this.publisher||(this.player.loop=e,this.publisher.loop=e)}set playbackRate(e){!this.player||!this.publisher||(this.player.playbackRate=e,this.publisher.playbackRate=e)}};function eV(e,t){if(t&&"function"!=typeof t)throw new Tx({code:px.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var tV=class{constructor(e){this.core=e,eb(this,"log"),eb(this,"mixedMusicMap",new Map),eb(this,"cacheMusicMap",new Map),$x+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat($x)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat($x)),this.core=e}getName(){return tV.Name}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(e){switch(e){case"start":return tV.startValidateRule;case"update":return tV.updateValidateRule;case"stop":return tV.stopValidateRule}}start(e){return ib(this,null,(function*(){let{room:t}=this.core;this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:i,url:r}=e;if(this.mixedMusicMap.has(i))return;let n=this.cacheMusicMap.get(i);n?e.url?n.reset():(n.mixInput.replaceSource(e.track),n.mixInput.connect()):(n=new Zx(e,t.audioManager),this.cacheMusicMap.set(i,n)),n.updateListener(e),n.updateSettings(e),yield n.play(),this.mixedMusicMap.set(i,n),this.log.info("start mix audio track ".concat(i," success.")),zP.addEnum({key:502700,value:3}),this.kvUpload(e)}))}update(e){return ib(this,null,(function*(){let{id:t,operation:i,seekFrom:r,playbackRate:n}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let o=this.mixedMusicMap.get(t);o?(o.updateSettings(e),o.updateListener(e),Nw(i)||o.setOperation(i),Nw(r)||o.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return ib(this,arguments,(function(e){var t=this;let{id:i}=e;return function*(){var e;t.mixedMusicMap.has(i)&&(t.log.info("remove music source, music id: ".concat(i)),null==(e=t.mixedMusicMap.get(i))||e.stop(),t.mixedMusicMap.delete(i)),"*"===i&&t.destroyAllMusic()}()}))}kvUpload(e){let{track:t,loop:i,volume:r,playbackRate:n,operation:o,seekFrom:s,onTimeUpdate:a,onDurationChange:c,onEnded:l}=e;t&&zP.addCount({key:502711}),i&&zP.addCount({key:502703}),r&&zP.addCount({key:502704}),n&&zP.addCount({key:502705}),o&&zP.addCount({key:502706}),s&&zP.addCount({key:502707}),"function"!=typeof a&&zP.addCount({key:502709}),"function"!=typeof l&&zP.addCount({key:502710}),"function"!=typeof c&&zP.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>this.stop({id:t})))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},iV=tV;eb(iV,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(e,t,i){if(e.url&&"*"!==e.url){let t=e.url.split("?")[0],r=["mp3","ogg","wav","flac"],n=t.split(".").pop(),o=r.indexOf(n)>=0,s=t.startsWith("blob"),a=t.startsWith("data");if(!(o||s||a))throw new Tx({code:px.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new Tx({code:px.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});eV("onTimeUpdate",e.onTimeUpdate),eV("onEnded",e.onEnded),eV("onDurationChange",e.onDurationChange)}}),eb(iV,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(e,t,i){eV("onTimeUpdate",e.onTimeUpdate),eV("onEnded",e.onEnded),eV("onDurationChange",e.onDurationChange)}}),eb(iV,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),eb(iV,"Name","AudioMixer");var rV,nV=e=>(e=Number(e))>0&&e<14e8,oV=0,sV=class{constructor(e){this.core=e,eb(this,"log"),eb(this,"audioContext",EM()),eb(this,"workletNode"),oV+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(oV)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(oV)),e.assetsPath&&this.preload("".concat(e.assetsPath,"/denoiser-wasm.js"))}static startValidateRule(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(t,i,r,n){if(!e.room.audioManager.hasAudioTrack)throw new Tx({code:px.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return rV||(rV=this.doPreload(e)),rV}doPreload(e){return ib(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield fM(this.audioContext,i)}finally{URL.revokeObjectURL(i)}}))}getName(){return sV.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(e){switch(e){case"start":return sV.startValidateRule(this.core);case"update":return sV.updateValidateRule;case"stop":return sV.stopValidateRule}}start(e){return ib(this,null,(function*(){let{room:t}=this.core;if(yield this.preload("".concat(e.assetsPath,"/denoiser-wasm.js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:i,sign:r,status:n,message:o}=yield function(e){return ib(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:r,timestamp:n}=e;return function*(){let e="https://".concat(function(e){let t;return t=nV(e)?cV.MAIN_OVERSEA:cV.MAIN,t}(t),"/api/v1/audioAiAuth?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(r,"&timestamp=").concat(n),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d="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)}}()}))}(YC(qC({},e),{timestamp:t}));if(!i)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(i,". Message: ").concat(o)),new Tx({code:px.INVALID_PARAMETER,message:o});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(e.sdkAppId),userId:e.userId,timestamp:t,sign:r,status:n}}),this.workletNode.port.onmessage=e=>{let{data:t}=e;"cost"===t.type&&this.log.debug("[RTCAIDenoiser] ".concat(t.value))}}this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})}))}update(){return ib(this,null,(function*(){}))}stop(){return ib(this,null,(function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)}))}destroy(){}},aV=sV;eb(aV,"updateValidateRule",{type:"object"}),eb(aV,"stopValidateRule",{type:"object"}),eb(aV,"Name","AIDenoiser");var cV={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};var lV=$C(rb(),1),dV=class extends lV.EventEmitter{constructor(){super(),this.state="nominal",this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return ib(this,null,(function*(){if(!this.observer)try{"PressureObserver"in window&&!ED&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(Rb){$N.uploadEvent({log:"stat-pressure-detector-start-failed",error:Rb})}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&TO.info("".concat(i.source,": ").concat(i.state)),this.emit("state-changed",{type:i.source,state:this.state})}destroy(){var e;try{null==(e=this.observer)||e.disconnect(),this.observer=null}catch(Rk){$N.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:Rk})}}},uV=new dV,hV=0,pV=class{constructor(e){this.core=e,eb(this,"log"),eb(this,"_seiMessageList",[]),eb(this,"_smallSeiMessageList",[]),eb(this,"_subStreamSeiMessageList",[]),eb(this,"_seiWorker"),hV++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(hV)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(hV)),this.core=e}encode(e,t){try{let i=EV(e,8===t?this._smallSeiMessageList:2===t?this._subStreamSeiMessageList:this._seiMessageList);i&&this.log.debug("".concat(i," sei sent"))}catch(Rk){this.log.warn(Rk)}return e}decode(e,t){return vV(e).forEach((e=>{this.core.trtc.emit(Fx.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:t.userId,streamType:2===t.mediaType?"sub":"main"})})),e}destroy(){}getValidateRule(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}start(e){rP?(this._seiWorker=function(){let e=[TV,fV,gV,_V,EV,vV,yV,SV],t=()=>{let e=[],t=[],i=[];self.onmessage=r=>{r.data.isMain?(e.push(r.data.message),r.data.small&&i.push(r.data.message)):t.push(r.data.message)},self.onrtctransform=r=>{let{options:n}=r.transformer,o=n.isReceiver?SV(n.userId,n.streamType):yV(n.isMain?n.small?i:e:t);r.transformer.readable.pipeThrough(o).pipeTo(r.transformer.writable)}},i="(()=>{".concat([fL].map((e=>"const ".concat(e.name,"=(()=>").concat(e.toString(),")()"))).join("\n"),"\n").concat(e.map((e=>e.toString())).join("\n"),";(").concat(t,")()})()"),r=new Blob([i],{type:"text/javascript"}),n=URL.createObjectURL(r),o=new Worker(n);return URL.revokeObjectURL(n),o}(),this._seiWorker.onmessage=e=>{this.core.trtc.emit(Fx.SEI_MESSAGE,YC(qC({},e.data),{streamType:Bx(e.data.streamType)}))},this._seiWorker.onerror=e=>{this.log.error("seiWorker error: ",e.message)},this.core.room.videoManager.enableSEI({seiWorker:this._seiWorker})):this.core.room.videoManager.enableSEI({encoder:this.encode.bind(this),decoder:this.decode.bind(this)})}stop(e){this.core.room.videoManager.disableSEI()}update(e){let{buffer:t,options:i}=e;var r;let n=[i.seiPayloadType,t],o=!!i.small;i.toSubStream?this._subStreamSeiMessageList.push(n):(this._seiMessageList.push(n),o&&this._smallSeiMessageList.push(n)),this.core.innerEmitter.emit("265",{room:this.core.room,data:n,isMain:!i.toSubStream}),null==(r=this._seiWorker)||r.postMessage({message:n,isMain:!i.toSubStream,small:o})}getName(){return pV.Name}getAlias(){return"sei"}getGroup(){return"sei"}},mV=pV;function _V(e){let[t,i]=e,r=i.byteLength,n=parseInt(String(r/255),10),o=r%255,s=[];s.push(0,0,0,1,6,t);for(let c=0;c<n;c++)s.push(255);s.push(o);let a=new DataView(i);return s.push(...new Uint8Array(a.buffer)),s.push(128),new fL(new DataView(new Uint8Array(s).buffer),!0)}function fV(e){return"empty"===e.type||0===e.data.byteLength}function gV(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}function TV(e){let t=0,i=0,r=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(r.getUint8(n)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}function EV(e,t){if(t.length>0&&e.data.byteLength>0){let i=9-TV(e.data);if(i<=0)return 0;let r=t.splice(0,i).reverse().map(_V),n=r.reduce(((e,t)=>e+t.dataView.byteLength),0),o=new ArrayBuffer(n+e.data.byteLength),s=new DataView(o),a=new DataView(e.data),c=0;for(let e=0;e<r.length;e++)for(let t=0;t<r[e].dataView.byteLength;t++)s.setInt8(c++,r[e].dataView.getInt8(t));for(let t=0;t<e.data.byteLength;t++)s.setInt8(c++,a.getInt8(t));return e.data=o,r.length}return 0}function vV(e){try{let t=new DataView(e.data);if(fV(e)||!gV(t))return[];let i=[],r=0,n=-1,o=-1;for(let s=0;s<e.data.byteLength;s++){let a=t.getUint8(s);if(0===a)r++;else if(1===a){if(2===r||3===r){let a=s-r;if(-1===n?n=a:-1===o&&(o=a,i.push(new fL(new DataView(t.buffer.slice(n,o)))),n=a,o=-1),6!==t.getUint8(s+1)){e.data=t.buffer.slice(a);break}}r=0}else r=0}return i.reverse()}catch(xP){return[]}}function yV(e){return new TransformStream({transform(t,i){EV(t,e),i.enqueue(t)}})}function SV(e,t){return new TransformStream({transform(i,r){vV(i).forEach((i=>{self.postMessage({seiPayloadType:i.seiPayloadType,data:i.seiPayload.buffer,userId:e,streamType:t})})),r.enqueue(i)}})}eb(mV,"Name","SEI");var IV=0,AV=new Set,RV=null;Ab("5.8.1-beta.9");var CV={RtcError:Tx,ErrorCode:px,ErrorCodeDictionary:mx},bV=class extends hb.EventEmitter{constructor(e,t){super(),eb(this,"_room"),eb(this,"_eventListened",new Set),eb(this,"_localVideoTrack",null),eb(this,"_localAudioTrack",null),eb(this,"_localScreenTrack",null),eb(this,"_localScreenAudioTrack",null),eb(this,"_localVideoConfig",null),eb(this,"_localScreenConfig",null),eb(this,"_localAudioConfig",null),eb(this,"_remoteVideoConfigMap",new Map),eb(this,"_remoteAudioConfigMap",new Map),eb(this,"_remoteAudioMuteMap",new Map),eb(this,"_mediaTrackMap",new WeakMap),eb(this,"_log",TO.createLogger({id:"t".concat(++IV)})),eb(this,"_plugins",new Map),eb(this,"_networkQuality",null),eb(this,"_speakerId"),this._room=new e(qC({logger:this._log,frameWorkType:bV.frameWorkType},t)),this._log.debug("TRTC.create() ".concat(JSON.stringify(t,((e,t)=>"plugins"===e?t.map((e=>e.Name)):t)))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(e){return this._room.audioManager.dump(e)}}}),t.plugins&&t.plugins.forEach((e=>{this._use(e,t.assetsPath)})),this._use(iV,t.assetsPath),this._use(aV,t.assetsPath),t.enableSEI&&nP&&(this._use(mV),this.startPlugin("SEI")),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(Fx.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 Tx({code:px.OPERATION_FAILED,extraCode:5504,messageParams:{reason:t,error:i}}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:i}=e;e.emit=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{return i.apply(e,n)}catch(Cb){let i=KN({key:oD.CATCH_HANDLER_ERROR,data:{name:t,event:n[0]},addDocLink:!1});return TO.warn("".concat(i,"\n\n").concat(Cb.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,t){var i;ux&&(ux=!1,5!==TO.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Vb,"/en/index.html")),console.info("* Changelog: ".concat(Vb,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),TO.info("TRTC Web SDK Version:",Ib),TO.info("UA:",navigator.userAgent),TO.info("URL: ".concat(location.href).concat("IFRAME"===(null==(i=self.frameElement)?void 0:i.tagName)?" in iframe":"")),UN().then((e=>{e&&TO.info(VN)})));let r=new bV(e,t||{});return AV.add(r),r}get room(){return this._room}_listenEvents(){DP(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(Fx.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(Fx.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(Fx.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(Fx.ERROR,Tx.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(Fx.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e,this.emit(Fx.NETWORK_QUALITY,e)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{DP(t,t).add("player-state-changed",(i=>{let r=YC(qC({},i),{userId:e.userId});t.kind===Zb.VIDEO&&(r.streamType=Bx(t.streamType)),this.emit(t.kind===Zb.AUDIO?Fx.AUDIO_PLAY_STATE_CHANGED:Fx.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===mb.PLAY_NOT_ALLOWED&&this.emit(Fx.AUTOPLAY_FAILED,{userId:t.userId})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{NP(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:r}=i,n=t.audioAvailable,o=t.videoAvailable,{audioAvailable:s,videoAvailable:a}=i;s||this._remoteAudioConfigMap.delete(r),a||this._remoteVideoConfigMap.delete("".concat(r,"_","main")),i.hasAuxiliary||this._remoteVideoConfigMap.delete("".concat(r,"_","sub")),n!==s&&(this.emit(s?Fx.REMOTE_AUDIO_AVAILABLE:Fx.REMOTE_AUDIO_UNAVAILABLE,{userId:r}),s?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i})),o!==a&&(this.emit(a?Fx.REMOTE_VIDEO_AVAILABLE:Fx.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"}),a?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"})),t.hasAuxiliary!==i.hasAuxiliary&&(this.emit(i.hasAuxiliary?Fx.REMOTE_VIDEO_AVAILABLE:Fx.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}),i.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}))})).add("sei-message",(e=>{this.emit(Fx.SEI_MESSAGE,YC(qC({},e),{streamType:Bx(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(Fx.ERROR,new Tx({code:px.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,i,r,n,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(r=this._networkQuality)?void 0:r.downlinkRTT)||0,upLoss:(null==(n=this._networkQuality)?void 0:n.uplinkLoss)||0,downLoss:(null==(o=this._networkQuality)?void 0:o.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/nD},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)/nD},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(Fx.STATISTICS,l)})).add("custom-message",(e=>{this.emit(Fx.CUSTOM_MESSAGE,e)})),DP(this,PM).add("audioInputAdded",(e=>{this.emit(Fx.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(Fx.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(Fx.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(Fx.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>ib(this,null,(function*(){if(this.emit(Fx.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),RV&&RV.deviceId===Jk){let e=(yield FM()).find((e=>e.deviceId===Jk));e&&RV.groupId!==e.groupId&&(RV=e,this.emit(Fx.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>ib(this,null,(function*(){this.emit(Fx.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield FM())[0];t&&RV&&(RV.deviceId===e.deviceId||RV.deviceId===Jk&&RV.groupId!==t.groupId)&&(RV=t,this.emit(Fx.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))))}use(e){let t,i;"plugin"in e?(t=e.plugin,i=e.assetsPath):t=e,this._use(t,i||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name))return void this._log.warn("duplicate install plugin",e.Name);let i=new e(Gx.call(this,{TRTC:bV,room:this._room,errorModule:CV,assetsPath:t}));this._plugins.set(e.Name,i),e.autoStart&&(this.startPlugin(e.Name),this._log.info("auto start plugin",e.Name))}enterRoom(e){return ib(this,null,(function*(){var t,i;let{scene:r="rtc",enableAutoPlayDialog:n=!0,autoReceiveAudio:o=!0,autoReceiveVideo:s=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!ww(e.proxy)&&e.proxy.turnServer&&(null==(i=(t=this._room).setTurnServer)||i.call(t,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=n,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=s,Pw(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:"audience"===e.role?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,r,bV.frameWorkType),this._checkTrackToPublish(),uV.start()}))}exitRoom(){return ib(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return ib(this,null,(function*(){null!=t&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),null!=t&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),"anchor"===e&&this._checkTrackToPublish()}))}destroy(){NP(this),this.removeAllListeners(),this._room.destroy(),AV.delete(this),0===AV.size&&uV.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach((e=>{var t;return null==(t=e.destroy)?void 0:t.call(e)}))}startLocalAudio(){return ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:i=!0,mute:r,option:n}=t,o=new _L(e._room.audioManager),s={},a={muted:!0};n&&(Nw(n.microphoneId)?Nw(n.audioTrack)||(s.customSource=n.audioTrack):s.deviceId=n.microphoneId,n&&Ow(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),Nw(n.profile)||(ww(n.profile)?Qb[n.profile]&&o.setProfile(Qb[n.profile]):o.setProfile(n.profile)),Ow(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),Nw(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),Nw(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),Nw(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",(t=>{e.emit(Fx.ERROR,new Tx({code:px.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(Fx.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=Tx.convertFrom(t.error)),e.emit(Fx.PUBLISH_STATE_CHANGED,YC(qC({},t),{error:i}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),Nw(r)||o.setMute(r),DP(o,o).add("player-state-changed",(t=>{e.emit(Fx.AUDIO_PLAY_STATE_CHANGED,YC(qC({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localAudioTrack=o,e._localAudioConfig=YC(qC({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:a,track:o})}()}))}updateLocalAudio(e){return ib(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:r}=e,n={};r&&(r.microphoneId?yield this._localAudioTrack.switchDevice(r.microphoneId):Nw(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),Nw(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),Nw(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!Nw(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),Nw(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Xw(this._localAudioConfig,e)}))}stopLocalAudio(){return ib(this,null,(function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),NP(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:i,publish:r=!0,mute:n,option:o}=t,s=new TL(e._room.videoManager),a={},c={};if(o&&(o.cameraId?a.deviceId=o.cameraId:Nw(o.useFrontCamera)?Nw(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?Zb.FACING_MODE_USER:Zb.FACING_MODE_ENVIRONMENT,Nw(o.profile)||(ww(o.profile)?Xb[o.profile]&&s.setProfile(Xb[o.profile]):s.setProfile(o.profile)),Nw(o.fillMode)||(c.objectFit=o.fillMode),Nw(o.mirror)||(c.mirror=o.mirror),Nw(o.small)||(GO()?ww(o.small)?s.small=Xb[o.small]:!0===o.small?s.small=Xb["120p"]:s.small=o.small:e._log.warn("small stream is not supported"))),s.on("5",(t=>{e.emit(Fx.ERROR,new Tx({code:px.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),s.on("2",(t=>{e.emit(Fx.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),s.on("4",(t=>{let i;t.error&&(i=Tx.convertFrom(t.error)),e.emit(Fx.PUBLISH_STATE_CHANGED,YC(qC({},t),{error:i}))})),e._listenOutputTrackChanged(s),yield s.capture(a),Nw(n)||(yield s.setMute(n)),s.mediaTrack)if(null!=o&&o.qosPreference){let e=Hx(o.qosPreference);s.mediaTrack.contentHint=e}else null!=o&&o.videoTrack||(s.mediaTrack.contentHint=Hx(hx.QOS_PREFERENCE_SMOOTH));DP(s,s).add("player-state-changed",(t=>{e.emit(Fx.VIDEO_PLAY_STATE_CHANGED,YC(qC({},t),{userId:"",streamType:"main"}))})),r&&e._room.isJoined&&e._room.publish(s).catch((()=>{})),e._localVideoTrack=s,e._localVideoConfig=YC(qC({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:s})}()}))}updateLocalVideo(e){return ib(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:r,option:n}=e,o={};if(n){if(Nw(n.profile)||(ww(n.profile)?Xb[n.profile]&&this._localVideoTrack.setProfile(Xb[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&Nw(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):Nw(n.useFrontCamera)?Nw(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?Zb.FACING_MODE_USER:Zb.FACING_MODE_ENVIRONMENT),Nw(n.fillMode)||(o.objectFit=n.fillMode),Nw(n.mirror)||(o.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let e=Hx(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e}if(n.small){let e=!this._localVideoTrack.small;GO()?(!0===n.small?this._localVideoTrack.small=Xb["120p"]:ww(n.small)?this._localVideoTrack.small=Xb[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),e&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else!1===n.small&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!Nw(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),Nw(r)||(yield this._localVideoTrack.setMute(r)),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Xw(this._localVideoConfig,e)}))}stopLocalVideo(){return ib(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),NP(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:i=null,publish:r=!0,option:n}=t,o=new SL(e._room.videoManager);o.on("4",(t=>{let i;t.error&&(i=Tx.convertFrom(t.error)),e.emit(Fx.PUBLISH_STATE_CHANGED,YC(qC({},t),{error:i}))})),e._listenOutputTrackChanged(o);let s=null,a={},c={};n&&(Nw(n.profile)||(ww(n.profile)?$b[n.profile]&&o.setProfile($b[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(a.systemAudio=!0,a.echoCancellation=n.echoCancellation,a.noiseSuppression=n.noiseSuppression,a.autoGainControl=n.autoGainControl),Nw(n.fillMode)||(c.objectFit=n.fillMode),n.videoTrack&&(a.videoTrack=n.videoTrack),n.audioTrack&&(a.audioTrack=n.audioTrack),n.captureElement&&(a.captureElement=n.captureElement),n.preferDisplaySurface&&(a.preferDisplaySurface=n.preferDisplaySurface));let l=yield o.capture(a);if(null!=n&&n.qosPreference){let e=Hx(n.qosPreference);o.mediaTrack.contentHint=e}else null!=n&&n.videoTrack||(o.mediaTrack.contentHint=Hx(hx.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(Zb.ENDED,(()=>{e._stopScreenShare(),e.emit(Fx.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(s=new IL(e._room.audioManager),s.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&s.setAudioOutput(e._speakerId)),DP(o,o).add("player-state-changed",(t=>{e.emit(Fx.VIDEO_PLAY_STATE_CHANGED,YC(qC({},t),{userId:"",streamType:"sub"}))})),r&&e._room.isJoined){let t=[o];s&&t.push(s),e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=o,e._localScreenAudioTrack=s,e._localScreenConfig=YC(qC({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:o})}()}))}updateScreenShare(e){return ib(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(Nw(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let e=Hx(r.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}this._room.isJoined&&!Nw(i)&&(i&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch((()=>{}))),this._localScreenConfig.publish&&!i&&(this._room.unpublish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch((()=>{})))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Xw(this._localScreenConfig,e)}))}stopScreenShare(){return ib(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return ib(this,null,(function*(){let{view:t,userId:i,streamType:r,option:n}=e,o="".concat(i,"_").concat(r);if(this._remoteVideoConfigMap.has(o))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(r));let s=this._room.remotePublishedUserMap.get(i);if(!s)return;let a={},c="main"===r?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._listenOutputTrackChanged(c),n&&(Nw(n.fillMode)||(a.objectFit=n.fillMode),Nw(n.mirror)||(a.mirror=n.mirror),a.canvasRender=n.canvasRender,"main"===r&&!Nw(n.small)&&(s.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,c.user))),yield this._room.subscribe(c),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._emitTrackEvent(c),this._remoteVideoConfigMap.set(o,{config:e}),n&&!Nw(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return ib(this,null,(function*(){var t,i;let{view:r,userId:n,streamType:o,option:s}=e,a="".concat(n,"_").concat(o),c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(n))return;let l={};s&&(Nw(s.fillMode)||(l.objectFit=s.fillMode),Nw(s.mirror)||(l.mirror=s.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);if("main"===o&&(null==u?void 0:u.muteState.hasVideo)&&(d=u.remoteVideoTrack),"sub"===o&&(null==u?void 0:u.muteState.hasAuxiliary)&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:h}=c;"main"===o&&s&&!Nw(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:h}),Xw(h,e);let p=Nw(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=Nw(r)?h.view:r,_=Nw(null==s?void 0:s.viewRoot)?null==(i=h.option)?void 0:i.viewRoot:s.viewRoot;this._observeView({remoteTrack:d,view:m,receiveWhenViewVisible:p,viewRoot:_})}))}stopRemoteVideo(e){return ib(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return ib(this,null,(function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:n,remoteAuxiliaryTrack:o}=r;"main"===e.streamType&&(n.stop(),t.hasVideo&&i.push(n)),"sub"===e.streamType&&(o.stop(),t.hasAuxiliary&&i.push(o))}for(let e of i)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.get(e.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(e.outMediaTrack));let n=this._remoteVideoConfigMap.get("".concat(e.userId,"_").concat(e.streamType));n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete("".concat(e.userId,"_").concat(e.streamType))}))}muteRemoteAudio(e,t){return ib(this,null,(function*(){if("*"===e)if(t)yield this._stopRemoteAudio({userId:e});else{let e=[...this._room.remotePublishedUserMap.values()];for(let t of e)t.muteState.hasAudio&&!this._remoteAudioConfigMap.has(t.userId)&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)}))}setRemoteAudioVolume(e,t){if("*"===e){let e=[...this._room.remotePublishedUserMap.values()];for(let i of e)this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);i&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}startPlugin(e,t){return ib(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return ib(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return ib(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){return this.listeners(e).includes(t)||(this._log.debug("on",e),super.on(e,t,i),this._eventListened.add(e)),this}off(e,t,i){return this._log.debug("off",e),"*"===e?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,i),this}getAudioTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"};var t,i;let r,n="main";if(ww(e)?r=e:(r=e.userId,e.streamType&&(n=e.streamType)),!r)return"sub"===n?(null==(t=this._localScreenAudioTrack)?void 0:t.mediaTrack)||null:(null==(i=this._localAudioTrack)?void 0:i.mediaTrack)||null;{let e=this._room.remotePublishedUserMap.get(r);if(e)return e.remoteAudioTrack.mediaTrack}return null}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main"}=e;if(""===t){if("main"===i&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let e=this._room.remotePublishedUserMap.get(t);if(e)return"main"===i?e.remoteVideoTrack.mediaTrack:e.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{userId:t,streamType:i="main"}=e;if(t){let e=this._room.remotePublishedUserMap.get(t);if("main"===i&&(null==e?void 0:e.muteState.hasVideo))return e.remoteVideoTrack.getVideoFrame();if("sub"===i&&(null==e?void 0:e.muteState.hasAuxiliary))return e.remoteAuxiliaryTrack.getVideoFrame()}else{if("main"===i&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}setCurrentSpeaker(e){var t,i;this._speakerId=e,null==(t=this._localAudioTrack)||t.setAudioOutput(e),null==(i=this._localScreenAudioTrack)||i.setAudioOutput(e),this._room.remotePublishedUserMap.forEach((t=>t.remoteAudioTrack.setAudioOutput(e)))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return ib(this,null,(function*(){let{userId:t,option:i}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let n={};i&&(Nw(i.volume)||(n.volume=i.volume));let o=r.remoteAudioTrack;this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(o),yield this._updateAudioPlayOption({playOption:n,track:o})}catch(yF){throw this._remoteAudioConfigMap.delete(t),yF}this._emitTrackEvent(o)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return ib(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 ib(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),Nw(t)&&n&&n.view&&!Kw(i)){let e=Zw(n.view);e.length>0&&(yield r.play(e,i))}if(!Nw(t)){let e=Zw(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return ib(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:r}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t)}catch(bb){}Nw(t.muted)||i.setPlayerMute(t.muted),Nw(t.volume)||i.setAudioVolume(t.volume/100)}()}))}_listenOutputTrackChanged(e){0===e.listeners("output-media-track-changed").length&&e.on("output-media-track-changed",(()=>this._emitTrackEvent(e,!1)))}_emitTrackEvent(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===i||(this._mediaTrackMap.set(e.outMediaTrack,i),this.emit(Fx.TRACK,{userId:i,streamType:Bx(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var e,t,i;let r=[];if((null==(e=this._localAudioConfig)?void 0:e.publish)&&this._localAudioTrack&&r.push(this._localAudioTrack),(null==(t=this._localVideoConfig)?void 0:t.publish)&&this._localVideoTrack&&r.push(this._localVideoTrack),null!=(i=this._localScreenConfig)&&i.publish&&(this._localScreenTrack&&r.push(this._localScreenTrack),this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack)),0!==r.length)return this._room.publish(...r).catch((()=>{}))}_observeView(e){let{remoteTrack:t,view:i,receiveWhenViewVisible:r=!1,viewRoot:n}=e;if(Nw(i))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(Bx(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||Lw(i)&&0===i.length||!r)return null==s||s.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch((()=>{})));let a=o.visibleViewMap||new Map,c=-1;(!s||s.root!==n)&&(null==s||s.disconnect(),a.clear(),s=new IntersectionObserver((e=>{e.forEach((e=>{a.set(e.target,e.isIntersecting)})),clearTimeout(c),c=window.setTimeout((()=>{[...a.values()].find((e=>e))?t.isSubscribed||this._room.subscribe(t).catch((()=>{})):t.isSubscribed&&this._room.unsubscribe(t).catch((()=>{}))}),200)}),{root:n}));let l=new Set(Zw(i));a.forEach(((e,t)=>{l.has(t)||(s.unobserve(t),a.delete(t))})),l.forEach((e=>{a.set(e,!0),s.observe(e)})),s.takeRecords().forEach((e=>{a.set(e.target,e.isIntersecting)})),o.visibleViewMap=a,o.observer=s}_exitRoom(){return ib(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach((e=>{this._stopRemoteAudio({userId:e}).catch()})),[...this._remoteVideoConfigMap.keys()].forEach((e=>{let t=e.includes("main")?"main":"sub",i=e.split("_".concat(t))[0];i&&this._stopRemoteVideo({userId:i,streamType:t}).catch()})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach((e=>{NP(e.remoteAudioTrack),NP(e.remoteVideoTrack),NP(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return ib(this,null,(function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield null==(e=this._room)?void 0:e.unpublish(...t).catch((()=>{}))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),NP(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_initActiveSpeaker(){return ib(this,null,(function*(){if(RV&&!MM(RV))this.emit(Fx.DEVICE_CHANGED,{type:"speaker",action:"active",device:RV});else{let e=yield FM();if(e[0]&&!MM(e[0]))RV=e[0],this.emit(Fx.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let e=e=>{let{track:t}=e;"audio"===t.kind&&(!RV||MM(RV))&&(this._initActiveSpeaker(),QN.off("102",this._initActiveSpeaker))};QN.on("102",e)}}}))}_onAudioAvailable(e){let{userId:t}=e,i=this._remoteAudioMuteMap.has(t)?this._remoteAudioMuteMap.get(t):this._remoteAudioMuteMap.get("*");(!1===i||this._room.autoReceiveAudio&&!i)&&this._doStartRemoteAudio({userId:t}).catch((()=>{}))}_onVideoAvailable(e){let{userId:t,streamType:i}=e;if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(t);if(r){let e="main"===i?r.remoteVideoTrack:r.remoteAuxiliaryTrack;this._room.subscribe(e).then((()=>{this._emitTrackEvent(e)})).catch((()=>{}))}}_onAudioUnavailable(e){let{userId:t,muteState:i}=e;i.hasAudio&&i.audioMuted||this._stopRemoteAudio({userId:t},!1).catch((()=>{}))}_onVideoUnavailable(e){let{userId:t,streamType:i}=e;this._stopRemoteVideo({userId:t,streamType:i},!1).catch((()=>{}))}sendSEIMessage(e,t){var i;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:YC(qC({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),zP.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),zP.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){TO.setLogLevel(e),Nw(t)||(t?TO.enableUploadLog():TO.disableUploadLog())}static isSupported(){return MO()}static getCameraList(){return VM(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return xM(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return FM(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(e){return ib(this,null,(function*(){(yield FM()).forEach((t=>{t.deviceId===e&&(AV.forEach((i=>{i.setCurrentSpeaker(e),i.emit(Fx.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),RV=t)}))}))}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:o,version:s}=e;switch(s&&(JP.version=s),t){case"count":JP.addCount({key:i,useUV:o});break;case"enum":JP.addEnum({key:i,value:r,useUV:o});break;case"number":JP.addNumber({key:i,value:r,split:n})}}},kV=bV;eb(kV,"_loggerManager",TO),eb(kV,"EVENT",Fx),eb(kV,"ERROR_CODE",px),eb(kV,"TYPE",hx),eb(kV,"frameWorkType",30),ZC([Qx({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?null==e?void 0:e.assetsPath:"default"}})})],kV.prototype,"use",1),ZC([zx(bx.TRTC.enterRoom),xx("room",((e,t)=>{let[i]=e,[r]=t;return(i.roomId||i.strRoomId)===(r.roomId||r.strRoomId)&&i.userId===r.userId&&i.sdkAppId===r.sdkAppId})),rL((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),Qx()],kV.prototype,"enterRoom",1),ZC([Qx()],kV.prototype,"exitRoom",1),ZC([zx(bx.TRTC.switchRole),Vx("room",{merge:(e,t)=>t}),Qx()],kV.prototype,"switchRole",1),ZC([Qx()],kV.prototype,"destroy",1),ZC([zx(bx.TRTC.startLocalAudio),xx("audio",((e,t)=>{let[i]=e,[r]=t;var n,o;return(null==(n=null==i?void 0:i.option)?void 0:n.microphoneId)===(null==(o=null==r?void 0:r.option)?void 0:o.microphoneId)})),Qx()],kV.prototype,"startLocalAudio",1),ZC([zx(bx.TRTC.updateLocalAudio),Vx("audio",{debounce:{delay:200,getKey:()=>"".concat(IV,"-localAudio"),isNeedToDebounce:e=>{var t;return!Nw(null==(t=e.option)?void 0:t.captureVolume)}}}),Qx()],kV.prototype,"updateLocalAudio",1),ZC([Ux("audio"),Qx()],kV.prototype,"stopLocalAudio",1),ZC([zx(bx.TRTC.startLocalVideo),xx("video",((e,t)=>{let[i]=e,[r]=t;var n,o;return(null==(n=null==i?void 0:i.option)?void 0:n.cameraId)===(null==(o=null==r?void 0:r.option)?void 0:o.cameraId)})),Qx()],kV.prototype,"startLocalVideo",1),ZC([zx(bx.TRTC.updateLocalVideo),Vx("video"),Qx()],kV.prototype,"updateLocalVideo",1),ZC([Ux("video"),Qx()],kV.prototype,"stopLocalVideo",1),ZC([zx(bx.TRTC.startScreenShare),xx("screen",(()=>!0)),Qx()],kV.prototype,"startScreenShare",1),ZC([zx(bx.TRTC.updateScreenShare),Vx("screen"),Qx()],kV.prototype,"updateScreenShare",1),ZC([Qx()],kV.prototype,"stopScreenShare",1),ZC([zx(bx.TRTC.startRemoteVideo),xx((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),Qx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],kV.prototype,"startRemoteVideo",1),ZC([zx(bx.TRTC.updateRemoteVideo),Vx((e=>"v".concat(e.userId).concat(e.streamType))),Qx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],kV.prototype,"updateRemoteVideo",1),ZC([zx(bx.TRTC.stopRemoteVideo),rL((e=>function(t){return ib(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)}))})),Qx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],kV.prototype,"stopRemoteVideo",1),ZC([Ux((e=>"v".concat(e.userId).concat(e.streamType)))],kV.prototype,"_stopRemoteVideo",1),ZC([zx(...bx.TRTC.muteRemoteAudio),Qx({getRemoteId:e=>e})],kV.prototype,"muteRemoteAudio",1),ZC([Kx(...bx.TRTC.setRemoteAudioVolume),function(e,t){return rL(((i,r)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];var s,a;let c=null==(s=Jx.get(this))?void 0:s.get(t(...n));c&&c>0&&clearTimeout(c);let l=window.setTimeout((()=>{i.apply(this,n)}),e);Jx.has(this)?null==(a=Jx.get(this))||a.set(t(...n),l):Jx.set(this,new Map([[t(...n),l]]))}))}(200,(e=>e)),Qx({getRemoteId:e=>e})],kV.prototype,"setRemoteAudioVolume",1),ZC([Xx("start"),iL((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),xx(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),Qx({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>FP[e.getName()]})],kV.prototype,"startPlugin",1),ZC([Xx("update"),Vx(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),Qx({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>BP[e.getName()]})],kV.prototype,"updatePlugin",1),ZC([Xx("stop"),Ux(((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i})),Qx({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>HP[e.getName()]})],kV.prototype,"stopPlugin",1),ZC([Kx(...bx.TRTC.enableAudioVolumeEvaluation)],kV.prototype,"enableAudioVolumeEvaluation",1),ZC([Qx()],kV.prototype,"getVideoSnapshot",1),ZC([Qx()],kV.prototype,"setCurrentSpeaker",1),ZC([xx((e=>"a".concat(e.userId)),(()=>!0))],kV.prototype,"_startRemoteAudio",1),ZC([rL((e=>function(t){return ib(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(YC(qC({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),Ux((e=>"a".concat(e.userId)))],kV.prototype,"_stopRemoteAudio",1),ZC([Ux("room")],kV.prototype,"_exitRoom",1),ZC([Ux("screen")],kV.prototype,"_stopScreenShare",1),ZC([zx(...bx.TRTC.sendSEIMessage),lx({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}})],kV.prototype,"sendSEIMessage",1),ZC([zx(bx.TRTC.sendCustomMessage),lx({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],kV.prototype,"sendCustomMessage",1),ZC([zx(bx.TRTC.create)],kV,"_create",1);var DV=kV,NV=class{constructor(){this._set=new Set,QN.on(fO.LEAVE_SUCCESS,this.delete,this)}add(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let r=this.getKey(t.userId,i||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let r=this.getKey(t.userId,t.roomId||i,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(e,t,i,r){return"".concat(i,"_").concat(t,"_").concat(e,"_").concat(r)}isJoined(e){let{userId:t,roomId:i,sdkAppId:r,room:n}=e;return"rtc"!==n.scene&&this._set.has(this.getKey(t,i,r,n.useStringRoomId))}};function wV(){return ib(this,null,(function*(){let e,t;try{let t=yield xM();e=t&&t.length}catch(u){}try{let e=yield VM();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:s}=this.checkSystemResult.detail,a=yO.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:r,h264Decode:o,vp8Encode:n,vp8Decode:s},l={browser:a.browser,os:a.os,trtc:c,devices:i},d={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};$N.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),$N.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var OV=$C(rb()),PV="1",MV="5",LV="2",xV="3",VV="5",UV="4",FV={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},BV=[FV.UPDATE_REMOTE_MUTE_STAT,FV.UPLINK_NETWORK_STATS,FV.USER_LIST_RES,FV.MUTE_RESULT,FV.SERVER_FIRST_PACKAGE_RECEIVED],HV={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},jV="publish_change",WV="join",GV="leave",JV="quality_report",zV="mute_uplink",KV="publish",qV="publish_state_change",YV="unpublish",QV="subscribe",XV="unsubscribe",$V="subscribe_change",ZV="start_publishing",eU="stop_publishing",tU="start_push_user_cdn",iU="stop_push_user_cdn",rU="start_mcu_mix",nU="stop_mcu_mix",oU="get_user_list",sU="change_role",aU="update_constraint_config",cU="rebuild_pc",lU="join/v2",dU="publish/v2",uU="subscribe/v3",hU="ability_status_report",pU="reconnect",mU="channel_msg",_U=new Set;var fU=class extends OV.default{constructor(e){var t,i;super(),eb(this,"room"),eb(this,"url"),eb(this,"backupUrl"),eb(this,"race"),eb(this,"destroyed",!1),eb(this,"_socketInUse"),eb(this,"_socket"),eb(this,"_backupSocket"),eb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),eb(this,"_currentState","DISCONNECTED"),eb(this,"_isReconnecting",!1),eb(this,"_seq",0),eb(this,"_log"),eb(this,"_lastMessageTime",-1),eb(this,"_connnectStartTime",-1),eb(this,"_stopConnectRetry"),eb(this,"bytesSent",0),eb(this,"bytesReceived",0),eb(this,"keepAlive",!1),eb(this,"signalDomainWhenUnifiedProxy"),this.room=e.room,this.race=!!Nw(e.race)||e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,((null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0)-_U.size>0&&this.room.enableSPC&&(this.keepAlive=!0,_U.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=TO.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.signalDomainWhenUnifiedProxy&&(e+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy))),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 ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;return function*(){if(e.isConnected)return Promise.resolve();e._log.info("connect to [".concat(e.url,", ").concat(e.backupUrl,"]").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive))),e.emitConnectionStateChanged("CONNECTING"),e._connnectStartTime=Ww();let i=[e.connectWS({url:e._urlWithParam,isMain:!0,timeout:t})];e.race&&e._backupUrlWithParam!==e._urlWithParam&&i.push(e.connectWS({url:e._backupUrlWithParam,isMain:!1,timeout:t})),e._socketInUse=yield jw(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?Zb.BACKUP:Zb.MAIN),e.emitConnectionStateChanged("CONNECTED")}()}))}connectWS(e){let{url:t,timeout:i,isMain:r}=e,n=new WebSocket(t);this.bindSocket(n),r?this._socket=n:this._backupSocket=n;let o=-1;return new Promise(((e,t)=>{n.onclose=t,n.onerror=t,n.onopen=()=>e(n),i&&(o=setTimeout((()=>{this.unbindAndCloseSocket(r?Zb.MAIN:Zb.BACKUP),t(new fb({code:mb.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),i))})).finally((()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)}))}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===Zb.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(Rk){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(Rk){}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?Zb.MAIN:Zb.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(Zb.MAIN),this.unbindAndCloseSocket(Zb.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:r}=t,n=Object.values(FV),o=Object.keys(FV)[n.indexOf(i)],s=HV[o]||i;switch(BV.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case FV.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,r.svrTime&&function(e){gb=e-(new Date).getTime();let t=new Date;t.setTime(e),TO.info("baseTime from server: ".concat(t," offset: ").concat(gb))}(r.svrTime),this._log.info("ChannelSetup Success"),zP.addSuccessEvent({key:521701,cost:Ww()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(PV,{signalInfo:this._signalInfo});else{let e=new fb({code:mb.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:KN({key:oD.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),zP.addFailedEvent({key:521701,error:e}),this.emit(MV,e)}break;case FV.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=r.relayOuterIp,this._signalInfo.relayInnerIp=r.relayInnerIp,this._signalInfo.relayPort=r.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(s,{data:t});break;default:this.emit(String(s),{data:t})}}reGetSignalChannelUrl(){return ib(this,null,(function*(){try{if(!this.room.joinParams)return;tw(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(Rb){}}))}reconnect(){return ib(this,null,(function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:i,relayInnerIp:r,relayPort:n}=this._signalInfo,{data:o}=yield this.sendWaitForResponse({command:pU,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:HV.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),zP.addSuccessEvent({key:521702,cost:Ww()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(zP.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(Rb){this._log.error(Rb),this.room.reJoin()}}}))}send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let i={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},r=JSON.stringify(i);return this._socketInUse.send(r),this.bytesSent+=oO(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:o,enableLog:s=!0}=e;return new Promise(((e,a)=>{let c=setTimeout((()=>{this.off(n,l);let e=new fb({code:mb.API_CALL_TIMEOUT,message:KN({key:oD.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),a(e)}),r),l=t=>{t.data.seq===d&&(clearTimeout(c),this.off(n,l),e(t))};this.on(n,l);let d=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:r=0,retryTimeout:n=0}=e;return YN({retryFunction:this.sendWaitForResponse,onError:e=>{let{retry:t}=e;this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(xV,t))},onRetrying:e=>{this._log.warn("".concat(t||i," timeout observed, retrying [").concat(e,"/").concat(r,"]"))},settings:{retries:r,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),_U.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(Zb.MAIN),this.unbindAndCloseSocket(Zb.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(e,"s"));let t=setTimeout((()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close(),this.off(HV.JOIN_ROOM_RESULT,i)}),1e3*e),i=e=>{0===e.data.code&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.off(HV.JOIN_ROOM_RESULT,i))};this.on(HV.JOIN_ROOM_RESULT,i)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(LV,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(xV):"DISCONNECTED"===e&&this.emit(VV))}};ZC([OP({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn("retrying to connect ".concat(e)),e>=3&&e%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],fU.prototype,"connect",1);var gU=$C(rb()),TU=0,EU=!1,vU=new Set,yU=!1,SU=class{constructor(e){eb(this,"userId"),eb(this,"tinyId"),eb(this,"_sdpSemantics"),eb(this,"_isUplink"),eb(this,"_room"),eb(this,"_log"),eb(this,"_signalChannel"),eb(this,"_isErrorObserved",!1),eb(this,"_waitForPeerConnectionConnectedPromise"),eb(this,"_waitForPeerConnectionConnectedPromiseReject",null),eb(this,"_peerConnection",null),eb(this,"_emitter",new gU.default),eb(this,"_currentState","DISCONNECTED"),eb(this,"_isReconnecting",!1),eb(this,"_reconnectionCount",0),eb(this,"_reconnectionTimer",-1),eb(this,"_isFirstConnection",!0),eb(this,"_prevTime",-1),eb(this,"_localAddress"),eb(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=TO.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=Ww())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,zP.addSuccessEvent({key:521705,cost:Math.min(Ww()-this._prevTime,3e4)})):this._isReconnecting&&zP.addSuccessEvent({key:521706,cost:Ww()-this._prevTime}),this._prevTime=-1}catch(xP){throw this._isFirstConnection?(this._isFirstConnection=!1,zP.addFailedEvent({key:521705,error:xP})):this._isReconnecting&&this._reconnectionCount>=3&&zP.addFailedEvent({key:521706,error:xP}),xP}}initialize(){let e={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(e),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(e){this._log.info("close connection"),this._emitter.emit("closed",e),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),vU.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:mb.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return vk;let e=null;if(this._isUplink){if(!KO()||0===this._peerConnection.getSenders().length)return vk;e=this._peerConnection.getSenders()[0].transport}else{if(!zO()||0===this._peerConnection.getReceivers().length)return vk;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:vk}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===yk.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===yk.FAILED||e.target.connectionState===yk.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new fb({message:r,code:mb.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===yk.CONNECTED||e.target.connectionState===yk.COMPLETED)&&(this.logSelectedCandidate(),$N.logSuccessEvent({userId:this._room.userId,eventType:bk.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(TU=0,EU=!1,yU=!0,vU.add(this)):vU.delete(this),QN.emit(fO.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 ib(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(FO(t)){let i=e.get(t.localCandidateId),r=e.get(t.remoteCandidateId);i&&(this._log.info("local candidate: ".concat(i.candidateType," ").concat(i.protocol,":").concat(i.ip||i.address,":").concat(i.port," ").concat(i.networkType||""," ").concat("relay"===i.candidateType?"relayProtocol:".concat(i.relayProtocol):"")),this._localAddress="".concat(i.ip||i.address,":").concat(i.port)),r&&(this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port)),this._remoteAddress="".concat(r.protocol,":").concat(r.ip||r.address));break}}))}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this._currentState)return e();this._waitForPeerConnectionConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new fb({code:mb.API_CALL_ABORTED,message:KN({key:oD.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{QN.off(fO.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new fb({code:mb.API_CALL_TIMEOUT,message:"connection timeout"});var i;TU+=1,i=this._signalChannel.isConnected,TU>2&&!EU&&0===vU.size&&i&&(this._log.warn("firewall restriction"),EU=!0,this._emitter.emit("firewall-restriction")),t(e)}),Fk);QN.on(fO.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",i,this)})),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally((()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}))),this._waitForPeerConnectionConnectedPromise}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(xV,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Ak()){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?mb.UPLINK_RECONNECTION_FAILED:mb.DOWNLINK_RECONNECTION_FAILED,message:KN({key:this._isUplink?oD.UPLINK_RECONNECTION_FAILED:oD.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(xV,this.reconnect,this),-1)}on(e,t,i){this._emitter.on(e,t,i)}off(e,t,i){this._emitter.off(e,t,i)}getIsReconnecting(){return this._isReconnecting}get isH264(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}},IU=$C(ub()),AU=function(e){return IU.default.parse(e)},RU=function(e){return IU.default.write(e)};function CU(e){return Object.keys(e).filter((t=>e[t]))}var bU=class extends SU{constructor(e){super(YC(qC({},e),{isUplink:!1})),eb(this,"_flag",0),eb(this,"role","anchor"),eb(this,"remoteAudioTrack"),eb(this,"remoteVideoTrack"),eb(this,"remoteAuxiliaryTrack"),eb(this,"ssrc",{audio:0,video:0,auxiliary:0}),eb(this,"_isSDPExchanging",!1),this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new kL(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new GL(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new JL(this._room,this)}get videoCodec(){var e,t;let i=null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)?void 0:t.sdp;return i?i.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return qw(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===Zb.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let t=e.streams[0],{track:i}=e,r=t.id===lk?Zb.MAIN:Zb.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=Zb.AUDIO;i.kind===Zb.VIDEO&&(n=r===Zb.MAIN?Zb.VIDEO:Zb.AUXILIARY);let o=this.remoteAudioTrack;n===Zb.VIDEO?o=this.remoteVideoTrack:n===Zb.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}addRRTRLine(e){let t=e.split("\r\n"),i=new Map;t.forEach(((e,r)=>{/^a=rtcp-fb:/.test(e)&&t[r+1]&&!/^a=rtcp-fb:/.test(t[r+1])&&i.set(r+1,"".concat(e.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))}));let r=[...i];for(let n=0;n<r.length;n++){let[e,i]=r[n];t.splice(e+n,0,i)}return t.join("\r\n")}addSPSDescription(e){let t=AU(e);return t.media.forEach((e=>{e.type===Zb.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),RU(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],i=AU(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),RU(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return ib(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===yk.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===yk.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(bb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(bb.message," ").concat(JSON.stringify(this.muteState))),new fb({code:mb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):bb}}))}unsubscribe(e){return ib(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:r}=e;return function*(){if("CONNECTED"===t._currentState&&("main"===r&&!t.isMainStreamSubscribed||"auxiliary"===r&&!t.isAuxStreamSubscribed))return void t._log.info("".concat(r," stream already unsubscribed"));let e=qC({},t.subscribeState);i.forEach((t=>{switch(t.mediaType){case 1:e.audio=!1;break;case 4:e.video=!1;break;case 8:e.smallVideo=!1;break;case 2:e.auxiliary=!1}}));let n="subscribe_change";Object.values(e).find((e=>!0===e))||(n="unsubscribe"),t._log.info("".concat("unsubscribe"===n?n:"subscribe"," ").concat(r," [").concat(CU(e),"]")),yield t.sendSubscription(n,e),"unsubscribe"===n&&(t.closePeerConnection(),t.emitConnectionStateChangedEvent("DISCONNECTED"))}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=XV,n=HV.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=$V,n=HV.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:r,data:i,responseCommand:n,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new fb({code:i.code,message:KN({key:oD.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return ib(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(Rk){throw e.closePeerConnection(!0),Rk}}()}))}exchangeSDP(e){return ib(this,null,(function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:i}=this._peerConnection.localDescription,r={type:t,sdp:i,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:QV,commandDesc:"exchange sdp",data:r,responseCommand:HV.SUBSCRIBE_RESULT,timeout:Nk});if(!this._peerConnection){let e=new fb({code:mb.INVALID_OPERATION,message:KN({key:oD.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(Rk){throw this._isSDPExchanging=!1,Rk}}))}createOffer(){return ib(this,null,(function*(){let e={voiceActivityDetection:!1};YO()&&this._sdpSemantics===wk?(this._peerConnection.addTransceiver(Zb.AUDIO,{direction:ek.RECVONLY}),this._peerConnection.addTransceiver(Zb.VIDEO,{direction:ek.RECVONLY}),this._peerConnection.addTransceiver(Zb.VIDEO,{direction:ek.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield PO();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=AU(e);return t.media.forEach((e=>{var t,i;if(e.type===Zb.VIDEO){let r=new Set;e.rtp.forEach((e=>{let{payload:t,codec:i}=e;return"H264"===i&&r.add(t)})),e.fmtp.forEach((e=>{let{payload:t,config:i}=e,n=i.match(/apt=(\d+)/);n&&n[1]&&r.has(Number(n[1]))&&r.add(t)}));let n=e=>{let{payload:t}=e;return!r.has(t)};e.rtp=e.rtp.filter(n),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=null==(i=e.payloads)?void 0:i.split(" ").filter((e=>!r.has(Number(e)))).join(" ")}})),RU(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=AU(e);return t.media.forEach((e=>{e.type===Zb.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),RU(t)}(t.sdp),this._sdpSemantics===wk&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)}))}onSubscribeResult(e){return ib(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===Pk)throw new fb({code:mb.NOT_SUPPORTED_H264,message:KN({key:oD.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new fb({code:t,message:KN({key:oD.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(n)),yield this._peerConnection.setRemoteDescription({type:r,sdp:n}),this.updateSSRC(n)}catch(o){throw this._log.error(o),o}}))}updateSSRC(e){try{AU(e).media.forEach((e=>{if(e.ssrcs)if(e.type===Zb.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(lk)}));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(lk)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(dk)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(Rk){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return ib(this,null,(function*(){if(!(tb(bU.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(Rk){let t=bw(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}},kU=bU;ZC([rL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this._emitter.off("closed",n),r(new fb({code:mb.API_CALL_ABORTED,message:KN({key:oD.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],kU.prototype,"subscribe",1),ZC([iL(SU.prototype.afterConnect),tL(SU.prototype.beforeConnect)],kU.prototype,"connect",1);var DU=kU,NU={voiceActivityDetection:!1},wU=class extends SU{constructor(e){super(YC(qC({},e),{isUplink:!0})),eb(this,"localMainAudioTrack",null),eb(this,"localMainVideoTrack",null),eb(this,"localAuxAudioTrack",null),eb(this,"localAuxVideoTrack",null),eb(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),eb(this,"_isPublishingAux",!1),eb(this,"_publishingLocalAudioTrack"),eb(this,"_publishingLocalVideoTrack"),eb(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}),eb(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(qO()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(i=o[2])||!i.track),n.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((e=>{e.track&&(e.track.kind===Zb.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return ib(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){let e;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),r&&(t._publishingLocalVideoTrack=r),t._isPublishingAux=n,r&&!n&&r.small&&(e=t._room.videoManager.smallTrack),t.sendMediaSettings(),YO()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:e,isAuxiliary:n}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:r,smallTrack:e}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,n?(r&&(t.localAuxVideoTrack=r),i&&(t.localAuxAudioTrack=i)):(r&&(t.localMainVideoTrack=r),i&&(t.localMainAudioTrack=i)),t.installTrackMuteEvents(i,r),t.sendMutedFlag()}()}))}publishByTransceiver(e){return ib(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n,isAuxiliary:o}=e;return function*(){t._log.info("publish by transceiver");let e=new MediaStream,s=null==r?void 0:r.outMediaTrack,a=null==i?void 0:i.outMediaTrack;a&&e.addTrack(a),s&&e.addTrack(s);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||Zb.AUDIO,{direction:ek.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?Zb.VIDEO:s||Zb.VIDEO,{direction:ek.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||Zb.VIDEO,{direction:ek.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||Zb.VIDEO,{direction:ek.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:Zb.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:Zb.VIDEO,videoType:o?Zb.AUXILIARY:Zb.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:Zb.VIDEO,videoType:Zb.SMALL}),e.push(2))}yield t.setTransceiverDirection(ek.SENDONLY,e),yield t.doPublishChange(),null==r||r.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),null==r||r.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()}))}publishByAddTrack(e){return ib(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n}=e;return function*(){t._log.info("publish by addtrack");let e=null==r?void 0:r.outMediaTrack,o=null==i?void 0:i.outMediaTrack;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return i&&o&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(r)));let s=new MediaStream;if(o&&s.addTrack(o),e&&s.addTrack(e),o&&t._peerConnection.addTrack(o,s),e&&(t._peerConnection.addTrack(e,s),n)){let e=new MediaStream;e.addTrack(n),t._peerConnection.addTrack(n,e)}yield t.connect()}()}))}enableSmall(e){return ib(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(ek.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ek.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 ib(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!qO())return i&&i.outMediaTrack&&!r&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):r&&r.outMediaTrack&&!i&&t.localMainAudioTrack?(yield t.removeTrack(r),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),void t.emitConnectionStateChangedEvent("DISCONNECTED",r));let e=r&&r===t.localAuxVideoTrack,n=null==r?void 0:r.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(yield o[0].replaceTrack(null),s.push(0),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=YC(qC({},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=YC(qC({},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(ek.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return ib(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:qV,data:t,responseCommand:HV.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:YV,commandDesc:"unpublish",responseCommand:HV.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===mb.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),eP){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*r.profile.bitrate,r.small&&(this._mediaSettings.smallVideoWidth=r.small.width,this._mediaSettings.smallVideoHeight=r.small.height,this._mediaSettings.smallVideoFps=r.small.frameRate,this._mediaSettings.smallVideoBps=1e3*r.small.bitrate)}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*n.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),r&&r.outMediaTrack&&(this._mediaSettings.videoWidth=r.profile.width,this._mediaSettings.videoHeight=r.profile.height,this._mediaSettings.videoFps=r.profile.frameRate,this._mediaSettings.videoBps=1e3*r.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:aU,data:this._mediaSettings,responseCommand:HV.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return ib(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Zb.AUXILIARY:Zb.MAIN," stream")),YO()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return ib(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Zb.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),1===n&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ek.INACTIVE&&(yield this.setTransceiverDirection(ek.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return ib(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;qO()&&this._peerConnection.getTransceivers().findIndex((e=>"stopped"===e.direction))>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let i=this._peerConnection.getSenders().find((e=>e.track&&e.track.kind===t.kind));if(i&&i.track){this._log.warn("sender already exists, remove sender first");let e=i.track;this.removeSender(i),yield this.updateOffer("remove",e)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===Zb.VIDEO&&e instanceof TL&&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===Ok||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=AU(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===Zb.VIDEO)return!0;return!1}removeSender(e){let t=null;qO()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&Dw(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return ib(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?Zb.AUXILIARY:Zb.MAIN," stream")),YO()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return ib(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Zb.AUDIO)yield i[0].sender.replaceTrack(null);else{let r=t?3:1;yield i[r].sender.replaceTrack(null),1===r&&e.small&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(ek.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return ib(this,null,(function*(){if(!ID)return;let i=!1,r=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let n=this._peerConnection.getTransceivers();if(t.forEach((t=>{n[t].direction!==e&&(n[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(ek.INACTIVE,"|").concat(ek.RECVONLY,"|").concat(ek.SENDONLY,")")))&&o++,t.includes(o)){if(e===ek.INACTIVE&&i.includes("a=".concat(ek.RECVONLY)))return r=!0,"a=".concat(e);if(e===ek.SENDONLY&&i.includes("a=".concat(ek.INACTIVE)))return r=!0,"a=".concat(ek.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}removeTrackBySender(e){return ib(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===Zb.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===Zb.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===Zb.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return ib(this,null,(function*(){var t;let i,r=null==(t=this._peerConnection)?void 0:t.getSenders();if(!r||0===r.length||!e.mediaTrack)return!1;if(i=YO()?e.kind===Zb.AUDIO?r[0]:r[1]:r.find((t=>t.track&&t.track.kind===e.kind)),!i)return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(e.kind," track on ").concat(n?Zb.AUXILIARY:Zb.MAIN," stream")),e.kind===Zb.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===Zb.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack)),!0}))}updateOffer(e,t){return ib(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(NU);ID&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(i);let r=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===Zb.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:r,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(n.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:jV,data:n,responseCommand:HV.UPDATE_OFFER_RESULT,timeout:Dk,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(Cb){throw this._log.error(Cb),Cb}}))}setBandwidth(e){return ib(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!ZO())return o?r===Zb.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(YO()){let t=0;r===Zb.VIDEO&&(t=n===Zb.SMALL?2:n===Zb.AUXILIARY?3:1),e=s[t]}else e=s.find((e=>e.track&&e.track.kind===r));if(e){let s=e.getParameters();(!s.encodings||0===s.encodings.length)&&(s.encodings=[{}]),s.encodings[0].maxBitrate=1e3*i;try{return yield e.setParameters(s),t._log.info("".concat(n||"").concat(r," bandwidth ").concat(i," kbps")),o}catch(a){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(a)),o)return r===Zb.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";ID&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===Zb.SMALL?n=1:i===Zb.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(o+=1,o===n?"".concat(e,"b=").concat(r,":").concat(t,"\r\n"):e)))}updateAudioBandwidthRestriction(e,t){let i="AS";return ID&&(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 ib(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(Rb){throw this.closePeerConnection(!0),this.uninstallEvents(),Rb}}))}exchangeSDP(){return ib(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(Rb){throw Rb}}))}createOffer(){return ib(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(NU);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(Rb){throw Rb}}))}doExchangeSDP(){let e={command:KV,responseCommand:HV.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof SL||this.localAuxVideoTrack instanceof SL,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then((e=>{let{code:t,message:i,data:r}=e.data;return 0===t?this.acceptAnswer(r):this.checkPublishResultCode(t,i)}))}setSDPDirection(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"all",r=AU(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),RU(r)}acceptAnswer(e){return ib(this,null,(function*(){var t,i,r,n,o;try{let s;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let e=(null==(t=this._publishingLocalVideoTrack)?void 0:t.profile.bitrate)||(null==(i=this.localMainVideoTrack)?void 0:i.profile.bitrate),o=(null==(r=this._publishingLocalAudioTrack)?void 0:r.profile.bitrate)||(null==(n=this.localMainAudioTrack)?void 0:n.profile.bitrate);if(e){let t=this._isPublishingAux?Zb.AUXILIARY:Zb.BIG;s=yield this.setBandwidth({bandwidth:e,type:Zb.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:Zb.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:Zb.VIDEO,videoType:Zb.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this._peerConnection.setRemoteDescription(a),this._log.debug("accepted answer: ".concat(s))}catch(yF){throw this._log.error("failed to accept remote answer ".concat(yF)),yF}}))}sendMutedFlag(e){var t,i,r;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let n={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(i=this.localMainVideoTrack)||!i.muted),auxVideo:!(null==(r=this.localAuxVideoTrack)||!r.muted)};this._log.info("send muted state: ".concat(JSON.stringify(n))),this._signalChannel.send(zV,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return ib(this,null,(function*(){if(!(tb(wU.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:YV,responseCommand:HV.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(Rk){let t=bw(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)&&QN.emit(fO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{AU(e).media.forEach(((e,t)=>{if(e.type===Zb.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===Ok&&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(Rk){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Zb.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Zb.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Zb.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Zb.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Zb.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Pk?(this._log.error(sD.NOT_SUPPORTED_H264ENCODE),new fb({code:mb.NOT_SUPPORTED_H264,message:KN({key:oD.NOT_SUPPORTED_H264ENCODE})})):new fb({code:mb.UNKNOWN,message:KN({key:oD.SIGNAL_RESPONSE_FAILED,data:{signalResponse:HV.PUBLISH_RESULT,code:e,message:t}})})}},OU=wU;ZC([rL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this._emitter.off("closed",n),r(new fb({code:mb.API_CALL_ABORTED,message:KN({key:oD.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],OU.prototype,"publish",1),ZC([iL(SU.prototype.afterConnect),tL(SU.prototype.beforeConnect)],OU.prototype,"connect",1);var PU=OU,MU=class{constructor(e,t){this.room=e,eb(this,"_log"),eb(this,"_prevReportTime",0),eb(this,"_prevReport",{}),eb(this,"_prevStats",null),eb(this,"_prevEncoderImplementation",""),eb(this,"_prevAuxEncoderImpl",""),eb(this,"_prevQualityLimitationReason",""),eb(this,"_prevAuxQualityLimitationReason",""),eb(this,"_prevDecoderImplementationMap",new Map),eb(this,"totalBytesSent",0),eb(this,"totalBytesReceived",0),eb(this,"_spcStats",null),this._log=t}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return ib(this,null,(function*(){let t={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},i=e.getPeerConnection(),r=e.getSSRC();if(i)try{if((this._spcStats||(yield i.getStats())).forEach((i=>{var n,o,s;let a,c;if("outbound-rtp"===i.type)if((i.mediaType||i.kind)===Zb.VIDEO){if(i.ssrc===r.video?(a=Zb.VIDEO,c=e.localMainVideoTrack):i.ssrc===r.small?a=Zb.SMALL:i.ssrc===r.auxiliary&&(c=e.localAuxVideoTrack,a=Zb.AUXILIARY),!a)return;if(t[a].bytesSent=i.bytesSent,t[a].packetsSent=i.packetsSent,t[a].framesEncoded=i.framesEncoded,Nw(i.keyFramesEncoded)||(t[a].keyFramesEncoded=i.keyFramesEncoded),Nw(i.nackCount)||(t[a].nackCount=i.nackCount),Nw(i.pliCount)||(t[a].pliCount=i.pliCount),Nw(i.retransmittedPacketsSent)||(t[a].retransmittedPacketsSent=i.retransmittedPacketsSent),Nw(i.totalEncodeTime)||(t[a].totalEncodeTime=i.totalEncodeTime),Nw(i.totalPacketSendDelay)||(t[a].totalPacketSendDelay=i.totalPacketSendDelay),!Nw(i.encoderImplementation)&&(a===Zb.VIDEO&&this._prevEncoderImplementation!==i.encoderImplementation||a===Zb.AUXILIARY&&this._prevAuxEncoderImpl!==i.encoderImplementation)){let t=2,r=this._prevEncoderImplementation;a===Zb.AUXILIARY&&(t=7,r=this._prevAuxEncoderImpl),QN.emit("262",{userId:e.userId,streamType:t,prevImplementation:r,implementation:i.encoderImplementation,codec:e.videoCodec,isHWCodec:i.powerEfficientEncoder}),this[a===Zb.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=i.encoderImplementation,this._log.info("".concat(a===Zb.AUXILIARY?"aux ":"","encoderImplementation change to ").concat(i.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(i.powerEfficientEncoder))}i.ssrc===r.video?!Nw(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(i.qualityLimitationReason)),QN.emit("263",{userId:e.userId,reason:i.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:null==(n=e.localMainVideoTrack)?void 0:n.isQosClearFirst}),this._prevQualityLimitationReason=i.qualityLimitationReason):i.ssrc===r.auxiliary&&!Nw(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevAuxQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(i.qualityLimitationReason)),QN.emit("263",{userId:e.userId,reason:i.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(o=e.localAuxVideoTrack)?void 0:o.isQosClearFirst}),this._prevAuxQualityLimitationReason=i.qualityLimitationReason)}else t.audio.bytesSent=i.bytesSent,t.audio.packetsSent=i.packetsSent;else"candidate-pair"===i.type?FO(i)&&Ow(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesSent=i.bytesSent):"media-source"===i.type&&(i.kind===Zb.AUDIO?(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0,i.echoReturnLoss,i.totalSamplesDuration&&(t.audio.totalSamplesDuration=i.totalSamplesDuration)):i.kind===Zb.VIDEO&&(i.trackIdentifier===e.getVideoTrackId(Zb.VIDEO)?t.video.fpsCapture=i.framesPerSecond:i.trackIdentifier===e.getVideoTrackId(Zb.AUXILIARY)?t.auxiliary.fpsCapture=i.framesPerSecond:t.small.fpsCapture=i.framesPerSecond));if(!Nw(i.audioLevel)&&(null==(s=e.localMainAudioTrack)?void 0:s.mediaTrack)&&i.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(t.audio.audioLevel=i.audioLevel||0),!Nw(i.frameWidth)){let n=Zb.SMALL;i.trackIdentifier===e.getVideoTrackId(Zb.VIDEO)||i.ssrc===r.video?n=Zb.VIDEO:(i.trackIdentifier===e.getVideoTrackId(Zb.AUXILIARY)||i.ssrc===r.auxiliary)&&(n=Zb.AUXILIARY),t[n].frameWidth=i.frameWidth,t[n].frameHeight=i.frameHeight,t[n].framesSent=i.framesSent}})),e.localMainAudioTrack){let i=e.localMainAudioTrack.getInternalAudioLevel();t.audio.micAudioLevel=i,0===t.audio.audioLevel&&(t.audio.audioLevel=i)}this.totalBytesSent||(this.totalBytesSent+=t.audio.bytesSent+t.video.bytesSent+t.auxiliary.bytesSent),Object.keys(t).forEach((i=>{i===Zb.AUDIO?e.localMainAudioTrack&&(e.localMainAudioTrack.stat=t[i]):i===Zb.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=t[i]):i===Zb.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=t[i])}))}catch(n){this._log.warn("failed to getStats on sender connection ".concat(n))}return t}))}getReceiverStats(e){return ib(this,null,(function*(){let t={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},i=e.getPeerConnection();if(i)try{let{ssrc:r}=e,{muteState:n,subscribeState:o}=e;(this._spcStats||(yield i.getStats())).forEach((i=>{if("inbound-rtp"===i.type){let s=(i.mediaType||i.kind)===Zb.AUDIO;if(s){if(i.ssrc!==r.audio||!n.hasAudio)return;t.audio.packetsReceived=i.packetsReceived,t.audio.bytesReceived=i.bytesReceived,t.audio.packetsLost=i.packetsLost,i.insertedSamplesForDeceleration&&(t.audio.insertedSamplesForDeceleration=i.insertedSamplesForDeceleration),i.removedSamplesForAcceleration&&(t.audio.removedSamplesForAcceleration=i.removedSamplesForAcceleration),i.totalSamplesDuration&&(t.audio.totalSamplesDuration=i.totalSamplesDuration),i.totalSamplesReceived&&(t.audio.totalSamplesReceived=i.totalSamplesReceived),i.concealedSamples&&(t.audio.concealedSamples=i.concealedSamples);let{remoteAudioTrack:o}=e;o.stat.packetsReceived=i.packetsReceived,o.stat.bytesReceived=i.bytesReceived,o.stat.packetsLost=i.packetsLost,t.audio.p2pDelay=o.stat.end2EndDelay,t.hasAudio=!0}else{if(ID&&0===i.bytesReceived)return;let s;i.ssrc===r.video&&n.hasVideo&&(t.video.packetsReceived=i.packetsReceived,t.video.bytesReceived=i.bytesReceived,t.video.packetsLost=i.packetsLost,t.video.framesReceived=i.framesReceived,t.video.framesDecoded=i.framesDecoded,t.video.fpsDecoded=i.framesPerSecond,t.hasVideo=!0,s=e.remoteVideoTrack,n.hasSmall&&o.smallVideo&&(t.isSmallSubscribed=!0),i.decoderImplementation&&(!this._prevDecoderImplementationMap.has(t.userId)||this._prevDecoderImplementationMap.get(t.userId)!==i.decoderImplementation)&&(this._log.info("".concat(t.userId," decoderImplementation change to ").concat(i.decoderImplementation," HWDecoder: ").concat(i.powerEfficientDecoder)),QN.emit("262",{userId:this.room.userId,remoteUserId:t.userId,prevImplementation:this._prevDecoderImplementationMap.get(t.userId),implementation:i.decoderImplementation,codec:e.videoCodec,isHWCodec:i.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(t.userId,i.decoderImplementation))),i.ssrc===r.auxiliary&&n.hasAuxiliary&&(t.auxiliary.packetsReceived=i.packetsReceived,t.auxiliary.bytesReceived=i.bytesReceived,t.auxiliary.packetsLost=i.packetsLost,t.auxiliary.framesReceived=i.framesReceived,t.auxiliary.framesDecoded=i.framesDecoded,t.auxiliary.fpsDecoded=i.framesPerSecond,s=e.remoteAuxiliaryTrack,t.hasAuxiliary=!0),s&&(s.stat.packetsReceived=i.packetsReceived,s.stat.bytesReceived=i.bytesReceived,s.stat.packetsLost=i.packetsLost,s.stat.framesReceived=i.framesReceived,s.stat.framesDecoded=i.framesDecoded,i.jitterBufferDelay&&(s.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)))}i.jitterBufferDelay&&(s?(t.audio.totalJitter=i.jitterBufferDelay,t.audio.totalJitterCount=i.jitterBufferEmittedCount):i.ssrc===r.video&&n.hasVideo?(t.video.totalJitter=i.jitterBufferDelay,t.video.totalJitterCount=i.jitterBufferEmittedCount):i.ssrc===r.auxiliary&&n.hasAuxiliary&&(t.auxiliary.totalJitter=i.jitterBufferDelay,t.auxiliary.totalJitterCount=i.jitterBufferEmittedCount))}else"candidate-pair"===i.type&&FO(i)&&Ow(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesReceived=i.bytesReceived);Nw(i.frameWidth)||((i.trackIdentifier===e.getMainStreamVideoTrackId()||i.ssrc===r.video)&&(t.video.frameWidth=i.frameWidth,t.video.frameHeight=i.frameHeight,e.remoteVideoTrack.stat.frameWidth=i.frameWidth,e.remoteVideoTrack.stat.frameHeight=i.frameHeight),(i.trackIdentifier===e.getAuxStreamVideoTrackId()||i.ssrc===r.auxiliary)&&(t.auxiliary.frameWidth=i.frameWidth,t.auxiliary.frameHeight=i.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=i.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=i.frameHeight)),!Nw(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(Cb){this._log.warn("failed to getStats on receiver connection ".concat(Cb))}return t}))}getStats(e,t){return ib(this,null,(function*(){let i={},r=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:i,receiverStats:r};let t=Ww(),n=yield e.getStats(),o=Ww();o-t>2e3&&this._log.warn("getStats cost ".concat(o-t,"ms"));let s=[],a=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);n.forEach((e=>a.has(e.type)&&s.push(e))),this._spcStats=s}e&&(i=yield this.getSenderStats(e));for(let[e,n]of t){let e=yield this.getReceiverStats(n);r.push(e)}return{senderStats:i,receiverStats:r}}))}getDifferenceValue(e,t){if(YM(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r}=e;var n;if(!YM(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*nD,uint32_audio_energy:1e6*(t.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(e.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*nD),t.senderStats.audio.totalSamplesDuration&&(i.msg_device_info.uint32_audio_capture_cost=t.senderStats.audio.totalSamplesDuration);let r=[];if(t.senderStats.video.bytesSent){let e={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};r.push(e)}if(t.senderStats.small.bytesSent){let e={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};r.push(e)}if(t.senderStats.auxiliary.bytesSent){let e={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};r.push(e)}let n={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:e,msg_video_status:r,msg_network_status:n}}let{statInterval:o}=this;i.msg_down_stream_info=[],t.receiverStats.forEach((e=>{let t={msg_user_info:{str_identifier:e.userId,uint64_tinyid:e.tinyId},msg_network_status:{uint32_rtt:e.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(e.hasAudio){let i={uint32_audio_p2p_delay:e.audio.p2pDelay,uint32_audio_cache_ms:e.audio.totalJitter,uint32_audio_cache_ms_count:e.audio.totalJitterCount,uint32_audio_codec_bitrate:e.audio.bytesReceived,uint32_audio_total_bitrate:e.audio.bytesReceived,uint32_audio_level:1e8*e.audio.audioLevel,uint32_audio_energy:1e6*e.audio.totalAudioEnergy,uint32_audio_receive:e.audio.packetsReceived,uint32_audio_origin_lost:e.audio.packetsLost};t.msg_audio_status=i}if(e.hasVideo){let i=r.get("".concat(e.userId,"_").concat(uk)),n=i?i.duration:0,o={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.video.framesDecoded,uint32_video_cache_ms:e.video.totalJitter,uint32_video_cache_ms_count:e.video.totalJitterCount};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=r.get("".concat(e.userId,"_").concat(hk)),n=i?i.duration:0,o={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.auxiliary.framesDecoded,uint32_video_cache_ms:e.auxiliary.totalJitter,uint32_video_cache_ms_count:e.auxiliary.totalJitterCount};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let s=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(i)),this._prevStats=JSON.parse(JSON.stringify(t)),i.msg_up_stream_info.msg_audio_status&&s.msg_up_stream_info.msg_audio_status){let e=s.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let r=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*r/o),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}null!=(n=s.msg_device_info)&&n.uint32_audio_capture_cost?i.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(s.msg_device_info.uint32_audio_capture_cost,i.msg_device_info.uint32_audio_capture_cost)/o):delete i.msg_device_info.uint32_audio_capture_cost}let c=s.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=c.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type));if(!t||0===t.uint32_video_codec_bitrate)return e.uint32_video_codec_bitrate=0,e.uint32_video_enc_fps=0,void(e.uint32_video_codec_fps=0);let r=0,n=0,s=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(r=t.uint32_video_codec_bitrate,n=t.uint32_video_enc_fps,s=t.uint32_video_codec_fps);let a=this.getDifferenceValue(r,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*a/o),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(n,e.uint32_video_enc_fps)/o),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(s,e.uint32_video_codec_fps)/o),ZD&&115===gN()&&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),Nw(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),Nw(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),Nw(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),Nw(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),Nw(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/o)),Nw(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/o))}));let l=s.msg_down_stream_info;i.msg_down_stream_info=i.msg_down_stream_info.filter((e=>l.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid))));let d=i.msg_down_stream_info;return d.forEach((e=>{let t=l.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(YM(e.msg_audio_status)||YM(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,r=t.msg_audio_status,n=this.getDifferenceValue(r.uint32_audio_cache_ms_count,i.uint32_audio_cache_ms_count);delete i.uint32_audio_cache_ms_count,i.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(r.uint32_audio_cache_ms,i.uint32_audio_cache_ms)/n)||0;let s=this.room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);s&&(s.remoteAudioTrack.stat.jitterBufferDelay=i.uint32_audio_cache_ms),i.uint32_audio_origin_lost=this.getDifferenceValue(r.uint32_audio_origin_lost,i.uint32_audio_origin_lost),i.uint32_audio_receive=this.getDifferenceValue(r.uint32_audio_receive,i.uint32_audio_receive),i.uint32_audio_receive+=i.uint32_audio_origin_lost;let a=this.getDifferenceValue(r.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*a/o),i.uint32_audio_total_bitrate=Math.round(8*a/o)}if(e.msg_video_status&&t.msg_video_status){let i=t.msg_video_status;e.msg_video_status=e.msg_video_status.filter((e=>i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)))),e.msg_video_status.forEach((e=>{let t=i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)),r=t.uint32_video_receive,n=t.uint32_video_origin_lost,s=t.uint32_video_codec_bitrate,a=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(n,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(r,e.uint32_video_receive)+e.uint32_video_origin_lost;let l=this.getDifferenceValue(s,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/o);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/o),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/o);let u=this.getDifferenceValue(t.uint32_video_cache_ms_count,e.uint32_video_cache_ms_count);delete e.uint32_video_cache_ms_count,e.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(t.uint32_video_cache_ms,e.uint32_video_cache_ms)/u)||0}))}})),a&&t.receiverStats.forEach((e=>{if(e.audio.concealedSamples&&e.audio.totalSamplesReceived){let t=a.receiverStats.find((t=>t.userId===e.userId));if(t&&t.audio.concealedSamples&&t.audio.totalSamplesReceived){let i=e.audio.concealedSamples-t.audio.concealedSamples,r=e.audio.totalSamplesReceived-t.audio.totalSamplesReceived,n=Math.floor(i/r*1e3*o);if(n>o/5){let t=d.find((t=>t.msg_user_info.str_identifier===e.userId));t&&(t.msg_audio_status.uint32_audio_block_time=n)}}}})),i}getStatsReport(e){return ib(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:r,freezeMap:n}=e;return function*(){let e={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield t.getStats(i,r);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:n}),t._prevReportTime=Date.now(),e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},LU=$C(rb()),xU=class extends LU.default{constructor(e){let{signalChannel:t,room:i}=e;super(),eb(this,"_room"),eb(this,"_signalChannel"),eb(this,"_log"),eb(this,"_uplinkRTT",0),eb(this,"_uplinkLoss",0),eb(this,"_downlinkRTT",0),eb(this,"_downlinkLoss",0),eb(this,"_downlinkPrevStatMap",new Map),eb(this,"_downlinkLossAndRTTMap",new Map),eb(this,"_interval",-1),eb(this,"_uplinkNetworkQuality",0),eb(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=TO.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(HV.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(LV,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,i;if(0!==e.data.code)return;let r=e.data.data;if(r.delay&&this.updateDelay(r.delay),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this._uplinkLoss=0,void(this._uplinkRTT=0);let n=null==(i=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:i.getPeerConnection();if(n&&this.isPeerConnectionDisconnected(n))return this.uplinkNetworkQuality=6,this._uplinkLoss=0,void(this._uplinkRTT=0);let o=r.expectAudPkg+r.expectVidPkg,s=r.recvAudPkg+r.recvVidPkg,a=o-s;0===o&&0===s||(this._uplinkLoss=a<=0?0:Math.round(a/o*100),this._uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return ib(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)===yk.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let n=0;n<t.length;n++){let e=t[n].getPeerConnection();if(!e)return;let{rtt:i,totalPacketsLost:r,totalPacketsReceived:o}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o});continue}let s=0,a=this._downlinkPrevStatMap.get(e),c=r-a.totalPacketsLost,l=o-a.totalPacketsReceived;s=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:s,userId:t[n].getUserId(),audioDelay:t[n].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[n].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach((e=>{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return;let{rtt:i,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=i,this._downlinkLoss=r,this.downlinkNetworkQuality=this.getNetworkQuality(r,i)}))}getStat(e){return ib(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!zO())return t;let i=e.getReceivers();try{for(let e=0;e<i.length;e++)(yield i[e].getStats()).forEach((e=>{"candidate-pair"===e.type&&Ow(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===Zb.AUDIO||e.mediaType===Zb.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return t}catch(r){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){"DISCONNECTED"===e.state?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):"CONNECTED"===e.state&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(e){let{state:t}=e;"DISCONNECTED"===t?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):"CONNECTED"===t&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==yk.DISCONNECTED&&e.connectionState!==yk.FAILED&&e.connectionState!==yk.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){-1===this._interval?(this._log.debug("start network quality calculating"),this._interval=RP.run(Xk,(()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];QN.emit(fO.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(xU.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss})}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.debug("stopped"),-1!==this._interval&&(RP.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach((e=>{let{srcTinyId:i,videoDelay:r,audioDelay:n}=e,o=t.get(i);if(o){let e=this._room.remotePublishedUserMap.get(o);null==e||e.setDelay({videoDelay:r,audioDelay:n})}}))}},VU=xU;eb(VU,"EVENT_NETWORK_QUALITY","0");var UU=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._eventMap=new Map,this._captureCostSum=0,this._captureCostCount=0,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=TO.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&Dw(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];let o=t.apply(i,r);return Uw(o)?o.catch((e=>TO.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(Rk){TO.error("".concat(t.name,"() error observed ").concat(Rk))}}}({fn:this[e],context:this}))})),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Ib,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:"live"===this._room.scene?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,UN().then((e=>{this._basicInfo.string_os_version=jN(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),QN.on(e,t),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",(()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId}))),this.addEvent(fO.JOIN_START,this.handleJoinStart).addEvent(fO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(fO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(fO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(fO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(fO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(fO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(fO.JOIN_FAILED,this.handleJoinFailed).addEvent(fO.LEAVE_START,this.handleLeaveStart).addEvent(fO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(fO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(fO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(fO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(fO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(fO.PUBLISH_START,this.handlePublishStart).addEvent(fO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(fO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(fO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(fO.PLAY_TRACK_START,this.handlePlayStart).addEvent(fO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(fO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!Vw(t)||!this.hitTest(t.room)||"PLAYING"===i&&(r===Zb.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(fO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(fO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(fO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(fO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let n=i.hasAudio||i.hasVideo||i.hasSmall,o=i.hasAuxiliary,s=r.hasAudio||r.hasVideo||r.hasSmall,a=r.hasAuxiliary;!n&&s&&this.handleRemoteStreamAdded(r.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")})).addEvent(fO.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)=>QN.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),RP.clearTask(this._intervalId)}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(e){this.hitTest(e.room)&&(0===this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_start_time=Date.now()),e.params&&(Nw(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),Nw(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),Nw(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(e){let{room:t,detailCost:i}=e;if(this.hitTest(t)&&i){let{totalCost:e,local:t,dns:r,tcp:n,tls:o,request:s,response:a}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=r,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=o,this._pathJoinRoom.int32_schedule_request=s,this._pathJoinRoom.int32_schedule_response=a}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(e){let{room:t,error:i}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=i instanceof fb?Number(i.getExtraCode()||i.getCode()):mb.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}handleJoinFailed(e){let{room:t,error:i}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=i.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout((()=>{this.report()})))}handleReceivedPublishUserList(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;!this.hitTest(t)||0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(e,t){var i;let r="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(r)){let n={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:YC(qC({},BU),{msg_user_info:new HU({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};n.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(r,n)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:r,subscribeState:n}=e;if(!this.hitTest(t))return;let{userId:o,tinyId:s,role:a}=i,c=new HU({userId:o,tinyId:s,role:"anchor"===a?20:21}),l=Date.now(),d="".concat(o,"_").concat(r),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=l),"main"===r?(i.muteState.hasVideo&&(n.video||n.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),i.muteState.hasAudio&&n.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):i.muteState.hasAuxiliary&&n.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l})}handleSubscribed(e){let{room:t,remotePublishedUser:i,streamType:r}=e;if(this.hitTest(t)){let e="".concat(i.userId,"_").concat(r),t=this._remoteStreamStatMap.get(e);t&&0===t.subscribedTime&&(t.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!Vw(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._remoteStreamStatMap.get(i);0===(null==r?void 0:r.playStreamTime)&&(r.playStreamTime=Date.now())}handleVideoLoadedData(e){let{track:t}=e;if(!Vw(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._pathMainVideoMap.get(i);r&&0===r.statsToReport.uint64_combine_first_frame_time&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=Date.now(),r=this._pathMainVideoMap.get(t),n=this._remoteStreamStatMap.get(t);if(r&&(0===r.statsToReport.uint64_render_first_frame_time&&(r.statsToReport.uint64_render_first_frame_time=i),n)){let{statsToReport:e,playStreamTime:t,subscribedTime:o}=n;0===e.uint32_video_render_first&&t-o<=100&&(e.uint32_video_render_first=i-r.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(t);if(o&&n){let{statsToReport:e,playStreamTime:t,subscribedTime:r}=n;0===e.uint32_video_render_first&&t-r<=100&&(e.uint32_video_render_first=i-o.sendSubscribeCMDTime)}}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=this._pathMainAudioMap.get(t);i&&0===i.statsToReport.uint64_play_first_frame_time&&(i.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(e){this.hitTest(e.room)&&(this._networkQuality.totalUplinkLoss+=e.uplink.loss,this._networkQuality.totalUplinkRTT+=e.uplink.rtt,this._networkQuality.count++,e.downlinks.forEach((e=>{let{rtt:t,loss:i,userId:r,videoDelay:n,audioDelay:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(s)s.totalRTT+=t,s.totalLoss+=i,n&&(s.totalVideoDelay=(s.totalVideoDelay||0)+n,s.videoDelayCount=(s.videoDelayCount||0)+1),o&&(s.totalAudioDelay=(s.totalAudioDelay||0)+o,s.audioDelayCount=(s.audioDelayCount||0)+1),s.count++;else{let e,s,a,c;n&&(s=n,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_device_info:t,msg_up_stream_info:i,msg_down_stream_info:r}=e.report;if(i.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:t,uint32_video_width:r,uint32_video_height:n}=i.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=t,this._localStreamStat.totalVideoWidth+=r,this._localStreamStat.totalVideoHeight+=n,this._localStreamStat.videoCount++}if(i.msg_audio_status){let{uint32_audio_level:e}=i.msg_audio_status;Math.floor(e/nD*100)>0&&(this._localStreamStat.totalAudioLevel+=e/nD,this._localStreamStat.audioLevelCount++)}r.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:r}=e,n=t.str_identifier,o=this._room.remotePublishedUserMap.get(n);if(r.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,r="".concat(n,"_").concat(t?"main":"auxiliary"),s=this._remoteStreamStatMap.get(r);if(s&&(t&&(null==o?void 0:o.remoteVideoTrack.isSubscribed)||i&&(null==o?void 0:o.remoteAuxiliaryTrack))){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*zC(10,6)))}})),i){let e="".concat(n,"_","main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&(null==o?void 0:o.remoteAudioTrack.isSubscribed)&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,o.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=o.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/nD*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/nD,t.audioLevelCount++))}})),t.uint32_audio_capture_cost&&(this._captureCostSum+=t.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart(e){let{room:t}=e;this.hitTest(t)&&0===this._localStreamStat.publishStartTime&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof fb?i.getExtraCode()||i.getCode():mb.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&rk))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&sk))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&ok))>=0}hitTest(e){return e===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach(((e,t)=>{let{userId:i}=e,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(r){let{totalLoss:t,count:i,audioDelayCount:n,videoDelayCount:o,totalAudioDelay:s,totalVideoDelay:a}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),n&&s&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(s/n),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/o))}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:n}=this._room;n&&(e.statsToReport.uint32_audio_play_time=n.getDuration(t,Zb.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,Zb.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,FU);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>FU&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+FU):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>FU&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+FU):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>FU&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+FU)}getReportData(){this._basicInfo.uint32_networkType=gw();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new HU({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Qw(this._signalInfo.relayIp),uint32_client_ip:Qw(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*zC(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map((e=>e.statsToReport)),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map((e=>e.statsToReport)),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map((e=>e.statsToReport)),uint32_info_client_ip:Qw(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return lO(e),e}report(){return ib(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(xP){this._log.warn(xP)}}))}upload(e){return ib(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=yield rD(e),r=i instanceof ArrayBuffer,n="".concat(hw(t,jb.KEY_POINT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i)),o||iD({url:n,body:i}),this.uploadKVStat(zP),this.uploadKVStat(JP)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return ib(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=YC(qC({},t.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(t);let i=yield rD(t),r="".concat(hw(+this._room.sdkAppId,jb.KV_STAT),"&gzip=").concat(+(i instanceof ArrayBuffer)),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(r,i)),n||iD({url:r,body:i})}))}};ZC([OP({settings:{timeout:500,retries:3}})],UU.prototype,"upload",1);var FU=5e3,BU={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},HU=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},jU=UU,WU=class{constructor(){eb(this,"_startTime"),eb(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=Ww())}stop(){0===this._endTime&&(this._endTime=Ww())}getDuration(){return 0===this._endTime?Ww()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},GU=class{constructor(e){eb(this,"_room",null),eb(this,"_durationMap"),eb(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(fO.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(fO.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(fO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;var n;let{userId:o}=r;if(!this.hitTest(t))return;i.hasAudio&&!r.hasAudio&&this.stopDurationItem("".concat(o,"_","main"),Zb.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_","main"),Zb.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_","auxiliary"),Zb.VIDEO);let s=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);!s||(!i.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,Zb.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,Zb.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,Zb.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>QN.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>QN.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);if(r.muteState.hasAudio&&"main"===i)if(r.remoteAudioTrack.isSubscribed){let e=new WU,t=this._durationMap.get(o);t?this.isRecording(t.audio)||t.audio.push(e):this._durationMap.set(o,{userId:n,type:i,audio:[e],video:[]})}else this.stopDurationItem(o,Zb.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let e=new WU,t=this._durationMap.get(o);t?this.isRecording(t.video)||t.video.push(e):this._durationMap.set(o,{userId:n,type:i,audio:[],video:[e]})}else this.stopDurationItem(o,Zb.VIDEO)}handleStreamStopped(e){let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);this.stopDurationItem(o,Zb.AUDIO),this.stopDurationItem(o,Zb.VIDEO)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new WU,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===Zb.AUDIO?[n]:[],video:t===Zb.AUDIO?[]:[n]})}stopDurationItem(e,t){if(this._durationMap.has(e)){let i=this._durationMap.get(e)[t].find((e=>0===e.endTime));i&&i.stop()}}hitTest(e){return this._room===e}getDuration(e,t){return this._durationMap.has(e)?this._durationMap.get(e)[t].reduce(((e,t)=>e+t.getDuration()),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},JU=class{constructor(e){eb(this,"_room"),eb(this,"_renderFreezeMap",new Map),eb(this,"_isVideoPlayingEventFiredMap",new Map),eb(this,"_dataFreezeMap",new Map),eb(this,"_monitorFreezeData",new Map),eb(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(fO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(fO.PLAY_TRACK_START,this.onPlayTrackStart).set(fO.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);this.stopDataFreeze({key:o,userId:n,type:i})})).set(fO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let{userId:n}=r;if(i.hasVideo&&!r.hasVideo){let e="main",t="".concat(r.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:n,type:e})}if(i.hasAuxiliary&&!r.hasAuxiliary){let e="auxiliary",t="".concat(r.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:n,type:e})}})).set(fO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(Vw(t)&&this.hitTest(t.room)&&n===Zb.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===Zb.MUTE?this.onVideoTrackMuted(t):r===Zb.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(fO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>QN.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>QN.off(t,e,this))),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i),n=this._dataFreezeMap.get(r),o=new WU;n?n.durationItemList.push(o):this._dataFreezeMap.set(r,{userId:t,type:i,durationItemList:[o],isFreezing(){let e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i);this.stopDataFreeze({key:r,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;!this.hitTest(t)||i.msg_down_stream_info.forEach((e=>{let t=this._room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);if(!t)return;let{userId:i,muteState:r}=t;e.msg_video_status.forEach((e=>{2===e.uint32_video_stream_type&&r.hasVideo&&!r.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"main"}),7===e.uint32_video_stream_type&&r.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"auxiliary"})}))}))}stopDataFreeze(e){let{key:t,userId:i,type:r}=e,n=this._dataFreezeMap.get(t);if(!n||!n.isFreezing())return;let o=n.durationItemList[n.durationItemList.length-1];o.stop();let s=o.getDuration();s>Lk?this._monitorFreezeData.set(t,{userId:i,type:r,duration:s}):n.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return ib(this,arguments,(function(e){var t=this;let{userId:i,fps:r,type:n}=e;return function*(){let e="".concat(i,"_").concat(n),o=t._renderFreezeMap.get(e);if(r<=2){let r=Ww();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:r,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(e,{userId:i,type:n,isFreeze:!0,freezeTimeline:[{startTime:r,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let e=o.freezeTimeline.pop();if(e){e.endTime=Ww();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!Vw(t)||!this.hitTest(t.room)||t.kind!==Zb.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()<Lk&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){let t=this._renderFreezeMap.get(e),i=0,r=0;if(t)if(t.isFreeze){let e=Ww()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;i=t.renderFreezeTotal+Math.min(e,5e3),r=t.freezeTimeline.length}else i=t.renderFreezeTotal;return{renderFreeze:i,count:r}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},zU=$C(rb(),1),KU=[1,0,0,0,1,1,0,1],qU=class extends wL{constructor(e){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),e instanceof jL)try{this.setTexBuffer(KU)}catch(Rb){e.destroy(Rb)}}draw2d(e,t,i,r,n){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let o=super.draw2d(e,t,i,r,n);return this.ctx2d.restore(),o}return!1}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}},YU=class{constructor(e,t){this.node=e,this.layout=t,eb(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}},QU=class extends wL{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0}),eb(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new YU(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 jL&&this.inputs.forEach((e=>{if(e){let t=this.layout2texCoords(e);e.positionBuffer?this.changeBufferData(e.positionBuffer,t):e.positionBuffer=this.createBuffer(t)}}))}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return super.connect(e,...i),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex((t=>(null==t?void 0:t.node)===e))]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&(t.node.useTexture(),this.draw(t.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&this.draw2d(t.node.image,t.x,t.y,t.width,t.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:i,width:r,height:n,name:o}=this,s=Date.now(),a=(e-this.lastInfo.totalFrames)/((s-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:i,width:r,height:n,timestamp:s,fps:a,name:o},qC({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 jL))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(r){}}))}},XU=class extends FL{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log}),eb(this,"ready",!1),eb(this,"_bgTexture"),eb(this,"_waterMarkTexture"),eb(this,"_lastMaskTexture"),eb(this,"_lastMaskFbo"),eb(this,"_textureValid",!1),eb(this,"_selfieTextureValid",!1),eb(this,"_selfieSegmentation"),eb(this,"wasm"),eb(this,"_prePrograme"),eb(this,"_segmentationMask"),eb(this,"_weixin",!1),t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this)),this.init(t).catch((()=>this.context.destroy(new Error("selfie_segmentation init faild"))))}init(e){return ib(this,null,(function*(){var t,i;let r=e.Wasm,n=this.context.ctx;if(this.wasm=new r.AllIn1(n),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:i,width:r,height:n}=e.waterMark;this.wasm.setWaterMark(t,i,r,n)}if(e.beautyParams){let{beauty:r,brightness:n,ruddy:o}=e.beautyParams;this.wasm.setBeauty(r,n,o,null==(t=this.context._canvas)?void 0:t.width,null==(i=this.context._canvas)?void 0:i.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.uniform1i(n.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(n.uniform1i(n.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(n.uniform1i(n.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),n.uniform1i(n.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(n.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\nuniform sampler2D u_texture;\nuniform sampler2D mask;\n\nin vec2 v_texCoord;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);\n}"),t=this.context.createShader(n.VERTEX_SHADER,"#version 300 es\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_texCoord;\nvoid main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n v_texCoord = a_texCoord;\n}");this._prePrograme=this.context.createProgram(t,e),n.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.uniform1i(n.getUniformLocation(this._prePrograme,"mask"),1)}this.ready=!0}))}onPredict(e){var t;let i=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():null==this||this._selfieSegmentation.bindTexture(),i.activeTexture(i.TEXTURE1),null==(t=this._selfieSegmentation)||t.bindTexture2d(e),i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,this._bgTexture||null),i.activeTexture(i.TEXTURE3),i.bindTexture(i.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),i.drawArrays(i.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){var t,i,r;let n=this.context.ctx;if(Dw(this.image.getVideoPlaybackQuality)&&TN){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:o,videoHeight:s}=this.image;this.image.width=o,this.image.height=s;let a=!1;if(this.totalFrames)this._weixin?this.useTexture():null==this||this._selfieSegmentation.bindTexture(),a=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),a=this._textureValid,this._textureValid=!0}return this.width===o&&this.height===s&&a?n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,this.image):(this.resize(o,s),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,this.image)),this.ready&&(this._weixin&&(n.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(n.activeTexture(n.TEXTURE1),null==(t=this._selfieSegmentation)||t.bindTexture2d(this._segmentationMask),n.bindFramebuffer(n.FRAMEBUFFER,this._lastMaskFbo||null)),n.drawArrays(n.TRIANGLE_STRIP,0,4),null==(i=this._selfieSegmentation)||i.bindTexture(),this._segmentationMask?n.copyTexSubImage2D(n.TEXTURE_2D,0,0,0,0,0,o,s):n.copyTexImage2D(n.TEXTURE_2D,0,n.RGBA,0,0,o,s,0)),null==(r=this._selfieSegmentation)||r.send(o,s)),this.totalFrames||(n.activeTexture(n.TEXTURE2),n.bindTexture(n.TEXTURE_2D,this._bgTexture||null),n.activeTexture(n.TEXTURE3),n.bindTexture(n.TEXTURE_2D,this._waterMarkTexture||null),n.drawArrays(n.TRIANGLE_STRIP,0,4)),!1}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&t.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&t.deleteProgram(this._prePrograme),null==(e=this.wasm)||e.close()}},$U=class extends zU.EventEmitter{constructor(e){super(),this.room=e,eb(this,"videoContext"),eb(this,"_glVideoContext"),eb(this,"_2dVideoContext"),eb(this,"destination"),eb(this,"smallVideoContext"),eb(this,"smallDestination"),eb(this,"smallTrackSource"),eb(this,"smallImageSource"),eb(this,"_isMirror",!1),eb(this,"cameraTrack"),eb(this,"cameraNode"),eb(this,"mirrorNode"),eb(this,"mixNode"),eb(this,"screenTrack"),eb(this,"screenNode"),eb(this,"selfModel",!1),eb(this,"blurRadius",3),eb(this,"arTrack"),eb(this,"Wasm"),eb(this,"waterMarkNode"),eb(this,"_waterMarkOption"),eb(this,"watermarkImageList",[]),eb(this,"_beautyParams"),eb(this,"isUsingArTrack",!1),eb(this,"_isMixScreen",!1),eb(this,"_virtualBackground"),eb(this,"virtualBackgroundInstance"),eb(this,"_bgAssetPath"),eb(this,"log",TO.createLogger({id:"vm"})),eb(this,"_checkId",0),eb(this,"_use2d",!1),eb(this,"_autoSwitchRenderMode",!0),eb(this,"_selfieSegmentation"),eb(this,"_seiEncodeProcessor"),eb(this,"_seiDecodeProcessor"),eb(this,"seiWorker"),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new WL({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode="auto"===e,this._autoSwitchRenderMode)return;let t="2d"===e;this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new WL({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new jL({frameRate:15,logger:this.log,name:"m"});try{this._glVideoContext.create(),this.sendCreateResult(),this._glVideoContext.on("unavailable",((e,t)=>{this.emit("error",{reason:e,error:t}),this.log.warn("video context unavailable",e,t),this.sendCreateResult("videoCtxGl",t||new Error(e)),this.update()}))}catch(Rb){this.emit("error",{reason:"create",error:Rb}),this.sendCreateResult("videoCtxGl",Rb)}return this._glVideoContext}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=RP.run(Zk,(()=>{this.destination&&this.log.debug(this.destination.getInfo())}),{delay:e})}destroy(){var e,t;null==(e=this._2dVideoContext)||e.destroy(),null==(t=this._glVideoContext)||t.destroy(),this.smallVideoContext.destroy(),RP.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(AN||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(){let e=arguments.length>1?arguments[1]:void 0,t="videoCtxGl"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"videoCtxGl")?512700:512701;e?zP.addFailedEvent({key:t,error:e}):zP.addSuccessEvent({key:t})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else{if(!t)return!0;if(!this._use2d)return!0;this.clear()}}else this.clear(),this._use2d=!0;return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return null==(e=this.smallDestination)?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return null==(e=this.cameraTrack)?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var t;try{let i=this.cameraTrack,{small:r,settings:n,player:o}=i;r?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new xL(this.smallVideoContext,r)),this.smallVideoContext.frameRate=r.frameRate,this.smallDestination.resolution=r,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),AN&&o.setCanvas(e);let s=e&&(null==(t=this.destination)?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),s=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info("set main output ".concat(s?s.label:"no output track")),i.setOutputMediaStreamTrack(s)}catch(Cb){this.log.error("set main output failed",Cb)}}update(){return ib(this,null,(function*(){var e,t;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:i,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination",logger:this.log})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(i.width,i.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new LL(this.videoContext,{name:"mainDestination",logger:this.log})),this.cameraNode=new XU(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=r.frameRate,this._use2d){let i=this.cameraNode;i.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new qU(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 QU(this.videoContext),i.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),null==(e=this.waterMarkNode)||e.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),null==(t=this.screenNode)||t.connect(this.mixNode,{zIndex:0}),i=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))),i.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext._canvas)}))}changeInput(e){var t,i,r,n;if(e instanceof SL)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof TL)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof GL){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);let t=e.mediaTrack;return this._seiDecodeProcessor&&(e.pipeline[1]=this._seiDecodeProcessor),e.setOutputMediaStreamTrack(t)}this.log.warn("change unknown input",null==(n=e.mediaTrack)?void 0:n.label)}configPipeline(e){e instanceof GL&&this._seiDecodeProcessor&&(e.pipeline[1]=this._seiDecodeProcessor)}removeInput(e){var t;e instanceof SL?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof TL?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof GL&&e.source&&e.source.context.destroy()}setCameraTrack(e){return ib(this,null,(function*(){this.cameraTrack=e,this._seiEncodeProcessor&&(this.cameraTrack.pipeline[0]=this._seiEncodeProcessor),this.update()}))}setScreenTrack(e){return this.screenTrack=e,this._seiEncodeProcessor&&(this.screenTrack.pipeline[0]=this._seiEncodeProcessor),this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return ib(this,null,(function*(){let i=document.createElement("canvas");t&&e&&(i.height=t,i.width=e);let r=i.getContext("2d");if(!r)throw new fb({code:mb.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort(((e,t)=>e.zIndex-t.zIndex)),this.watermarkImageList.forEach((e=>{let{image:t,x:i,y:n,width:o,height:s}=e;r.drawImage(t,i,n,o,s)})),aO(i.toDataURL())}))}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some((t=>t.imageUrl===e.imageUrl&&t.height===e.height&&t.width===e.width&&t.x===e.x&&t.y===e.y&&t.type===e.type&&t.zIndex===e.zIndex))||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==t))),this.watermarkImageList.push(e))}setBeautyParams(e){return ib(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return ib(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return ib(this,null,(function*(){let t;try{t=yield aO((null==e?void 0:e.imageElement)||e.imageUrl)}catch(c){throw new fb({code:mb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:i=0,y:r=0,width:n=t.width,height:o=t.height,type:s="watermark",zIndex:a=2}=e;this.pushWaterMarkImageList({x:i,y:r,width:n,height:o,image:t,zIndex:a,type:s,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return ib(this,null,(function*(){this.watermarkImageList=this.watermarkImageList.filter((t=>t.type!==e)),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()}))}freshWatermark(){return ib(this,null,(function*(){var e,t,i;null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let r=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(i=this.cameraTrack)?void 0:i.settings.height);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()}))}setVirtualBackground(e){return ib(this,null,(function*(){if(e){if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,"image"===e.type?this._virtualBackground=yield aO(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}else this._virtualBackground=void 0;this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat((null==e?void 0:e.type)||"",", ").concat(this.blurRadius||"")),this.update()}))}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return ib(this,null,(function*(){var e;null==(e=this.cameraTrack)||!e.mediaTrack||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))}))}disableAr(){var e;this.isUsingArTrack=!1,null==(e=this.arTrack)||e.stop(),this.arTrack=void 0,this.update()}clear(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}enableSEI(e){let{encoder:t,decoder:i,seiWorker:r}=e;r?this.seiWorker=r:(this._seiEncodeProcessor=t,this._seiDecodeProcessor=i,this.cameraTrack&&(this.cameraTrack.pipeline[0]=this._seiEncodeProcessor),this.screenTrack&&(this.screenTrack.pipeline[0]=this._seiEncodeProcessor))}disableSEI(){var e;null==(e=this.seiWorker)||e.terminate(),delete this.seiWorker,delete this._seiEncodeProcessor,delete this._seiDecodeProcessor,this.cameraTrack&&(this.cameraTrack.pipeline[0]=void 0),this.screenTrack&&(this.screenTrack.pipeline[0]=void 0)}},ZU=0,eF=class extends vP{constructor(e){super("room"),this.seq=++ZU,this.role="anchor",this.joinParams=null,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=TO.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this.isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,Pw(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Pw(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Pw(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new jU({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new GU({room:this}),this.badCaseDetector=new JU({room:this}),this.audioManager=new AL(this),this.videoManager=new $U(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}get localMainVideoTrack(){for(let e of this.localTracks)if(4&e.mediaType)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(2&e.mediaType)return e;return null}getLogger(){return this._log}get isJoining(){return"joining"===this.state.toString()}get isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return ib(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return ib(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return ib(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(ww(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Rw(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:r,scheduleProxy:n,unifiedProxy:o}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=o,o?(nw([o,o]),Ob("https://".concat(o))):(r&&Ob(r),n&&nw(n))}QN.once(fO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:rw.main,sched_back_domain:rw.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return ib(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return ib(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 ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"main";return function*(){let i={};return e.remotePublishedUserMap.forEach((e=>{let r="auxiliary"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;i[e.userId]=r.stat})),i}()}))}checkDestroy(){if(this.isDestroyed)throw new fb({code:mb.INVALID_OPERATION,message:KN({key:oD.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(sD.INVALID_DESTROY),new fb({code:mb.INVALID_OPERATION,message:KN({key:oD.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,QN.emit(fO.ROOM_DESTROY,{room:this})}schedule(e,t){return ib(this,null,(function*(){var i,r;let n=Ww();try{let{isCached:o,result:s,detailCost:a}=yield iw({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Ib,userSig:this.userSig,role:"live"===this.scene?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=o,this._log.info("schedule cache:".concat(+o," ").concat(rO(s,{keysToExclude:["username","credential"]}))),o&&QN.once(fO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=qC(qC({},this.scheduleResult),s),Ow(null==(i=s.config)?void 0:i.retryCount)&&Ik(s.config.retryCount),ww(null==(r=s.config)?void 0:r.loggerDomain)&&Ob(s.config.loggerDomain),QN.emit(fO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:a}),zP.addSuccessEvent({key:521700,cost:Ww()-n,split:50})}catch(o){throw zP.addFailedEvent({key:521700,error:o}),o}}))}},tF=$C(rb(),1),iF=Symbol("instance"),rF=Symbol("cacheResult"),nF=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,lF.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},oF=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var sF=new Map;function aF(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,n,o)=>{let s=i.action||n;if(!i.context){let i=sF.get(r)||[];sF.has(r)||sF.set(r,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let r=this;for(var n=arguments.length,o=new Array(n),c=0;c<n;c++)o[c]=arguments[c];if(i.context&&(r=dF.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return r[rF];r.state instanceof nF&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;if(Array.isArray(e)?0==e.length?r.state instanceof nF&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new oF(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not in from config"))):e!==r.state&&(l=new oF(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e))),l){if(!i.fail){if(i.ignoreError)return l;throw l}i.fail.call(this,l)}let d=r.state,u=new nF(d,t,s);lF.call(r,u);let h=e=>{var n;return r[rF]=e,u.aborted||(lF.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[rF])),e},p=e=>{let t=e instanceof Error?e.message:String(e);if(lF.call(r,d,e),!i.fail){if(i.ignoreError)return e;throw e}i.fail.call(this,new oF(r._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(h).catch(p):h(e)}catch(m){p(m)}}}}var cF="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 lF(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(dF.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var dF=class extends tF.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=dF.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let r=i[iF];r?this.name=r.name+"-"+r.count++:i[iF]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=sF.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);sF.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?r.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:o})})):n.push({to:i,action:o})})),r.forEach((e=>{let{from:t,to:r,action:n}=e;o.add(t),o.add(r),o.add(n+"ing"),i.add("".concat(t," --\x3e ").concat(n,"ing : ").concat(n)),i.add("".concat(n,"ing --\x3e ").concat(r," : ").concat(n," 🟢")),i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🔴"))})),n.forEach((e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=dF.instances.get(e),t||dF.instances.set(e,t=new dF(e,void 0,Object.create(dF.prototype)))):(t=dF.instances2.get(e),t||dF.instances2.set(e,t=new dF(e.constructor.name,void 0,Object.create(dF.prototype)))),t}static getState(e){var t;return null===(t=dF.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};cF(dF.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){lF.call(this,e)}};dF.STATECHANGED="stateChanged",dF.UPDATEAFSM="updateAFSM",dF.INIT="[*]",dF.ON="on",dF.OFF="off",dF.instances=new Map,dF.instances2=new WeakMap;var uF=$C(rb()),hF=$C(ub());function pF(e){var t;let i=[];for(let r=0;r<e.rtp.length;r++){if(["rtx","red","ulpfec"].includes(e.rtp[r].codec))continue;let n=e.fmtp.filter((t=>t.payload===e.rtp[r].payload))[0];i.push({payload:e.rtp[r].payload,codec:e.rtp[r].codec,fmtp:n?n.config:"",rate:e.rtp[r].rate,rtx:"rtx"===(null==(t=e.rtp[r+1])?void 0:t.codec)?e.rtp[r+1].payload:0,rtcpFb:((null==e?void 0:e.rtcpFb)||[]).filter((t=>t.payload===e.rtp[r].payload)).map((e=>{let{type:t,subtype:i}=e;return{id:t,params:i?[i]:[]}}))})}return i}var mF=(e,t)=>ib(void 0,null,(function*(){var i;let r=AU(e),n={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};n.ice.ufrag=String(r.media[0].iceUfrag),n.ice.password=r.media[0].icePwd||"",r.fingerprint&&(n.dtls.hash=r.fingerprint.type,n.dtls.fingerprint=r.fingerprint.hash,n.dtls.setup=r.setup||""),r.media[0].fingerprint&&(n.dtls.hash=r.media[0].fingerprint.type,n.dtls.fingerprint=r.media[0].fingerprint.hash),n.dtls.setup=r.media[0].setup||"";let o=r.media[0],s=r.media[1];o.ext&&(n.audio.extensions=o.ext.map((e=>({id:e.value,uri:e.uri})))),s.ext&&(n.video.extensions=s.ext.map((e=>({id:e.value,uri:e.uri}))));let a={codec:o.rtp[0].codec,fmtp:o.fmtp[0].config,payload:o.fmtp[0].payload,rate:o.rtp[0].rate,channel:o.rtp[0].encoding,rtcpFb:[],rtx:0};null==(i=o.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:r}=e;if(t===a.payload){let e={id:i,params:[]};r&&e.params.push(r),a.rtcpFb.push(e)}})),n.audio.codecs.push(a);let c=["h264","vp8"];return t&&c.shift(),n.video.codecs=[...pF(s)].filter((e=>c.includes(e.codec.toLocaleLowerCase()))),n.video.decoders=(yield function(){return ib(this,null,(function*(){let e=new RTCPeerConnection;e.addTransceiver(Zb.VIDEO,{direction:Zb.TRANSCEIVER_DIRECTION_RECVONLY});let t=yield e.createOffer();if(!t.sdp)return[];let i=pF(AU(t.sdp).media[0]);return e.close(),i}))}()).filter((e=>["h264","vp8"].includes(e.codec.toLocaleLowerCase()))),n})),_F=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,o=AU(r),s={extmapAllowMixed:"extmap-allow-mixed",groups:o.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},a={candidates:t.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:Zb.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:Zb.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(fF({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),n&&s.media.push(o.media.find((e=>"dc"===e.mid))),RU(s)},fF=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,isDownlink:o=!1}=e,s={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:Zb.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(t),payloads:"",port:n.media[0].port,protocol:n.media[0].protocol,type:Zb.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(o)(i.video.decoders||i.video.codecs).forEach((e=>{gF(s,e)}));else{let e=i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264"))),t=i.video.codecs[e]||r.video.codecs[0];gF(s,t)}return s},gF=(e,t)=>{e.payloads="".concat(e.payloads," ").concat(t.payload).trim(),e.fmtp.push({payload:t.payload,config:t.fmtp}),e.rtcpFb=[...e.rtcpFb||[],...(t.rtcpfb||t.rtcpFb).map((e=>({payload:t.payload,type:e.id,subtype:e.params[0]})))],e.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(e.payloads="".concat(e.payloads," ").concat(t.rtx),e.fmtp.push({payload:t.rtx,config:"apt=".concat(t.payload)}),e.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))};var TF=(e,t,i)=>{let r=hF.default.parse(e);return r.media.forEach(((e,n)=>{var o;(e.type===Zb.AUDIO||e.type===Zb.VIDEO)&&(function(e){if(!e.rtcpFb)return;let t=[];e.rtcpFb.forEach(((i,r)=>{var n;t.push(i),e.rtcpFb&&(null==(n=e.rtcpFb[r+1])?void 0:n.payload)!==i.payload&&"rrtr"!==i.type&&t.push({payload:i.payload,type:"rrtr"})})),e.rtcpFb=t}(e),function(e){e.type===Zb.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===Zb.AUDIO&&e.fmtp&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))}(e),function(e){let t=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}(e),e.type===Zb.VIDEO&&(n<4?(e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach((t=>gF(e,t)))):i&&(e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],(i.video.decoders||i.video.codecs).forEach((t=>gF(e,t)))))),(null==(o=e.payloads)?void 0:o.includes("datachannel"))&&r.groups&&e.mid&&(r.groups[0].mids=r.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),hF.default.write(r)},EF=$C(rb()),vF=class extends EF.EventEmitter{constructor(e){super(),this.room=e,eb(this,"mainFpsHealth",1),eb(this,"mainBitrateHealth",1),eb(this,"badMainBitrateHealthCount",0),eb(this,"lastEmitBadHealthTime",0),eb(this,"log"),!ED&&TN&&QN.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged(e){let{remoteUserId:t,streamType:i,isHWCodec:r,codec:n}=e;if(!t&&7!==i&&"h264"===n){if(!r)return void this.room.off("heartbeat-report",this.onHeartbeatReport,this);this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<3e4||(e.msg_up_stream_info.msg_video_status.forEach((e=>{if(e.uint32_video_enc_fps&&e.uint32_video_capture_fps){let t=e.uint32_video_enc_fps/e.uint32_video_capture_fps;2===e.uint32_video_stream_type&&(this.mainFpsHealth=t)}if(e.uint32_video_codec_bitrate&&2===e.uint32_video_stream_type){let{localMainVideoTrack:t}=this.room;t&&(this.mainBitrateHealth=e.uint32_video_codec_bitrate/1e3/t.profile.bitrate)}})),this.log.debug("mainBitrateHealth: ".concat(this.mainBitrateHealth," mainFpsHealth: ").concat(this.mainFpsHealth)),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn("bad main bitrate health: ".concat(this.mainBitrateHealth)),this.emit("1",{isAux:!1}))))}destroy(){QN.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};eb(vF,"EVENT_BAD_HEALTH","bad_health");var yF,SF=vF,IF=((yF=IF||{}).TRACK="track",yF.DATA_CHANNEL_MESSAGE="data_channel_msg",yF[yF.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",yF[yF.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",yF.RECONNECTED="spc-reconnected",yF.RECONNECT_FAILED="spc-reconnect-failed",yF.ERROR="error",yF.SEI_MESSAGE="sei-message",yF),AF=0,RF=!1,CF=new Set,bF=1,kF=class extends uF.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),eb(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),eb(this,"currentState","DISCONNECTED"),eb(this,"_room"),eb(this,"_signalChannel"),eb(this,"_peerConnection",null),eb(this,"_datachannel",null),eb(this,"_enableCustomMessage"),eb(this,"_log"),eb(this,"_downlinkMIDMap",new Map),eb(this,"_downlinkMIDUserIDMap",new Map),eb(this,"_reconnectionTimer",-1),eb(this,"reconnectionCount",0),eb(this,"clientAbility"),eb(this,"_serverAbility",null),eb(this,"addDownlinkQueue",new Set),eb(this,"removeDownlinkQueue",new Set),eb(this,"_parsedAnswer",null),eb(this,"_updateSDPPromise",null),eb(this,"_waitForPCConnectedPromise"),eb(this,"_waitForPCConnectedPromiseReject",null),eb(this,"_isSDPLogged",!1),eb(this,"enableInsertableStreams",!1),eb(this,"insertableStreamsAbortMap",new Map),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=TO.createLogger({id:"spc".concat(bF++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&iP&&(this.enableInsertableStreams=!0),this._room.healthDetector.on("1",(e=>{let{isAux:t}=e;this.useHWEncoder(!1,t?7:2)}))}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((e=>"h264"===e.codec.toLowerCase()))),e}addAbortController(e,t){var i;null==(i=this.insertableStreamsAbortMap.get(e))||i.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find((e=>"vp8"===e.codec.toLowerCase()))),e}get videoCodec(){var e,t;let i=null==(e=this._parsedAnswer)?void 0:e.media[1].rtp.find((e=>["h264","vp8"].includes(e.codec.toLowerCase())));return i?i.codec.toLowerCase():null!=(t=this._serverAbility)&&t.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return null!=(e=this._serverAbility)&&e.video.decoders.find((e=>"h264"===e.codec.toLowerCase()))?"h264":"vp8"}get isUsingH264(){return"h264"===this.videoCodec}get is42001fSupported(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f")))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=AU(e),i={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach(((e,t)=>{var r;if(e.ssrcs&&!Nw(e.ssrcs[0].id)){let n=Number(e.ssrcs[0].id),o=Number(null==(r=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:r.id);switch(t){case 0:i.audioSsrc=n;break;case 1:i.bigVideoSsrc=n,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=n,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=n,i.auxVideoRtxSsrc=o}}})),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}initialize(){return ib(this,null,(function*(){var e;let t;try{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let e=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(e)),"checking"===e&&0===this.stat.iceStartTime?this.stat.iceStartTime=Date.now():"connected"===e&&0===this.stat.iceEndTime&&(this.stat.iceEndTime=Date.now())},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 NF(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(Zb.AUDIO,{direction:Zb.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Zb.VIDEO,{direction:Zb.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Zb.VIDEO,{direction:Zb.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Zb.VIDEO,{direction:Zb.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield mF(t.sdp,(null==(e=this._room.scheduleResult.config)?void 0:e.remove264FromSDP)||!1),yield this.setOffer(t),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;!e||(this._log.debug("dtls state: ".concat(e.state)),"connecting"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():"connected"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()))}),zP.addSuccessEvent({key:521707}),this.clientAbility}catch(Cb){throw zP.addFailedEvent({key:521707,error:Cb}),this._log.error("initialize failed ".concat(Cb," \noffer: ").concat(null==t?void 0:t.sdp)),Cb}}))}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return ib(this,null,(function*(){try{if("CONNECTED"===this.currentState)return;let i=Ww(),r={type:"answer",sdp:_F({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(r),yield this.waitForPeerConnectionConnected(),t||zP.addSuccessEvent({key:521703,cost:Ww()-i})}catch(Cb){let i=Cb instanceof fb&&Cb.code===mb.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(Cb),e),this.reset(),!i&&!this.isReconnecting&&(zP.addFailedEvent({key:521703,error:Cb}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),Cb}}))}reconnect(){return ib(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(xV,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:cU,responseCommand:HV.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),zP.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),QN.emit(fO.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(Rb){if(!this.isReconnecting)return;if(null!=Rb&&Rb.message.includes("timeout")){let e=bw(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==Rb?void 0:Rb.code," ").concat(Rb)),zP.addFailedEvent({key:521704,error:Rb}),this.reconnectionCount>=Ak()&&this._log.warn("SDK has tried reconnect for ".concat(Ak()," 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 ib(this,null,(function*(){this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect()}))}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(xV,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===yk.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===yk.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===yk.FAILED||e.target.connectionState===yk.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===yk.CONNECTED||e.target.connectionState===yk.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),QN.emit(fO.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 vk;let e=null;return KO()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,zO()&&0!==this._peerConnection.getReceivers().length&&e?e.state:vk):vk}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(IF.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return ib(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(FO(i)){let t=e.get(i.localCandidateId),r=e.get(i.remoteCandidateId);t&&(this._log.info("local candidate: ".concat(t.candidateType," ").concat(t.protocol,":").concat(t.ip||t.address,":").concat(t.port," ").concat(t.networkType||""," ").concat("relay"===t.candidateType?"relayProtocol:".concat(t.relayProtocol):"")),t.networkType&&fw(t.networkType)),r&&this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port));break}}))}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this.currentState)return e();this._waitForPCConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new fb({code:mb.API_CALL_ABORTED,message:KN({key:oD.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{QN.off(fO.LEAVE_SUCCESS,r,this),this.off(IF.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{n();let e=new fb({code:mb.API_CALL_TIMEOUT,message:"connection timeout"});var i;AF+=1,i=this._signalChannel.isConnected,AF>2&&!RF&&0===CF.size&&i&&(this._log.warn("firewall restriction"),RF=!0,this.emit(IF.FIREWALL_RESTRICTION)),t(e)}),Fk);QN.on(fO.LEAVE_SUCCESS,r,this),this.on(IF.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 ib(this,null,(function*(){if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),0===this.addDownlinkQueue.size)try{yield this.updateSDP(),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(Rk){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(Rk)),yield this.startReconnection()}}))}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,userId:i,tinyId:r}=e;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(i," ").concat(JSON.stringify(t)));let n=this._peerConnection.getTransceivers().filter((e=>"inactive"===e.direction)).slice(0,3).map((e=>(e.direction=Zb.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=AU(this._peerConnection.remoteDescription.sdp));let o,s,a,c=this._parsedAnswer.media.filter((e=>{var t;return null==(t=e.ssrcs)?void 0:t.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(r)}))}));if(3===c.length)o=c[0],s=c[1],a=c[2];else if(3===n.length)o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[0]))),s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[1]))),a=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[2])));else if(0===n.length){this._peerConnection.addTransceiver(Zb.AUDIO,{direction:Zb.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Zb.VIDEO,{direction:Zb.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Zb.VIDEO,{direction:Zb.TRANSCEIVER_DIRECTION_RECVONLY}),o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=fF({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:AU(this._peerConnection.localDescription.sdp),isDownlink:!0});s=JSON.parse(JSON.stringify(e)),a=JSON.parse(JSON.stringify(e)),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a)}o.direction=Zb.TRANSCEIVER_DIRECTION_SENDONLY;let l="".concat(r,"-").concat(t.audio);o.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(l)},{id:t.audio,attribute:"msid",value:"".concat(l,"-").concat(Zb.MAIN," ").concat(l,"-audio")}],s.direction=Zb.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(Zb.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(Zb.MAIN," ").concat(l,"-bigvideo")}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=Zb.TRANSCEIVER_DIRECTION_SENDONLY;let d="".concat(l,"-aux");a.ssrcs=[{id:t.auxiliary,attribute:"cname",value:d},{id:t.auxiliary,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Zb.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(Zb.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Zb.VIDEO)}],a.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map((e=>e.mid)).join(" ")),this._downlinkMIDMap.set(i,[o.mid,s.mid,a.mid]),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(s.mid,i),this._downlinkMIDUserIDMap.set(a.mid,i)}removeDownlink(e){return ib(this,null,(function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(e,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),i=!1;this._peerConnection.getTransceivers().forEach((e=>{null!=t&&t.includes(Number(e.mid))&&(i=!0,e.direction="inactive")})),this._parsedAnswer||(this._parsedAnswer=AU(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((e=>{null!=t&&t.includes(Number(e.mid))&&(i=!0,e.direction="inactive",e.ssrcs=[],e.ssrcGroups=[])})),0===this.removeDownlinkQueue.size&&i&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),null==t||t.forEach((e=>this._downlinkMIDUserIDMap.delete(e))),this._log.info("removeDownlink(".concat(e,") done"))}))}setBandwidth(e){return ib(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(ZO()){let e=this._peerConnection.getSenders().slice(0,4);for(let s=0;s<e.length;s++){let o,a=e[s];0===s&&t?o=t:1===s&&i?o=i:2===s&&r?o=r:3===s&&n&&(o=n),o&&(yield this.setSenderMaxBitrate(a,o))}let o=!1;i&&e[1].track&&(o=this.setStartBitrate(1,i)),n&&e[3].track&&(o=this.setStartBitrate(3,n)||o),o&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info("setBandwidth ".concat(JSON.stringify(e)))}catch(o){this._log.error("failed to set bandwidth: ".concat(o))}}))}setStartBitrate(e,t){var i,r;return!(null==(i=this._peerConnection)||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=AU(this._peerConnection.remoteDescription.sdp)),null==(r=this._parsedAnswer.media[e])||!r.fmtp[0]))&&(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),!0)}setSenderMaxBitrate(e,t){let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),"unlimited"===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,e.setParameters(i)}setBandwidthBySDP(e){let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=AU(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=AU(this._peerConnection.remoteDescription.sdp));let s=ID?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:ID?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:ID?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:ID?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:ID?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:s,limit:ID?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:ID?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:s,limit:ID?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:ID?1e3*n:n}]);let a={type:"offer",sdp:RU(o)};return this.updateSDP({localDescription:a})}setScaleResolutionDownBy(e,t){if(1===t)return;let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),i.encodings[0].scaleResolutionDownBy=t,e.setParameters(i)}updateSDP(){let{localDescription:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=RU(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,r)=>ib(this,null,(function*(){var n,o;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,i()}catch(yF){this._log.error(yF),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection(null==(n=this._peerConnection.localDescription)?void 0:n.sdp)," \nnext offer: ").concat(this.filterSDPDirection(null==e?void 0:e.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection(null==(o=this._peerConnection.remoteDescription)?void 0:o.sdp)," \nnext answer: ").concat(this.filterSDPDirection(t))),this._log.warn("offer: ".concat(null==e?void 0:e.sdp)),this._log.warn("answer: ".concat(t)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map((e=>{let{mid:t,currentDirection:i,direction:r,stopped:n}=e;return{mid:t,currentDirection:i,direction:r,stopped:n}}))))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,r(yF)}})))),this._updateSDPPromise}filterSDPDirection(){return AU(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((e=>e.direction))}setOffer(e){return this._log.info("setting offer"),this._log.debug(e.sdp),this._peerConnection.setLocalDescription({type:"offer",sdp:TF(e.sdp,this.clientAbility,this._serverAbility)})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return ib(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach((i=>{var r;if(i.type===Zb.VIDEO){let n=this._serverAbility.video.codecs.find((t=>t.codec.toLowerCase()===e));n&&(null==(r=i.payloads)||!r.includes(String(n.payload)))&&(i.fmtp=[],i.payloads="",i.rtp=[],i.rtcpFb=[],gF(i,n),t=!0)}})),t&&(this._log.warn("switch video encoder to ".concat(e)),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:RU(this._parsedAnswer)}))}))}useHWEncoder(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;return ib(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];Nw(t)?r=this._parsedAnswer.media.slice(1,4):2===t?r.push(this._parsedAnswer.media[1]):3===t?r.push(this._parsedAnswer.media[2]):7===t&&r.push(this._parsedAnswer.media[3]),r.forEach((t=>{var r;if(t.type===Zb.VIDEO){let n;e&&this.is42001fSupported?n=this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f"))):e||(n=this._serverAbility.video.codecs.find((e=>e.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264")))),n&&(null==(r=t.payloads)||!r.includes(String(n.payload)))&&(t.fmtp=[],t.payloads="",t.rtp=[],t.rtcpFb=[],gF(t,n),i=!0)}})),i&&(this._log.warn("use ".concat(e?"hw":"sw"," encoder")),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:RU(this._parsedAnswer)}))}))}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.insertableStreamsAbortMap.forEach((e=>"function"==typeof e.abort&&e.abort("destroy"))),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map((e=>t[e]))}};ZC([dL("reconnect")],kF.prototype,"startReconnection",1),ZC([uL((e=>e.userId))],kF.prototype,"addDownlink",1),ZC([uL((e=>e))],kF.prototype,"removeDownlink",1),ZC([lL(!0)],kF.prototype,"updateSDP",1);var DF=class{constructor(e){eb(this,"tag"),eb(this,"len"),eb(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}},NF=class{constructor(e){eb(this,"tinyId"),eb(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new DF(new Uint8Array(e).slice(i,i+2+2+n).buffer);r.push(o),i+=4+n}r.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},wF=new Set;function OF(){let e=Math.floor(4294967296*Math.random());return wF.has(e)?OF():(wF.add(e),e)}var PF=$C(rb()),MF=class extends PF.default{constructor(e){super(),eb(this,"userId"),eb(this,"tinyId"),eb(this,"_sdpSemantics"),eb(this,"_isUplink"),eb(this,"_room"),eb(this,"_log"),eb(this,"_currentState","DISCONNECTED"),eb(this,"_prevTime",-1),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=TO.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(QN.emit(fO.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"))}},LF=class extends MF{constructor(e){super(YC(qC({},e),{isUplink:!0})),eb(this,"localMainAudioTrack",null),eb(this,"localMainVideoTrack",null),eb(this,"localAuxAudioTrack",null),eb(this,"localAuxVideoTrack",null),eb(this,"_isPublishingAux",!1),eb(this,"_publishingLocalAudioTrack"),eb(this,"_publishingLocalVideoTrack"),eb(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}),eb(this,"_flag",0),eb(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc:r,smallVideoRtxSsrc:n,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:o||0,auxiliaryRtx:s||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:i}=this,r=Object.keys(t).find((e=>t[e]!==i[e]));if(r){if(!e)return void(this._checkPublishStateTimeoutId=RP.run(eD,(()=>this.checkPublishState(!0)),{delay:1e4,count:1}));this._log.warn("publish state not matched, ".concat(r," local:").concat(t[r]," server:").concat(i[r]," ").concat(jN()," ").concat(FN())),zP.addCount({key:521e3})}RP.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(qO()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(i=o[2])||!i.track),n.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((e=>{e.track&&(e.track.kind===Zb.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}get serverPublishState(){return{audio:!!(this.flag&sk),bigVideo:!!(this.flag&rk),smallVideo:!!(this.flag&nk),auxVideo:!!(this.flag&ok)}}get muteState(){var e,t,i;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(i=this.localAuxVideoTrack)||!i.muted)}}initialize(){this.installEvents()}close(e){var t;let i=(null==(t=this._peerConnection)?void 0:t.getSenders())||[];for(let r of i)r.replaceTrack(null);super.close(e),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e,t;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),null!=(e=this.singlePC)&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(t=this.singlePC)||t.on("spc-reconnected",this.onSinglePCReconnected,this),rP&&this._room.enableSEI&&!QN.listeners(fO.SEND_SEI_MESSAGE).includes(this.sendSEIByWorker)&&(this.sendSEIByWorker=this.sendSEIByWorker.bind(this),QN.on(fO.SEND_SEI_MESSAGE,this.sendSEIByWorker))}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this),QN.off(fO.SEND_SEI_MESSAGE,this.sendSEIByWorker)}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}onVideoEncodeFailed(e){var t,i;e&&e.isMediaTrackActive&&"h264"===this.videoCodec&&(this._log.warn("h264 encoder not working"),null!=(t=this.singlePC)&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),null==(i=this.singlePC)||i.switchVideoEncoder("vp8")))}publish(e){return ib(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e,o,s,a,c,l,d;if(!t.singlePC)return;yield t.singlePC.waitForPeerConnectionConnected();let u,{publishState:h,muteState:p}=t;if(i&&(t._publishingLocalAudioTrack=i,h.audio=!0,p.audio=i.muted),r){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new fb({code:mb.NOT_SUPPORTED_H264,message:KN({key:oD.NOT_SUPPORTED_H264ENCODE})});ED&&115===gN()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to 480p"),r.setProfile(Xb["480p_2"]),yield r.applyProfile()),t._publishingLocalVideoTrack=r,n?(h.auxVideo=!0,p.auxVideo=r.muted):(h.bigVideo=!0,p.bigVideo=r.muted)}if(t._isPublishingAux=n,r&&!n&&r.small&&(u=t._room.videoManager.smallTrack,h.smallVideo=!0),yield t._signalChannel.sendWaitForResponseWithRetry({command:dU,responseCommand:HV.SPC_PUBLISH_RESULT,data:YC(qC({},t.singlePC.uplinkSSRC),{state:h,muteState:p}),retries:3}),yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:u,isAuxiliary:n}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r){t[n?"localAuxVideoTrack":"localMainVideoTrack"]=r;let{scaleResolutionDownBy:e}=r;e>1&&(t._log.warn("setScaleResolutionDownBy ".concat(r.streamType," ").concat(e)),yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[n?3:1],e))}i&&(t[n?"localAuxAudioTrack":"localMainAudioTrack"]=i),yield t.singlePC.setBandwidth({audio:(null==(e=t.localMainAudioTrack)?void 0:e.profile.bitrate)||(null==(o=t.localAuxAudioTrack)?void 0:o.profile.bitrate),bigVideo:null==(s=t.localMainVideoTrack)?void 0:s.profile.bitrate,smallVideo:null==(c=null==(a=t.localMainVideoTrack)?void 0:a.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),t.sendMediaSettings(),t.installTrackMuteEvents(i,r),!n&&(t._room.preferHW||(null==(d=t._room.scheduleResult.config)?void 0:d.preferHW))&&r&&r.profile.width*r.profile.height>=921600&&t.singlePC.useHWEncoder(!0,2)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!YO())return;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[],d=(e,t,i)=>{var r;let n=a[t].sender.replaceTrack(i);l.push(t),null!=(r=this.singlePC)&&r.enableInsertableStreams&&n.then((()=>this.createEncodedStreams(a[t].sender,e))),c.push(n)};s&&d(t.mediaType,0,s),o&&d(i.mediaType,n?3:1,o),r&&d(8,2,r);let u=this.setTransceiverDirection(ek.SENDONLY,l);return c.push(u),Promise.all(c)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var i,r;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let n=e.createEncodedStreams(),o=new AbortController;null==(i=this.singlePC)||i.addAbortController(e,o),(null!=(r=this.getTrackByMediaType(t))&&r.enableEncodeFrame?n.readable.pipeThrough(new TransformStream({transform:(e,i)=>{var r;let n=this.getTrackByMediaType(t);i.enqueue((null==(r=this.singlePC)?void 0:r.isUsingH264)&&n?n.encodeFrame(e,8===t):e)}}),o):n.readable).pipeTo(n.writable,o).catch((e=>{this._log.debug("encoded stream error",e),"destory"!==e&&this._log.warn(e)}))}sendSEIByWorker(e){let{room:t,isMain:i}=e;var r;if(t!==this._room||!this._peerConnection||!this.singlePC||!this._room.videoManager.seiWorker)return;let n=this._peerConnection.getSenders()[i?1:3];if(n&&(n.transform||(n.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!1,isMain:i})),i&&(null==(r=this.localMainVideoTrack)?void 0:r.small))){let e=this._peerConnection.getSenders()[2];e.transform||(e.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!1,isMain:i,small:!0}))}}enableSmall(e){return ib(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(ek.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ek.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 ib(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){let e=r&&r===t.localAuxVideoTrack,n=null==r?void 0:r.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(yield o[0].replaceTrack(null),s.push(0),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=YC(qC({},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=YC(qC({},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(ek.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return ib(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:qV,data:t,responseCommand:HV.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(i.data.code,i.data.message)}))}doUnpublish(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._signalChannel.sendWaitForResponse({command:YV,commandDesc:"unpublish",responseCommand:HV.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===mb.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),eP){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*r.profile.bitrate,r.small&&(this._mediaSettings.smallVideoWidth=r.small.width,this._mediaSettings.smallVideoHeight=r.small.height,this._mediaSettings.smallVideoFps=r.small.frameRate,this._mediaSettings.smallVideoBps=1e3*r.small.bitrate)}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*n.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),r&&r.outMediaTrack&&(this._mediaSettings.videoWidth=r.profile.width,this._mediaSettings.videoHeight=r.profile.height,this._mediaSettings.videoFps=r.profile.frameRate,this._mediaSettings.videoBps=1e3*r.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:aU,data:this._mediaSettings,responseCommand:HV.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return ib(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Zb.AUXILIARY:Zb.MAIN," stream")),qO()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return ib(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Zb.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),1===n&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ek.INACTIVE&&(yield this.setTransceiverDirection(ek.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return ib(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?Zb.AUXILIARY:Zb.MAIN," stream")),qO()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return ib(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Zb.AUDIO)yield i[0].sender.replaceTrack(null);else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._room.videoManager.hasSmall&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(ek.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return ib(this,null,(function*(){if(!ID)return;let i=!1,r=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let n=this._peerConnection.getTransceivers();if(t.forEach((t=>{n[t].direction!==e&&(n[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(ek.INACTIVE,"|").concat(ek.RECVONLY,"|").concat(ek.SENDONLY,")")))&&o++,t.includes(o)){if(e===ek.INACTIVE&&i.includes("a=".concat(ek.RECVONLY)))return r=!0,"a=".concat(e);if(e===ek.SENDONLY&&i.includes("a=".concat(ek.INACTIVE)))return r=!0,"a=".concat(ek.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}replaceTrack(e){return ib(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!i||0===i.length||!r||i.find((e=>e.track===r)))return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(r.kind," track ").concat(r.id," on ").concat(n?Zb.AUXILIARY:Zb.MAIN," stream")),r.kind===Zb.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===Zb.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0}))}setBandwidth(e){return ib(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===Zb.AUDIO?e.audio=i:"big"===n?e.bigVideo=i:"small"===n?e.smallVideo=i:e.auxVideo=i,yield t.singlePC.setBandwidth(e)}}()}))}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:zV,responseCommand:HV.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&QN.emit(fO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Zb.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Zb.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Zb.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Zb.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Zb.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Pk?(this._log.error(sD.NOT_SUPPORTED_H264ENCODE),new fb({code:mb.NOT_SUPPORTED_H264,message:KN({key:oD.NOT_SUPPORTED_H264ENCODE})})):new fb({code:mb.UNKNOWN,message:KN({key:oD.SIGNAL_RESPONSE_FAILED,data:{signalResponse:HV.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return ib(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}))}))}};ZC([iL((function(e){let{localVideoTrack:t}=e;null==t||t.once("6",this.onVideoEncodeFailed,this)}))],LF.prototype,"publish",1),ZC([iL((function(e){let{localVideoTrack:t}=e;null==t||t.off("6",this.onVideoEncodeFailed,this)}))],LF.prototype,"unpublish",1);var xF=LF;function VF(e){return Object.keys(e).filter((t=>e[t]))}var UF=class extends MF{constructor(e){super(YC(qC({},e),{isUplink:!1})),eb(this,"_flag",0),eb(this,"role","anchor"),eb(this,"remoteAudioTrack"),eb(this,"remoteVideoTrack"),eb(this,"remoteAuxiliaryTrack"),eb(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),this.flag=e.flag,this.remoteAudioTrack=new kL(this._room,this),this.remoteVideoTrack=new GL(this._room,this),this.remoteAuxiliaryTrack=new JL(this._room,this),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.downlinkVideoCodec)||"h264"}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return qw(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===Zb.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let t=e.streams[0],{track:i,receiver:r}=e;if(!t.id.includes(this.tinyId))return;let n=t.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(n," ").concat(i.kind));let o=Zb.AUDIO;i.kind===Zb.VIDEO&&(o=n===Zb.MAIN?Zb.VIDEO:Zb.AUXILIARY);let s=this.remoteAudioTrack;o===Zb.VIDEO?s=this.remoteVideoTrack:o===Zb.AUXILIARY&&(s=this.remoteAuxiliaryTrack),this._room.enableSEI&&rP&&this.receiveSEIByWorker(r,n),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s,r),s.setInputMediaStreamTrack(i)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let i=t.createEncodedStreams(),r=new AbortController,n={abortController:r,enqueue:t=>{var i;return null!=(i=this.singlePC)&&i.isUsingH264?e.decodeFrame(t):t}};(e.enableDecodeFrame?i.readable.pipeThrough(new TransformStream({transform:(e,t)=>t.enqueue(n.enqueue(e))})):i.readable).pipeTo(i.writable,r).catch((e=>{"destory"!==e&&this._log.warn(e)})),this.singlePC.addAbortController(t,r)}}receiveSEIByWorker(e,t){e.track.kind===Zb.AUDIO||!this._peerConnection||!this.singlePC||!this._room.videoManager.seiWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!0,userId:this.userId,streamType:t}))}subscribe(e,t){return ib(this,null,(function*(){try{if(this._log.info("subscribe ".concat(t," ").concat(VF(e))),this.hasSSRC){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(Cb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Cb.message," ").concat(JSON.stringify(this.muteState))),new fb({code:mb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Cb}}))}checkTrackEnded(e){var t,i,r;if((e.audio&&"ended"===(null==(t=this.remoteAudioTrack.mediaTrack)?void 0:t.readyState)||e.video&&"ended"===(null==(i=this.remoteVideoTrack.mediaTrack)?void 0:i.readyState)||e.auxiliary&&"ended"===(null==(r=this.remoteAuxiliaryTrack.mediaTrack)?void 0:r.readState))&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),TN&&yN<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return ib(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:r}=e;return function*(){var e;if("main"===r&&!t.isMainStreamSubscribed||"auxiliary"===r&&!t.isAuxStreamSubscribed)return void t._log.info("".concat(r," stream already unsubscribed"));let n=qC({},t.subscribeState);i.forEach((e=>{switch(e.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1}}));let o="subscribe_change";Object.values(n).find((e=>!0===e))||(o="unsubscribe"),t._log.info("".concat("unsubscribe"===o?o:"subscribe"," ").concat(r," [").concat(VF(n),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,n),"unsubscribe"===o&&(yield t.removeDownlink())}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=XV,n=HV.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=$V,n=HV.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:r,data:i,responseCommand:n,timeout:1e4,retries:3}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new fb({code:i.code,message:KN({key:oD.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected();try{if(i||!e.hasSSRC){let i={audioSsrc:OF(),bigVideoSsrc:OF(),bigVideoRtxSsrc:OF(),auxVideoSsrc:OF(),auxVideoRtxSsrc:OF()},{audioSsrc:n,bigVideoSsrc:o,bigVideoRtxSsrc:s,auxVideoSsrc:a,auxVideoRtxSsrc:c}=i;e.ssrc={audio:n,video:o,videoRtx:s,auxiliary:a,auxiliaryRtx:c},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let r=yield e._signalChannel.sendWaitForResponseWithRetry({command:uU,responseCommand:HV.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!1,ssrc:i},retries:3,retryTimeout:0});if(0!==r.data.code)throw new fb({code:r.data.code,message:r.data.message})}catch(r){throw yield e.removeDownlink(),r}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}finally{let t=e._room.scheduleResult.config;((null==t?void 0:t.jitterDelay)||(null==t?void 0:t.jitterDelayAux))&&e.setJitterBufferDelay({mainDelay:t.jitterDelay,auxDelay:t.jitterDelayAux})}}}()}))}removeDownlink(){return ib(this,null,(function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;((null==e?void 0:e.jitterDelay)||(null==e?void 0:e.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)}))}setJitterBufferDelay(e){let{mainDelay:t,auxDelay:i}=e;if(!this.singlePC||!this._peerConnection||pO(t)&&pO(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return Ow(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),Ow(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,pO(t)&&(this.remoteAudioTrack.jitterBufferDelay=i)),new Promise((e=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:e})}))}doSetJitterBufferDelay(e){let{mainDelay:t,auxDelay:i,receivers:r,resolve:n}=e,o=-1;try{if(0===t&&0===i)return r.forEach((e=>e.jitterBufferTarget=0)),n();if(r.forEach((e=>{var r;let n=e.track===this.remoteAuxiliaryTrack.outMediaTrack||pO(t)&&e.track===this.remoteAudioTrack.outMediaTrack;if(n&&pO(i)||!n&&pO(t))return;let o=n?i||0:t,s=(e.jitterBufferTarget||0)+100;s>o||(e.jitterBufferTarget=s,this._log.debug("set ".concat(n?"aux ":"").concat(null==(r=null==e?void 0:e.track)?void 0:r.kind," jitterBuffer delay ").concat(s," -> ").concat(o)))})),!r.find((e=>{let r=e.track===this.remoteAuxiliaryTrack.outMediaTrack?i||0:t;return e.jitterBufferTarget<r})))return this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i," done")),n();o=setTimeout((()=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:n})}),1e3)}catch(s){this._log.warn("set jitterBuffer delay error: ".concat(s)),clearTimeout(o),n()}}};ZC([lL(),rL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this.off("closed",n),r(new fb({code:mb.API_CALL_ABORTED,message:KN({key:oD.CONNECTION_ABORTED,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],UF.prototype,"subscribe",1),ZC([lL()],UF.prototype,"unsubscribe",1),ZC([uL((()=>"jitter"))],UF.prototype,"setJitterBufferDelay",1);var FF=UF;var BF=$C(rb());var HF=class extends BF.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,eb(this,"log"),eb(this,"cmdIdSeqMap",new Map),eb(this,"messageMap",new Map),this.log=TO.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(HV.RECEIVE_CUSTOM_MSG,this.onReceiveMsg)}send(e){let{cmdId:t,data:i}=e,r=this.cmdIdSeqMap.get(t)||Math.floor(16383*Math.random()),n={cmdId:t,msg:btoa(String.fromCharCode(...new Uint8Array(i))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(t,r+1),this.signalChannel.send(mU,n),this.log.debug("send custom msg: ".concat(JSON.stringify(n)))}onReceiveMsg(e){let{data:t}=e.data,i=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(i){let e={userId:i,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),(e=>e.charCodeAt(0))).buffer};if(t.ordered){let t="".concat(i,"_").concat(e.cmdId),r=this.messageMap.get(t);if(r&&0!==r.lastSeq)if(Math.abs(r.lastSeq-e.seq)>HF.SEQ_INTERVAL)this.messageMap.set(t,{lastSeq:e.seq,cachedMessageMap:new Map}),this.emitMessage(e);else if(e.seq>r.lastSeq){if(e.seq===r.lastSeq+1)this.emitMessage(e);else if(!r.cachedMessageMap.has(e.seq)){let t=setTimeout((()=>this.emitMessage(e,!0)),5e3);r.cachedMessageMap.set(e.seq,{message:e,timeoutId:t})}}else this.log.debug("drop message ".concat(e.userId,"-").concat(e.cmdId,"-").concat(e.seq));else r||(r={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(t,r),setTimeout((()=>this.emitMessage(e,!0)),100)),r.cachedMessageMap.set(e.seq,{message:e})}else this.emit("message",e)}}emitMessage(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i;let r=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),n=e;if(r){if(t){let e=[...r.cachedMessageMap.values()].sort(((e,t)=>e.message.seq-t.message.seq));e[0]&&(n=e[0].message)}0!==r.lastSeq&&n.seq-r.lastSeq>1&&this.log.debug("msg lost userId: ".concat(n.userId," seq: ").concat(r.lastSeq," -> ").concat(n.seq)),r.lastSeq=n.seq,clearTimeout(null==(i=r.cachedMessageMap.get(n.seq))?void 0:i.timeoutId),r.cachedMessageMap.delete(n.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(n))),this.emit("message",n);let o=null==r?void 0:r.cachedMessageMap.get(n.seq+1);o&&this.emitMessage(o.message)}},jF=HF;eb(jF,"SEQ_INTERVAL",300);var WF,{isString:GF,isUndefined:JF,getNetworkType:zF,isEmpty:KF}=vb,qF=class extends eF{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=QO,this._changeBigSmallRecords=new Map,this._networkQuality=null,this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=0,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this.preferHW=!1,this._stats=new MU(this,this._log),this.userManager=new cx(this.userId,this._log),this._version=Ib,this.sdpSemantics=Ok,JF(e.sdpSemantics)?yO.isUnifiedPlanDefault()&&(this.sdpSemantics=wk):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(zF())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!JF(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&QO,!JF(e.enableSPC)&&QO&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new SF(this)}get isMainStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex((e=>e.muteState.hasAuxiliary))>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,i){return ib(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",(e=>{this.emit("peer-join",e)})),this.userManager.on("2",(e=>{this.closeDownLinkConnection(e,"remote user exitRoom"),this.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(e=>{var t=((e,t)=>{var i={};for(var r in e)WC.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&HC)for(var r of HC(e))t.indexOf(r)<0&&GC.call(e,r)&&(i[r]=e[r]);return i})(e,[]);QN.emit(fO.REMOTE_PUBLISH_STATE_CHANGED,qC({room:this},t)),this.emit("remote-publish-state-changed",qC({},t))})),this.joinParams=e,new Promise(((t,i)=>ib(this,null,(function*(){var r,n;this._joinReject=i;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(o){if(!(o instanceof fb&&o.code===mb.SPC_INITIALIZED_FAILED))return i(o);null==(r=this.signalChannel)||r.destroy(),yield this.initialize()}let s=Ww();yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),zP.addSuccessEvent({key:521708,cost:Ww()-s}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(MP){zP.addFailedEvent({key:521708,error:MP}),i(MP)}this._joinReject=null}))))}))}initSinglePC(){return ib(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new kF({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",(e=>this.emit("sei-message",e))),this.singlePC.once("error",(()=>this.fallbackToMPC()));try{return yield this.singlePC.initialize()}catch(Rb){throw this.fallbackToMPC(),new fb({code:mb.SPC_INITIALIZED_FAILED,message:null==Rb?void 0:Rb.message})}}}))}doJoin(e,t){return new Promise(((i,r)=>ib(this,null,(function*(){var n,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(MV,(e=>{this.clearJoinTimeout(),QN.emit(fO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)})),Pw(null==(o=null==(n=this.scheduleResult)?void 0:n.config)?void 0:o.singlePC)&&QO&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let a={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:"live"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:WN(),netType:gw(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;(null==(s=this.scheduleResult.config)?void 0:s.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{r(new fb({code:mb.JOIN_ROOM_FAILED,message:KN({key:oD.JOIN_ROOM_TIMEOUT})}))}),c),QN.emit(fO.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?lU:WV,a),this.signalChannel.once(HV.JOIN_ROOM_RESULT,(e=>{this.clearJoinTimeout();let{code:t,message:n,data:o,tinyId:s}=e.data;QN.emit(fO.JOIN_RECEIVED_CMD_RES,{room:this,code:t}),0===t?(this._log.info("Join room success, start heartbeat"),s&&(this.tinyId=s),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=o.publishers,this.singlePC&&this.singlePC.connect(o.ability).catch((()=>{})),i()):(this._log.error("Join room failed result: ".concat(t," error: ").concat(n)),r(new fb({code:mb.JOIN_ROOM_FAILED,extraCode:t,message:KN({key:oD.JOIN_ROOM_FAILED,data:{error:n,code:t}})})))}))}))))}reJoin(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return ib(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let t,i=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,i.push(this.initSinglePC().then((e=>(t=e,e))))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),i.push(this.signalChannel.connect())),yield Promise.all(i),yield this.doJoin(YC(qC({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),$N.logSuccessEvent({userId:this.userId,eventType:bk.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(IF.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof xF&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(IF.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof PU&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(Rk){this._log.warn("reJoin fail ".concat(Rk)),this.reset(),$N.logFailedEvent({userId:this.userId,eventType:bk.REJOIN,error:Rk}),this.emit("error",new fb({code:mb.JOIN_ROOM_FAILED,message:KN({key:oD.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return ib(this,null,(function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this.signalChannel||function(e){let t=[..._U.values()].find((t=>t.room.userId===e&&!t.room.isJoined));return t||null}(this.userId),n=!!(r&&r.isConnected&&r.keepAlive);return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e=this.scheduleResult.domains[0]),this._log.info("".concat(n?"reuse":"setup"," signal channel")),n?(r.url=t,r.backupUrl=i,r.room=this,this.signalChannel=r):(this.signalChannel=new fU({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:t,backupUrl:i,race:this.enableSPC&&!this.proxy_ws,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?e:void 0}),this._customMessageManager=new jF(this,this.signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this._networkQuality||(this._networkQuality=new VU({signalChannel:this.signalChannel,room:this}),this._networkQuality.on(VU.EVENT_NETWORK_QUALITY,(e=>{this.emit("network-quality",e)}))),DP(this,this.signalChannel).add(LV,(e=>{QN.emit(fO.SIGNAL_CONNECTION_STATE_CHANGED,qC({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(UV,(e=>{this.reset(),this.emit("error",e)})).add(HV.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})).add(HV.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(HV.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(HV.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if($N.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(PV,(e=>{this.tinyId=e.signalInfo.tinyId,QN.emit(fO.JOIN_SIGNAL_CONNECTION_END,{room:this})})),QN.emit(fO.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&QN.emit(fO.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this.signalChannel=e,e||NP(this)}leave(){return ib(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(Rk){}this._log.info("leave() => leaving room"),QN.emit(fO.LEAVE_SEND_CMD,{room:this}),null==(e=this.signalChannel)||e.send(GV)}))}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach((e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")}))}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){-1===this._heartbeat&&(this._heartbeat=RP.run(Xk,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),RP.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return ib(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});this.badCaseDetector.resetMonitor();let r=null!=(e=this.signalChannel)&&e.isConnected?function(e){if(ox.has(e)){let t=ox.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType})));return ox.delete(e),t}return[]}(this.userId):[],n=YC(qC({str_sdk_version:Sb,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i),{msg_device_info:qC({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:gw()},i.msg_device_info)});if(this.heartbeatReport=n,QN.emit(fO.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(JV,n);let e=Date.now();this._lastHeartBeatTime>0&&e-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(e-this._lastHeartBeatTime)),this._lastHeartBeatTime=e}this.emit("heartbeat-report",YC(qC({},n),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map((e=>{let{userId:t,srcTinyId:i,flag:r}=e;t===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=r);let n=this.remotePublishedUserMap.get(t);return n&&this.checkSubscribeBigSmallVideo(n),{userId:t,tinyId:i,flag:r}}));QN.emit(fO.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof PU&&(this.uplinkConnection=null)),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r}=e,n=new(this.singlePC?FF:DU)({userId:t,tinyId:i,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,t),this.emit("remote-published",n)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",(e=>{let i=e.getCode();i!==mb.ICE_TRANSPORT_ERROR&&(i===mb.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",YC(qC({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=RP.run(Xk,this.syncUserList.bind(this)))}stopSyncUserListInterval(){RP.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then((e=>{this.userManager.setUserList(e)})).catch((e=>{this._log.debug("sync user list failed: ".concat(e))}))}getUserList(){var e;return null!=(e=this.signalChannel)&&e.isConnected?this.signalChannel.sendWaitForResponse({command:oU,responseCommand:HV.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((e=>{let{data:t}=e,{code:i,message:r}=t;if(0===i)return(t.data&&t.data.userList||[]).map((e=>{let{userId:t,srcTinyId:i,role:r}=e;return{userId:t,tinyId:i,role:r}}));throw KN({key:oD.SIGNAL_RESPONSE_FAILED,data:{signalResponse:HV.USER_LIST_RES,code:i,message:r}})})):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!yU)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?(null==(e=this.singlePC.getPeerConnection())?void 0:e.connectionState)===yk.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof SU&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===yk.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return ib(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),$N.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,null==(e=this.singlePC)||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new PU({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0})),e.close()}this.remotePublishedUserMap.forEach((e=>{let t=new DU({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:mb.INVALID_OPERATION,message:KN({key:oD.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy())}switchRole(e){return ib(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:sU,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:HV.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(t.data))),this.signalChannel.sendWaitForResponseWithRetry(t).then((t=>{let{code:i,message:r}=t.data;if(0!==i)throw new fb({code:mb.SWITCH_ROLE_FAILED,message:KN({key:oD.SWITCH_ROLE_FAILED,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof fb&&e.getCode()===mb.API_CALL_TIMEOUT&&(e=new fb({code:mb.SWITCH_ROLE_FAILED,message:KN({key:oD.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 ib(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof _L&&(t instanceof IL?i.audio=t:e.audio=t),t instanceof TL&&(t instanceof SL&&2===t.mediaType?i.video=t:e.video=t)}));let r=KF(e),n=KF(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new xF({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new PU({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",YC(qC({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==mb.ICE_TRANSPORT_ERROR&&(t===mb.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})));let o=t.map((e=>e.kind)).join(",");r||(this._log.info("publish() => main ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:e.audio,localVideoTrack:e.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info("publish() => aux ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:i.audio,localVideoTrack:i.video,isAuxiliary:!0}),this._log.info("aux is published"))}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ib(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 _L&&(t instanceof IL?i.audio=t:e.audio=t),t instanceof TL&&(t instanceof SL&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");KF(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),KF(i)||(this._log.info("unpublish() => aux ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(r){}0===this.localTracks.size&&this.closeUplink("you unpublished")}))}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return this.uplinkConnection&&e.mediaTrack?this.uplinkConnection.removeTrack(e).then((t=>(e.unpublish(),t))):Promise.resolve()}replaceTrack(e){return this.uplinkConnection&&e.mediaTrack&&$O()?this.uplinkConnection.replaceTrack(e).then((t=>{t&&QN.emit(fO.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return ib(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return ib(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:Zb.VIDEO,videoType:Zb.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 ib(this,null,(function*(){if(t=t.filter((e=>!e.isSubscribed)),0===t.length)return;let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let r=t.find((e=>2===e.mediaType))?"auxiliary":"main";try{let n=qC({},i.subscribeState);t.forEach((e=>{switch(e.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0}}));let o=this._changeBigSmallRecords.get(e);o&&o.options.smallVideo&&i.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),QN.emit(fO.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(CU(n),"] prev: [").concat(CU(i.subscribeState),"]")),yield i.subscribe(n,r),this._log.info("subscribe ".concat(e," ").concat(r," done"));for(let e of t)e.mediaTrack||(yield e.waitHasMediaTrack());QN.emit(fO.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(bb){let i=bb instanceof fb?bb.getCode():mb.UNKNOWN,n=bb;throw bb instanceof fb?i===mb.REMOTE_STREAM_NOT_EXIST&&(n=new fb({code:mb.API_CALL_ABORTED,message:KN({key:oD.API_CALL_ABORTED,data:{message:bb.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new fb({code:i,message:KN({key:oD.SUBSCRIBE_FAILED,data:{message:bb.message,userId:e,streamType:r}})}),this._log.error(n)),n}}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ib(this,null,(function*(){let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let r=t.find((e=>2===e.mediaType))?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(e," ").concat(r));try{yield i.unsubscribe({remoteTracks:t,streamType:r})}catch(bb){this._log.warn("unsubscribe() => failed ".concat(bb))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),QN.emit(fO.UNSUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1?arguments[1]:void 0;if(e<=0)return this._enableAudioVolumeEvaluation=!1,void RP.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),QN.emit(fO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&RP.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=RP.run($k,(()=>{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 ib(this,null,(function*(){var e;let t={};return t[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},null!=(e=this.uplinkConnection)&&e.localMainAudioTrack&&(t[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),t}))}getLocalVideoStats(){return ib(this,null,(function*(){var e,t;let i={};return i[this.userId]=(null==(t=null==(e=this.uplinkConnection)?void 0:e.localMainVideoTrack)?void 0:t.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},i}))}getTransportStats(){return ib(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 ib(this,null,(function*(){let t={};for(let[i,r]of this.remotePublishedUserMap)"main"===e&&r.muteState.hasVideo&&(t[i]=r.remoteVideoTrack.stat),"auxiliary"===e&&r.muteState.hasAuxiliary&&(t[i]=r.remoteAuxiliaryTrack.stat);return t}))}getRemoteAudioStats(){return ib(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(vb.getTurnServer(e)))):vb.isPlainObject(e)&&i.push(vb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:rU,data:e,timeout:5e3,responseCommand:HV.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:nU,data:e,timeout:5e3,responseCommand:HV.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?ZV:tU,data:e,timeout:5e3,responseCommand:t?HV.START_PUBLISH_TENCENT_CDN_RES:HV.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?eU:iU,data:e,timeout:5e3,responseCommand:t?HV.STOP_PUBLISH_TENCENT_CDN_RES:HV.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:hU,data:e,timeout:5e3,responseCommand:HV.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=vb.getEnv();return t?(e.mainUrl="wss://".concat(t,".rtc.qq.com"),e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl="wss://".concat(this.proxy_unified),e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}getSignalInfo(){var e;return(null==(e=this.signalChannel)?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):this.signalChannel.close(),this.setSignalChannel(null)),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return ib(this,null,(function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:r,hasVideo:n}}=e;if(!r&&!n||!t.video&&!t.smallVideo)return;let o=this._changeBigSmallRecords.get(i);if(!o||o.isSubscribing||o.reSubscribeCount<=0)return;let{options:s,reSubscribeCount:a}=o;if(s.video&&t.video||s.smallVideo&&t.smallVideo&&r)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:s.video,smallVideo:s.smallVideo};try{if(!r&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;o.isSubscribing=!0,o.reSubscribeCount=a-1,yield e.subscribe(c,"main"),e.remoteVideoTrack.setMediaType(c.smallVideo?8:4),this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video successfully. count ").concat(Yk-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=Yk}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(Yk-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:Yk};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(GF(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!JF(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new fb({code:mb.INVALID_PARAMETER,message:KN({key:oD.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(!JF(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new fb({code:mb.INVALID_PARAMETER,message:KN({key:oD.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!JF(e.userDefinePushArgs)){if(!(GF(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new fb({code:mb.INVALID_PARAMETER,message:KN({key:oD.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}KF(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&iP)return this.singlePC.enableInsertableStreams=!0,this.singlePC.startReconnection()}sendSignalMessage(e){var t;return this.signalChannel?null==(t=this.signalChannel)?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new fb({code:mb.INVALID_OPERATION,message:"not join"}))}};return ZC([aF(["left",dF.INIT],"joined"),OP({settings:{retries:1,timeout:0},onError(e,t,i){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),tw(!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))}}),rL((e=>{let t=new NV;return function(i,r,n){return ib(this,null,(function*(){let o=String(i.roomId||i.strRoomId);if(this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.userSig=i.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,i.privateMapKey=i.privateMapKey||"",this.isJoined)throw new fb({code:mb.INVALID_OPERATION,message:KN({key:oD.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new fb({code:mb.INVALID_OPERATION,message:KN({key:oD.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)),QN.emit(fO.JOIN_START,{room:this,roomId:o,params:i}),this.checkSystemResult=yield yO.checkSystemRequirementsInternal(),this.checkDestroy();let s=vb.getEnv();s||(s=Wb.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(tk.OLD_CLOUD_LADDER)?s=Wb.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(tk.WEBRTC)&&(s=Wb.WEBRTC))),$N.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),wV.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!yO.isWebRTCSupported()||!a&&!c)throw new fb({code:mb.NOT_SUPPORTED,message:KN({key:oD.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!vb.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=vb.performanceNow(),QN.emit(fO.JOIN_SUCCESS,{room:this}),30===n&&!i.component&&$N.uploadEvent({log:"stat-conv-".concat(Number(ON),"-").concat(location.hostname),userId:this.userId}),t}catch(MP){throw t.delete({room:this,roomId:o}),QN.emit(fO.JOIN_FAILED,{room:this,error:MP}),MP}}))}}))],qF.prototype,"join",1),ZC([aF("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),rL((e=>function(){return ib(this,null,(function*(){QN.emit(fO.LEAVE_START,{room:this}),yield e.call(this),QN.emit(fO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),dL("leave room"),PP({fnName:"publish",validateArgs:!1}),PP({fnName:"unsubscribe",validateArgs:!1})],qF.prototype,"leave",1),ZC([lL(),rL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return ib(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"capture"===e.state)),!i.length))return;QN.emit("61",{room:this});let t=e.apply(this,i);return i.forEach((e=>e.publish(this,t))),t}))})),OP({settings:{retries:Ak,timeout:e=>bw(e)},onError(e,t,i){var r;null!=(r=e.message)&&r.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error("publish failed: ".concat(e)),i(e),QN.emit(fO.PUBLISH_FAILED,{room:this}))}})],qF.prototype,"publish",1),ZC([PP({fnName:"publish"}),(WF="api-call",function(e,t,i){let r=i.value;return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let n=aL.get(this);if(n){let e=n.queue.filter(((e,i)=>{if(0===i)return!0;let r=!0;return e.args.forEach((e=>{t.find((t=>t===e))||(r=!1)})),!r||(e.reject(new fb({code:mb.API_CALL_ABORTED,message:WF})),!1)}));n.queue=e}return r.apply(this,t)},i}),lL(),rL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let n=e.apply(this,i);return i.forEach((e=>e.unpublish())),n})),iL((function(){var e,t;0===this.localTracks.size&&KO()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((e=>e.track&&e.replaceTrack(null))))}))],qF.prototype,"unpublish",1),ZC([uL((e=>e.userId))],qF.prototype,"replaceTrack",1),ZC([uL((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),RL(),rL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let n=e.apply(this,i);return i.forEach((e=>!e.isSubscribed&&e.subscribe(n))),n})),OP({settings:{retries:Ak,timeout:e=>bw(e)},onError(e,t,i,r){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),i(e),QN.emit(fO.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],qF.prototype,"subscribe",1),ZC([PP({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")}))}}),uL((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],qF.prototype,"unsubscribe",1),DV.create=DV._create.bind(DV,qF),DV}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TRTC=t()}(this,(function(){function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},i=function(e){try{return!!e()}catch(t){return!0}},r=!i((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),n=r,o=Function.prototype,s=o.call,a=n&&o.bind.bind(s,s),c=n?a:function(e){return function(){return s.apply(e,arguments)}},l=c,d=l({}.toString),u=l("".slice),h=function(e){return u(d(e),8,-1)},p=i,m=h,_=Object,f=c("".split),g=p((function(){return!_("z").propertyIsEnumerable(0)}))?function(e){return"String"==m(e)?f(e,""):_(e)}:_,T=function(e){return null==e},E=T,S=TypeError,y=function(e){if(E(e))throw S("Can't call method on "+e);return e},v=g,I=y,A=function(e){return v(I(e))},R=function(e){return e&&e.Math==Math&&e},C=R("object"==typeof globalThis&&globalThis)||R("object"==typeof window&&window)||R("object"==typeof self&&self)||R("object"==typeof t&&t)||function(){return this}()||Function("return this")(),b={},k={get exports(){return b},set exports(e){b=e}},D=C,N=Object.defineProperty,w=function(e,t){try{N(D,e,{value:t,configurable:!0,writable:!0})}catch(i){D[e]=t}return t},O=w,P="__core-js_shared__",M=C[P]||O(P,{}),L=M;(k.exports=function(e,t){return L[e]||(L[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.30.0",mode:"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.30.0/LICENSE",source:"https://github.com/zloirock/core-js"});var x,V,U=y,F=Object,B=function(e){return F(U(e))},H=B,j=c({}.hasOwnProperty),W=Object.hasOwn||function(e,t){return j(H(e),t)},G=c,J=0,K=Math.random(),z=G(1..toString),q=function(e){return"Symbol("+(void 0===e?"":e)+")_"+z(++J+K,36)},Y="undefined"!=typeof navigator&&String(navigator.userAgent)||"",Q=C,X=Y,$=Q.process,Z=Q.Deno,ee=$&&$.versions||Z&&Z.version,te=ee&&ee.v8;te&&(V=(x=te.split("."))[0]>0&&x[0]<4?1:+(x[0]+x[1])),!V&&X&&(!(x=X.match(/Edge\/(\d+)/))||x[1]>=74)&&(x=X.match(/Chrome\/(\d+)/))&&(V=+x[1]);var ie=V,re=ie,ne=i,oe=!!Object.getOwnPropertySymbols&&!ne((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&re&&re<41})),se=oe&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ae=b,ce=W,le=q,de=oe,ue=se,he=C.Symbol,pe=ae("wks"),me=ue?he.for||he:he&&he.withoutSetter||le,_e=function(e){return ce(pe,e)||(pe[e]=de&&ce(he,e)?he[e]:me("Symbol."+e)),pe[e]},fe="object"==typeof document&&document.all,ge={all:fe,IS_HTMLDDA:void 0===fe&&void 0!==fe},Te=ge.all,Ee=ge.IS_HTMLDDA?function(e){return"function"==typeof e||e===Te}:function(e){return"function"==typeof e},Se=Ee,ye=ge.all,ve=ge.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:Se(e)||e===ye}:function(e){return"object"==typeof e?null!==e:Se(e)},Ie=ve,Ae=String,Re=TypeError,Ce=function(e){if(Ie(e))return e;throw Re(Ae(e)+" is not an object")},be={},ke=!i((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),De=ke&&i((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Ne={},we=ve,Oe=C.document,Pe=we(Oe)&&we(Oe.createElement),Me=function(e){return Pe?Oe.createElement(e):{}},Le=Me,xe=!ke&&!i((function(){return 7!=Object.defineProperty(Le("div"),"a",{get:function(){return 7}}).a})),Ve=r,Ue=Function.prototype.call,Fe=Ve?Ue.bind(Ue):function(){return Ue.apply(Ue,arguments)},Be=C,He=Ee,je=function(e,t){return arguments.length<2?(i=Be[e],He(i)?i:void 0):Be[e]&&Be[e][t];var i},We=c({}.isPrototypeOf),Ge=je,Je=Ee,Ke=We,ze=Object,qe=se?function(e){return"symbol"==typeof e}:function(e){var t=Ge("Symbol");return Je(t)&&Ke(t.prototype,ze(e))},Ye=String,Qe=function(e){try{return Ye(e)}catch(t){return"Object"}},Xe=Ee,$e=Qe,Ze=TypeError,et=function(e){if(Xe(e))return e;throw Ze($e(e)+" is not a function")},tt=et,it=T,rt=function(e,t){var i=e[t];return it(i)?void 0:tt(i)},nt=Fe,ot=Ee,st=ve,at=TypeError,ct=Fe,lt=ve,dt=qe,ut=rt,ht=function(e,t){var i,r;if("string"===t&&ot(i=e.toString)&&!st(r=nt(i,e)))return r;if(ot(i=e.valueOf)&&!st(r=nt(i,e)))return r;if("string"!==t&&ot(i=e.toString)&&!st(r=nt(i,e)))return r;throw at("Can't convert object to primitive value")},pt=TypeError,mt=_e("toPrimitive"),_t=function(e,t){if(!lt(e)||dt(e))return e;var i,r=ut(e,mt);if(r){if(void 0===t&&(t="default"),i=ct(r,e,t),!lt(i)||dt(i))return i;throw pt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ht(e,t)},ft=_t,gt=qe,Tt=function(e){var t=ft(e,"string");return gt(t)?t:t+""},Et=ke,St=xe,yt=De,vt=Ce,It=Tt,At=TypeError,Rt=Object.defineProperty,Ct=Object.getOwnPropertyDescriptor,bt="enumerable",kt="configurable",Dt="writable";Ne.f=Et?yt?function(e,t,i){if(vt(e),t=It(t),vt(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Dt in i&&!i[Dt]){var r=Ct(e,t);r&&r[Dt]&&(e[t]=i.value,i={configurable:kt in i?i[kt]:r[kt],enumerable:bt in i?i[bt]:r[bt],writable:!1})}return Rt(e,t,i)}:Rt:function(e,t,i){if(vt(e),t=It(t),vt(i),St)try{return Rt(e,t,i)}catch(r){}if("get"in i||"set"in i)throw At("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Nt=Math.ceil,wt=Math.floor,Ot=Math.trunc||function(e){var t=+e;return(t>0?wt:Nt)(t)},Pt=Ot,Mt=function(e){var t=+e;return t!=t||0===t?0:Pt(t)},Lt=Mt,xt=Math.max,Vt=Math.min,Ut=function(e,t){var i=Lt(e);return i<0?xt(i+t,0):Vt(i,t)},Ft=Mt,Bt=Math.min,Ht=function(e){return e>0?Bt(Ft(e),9007199254740991):0},jt=Ht,Wt=function(e){return jt(e.length)},Gt=A,Jt=Ut,Kt=Wt,zt=function(e){return function(t,i,r){var n,o=Gt(t),s=Kt(o),a=Jt(r,s);if(e&&i!=i){for(;s>a;)if((n=o[a++])!=n)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===i)return e||a||0;return!e&&-1}},qt={includes:zt(!0),indexOf:zt(!1)},Yt={},Qt=W,Xt=A,$t=qt.indexOf,Zt=Yt,ei=c([].push),ti=function(e,t){var i,r=Xt(e),n=0,o=[];for(i in r)!Qt(Zt,i)&&Qt(r,i)&&ei(o,i);for(;t.length>n;)Qt(r,i=t[n++])&&(~$t(o,i)||ei(o,i));return o},ii=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ri=ti,ni=ii,oi=Object.keys||function(e){return ri(e,ni)},si=ke,ai=De,ci=Ne,li=Ce,di=A,ui=oi;be.f=si&&!ai?Object.defineProperties:function(e,t){li(e);for(var i,r=di(t),n=ui(t),o=n.length,s=0;o>s;)ci.f(e,i=n[s++],r[i]);return e};var hi,pi=je("document","documentElement"),mi=q,_i=b("keys"),fi=function(e){return _i[e]||(_i[e]=mi(e))},gi=Ce,Ti=be,Ei=ii,Si=Yt,yi=pi,vi=Me,Ii="prototype",Ai="script",Ri=fi("IE_PROTO"),Ci=function(){},bi=function(e){return"<"+Ai+">"+e+"</"+Ai+">"},ki=function(e){e.write(bi("")),e.close();var t=e.parentWindow.Object;return e=null,t},Di=function(){try{hi=new ActiveXObject("htmlfile")}catch(n){}var e,t,i;Di="undefined"!=typeof document?document.domain&&hi?ki(hi):(t=vi("iframe"),i="java"+Ai+":",t.style.display="none",yi.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(bi("document.F=Object")),e.close(),e.F):ki(hi);for(var r=Ei.length;r--;)delete Di[Ii][Ei[r]];return Di()};Si[Ri]=!0;var Ni=Object.create||function(e,t){var i;return null!==e?(Ci[Ii]=gi(e),i=new Ci,Ci[Ii]=null,i[Ri]=e):i=Di(),void 0===t?i:Ti.f(i,t)},wi=_e,Oi=Ni,Pi=Ne.f,Mi=wi("unscopables"),Li=Array.prototype;null==Li[Mi]&&Pi(Li,Mi,{configurable:!0,value:Oi(null)});var xi,Vi,Ui,Fi=function(e){Li[Mi][e]=!0},Bi={},Hi=Ee,ji=C.WeakMap,Wi=Hi(ji)&&/native code/.test(String(ji)),Gi=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},Ji=Ne,Ki=Gi,zi=ke?function(e,t,i){return Ji.f(e,t,Ki(1,i))}:function(e,t,i){return e[t]=i,e},qi=Wi,Yi=C,Qi=ve,Xi=zi,$i=W,Zi=M,er=fi,tr=Yt,ir="Object already initialized",rr=Yi.TypeError,nr=Yi.WeakMap;if(qi||Zi.state){var or=Zi.state||(Zi.state=new nr);or.get=or.get,or.has=or.has,or.set=or.set,xi=function(e,t){if(or.has(e))throw rr(ir);return t.facade=e,or.set(e,t),t},Vi=function(e){return or.get(e)||{}},Ui=function(e){return or.has(e)}}else{var sr=er("state");tr[sr]=!0,xi=function(e,t){if($i(e,sr))throw rr(ir);return t.facade=e,Xi(e,sr,t),t},Vi=function(e){return $i(e,sr)?e[sr]:{}},Ui=function(e){return $i(e,sr)}}var ar={set:xi,get:Vi,has:Ui,enforce:function(e){return Ui(e)?Vi(e):xi(e,{})},getterFor:function(e){return function(t){var i;if(!Qi(t)||(i=Vi(t)).type!==e)throw rr("Incompatible receiver, "+e+" required");return i}}},cr={},lr={},dr={}.propertyIsEnumerable,ur=Object.getOwnPropertyDescriptor,hr=ur&&!dr.call({1:2},1);lr.f=hr?function(e){var t=ur(this,e);return!!t&&t.enumerable}:dr;var pr=ke,mr=Fe,_r=lr,fr=Gi,gr=A,Tr=Tt,Er=W,Sr=xe,yr=Object.getOwnPropertyDescriptor;cr.f=pr?yr:function(e,t){if(e=gr(e),t=Tr(t),Sr)try{return yr(e,t)}catch(i){}if(Er(e,t))return fr(!mr(_r.f,e,t),e[t])};var vr={},Ir={get exports(){return vr},set exports(e){vr=e}},Ar=ke,Rr=W,Cr=Function.prototype,br=Ar&&Object.getOwnPropertyDescriptor,kr=Rr(Cr,"name"),Dr={EXISTS:kr,PROPER:kr&&"something"===function(){}.name,CONFIGURABLE:kr&&(!Ar||Ar&&br(Cr,"name").configurable)},Nr=Ee,wr=M,Or=c(Function.toString);Nr(wr.inspectSource)||(wr.inspectSource=function(e){return Or(e)});var Pr=wr.inspectSource,Mr=c,Lr=i,xr=Ee,Vr=W,Ur=ke,Fr=Dr.CONFIGURABLE,Br=Pr,Hr=ar.enforce,jr=ar.get,Wr=String,Gr=Object.defineProperty,Jr=Mr("".slice),Kr=Mr("".replace),zr=Mr([].join),qr=Ur&&!Lr((function(){return 8!==Gr((function(){}),"length",{value:8}).length})),Yr=String(String).split("String"),Qr=Ir.exports=function(e,t,i){"Symbol("===Jr(Wr(t),0,7)&&(t="["+Kr(Wr(t),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Vr(e,"name")||Fr&&e.name!==t)&&(Ur?Gr(e,"name",{value:t,configurable:!0}):e.name=t),qr&&i&&Vr(i,"arity")&&e.length!==i.arity&&Gr(e,"length",{value:i.arity});try{i&&Vr(i,"constructor")&&i.constructor?Ur&&Gr(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var r=Hr(e);return Vr(r,"source")||(r.source=zr(Yr,"string"==typeof t?t:"")),e};Function.prototype.toString=Qr((function(){return xr(this)&&jr(this).source||Br(this)}),"toString");var Xr=Ee,$r=Ne,Zr=vr,en=w,tn=function(e,t,i,r){r||(r={});var n=r.enumerable,o=void 0!==r.name?r.name:t;if(Xr(i)&&Zr(i,o,r),r.global)n?e[t]=i:en(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch(s){}n?e[t]=i:$r.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},rn={},nn=ti,on=ii.concat("length","prototype");rn.f=Object.getOwnPropertyNames||function(e){return nn(e,on)};var sn={};sn.f=Object.getOwnPropertySymbols;var an,cn,ln,dn=je,un=rn,hn=sn,pn=Ce,mn=c([].concat),_n=dn("Reflect","ownKeys")||function(e){var t=un.f(pn(e)),i=hn.f;return i?mn(t,i(e)):t},fn=W,gn=_n,Tn=cr,En=Ne,Sn=function(e,t,i){for(var r=gn(t),n=En.f,o=Tn.f,s=0;s<r.length;s++){var a=r[s];fn(e,a)||i&&fn(i,a)||n(e,a,o(t,a))}},yn=i,vn=Ee,In=/#|\.prototype\./,An=function(e,t){var i=Cn[Rn(e)];return i==kn||i!=bn&&(vn(t)?yn(t):!!t)},Rn=An.normalize=function(e){return String(e).replace(In,".").toLowerCase()},Cn=An.data={},bn=An.NATIVE="N",kn=An.POLYFILL="P",Dn=An,Nn=C,wn=cr.f,On=zi,Pn=tn,Mn=w,Ln=Sn,xn=Dn,Vn=function(e,t){var i,r,n,o,s,a=e.target,c=e.global,l=e.stat;if(i=c?Nn:l?Nn[a]||Mn(a,{}):(Nn[a]||{}).prototype)for(r in t){if(o=t[r],n=e.dontCallGetSet?(s=wn(i,r))&&s.value:i[r],!xn(c?r:a+(l?".":"#")+r,e.forced)&&void 0!==n){if(typeof o==typeof n)continue;Ln(o,n)}(e.sham||n&&n.sham)&&On(o,"sham",!0),Pn(i,r,o,e)}},Un=!i((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Fn=W,Bn=Ee,Hn=B,jn=Un,Wn=fi("IE_PROTO"),Gn=Object,Jn=Gn.prototype,Kn=jn?Gn.getPrototypeOf:function(e){var t=Hn(e);if(Fn(t,Wn))return t[Wn];var i=t.constructor;return Bn(i)&&t instanceof i?i.prototype:t instanceof Gn?Jn:null},zn=i,qn=Ee,Yn=ve,Qn=Kn,Xn=tn,$n=_e("iterator"),Zn=!1;[].keys&&("next"in(ln=[].keys())?(cn=Qn(Qn(ln)))!==Object.prototype&&(an=cn):Zn=!0);var eo=!Yn(an)||zn((function(){var e={};return an[$n].call(e)!==e}));eo&&(an={}),qn(an[$n])||Xn(an,$n,(function(){return this}));var to={IteratorPrototype:an,BUGGY_SAFARI_ITERATORS:Zn},io=Ne.f,ro=W,no=_e("toStringTag"),oo=function(e,t,i){e&&!i&&(e=e.prototype),e&&!ro(e,no)&&io(e,no,{configurable:!0,value:t})},so=to.IteratorPrototype,ao=Ni,co=Gi,lo=oo,uo=Bi,ho=function(){return this},po=function(e,t,i,r){var n=t+" Iterator";return e.prototype=ao(so,{next:co(+!r,i)}),lo(e,n,!1),uo[n]=ho,e},mo=c,_o=et,fo=Ee,go=String,To=TypeError,Eo=function(e,t,i){try{return mo(_o(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},So=Ce,yo=function(e){if("object"==typeof e||fo(e))return e;throw To("Can't set "+go(e)+" as a prototype")},vo=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Eo(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return So(i),yo(r),t?e(i,r):i.__proto__=r,i}}():void 0),Io=Vn,Ao=Fe,Ro=Ee,Co=po,bo=Kn,ko=vo,Do=oo,No=zi,wo=tn,Oo=Bi,Po=Dr.PROPER,Mo=Dr.CONFIGURABLE,Lo=to.IteratorPrototype,xo=to.BUGGY_SAFARI_ITERATORS,Vo=_e("iterator"),Uo="keys",Fo="values",Bo="entries",Ho=function(){return this},jo=function(e,t,i,r,n,o,s){Co(i,t,r);var a,c,l,d=function(e){if(e===n&&_)return _;if(!xo&&e in p)return p[e];switch(e){case Uo:case Fo:case Bo:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[Vo]||p["@@iterator"]||n&&p[n],_=!xo&&m||d(n),f="Array"==t&&p.entries||m;if(f&&(a=bo(f.call(new e)))!==Object.prototype&&a.next&&(bo(a)!==Lo&&(ko?ko(a,Lo):Ro(a[Vo])||wo(a,Vo,Ho)),Do(a,u,!0)),Po&&n==Fo&&m&&m.name!==Fo&&(Mo?No(p,"name",Fo):(h=!0,_=function(){return Ao(m,this)})),n)if(c={values:d(Fo),keys:o?_:d(Uo),entries:d(Bo)},s)for(l in c)(xo||h||!(l in p))&&wo(p,l,c[l]);else Io({target:t,proto:!0,forced:xo||h},c);return p[Vo]!==_&&wo(p,Vo,_,{name:n}),Oo[t]=_,c},Wo=function(e,t){return{value:e,done:t}},Go=A,Jo=Fi,Ko=Bi,zo=ar,qo=Ne.f,Yo=jo,Qo=Wo,Xo=ke,$o="Array Iterator",Zo=zo.set,es=zo.getterFor($o),ts=Yo(Array,"Array",(function(e,t){Zo(this,{type:$o,target:Go(e),index:0,kind:t})}),(function(){var e=es(this),t=e.target,i=e.kind,r=e.index++;return!t||r>=t.length?(e.target=void 0,Qo(void 0,!0)):Qo("keys"==i?r:"values"==i?t[r]:[r,t[r]],!1)}),"values"),is=Ko.Arguments=Ko.Array;if(Jo("keys"),Jo("values"),Jo("entries"),Xo&&"values"!==is.name)try{qo(is,"name",{value:"values"})}catch(FF){}var rs={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},ns=Me("span").classList,os=ns&&ns.constructor&&ns.constructor.prototype,ss=os===Object.prototype?void 0:os,as=C,cs=rs,ls=ss,ds=ts,us=zi,hs=_e,ps=hs("iterator"),ms=hs("toStringTag"),_s=ds.values,fs=function(e,t){if(e){if(e[ps]!==_s)try{us(e,ps,_s)}catch(FF){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(FF){e[i]=ds[i]}}};for(var gs in cs)fs(as[gs]&&as[gs].prototype,gs);fs(ls,"DOMTokenList");var Ts="undefined"!=typeof process&&"process"==h(process),Es=vr,Ss=Ne,ys=function(e,t,i){return i.get&&Es(i.get,t,{getter:!0}),i.set&&Es(i.set,t,{setter:!0}),Ss.f(e,t,i)},vs=je,Is=ys,As=ke,Rs=_e("species"),Cs=function(e){var t=vs(e);As&&t&&!t[Rs]&&Is(t,Rs,{configurable:!0,get:function(){return this}})},bs=We,ks=TypeError,Ds=function(e,t){if(bs(t,e))return e;throw ks("Incorrect invocation")},Ns={};Ns[_e("toStringTag")]="z";var ws="[object z]"===String(Ns),Os=Ee,Ps=h,Ms=_e("toStringTag"),Ls=Object,xs="Arguments"==Ps(function(){return arguments}()),Vs=ws?Ps:function(e){var t,i,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(FF){}}(t=Ls(e),Ms))?i:xs?Ps(t):"Object"==(r=Ps(t))&&Os(t.callee)?"Arguments":r},Us=c,Fs=i,Bs=Ee,Hs=Vs,js=Pr,Ws=function(){},Gs=[],Js=je("Reflect","construct"),Ks=/^\s*(?:class|function)\b/,zs=Us(Ks.exec),qs=!Ks.exec(Ws),Ys=function(e){if(!Bs(e))return!1;try{return Js(Ws,Gs,e),!0}catch(FF){return!1}},Qs=function(e){if(!Bs(e))return!1;switch(Hs(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return qs||!!zs(Ks,js(e))}catch(FF){return!0}};Qs.sham=!0;var Xs,$s,Zs,ea,ta=!Js||Fs((function(){var e;return Ys(Ys.call)||!Ys(Object)||!Ys((function(){e=!0}))||e}))?Qs:Ys,ia=ta,ra=Qe,na=TypeError,oa=function(e){if(ia(e))return e;throw na(ra(e)+" is not a constructor")},sa=Ce,aa=oa,ca=T,la=_e("species"),da=function(e,t){var i,r=sa(e).constructor;return void 0===r||ca(i=sa(r)[la])?t:aa(i)},ua=r,ha=Function.prototype,pa=ha.apply,ma=ha.call,_a="object"==typeof Reflect&&Reflect.apply||(ua?ma.bind(pa):function(){return ma.apply(pa,arguments)}),fa=h,ga=c,Ta=function(e){if("Function"===fa(e))return ga(e)},Ea=et,Sa=r,ya=Ta(Ta.bind),va=function(e,t){return Ea(e),void 0===t?e:Sa?ya(e,t):function(){return e.apply(t,arguments)}},Ia=c([].slice),Aa=TypeError,Ra=function(e,t){if(e<t)throw Aa("Not enough arguments");return e},Ca=/(?:ipad|iphone|ipod).*applewebkit/i.test(Y),ba=C,ka=_a,Da=va,Na=Ee,wa=W,Oa=i,Pa=pi,Ma=Ia,La=Me,xa=Ra,Va=Ca,Ua=Ts,Fa=ba.setImmediate,Ba=ba.clearImmediate,Ha=ba.process,ja=ba.Dispatch,Wa=ba.Function,Ga=ba.MessageChannel,Ja=ba.String,Ka=0,za={},qa="onreadystatechange";Oa((function(){Xs=ba.location}));var Ya=function(e){if(wa(za,e)){var t=za[e];delete za[e],t()}},Qa=function(e){return function(){Ya(e)}},Xa=function(e){Ya(e.data)},$a=function(e){ba.postMessage(Ja(e),Xs.protocol+"//"+Xs.host)};Fa&&Ba||(Fa=function(e){xa(arguments.length,1);var t=Na(e)?e:Wa(e),i=Ma(arguments,1);return za[++Ka]=function(){ka(t,void 0,i)},$s(Ka),Ka},Ba=function(e){delete za[e]},Ua?$s=function(e){Ha.nextTick(Qa(e))}:ja&&ja.now?$s=function(e){ja.now(Qa(e))}:Ga&&!Va?(ea=(Zs=new Ga).port2,Zs.port1.onmessage=Xa,$s=Da(ea.postMessage,ea)):ba.addEventListener&&Na(ba.postMessage)&&!ba.importScripts&&Xs&&"file:"!==Xs.protocol&&!Oa($a)?($s=$a,ba.addEventListener("message",Xa,!1)):$s=qa in La("script")?function(e){Pa.appendChild(La("script"))[qa]=function(){Pa.removeChild(this),Ya(e)}}:function(e){setTimeout(Qa(e),0)});var Za={set:Fa,clear:Ba},ec=function(){this.head=null,this.tail=null};ec.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var tc,ic,rc,nc,oc,sc=ec,ac=/ipad|iphone|ipod/i.test(Y)&&"undefined"!=typeof Pebble,cc=/web0s(?!.*chrome)/i.test(Y),lc=C,dc=va,uc=cr.f,hc=Za.set,pc=sc,mc=Ca,_c=ac,fc=cc,gc=Ts,Tc=lc.MutationObserver||lc.WebKitMutationObserver,Ec=lc.document,Sc=lc.process,yc=lc.Promise,vc=uc(lc,"queueMicrotask"),Ic=vc&&vc.value;if(!Ic){var Ac=new pc,Rc=function(){var e,t;for(gc&&(e=Sc.domain)&&e.exit();t=Ac.get();)try{t()}catch(FF){throw Ac.head&&tc(),FF}e&&e.enter()};mc||gc||fc||!Tc||!Ec?!_c&&yc&&yc.resolve?((nc=yc.resolve(void 0)).constructor=yc,oc=dc(nc.then,nc),tc=function(){oc(Rc)}):gc?tc=function(){Sc.nextTick(Rc)}:(hc=dc(hc,lc),tc=function(){hc(Rc)}):(ic=!0,rc=Ec.createTextNode(""),new Tc(Rc).observe(rc,{characterData:!0}),tc=function(){rc.data=ic=!ic}),Ic=function(e){Ac.head||tc(),Ac.add(e)}}var Cc=Ic,bc=function(e){try{return{error:!1,value:e()}}catch(FF){return{error:!0,value:FF}}},kc=C.Promise,Dc="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,Nc=!Dc&&!Ts&&"object"==typeof window&&"object"==typeof document,wc=C,Oc=kc,Pc=Ee,Mc=Dn,Lc=Pr,xc=_e,Vc=Nc,Uc=Dc,Fc=ie;Oc&&Oc.prototype;var Bc=xc("species"),Hc=!1,jc=Pc(wc.PromiseRejectionEvent),Wc=Mc("Promise",(function(){var e=Lc(Oc),t=e!==String(Oc);if(!t&&66===Fc)return!0;if(!Fc||Fc<51||!/native code/.test(e)){var i=new Oc((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((i.constructor={})[Bc]=r,!(Hc=i.then((function(){}))instanceof r))return!0}return!t&&(Vc||Uc)&&!jc})),Gc={CONSTRUCTOR:Wc,REJECTION_EVENT:jc,SUBCLASSING:Hc},Jc={},Kc=et,zc=TypeError,qc=function(e){var t,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw zc("Bad Promise constructor");t=e,i=r})),this.resolve=Kc(t),this.reject=Kc(i)};Jc.f=function(e){return new qc(e)};var Yc,Qc,Xc,$c=Vn,Zc=Ts,el=C,tl=Fe,il=tn,rl=vo,nl=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(FF){}},ml=bc,_l=sc,fl=ar,gl=kc,Tl=Jc,El="Promise",Sl=Gc.CONSTRUCTOR,yl=Gc.REJECTION_EVENT,vl=Gc.SUBCLASSING,Il=fl.getterFor(El),Al=fl.set,Rl=gl&&gl.prototype,Cl=gl,bl=Rl,kl=el.TypeError,Dl=el.document,Nl=el.process,wl=Tl.f,Ol=wl,Pl=!!(Dl&&Dl.createEvent&&el.dispatchEvent),Ml="unhandledrejection",Ll=function(e){var t;return!(!cl(e)||!al(t=e.then))&&t},xl=function(e,t){var i,r,n,o=t.value,s=1==t.state,a=s?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{a?(s||(2===t.rejection&&Hl(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),n=!0)),i===e.promise?l(kl("Promise-chain cycle")):(r=Ll(i))?tl(r,i,c,l):c(i)):l(o)}catch(FF){d&&!n&&d.exit(),l(FF)}},Vl=function(e,t){e.notified||(e.notified=!0,hl((function(){for(var i,r=e.reactions;i=r.get();)xl(i,e);e.notified=!1,t&&!e.rejection&&Fl(e)})))},Ul=function(e,t,i){var r,n;Pl?((r=Dl.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),el.dispatchEvent(r)):r={promise:t,reason:i},!yl&&(n=el["on"+e])?n(r):e===Ml&&pl("Unhandled promise rejection",i)},Fl=function(e){tl(ul,el,(function(){var t,i=e.facade,r=e.value;if(Bl(e)&&(t=ml((function(){Zc?Nl.emit("unhandledRejection",r,i):Ul(Ml,i,r)})),e.rejection=Zc||Bl(e)?2:1,t.error))throw t.value}))},Bl=function(e){return 1!==e.rejection&&!e.parent},Hl=function(e){tl(ul,el,(function(){var t=e.facade;Zc?Nl.emit("rejectionHandled",t):Ul("rejectionhandled",t,e.value)}))},jl=function(e,t,i){return function(r){e(t,r,i)}},Wl=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Vl(e,!0))},Gl=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw kl("Promise can't be resolved itself");var r=Ll(t);r?hl((function(){var i={done:!1};try{tl(r,t,jl(Gl,i,e),jl(Wl,i,e))}catch(FF){Wl(i,FF,e)}})):(e.value=t,e.state=1,Vl(e,!1))}catch(FF){Wl({done:!1},FF,e)}}};if(Sl&&(bl=(Cl=function(e){ll(this,bl),sl(e),tl(Yc,this);var t=Il(this);try{e(jl(Gl,t),jl(Wl,t))}catch(FF){Wl(t,FF)}}).prototype,(Yc=function(e){Al(this,{type:El,done:!1,notified:!1,parent:!1,reactions:new _l,rejection:!1,state:0,value:void 0})}).prototype=il(bl,"then",(function(e,t){var i=Il(this),r=wl(dl(this,Cl));return i.parent=!0,r.ok=!al(e)||e,r.fail=al(t)&&t,r.domain=Zc?Nl.domain:void 0,0==i.state?i.reactions.add(r):hl((function(){xl(r,i)})),r.promise})),Qc=function(){var e=new Yc,t=Il(e);this.promise=e,this.resolve=jl(Gl,t),this.reject=jl(Wl,t)},Tl.f=wl=function(e){return e===Cl||undefined===e?new Qc(e):Ol(e)},al(gl)&&Rl!==Object.prototype)){Xc=Rl.then,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(FF){}rl&&rl(Rl,bl)}$c({global:!0,constructor:!0,wrap:!0,forced:Sl},{Promise:Cl}),nl(Cl,El,!1),ol(El);var Jl=Bi,Kl=_e("iterator"),zl=Array.prototype,ql=function(e){return void 0!==e&&(Jl.Array===e||zl[Kl]===e)},Yl=Vs,Ql=rt,Xl=T,$l=Bi,Zl=_e("iterator"),ed=function(e){if(!Xl(e))return Ql(e,Zl)||Ql(e,"@@iterator")||$l[Yl(e)]},td=Fe,id=et,rd=Ce,nd=Qe,od=ed,sd=TypeError,ad=function(e,t){var i=arguments.length<2?od(e):t;if(id(i))return rd(td(i,e));throw sd(nd(e)+" is not iterable")},cd=Fe,ld=Ce,dd=rt,ud=function(e,t,i){var r,n;ld(e);try{if(!(r=dd(e,"return"))){if("throw"===t)throw i;return i}r=cd(r,e)}catch(FF){n=!0,r=FF}if("throw"===t)throw i;if(n)throw r;return ld(r),i},hd=va,pd=Fe,md=Ce,_d=Qe,fd=ql,gd=Wt,Td=We,Ed=ad,Sd=ed,yd=ud,vd=TypeError,Id=function(e,t){this.stopped=e,this.result=t},Ad=Id.prototype,Rd=function(e,t,i){var r,n,o,s,a,c,l,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),_=hd(t,d),f=function(e){return r&&yd(r,"normal",e),new Id(!0,e)},g=function(e){return u?(md(e),m?_(e[0],e[1],f):_(e[0],e[1])):m?_(e,f):_(e)};if(h)r=e.iterator;else if(p)r=e;else{if(!(n=Sd(e)))throw vd(_d(e)+" is not iterable");if(fd(n)){for(o=0,s=gd(e);s>o;o++)if((a=g(e[o]))&&Td(Ad,a))return a;return new Id(!1)}r=Ed(e,n)}for(c=h?e.next:r.next;!(l=pd(c,r)).done;){try{a=g(l.value)}catch(FF){yd(r,"throw",FF)}if("object"==typeof a&&a&&Td(Ad,a))return a}return new Id(!1)},Cd=_e("iterator"),bd=!1;try{var kd=0,Dd={next:function(){return{done:!!kd++}},return:function(){bd=!0}};Dd[Cd]=function(){return this},Array.from(Dd,(function(){throw 2}))}catch(FF){}var Nd=function(e,t){if(!t&&!bd)return!1;var i=!1;try{var r={};r[Cd]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(FF){}return i},wd=kc,Od=Gc.CONSTRUCTOR||!Nd((function(e){wd.all(e).then(void 0,(function(){}))})),Pd=Fe,Md=et,Ld=Jc,xd=bc,Vd=Rd;Vn({target:"Promise",stat:!0,forced:Od},{all:function(e){var t=this,i=Ld.f(t),r=i.resolve,n=i.reject,o=xd((function(){var i=Md(t.resolve),o=[],s=0,a=1;Vd(e,(function(e){var c=s++,l=!1;a++,Pd(i,t,e).then((function(e){l||(l=!0,o[c]=e,--a||r(o))}),n)})),--a||r(o)}));return o.error&&n(o.value),i.promise}});var Ud=Vn,Fd=Gc.CONSTRUCTOR,Bd=kc,Hd=je,jd=Ee,Wd=tn,Gd=Bd&&Bd.prototype;if(Ud({target:"Promise",proto:!0,forced:Fd,real:!0},{catch:function(e){return this.then(void 0,e)}}),jd(Bd)){var Jd=Hd("Promise").prototype.catch;Gd.catch!==Jd&&Wd(Gd,"catch",Jd,{unsafe:!0})}var Kd=Fe,zd=et,qd=Jc,Yd=bc,Qd=Rd;Vn({target:"Promise",stat:!0,forced:Od},{race:function(e){var t=this,i=qd.f(t),r=i.reject,n=Yd((function(){var n=zd(t.resolve);Qd(e,(function(e){Kd(n,t,e).then(i.resolve,r)}))}));return n.error&&r(n.value),i.promise}});var Xd=Fe,$d=Jc;Vn({target:"Promise",stat:!0,forced:Gc.CONSTRUCTOR},{reject:function(e){var t=$d.f(this);return Xd(t.reject,void 0,e),t.promise}});var Zd=Ce,eu=ve,tu=Jc,iu=function(e,t){if(Zd(e),eu(t)&&t.constructor===e)return t;var i=tu.f(e);return(0,i.resolve)(t),i.promise},ru=Vn,nu=Gc.CONSTRUCTOR,ou=iu;je("Promise"),ru({target:"Promise",stat:!0,forced:nu},{resolve:function(e){return ou(this,e)}});var su=Ee,au=ve,cu=vo,lu=function(e,t,i){var r,n;return cu&&su(r=t.constructor)&&r!==i&&au(n=r.prototype)&&n!==i.prototype&&cu(e,n),e},du=ve,uu=h,hu=_e("match"),pu=Vs,mu=String,_u=function(e){if("Symbol"===pu(e))throw TypeError("Cannot convert a Symbol value to a string");return mu(e)},fu=Ce,gu=function(){var e=fu(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},Tu=Fe,Eu=W,Su=We,yu=gu,vu=RegExp.prototype,Iu=i,Au=C.RegExp,Ru=Iu((function(){var e=Au("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),Cu=Ru||Iu((function(){return!Au("a","y").sticky})),bu=Ru||Iu((function(){var e=Au("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),ku={BROKEN_CARET:bu,MISSED_STICKY:Cu,UNSUPPORTED_Y:Ru},Du=Ne.f,Nu=i,wu=C.RegExp,Ou=Nu((function(){var e=wu(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),Pu=i,Mu=C.RegExp,Lu=Pu((function(){var e=Mu("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),xu=ke,Vu=C,Uu=c,Fu=Dn,Bu=lu,Hu=zi,ju=rn.f,Wu=We,Gu=function(e){var t;return du(e)&&(void 0!==(t=e[hu])?!!t:"RegExp"==uu(e))},Ju=_u,Ku=function(e){var t=e.flags;return void 0!==t||"flags"in vu||Eu(e,"flags")||!Su(vu,e)?t:Tu(yu,e)},zu=ku,qu=function(e,t,i){i in e||Du(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Yu=tn,Qu=i,Xu=W,$u=ar.enforce,Zu=Cs,eh=Ou,th=Lu,ih=_e("match"),rh=Vu.RegExp,nh=rh.prototype,oh=Vu.SyntaxError,sh=Uu(nh.exec),ah=Uu("".charAt),ch=Uu("".replace),lh=Uu("".indexOf),dh=Uu("".slice),uh=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,hh=/a/g,ph=/a/g,mh=new rh(hh)!==hh,_h=zu.MISSED_STICKY,fh=zu.UNSUPPORTED_Y,gh=xu&&(!mh||_h||eh||th||Qu((function(){return ph[ih]=!1,rh(hh)!=hh||rh(ph)==ph||"/a/i"!=rh(hh,"i")})));if(Fu("RegExp",gh)){for(var Th=function(e,t){var i,r,n,o,s,a,c=Wu(nh,this),l=Gu(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Th)return e;if((l||Wu(nh,e))&&(e=e.source,d&&(t=Ku(h))),e=void 0===e?"":Ju(e),t=void 0===t?"":Ju(t),h=e,eh&&"dotAll"in hh&&(r=!!t&&lh(t,"s")>-1)&&(t=ch(t,/s/g,"")),i=t,_h&&"sticky"in hh&&(n=!!t&&lh(t,"y")>-1)&&fh&&(t=ch(t,/y/g,"")),th&&(o=function(e){for(var t,i=e.length,r=0,n="",o=[],s={},a=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=ah(e,r)))t+=ah(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:sh(uh,dh(e,r+1))&&(r+=2,c=!0),n+=t,l++;continue;case">"===t&&c:if(""===d||Xu(s,d))throw new oh("Invalid capture group name");s[d]=!0,o[o.length]=[d,l],c=!1,d="";continue}c?d+=t:n+=t}return[n,o]}(e),e=o[0],u=o[1]),s=Bu(rh(e,t),c?this:nh,Th),(r||n||u.length)&&(a=$u(s),r&&(a.dotAll=!0,a.raw=Th(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=ah(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+ah(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Hu(s,"source",""===h?"(?:)":h)}catch(FF){}return s},Eh=ju(rh),Sh=0;Eh.length>Sh;)qu(Th,rh,Eh[Sh++]);nh.constructor=Th,Th.prototype=nh,Yu(Vu,"RegExp",Th,{constructor:!0})}Zu("RegExp");var yh=Fe,vh=c,Ih=_u,Ah=gu,Rh=ku,Ch=Ni,bh=ar.get,kh=Ou,Dh=Lu,Nh=b("native-string-replace",String.prototype.replace),wh=RegExp.prototype.exec,Oh=wh,Ph=vh("".charAt),Mh=vh("".indexOf),Lh=vh("".replace),xh=vh("".slice),Vh=function(){var e=/a/,t=/b*/g;return yh(wh,e,"a"),yh(wh,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Uh=Rh.BROKEN_CARET,Fh=void 0!==/()??/.exec("")[1];(Vh||Fh||Uh||kh||Dh)&&(Oh=function(e){var t,i,r,n,o,s,a,c=this,l=bh(c),d=Ih(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=yh(Oh,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Uh&&c.sticky,m=yh(Ah,c),_=c.source,f=0,g=d;if(p&&(m=Lh(m,"y",""),-1===Mh(m,"g")&&(m+="g"),g=xh(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Ph(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),Fh&&(i=new RegExp("^"+_+"$(?!\\s)",m)),Vh&&(r=c.lastIndex),n=yh(wh,p?i:c,g),p?n?(n.input=xh(n.input,f),n[0]=xh(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:Vh&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),Fh&&n&&n.length>1&&yh(Nh,n[0],i,(function(){for(o=1;o<arguments.length-2;o++)void 0===arguments[o]&&(n[o]=void 0)})),n&&h)for(n.groups=s=Ch(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=n[a[1]];return n});var Bh=Oh;Vn({target:"RegExp",proto:!0,forced:/./.exec!==Bh},{exec:Bh});var Hh=h,jh=Array.isArray||function(e){return"Array"==Hh(e)},Wh=jh,Gh=ta,Jh=ve,Kh=_e("species"),zh=Array,qh=function(e){var t;return Wh(e)&&(t=e.constructor,(Gh(t)&&(t===zh||Wh(t.prototype))||Jh(t)&&null===(t=t[Kh]))&&(t=void 0)),void 0===t?zh:t},Yh=va,Qh=g,Xh=B,$h=Wt,Zh=function(e,t){return new(qh(e))(0===t?0:t)},ep=c([].push),tp=function(e){var t=1==e,i=2==e,r=3==e,n=4==e,o=6==e,s=7==e,a=5==e||o;return function(c,l,d,u){for(var h,p,m=Xh(c),_=Qh(m),f=Yh(l,d),g=$h(_),T=0,E=u||Zh,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:ep(S,h)}else switch(e){case 4:return!1;case 7:ep(S,h)}return o?-1:r||n?n:S}},ip={forEach:tp(0),map:tp(1),filter:tp(2),some:tp(3),every:tp(4),find:tp(5),findIndex:tp(6),filterReject:tp(7)},rp=i,np=function(e,t){var i=[][e];return!!i&&rp((function(){i.call(null,t||function(){return 1},1)}))},op=ip.forEach,sp=np("forEach")?[].forEach:function(e){return op(this,e,arguments.length>1?arguments[1]:void 0)},ap=C,cp=rs,lp=ss,dp=sp,up=zi,hp=function(e){if(e&&e.forEach!==dp)try{up(e,"forEach",dp)}catch(FF){e.forEach=dp}};for(var pp in cp)cp[pp]&&hp(ap[pp]&&ap[pp].prototype);hp(lp);var mp=et,_p=B,fp=g,gp=Wt,Tp=TypeError,Ep=function(e){return function(t,i,r,n){mp(i);var o=_p(t),s=fp(o),a=gp(o),c=e?a-1:0,l=e?-1:1;if(r<2)for(;;){if(c in s){n=s[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw Tp("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=l)c in s&&(n=i(n,s[c],c,o));return n}},Sp={left:Ep(!1),right:Ep(!0)}.left;Vn({target:"Array",proto:!0,forced:!Ts&&ie>79&&ie<83||!np("reduce")},{reduce:function(e){var t=arguments.length;return Sp(this,e,t,t>1?arguments[1]:void 0)}});var yp=Ta,vp=tn,Ip=Bh,Ap=i,Rp=_e,Cp=zi,bp=Rp("species"),kp=RegExp.prototype,Dp=c,Np=Mt,wp=_u,Op=y,Pp=Dp("".charAt),Mp=Dp("".charCodeAt),Lp=Dp("".slice),xp=function(e){return function(t,i){var r,n,o=wp(Op(t)),s=Np(i),a=o.length;return s<0||s>=a?e?"":void 0:(r=Mp(o,s))<55296||r>56319||s+1===a||(n=Mp(o,s+1))<56320||n>57343?e?Pp(o,s):r:e?Lp(o,s,s+2):n-56320+(r-55296<<10)+65536}},Vp={codeAt:xp(!1),charAt:xp(!0)},Up=Vp.charAt,Fp=c,Bp=B,Hp=Math.floor,jp=Fp("".charAt),Wp=Fp("".replace),Gp=Fp("".slice),Jp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Kp=/\$([$&'`]|\d{1,2})/g,zp=Fe,qp=Ce,Yp=Ee,Qp=h,Xp=Bh,$p=TypeError,Zp=_a,em=Fe,tm=c,im=function(e,t,i,r){var n=Rp(e),o=!Ap((function(){var t={};return t[n]=function(){return 7},7!=""[e](t)})),s=o&&!Ap((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[bp]=function(){return i},i.flags="",i[n]=/./[n]),i.exec=function(){return t=!0,null},i[n](""),!t}));if(!o||!s||i){var a=yp(/./[n]),c=t(n,""[e],(function(e,t,i,r,n){var s=yp(e),c=t.exec;return c===Ip||c===kp.exec?o&&!n?{done:!0,value:a(t,i,r)}:{done:!0,value:s(i,t,r)}:{done:!1}}));vp(String.prototype,e,c[0]),vp(kp,n,c[1])}r&&Cp(kp[n],"sham",!0)},rm=i,nm=Ce,om=Ee,sm=T,am=Mt,cm=Ht,lm=_u,dm=y,um=function(e,t,i){return t+(i?Up(e,t).length:1)},hm=rt,pm=function(e,t,i,r,n,o){var s=i+e.length,a=r.length,c=Kp;return void 0!==n&&(n=Bp(n),c=Jp),Wp(o,c,(function(o,c){var l;switch(jp(c,0)){case"$":return"$";case"&":return e;case"`":return Gp(t,0,i);case"'":return Gp(t,s);case"<":l=n[Gp(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Hp(d/10);return 0===u?o:u<=a?void 0===r[u-1]?jp(c,1):r[u-1]+jp(c,1):o}l=r[d-1]}return void 0===l?"":l}))},mm=function(e,t){var i=e.exec;if(Yp(i)){var r=zp(i,e,t);return null!==r&&qp(r),r}if("RegExp"===Qp(e))return zp(Xp,e,t);throw $p("RegExp#exec called on incompatible receiver")},_m=_e("replace"),fm=Math.max,gm=Math.min,Tm=tm([].concat),Em=tm([].push),Sm=tm("".indexOf),ym=tm("".slice),vm=function(e){return void 0===e?e:String(e)},Im="$0"==="a".replace(/./,"$0"),Am=!!/./[_m]&&""===/./[_m]("a","$0"),Rm=!rm((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));im("replace",(function(e,t,i){var r=Am?"$":"$0";return[function(e,i){var r=dm(this),n=sm(e)?void 0:hm(e,_m);return n?em(n,e,r,i):em(t,lm(r),e,i)},function(e,n){var o=nm(this),s=lm(e);if("string"==typeof n&&-1===Sm(n,r)&&-1===Sm(n,"$<")){var a=i(t,o,s,n);if(a.done)return a.value}var c=om(n);c||(n=lm(n));var l=o.global;if(l){var d=o.unicode;o.lastIndex=0}for(var u=[];;){var h=mm(o,s);if(null===h)break;if(Em(u,h),!l)break;""===lm(h[0])&&(o.lastIndex=um(s,cm(o.lastIndex),d))}for(var p="",m=0,_=0;_<u.length;_++){for(var f=lm((h=u[_])[0]),g=fm(gm(am(h.index),s.length),0),T=[],E=1;E<h.length;E++)Em(T,vm(h[E]));var S=h.groups;if(c){var y=Tm([f],T,g,s);void 0!==S&&Em(y,S);var v=lm(Zp(n,void 0,y))}else v=pm(f,s,g,T,S,n);g>=m&&(p+=ym(s,m,g)+v,m=g+f.length)}return p+ym(s,m)}]}),!Rm||!Im||Am);var Cm=qt.includes,bm=Fi;Vn({target:"Array",proto:!0,forced:i((function(){return!Array(1).includes()}))},{includes:function(e){return Cm(this,e,arguments.length>1?arguments[1]:void 0)}}),bm("includes");var km=Mt,Dm=_u,Nm=y,wm=RangeError,Om=c,Pm=Ht,Mm=_u,Lm=function(e){var t=Dm(Nm(this)),i="",r=km(e);if(r<0||Infinity==r)throw wm("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},xm=y,Vm=Om(Lm),Um=Om("".slice),Fm=Math.ceil,Bm=function(e){return function(t,i,r){var n,o,s=Mm(xm(t)),a=Pm(i),c=s.length,l=void 0===r?" ":Mm(r);return a<=c||""==l?s:((o=Vm(l,Fm((n=a-c)/l.length))).length>n&&(o=Um(o,0,n)),e?s+o:o+s)}},Hm={start:Bm(!1),end:Bm(!0)},jm=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Y),Wm=Hm.start;Vn({target:"String",proto:!0,forced:jm},{padStart:function(e){return Wm(this,e,arguments.length>1?arguments[1]:void 0)}});var Gm=i,Jm=ke,Km=_e("iterator"),zm=!Gm((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i="";return e.pathname="c%20d",t.forEach((function(e,r){t.delete("b"),i+=r+e})),!t.size&&!Jm||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[Km]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==i||"x"!==new URL("http://x",void 0).host})),qm=tn,Ym=function(e,t,i){for(var r in t)qm(e,r,t[r],i);return e},Qm=Tt,Xm=Ne,$m=Gi,Zm=function(e,t,i){var r=Qm(t);r in e?Xm.f(e,r,$m(0,i)):e[r]=i},e_=Ut,t_=Wt,i_=Zm,r_=Array,n_=Math.max,o_=function(e,t,i){for(var r=t_(e),n=e_(t,r),o=e_(void 0===i?r:i,r),s=r_(n_(o-n,0)),a=0;n<o;n++,a++)i_(s,a,e[n]);return s.length=a,s},s_=o_,a_=Math.floor,c_=function(e,t){var i=e.length,r=a_(i/2);return i<8?l_(e,t):d_(e,c_(s_(e,0,r),t),c_(s_(e,r),t),t)},l_=function(e,t){for(var i,r,n=e.length,o=1;o<n;){for(r=o,i=e[o];r&&t(e[r-1],i)>0;)e[r]=e[--r];r!==o++&&(e[r]=i)}return e},d_=function(e,t,i,r){for(var n=t.length,o=i.length,s=0,a=0;s<n||a<o;)e[s+a]=s<n&&a<o?r(t[s],i[a])<=0?t[s++]:i[a++]:s<n?t[s++]:i[a++];return e},u_=c_,h_=Vn,p_=C,m_=Fe,__=c,f_=ke,g_=zm,T_=tn,E_=ys,S_=Ym,y_=oo,v_=po,I_=ar,A_=Ds,R_=Ee,C_=W,b_=va,k_=Vs,D_=Ce,N_=ve,w_=_u,O_=Ni,P_=Gi,M_=ad,L_=ed,x_=Ra,V_=u_,U_=_e("iterator"),F_="URLSearchParams",B_=F_+"Iterator",H_=I_.set,j_=I_.getterFor(F_),W_=I_.getterFor(B_),G_=Object.getOwnPropertyDescriptor,J_=function(e){if(!f_)return p_[e];var t=G_(p_,e);return t&&t.value},K_=J_("fetch"),z_=J_("Request"),q_=J_("Headers"),Y_=z_&&z_.prototype,Q_=q_&&q_.prototype,X_=p_.RegExp,$_=p_.TypeError,Z_=p_.decodeURIComponent,ef=p_.encodeURIComponent,tf=__("".charAt),rf=__([].join),nf=__([].push),of=__("".replace),sf=__([].shift),af=__([].splice),cf=__("".split),lf=__("".slice),df=/\+/g,uf=Array(4),hf=function(e){return uf[e-1]||(uf[e-1]=X_("((?:%[\\da-f]{2}){"+e+"})","gi"))},pf=function(e){try{return Z_(e)}catch(FF){return e}},mf=function(e){var t=of(e,df," "),i=4;try{return Z_(t)}catch(FF){for(;i;)t=of(t,hf(i--),pf);return t}},_f=/[!'()~]|%20/g,ff={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},gf=function(e){return ff[e]},Tf=function(e){return of(ef(e),_f,gf)},Ef=v_((function(e,t){H_(this,{type:B_,iterator:M_(j_(e).entries),kind:t})}),"Iterator",(function(){var e=W_(this),t=e.kind,i=e.iterator.next(),r=i.value;return i.done||(i.value="keys"===t?r.key:"values"===t?r.value:[r.key,r.value]),i}),!0),Sf=function(e){this.entries=[],this.url=null,void 0!==e&&(N_(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===tf(e,0)?lf(e,1):e:w_(e)))};Sf.prototype={type:F_,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,s,a,c=L_(e);if(c)for(i=(t=M_(e,c)).next;!(r=m_(i,t)).done;){if(o=(n=M_(D_(r.value))).next,(s=m_(o,n)).done||(a=m_(o,n)).done||!m_(o,n).done)throw $_("Expected sequence with length 2");nf(this.entries,{key:w_(s.value),value:w_(a.value)})}else for(var l in e)C_(e,l)&&nf(this.entries,{key:l,value:w_(e[l])})},parseQuery:function(e){if(e)for(var t,i,r=cf(e,"&"),n=0;n<r.length;)(t=r[n++]).length&&(i=cf(t,"="),nf(this.entries,{key:mf(sf(i)),value:mf(rf(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],nf(i,Tf(e.key)+"="+Tf(e.value));return rf(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var yf=function(){A_(this,vf);var e=H_(this,new Sf(arguments.length>0?arguments[0]:void 0));f_||(this.length=e.entries.length)},vf=yf.prototype;if(S_(vf,{append:function(e,t){x_(arguments.length,2);var i=j_(this);nf(i.entries,{key:w_(e),value:w_(t)}),f_||this.length++,i.updateURL()},delete:function(e){x_(arguments.length,1);for(var t=j_(this),i=t.entries,r=w_(e),n=0;n<i.length;)i[n].key===r?af(i,n,1):n++;f_||(this.length=i.length),t.updateURL()},get:function(e){x_(arguments.length,1);for(var t=j_(this).entries,i=w_(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){x_(arguments.length,1);for(var t=j_(this).entries,i=w_(e),r=[],n=0;n<t.length;n++)t[n].key===i&&nf(r,t[n].value);return r},has:function(e){x_(arguments.length,1);for(var t=j_(this).entries,i=w_(e),r=0;r<t.length;)if(t[r++].key===i)return!0;return!1},set:function(e,t){x_(arguments.length,1);for(var i,r=j_(this),n=r.entries,o=!1,s=w_(e),a=w_(t),c=0;c<n.length;c++)(i=n[c]).key===s&&(o?af(n,c--,1):(o=!0,i.value=a));o||nf(n,{key:s,value:a}),f_||(this.length=n.length),r.updateURL()},sort:function(){var e=j_(this);V_(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=j_(this).entries,r=b_(e,arguments.length>1?arguments[1]:void 0),n=0;n<i.length;)r((t=i[n++]).value,t.key,this)},keys:function(){return new Ef(this,"keys")},values:function(){return new Ef(this,"values")},entries:function(){return new Ef(this,"entries")}},{enumerable:!0}),T_(vf,U_,vf.entries,{name:"entries"}),T_(vf,"toString",(function(){return j_(this).serialize()}),{enumerable:!0}),f_&&E_(vf,"size",{get:function(){return j_(this).entries.length},configurable:!0,enumerable:!0}),y_(yf,F_),h_({global:!0,constructor:!0,forced:!g_},{URLSearchParams:yf}),!g_&&R_(q_)){var If=__(Q_.has),Af=__(Q_.set),Rf=function(e){if(N_(e)){var t,i=e.body;if(k_(i)===F_)return t=e.headers?new q_(e.headers):new q_,If(t,"content-type")||Af(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),O_(e,{body:P_(0,w_(i)),headers:P_(0,t)})}return e};if(R_(K_)&&h_({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return K_(e,arguments.length>1?Rf(arguments[1]):{})}}),R_(z_)){var Cf=function(e){return A_(this,Y_),new z_(e,arguments.length>1?Rf(arguments[1]):{})};Y_.constructor=Cf,Cf.prototype=Y_,h_({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:Cf})}}var bf={URLSearchParams:yf,getState:j_},kf=Vn,Df=kc,Nf=i,wf=je,Of=Ee,Pf=da,Mf=iu,Lf=tn,xf=Df&&Df.prototype;if(kf({target:"Promise",proto:!0,real:!0,forced:!!Df&&Nf((function(){xf.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Pf(this,wf("Promise")),i=Of(e);return this.then(i?function(i){return Mf(t,e()).then((function(){return i}))}:e,i?function(i){return Mf(t,e()).then((function(){throw i}))}:e)}}),Of(Df)){var Vf=wf("Promise").prototype.finally;xf.finally!==Vf&&Lf(xf,"finally",Vf,{unsafe:!0})}var Uf="\t\n\v\f\r                 \u2028\u2029\ufeff",Ff=y,Bf=_u,Hf=Uf,jf=c("".replace),Wf=RegExp("^["+Hf+"]+"),Gf=RegExp("(^|[^"+Hf+"])["+Hf+"]+$"),Jf=function(e){return function(t){var i=Bf(Ff(t));return 1&e&&(i=jf(i,Wf,"")),2&e&&(i=jf(i,Gf,"$1")),i}},Kf={start:Jf(1),end:Jf(2),trim:Jf(3)},zf=Dr.PROPER,qf=i,Yf=Uf,Qf=Kf.trim;Vn({target:"String",proto:!0,forced:function(e){return qf((function(){return!!Yf[e]()||"​…᠎"!=="​…᠎"[e]()||zf&&Yf[e].name!==e}))}("trim")},{trim:function(){return Qf(this)}});var Xf="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,$f=Mt,Zf=Ht,eg=RangeError,tg=function(e){if(void 0===e)return 0;var t=$f(e),i=Zf(t);if(t!==i)throw eg("Wrong length or index");return i},ig=Array,rg=Math.abs,ng=Math.pow,og=Math.floor,sg=Math.log,ag=Math.LN2,cg={pack:function(e,t,i){var r,n,o,s=ig(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?ng(2,-24)-ng(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=rg(e))!=e||Infinity===e?(n=e!=e?1:0,r=c):(r=og(sg(e)/ag),e*(o=ng(2,-r))<1&&(r--,o*=2),(e+=r+l>=1?d/o:d*ng(2,1-l))*o>=2&&(r++,o/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*o-1)*ng(2,t),r+=l):(n=e*ng(2,l-1)*ng(2,t),r=0));t>=8;)s[h++]=255&n,n/=256,t-=8;for(r=r<<t|n,a+=t;a>0;)s[h++]=255&r,r/=256,a-=8;return s[--h]|=128*u,s},unpack:function(e,t){var i,r=e.length,n=8*r-t-1,o=(1<<n)-1,s=o>>1,a=n-7,c=r-1,l=e[c--],d=127&l;for(l>>=7;a>0;)d=256*d+e[c--],a-=8;for(i=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)i=256*i+e[c--],a-=8;if(0===d)d=1-s;else{if(d===o)return i?NaN:l?-Infinity:Infinity;i+=ng(2,t),d-=s}return(l?-1:1)*i*ng(2,d-t)}},lg=B,dg=Ut,ug=Wt,hg=function(e){for(var t=lg(this),i=ug(t),r=arguments.length,n=dg(r>1?arguments[1]:void 0,i),o=r>2?arguments[2]:void 0,s=void 0===o?i:dg(o,i);s>n;)t[n++]=e;return t},pg=C,mg=c,_g=ke,fg=Xf,gg=Dr,Tg=zi,Eg=ys,Sg=Ym,yg=i,vg=Ds,Ig=Mt,Ag=Ht,Rg=tg,Cg=cg,bg=Kn,kg=vo,Dg=rn.f,Ng=hg,wg=o_,Og=oo,Pg=ar,Mg=gg.PROPER,Lg=gg.CONFIGURABLE,xg="ArrayBuffer",Vg="DataView",Ug="prototype",Fg="Wrong index",Bg=Pg.getterFor(xg),Hg=Pg.getterFor(Vg),jg=Pg.set,Wg=pg[xg],Gg=Wg,Jg=Gg&&Gg[Ug],Kg=pg[Vg],zg=Kg&&Kg[Ug],qg=Object.prototype,Yg=pg.Array,Qg=pg.RangeError,Xg=mg(Ng),$g=mg([].reverse),Zg=Cg.pack,eT=Cg.unpack,tT=function(e){return[255&e]},iT=function(e){return[255&e,e>>8&255]},rT=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},nT=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},oT=function(e){return Zg(e,23,4)},sT=function(e){return Zg(e,52,8)},aT=function(e,t,i){Eg(e[Ug],t,{configurable:!0,get:function(){return i(this)[t]}})},cT=function(e,t,i,r){var n=Rg(i),o=Hg(e);if(n+t>o.byteLength)throw Qg(Fg);var s=o.bytes,a=n+o.byteOffset,c=wg(s,a,a+t);return r?c:$g(c)},lT=function(e,t,i,r,n,o){var s=Rg(i),a=Hg(e);if(s+t>a.byteLength)throw Qg(Fg);for(var c=a.bytes,l=s+a.byteOffset,d=r(+n),u=0;u<t;u++)c[l+u]=d[o?u:t-u-1]};if(fg){var dT=Mg&&Wg.name!==xg;if(yg((function(){Wg(1)}))&&yg((function(){new Wg(-1)}))&&!yg((function(){return new Wg,new Wg(1.5),new Wg(NaN),1!=Wg.length||dT&&!Lg})))dT&&Lg&&Tg(Wg,"name",xg);else{(Gg=function(e){return vg(this,Jg),new Wg(Rg(e))})[Ug]=Jg;for(var uT,hT=Dg(Wg),pT=0;hT.length>pT;)(uT=hT[pT++])in Gg||Tg(Gg,uT,Wg[uT]);Jg.constructor=Gg}kg&&bg(zg)!==qg&&kg(zg,qg);var mT=new Kg(new Gg(2)),_T=mg(zg.setInt8);mT.setInt8(0,2147483648),mT.setInt8(1,2147483649),!mT.getInt8(0)&&mT.getInt8(1)||Sg(zg,{setInt8:function(e,t){_T(this,e,t<<24>>24)},setUint8:function(e,t){_T(this,e,t<<24>>24)}},{unsafe:!0})}else Jg=(Gg=function(e){vg(this,Jg);var t=Rg(e);jg(this,{type:xg,bytes:Xg(Yg(t),0),byteLength:t}),_g||(this.byteLength=t,this.detached=!1)})[Ug],zg=(Kg=function(e,t,i){vg(this,zg),vg(e,Jg);var r=Bg(e),n=r.byteLength,o=Ig(t);if(o<0||o>n)throw Qg("Wrong offset");if(o+(i=void 0===i?n-o:Ag(i))>n)throw Qg("Wrong length");jg(this,{type:Vg,buffer:e,byteLength:i,byteOffset:o,bytes:r.bytes}),_g||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[Ug],_g&&(aT(Gg,"byteLength",Bg),aT(Kg,"buffer",Hg),aT(Kg,"byteLength",Hg),aT(Kg,"byteOffset",Hg)),Sg(zg,{getInt8:function(e){return cT(this,1,e)[0]<<24>>24},getUint8:function(e){return cT(this,1,e)[0]},getInt16:function(e){var t=cT(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=cT(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return nT(cT(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return nT(cT(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return eT(cT(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return eT(cT(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){lT(this,1,e,tT,t)},setUint8:function(e,t){lT(this,1,e,tT,t)},setInt16:function(e,t){lT(this,2,e,iT,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){lT(this,2,e,iT,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){lT(this,4,e,rT,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){lT(this,4,e,rT,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){lT(this,4,e,oT,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){lT(this,8,e,sT,t,arguments.length>2?arguments[2]:void 0)}});Og(Gg,xg),Og(Kg,Vg);var fT={ArrayBuffer:Gg,DataView:Kg},gT=Vn,TT=Ta,ET=i,ST=Ce,yT=Ut,vT=Ht,IT=da,AT=fT.ArrayBuffer,RT=fT.DataView,CT=RT.prototype,bT=TT(AT.prototype.slice),kT=TT(CT.getUint8),DT=TT(CT.setUint8);gT({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:ET((function(){return!new AT(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(bT&&void 0===t)return bT(ST(this),e);for(var i=ST(this).byteLength,r=yT(e,i),n=yT(void 0===t?i:t,i),o=new(IT(this,AT))(vT(n-r)),s=new RT(this),a=new RT(o),c=0;r<n;)DT(a,c++,kT(s,r++));return o}});var NT,wT,OT,PT={},MT={get exports(){return PT},set exports(e){PT=e}},LT=Xf,xT=ke,VT=C,UT=Ee,FT=ve,BT=W,HT=Vs,jT=Qe,WT=zi,GT=tn,JT=ys,KT=We,zT=Kn,qT=vo,YT=_e,QT=q,XT=ar.enforce,$T=ar.get,ZT=VT.Int8Array,eE=ZT&&ZT.prototype,tE=VT.Uint8ClampedArray,iE=tE&&tE.prototype,rE=ZT&&zT(ZT),nE=eE&&zT(eE),oE=Object.prototype,sE=VT.TypeError,aE=YT("toStringTag"),cE=QT("TYPED_ARRAY_TAG"),lE="TypedArrayConstructor",dE=LT&&!!qT&&"Opera"!==HT(VT.opera),uE=!1,hE={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},pE={BigInt64Array:8,BigUint64Array:8},mE=function(e){var t=zT(e);if(FT(t)){var i=$T(t);return i&&BT(i,lE)?i[lE]:mE(t)}},_E=function(e){if(!FT(e))return!1;var t=HT(e);return BT(hE,t)||BT(pE,t)};for(NT in hE)(OT=(wT=VT[NT])&&wT.prototype)?XT(OT)[lE]=wT:dE=!1;for(NT in pE)(OT=(wT=VT[NT])&&wT.prototype)&&(XT(OT)[lE]=wT);if((!dE||!UT(rE)||rE===Function.prototype)&&(rE=function(){throw sE("Incorrect invocation")},dE))for(NT in hE)VT[NT]&&qT(VT[NT],rE);if((!dE||!nE||nE===oE)&&(nE=rE.prototype,dE))for(NT in hE)VT[NT]&&qT(VT[NT].prototype,nE);if(dE&&zT(iE)!==nE&&qT(iE,nE),xT&&!BT(nE,aE))for(NT in uE=!0,JT(nE,aE,{configurable:!0,get:function(){return FT(this)?this[cE]:void 0}}),hE)VT[NT]&&WT(VT[NT],cE,NT);var fE={NATIVE_ARRAY_BUFFER_VIEWS:dE,TYPED_ARRAY_TAG:uE&&cE,aTypedArray:function(e){if(_E(e))return e;throw sE("Target is not a typed array")},aTypedArrayConstructor:function(e){if(UT(e)&&(!qT||KT(rE,e)))return e;throw sE(jT(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(xT){if(i)for(var n in hE){var o=VT[n];if(o&&BT(o.prototype,e))try{delete o.prototype[e]}catch(FF){try{o.prototype[e]=t}catch(s){}}}nE[e]&&!i||GT(nE,e,i?t:dE&&eE[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(xT){if(qT){if(i)for(r in hE)if((n=VT[r])&&BT(n,e))try{delete n[e]}catch(FF){}if(rE[e]&&!i)return;try{return GT(rE,e,i?t:dE&&rE[e]||t)}catch(FF){}}for(r in hE)!(n=VT[r])||n[e]&&!i||GT(n,e,t)}},getTypedArrayConstructor:mE,isView:function(e){if(!FT(e))return!1;var t=HT(e);return"DataView"===t||BT(hE,t)||BT(pE,t)},isTypedArray:_E,TypedArray:rE,TypedArrayPrototype:nE},gE=C,TE=i,EE=Nd,SE=fE.NATIVE_ARRAY_BUFFER_VIEWS,yE=gE.ArrayBuffer,vE=gE.Int8Array,IE=!SE||!TE((function(){vE(1)}))||!TE((function(){new vE(-1)}))||!EE((function(e){new vE,new vE(null),new vE(1.5),new vE(e)}),!0)||TE((function(){return 1!==new vE(new yE(2),1,void 0).length})),AE=ve,RE=Math.floor,CE=Number.isInteger||function(e){return!AE(e)&&isFinite(e)&&RE(e)===e},bE=Mt,kE=RangeError,DE=function(e){var t=bE(e);if(t<0)throw kE("The argument can't be less than 0");return t},NE=RangeError,wE=function(e,t){var i=DE(e);if(i%t)throw NE("Wrong offset");return i},OE=Vs,PE=_t,ME=TypeError,LE=function(e){var t=PE(e,"number");if("number"==typeof t)throw ME("Can't convert number to bigint");return BigInt(t)},xE=va,VE=Fe,UE=oa,FE=B,BE=Wt,HE=ad,jE=ed,WE=ql,GE=function(e){var t=OE(e);return"BigInt64Array"==t||"BigUint64Array"==t},JE=fE.aTypedArrayConstructor,KE=LE,zE=function(e){var t,i,r,n,o,s,a,c,l=UE(this),d=FE(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=jE(d);if(m&&!WE(m))for(c=(a=HE(d,m)).next,d=[];!(s=VE(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=xE(h,arguments[2])),i=BE(d),r=new(JE(l))(i),n=GE(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?KE(o):+o;return r},qE=Vn,YE=C,QE=Fe,XE=ke,$E=IE,ZE=fE,eS=fT,tS=Ds,iS=Gi,rS=zi,nS=CE,oS=Ht,sS=tg,aS=wE,cS=Tt,lS=W,dS=Vs,uS=ve,hS=qe,pS=Ni,mS=We,_S=vo,fS=rn.f,gS=zE,TS=ip.forEach,ES=Cs,SS=ys,yS=Ne,vS=cr,IS=lu,AS=ar.get,RS=ar.set,CS=ar.enforce,bS=yS.f,kS=vS.f,DS=Math.round,NS=YE.RangeError,wS=eS.ArrayBuffer,OS=wS.prototype,PS=eS.DataView,MS=ZE.NATIVE_ARRAY_BUFFER_VIEWS,LS=ZE.TYPED_ARRAY_TAG,xS=ZE.TypedArray,VS=ZE.TypedArrayPrototype,US=ZE.aTypedArrayConstructor,FS=ZE.isTypedArray,BS="BYTES_PER_ELEMENT",HS="Wrong length",jS=function(e,t){US(e);for(var i=0,r=t.length,n=new e(r);r>i;)n[i]=t[i++];return n},WS=function(e,t){SS(e,t,{configurable:!0,get:function(){return AS(this)[t]}})},GS=function(e){var t;return mS(OS,e)||"ArrayBuffer"==(t=dS(e))||"SharedArrayBuffer"==t},JS=function(e,t){return FS(e)&&!hS(t)&&t in e&&nS(+t)&&t>=0},KS=function(e,t){return t=cS(t),JS(e,t)?iS(2,e[t]):kS(e,t)},zS=function(e,t,i){return t=cS(t),!(JS(e,t)&&uS(i)&&lS(i,"value"))||lS(i,"get")||lS(i,"set")||i.configurable||lS(i,"writable")&&!i.writable||lS(i,"enumerable")&&!i.enumerable?bS(e,t,i):(e[t]=i.value,e)};XE?(MS||(vS.f=KS,yS.f=zS,WS(VS,"buffer"),WS(VS,"byteOffset"),WS(VS,"byteLength"),WS(VS,"length")),qE({target:"Object",stat:!0,forced:!MS},{getOwnPropertyDescriptor:KS,defineProperty:zS}),MT.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=YE[n],c=a,l=c&&c.prototype,d={},u=function(e,t){bS(e,t,{get:function(){return function(e,t){var i=AS(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=AS(e);i&&(n=(n=DS(n))<0?0:n>255?255:255&n),o.view[s](t*r+o.byteOffset,n,!0)}(this,t,e)},enumerable:!0})};MS?$E&&(c=t((function(e,t,i,n){return tS(e,l),IS(uS(t)?GS(t)?void 0!==n?new a(t,aS(i,r),n):void 0!==i?new a(t,aS(i,r)):new a(t):FS(t)?jS(c,t):QE(gS,c,t):new a(sS(t)),e,c)})),_S&&_S(c,xS),TS(fS(a),(function(e){e in c||rS(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,n){tS(e,l);var o,s,a,d=0,h=0;if(uS(t)){if(!GS(t))return FS(t)?jS(c,t):QE(gS,c,t);o=t,h=aS(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw NS(HS);if((s=p-h)<0)throw NS(HS)}else if((s=oS(n)*r)+h>p)throw NS(HS);a=s/r}else a=sS(t),o=new wS(s=a*r);for(RS(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new PS(o)});d<a;)u(e,d++)})),_S&&_S(c,xS),l=c.prototype=pS(VS)),l.constructor!==c&&rS(l,"constructor",c),CS(l).TypedArrayConstructor=c,LS&&rS(l,LS,n);var h=c!=a;d[n]=c,qE({global:!0,constructor:!0,forced:h,sham:!MS},d),BS in c||rS(c,BS,r),BS in l||rS(l,BS,r),ES(n)}):MT.exports=function(){},PT("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var qS=hg,YS=LE,QS=Vs,XS=Fe,$S=i,ZS=fE.aTypedArray,ey=fE.exportTypedArrayMethod,ty=c("".slice);ey("fill",(function(e){var t=arguments.length;ZS(this);var i="Big"===ty(QS(this),0,3)?YS(e):+e;return XS(qS,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),$S((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var iy=C,ry=Fe,ny=fE,oy=Wt,sy=wE,ay=B,cy=i,ly=iy.RangeError,dy=iy.Int8Array,uy=dy&&dy.prototype,hy=uy&&uy.set,py=ny.aTypedArray,my=ny.exportTypedArrayMethod,_y=!cy((function(){var e=new Uint8ClampedArray(2);return ry(hy,e,{length:1,0:3},1),3!==e[1]})),fy=_y&&ny.NATIVE_ARRAY_BUFFER_VIEWS&&cy((function(){var e=new dy(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));my("set",(function(e){py(this);var t=sy(arguments.length>1?arguments[1]:void 0,1),i=ay(e);if(_y)return ry(hy,this,i,t);var r=this.length,n=oy(i),o=0;if(n+t>r)throw ly("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!_y||fy);var gy=Y.match(/firefox\/(\d+)/i),Ty=!!gy&&+gy[1],Ey=/MSIE|Trident/.test(Y),Sy=Y.match(/AppleWebKit\/(\d+)\./),yy=!!Sy&&+Sy[1],vy=Ta,Iy=i,Ay=et,Ry=u_,Cy=Ty,by=Ey,ky=ie,Dy=yy,Ny=fE.aTypedArray,wy=fE.exportTypedArrayMethod,Oy=C.Uint16Array,Py=Oy&&vy(Oy.prototype.sort),My=!(!Py||Iy((function(){Py(new Oy(2),null)}))&&Iy((function(){Py(new Oy(2),{})}))),Ly=!!Py&&!Iy((function(){if(ky)return ky<74;if(Cy)return Cy<67;if(by)return!0;if(Dy)return Dy<602;var e,t,i=new Oy(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(Py(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));wy("sort",(function(e){return void 0!==e&&Ay(e),Ly?Py(this,e):Ry(Ny(this),function(e){return function(t,i){return void 0!==e?+e(t,i)||0:i!=i?-1:t!=t?1:0===t&&0===i?1/t>0&&1/i<0?1:-1:t>i}}(e))}),!Ly||My);var xy=Vn,Vy=ke,Uy=c,Fy=W,By=Ee,Hy=We,jy=_u,Wy=ys,Gy=Sn,Jy=C.Symbol,Ky=Jy&&Jy.prototype;if(Vy&&By(Jy)&&(!("description"in Ky)||void 0!==Jy().description)){var zy={},qy=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:jy(arguments[0]),t=Hy(Ky,this)?new Jy(e):void 0===e?Jy():Jy(e);return""===e&&(zy[t]=!0),t};Gy(qy,Jy),qy.prototype=Ky,Ky.constructor=qy;var Yy="Symbol(test)"==String(Jy("test")),Qy=Uy(Ky.valueOf),Xy=Uy(Ky.toString),$y=/^Symbol\((.*)\)[^)]+$/,Zy=Uy("".replace),ev=Uy("".slice);Wy(Ky,"description",{configurable:!0,get:function(){var e=Qy(this);if(Fy(zy,e))return"";var t=Xy(e),i=Yy?ev(t,7,-1):Zy(t,$y,"$1");return""===i?void 0:i}}),xy({global:!0,constructor:!0,forced:!0},{Symbol:qy})}var tv=Vp.charAt,iv=_u,rv=ar,nv=jo,ov=Wo,sv="String Iterator",av=rv.set,cv=rv.getterFor(sv);nv(String,"String",(function(e){av(this,{type:sv,string:iv(e),index:0})}),(function(){var e,t=cv(this),i=t.string,r=t.index;return r>=i.length?ov(void 0,!0):(e=tv(i,r),t.index+=e.length,ov(e,!1))}));var lv,dv=ke,uv=c,hv=Fe,pv=i,mv=oi,_v=sn,fv=lr,gv=B,Tv=g,Ev=Object.assign,Sv=Object.defineProperty,yv=uv([].concat),vv=!Ev||pv((function(){if(dv&&1!==Ev({b:1},Ev(Sv({},"a",{enumerable:!0,get:function(){Sv(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol(),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach((function(e){t[e]=e})),7!=Ev({},e)[i]||mv(Ev({},t)).join("")!=r}))?function(e,t){for(var i=gv(e),r=arguments.length,n=1,o=_v.f,s=fv.f;r>n;)for(var a,c=Tv(arguments[n++]),l=o?yv(mv(c),o(c)):mv(c),d=l.length,u=0;d>u;)a=l[u++],dv&&!hv(s,c,a)||(i[a]=c[a]);return i}:Ev,Iv=Ce,Av=ud,Rv=va,Cv=Fe,bv=B,kv=function(e,t,i,r){try{return r?t(Iv(i)[0],i[1]):t(i)}catch(FF){Av(e,"throw",FF)}},Dv=ql,Nv=ta,wv=Wt,Ov=Zm,Pv=ad,Mv=ed,Lv=Array,xv=c,Vv=2147483647,Uv=/[^\0-\u007E]/,Fv=/[.\u3002\uFF0E\uFF61]/g,Bv="Overflow: input needs wider integers to process",Hv=RangeError,jv=xv(Fv.exec),Wv=Math.floor,Gv=String.fromCharCode,Jv=xv("".charCodeAt),Kv=xv([].join),zv=xv([].push),qv=xv("".replace),Yv=xv("".split),Qv=xv("".toLowerCase),Xv=function(e){return e+22+75*(e<26)},$v=function(e,t,i){var r=0;for(e=i?Wv(e/700):e>>1,e+=Wv(e/t);e>455;)e=Wv(e/35),r+=36;return Wv(r+36*e/(e+38))},Zv=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=Jv(e,i++);if(n>=55296&&n<=56319&&i<r){var o=Jv(e,i++);56320==(64512&o)?zv(t,((1023&n)<<10)+(1023&o)+65536):(zv(t,n),i--)}else zv(t,n)}return t}(e);var i,r,n=e.length,o=128,s=0,a=72;for(i=0;i<e.length;i++)(r=e[i])<128&&zv(t,Gv(r));var c=t.length,l=c;for(c&&zv(t,"-");l<n;){var d=Vv;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>Wv((Vv-s)/u))throw Hv(Bv);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++s>Vv)throw Hv(Bv);if(r==o){for(var h=s,p=36;;){var m=p<=a?1:p>=a+26?26:p-a;if(h<m)break;var _=h-m,f=36-m;zv(t,Gv(Xv(m+_%f))),h=Wv(_/f),p+=36}zv(t,Gv(Xv(h))),a=$v(s,u,l==c),s=0,l++}}s++,o++}return Kv(t,"")},eI=Vn,tI=ke,iI=zm,rI=C,nI=va,oI=c,sI=tn,aI=ys,cI=Ds,lI=W,dI=vv,uI=function(e){var t=bv(e),i=Nv(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=Rv(n,r>2?arguments[2]:void 0));var s,a,c,l,d,u,h=Mv(t),p=0;if(!h||this===Lv&&Dv(h))for(s=wv(t),a=i?new this(s):Lv(s);s>p;p++)u=o?n(t[p],p):t[p],Ov(a,p,u);else for(d=(l=Pv(t,h)).next,a=i?new this:[];!(c=Cv(d,l)).done;p++)u=o?kv(l,n,[c.value,p],!0):c.value,Ov(a,p,u);return a.length=p,a},hI=o_,pI=Vp.codeAt,mI=function(e){var t,i,r=[],n=Yv(qv(Qv(e),Fv,"."),".");for(t=0;t<n.length;t++)i=n[t],zv(r,jv(Uv,i)?"xn--"+Zv(i):i);return Kv(r,".")},_I=_u,fI=oo,gI=Ra,TI=bf,EI=ar,SI=EI.set,yI=EI.getterFor("URL"),vI=TI.URLSearchParams,II=TI.getState,AI=rI.URL,RI=rI.TypeError,CI=rI.parseInt,bI=Math.floor,kI=Math.pow,DI=oI("".charAt),NI=oI(/./.exec),wI=oI([].join),OI=oI(1..toString),PI=oI([].pop),MI=oI([].push),LI=oI("".replace),xI=oI([].shift),VI=oI("".split),UI=oI("".slice),FI=oI("".toLowerCase),BI=oI([].unshift),HI="Invalid scheme",jI="Invalid host",WI="Invalid port",GI=/[a-z]/i,JI=/[\d+-.a-z]/i,KI=/\d/,zI=/^0x/i,qI=/^[0-7]+$/,YI=/^\d+$/,QI=/^[\da-f]+$/i,XI=/[\0\t\n\r #%/:<>?@[\\\]^|]/,$I=/[\0\t\n\r #/:<>?@[\\\]^|]/,ZI=/^[\u0000-\u0020]+/,eA=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,tA=/[\t\n\r]/g,iA=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)BI(t,e%256),e=bI(e/256);return wI(t,".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,i=1,r=null,n=0,o=0;o<8;o++)0!==e[o]?(n>i&&(t=r,i=n),r=null,n=0):(null===r&&(r=o),++n);return n>i&&(t=r,i=n),t}(e),i=0;i<8;i++)n&&0===e[i]||(n&&(n=!1),r===i?(t+=i?":":"::",n=!0):(t+=OI(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},rA={},nA=dI({},rA,{" ":1,'"':1,"<":1,">":1,"`":1}),oA=dI({},nA,{"#":1,"?":1,"{":1,"}":1}),sA=dI({},oA,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),aA=function(e,t){var i=pI(e,0);return i>32&&i<127&&!lI(t,e)?e:encodeURIComponent(e)},cA={ftp:21,file:null,http:80,https:443,ws:80,wss:443},lA=function(e,t){var i;return 2==e.length&&NI(GI,DI(e,0))&&(":"==(i=DI(e,1))||!t&&"|"==i)},dA=function(e){var t;return e.length>1&&lA(UI(e,0,2))&&(2==e.length||"/"===(t=DI(e,2))||"\\"===t||"?"===t||"#"===t)},uA=function(e){return"."===e||"%2e"===FI(e)},hA={},pA={},mA={},_A={},fA={},gA={},TA={},EA={},SA={},yA={},vA={},IA={},AA={},RA={},CA={},bA={},kA={},DA={},NA={},wA={},OA={},PA=function(e,t,i){var r,n,o,s=_I(e);if(t){if(n=this.parse(s))throw RI(n);this.searchParams=null}else{if(void 0!==i&&(r=new PA(i,!0)),n=this.parse(s,null,r))throw RI(n);(o=II(new vI)).bindURL(this),this.searchParams=o}};PA.prototype={type:"URL",parse:function(e,t,i){var r,n,o,s,a,c=this,l=t||hA,d=0,u="",h=!1,p=!1,m=!1;for(e=_I(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=LI(e,ZI,""),e=LI(e,eA,"$1")),e=LI(e,tA,""),r=uI(e);d<=r.length;){switch(n=r[d],l){case hA:if(!n||!NI(GI,n)){if(t)return HI;l=mA;continue}u+=FI(n),l=pA;break;case pA:if(n&&(NI(JI,n)||"+"==n||"-"==n||"."==n))u+=FI(n);else{if(":"!=n){if(t)return HI;u="",l=mA,d=0;continue}if(t&&(c.isSpecial()!=lI(cA,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&cA[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?l=RA:c.isSpecial()&&i&&i.scheme==c.scheme?l=_A:c.isSpecial()?l=EA:"/"==r[d+1]?(l=fA,d++):(c.cannotBeABaseURL=!0,MI(c.path,""),l=NA)}break;case mA:if(!i||i.cannotBeABaseURL&&"#"!=n)return HI;if(i.cannotBeABaseURL&&"#"==n){c.scheme=i.scheme,c.path=hI(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=OA;break}l="file"==i.scheme?RA:gA;continue;case _A:if("/"!=n||"/"!=r[d+1]){l=gA;continue}l=SA,d++;break;case fA:if("/"==n){l=yA;break}l=DA;continue;case gA:if(c.scheme=i.scheme,n==lv)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=hI(i.path),c.query=i.query;else if("/"==n||"\\"==n&&c.isSpecial())l=TA;else if("?"==n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=hI(i.path),c.query="",l=wA;else{if("#"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=hI(i.path),c.path.length--,l=DA;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=hI(i.path),c.query=i.query,c.fragment="",l=OA}break;case TA:if(!c.isSpecial()||"/"!=n&&"\\"!=n){if("/"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=DA;continue}l=yA}else l=SA;break;case EA:if(l=SA,"/"!=n||"/"!=DI(u,d+1))continue;d++;break;case SA:if("/"!=n&&"\\"!=n){l=yA;continue}break;case yA:if("@"==n){h&&(u="%40"+u),h=!0,o=uI(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!=f||m){var g=aA(f,sA);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n==lv||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(h&&""==u)return"Invalid authority";d-=uI(u).length+1,u="",l=vA}else u+=n;break;case vA:case IA:if(t&&"file"==c.scheme){l=bA;continue}if(":"!=n||p){if(n==lv||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(c.isSpecial()&&""==u)return jI;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=kA,t)return;continue}"["==n?p=!0:"]"==n&&(p=!1),u+=n}else{if(""==u)return jI;if(s=c.parseHost(u))return s;if(u="",l=AA,t==IA)return}break;case AA:if(!NI(KI,n)){if(n==lv||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()||t){if(""!=u){var T=CI(u,10);if(T>65535)return WI;c.port=c.isSpecial()&&T===cA[c.scheme]?null:T,u=""}if(t)return;l=kA;continue}return WI}u+=n;break;case RA:if(c.scheme="file","/"==n||"\\"==n)l=CA;else{if(!i||"file"!=i.scheme){l=DA;continue}if(n==lv)c.host=i.host,c.path=hI(i.path),c.query=i.query;else if("?"==n)c.host=i.host,c.path=hI(i.path),c.query="",l=wA;else{if("#"!=n){dA(wI(hI(r,d),""))||(c.host=i.host,c.path=hI(i.path),c.shortenPath()),l=DA;continue}c.host=i.host,c.path=hI(i.path),c.query=i.query,c.fragment="",l=OA}}break;case CA:if("/"==n||"\\"==n){l=bA;break}i&&"file"==i.scheme&&!dA(wI(hI(r,d),""))&&(lA(i.path[0],!0)?MI(c.path,i.path[0]):c.host=i.host),l=DA;continue;case bA:if(n==lv||"/"==n||"\\"==n||"?"==n||"#"==n){if(!t&&lA(u))l=DA;else if(""==u){if(c.host="",t)return;l=kA}else{if(s=c.parseHost(u))return s;if("localhost"==c.host&&(c.host=""),t)return;u="",l=kA}continue}u+=n;break;case kA:if(c.isSpecial()){if(l=DA,"/"!=n&&"\\"!=n)continue}else if(t||"?"!=n)if(t||"#"!=n){if(n!=lv&&(l=DA,"/"!=n))continue}else c.fragment="",l=OA;else c.query="",l=wA;break;case DA:if(n==lv||"/"==n||"\\"==n&&c.isSpecial()||!t&&("?"==n||"#"==n)){if(".."===(a=FI(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==n||"\\"==n&&c.isSpecial()||MI(c.path,"")):uA(u)?"/"==n||"\\"==n&&c.isSpecial()||MI(c.path,""):("file"==c.scheme&&!c.path.length&&lA(u)&&(c.host&&(c.host=""),u=DI(u,0)+":"),MI(c.path,u)),u="","file"==c.scheme&&(n==lv||"?"==n||"#"==n))for(;c.path.length>1&&""===c.path[0];)xI(c.path);"?"==n?(c.query="",l=wA):"#"==n&&(c.fragment="",l=OA)}else u+=aA(n,oA);break;case NA:"?"==n?(c.query="",l=wA):"#"==n?(c.fragment="",l=OA):n!=lv&&(c.path[0]+=aA(n,rA));break;case wA:t||"#"!=n?n!=lv&&("'"==n&&c.isSpecial()?c.query+="%27":c.query+="#"==n?"%23":aA(n,rA)):(c.fragment="",l=OA);break;case OA:n!=lv&&(c.fragment+=aA(n,nA))}d++}},parseHost:function(e){var t,i,r;if("["==DI(e,0)){if("]"!=DI(e,e.length-1))return jI;if(t=function(e){var t,i,r,n,o,s,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return DI(e,u)};if(":"==h()){if(":"!=DI(e,1))return;u+=2,d=++l}for(;h();){if(8==l)return;if(":"!=h()){for(t=i=0;i<4&&NI(QI,h());)t=16*t+CI(h(),16),u++,i++;if("."==h()){if(0==i)return;if(u-=i,l>6)return;for(r=0;h();){if(n=null,r>0){if(!("."==h()&&r<4))return;u++}if(!NI(KI,h()))return;for(;NI(KI,h());){if(o=CI(h(),10),null===n)n=o;else{if(0==n)return;n=10*n+o}if(n>255)return;u++}c[l]=256*c[l]+n,2!=++r&&4!=r||l++}if(4!=r)return;break}if(":"==h()){if(u++,!h())return}else if(h())return;c[l++]=t}else{if(null!==d)return;u++,d=++l}}if(null!==d)for(s=l-d,l=7;0!=l&&s>0;)a=c[l],c[l--]=c[d+s-1],c[d+--s]=a;else if(8!=l)return;return c}(UI(e,1,-1)),!t)return jI;this.host=t}else if(this.isSpecial()){if(e=mI(e),NI(XI,e))return jI;if(t=function(e){var t,i,r,n,o,s,a,c=VI(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],r=0;r<t;r++){if(""==(n=c[r]))return e;if(o=10,n.length>1&&"0"==DI(n,0)&&(o=NI(zI,n)?16:8,n=UI(n,8==o?1:2)),""===n)s=0;else{if(!NI(10==o?YI:8==o?qI:QI,n))return e;s=CI(n,o)}MI(i,s)}for(r=0;r<t;r++)if(s=i[r],r==t-1){if(s>=kI(256,5-t))return null}else if(s>255)return null;for(a=PI(i),r=0;r<i.length;r++)a+=i[r]*kI(256,3-r);return a}(e),null===t)return jI;this.host=t}else{if(NI($I,e))return jI;for(t="",i=uI(e),r=0;r<i.length;r++)t+=aA(i[r],rA);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return lI(cA,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&lA(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,r=e.password,n=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,l=t+":";return null!==n?(l+="//",e.includesCredentials()&&(l+=i+(r?":"+r:"")+"@"),l+=iA(n),null!==o&&(l+=":"+o)):"file"==t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+wI(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw RI(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new MA(e.path[0]).origin}catch(FF){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+iA(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(_I(e)+":",hA)},getUsername:function(){return this.username},setUsername:function(e){var t=uI(_I(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=aA(t[i],sA)}},getPassword:function(){return this.password},setPassword:function(e){var t=uI(_I(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=aA(t[i],sA)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?iA(e):iA(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,vA)},getHostname:function(){var e=this.host;return null===e?"":iA(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,IA)},getPort:function(){var e=this.port;return null===e?"":_I(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=_I(e))?this.port=null:this.parse(e,AA))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+wI(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,kA))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=_I(e))?this.query=null:("?"==DI(e,0)&&(e=UI(e,1)),this.query="",this.parse(e,wA)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=_I(e))?("#"==DI(e,0)&&(e=UI(e,1)),this.fragment="",this.parse(e,OA)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var MA=function(e){var t=cI(this,LA),i=gI(arguments.length,1)>1?arguments[1]:void 0,r=SI(t,new PA(e,!1,i));tI||(t.href=r.serialize(),t.origin=r.getOrigin(),t.protocol=r.getProtocol(),t.username=r.getUsername(),t.password=r.getPassword(),t.host=r.getHost(),t.hostname=r.getHostname(),t.port=r.getPort(),t.pathname=r.getPathname(),t.search=r.getSearch(),t.searchParams=r.getSearchParams(),t.hash=r.getHash())},LA=MA.prototype,xA=function(e,t){return{get:function(){return yI(this)[e]()},set:t&&function(e){return yI(this)[t](e)},configurable:!0,enumerable:!0}};if(tI&&(aI(LA,"href",xA("serialize","setHref")),aI(LA,"origin",xA("getOrigin")),aI(LA,"protocol",xA("getProtocol","setProtocol")),aI(LA,"username",xA("getUsername","setUsername")),aI(LA,"password",xA("getPassword","setPassword")),aI(LA,"host",xA("getHost","setHost")),aI(LA,"hostname",xA("getHostname","setHostname")),aI(LA,"port",xA("getPort","setPort")),aI(LA,"pathname",xA("getPathname","setPathname")),aI(LA,"search",xA("getSearch","setSearch")),aI(LA,"searchParams",xA("getSearchParams")),aI(LA,"hash",xA("getHash","setHash"))),sI(LA,"toJSON",(function(){return yI(this).serialize()}),{enumerable:!0}),sI(LA,"toString",(function(){return yI(this).serialize()}),{enumerable:!0}),AI){var VA=AI.createObjectURL,UA=AI.revokeObjectURL;VA&&sI(MA,"createObjectURL",nI(VA,AI)),UA&&sI(MA,"revokeObjectURL",nI(UA,AI))}fI(MA,"URL"),eI({global:!0,constructor:!0,forced:!iI,sham:!tI},{URL:MA}),PT("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var FA=Cs,BA="ArrayBuffer",HA=fT[BA];Vn({global:!0,constructor:!0,forced:C[BA]!==HA},{ArrayBuffer:HA}),FA(BA);var jA=Vn,WA=jh,GA=c([].reverse),JA=[1,2];jA({target:"Array",proto:!0,forced:String(JA)===String(JA.reverse())},{reverse:function(){return WA(this)&&(this.length=this.length),GA(this)}});var KA=Qe,zA=TypeError,qA=Vn,YA=c,QA=et,XA=B,$A=Wt,ZA=function(e,t){if(!delete e[t])throw zA("Cannot delete property "+KA(t)+" of "+KA(e))},eR=_u,tR=i,iR=u_,rR=np,nR=Ty,oR=Ey,sR=ie,aR=yy,cR=[],lR=YA(cR.sort),dR=YA(cR.push),uR=tR((function(){cR.sort(void 0)})),hR=tR((function(){cR.sort(null)})),pR=rR("sort"),mR=!tR((function(){if(sR)return sR<70;if(!(nR&&nR>3)){if(oR)return!0;if(aR)return aR<603;var e,t,i,r,n="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(r=0;r<47;r++)cR.push({k:t+r,v:i})}for(cR.sort((function(e,t){return t.v-e.v})),r=0;r<cR.length;r++)t=cR[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));qA({target:"Array",proto:!0,forced:uR||!hR||!pR||!mR},{sort:function(e){void 0!==e&&QA(e);var t=XA(this);if(mR)return void 0===e?lR(t):lR(t,e);var i,r,n=[],o=$A(t);for(r=0;r<o;r++)r in t&&dR(n,t[r]);for(iR(n,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:eR(t)>eR(i)?1:-1}}(e)),i=$A(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)ZA(t,r++);return t}}),(0,fE.exportTypedArrayStaticMethod)("from",zE,IE);let _R=!0,fR=!0;function gR(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function TR(e,t,i){if(!e.RTCPeerConnection)return;const r=e.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return n.apply(this,arguments);const o=e=>{const t=i(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,o),n.apply(this,[e,o])};const o=r.removeEventListener;r.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.apply(this,arguments);const r=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,r])},Object.defineProperty(r,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function ER(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(_R=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function SR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(fR=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function yR(){if("object"==typeof window){if(_R)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function vR(e,t){fR&&console.warn(e+" is deprecated, please use "+t+" instead.")}function IR(e){return"[object Object]"===Object.prototype.toString.call(e)}function AR(e){return IR(e)?Object.keys(e).reduce((function(t,i){const r=IR(e[i]),n=r?AR(e[i]):e[i],o=r&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[i]:n})}),{}):e}function RR(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?RR(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{RR(e,e.get(t),i)}))})))}function CR(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((i=>{i.type===r&&i.trackId===t.id&&RR(e,i,n)}))})),n}const bR=yR;function kR(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const r=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const r="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==r.ideal){t.optional=t.optional||[];let e={};"number"==typeof r.ideal?(e[n("min",i)]=r.ideal,t.optional.push(e),e={},e[n("max",i)]=r.ideal,t.optional.push(e)):(e[n("",i)]=r.ideal,t.optional.push(e))}void 0!==r.exact&&"number"!=typeof r.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",i)]=r.exact):["min","max"].forEach((e=>{void 0!==r[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,i)]=r[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=r(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let s=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=r(e.video),bR("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return bR("chrome: "+JSON.stringify(e)),n(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,r){n(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{r&&r(o(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function DR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function NR(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const n=new Event("track");n.track=i.track,n.receiver=r,n.transceiver={receiver:r},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const n=new Event("track");n.track=i,n.receiver=r,n.transceiver={receiver:r},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else TR(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function wR(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let n=i.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function OR(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,r]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const r=function(e){i(o(n(e)))};return t.apply(this,[r,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(o(n(t)))},i])})).then(i,r)}}function PR(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>CR(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),TR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>CR(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,r;return this.getSenders().forEach((i=>{i.track===e&&(t?r=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?r=!0:i=t),t.track===e))),r||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function MR(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const r=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(r)&&this._shimmedLocalStreams[i.id].push(r):this._shimmedLocalStreams[i.id]=[i,r],r};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const r=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(r)};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function LR(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return MR(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}r.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const r=[].slice.call(arguments,1);if(1!==r.length||!r[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const n=this._streams[i.id];if(n)n.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const r=new e.MediaStream([t]);this._streams[i.id]=r,this._reverseStreams[r.id]=i,this.addStream(r)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=r[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function xR(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}))}function VR(e,t){TR(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var UR=Object.freeze({__proto__:null,shimMediaStream:DR,shimOnTrack:NR,shimGetSendersWithDtmf:wR,shimGetStats:OR,shimSenderReceiverGetStats:PR,shimAddTrackRemoveTrackWithNative:MR,shimAddTrackRemoveTrack:LR,shimPeerConnection:xR,fixNegotiationNeeded:VR,shimGetUserMedia:kR,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const r=i.video&&i.video.width,n=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},r&&(i.video.mandatory.maxWidth=r),n&&(i.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function FR(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){vR("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},r&&r.prototype.getSettings){const t=r.prototype.getSettings;r.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(r&&r.prototype.applyConstraints){const t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function BR(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function HR(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,o]=arguments;return r.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(ub){if("TypeError"!==ub.name)throw ub;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,o)}}function jR(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function WR(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),TR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function GR(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){vR("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function JR(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function KR(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const r=t.apply(this,arguments);if(i){const{sender:t}=r,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return r})}function zR(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function qR(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function YR(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var QR=Object.freeze({__proto__:null,shimOnTrack:BR,shimPeerConnection:HR,shimSenderGetStats:jR,shimReceiverGetStats:WR,shimRemoveStream:GR,shimRTCDataChannel:JR,shimAddTransceiver:KR,shimGetParameters:zR,shimCreateOffer:qR,shimCreateAnswer:YR,shimGetUserMedia:FR,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function XR(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function $R(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function ZR(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,i){const r=n.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r};t.setLocalDescription=a,a=function(e,t,i){const r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.setRemoteDescription=a,a=function(e,t,i){const r=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.addIceCandidate=a}function eC(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(tC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function tC(e){return e&&void 0!==e.video?Object.assign({},e,{video:AR(e.video)}):e}function iC(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let r=e.iceServers[i];void 0===r.urls&&r.url?(vR("RTCIceServer.url","RTCIceServer.urls"),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function rC(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function nC(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function oC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var sC=Object.freeze({__proto__:null,shimLocalStreamsAPI:XR,shimRemoteStreamsAPI:$R,shimCallbacksAPI:ZR,shimGetUserMedia:eC,shimConstraints:tC,shimRTCIceServerUrls:iC,shimTrackEventTransceiver:rC,shimCreateOfferLegacy:nC,shimAudioContext:oC}),aC={};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let r=8;r<t.length;r+=2)switch(t[r]){case"raddr":i.relatedAddress=t[r+1];break;case"rport":i.relatedPort=parseInt(t[r+1],10);break;case"tcptype":i.tcpType=t[r+1];break;case"ufrag":i.ufrag=t[r+1],i.usernameFragment=t[r+1];break;default:void 0===i[t[r]]&&(i[t[r]]=t[r+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const r=e.substring(e.indexOf(" ")+1).split(";");for(let n=0;n<r.length;n++)i=r[n].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const r=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+i+" "+r.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substring(t+1,r),i.value=e.substring(r+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const r=t.matchPrefix(e+i,"a=ice-ufrag:")[0],n=t.matchPrefix(e+i,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substring(12),password:n.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(" ");i.profile=r[2];for(let o=3;o<r.length;o++){const n=r[o],s=t.matchPrefix(e,"a=rtpmap:"+n+" ")[0];if(s){const r=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+n+" ");switch(r.parameters=o.length?t.parseFmtp(o[0]):{},r.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+n+" ").map(t.parseRtcpFb),i.codecs.push(r),r.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(r.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const n=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{n.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let r="";r+="m="+e+" ",r+=i.codecs.length>0?"9":"0",r+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{r+=t.writeRtpMap(e),r+=t.writeFmtp(e),r+=t.writeRtcpFb(e)}));let n=0;return i.codecs.forEach((e=>{e.maxptime>n&&(n=e.maxptime)})),n>0&&(r+="a=maxptime:"+n+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{r+=t.writeExtmap(e)})),r},t.parseRtpEncodingParameters=function(e){const i=[],r=t.parseRtpParameters(e),n=-1!==r.fecMechanisms.indexOf("RED"),o=-1!==r.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===a&&(c=l[0][1]),r.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),n&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=d}))),i},t.parseRtcpParameters=function(e){const i={},r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=n.length>0,i.compound=0===n.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const r=t.matchPrefix(e,"a=msid:");if(1===r.length)return i=r[0].substring(7).split(" "),{stream:i[0],track:i[1]};const n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return n.length>0?(i=n[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),r=t.matchPrefix(e,"a=max-message-size:");let n;r.length>0&&(n=parseInt(r[0].substring(19),10)),isNaN(n)&&(n=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:n};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,r){let n;const o=void 0!==i?i:2;n=e||t.generateSessionId();return"v=0\r\no="+(r||"thisisadapterortc")+" "+n+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const r=t.splitLines(e);for(let t=0;t<r.length;t++)switch(r[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}({get exports(){return aC},set exports(e){aC=e}});var cC=aC,lC=e({__proto__:null,default:cC},[aC]);function dC(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),r=cC.parseCandidate(e.candidate);for(const e in r)e in i||Object.defineProperty(i,e,{value:r[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,TR(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function uC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||TR(e,"icecandidate",(e=>{if(e.candidate){const t=cC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function hC(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=cC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=cC.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),r=function(e,i){let r=65536;"firefox"===t.browser&&57===t.version&&(r=65535);const n=cC.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?r=parseInt(n[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(r=2147483637),r}(arguments[0],e);let n;n=0===i&&0===r?Number.POSITIVE_INFINITY:0===i||0===r?Math.max(i,r):Math.min(i,r);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>n}),this._sctp=o}return i.apply(this,arguments)}}function pC(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const r=arguments[0],n=r.length||r.size||r.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},TR(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function 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 _C(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 fC(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 gC(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 TC=Object.freeze({__proto__:null,shimRTCIceCandidate:dC,shimRTCIceCandidateRelayProtocol:uC,shimMaxMessageSize:hC,shimSendThrowTypeError:pC,shimConnectionState:mC,removeExtmapAllowMixed:_C,shimAddIceCandidateNullOrEmpty:fC,shimParameterlessSetLocalDescription:gC});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=yR,r=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=gR(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=gR(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=gR(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:TC,extractVersion:gR,disableLog:ER,disableWarnings:SR,sdp:lC};switch(r.browser){case"chrome":if(!UR||!xR||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),n;if(null===r.version)return i("Chrome shim can not determine version, not shimming."),n;i("adapter.js shimming chrome."),n.browserShim=UR,fC(e,r),gC(e),kR(e,r),DR(e),xR(e,r),NR(e),LR(e,r),wR(e),OR(e),PR(e),VR(e,r),dC(e),uC(e),mC(e),hC(e,r),pC(e),_C(e,r);break;case"firefox":if(!QR||!HR||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=QR,fC(e,r),gC(e),FR(e,r),HR(e,r),BR(e),GR(e),jR(e),WR(e),JR(e),KR(e),zR(e),qR(e),YR(e),dC(e),mC(e),hC(e,r),pC(e);break;case"safari":if(!sC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=sC,fC(e,r),gC(e),iC(e),nC(e),ZR(e),XR(e),$R(e),rC(e),eC(e),oC(e),dC(e),uC(e),hC(e,r),pC(e),_C(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var EC,SC=Object.create,yC=Object.defineProperty,vC=Object.defineProperties,IC=Object.getOwnPropertyDescriptor,AC=Object.getOwnPropertyDescriptors,RC=Object.getOwnPropertyNames,CC=Object.getOwnPropertySymbols,bC=Object.getPrototypeOf,kC=Object.prototype.hasOwnProperty,DC=Object.prototype.propertyIsEnumerable,NC=Reflect.get,wC=Math.pow,OC=(e,t,i)=>t in e?yC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,PC=(e,t)=>{for(var i in t||(t={}))kC.call(t,i)&&OC(e,i,t[i]);if(CC)for(var i of CC(t))DC.call(t,i)&&OC(e,i,t[i]);return e},MC=(e,t)=>vC(e,AC(t)),LC=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),xC=(e,t)=>{for(var i in t)yC(e,i,{get:t[i],enumerable:!0})},VC=(e,t,i)=>(i=null!=e?SC(bC(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of RC(t))!kC.call(e,n)&&n!==i&&yC(e,n,{get:()=>t[n],enumerable:!(r=IC(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:yC(i,"default",{value:e,enumerable:!0}),e)),UC=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?IC(t,i):t,s=e.length-1;s>=0;s--)(n=e[s])&&(o=(r?n(t,i,o):n(o))||o);return r&&o&&yC(t,i,o),o},FC=(e,t,i)=>(OC(e,"symbol"!=typeof t?t+"":t,i),i),BC=(e,t,i)=>NC(bC(e),i,t),HC=(e,t,i)=>new Promise(((r,n)=>{var o=e=>{try{a(i.next(e))}catch(SP){n(SP)}},s=e=>{try{a(i.throw(e))}catch(SP){n(SP)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),jC=LC(((e,t)=>{var i=Object.prototype.hasOwnProperty,r="~";function n(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,i,n,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new o(i,n||e,s),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function c(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),c.prototype.eventNames=function(){var e,t,n=[];if(0===this._eventsCount)return n;for(t in e=this._events)i.call(e,t)&&n.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},c.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,o=i.length,s=new Array(o);n<o;n++)s[n]=i[n].fn;return s},c.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},c.prototype.emit=function(e,t,i,n,o,s){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,d=this._events[a],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,n),!0;case 5:return d.fn.call(d.context,t,i,n,o),!0;case 6:return d.fn.call(d.context,t,i,n,o,s),!0}for(l=1,c=new Array(u-1);l<u;l++)c[l-1]=arguments[l];d.fn.apply(d.context,c)}else{var h,p=d.length;for(l=0;l<p;l++)switch(d[l].once&&this.removeListener(e,d[l].fn,void 0,!0),u){case 1:d[l].fn.call(d[l].context);break;case 2:d[l].fn.call(d[l].context,t);break;case 3:d[l].fn.call(d[l].context,t,i);break;case 4:d[l].fn.call(d[l].context,t,i,n);break;default:if(!c)for(h=1,c=new Array(u-1);h<u;h++)c[h-1]=arguments[h];d[l].fn.apply(d[l].context,c)}}return!0},c.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},c.prototype.removeListener=function(e,t,i,n){var o=r?r+e:e;if(!this._events[o])return this;if(!t)return a(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!n||s.once)&&(!i||s.context===i)&&a(this,o);else{for(var c=0,l=[],d=s.length;c<d;c++)(s[c].fn!==t||n&&!s[c].once||i&&s[c].context!==i)&&l.push(s[c]);l.length?this._events[o]=1===l.length?l[0]:l:a(this,o)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new n,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,void 0!==t&&(t.exports=c)})),WC=LC(((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")}))}))})),GC=LC((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var n=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:n&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=WC(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),JC=LC(((e,t)=>{var i=WC(),r=/%[sdv%]/g,n=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},o=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||s,n=t.innerOrder||a,c=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),KC=LC((e=>{var t=GC(),i=JC();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})),zC=LC(((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")}))}))})),qC=LC((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var n=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:n&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=zC(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),YC=LC(((e,t)=>{var i=zC(),r=/%[sdv%]/g,n=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},o=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||s,n=t.innerOrder||a,c=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),QC=LC((e=>{var t=qC(),i=YC();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})),XC=VC(jC()),$C=((EC=$C||{})[EC.INVALID_PARAMETER=4096]="INVALID_PARAMETER",EC[EC.INVALID_OPERATION=4097]="INVALID_OPERATION",EC[EC.NOT_SUPPORTED=4098]="NOT_SUPPORTED",EC[EC.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",EC[EC.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",EC[EC.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",EC[EC.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",EC[EC.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",EC[EC.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",EC[EC.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",EC[EC.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",EC[EC.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",EC[EC.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",EC[EC.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",EC[EC.CLIENT_BANNED=16448]="CLIENT_BANNED",EC[EC.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",EC[EC.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",EC[EC.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",EC[EC.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",EC[EC.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",EC[EC.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",EC[EC.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",EC[EC.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",EC[EC.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",EC[EC.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",EC[EC.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",EC[EC.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",EC[EC.API_CALL_ABORTED=16461]="API_CALL_ABORTED",EC[EC.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",EC[EC.UNKNOWN=65535]="UNKNOWN",EC),ZC=$C,eb=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=ZC.UNKNOWN,extraCode:n=0,constraint:o}=e,s="<".concat(function(e){for(let t in ZC)if(ZC[t]===e)return t;return"UNKNOWN"}(r)," 0x").concat(r.toString(16),">"),a="".concat(i).concat(o?" constraint: ".concat(o):"").concat(null!=i&&i.includes(s)?"":" ".concat(s));super(a),FC(this,"code"),FC(this,"extraCode"),FC(this,"message"),FC(this,"originMessage"),FC(this,"name"),FC(this,"constraint"),this.code=r,this.extraCode=n,this.name=t,this.message=a,this.constraint=o,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},tb=eb,ib=0,rb=!0,nb=function(){return(new Date).getTime()+ib},ob=function(){let e=new Date;return e.setTime(nb()),e.toLocaleString()},sb={};xC(sb,{bytes2ms:()=>nw,convertObjectNumberToInt:()=>qw,copyProperties:()=>rw,deepClone:()=>Vw,deepMerge:()=>xw,delay:()=>Yw,fibonacci:()=>uw,formatedTime:()=>Hw,getAbilityConfigUrl:()=>JN,getConstructorName:()=>Rw,getContainerFromElement:()=>Fw,getEnv:()=>YN,getInternalVersion:()=>Nw,getLoggerUrl:()=>XN,getMuteStateFromFlag:()=>Pw,getNetworkType:()=>ZN,getNumNetworkType:()=>iw,getReconnectionTimeout:()=>hw,getStringByteLength:()=>Gw,getTurnServer:()=>Mw,getUint32Version:()=>zw,getValueType:()=>pw,getViewListFromView:()=>Uw,glog:()=>cw,ipv4ToUint32:()=>Lw,isArray:()=>Sw,isAudioWorkletSupported:()=>Cw,isBoolean:()=>Tw,isConstructor:()=>Aw,isEmpty:()=>Ow,isFunction:()=>mw,isLangChinese:()=>lw,isMediaStreamTrack:()=>yw,isNumber:()=>gw,isObject:()=>Ew,isOverseaSdkAppId:()=>QN,isPlainObject:()=>dw,isPortrait:()=>Jw,isPromise:()=>Iw,isRemoteTrack:()=>vw,isString:()=>fw,isUndefined:()=>_w,loadImage:()=>Kw,ms2bytes:()=>sw,ms2samples:()=>aw,performanceNow:()=>kw,promiseAny:()=>bw,samples2ms:()=>ow,setNetworkType:()=>tw,stringify:()=>jw,stringifyIncludeValue:()=>Ww,throttlePromise:()=>Qw});var ab={};xC(ab,{AUDIO_MUTE_BIT:()=>zb,AUDIO_STAT_BIT:()=>Kb,AUX_STAT_BIT:()=>Jb,AUX_STREAM_MSID:()=>Qb,BACKEND_ENV:()=>Hb,BASE_DOC_URL:()=>Ib,BASE_HOST:()=>Eb,CAPABILITIES_KEYS:()=>Hk,CLASS_NAME:()=>kk,CLOUD_CONSOLE_URL:()=>vb,DATA_FREEZE_TIMING:()=>yk,DOC_URL:()=>Ab,DTLS_STATE_UNKNOWN:()=>sk,ENV_NAME:()=>Db,EXCHANGE_SDP_TIMEOUT:()=>fk,INTERVAL:()=>Fk,IS_WORKER:()=>mb,IS_WORKLET:()=>_b,KIBANA_EVENT:()=>pk,LOCAL_STREAM_PUBLISH_STATE:()=>Sk,LOGGER_CMD_TYPE:()=>kb,LOGGER_DOMAIN:()=>Rb,LOGGER_DOMAIN_OVERSEA:()=>Cb,LOG_LEVEL:()=>Nb,LOG_LEVEL_NAME:()=>Pk,MAIN_STREAM_MSID:()=>Yb,MICROPHONE_COMMUNICATIONS:()=>Ok,MICROPHONE_DEFAULT:()=>Nk,NAME:()=>Fb,NETWORK_TYPE:()=>Pb,NOT_SUPPORTED_H264:()=>Ek,PAUSED_RETRY_COUNT:()=>Dk,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Rk,PEER_CONNECTION_STATE:()=>ak,PEER_LEAVE_REASON:()=>Mk,RAF:()=>Uk,RECOVER_CAPTURE_INTERVAL:()=>xk,REMOTE_STREAM_TYPE_AUX:()=>$b,REMOTE_STREAM_TYPE_MAIN:()=>Xb,RENDER_FREEZE_TIMING:()=>vk,RIC:()=>Vk,SCHEDULE_DOMAIN:()=>Ck,SCHEDULE_TIMEOUT:()=>bk,SDP_SEMANTICS_PLAN_B:()=>Tk,SDP_SEMANTICS_UNIFIED_PLAN:()=>gk,SECOND_HOST:()=>Sb,SIGNAL_PING_PONG_INTERVAL:()=>Ob,SIGNAL_PING_TIMEOUT:()=>wb,SIGNAL_RECONNECTION_COUNT:()=>hk,SMALL_STAT_BIT:()=>Gb,SPEAKER_DEFAULT:()=>wk,STORAGE_EXPIRES_TIME:()=>Mb,STREAM_TYPE_BIG:()=>Ik,STREAM_TYPE_SMALL:()=>Ak,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Lk,SYNC_USER_LIST_INTERVAL:()=>mk,Scene:()=>jb,Switch:()=>Lb,THIRD_HOST:()=>yb,TIMEOUT:()=>Bk,TRANSPORT_DIRECTION:()=>Bb,TRTC_ERROR_ASSISTANCE:()=>bb,TRTC_QUALITY_BAD:()=>rk,TRTC_QUALITY_DISCONNECTED:()=>ok,TRTC_QUALITY_EXCELLENT:()=>ek,TRTC_QUALITY_GOOD:()=>tk,TRTC_QUALITY_POOR:()=>ik,TRTC_QUALITY_UNKNOWN:()=>Zb,TRTC_QUALITY_VERY_BAD:()=>nk,UPDATE_OFFER_TIMEOUT:()=>_k,VIDEO_MUTE_BIT:()=>qb,VIDEO_STAT_BIT:()=>Wb,audioProfileMap:()=>xb,getRetryCount:()=>dk,getScriptDir:()=>fb,innerVersion:()=>cb,loggerProxy:()=>gb,screenProfileMap:()=>Ub,setLoggerProxy:()=>Tb,setRetryCount:()=>lk,setVersion:()=>db,version:()=>lb,videoProfileMap:()=>Vb});var cb="4.15.00.1600",lb="5.0.0";function db(e){lb=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));cb="".concat(t,".").concat(Math.min(15,i),".").concat(Math.min(15,r),".").concat(i.toString().padStart(2,"0")).concat(r.toString().padStart(2,"0"))}var ub,hb,pb,mb="undefined"!=typeof importScripts,_b="undefined"!=typeof registerProcessor,fb=()=>{let e=mb?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},gb="",Tb=e=>gb=e,Eb="web.sdk.qcloud.com",Sb="web.sdk.tencent.cn",yb="web.sdk.cloud.tencent.cn",vb="https://console.cloud.tencent.com/trtc",Ib="https://".concat(Eb,"/trtc/webrtc/v5/doc"),Ab="".concat(Ib,"/zh-cn/"),Rb="https://yun.tim.qq.com",Cb="https://apisgp.my-imcloud.com",bb="trtc_error_assistance",kb={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Db={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Nb=((pb=Nb||{})[pb.TRACE=0]="TRACE",pb[pb.DEBUG=1]="DEBUG",pb[pb.INFO=2]="INFO",pb[pb.WARN=3]="WARN",pb[pb.ERROR=4]="ERROR",pb[pb.NONE=5]="NONE",pb),wb=18e3,Ob=2e3,Pb={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Mb=6048e5,Lb=((hb=Lb||{}).USEAINS="useAINS",hb.ENABLEDEBUG="enableDebug",hb.USEV2="useV2",hb.USEWT="useWt",hb),xb={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},Vb={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},Ub={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},Fb={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},Bb={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Hb={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},jb=((ub=jb||{}).LIVE="live",ub.RTC="rtc",ub),Wb=1,Gb=2,Jb=4,Kb=8,zb=64,qb=16,Yb="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Qb="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Xb=Fb.MAIN,$b=Fb.AUXILIARY,Zb=0,ek=1,tk=2,ik=3,rk=4,nk=5,ok=6,sk="unknown",ak={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},ck=1/0;function lk(e){ck=e}function dk(){return ck}var uk,hk=30,pk={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},mk=1e4,_k=1e4,fk=1e4,gk="unified-plan",Tk="plan-b",Ek=1028,Sk=((uk=Sk||{})[uk.UNPUBLISH=-1]="UNPUBLISH",uk[uk.PUBLISHING=0]="PUBLISHING",uk[uk.PUBLISHED=1]="PUBLISHED",uk),yk=500,vk=1e3,Ik=Fb.BIG,Ak=Fb.SMALL,Rk=1e4,Ck={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_OLD:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA_OLD:"schedule-ecdn.rtc.tencentcloud.com"},bk=2e3,kk={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Dk=5,Nk="default",wk=Nk,Ok="communications",Pk=Object.keys(Nb),Mk=["normal leave","timeout leave","kick","role change"],Lk=10,xk=2e3,Vk="ric",Uk="raf",Fk="interval",Bk="timeout",Hk=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"];function jk(e){let{url:t,body:i,method:r,timeout:n}=e,o=new XMLHttpRequest;return new Promise(((e,s)=>{o.onreadystatechange=()=>{if(4===o.readyState)if(o.status>=200&&o.status<300)try{let t=JSON.parse(o.response);e({data:t})}catch(t){e({data:o.response})}else s({status:o.status,statusText:o.statusText||"request failed!"})},o.timeout=n||5e3,o.open(r||"POST",t,!0),o.send(i)}))}function Wk(e){return HC(this,null,(function*(){let t=kw(),i=JSON.stringify(e);try{if(!CompressionStream||i.length<=2800)return i;let e=new Blob([i],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),r=yield(yield(yield new Response(e)).blob()).arrayBuffer();return rO.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(kw()-t,"ms")),r}catch(uk){return i}}))}var Gk=1e8,Jk={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},Kk={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(r,"(), received type: ").concat(pw(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(r,"(), received type: ").concat(pw(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:r,value:n}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(n,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,fnName:r,value:n}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(n,".")},API_CALL_TIMEOUT:e=>"".concat(e.commandDesc||e.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," })."),ERROR_MESSAGE(e){let t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>"exchange sdp failed ".concat(e.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>"'".concat(e,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:e=>"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(e){let{error:t,code:i}=e;return"Failed to join room - ".concat(t," code: ").concat(i)},REJOIN_ROOM_FAILED:e=>"reJoin room: ".concat(e.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:"no permission to publish() under live/".concat("audience",', please call switchRole("',"anchor",'") firstly before publish().'),INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>"duplicate ".concat(e," stream publishing, please unpublish your prev ").concat(e," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(e){let{message:t,userId:i,streamType:r}=e;return"failed to subscribe ".concat(i," ").concat(r," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as ".concat("anchor"," or ","audience","."),INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,"."),CLIENT_BANNED:e=>"client was banned because of ".concat(e.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>"startPublishCDNStream failed, errMsg: ".concat(e.message,"."),STOP_PUBLISH_CDN_FAILED:e=>"stopPublishCDNStream failed, errMsg: ".concat(e.message,"."),INVALID_STREAM_ID:e=>"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>"cannot replace ".concat(e.kind," track because stream has not ").concat(e.kind," track"),NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:e=>"startMixTranscode failed, errMsg: ".concat(e.message,"."),STOP_MIX_TRANSCODE_FAILED:e=>"stopMixTranscode failed, errMsg: ".concat(e.message,"."),MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:e=>"'".concat(e,"' is required and must be between 1 and 15."),MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:e=>{let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE:e=>{let{key:t,fnName:i,type:r}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(r,".")},PLAY_FAILED:e=>"".concat(e.media," play failed,browser exception: ").concat(e.error.toString()),INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:e=>"".concat(e,"Track is not supported on your browser."),NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:e=>"".concat(e.signalResponse," failed, response code is ").concat(e.code," , errMsg: ").concat(e.message,"."),CATCH_HANDLER_ERROR(e){let{name:t,event:i}=e;return"an error was caught in ".concat(t,".on('").concat(i,"', handler), please check your code in 'handler'.")},API_NOT_EXIST(e){let{name:t}=e;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:e=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(e){let{funName:t}=e;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage".concat(!1===e?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:e=>{let{isSize:t,name:i,timesInSecond:r,maxSizeInSecond:n}=e;return"api ".concat(i," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(n," bytes"):r," in a second.")},CONNECTION_ABORTED:e=>"connection aborted due to: ".concat(e),API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(e.userId," ").concat(e.streamType," stream aborted, reason: remote user ").concat(e.userId," unpublished stream."):"API aborted, reason: ".concat(e.message),t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:e=>"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")},zk={};xC(zk,{ANDROID_VERSION:()=>sD,CHROME_MAJOR_VERSION:()=>aN,CHROME_VERSION:()=>cN,EDGE_VERSION:()=>pD,EDG_MAJOR_VERSION:()=>fD,EDG_VERSION:()=>_D,FIREFOX_MAJOR_VERSION:()=>uD,FIREFOX_VERSION:()=>dD,HUAWEI_VERSION:()=>QD,IE_VERSION:()=>bD,IOS_MAIN_VERSION:()=>mN,IOS_VERSION:()=>pN,IPADQQB_VERSION:()=>UD,IS_ANDROID:()=>oD,IS_ANDROID_WEBVIEW:()=>hN,IS_ANY_SAFARI:()=>dN,IS_CHROME:()=>oN,IS_CHROME_OS:()=>jD,IS_CHROMIUM_BASE:()=>nN,IS_EDG:()=>mD,IS_EDGE:()=>hD,IS_ELECTRON:()=>JD,IS_FIREFOX:()=>lD,IS_HEADLESS_CHROME:()=>sN,IS_HUAWEI:()=>YD,IS_HUAWEIBROWSER:()=>qD,IS_IE:()=>CD,IS_IE8:()=>RD,IS_IOS:()=>nD,IS_IOS_13_OR_14:()=>gN,IS_IOS_15_1:()=>fN,IS_IPAD:()=>eD,IS_IPADQQB:()=>VD,IS_IPAD_PRO:()=>tD,IS_IPHONE:()=>iD,IS_IPOD:()=>rD,IS_LINUX:()=>HD,IS_LOCAL:()=>TN,IS_MAC:()=>BD,IS_MACQQB:()=>LD,IS_MIBROWSER:()=>KD,IS_MQQB:()=>wD,IS_NATIVE_ANDROID:()=>cD,IS_OLD_ANDROID:()=>aD,IS_OPPOBROWSER:()=>ZD,IS_SAFARI:()=>lN,IS_SAFARI_15_1:()=>_N,IS_SAMSUNGBROWSER:()=>XD,IS_SOGOU:()=>ED,IS_SOGOUM:()=>gD,IS_TBS:()=>yD,IS_UCBROWSER:()=>GD,IS_VIVOBROWSER:()=>tN,IS_WECHAT:()=>kD,IS_WIN:()=>FD,IS_WQQB:()=>PD,IS_WX:()=>WD,IS_X5MQQB:()=>ND,IS_XWEB:()=>ID,MACQQB_VERSION:()=>xD,MI_VERSION:()=>zD,MQQB_VERSION:()=>OD,OPPO_VERSION:()=>eN,SAFARI_VERSION:()=>uN,SAMSUNG_VERSION:()=>$D,SOGOUM_VERSION:()=>TD,SOGOU_VERSION:()=>SD,TBS_VERSION:()=>vD,UA_DATA_STRING:()=>IN,USER_AGENT:()=>qk,VIVO_VERSION:()=>iN,WECHAT_VERSION:()=>DD,WQQB_VERSION:()=>MD,XWEB_VERSION:()=>AD,browserInfo:()=>SN,getBrowserInfo:()=>yN,getChromeMajorVersion:()=>rN,getDeviceModel:()=>RN,getOSName:()=>bN,getOSString:()=>kN,getOSType:()=>NN,getTerminalType:()=>DN,getUserAgentData:()=>AN,isLocalStorageEnabled:()=>EN});var qk="undefined"==typeof navigator?"":navigator.userAgent,Yk=e=>new RegExp(e,"i").test(qk),Qk=e=>{if(Yk(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=qk.match(t);if(i&&i[1])return i[1]}return""},Xk=e=>{if(Yk(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=qk.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},$k=/AppleWebKit\/([\d.]+)/i.exec(qk),Zk=$k?parseFloat($k[1]):NaN,eD=Yk("iPad"),tD="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Yk("Macintosh"),iD=Yk("iPhone")&&!eD,rD=Yk("iPod"),nD=iD||eD||rD||tD,oD=Yk("Android"),sD=function(){if(oD){let e=qk.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}(),aD=oD&&Yk("webkit")&&sD<2.3,cD=oD&&sD<5&&Zk<537,lD=Yk("Firefox"),dD=Qk("Firefox"),uD=Xk("Firefox"),hD=Yk("Edge"),pD=Qk("Edge"),mD=Yk("Edg"),_D=Qk("Edg"),fD=Xk("Edg"),gD=Yk("SogouMobileBrowser"),TD=Qk("SogouMobileBrowser"),ED=Yk("MetaSr\\s"),SD=Qk("MetaSr\\s"),yD=Yk("TBS"),vD=Qk("TBS"),ID=Yk("XWEB"),AD=Qk("XWEB"),RD=Yk("MSIE\\s8\\.0"),CD=Yk("MSIE\\/\\d+"),bD=function(){if(CD){let e=/MSIE\s(\d+)\.\d/.exec(qk),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(qk)&&/rv:11.0/.test(qk)&&(t=11),t}return NaN}(),kD=Yk("(micromessenger|webbrowser)"),DD=Qk("MicroMessenger"),ND=!yD&&Yk("MQQBrowser")&&Yk("COVC"),wD=!yD&&Yk("MQQBrowser")&&!Yk("COVC"),OD=wD||ND?Qk("MQQBrowser"):"",PD=!yD&&Yk(" QQBrowser"),MD=Qk(" QQBrowser"),LD=!yD&&Yk("QQBrowserLite"),xD=Qk("QQBrowserLite"),VD=!yD&&Yk("MQBHD"),UD=Qk("MQBHD"),FD=Yk("Windows"),BD=!nD&&Yk("MAC OS X"),HD=!oD&&Yk("Linux"),jD=Yk("CrOS"),WD=Yk("MicroMessenger"),GD=Yk("UCBrowser"),JD=Yk("Electron"),KD=Yk("MiuiBrowser"),zD=Qk("MiuiBrowser"),qD=Yk("HuaweiBrowser"),YD=Yk("Huawei"),QD=Qk("HuaweiBrowser"),XD=Yk("SamsungBrowser"),$D=Qk("SamsungBrowser"),ZD=Yk("HeyTapBrowser"),eN=Qk("HeyTapBrowser"),tN=Yk("VivoBrowser"),iN=Qk("VivoBrowser"),rN=()=>Xk("Chrome"),nN=Yk("Chrome"),oN=!hD&&!ED&&!gD&&!yD&&!ID&&!mD&&!PD&&!KD&&!qD&&!XD&&!ZD&&!tN&&nN,sN=Yk("HeadlessChrome"),aN=rN(),cN=Qk("Chrome"),lN=!nN&&!wD&&!ND&&!LD&&!VD&&Yk("Safari"),dN=lN||nD,uN=Qk("Version"),hN=/Android.*(wv|.0.0.0)/.test(qk),pN=(()=>{if(tD)return uN;if(nD){let e=qk.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),mN=Number(pN.split(".")[0]),_N="15.1"===uN,fN="15.1"===pN,gN=(()=>{let e=Number(pN.split(".")[0]);return 14===e||13===e})(),TN="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),EN=(()=>{let e;return()=>{if(_w(e))try{e=!!window.localStorage}catch(vP){e=!1}return e}})(),SN=yN();function yN(){let e=new Map([[lD,["Firefox",dD]],[mD,["Edg",_D]],[oN,["Chrome",cN]],[lN,["Safari",uN]],[yD,["TBS",vD]],[ID,["XWEB",AD]],[kD&&iD,["WeChat",DD]],[PD,["QQ(Win)",MD]],[wD,["QQ(Mobile)",OD]],[ND,["QQ(Mobile X5)",OD]],[LD,["QQ(Mac)",xD]],[VD,["QQ(iPad)",UD]],[KD,["MI",zD]],[qD,["HW",QD]],[XD,["Samsung",$D]],[ZD,["OPPO",eN]],[tN,["VIVO",iN]],[hD,["EDGE",pD]],[gD,["SogouMobile",TD]],[ED,["Sogou",SD]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var vN=null,IN="";function AN(){return HC(this,null,(function*(){if(vN)return vN;if(!navigator.userAgentData||!mw(navigator.userAgentData.getHighEntropyValues))return null;try{return(vN=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!IN&&(IN="UAData: ".concat(vN.platform,"/").concat(vN.platformVersion),vN.architecture&&vN.bitness&&(IN+=" ".concat(vN.architecture,"/").concat(vN.bitness)),vN.mobile&&(IN+=" mobile"),vN.model&&(IN+=" model: ".concat(vN.model)),vN.fullVersionList&&(IN+=" ".concat(vN.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),vN}catch(PF){return null}}))}function RN(){return(null==vN?void 0:vN.model)||""}var CN=new Map([[oD,"Android"],[nD,"iOS"],[FD,"Windows"],[BD,"MacOS"],[HD,"Linux"],[jD,"ChromeOS"]]),bN=function(){return CN.get(!0)?CN.get(!0):vN?vN.platform:"unknown"},kN=()=>{let e=bN();return e+="/".concat(SN.name,"/").concat(lN?SN.version:SN.version.split(".")[0]),null!=vN&&vN.platformVersion&&(e+="/".concat(vN.platformVersion)),null!=vN&&vN.architecture&&(e+="/".concat(vN.architecture)),e};function DN(){return oD?4:iD?2:eD?3:BD?12:FD?5:HD?13:1}function NN(){return oD?"Android":iD?"iPhone":eD?"iPad":BD?"Mac":FD?"Windows":HD?"Linux":"unknown"}var wN=(e,t)=>t?"".concat(Ib,"/").concat(e,"/").concat(t):"".concat(Ib,"/").concat(e,"/index.html"),ON=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let e=null==localStorage?void 0:localStorage.getItem(bb);if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let i=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:r}}return{}};function PN(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",s="",a="";mw(Kk[t])?o=Kk[t](i):fw(Kk[t])&&(o=Kk[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=ON();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(mw(l[t])?a=l[t](i):fw(l[t])&&(a=l[t]));let d=o;return lw()&&(c&&c[t]&&(mw(c[t])?s=c[t](i):fw(c[t])&&(s=c[t])),s&&(d=n?"".concat(s,"\n请查看文档: ").concat(wN("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(wN("en",a),"\n")),d}var MN=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:n,onRetryFailed:o,onRetrySuccess:s,context:a}=e;return function(){for(var e=arguments.length,c=new Array(e),l=0;l<e;l++)c[l]=arguments[l];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,_=(e,i)=>HC(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<(mw(d)?d():d)?(h++,m=1,mw(n)&&n.call(this,h,t),p=window.setTimeout((()=>{p=-1,_(e,i)}),mw(u)?u(h):u)):(t(),mw(o)&&o.call(this,f))};mw(r)?r.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(_)}},LN=new(VC(jC(),1).default),xN=(e=>(e.ROOM_DESTROY="1",e.JOIN_START="21",e.JOIN_SCHEDULE_SUCCESS="22",e.JOIN_SIGNAL_CONNECTION_START="23",e.JOIN_SIGNAL_CONNECTION_END="24",e.JOIN_SEND_CMD="25",e.JOIN_RECEIVED_CMD_RES="26",e.JOIN_SUCCESS="27",e.JOIN_FAILED="28",e.LEAVE_START="51",e.LEAVE_SEND_CMD="52",e.LEAVE_SUCCESS="53",e.PUBLISH_START="61",e.SEND_FIRST_VIDEO_FRAME="62",e.PUBLISH_FAILED="63",e.SUBSCRIBE_START="81",e.SUBSCRIBE_SUCCESS="82",e.SUBSCRIBE_FAILED="84",e.UNSUBSCRIBE_SUCCESS="83",e.LOCAL_TRACK_CAPTURE_START="101",e.LOCAL_TRACK_CAPTURE_SUCCESS="102",e.LOCAL_TRACK_CAPTURE_FAILED="103",e.LOCAL_TRACK_PUBLISHED="104",e.LOCAL_TRACK_UNPUBLISHED="105",e.LOCAL_TRACK_REPLACED="106",e.SWITCH_DEVICE_SUCCESS="107",e.TRACK_MUTED="108",e.TRACK_UNMUTED="109",e.REMOTE_TRACK_SUBSCRIBED="110",e.REMOTE_TRACK_UNSUBSCRIBED="111",e.LOCAL_TRACK_RECAPTURE="112",e.PLAY_TRACK_START="151",e.PLAYER_STATE_CHANGED="152",e.VIDEO_LOADED_DATA="153",e.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",e.SIGNAL_CONNECTION_STATE_CHANGED="201",e.PEER_CONNECTION_STATE_CHANGED="202",e.SINGLE_CONNECTION_STAT="203",e.SPC_RECONNECTED="204",e.HEARTBEAT_REPORT="251",e.RECEIVED_PUBLISHED_USER_LIST="252",e.REMOTE_PUBLISH_STATE_CHANGED="253",e.AUDIO_LEVEL_INTERVAL="260",e.NETWORK_QUALITY="261",e.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",e.QUALITY_LIMITATION_CHANGED="263",e.LOG="264",e.SEND_SEI_MESSAGE="265",e))(xN||{}),VN=new class{constructor(){this._roomIdMap=new Map,"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:lb,env:Db.QCLOUD,browserVersion:SN.name+SN.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:i,userId:r,roomId:n}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=r,this._roomIdMap.set(r,String(n))}logSuccessEvent(e){TN||!rO.isAbleToUpload||this._configs.env===Db.QCLOUD&&this.uploadEventToKibana(MC(PC({},e),{result:"success"}))}logFailedEvent(e){if(TN||!rO.isAbleToUpload)return;let{eventType:t,code:i,error:r,userId:n}=e,o={roomId:this._roomIdMap.get(n||this._configs.userId),userId:n,eventType:t,result:"failed",code:i||(null==r?void 0:r.extraCode)||(null==r?void 0:r.code)||ZC.UNKNOWN};this._configs.env===Db.QCLOUD&&this.uploadEventToKibana(MC(PC({},o),{error:r}))}uploadEventToKibana(e){let t="stat-".concat(e.eventType,"-").concat(e.result);("delta-join"===e.eventType||"delta-leave"===e.eventType||"delta-publish"===e.eventType)&&(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}uploadEvent(e){let{log:t,userId:i,error:r}=e,n={timestamp:ob(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:lb,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+="\n".concat(r.stack))),this.sendRequest(XN(this._configs.sdkAppId,kb.LOG),n)}sendRequest(e,t){rO.isAbleToUpload?jk({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},UN=null,FN=!0;function BN(e){Tw(e)&&e!==FN&&(FN=e,rO.info("setIsNeedToSchedule ".concat(e)))}function HN(e){return HC(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:n,userSig:o,version:s,frameWorkType:a,role:c,latencyLevel:l}=e;return function*(){if(!FN&&UN)return{isCached:!0,result:UN};let e={delta:0,count:[1,1],msg:[],detail:[]};try{let d=new FormData;d.append("userId",String(t)),d.append("sdkAppId",String(i)),d.append("isStrGroupId",String(r)),d.append("groupId",String(n)),d.append("sdkVersion",s),d.append("userSig",String(o)),c&&d.append("role",String(c)),l&&d.append("latencyLevel",String(l)),a&&d.append("frameWorkType",String(a));let u=kw(),h=yield function(e,t,i){return new Promise(((r,n)=>{let o=null;bw([qN((e=>t.count[0]=e+1),(e=>{let{error:r,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[0]=r.message,o||(s>=2&&(a[0]=GN(i,Fb.MAIN,!0)),n())}))(GN(i,Fb.MAIN),e,{get timeout(){return 1e3*uw(2+t.count[0])}}),qN((e=>t.count[1]=e+1),(e=>{let{error:r,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[1]=r.message,o||(s>=2&&(a[0]=GN(i,Fb.BACKUP,!0)),n())}))(GN(i,Fb.BACKUP),e,{get timeout(){return 1e3*uw(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}(d,e,i);h.config&&(h.config.loggerDomain&&Tb(h.config.loggerDomain),Tw(h.config.scheduleCache)&&BN(!h.config.scheduleCache)),e.delta=kw()-u;let p=function(e,t,i){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let n=performance.getEntriesByType("resource"),o=GN(e,Fb.MAIN),s=GN(e,Fb.BACKUP);for(let e of n)if(e.startTime>=i&&(e.name===o||e.name===s)&&e.transferSize>0){let i=e.name===o?Fb.MAIN:Fb.BACKUP,n=Math.round(e.duration),s=Math.round(e.domainLookupStart-e.startTime),a=e.redirectStart>0?Math.round(e.redirectEnd-e.redirectStart):0,c=e.fetchStart>0?Math.round(e.domainLookupStart-e.fetchStart):0,l=Math.round(e.domainLookupEnd-e.domainLookupStart),d=Math.round(e.requestStart-e.secureConnectionStart),u=Math.round(e.secureConnectionStart-e.connectStart),h=Math.round(e.responseStart-e.requestStart),p=Math.round(e.responseEnd-e.responseStart),m=[l,d,u,h,p];VN.uploadEvent({log:"stat-schedule-net:".concat(n,"(").concat(s,"(").concat(a,"->").concat(c,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=MC(PC({},r),{totalCost:n,local:s,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(o){rO.error("getScheduleDetailCost error",o)}return r}(Number(i),t,u);return UN=h,{isCached:!1,result:h,detailCost:p}}catch(d){let e=Sw(d)?d[0]:d,t=gw(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),r=new tb({code:ZC.SCHEDULE_FAILED,extraCode:t,message:PN({key:Jk.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw rO.error(i,t),r}}()}))}document&&document.head.insertAdjacentHTML("beforeend",Object.values(Ck).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),LN.on("28",(()=>BN(!0))),LN.on("63",(()=>BN(!0))),LN.on("84",(()=>BN(!0))),LN.on("201",(e=>{"RECONNECTING"===e.state&&BN(!0)})),LN.on("202",(e=>{"RECONNECTING"===e.state&&BN(!0)}));var jN={main:"",backup:""};function WN(e){Sw(e)?(jN.main=e[0],jN.backup=e[1]):jN.main=e}function GN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Fb.MAIN,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return"https://".concat(jN[t]||KN(e,t,i),"/api/v1/config")}function JN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Fb.MAIN;return"https://".concat(jN[t]||KN(e,t),"/api/v1/trtcAutoConf")}function KN(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Fb.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return QN(e)?i===Fb.MAIN?Ck.MAIN_OVERSEA:Ck.BACKUP_OVERSEA:(t=QN(e)?r?i===Fb.MAIN?Ck.MAIN_OVERSEA_OLD:Ck.BACKUP_OVERSEA_OLD:i===Fb.MAIN?Ck.MAIN_OVERSEA:Ck.BACKUP_OVERSEA:i===Fb.MAIN?Ck.MAIN:Ck.BACKUP,t)}function zN(e,t,i){return new Promise(((r,n)=>{jk({url:e,body:t,timeout:i.timeout}).then((e=>{0===e.data.code?r(e.data.data):n({code:e.data.code,message:e.data.msg})})).catch(n)}))}var qN=(e,t)=>MN({retryFunction:zN,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var YN=function(){return new URLSearchParams(location.search).get("trtc_env")||""},QN=e=>Number(e)<14e8,XN=function(e,t){let i;i=gb||(QN(e)?Cb:Rb);let r=Math.floor(Math.random()*wC(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},$N="unknown";function ZN(){if("unknown"!==$N)return $N;let{userAgent:e,connection:t}=navigator,i=(e.match(/NetType\/\S+/)||[])[0]||"";i=i.toLowerCase().replace("nettype/",""),"3gnet"===i&&(i="3g");let r=t&&t.type&&t.type.toLowerCase(),n=t&&t.effectiveType&&t.effectiveType.toLowerCase();return"slow-2"===n&&(n="2g"),r&&($N=ew(r,n)),$N}function ew(e,t){if(Pb[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function tw(e){$N=ew(e)}function iw(){return Pb[ZN()]}function rw(e,t){for(let i of Reflect.ownKeys(t))if("constructor"!==i&&"prototype"!==i&&"name"!==i){let r=Object.getOwnPropertyDescriptor(t,i)||"";Object.defineProperty(e,i,r)}return e}function nw(e){return ow(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function ow(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function sw(e){return 4*aw(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function aw(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var cw="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},lw=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},dw=function(e){if(!e||"object"!=typeof e||"[object Object]"!=Object.prototype.toString.call(e))return!1;let t=Object.getPrototypeOf(e);if(null===t)return!0;let i=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof i&&i instanceof i&&Function.prototype.toString.call(i)===Function.prototype.toString.call(Object)};function uw(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:uw(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function hw(e){return e>8?3e4:1e3*uw(e)}function pw(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var mw=e=>"function"==typeof e,_w=e=>void 0===e,fw=e=>"string"==typeof e,gw=e=>"number"==typeof e,Tw=e=>"boolean"==typeof e,Ew=e=>"object"===pw(e),Sw=e=>"array"===pw(e),yw=e=>pw(e)==="MediaStreamTrack".toLowerCase(),vw=e=>e.isRemote,Iw=e=>"promise"===pw(e),Aw=e=>mw(e)&&e.prototype.constructor===e,Rw=e=>Aw(e)?e.prototype.constructor.name:"",Cw="undefined"!=typeof AudioWorkletNode;function bw(e){return new Promise(((t,i)=>{let r=[];e.forEach((n=>{n.then(t).catch((t=>{r.push(t),r.length===e.length&&i(r)}))}))}))}function kw(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var Dw=e=>+e<10?"0".concat(e):e,Nw=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=Dw(i[1])+Dw(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},ww=Object.prototype.hasOwnProperty;function Ow(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(dw(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(let t in e)if(ww.call(e,t))return!1;return!0}return!1}function Pw(e,t){return{userId:t,hasAudio:!!(e&Kb),hasVideo:!!(e&Wb),hasAuxiliary:!!(e&Jb),hasSmall:!!(e&Gb),audioMuted:!!(e&zb),videoMuted:!!(e&qb),audioAvailable:!(!(e&Kb)||e&zb),videoAvailable:!(!(e&Wb)||e&qb)}}function Mw(e){let t={urls:"turn:".concat(e.url)};return!_w(e.username)&&!_w(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",_w(e.credentialType)||(t.credentialType=e.credentialType)),t}function Lw(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!fw(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 xw=function(e,t,i,r){if(!Ew(e)||!Ew(t))return 0;let n,o=0,s=Object.keys(t);for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(_w(t[n])||i&&i.includes(n)))if(Ew(e[n])&&Ew(t[n]))o+=xw(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=Vw(t[n]),o+=1)}return o};function Vw(e){if(Sw(e)){let t=[];return e.forEach(((e,i)=>{t[i]=Vw(e)})),t}if(Ew(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=Vw(e[i])})),t}return e}var Uw=e=>{let t=[];if(Sw(e))t=[...e];else if(fw(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},Fw=e=>fw(e)?document.getElementById(e):e,Bw=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),Hw=()=>Bw.format(new Date);function jw(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(Sw(e))return"[".concat(e.map((e=>jw(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!dw(e)||!Sw(i)&&!Sw(r))return JSON.stringify(e);let t={},n=new Set(i),o=new Set(r);return Object.keys(e).forEach((s=>{(0===o.size&&n.has(s)||0===n.size&&!o.has(s))&&(t[s]=dw(e[s])||Sw(e[s])?JSON.parse(jw(e[s],{keysToExclude:r,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(uk){return"{}"}}function Ww(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=[];return Object.keys(e).forEach((r=>{t===e[r]&&i.push(r)})),jw(e,{keysToInclude:i})}function Gw(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Jw=()=>{var e,t,i,r;return null!=(e=window.screen)&&e.orientation?!(null==(r=null==(i=null==(t=window.screen)?void 0:t.orientation)?void 0:i.type)||!r.includes("portrait")):0===window.orientation||180===window.orientation},Kw=e=>HC(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(fw(e))r=new Image,r.crossOrigin="anonymous",r.src=e;else if(r=e,r.complete)return void t(r);r.onload=()=>t(r),r.onerror=i}))})),zw=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},qw=e=>(Object.keys(e).forEach((t=>{gw(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(dw(e[t])||Sw(e[t]))&&qw(e[t])})),e);function Yw(e){return new Promise((t=>setTimeout(t,e)))}var Qw=(e,t)=>{let i=null;return function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return i||(i=e.apply(t||this,n),i.finally((()=>i=null)),i)}},Xw=Object.prototype.hasOwnProperty,$w=e=>void 0===e;function Zw(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(function(e){if(!e||"object"!=typeof e||"[object Object]"!=Object.prototype.toString.call(e))return!1;let t=Object.getPrototypeOf(e);if(null===t)return!0;let i=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof i&&i instanceof i&&Function.prototype.toString.call(i)===Function.prototype.toString.call(Object)}(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(let t in e)if(Xw.call(e,t))return!1;return!0}return!1}var eO=class{constructor(e){FC(this,"userId"),FC(this,"remoteUserId"),FC(this,"id"),FC(this,"sdkAppId"),FC(this,"type"),FC(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal="boolean"!=typeof e.isLocal||e.isLocal,this.type=this.isLocal?"":e.type}createChild(e){return Object.setPrototypeOf(e,this)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId;t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(this.id).concat(i?"|".concat(i):"","]")),rO.log(e,t,$w(this.userId)||Zw(this.userId),this.userId,this.sdkAppId)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}},tO=xN,iO=!(nD||oD||sN),rO=new class{constructor(){FC(this,"_isEnableUploadLog",!0),FC(this,"_localJoinedUser",new Map),FC(this,"_queue",[]),FC(this,"_timeoutId",-1),FC(this,"_logLevel",1),FC(this,"_logLevelToUpload",2),!mb&&!_b&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){LN.on(tO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&Nb[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),LN.on(tO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),LN.once(tO.JOIN_FAILED,(()=>{this.startUpload()})),LN.on(tO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.deleteJoinedUser(t.userId)}))}startUpload(){-1===this._timeoutId&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch((()=>{})),this._timeoutId=window.setTimeout((()=>this.uploadInterval()),2e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&0===this._localJoinedUser.size)return e;let t=0;for(;t<this._queue.length&&50!==t;t++){let i=this._queue[t];if(i.forAllJoinedClients)this._localJoinedUser.forEach((t=>{let{userId:r,sdkAppId:n}=t;e.map.has(r)?e.map.get(r).logs.push(i):e.map.set(r,{userId:r,sdkAppId:n,logs:[i]})}));else if(fw(i.userId)&&gw(i.sdkAppId)){let{userId:t,sdkAppId:r}=i;e.map.has(t)?e.map.get(t).logs.push(i):e.map.set(t,{userId:t,sdkAppId:r,logs:[i]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e}upload(){return HC(this,null,(function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;e<t.length;e++){let{userId:i,sdkAppId:r,logs:n}=t[e];yield this.uploadLogWithRetry(JSON.stringify({timestamp:ob(),sdkAppId:String(r),userId:i,version:lb,log:n.map((e=>e.log)).join("\n")}),r),n.forEach((e=>e.uploaded=!0))}}catch(hb){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return MN({retryFunction:()=>jk({url:XN(t,kb.LOG),body:e,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;t.setTime(nb());let i=String(t.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),"[".concat(t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(i,"] <").concat(Nb[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){_w(Nb[e])||(this._logLevel!==e&&this.info("setLogLevel",e),this._logLevel=e)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(e){if(fw(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(ub){return""}}log(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;var o;t.unshift(this.getPrefix(e));let s={log:t.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:e,userId:r,sdkAppId:n,forAllJoinedClients:i};if(LN.emit(tO.LOG,{log:s}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(s),e<this._logLevel)return;let a=(null==(o=Nb[e])?void 0:o.toLowerCase())||"info";iO?console[a]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...t):console[a](...t)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}createLogger(e){return new eO(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Nb[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}},nO=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)}))},oO=new class{constructor(){FC(this,"_prefix","TRTC"),FC(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){EN()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix)){let t=localStorage.getItem(e);if(!t)return!1;let i=JSON.parse(t);if(i&&i.expiresIn<Date.now())return!0}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(EN())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(vP){rO.warn(vP)}}getItem(e){if(!EN())return null;try{let t=localStorage.getItem(this.getRealKey(e));if(!t)return null;let i=JSON.parse(t);return i&&i.expiresIn>=Date.now()?i.value:null}catch(ub){rO.warn(ub)}}setItem(e,t){if(EN())try{let i={expiresIn:Date.now()+Mb,value:t};this._queue.set(this.getRealKey(e),i)}catch(uk){rO.warn(uk)}}deleteItem(e){if(!EN())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(ub){return rO.warn(ub),!1}}clear(){if(EN())try{localStorage.clear()}catch(vP){rO.warn(vP)}}},sO={};xC(sO,{HTTPS_API:()=>IO,IS_GET_CAPABILITIES_SUPPORTED:()=>BO,IS_GET_SETTINGS_SUPPORTED:()=>FO,IS_INSERTABLE_STREAM_SUPPORTED:()=>HO,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>jO,IS_SEI_SUPPORTED:()=>WO,IS_SPC_SUPPORTED:()=>LO,basis:()=>YO,checkSystemRequirementsInternal:()=>EO,decodeSupportStatus:()=>TO,encodeSupportStatus:()=>gO,getBrowserInfo:()=>dO,getDisplayResolution:()=>RO,isAddTransceiverSupported:()=>MO,isBrowserSupported:()=>uO,isGetReceiversSupported:()=>wO,isGetSendersSupported:()=>OO,isGetTransceiversSupported:()=>PO,isGetUserMediaSupported:()=>CO,isMediaDevicesSupported:()=>pO,isMediaSessionSupported:()=>KO,isMediaStreamTrackProcessorSupported:()=>fO,isReplaceTrackSupported:()=>VO,isSIMDSupported:()=>qO,isScreenCaptureApiAvailable:()=>yO,isSelectedCandidatePair:()=>AO,isSetParametersSupported:()=>UO,isSmallStreamAPISupported:()=>kO,isSmallStreamSupported:()=>DO,isStopTransceiverSupported:()=>xO,isTRTCSupported:()=>SO,isUnifiedPlanDefault:()=>NO,isUsedInHttpProtocol:()=>_O,isWebAudioSupported:()=>bO,isWebCodecSupported:()=>JO,isWebCodecsSupported:()=>hO,isWebRTCSupported:()=>GO,isWebTransportSupported:()=>zO});var aO=VC(KC(),1),cO={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},lO=new Map([[lD,["Firefox",dD]],[mD,["Edg",_D]],[oN,["Chrome",cN]],[lN,["Safari",uN]],[yD,["TBS",vD]],[ID,["XWEB",AD]],[kD&&iD,["WeChat",DD]],[PD,["QQ(Win)",MD]],[wD,["QQ(Mobile)",OD]],[ND,["QQ(Mobile X5)",OD]],[LD,["QQ(Mac)",xD]],[VD,["QQ(iPad)",UD]],[KD,["MI",zD]],[qD,["HW",QD]],[XD,["Samsung",$D]],[ZD,["OPPO",eN]],[tN,["VIVO",iN]],[hD,["EDGE",pD]],[gD,["SogouMobile",TD]],[ED,["Sogou",SD]]]);function dO(){let e=lO.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var uO=function(){return!(GD||hD||mD&&fD<80||lD&&uD<56)},hO=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},pO=function(){if(!navigator.mediaDevices)return _O()||rO.error(Kk.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},mO=!1;function _O(){return"http:"===location.protocol&&!TN&&(mO||rO.error(PN({key:Jk.NOT_SUPPORTED_HTTP})),mO=!0,!0)}var fO=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},gO=function(){return HC(this,null,(function*(){if(cO.detail.isH264EncodeSupported&&cO.detail.isVp8EncodeSupported)return{isH264EncodeSupported:cO.detail.isH264EncodeSupported,isVp8EncodeSupported:cO.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection,n=document.createElement(Fb.CANVAS);n.getContext("2d");let o=n.captureStream(0);return r.addTrack(o.getVideoTracks()[0],o),e=yield r.createOffer(),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),cO.detail.isH264EncodeSupported=t,cO.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:cO.detail.isH264EncodeSupported,isVp8EncodeSupported:cO.detail.isVp8EncodeSupported}}catch(uk){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},TO=function(){return HC(this,null,(function*(){if(cO.detail.isH264DecodeSupported&&cO.detail.isVp8DecodeSupported)return{isH264DecodeSupported:cO.detail.isH264DecodeSupported,isVp8DecodeSupported:cO.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection;return e=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch(uk){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},EO=Qw((()=>HC(void 0,null,(function*(){if(cO.result&&cO.detail.isH264EncodeSupported&&cO.detail.isVp8EncodeSupported&&cO.detail.isH264DecodeSupported&&cO.detail.isVp8DecodeSupported)return cO;let e=uO(),t=GO(),i=hO(),r=pO(),{isH264EncodeSupported:n,isVp8EncodeSupported:o}=yield gO(),{isH264DecodeSupported:s,isVp8DecodeSupported:a}=yield TO();if(!n||!o){let e=yield gO();rO.warn("detect encode again h264:".concat(n," vp8:").concat(o," result: ").concat(JSON.stringify(e))),n=e.isH264EncodeSupported,o=e.isVp8EncodeSupported}if(n&&s&&(ZD||tN||hN)&&!yD&&rN()<79){let{encode:e,decode:t}=yield function(){return HC(this,null,(function*(){return vO||(vO=new Promise((e=>HC(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{rO.warn("detectH264Supported start");let r=document.createElement("canvas"),n=r.getContext("2d");r.width=320,r.height=240;let o=setInterval((()=>{n.fillText("test",Math.floor(320*Math.random()),Math.floor(240*Math.random()))}),66),s=-1,a=-1;i=()=>{clearInterval(s),clearInterval(o),clearTimeout(a),l.close(),d.close(),c.getTracks().forEach((e=>e.stop()))},a=setTimeout((()=>{i(),e(t)}),2e3);let c=r.captureStream(),l=new RTCPeerConnection({}),d=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",(e=>d.addIceCandidate(e.candidate))),d.addEventListener("icecandidate",(e=>l.addIceCandidate(e.candidate))),l.addTrack(c.getVideoTracks()[0],c);let u=yield l.createOffer();yield l.setLocalDescription(u),yield d.setRemoteDescription(u);let h=yield d.createAnswer(),p=aO.default.parse(h.sdp),m=p.media[0].rtp.findIndex((e=>"H264"===e.codec));p.media[0].rtp=[p.media[0].rtp[m]],p.media[0].fmtp=p.media[0].fmtp.filter((e=>e.payload===p.media[0].rtp[0].payload)),p.media[0].rtcpFb&&(p.media[0].rtcpFb=p.media[0].rtcpFb.filter((e=>e.payload===p.media[0].rtp[0].payload))),h.sdp=aO.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval((()=>HC(this,null,(function*(){t.encode&&t.decode&&(i(),e(t));let r=yield l.getSenders()[0].getStats(),n=yield d.getReceivers()[0].getStats();t.encode||r.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===Fb.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===Fb.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(r){i(),rO.warn(r),e(t)}})))).then((e=>((!e.encode||!e.decode)&&rO.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(IN)),e))),vO)}))}();n=e,s=t}return cO.result=e&&t&&r&&(n||o)&&(s||a),cO.detail.isBrowserSupported=e,cO.detail.isWebRTCSupported=t,cO.detail.isWebCodecsSupported=i,cO.detail.isMediaDevicesSupported=r,cO.detail.isScreenShareSupported=yO(),cO.detail.isSmallStreamSupported=DO(),cO.detail.isH264EncodeSupported=n,cO.detail.isVp8EncodeSupported=o,cO.detail.isH264DecodeSupported=s,cO.detail.isVp8DecodeSupported=a,cO.result||rO.error("".concat(navigator.userAgent," ").concat(Ww(cO.detail,!1))),oO.setItem(QO,{ua:navigator.userAgent,checkResult:cO}),cO})))),SO=function(){return cO.result},yO=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},vO=null;var IO=(e,t,i)=>{"http:"===location.protocol&&!TN&&(e[t]=()=>{throw new tb({code:ZC.INVALID_OPERATION,message:Kk.NOT_SUPPORTED_HTTP})})},AO=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(Tw(e.selected)&&!e.selected)};function RO(){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 CO(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function bO(){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 kO(){return"captureStream"in HTMLCanvasElement.prototype}function DO(){return!(kD||nD||aN&&aN<63)&&!(!uO()||!kO())}var NO=function(){if(_w(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:gk}),e.addTransceiver(Fb.AUDIO),t=!0}catch(ub){}return null==e||e.close(),t};function wO(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function OO(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function PO(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function MO(){return 11!==mN&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var LO=!(!MO()||nN&&aN<86);function xO(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function VO(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function UO(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&OO()}var FO=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,BO=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,HO="createEncodedStreams"in window.RTCRtpSender.prototype&&rN()>=86,jO="RTCRtpScriptTransform"in window,WO="RTCRtpSender"in window&&(HO||jO),GO=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function JO(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return _w(window.AudioDecoder)||(e.AudioDecoder=!0),_w(window.AudioEncoder)||(e.AudioEncoder=!0),_w(window.VideoDecoder)||(e.VideoDecoder=!0),_w(window.VideoEncoder)||(e.VideoEncoder=!0),_w(window.ImageDecoder)||(e.ImageDecoder=!0),e}function KO(){return"mediaSession"in navigator&&!_w(navigator.mediaSession.setActionHandler)}function zO(){return!_w(window.WebTransport)}function qO(){return"undefined"==typeof WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function YO(){let e={browser:"".concat(SN.name,"/").concat(SN.version),os:bN(),displayResolution:RO(),isScreenShareSupported:yO(),isWebRTCSupported:GO(),isGetUserMediaSupported:CO(),isWebAudioSupported:bO(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:JO(),isMediaSessionSupported:KO(),isWebTransportSupported:zO()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var QO="checkResult";!function(){_O();let e=oO.getItem(QO);e&&e.ua===navigator.userAgent&&(cO=e.checkResult),EO()}();var XO=VC(jC(),1),$O=Symbol("instance"),ZO=Symbol("cacheResult"),eP=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,oP.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},tP=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var iP=new Map;function rP(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,n,o)=>{let s=i.action||n;if(!i.context){let i=iP.get(r)||[];iP.has(r)||iP.set(r,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let r=this;for(var n=arguments.length,o=new Array(n),c=0;c<n;c++)o[c]=arguments[c];if(i.context&&(r=sP.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return i.sync?r[ZO]:Promise.resolve(r[ZO]);r.state instanceof eP&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof eP&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new tP(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e.join("|")))):e!==r.state&&(l=new tP(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e)));let d=e=>{if(i.fail&&i.fail.call(this,e),i.sync){if(i.ignoreError)return e;throw e}return i.ignoreError?Promise.resolve(e):Promise.reject(e)};if(l)return d(l);let u=r.state,h=new eP(u,t,s);oP.call(r,h);let p=e=>{var n;return r[ZO]=e,h.aborted||(oP.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[ZO])),e},m=e=>{let t=e instanceof Error?e.message:String(e);return oP.call(r,u,e),d(new tP(r._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(p).catch(m):i.sync?p(e):Promise.resolve(p(e))}catch(_){return m(_)}}}}var nP="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 oP(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(sP.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var sP=class extends XO.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=sP.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let r=i[$O];r?this.name=r.name+"-"+r.count++:i[$O]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=iP.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);iP.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?r.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:o})})):n.push({to:i,action:o})})),r.forEach((e=>{let{from:t,to:r,action:n}=e;o.add(t),o.add(r),o.add(n+"ing"),i.add("".concat(t," --\x3e ").concat(n,"ing : ").concat(n)),i.add("".concat(n,"ing --\x3e ").concat(r," : ").concat(n," 🟢")),i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🔴"))})),n.forEach((e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=sP.instances.get(e),t||sP.instances.set(e,t=new sP(e,void 0,Object.create(sP.prototype)))):(t=sP.instances2.get(e),t||sP.instances2.set(e,t=new sP(e.constructor.name,void 0,Object.create(sP.prototype)))),t}static getState(e){var t;return null===(t=sP.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};nP(sP.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){oP.call(this,e)}};sP.STATECHANGED="stateChanged",sP.UPDATEAFSM="updateAFSM",sP.INIT="[*]",sP.ON="on",sP.OFF="off",sP.instances=new Map,sP.instances2=new WeakMap;var aP=(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)},cP=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},lP=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),dP=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Bk,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=PC(e===Fk?{delay:2e3,count:0,backgroundTask:!0}:e===Vk?{delay:1e4,count:0}:e===Uk?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),Ew(t)&&(i=PC(PC({},i),t)),mw(e)&&(t=e,e=Bk);let r=PC({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i);return this.taskMap.set(r.taskID,r),this[e](r),r.taskID}static interval(e){return e.intervalID=setInterval((()=>{e.callback(),e.loopCount+=1,this.isBreakLoop(e)}),e.delay)}static intervalInWorker(e){e.delay=(1e3/e.fps).toFixed(2);let t=new Worker(URL.createObjectURL(new Blob(["\n let timerID = null;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timerID = setInterval(() => {\n self.postMessage('tick');\n }, ".concat(e.delay,");\n } else if (e.data === 'stop') {\n clearInterval(timerID);\n }\n };\n ")],{type:"application/javascript"})));t.onmessage=i=>{"tick"===i.data&&(e.callback(),e.loopCount+=1,this.isBreakLoop(e)&&t.postMessage("stop"))},e.worker=t,t.postMessage("start")}static timeout(e){let t=()=>{if(e.callback(),e.loopCount+=1,!this.isBreakLoop(e))return e.timeoutID=setTimeout(t,e.delay)};return e.timeoutID=setTimeout(t,e.delay)}static ric(e){let t,i=kw(),r=()=>{if(t=kw()-i,t>=e.delay&&(i=kw()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=aP(r,{timeout:e.delay})};return e.ricID=aP(r,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=kw(),r=()=>document.hidden&&e.backgroundTask?(t=kw()-i,i=kw(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(r,e.delay-Math.floor(t%e.delay))):(t=kw()-i,t>=e.delay&&(i=kw()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),this.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(r));if(e.rafID=requestAnimationFrame(r),e.backgroundTask){let t=()=>{if(document.hidden){let t=kw()-i;t>=e.delay?r():e.timeoutID=setTimeout(r,e.delay-t)}};document.addEventListener("visibilitychange",t),e.onVisibilitychange=t,document.hidden&&t()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:t,timeoutID:i,rafID:r,ricID:n,onVisibilitychange:o,worker:s}=this.taskMap.get(e);return s&&s.terminate(),t&&clearInterval(t),i&&clearTimeout(i),r&&lP(r),n&&cP(n),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.taskMap.has(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};dP.taskMap=new Map,dP.currentTaskID=1;var uP=dP;Fb.SEI_MESSAGE;var hP={LOADED_DATA:Fb.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},pP={};xC(pP,{create:()=>_P,remove:()=>fP});var mP=new WeakMap;function _P(e,t){mP.has(e)||mP.set(e,[]);let i=mP.get(e),r={add:(e,n)=>("addEventListener"in t?(i.push(t.removeEventListener.bind(t,e,n)),t.addEventListener(e,n)):(i.push(t.off.bind(t,e,n)),t.on(e,n)),r)};return r}function fP(e){let t=mP.get(e);t&&(t.forEach((e=>e())),mP.delete(e))}var gP=new WeakMap;function TP(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,s){let a=MN({retryFunction:s.value,settings:t,onError(t){let{error:r,retry:n,reject:s,retryFuncArgs:a}=t;var c;i?i.call(this,r,(()=>{var t;null!=(t=gP.get(e))&&t.has(o)?n():s(r)}),s,a):null!=(c=gP.get(e))&&c.has(o)?n():s(r)},onRetrying(t,i){var n;mw(r)&&r.call(this,t,i),null!=(n=gP.get(e))&&n.has(o)&&(gP.get(e).get(o).stopRetry=i)},onRetryFailed:n});return s.value=function(){let t=gP.get(e);for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return t?t.set(o,{args:r}):gP.set(e,new Map([[o,{args:r}]])),a.apply(this,r).finally((()=>{var t;return null==(t=gP.get(e))?void 0:t.delete(o)}))},s}}function EP(e){let{fnName:t,callback:i,validateArgs:r=!0}=e;return function(e,n,o){let s=o.value;return o.value=function(){for(var n,o,a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(null!=(n=gP.get(e))&&n.has(t)){let{stopRetry:n,args:s}=gP.get(e).get(t),a=!0;if(r)for(let e of s)if(!c.find((t=>t===e))){a=!1;break}a&&(i&&i.apply(this,c),n&&n(),null==(o=gP.get(e))||o.delete(t))}return s.apply(this,c)},o}}var SP,yP,vP,IP=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.countMap=new Map,this.distributionMap=new Map,this.log=rO.createLogger({id:"kv"}),e&&(LN.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===Fb.AUDIO?kP.START_MICROPHONE:DP.START_CAMERA,cost:i})})),LN.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===Fb.AUDIO?kP.START_MICROPHONE:DP.START_CAMERA,error:i})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:zw(this.version||lb),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,uint32_count:i}})),stats_distribution:[...this.distributionMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,distribution_items:[...i.entries()].map((e=>{let[t,i]=e;return{uint32_item_key:t,uint32_item_value:i}}))}}))};return this.countMap.clear(),this.distributionMap.clear(),e}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){let t=+String(e).slice(-3);return t>=700&&t<799}isErrorCodeKey(e){let t=+String(e).slice(-3);return t>=600&&t<699}isCountKey(e){let t=+String(e).slice(-3);return t>=0&&t<599}isNumberKey(e){let t=+String(e).slice(-3);return t>=800&&t<899}addCount(e){let{key:t,useUV:i=!1}=e;this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}addEnum(e){let{key:t,value:i,useUV:r=!0}=e;var n;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=(null==(n=this.distributionMap)?void 0:n.get(t))||new Map;o.set(i,(o.get(i)||0)+1),this.distributionMap.set(t,o)}addNumber(e){let{key:t,value:i,split:r=100,useUV:n=!1}=e;var o;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(n&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=(null==(o=this.distributionMap)?void 0:o.get(t))||new Map,a=0;if(gw(r))a=Math.floor(i/r);else for(let c=r.length-1;c>0;c--)if(i>r[c]){a=c;break}s.set(a,(s.get(a)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent(e){let{key:t,cost:i,timeKey:r,split:n}=e;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),i)){let e=+String(t).slice(-3);e<800&&e>=700?this.addNumber({key:r||t+100,value:i,split:n}):r||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:i}=e;if(!t)return;let r=ZC.UNKNOWN;i&&(gw(i)?r=i:(!_w(i.extraCode)||!_w(i.code))&&(r=i.extraCode||i.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:r,useUV:!1})}},AP=((yP=AP||{})[yP.enterRoom=500700]="enterRoom",yP[yP.exitRoom=500701]="exitRoom",yP[yP.switchRole=500702]="switchRole",yP[yP.destroy=500703]="destroy",yP[yP.startLocalAudio=500704]="startLocalAudio",yP[yP.updateLocalAudio=500705]="updateLocalAudio",yP[yP.stopLocalAudio=500706]="stopLocalAudio",yP[yP.startLocalVideo=500707]="startLocalVideo",yP[yP.updateLocalVideo=500708]="updateLocalVideo",yP[yP.stopLocalVideo=500709]="stopLocalVideo",yP[yP.startScreenShare=500710]="startScreenShare",yP[yP.updateScreenShare=500711]="updateScreenShare",yP[yP.stopScreenShare=500712]="stopScreenShare",yP[yP.startRemoteVideo=500713]="startRemoteVideo",yP[yP.updateRemoteVideo=500714]="updateRemoteVideo",yP[yP.stopRemoteVideo=500715]="stopRemoteVideo",yP[yP.muteRemoteAudio=500716]="muteRemoteAudio",yP[yP.setRemoteAudioVolume=500717]="setRemoteAudioVolume",yP[yP.use=500718]="use",yP[yP.sendSEIMessage=5e5]="sendSEIMessage",yP[yP.sendCustomMessage=500001]="sendCustomMessage",yP),RP=((SP=RP||{})[SP.AudioMixer=550700]="AudioMixer",SP[SP.AIDenoiser=551700]="AIDenoiser",SP[SP.VirtualBackground=570700]="VirtualBackground",SP[SP.Beauty=571700]="Beauty",SP[SP.Watermark=572700]="Watermark",SP[SP.BasicBeauty=574700]="BasicBeauty",SP[SP.CDNStreaming=590700]="CDNStreaming",SP[SP.DeviceDetector=591700]="DeviceDetector",SP[SP.Debug=592700]="Debug",SP),CP=(e=>(e[e.AudioMixer=550701]="AudioMixer",e[e.AIDenoiser=551701]="AIDenoiser",e[e.VirtualBackground=570701]="VirtualBackground",e[e.Beauty=571701]="Beauty",e[e.Watermark=572701]="Watermark",e[e.BasicBeauty=574701]="BasicBeauty",e[e.CDNStreaming=590701]="CDNStreaming",e[e.DeviceDetector=591701]="DeviceDetector",e[e.Debug=592701]="Debug",e))(CP||{}),bP=(e=>(e[e.AudioMixer=550702]="AudioMixer",e[e.AIDenoiser=551702]="AIDenoiser",e[e.VirtualBackground=570702]="VirtualBackground",e[e.Beauty=571702]="Beauty",e[e.Watermark=572702]="Watermark",e[e.BasicBeauty=574702]="BasicBeauty",e[e.CDNStreaming=590702]="CDNStreaming",e[e.DeviceDetector=591702]="DeviceDetector",e[e.Debug=592702]="Debug",e))(bP||{}),kP=(e=>(e[e.START_MICROPHONE=501700]="START_MICROPHONE",e[e.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",e[e.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",e))(kP||{}),DP=((vP=DP||{})[vP.START_CAMERA=511700]="START_CAMERA",vP),NP=new IP(!0),wP=new IP(!1),OP=NP,PP=class extends sP{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,FC(this,"id"),FC(this,"element",null),FC(this,"track"),FC(this,"url"),FC(this,"attr"),FC(this,"muted"),FC(this,"_log"),FC(this,"_pausedRetryCount"),FC(this,"_isElementPlayingFired",!1),FC(this,"_interval"),FC(this,"_delayDestroyTimeoutId",0),FC(this,"_isReplayByRecreateMediaStreamIng",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Dk,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){var e;return"PLAYING"===this._state&&!1===(null==(e=this.element)?void 0:e.paused)}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,null!==e&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return HC(this,null,(function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield this.element.play()}catch(ub){let t=PN({key:Jk.PLAY_FAILED,data:{media:this.kind,error:ub}});if(this.track&&!this.track.muted&&this._log.warn(ub),t.includes("NotAllowedError"))throw new tb({code:ZC.PLAY_NOT_ALLOWED,message:t})}}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this._isElementPlayingFired=!1,this.unbindEvents(),e>0?this._delayDestroyTimeoutId||(this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout((()=>this.destroyElement()),3*e)):this.destroyElement(),this.handleStopped(Fb.ENDED),this._interval>0&&uP.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():fN?this.replay():this.play().catch((()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch((()=>{}))}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return _P(this.element,this.element).add(Fb.PLAYING,e).add(Fb.ENDED,e).add(Fb.PAUSE,e).add(Fb.ERROR,e).add(Fb.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==pP||pP.create(this.track,this.track).add(Fb.ENDED,e).add(Fb.MUTE,e).add(Fb.UNMUTE,e),this.track.readyState===Fb.ENDED&&this.handleTrackEvent({type:Fb.ENDED}),this.track.muted&&this.handleTrackEvent({type:Fb.MUTE})}}bindAutoPlayEvent(){LN.on(tO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&fP(this.track)}unbindEvents(){this.element&&fP(this.element),this.unbindTrackEvents(),LN.off(tO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case Fb.PLAYING:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(Fb.PLAYING),this._interval&&(uP.clearTask(this._interval),this._interval=-1);break;case Fb.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(Fb.ENDED);break;case Fb.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(Fb.PAUSE),nD&&(this._interval=uP.run(Bk,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case Fb.ERROR:if(this.element&&this.element.error){this.handlePaused(Fb.ERROR);let{code:e,message:t}=this.element.error;this._log.error("".concat(this.kind," ").concat(this._log.isLocal?"local":"remote"," MediaError code: ").concat(e," message: ").concat(t," userAgent: ").concat(navigator.userAgent)),VN.uploadEvent({log:"stat-".concat(this.kind,"-").concat(pk.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),this.replayByRecreateMediaStream()}break;case Fb.LOADEDDATA:this.kind===Fb.VIDEO&&this.emit(hP.LOADED_DATA)}}replayByRecreateMediaStream(){if(!this._isReplayByRecreateMediaStreamIng)return this._isReplayByRecreateMediaStreamIng=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),VN.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),OP.addSuccessEvent({key:this.kind===Fb.AUDIO?506700:516700})})).catch((()=>{var e,t;this._log.error("replayByRecreateMediaStream failed"),VN.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),OP.addFailedEvent({key:this.kind===Fb.AUDIO?506700:516700,error:null==(e=this.element)?void 0:e.error}),null!=(t=this.element)&&t.error&&this.emit(hP.ERROR,this.element.error)})).finally((()=>{this._isReplayByRecreateMediaStreamIng=!1}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,i)=>{Yw(e).then((()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var e,t,r;this._log.warn("element onerror ".concat(null==(t=null==(e=this.element)?void 0:e.error)?void 0:t.code," fired after recreated mediaStream")),i(null==(r=this.element)?void 0:r.error)}),Yw(5e3).then((()=>{var e,r;(!this.isPlaying||(null==(e=this.element)?void 0:e.error))&&i(null==(r=this.element)?void 0:r.error),t()}))}))})).finally((()=>{this.element&&(this.element.onerror=null)}))}handleTrackEvent(e){switch(e.type){case Fb.ENDED:this.handleStopped(Fb.ENDED);break;case Fb.MUTE:this.handlePaused(Fb.MUTE);break;case Fb.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(Fb.UNMUTE)}}handlePlaying(e){this.emit(hP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(hP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(hP.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};UC([TP({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],PP.prototype,"doReplayByRecreateMediaStream",1),UC([rP([],"PLAYING",{sync:!0})],PP.prototype,"handlePlaying",1),UC([rP("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],PP.prototype,"handlePaused",1),UC([rP([],"STOPPED",{sync:!0})],PP.prototype,"handleStopped",1);var MP="trtc_autoplay",LP="".concat(MP,"_mask"),xP="".concat(MP,"_wrapper"),VP="".concat(MP,"_header"),UP="".concat(MP,"_content"),FP="".concat(MP,"_action_wrapper"),BP="".concat(MP,"_question"),HP="".concat(MP,"_collapse"),jP="".concat(MP,"_action_confirm"),WP="".concat(MP,"_detail"),GP="#2473E8",JP="dialog",KP="".concat(JP,"-show"),zP="".concat(JP,"-1"),qP="".concat(JP,"-2"),YP=!1,QP=()=>!!document.querySelector(".".concat(xP)),XP="".concat(Ib,"/").concat(lw()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),$P="<br><a href='".concat(XP,"' target='_blank'>").concat(lw()?"其他方案?":"Any other solution?","</a>"),ZP="".concat(lw()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat($P):"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($P)),eM=class{constructor(){if(FC(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),FC(this,"_dialogNode",null),FC(this,"_bodyPosition",""),FC(this,"_showDetail",!1),FC(this,"_isCollapseClicked",!1),FC(this,"_isQuestionClicked",!1),lw()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!YP){let e=document.createElement("style");e.innerHTML=".".concat(LP,"{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(LP," div:not(.").concat(FP,"){display:block !important;}.").concat(xP,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(xP," a{color:").concat(GP,";}.").concat(VP,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(UP,"{margin:8px 0;}.").concat(FP,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(HP,"{margin-right:auto;cursor:pointer}.").concat(BP,"{height:100%;line-height:16px;cursor:pointer;}.").concat(jP,"{margin-left:8px;color:#fff;background:").concat(GP,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(jP,":hover{opacity:0.9;}.").concat(HP,",.").concat(jP,",.").concat(UP,",.").concat(BP,"{font-size:14px;}@media screen and (max-width:750px){.").concat(xP,"{width:80vw;}}"),document.head.appendChild(e),YP=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(LP,"\"><div class='").concat(xP,"'><div class='").concat(VP,"'>").concat(location.host,"</div><div class='").concat(UP,"'>").concat(this.content,"</div><div class='").concat(WP,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(ZP,"</div><div class='").concat(FP,"'></div></div></div>").trim();let t=document.createElement("button");t.className=jP,t.innerText=lw()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=BP,i.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>\n <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>\n <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>\n </svg>\n ',i.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=HP,r.innerText="".concat(lw()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(FP));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){QP()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(xP)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",rO.info("show autoplay dialog"),VN.uploadEvent({log:KP}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){rO.warn("confirm clicked, try resume stream"),LN.emit(tO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(WP));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||VN.uploadEvent({log:zP}),this._isCollapseClicked=!0}onQuestionClick(){window.open(XP,"_blank"),this._isQuestionClicked||VN.uploadEvent({log:qP}),this._isQuestionClicked=!0}},tM=class extends PP{constructor(e){super(e,Fb.VIDEO),FC(this,"viewMirror",!1),FC(this,"objectFit"),FC(this,"container"),FC(this,"canvas"),this.container=e.container,this.canvas=e.canvas,_w(e.viewMirror)||(this.viewMirror=e.viewMirror),_w(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var e;let t=document.createElement(Fb.VIDEO);this.track&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(Fb.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(Fb.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){var t;super.handleElementEvent(e);let i=e.type;if(i===Fb.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id)),this._pausedRetryCount>0&&!QP()&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--)),this.viewMirror&&this.element){let e=this.element.style.transform;i===Fb.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):i===Fb.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}}setCanvas(e){var t,i;this.canvas!==e&&(null==(t=this.canvas)||t.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e,e&&(null==(i=this.container)||i.appendChild(e)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(t,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;super.stop(e),null==(t=this.canvas)||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(hP.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}};function iM(e,t){return HC(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),rO.info("worklet addModule success")}catch(ub){throw rO.info("worklet addModule catch error. ".concat(ub.message)),ub}}))}"undefined"!=typeof window&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var rM=new window.AudioContext({sampleRate:48e3}),nM=()=>{"suspended"===rM.state?(rM.resume(),document.addEventListener("click",nM)):"interrupted"===rM.state?rM.resume():document.removeEventListener("click",nM)};document.addEventListener("click",nM),rM.onstatechange=()=>{rO.info("context state: ".concat(rM.state)),nM()};var oM=e=>rM,sM=class{constructor(){this.pre=new Set,this.next=new Set,this.connectedNodes=new Set,this._channelCount=1}get channelCount(){return this._channelCount}set channelCount(e){this._channelCount=e,this.node&&(this.node.channelCount=e),this.next.forEach((t=>t.channelCount=e))}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&(null==(e=this.context)||e.reduceMixWeight()),delete this.context}setNode(e){var t;if(!this.node)try{null==(t=this.context)||t.addMixWeight(),this.node=e,this.node.channelCountMode="explicit",this.node.channelCount=this._channelCount,this.preNodeReconnect(),this.reconnect(),OP.addSuccessEvent({key:502701})}catch(uk){rO.error(uk),OP.addFailedEvent({key:502701,error:uk})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),OP.addSuccessEvent({key:502702})}catch(ub){rO.error(ub),OP.addFailedEvent({key:502702,error:ub})}}preNodeReconnect(){this.pre.forEach((e=>{e.node?e.reconnect():e.preNodeReconnect()}))}connectNext(e){this.next.forEach((t=>e._connect(t.node)||t.connectNext(e)))}_connect(e){return!(!this.node||!e)&&(this.node.connect(e),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach((e=>{var t;return null==(t=this.node)?void 0:t.disconnect(e)})),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t.forEach((e=>{this.next.add(e),e.pre.add(this)})),this}},aM=class extends sM{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,this.dataArray=new Uint8Array(0)}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=0,i=0,r="M".concat(t,",").concat(i);for(let n=0;n<e.length;n++)i=e[n]/128*100/2,r+="L".concat(t,",").concat(i),t+=1;return r}},cM=class{constructor(){this.source=new sM,this.gain=new sM,this.destination=new sM}get volume(){var e;return(null==(e=this.gain.node)?void 0:e.gain.value)||1}setVolume(e){1!==e?(this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.deleteNode(),this.source.setNode(function(e){let t=uM.get(e);if(t)return t;let i=oM();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return uM.set(e,t),t}(e))}get track(){var e;return null==(e=this.stream)?void 0:e.getAudioTracks()[0]}get stream(){var e;return null==(e=this.destination.node)?void 0:e.stream}},lM=class extends cM{constructor(e){super(),this.context=e,this.denoiser=new sM,this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){!this.context.inputs.has(this)||(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){1!==e?(this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}},dM=class{constructor(){this.audioContext=oM(),this.destination=this.audioContext.createMediaStreamDestination(),this.inputs=new Set,this.mixWeight=0}addMixWeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.mixWeight+=e,this.mixWeight-1==e+1>>1&&this.mixOnChange()}reduceMixWeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.addMixWeight(-e)}close(){this.inputs.forEach((e=>e.remove()))}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},uM=new WeakMap;var hM=class{constructor(e){FC(this,"_volume",0),FC(this,"_log"),FC(this,"_scriptProcessorNode",null),FC(this,"_audioWorkletNode",null),FC(this,"_interval",200),FC(this,"ready",this.preload());let{log:t}=e;this._log=t,LN.on(tO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return hM.workletReady||(hM.workletReady=iM(hM.audioContext,URL.createObjectURL(new Blob(['\nclass VolumeMeter extends AudioWorkletProcessor{constructor(){super();this.volume=0;this.intervalTime=200;this.tick=this.intervalTime;this.isStop=false;this.cache=[];this.sentFirstInfo1=false;this.unmute=false;this.port.onmessage=(event)=>{const{data}=event;switch(data.name){case"chunk":this.cache.push.apply(this.cache,data.data);if(!this.sentFirstInfo1){this.port.postMessage({cl:data.data.length});this.sentFirstInfo1=true;}\nbreak;case"setIntervalTime":this.intervalTime=data.intervalTime;break;case"unmute":this.unmute=true;break;case"stop":this.isStop=true;break;}};}\nprocess(inputs,outputs){const input=inputs[0];const output=outputs[0];if(!input&&!output){return true;}\nif(this.isStop){return false;}\nconst l=output?output[0].length:0;const cl=this.cache.length;if(cl>l){output[0].set(this.cache.slice(0,l));this.cache=this.cache.slice(l);}else if(this.unmute){output[0].set(input[0]);}\nconst firstChannel=cl>l?output[0]:input[0];if(!firstChannel){return true;}\nlet sum=0;let rms;for(let i=0;i<firstChannel.length;++i){sum+=firstChannel[i]*firstChannel[i];}\nrms=Math.sqrt(sum/firstChannel.length);this.volume=Math.max(rms,this.volume*0.95);this.tick-=firstChannel.length;if(this.tick<0){this.tick+=(this.intervalTime/1000)*sampleRate;this.port.postMessage({volume:this.volume,cacheLen:cl,outputLen:l});}\nreturn true;}}\nregisterProcessor("volume-meter",VolumeMeter);\n'],{type:"application/javascript"})))),hM.workletReady.then((()=>this.initAudioWorklet())).catch((()=>this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(hM.audioContext,"volume-meter");let e=!1;this._audioWorkletNode.port.onmessage=t=>{this._volume=t.data.volume||0,!e&&t.data.cacheLen&&t.data.outputLen&&(this._log.warn("worklet play success"),e=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(vP){VN.logFailedEvent({userId:this._log.userId,eventType:pk.LOAD_WORKLET,error:vP}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=oM().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{let t=e.inputBuffer.getChannelData(0),i=0;for(let r=0;r<t.length;++r)i+=t[r]*t[r];this._volume=Math.sqrt(i/t.length)||0}}catch(vP){this._log.error("volumeMeter init script processor error: ".concat(vP))}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,LN.off(tO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(e){var t;let{interval:i}=e;this._interval=i,null==(t=this._audioWorkletNode)||t.port.postMessage({name:"setIntervalTime",intervalTime:i})}},pM=hM;FC(pM,"audioContext",oM()),FC(pM,"workletReady");var mM=class extends sM{constructor(e){super(),FC(this,"_volumeMeter"),this._volumeMeter=new pM(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return HC(this,null,(function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)}))}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),i=new Float32Array(t>>2);e.copyTo(i,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:i},[i.buffer]),e.close()}}},_M=VC(jC(),1),fM=e=>t=>t.deviceId===e,gM=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";FC(this,"kind"),FC(this,"type"),FC(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&&SM(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(fM(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");rO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(fM(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");rO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},TM=class extends _M.EventEmitter{constructor(){super(),FC(this,"audioInputs",new gM(Fb.AUDIO)),FC(this,"videoInputs",new gM(Fb.VIDEO)),FC(this,"audioOutputs",new gM(Fb.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||uP.run(Fk,(()=>{this.update()}),{delay:1e4}))}init(){yM().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return HC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield yM(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},EM=_b||mb?null:new TM;function SM(e){return e.deviceId===e.groupId&&""===e.groupId}function yM(){return HC(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(_O()||!pO())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{SM(e)&&(e.kind===Fb.AUDIO_INPUT?i.audio=!0:e.kind===Fb.VIDEO_INPUT&&(i.video=!0))})),2===e&&(i.audio=!1),1===e&&(i.video=!1),i.audio||i.video){let e;try{e=yield navigator.mediaDevices.getUserMedia(i)}catch(hb){rO.debug("capture before getDevices failed: ",hb)}t=yield navigator.mediaDevices.enumerateDevices(),null==e||e.getTracks().forEach((e=>e.stop()))}}return t.map(((e,t)=>{let i={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||"".concat(e.kind,"_").concat(t)};return e.deviceId.length>0&&CM.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function vM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return EM.update(e?1:0).then((e=>e.audioInputs.devices))}function IM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return EM.update(e?2:0).then((e=>e.videoInputs.devices))}var AM=!1;function RM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return HC(this,null,(function*(){return EM.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var CM=new Set;function bM(e,t){return HC(this,null,(function*(){let i=(yield vM()).find((e=>e.deviceId===Nk));return(null==i?void 0:i.groupId)===e&&i.label===t}))}var kM,DM=class extends cM{constructor(e){super(),this.log=e,FC(this,"volumeMeter"),FC(this,"volumeDestination"),FC(this,"analyser",new aM),this.volumeMeter=new mM({log:this.log}),this.volumeDestination=new sM,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},NM=class extends PP{constructor(e){super(e,Fb.AUDIO),FC(this,"_outputDeviceId"),FC(this,"_volume",1),FC(this,"_destination",oM().createMediaStreamDestination()),FC(this,"pipeline"),FC(this,"volumeMeterMode","worklet"),this.pipeline=new DM(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if(("15.2"===pN||"15.3"===pN||"15.4"===pN)&&this.muted)return void this._log.info("audioElement is muted.");let e=kM||new Audio;e.setAttribute("autoplay","autoplay"),e.srcObject=this.getMediaStream(),e.muted=this.muted,this.element=e,e===kM&&(kM=void 0),this.bindElementEvents()}play(){return HC(this,null,(function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(oM().createAnalyser()),this.setVolume(this._volume),function(){HC(this,null,(function*(){try{AM||(AM=!0,rO.info("speakers:".concat((yield RM()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(PF){}}))}(),BC(NM.prototype,this,"play").call(this)}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destory(),super.stop(e)}setSinkId(e){return HC(this,null,(function*(){var t,i;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield null==(i=(t=this.element).setSinkId)?void 0:i.call(t,e))}))}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},wM=class extends NM{constructor(e){super(e),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(e){var t;this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(hP.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this.pipeline.source.channelCount=(null==(t=e.getSettings())?void 0:t.channelCount)||1,this.pipeline.replaceSource(e),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e]))):this.pipeline.source.deleteNode())}setSourceNode(e){!e||this.pipeline.source.node===e||(this.pipeline.replaceSource(e),e instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch((()=>{})),this.setVolume(this._volume)))}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}},OM=class extends NM{constructor(e){super(e),FC(this,"_sourceElement"),this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,i,r;(null==(i=null==(t=this.element)?void 0:t.error)?void 0:i.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(hP.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=(null==(r=e.getSettings())?void 0:r.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?(this.element?this._log.info("set element volume: ".concat(e)):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),fP(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destory();let t=this._sourceElement||this.element;t&&dN&&(kM=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},PM=class extends sP{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:o=(1===r?OM:tM)}=e;var s;super(),FC(this,"id",nO()),FC(this,"userId",""),FC(this,"isRemote"),FC(this,"mediaType"),FC(this,"room"),FC(this,"user"),FC(this,"_log"),FC(this,"_inputTrack"),FC(this,"_outputTrack"),FC(this,"isPlayCalled"),FC(this,"container",null),FC(this,"player"),FC(this,"subVideoPlayerMap"),FC(this,"muted",!1),FC(this,"abortCtrl"),FC(this,"objectFit","cover"),FC(this,"mirror"),FC(this,"isScreen",!1),FC(this,"manager"),FC(this,"trackSettings"),FC(this,"onPlayerError"),this.userId=t||"",this.mediaType=r,this._log=rO.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=n||this.room)?void 0:s.userId,remoteUserId:this instanceof ZM?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof ZM}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(hP.PLAYER_STATE_CHANGED,(e=>{LN.emit(tO.PLAYER_STATE_CHANGED,PC({track:this},e)),this.emit("player-state-changed",e)})),this.kind===Fb.VIDEO&&(this.player.on(hP.LOADED_DATA,(()=>{LN.emit(tO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(hP.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))}))),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(hP.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||rO}get kind(){return 1===this.mediaType?Fb.AUDIO:Fb.VIDEO}get strMediaType(){return 4===this.mediaType?Fb.VIDEO:2===this.mediaType?Fb.SCREEN:Fb.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&(!this.mediaTrack.muted&&"live"===this.mediaTrack.readyState&&this.mediaTrack.enabled)}play(e,t){return HC(this,null,(function*(){let i=Sw(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!_w(t.muted)&&this.setPlayerMute(t.muted),t&&!_w(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof tM&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),Sw(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!_w(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===Fb.VIDEO)&&this.setPlayerMute(!0),t&&!_w(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof tM&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof tM&&this.player.setContainer(i)),LN.emit(tO.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(),Sw(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(r){throw this.handleAutoPlayFailed(),this.emit("error",r),r}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==Fb.VIDEO||_w(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(Tw(this.mirror))return i.setViewMirror(this.mirror),void(r&&(r.mirror=!1));switch(this.mirror){case"view":r&&(r.mirror=!1),i.setViewMirror(!0);break;case"publish":r&&(r.mirror=!0),i.setViewMirror(!0);break;case"both":r&&(r.mirror=!0),i.setViewMirror(!1)}}playSubContainer(e,t){return HC(this,null,(function*(){if(!this._outputTrack||this.kind===Fb.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,i)=>{var r;e.find((e=>i===e))||(t.stop(),null==(r=this.subVideoPlayerMap)||r.delete(i))}));for(let[r,n]of e.entries()){let e=this.subVideoPlayerMap.get(n);e?t&&(_w(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new tM({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(r+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let e of i)e.setViewMirror(this.player.mirror),yield e.play()}))}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return(null==(e=this.player)?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(vw(this)?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return HC(this,null,(function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),LN.emit(e?tO.TRACK_MUTED:tO.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){_P(e,e).add(Fb.MUTE,this.onTrackMuted).add(Fb.UNMUTE,this.onTrackUnmuted).add(Fb.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Fb.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){fP(e)}setInputMediaStreamTrack(e){var t;let i=this._inputTrack;if(e!==i)return this._inputTrack=e,this.trackSettings=null==(t=e.getSettings)?void 0:t.call(e),e.enabled=!this.muted,i&&this.uninstallTrackEvent(i),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,i||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(t=e.getSettings)?void 0:t.call(e).deviceId,e.label),this._outputTrack=e,this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled)if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch((()=>this.handleAutoPlayFailed())),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(vw(this)?this.jitterBufferDelay:0),void this.log.info("playing state updated, stop ".concat(this.kind));this.log.debug("updatePlayingState abort ".concat(this.isPlayCalled," ").concat(e," ").concat(this.player.isStopped))}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new eM;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof tM?this.player.getVideoFrame():""}onTrackMuted(){this._log.warn("".concat(this.kind," track is unable to provide media output"))}onTrackUnmuted(){this._log.info("".concat(this.kind," track is able to provide media output"))}onTrackEnded(){this._log.warn("".concat(this.kind," track ended"))}};UC([rP([],sP.INIT,{sync:!0})],PM.prototype,"close",1);var MM=Object.prototype.hasOwnProperty;var LM=function(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(dw(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(let t in e)if(MM.call(e,t))return!1;return!0}return!1},xM=MN({retryFunction:function(e){return HC(this,null,(function*(){let t=function(e){return{audio:UM(e),video:FM(e)}}(e);rO.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId"];t.audio&&(i=yield vM(),rO.info("microphones: ".concat(jw(i,{keysToInclude:n})))),t.video&&(r=yield IM(),rO.info("cameras: ".concat(jw(r,{keysToInclude:n}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return BO&&e.getTracks().forEach((e=>{rO.info("".concat(e.kind," capabilities: ").concat(jw(e.getCapabilities(),{keysToInclude:Hk})))})),e}catch(o){let{message:t}=o;throw"NotFoundError"===o.name&&(e.video&&r&&0===r.length&&(t=PN({key:Jk.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(t=PN({key:Jk.MICROPHONE_NOT_FOUND}))),new tb({code:ZC.INITIALIZE_FAILED,name:o.name,message:t,constraint:o.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,retryFuncArgs:n,retriedCount:o}=e,s=o+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===s?n[0].video&&(n[0].maxResolution=!1,(!lN||n[0].width*n[0].height<=2073600)&&n[0].frameRate&&(n[0].frameRate=n[0].frameRate>10?10:5)):2===s?n[0].useDeviceIdOnly=!0:3===s&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&VM(n[0].microphoneId,!1),n[0].cameraId&&VM(n[0].cameraId,!0)},onRetrying:e=>{rO.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{VN.logFailedEvent({eventType:pk.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{VN.logSuccessEvent({eventType:pk.GET_USER_MEDIA_RETRY}),VN.uploadEvent({log:"stat-".concat(pk.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function VM(e,t){return HC(this,null,(function*(){let i=(t?yield IM():yield vM()).find((t=>t.deviceId===e));i&&mw(i.getCapabilities)&&rO.warn(jw(i.getCapabilities(),{keysToInclude:Hk}))}))}function UM(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!LM(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(gw(e.channelCount)&&(t.channelCount=e.channelCount),Tw(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),Tw(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),Tw(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!LM(t)||t)}function FM(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&&!LM(i)?i:(e.width&&(i.width={ideal:e.width},t&&!lD&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!lD&&(i.height.max=e.height)),lD&&BD&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!LM(i)||i)}var BM=xM;function HM(e){return WM(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return HC(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function jM(e){return WM(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return HC(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function WM(e){return function(t,i,r){return r.value=e(r.value,i),r}}var GM=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&rO.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{rO.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),JM=0,KM=class{constructor(){this.log=rO.createLogger({id:"fq".concat(++JM)}),this.isRunning=!1,this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return 0===this.length?null:this.queue[this.length-1]}push(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i,r;let n=PC({},e),o=new Promise(((e,t)=>{n.resolve=e,n.reject=t}));return n.promise=o,t?this.length<=1?this.queue.push(n):null==(r=null==(i=this.lastQueueItem)?void 0:i.promise)||r.then(n.resolve,n.reject):this.queue.push(n),this.log.debug("push ".concat(this.length)),this.isRunning||this.callNext(),o}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length)),e}callNext(){if(this.isRunning||0===this.length)return;this.log.debug("callNext ",this.length);let{fn:e,args:t,context:i,resolve:r,reject:n}=this.queue[0];this.isRunning=!0,e.apply(i,t).then(r,n).finally((()=>{this.isRunning=!1,this.shift(),this.callNext()}))}},zM=new WeakMap,qM=new WeakMap;function YM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return function(t,i,r){let n=r.value;return r.value=function(){let t=zM.get(this)||new KM;for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return zM.set(this,t),t.push({fn:n,args:r,context:this},e)},r}}function QM(e){return function(t,i,r){let n=r.value;return r.value=function(){var t,i,r;let o=[];for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return null==(i=null==(t=zM.get(this))?void 0:t.queue)||i.forEach((e=>o.push(e))),null==(r=qM.get(this))||r.forEach((e=>null==e?void 0:e.queue.forEach((e=>o.push(e))))),o.forEach((t=>{t.reject(new tb({code:ZC.API_CALL_ABORTED,message:e}))})),zM.delete(this),qM.delete(this),n.apply(this,a)},r}}function XM(e){return function(t,i,r){let n=r.value,o=t=>e(...t);return r.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=qM.get(this)||new Map,s=r.get(o(t))||new KM;return r.set(o(t),s),qM.set(this,r),s.push({fn:n,args:t,context:this})},r}}var $M=class extends PM{constructor(e,t){super({mediaType:e,PlayerClass:t}),FC(this,"isRemote",!1),FC(this,"deviceId"),FC(this,"groupId",""),FC(this,"label",""),FC(this,"_isRecapturing",!1),FC(this,"_lastRecaptureTime",0),FC(this,"_onMuteTimeoutId",-1),FC(this,"_encodeCheckTimeoutId",-1),FC(this,"profile")}get enableEncodeFrame(){return!1}get isPublished(){return"publish"===this.state}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){_P(e,e).add(Fb.MUTE,this.onTrackMuted).add(Fb.UNMUTE,this.onTrackUnmuted).add(Fb.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Fb.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){fP(e)}setStateToCapture(){}capture(e){return HC(this,null,(function*(){var t;try{let i,r=kw();LN.emit(tO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield BM(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),LN.emit(tO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:kw()-r}),i}catch(hb){throw LN.emit(tO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:hb}),this.log.error("getUserMedia error observed ".concat(hb)),hb}}))}setInputMediaStreamTrack(e){return this.state===sP.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),null==(t=this.room)?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),LN.emit(tO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return HC(this,null,(function*(){if(this.mediaTrack&&FO){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return HC(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==Fb.AUDIO||t!==Nk||(yield bM(r,n)))}()}))}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=i,t&&(this.groupId=t),yM().then((t=>{let i=t.find((t=>t.deviceId===e));i&&this.emit("2",i)})))}}))}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return!(!this.deviceId||!this.mediaTrack||this.kind===Fb.AUDIO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("麦克风"))return!0;let i="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(Fb.AUDIO_INPUT);return!!CM.has(i)}(this.mediaTrack)||this.kind===Fb.VIDEO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let i="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(Fb.VIDEO_INPUT);return!!CM.has(i)}(this.mediaTrack)||this._isRecapturing||e&&BD&&lN)}onTrackMuted(){if(super.onTrackMuted(),GM(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<xk)return void setTimeout((()=>this.onTrackMuted()),xk);this._onMuteTimeoutId=setTimeout((()=>HC(this,null,(function*(){var e;if(null!=(e=this.mediaTrack)&&e.muted){if((nD||oD)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return HC(this,null,(function*(){if(BC($M.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<xk)return void setTimeout((()=>this.onTrackEnded()),xk);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return HC(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 vM():yield IM()).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}),LN.emit(tO.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),LN.emit(tO.LOCAL_TRACK_RECAPTURE,{track:this,error:e})}))}))}getRecoverCaptureDeviceId(){return HC(this,null,(function*(){let e=this instanceof nL;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(eL.get(t)||0)+1;if(eL.set(t,i),i>=3){let r=e?(yield IM()).find((e=>!eL.has(e.deviceId))):(yield vM()).find((e=>!eL.has(e.deviceId)));r&&(this.log.warn("".concat(t," capture fail ").concat(i," times, change new ").concat(r.deviceId)),t=r.deviceId)}}return t}))}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),null==(e=this.manager)||e.removeInput(this)}},ZM=$M;UC([rP(sP.INIT,"capture",{ignoreError:!0,sync:!0})],ZM.prototype,"setStateToCapture",1),UC([YM()],ZM.prototype,"capture",1),UC([rP("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),LN.emit(tO.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this._encodeCheckTimeoutId=setTimeout((()=>{if(this.isPublished&&this.isMediaTrackActive){let e=this.stat.bytesSent>0;OP[e?"addSuccessEvent":"addFailedEvent"]({key:this.kind===Fb.AUDIO?503700:513702}),e||(this.log.warn("encode failed"),this.emit("6",this))}}),5e3)},fail(e){let t="error",i=e.cause;i.message.includes("timeout")?t="timeout":i.code===ZC.API_CALL_ABORTED&&(t="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:i})}})],ZM.prototype,"publish",1),UC([WM((e=>function(){return HC(this,null,(function*(){let t="publish"===this.state?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)}))})),rP([],"capture",{sync:!0})],ZM.prototype,"unpublish",1);var eL=new Map;LN.on(tO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&eL.delete(e.track.deviceId)}));var tL=class extends ZM{constructor(e){super(1,wM),FC(this,"mediaType",1),FC(this,"volume",0),FC(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),FC(this,"playerMuted",!0),FC(this,"pipeline"),FC(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),this.manager=e,this.pipeline=new lM(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return HC(this,null,(function*(){yield BC(tL.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};OP.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),OP.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),OP.addEnum({key:502700,value:0});let{sampleRate:i,channelCount:r}=t;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:i,channelCount:r}))),this.pipeline.source.channelCount=r||1,this.pipeline.replaceSource(e),this.updatePlayingState(!!e)}))}capture(e){let{deviceId:t,customSource:i,useExactDeviceId:r=!1}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,customSource:i})}switchDevice(e){return HC(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==Nk)return;if(yield bM(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)),LN.emit(tO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(uk){throw this.log.error("switch microphone failed ".concat(uk)),this.deviceId&&this.recapture(this.deviceId),uk}}}))}listenDeviceChange(){EM&&!EM.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&EM.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return HC(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e))),KL(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield vM();t[0]?this.recapture(t[0].deviceId):EM.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return HC(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:n}=e;return function*(){let e=!1;!_w(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!_w(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,e=!0),!_w(n)&&n!==t.profile.autoGainControl&&(t.profile.autoGainControl=n,e=!0),e&&t.deviceId&&(yield t.recapture(t.deviceId))}()}))}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&OP.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch((t=>this._log.warn("".concat(e?"enable":"disable"," ANS failed "),t)))}addDenoiser(e){var t;aN<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(OP.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1))}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),EM.off("audioInputAdded",this.handleMicrophoneAdded,this),EM.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return HC(this,null,(function*(){try{yield BC(tL.prototype,this,"recapture").call(this,e)}catch(uk){let i=(yield vM()).find((t=>t.deviceId!==e));if(!i)throw uk;yield BC(tL.prototype,this,"recapture").call(this,i.deviceId)}}))}},iL=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,i=[],r=0;for(let o=e;o<=t;o++){let e=this.dataView.getInt8(o);switch(e){case 0:case 1:case 2:case 3:2===r&&(i.push(3),r=0),0==e?r++:r=0,i.push(e);break;default:r=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],r=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:r++,i.push(this.dataView.getInt8(o));break;case 3:2!==r&&i.push(this.dataView.getInt8(o)),r=0;break;default:i.push(this.dataView.getInt8(o)),r=0}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}get isSEI(){return 6===this.dataView.getUint8(4)}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let n=6;n<this.dataView.buffer.byteLength;n++){let i=this.dataView.getUint8(n);if(t++,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),r=new DataView(i);for(let n=0;n<i.byteLength;n++,t++)r.setInt8(n,this.dataView.getInt8(t));return r}},rL=class{constructor(){FC(this,"_seiMessageList",[]),FC(this,"_smallSeiMessageList",[]),FC(this,"_seiPayloadType",243)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),r=t%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let s=0;s<i;s++)n.push(255);n.push(r);let o=new DataView(e);return n.push(...new Uint8Array(o.buffer)),n.push(128),new iL(new DataView(new Uint8Array(n).buffer),!0)}sendSEI(e,t){null!=t&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),null!=t&&t.small&&this._smallSeiMessageList.push(e)}getNaluCount(e){let t=0,i=0,r=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(r.getUint8(n)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}encode(e,t){let i=t?this._smallSeiMessageList:this._seiMessageList;if(i.length>0&&e.data.byteLength>0){let t=9-this.getNaluCount(e.data);if(t<=0)return 0;let r=i.splice(0,t).reverse().map(this.encodeSEINalu.bind(this)),n=r.reduce(((e,t)=>e+t.dataView.byteLength),0),o=new ArrayBuffer(n+e.data.byteLength),s=new DataView(o),a=new DataView(e.data),c=0;for(let e=0;e<r.length;e++)for(let t=0;t<r[e].dataView.byteLength;t++)s.setInt8(c++,r[e].dataView.getInt8(t));for(let i=0;i<e.data.byteLength;i++)s.setInt8(c++,a.getInt8(i));return e.data=o,r.length}return 0}},nL=class extends ZM{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,tM),FC(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),FC(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0}),FC(this,"small"),FC(this,"isNeedToSetBandwidth"),FC(this,"muteImage"),FC(this,"manager"),FC(this,"_seiCodec",new rL),FC(this,"pipeline",[]),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(MC(PC({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",t),this.on("publish",t),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(FO&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}setMute(e){return HC(this,null,(function*(){var t,i,r;if(fw(e)){if(this.muteImage===e)return;yield null==(t=this.manager)?void 0:t.deleteWatermark("mute"),yield null==(i=this.manager)?void 0:i.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,BC(nL.prototype,this,"setMute").call(this,!1)}else yield null==(r=this.manager)?void 0:r.deleteWatermark("mute"),this.muteImage=void 0,BC(nL.prototype,this,"setMute").call(this,e)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:r=!1,customSource:n}=e;return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,customSource:n})}setProfile(e){let t=PC({},e),i=t.width>t.height;t.width*t.height<=19200&&oD&&nN&&(this.log.warn("resolution is ".concat(t.width,"*").concat(t.height,", fallback to 240*180")),t.width=i?240:180,t.height=i?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&gN&&(t.width=i?1280:720,t.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(MC(PC({},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:Fb.VIDEO,videoType:Fb.BIG})})):void 0}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return FO&&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:Jw()&&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 HC(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),LN.emit(tO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(uk){throw this.log.error("switch camera failed ".concat(uk)),this.deviceId&&this.recapture(this.deviceId),uk}}))}listenDeviceChange(){EM&&!EM.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&EM.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return HC(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e))),KL(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield IM();t[0]?this.recapture(t[0].deviceId):EM.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return HC(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}encodeFrame(e,t){let i=t?8:this.mediaType;return this.pipeline.reduce(((e,t)=>t?t(e,i):e),e)}get enableEncodeFrame(){return this.pipeline.some((e=>e))}play(e,t){return HC(this,null,(function*(){return _w(this.mirror)&&!this.isScreen&&this.setMirror("view"),BC(nL.prototype,this,"play").call(this,e,t)}))}close(){EM.off("videoInputAdded",this.handleCameraAdded,this),EM.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return HC(this,null,(function*(){try{yield BC(nL.prototype,this,"recapture").call(this,e)}catch(uk){let i=(yield IM()).find((t=>t.deviceId!==e));if(!i)throw uk;yield BC(nL.prototype,this,"recapture").call(this,i.deviceId)}}))}},oL=nO();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:oL,exposeOrigin:!0,permittedOrigins:["*"]})}catch(PF){}var sL,aL=function(e){return HC(this,null,(function*(){let t=null,i=function(e){let t={preferCurrentTab:"current-tab"===e.preferDisplaySurface||!!e.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:lN?{max:e.width}:{ideal:e.width,max:e.width},height:lN?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:e.preferDisplaySurface||"monitor"};if(t.video=i,e.systemAudio){let{echoCancellation:i=!0,noiseSuppression:r=!1,autoGainControl:n=!1}=e;t.audio={echoCancellation:i,noiseSuppression:r,autoGainControl:n,sampleRate:48e3}}return t}(e);rO.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(oN&&aN<74||lN||lD)&&rO.warn("Your browser not support capture system audio");let n=r.getVideoTracks()[0];if(n){if(e.frameRate)try{yield n.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height})}catch(o){rO.warn("screen applyConstraints failed: ".concat(o))}e.captureElement&&(yield function(e,t){return HC(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&mw(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==oL)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){rO.warn("cropTo target failed ".concat(r))}}))}(n,e.captureElement))}if(e.audio){let i=function(e){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return _w(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);rO.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},cL=class extends nL{constructor(e){super(e,2),FC(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),FC(this,"objectFit","contain"),FC(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return HC(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:r,echoCancellation:n,noiseSuppression:o,audioTrack:s,videoTrack:a,captureElement:c,preferDisplaySurface:l}=e;return function*(){try{let e;return a||s?(e=new MediaStream,a&&e.addTrack(a),s&&e.addTrack(s)):e=yield aL({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:r,echoCancellation:n,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof tb?e:new tb({code:ZC.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return HC(this,null,(function*(){throw new Error("Method not implemented.")}))}},lL=class extends tL{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}};var dL=class extends dM{constructor(e){super(),this.room=e,FC(this,"_localAudioTrack"),FC(this,"_localScreenAudioTrack"),FC(this,"log",rO.createLogger({id:"am"})),FC(this,"denoiser"),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}dump(e){var t,i;if(!this._localAudioTrack)return;let r=[],n=[];null!=(t=this._localAudioPipline)&&t.source.node&&(r.push(this._localAudioPipline.source.node),n.push("mic")),null!=(i=this._localAudioPipline)&&i.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),n.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),n.push("mix")),this.log.info("dump audio track ".concat(n,", duration: ").concat(e));let o=new AbortController,s=[],a=setTimeout((()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")}),1e3*e),c=()=>{for(let e=0;e<n.length;e++){let t=URL.createObjectURL(new Blob(s[e])),i=document.createElement("a");i.href=t,i.download="".concat(n[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(a),o.abort("download")},l=function(e){return HC(this,null,(function*(){let t=oM();sL||(sL=iM(t,URL.createObjectURL(new Blob(["registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});"],{type:"application/javascript"})))),yield sL;let i=new AudioWorkletNode(t,"dumper",{numberOfInputs:e.length,numberOfOutputs:0});return e.forEach(((e,t)=>e.connect(i,0,t))),new ReadableStream({start(e){i.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach((e=>e.disconnect(i))),i.port.close()}})}))}(r).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>s[t]=s[t]?s[t].concat(e[0]):[e[0]]))}}),o).catch((e=>c))));return{then:l.then.bind(l),download:c}}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}changeInput(e){if(e instanceof lL)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof tL)this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof mL)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;null==(e=this._localAudioTrack)||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),null==(t=this._localScreenAudioTrack)||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof lL?delete this._localScreenAudioTrack:e instanceof tL&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,null==(t=this._localAudioTrack)||t.removeDenoiser(e)}destroy(){this.close()}};function uL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return WM(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];return new Promise(((n,s)=>{let a=setTimeout((()=>{let i=new tb({code:ZC.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});rO.warn(i),2===t?s(i):1===t&&n()}),1e3*e);i.apply(this,o).then(n,s).finally((()=>{clearTimeout(a)}))}))}))}var hL=class extends PM{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,FC(this,"tinyId"),FC(this,"isRemote",!0),FC(this,"jitterBufferDelay",0),FC(this,"_decodeCheckTimeoutId",-1),this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)}))}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===hL.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," hasFlag: ").concat(this.hasFlag," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},pL=hL;FC(pL,"STATE_SUBSCRIBE","subscribe"),UC([uL(5,1)],pL.prototype,"waitHasMediaTrack",1),UC([rP(sP.INIT,pL.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),LN.emit(tO.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),this._decodeCheckTimeoutId=setTimeout((()=>{if(this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let e=this.player.isPlaying||(this.kind===Fb.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0);OP[e?"addSuccessEvent":"addFailedEvent"]({key:this.kind===Fb.AUDIO?504700:514702}),e||this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===Fb.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0)," )"))}}),5e3)},ignoreError:!0})],pL.prototype,"subscribe",1),UC([rP(pL.STATE_SUBSCRIBE,sP.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),LN.emit(tO.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],pL.prototype,"unsubscribe",1);var mL=class extends pL{constructor(e,t){super(e,t,1),FC(this,"volume",0),FC(this,"mediaType",1),FC(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),FC(this,"audioDecoder"),this.manager=e.audioManager}onPlayerError(e){if(this.enableDecodeFrame){this.room.enableInsertableStreams();let e=new AudioDecoder({error:e=>this._log.error(e),output:e=>{this.player.write(e)}});e.configure({codec:"opus",sampleRate:48e3,numberOfChannels:1}),this._log.info("audioDecoder state:".concat(e.state)),this.audioDecoder=e}}get enableDecodeFrame(){var e,t;return(null==(t=null==(e=this.player.element)?void 0:e.error)?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&WO&&JO().AudioDecoder}decodeFrame(e){var t;return"configured"===(null==(t=this.audioDecoder)?void 0:t.state)&&this.audioDecoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"})),e}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}},_L=[-1,-1,1,-1,-1,1,1,1],fL=[0,0,1,0,0,1,1,1],gL=class extends sP{constructor(e,t){if(super(),this.context=e,FC(this,"name"),FC(this,"input"),FC(this,"output"),FC(this,"texture"),FC(this,"ctx2d",null),FC(this,"fbo"),FC(this,"width",0),FC(this,"height",0),FC(this,"x",0),FC(this,"y",0),FC(this,"program"),FC(this,"vertexShader"),FC(this,"fragmentShader"),FC(this,"totalFrames",0),FC(this,"dropFrames",0),FC(this,"matchInputSize",!0),FC(this,"texCoordBuffer"),FC(this,"positionBuffer"),FC(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),FC(this,"cost",0),FC(this,"_canvas",null),FC(this,"_image"),this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof DL){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(fL),this.positionBuffer=this.createBuffer(_L),!1!==t.createTexture&&(this.texture=i.createTexture(),this.useTexture(),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.pixelStorei(i.PACK_ALIGNMENT,1),i.pixelStorei(i.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=i.createFramebuffer(),this.useBufferFrame(),this.useTexture(),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(i.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(i.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(hb){this.context.destroy(hb)}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,i=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,i),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),i}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return e.addInput(this,...i),this.output=e,e}addInput(e){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();return!!(this.context instanceof kL&&this.render(e)||this.context instanceof DL&&this.render2d(e))&&(this.totalFrames++,this.cost=Date.now()-t,!0)}render2d(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&this.draw2d(this.input.image,0,0,this.width,this.height)}disconnect(){for(var e,t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];null==(e=this.output)||e.removeInput(this,...i),delete this.output}removeInput(e){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),null==(e=this.output)||e.removeInput(this),delete this.output,null==(t=this.input)||t.disconnect(),this.context instanceof kL){let e=this.context.ctx;e.deleteBuffer(this.texCoordBuffer),e.deleteBuffer(this.positionBuffer),this.fbo&&e.deleteFramebuffer(this.fbo),this.texture&&e.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&e.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&e.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&e.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures(null==(e=this.input)?void 0:e.texture)}useTextures(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];i.forEach(((t,i)=>{t&&(e.activeTexture(e.TEXTURE0+i),e.bindTexture(e.TEXTURE_2D,t))}))}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),i}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let i=this.context.ctx;i.bindBuffer(i.ARRAY_BUFFER,e),i.bufferData(i.ARRAY_BUFFER,new Float32Array(t),i.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];i.forEach(((t,i)=>{e.enableVertexAttribArray(i),e.bindBuffer(e.ARRAY_BUFFER,t),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0)}))}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(this.width!==e||this.height!==t){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let i=this.context.ctx;i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let i=this.context.ctx;i.drawArrays(i.TRIANGLE_STRIP,0,4)}draw2d(e,t,i,r,n){return!(!this.ctx2d||!e)&&(e instanceof ImageData?this.ctx2d.putImageData(e,t,i):this.ctx2d.drawImage(e,t,i,r,n),!0)}getInfo(){var e;let{totalFrames:t,x:i,y:r,width:n,height:o,name:s,cost:a}=this,c=Date.now(),l=(t-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:t,x:i,y:r,width:n,height:o,timestamp:c,fps:l,name:s,cost:a},PC({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}};UC([rP(sP.INIT,"connected",{sync:!0})],gL.prototype,"connect",1),UC([rP("connected",sP.INIT,{ignoreError:!0,sync:!0})],gL.prototype,"disconnect",1),UC([rP([],"closed",{sync:!0})],gL.prototype,"close",1);var TL=[0,1,1,1,0,0,1,0],EL=class extends gL{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),FC(this,"_intervalId",0),FC(this,"_sequence",0),FC(this,"checkGLError",!1),e instanceof DL?this.ctx2d=e.ctx:e.available&&(null==t?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(TL)}start(e){this._intervalId=uP.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(uP.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof kL){let e=this.context.ctx.getError();e&&this.context.destroy(new Error("".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)))}}),{fps:this.context.frameRate})}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];super.addInput(e,...i),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),uP.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},SL=class extends EL{constructor(e,t){super(e,t),FC(this,"_videoTrack"),FC(this,"_canvasContainer"),Number(uN)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks();let i=e=>{var t;let i=()=>{var t;return null==(t=this._videoTrack)?void 0:t.removeEventListener(e,r)},r=()=>{i(),this.context.destroy(new Error("video track ".concat(e)))};this.once("closed",i),null==(t=this._videoTrack)||t.addEventListener(e,r)};e instanceof kL&&i("mute"),i("ended")}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack,null==(t=this._canvasContainer)||t.remove()}},yL=class extends SL{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},vL=class extends SL{constructor(e,t){super(e,{name:"smallDestination"}),this.resolution=t}resize(e,t){let i,r=e*t,n=this.resolution.width*this.resolution.height;rO.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),r>n?i=r/n:(rO.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(e," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),i=r/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},IL=class extends gL{constructor(e,t){super(e,PC({name:"imageSource"},t)),FC(this,"_lastImage"),FC(this,"_totalFrames",0),FC(this,"_autoResize",!1),this._autoResize=!1!==(null==t?void 0:t.autoResize)}_render(e,t){var i,r;let{width:n,height:o}=this;if(this.image instanceof HTMLVideoElement){if(mw(this.image.getVideoPlaybackQuality)&&nN){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(!0===(null==(r=null==(i=this.image.srcObject)?void 0:i.getVideoTracks()[0])?void 0:r.muted)||this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}if(({videoWidth:n,videoHeight:o}=this.image),!n||!o)return!1;this.image.width=n,this.image.height=o}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if(({width:n,height:o}=this.image),this.image!==this._lastImage)this._lastImage=this.image;else if(n===this.width&&o===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&(({width:n,height:o}=this.image),this._lastImage=this.image);if(!this._autoResize)return!0;if(this.width===n&&this.height===o&&this.totalFrames){if(t){this.useTexture();let e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,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(n,o)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},AL=class extends IL{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource"}get image(){return this._player.element}},RL=class extends AL{constructor(e,t,i){super(e,new tM({id:i.name,track:t,muted:!0,container:null,objectFit:"contain",log:i.logger}),i),this.name="videoTrackSource",this._player.play()}get image(){return this._player.element}replaceTrack(e){this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},CL=class extends sP{constructor(e){super(),FC(this,"frameRate"),FC(this,"_canvas"),FC(this,"log"),FC(this,"hasAlpha",!1),FC(this,"name"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new RL(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new SL(this,e)}createVideoImageSource(e,t){return new IL(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new AL(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};FC(CL,"_ids",0);var bL={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},kL=class extends CL{constructor(){super(...arguments),FC(this,"defaultProgam"),FC(this,"defaultVShader"),FC(this,"defaultFShader"),FC(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(CL._ids++)),this.ctx=this._canvas.getContext("webgl2",bL),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,"\n// 顶点着色器\nattribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main() {\n gl_Position = a_position;\n v_texCoord = a_texCoord;\n}\n"),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,"\n// 片元着色器\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\n\nvoid main() {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n} "),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",(()=>{this.destroy(new Error("webgl context lost"))})),this.log.info("video context created use webgl")}destroy(e){return this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;null==(t=this.ctx)||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let i=this.ctx,r=i.createShader(e);return i.shaderSource(r,t),i.compileShader(r),r}createProgram(e,t){let i=this.ctx,r=i.createProgram();return i.attachShader(r,e),i.attachShader(r,t),i.linkProgram(r),i.getProgramParameter(r,i.LINK_STATUS)||this.log.error(i.getProgramInfoLog(r)),r}};UC([rP(sP.INIT,"created",{sync:!0})],kL.prototype,"create",1),UC([rP("created",sP.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit("unavailable",e),this.removeAllListeners()}})],kL.prototype,"destroy",1);var DL=class extends CL{constructor(){super(...arguments),FC(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(CL._ids++),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()}};UC([rP(sP.INIT,"created",{sync:!0})],DL.prototype,"create",1),UC([rP("created",sP.INIT,{ignoreError:!0,sync:!0})],DL.prototype,"destroy",1);var NL=class extends pL{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),FC(this,"mediaType",4),FC(this,"source"),FC(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),FC(this,"pipeline",[]),this.manager=e.videoManager}play(e,t){return(Tw(null==t?void 0:t.canvasRender)?t.canvasRender:17===mN)&&!this.source&&this.useCanvasPlayer(),super.play(e,t)}useCanvasPlayer(){if(this.log.info("useCanvasPlayer(), ".concat(!!this.player.element)),!this.player.element)return;let e=new DL({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=e.createVideoPlayerSource(this.player);this.source=t;let i=new EL(e);t.connect(i),this.player.setCanvas(e._canvas),this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this)}updateCanvasPlayerFPS(e){let t=this.decodeFPS,i=(r=t,[15,30,45,60].reduce(((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)));var r;!gw(t)||t<=0?this.log.debug("updateCanvasPlayerFPS() ignore decoder: ".concat(t," ")):i!==e.frameRate?(this.log.info("updateCanvasPlayerFPS() decoder: ".concat(t,", closest: ").concat(i,", current: ").concat(e.frameRate)),e.frameRate=i):this.log.debug("updateCanvasPlayerFPS() ignore ClosestFPS ".concat(i," == ").concat(e.frameRate))}get decodeFPS(){var e;let{msg_video_status:t}=(null==(e=this.room.heartbeatReport)?void 0:e.msg_down_stream_info.find((e=>e.msg_user_info.str_identifier===this.userId)))||{},i=2===this.mediaType?7:this.isSmall?3:2;if(!t||0===t.length)return 0;let r=t.find((e=>e.uint32_video_stream_type===i));return(null==r?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}get enableDecodeFrame(){return this.manager.configPipeline(this),this.pipeline.some((e=>e))}decodeFrame(e){return this.pipeline.reduce(((e,t)=>t?t(e,this):e),e)}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}},wL=class extends NL{constructor(e,t){super(e,t,2),FC(this,"mediaType",2),FC(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function OL(){}var PL=e=>e(),ML=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,LL=1,xL=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new HL(e,this,this.streamId++);return jL.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},VL=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=OL,this.error=OL,this.next=OL,this.dispose=OL,this.subscribe=OL,this.doDefer()}subscribe(e){return e instanceof xL?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(PL),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}},UL=class extends VL{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 FL(e,t,i){if(ML()){let r=Object.defineProperties(Object.setPrototypeOf(e,xL.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}});jL.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof xL&&jL.addSource(r,t)}return r}return e}function BL(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var HL=class extends UL{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{jL.defer(this.source,this.id)}))}next(e){jL.next(this.source,this.id,e),this.sink.next(e)}complete(){jL.complete(this.source,this.id),this.sink.complete()}error(e){jL.complete(this.source,this.id,e),this.sink.error(e)}},jL={addSource(e,t){BL("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){BL("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;BL("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){BL("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){BL("defer",{id:e.id,streamId:t})},pipe(e){BL("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){BL("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=LL++),BL("create",{name:e.toString(),id:e.id})}},WL=class extends VL{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 GL=function(e,t){return function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return i=>{if(i instanceof xL){let n=FL((t=>{let o=new e(t,...r);o.sourceId=n.id,o.subscribe(i)}),t,arguments);return n.source=i,jL.pipe(n),n}return t=>i(new e(t,...r))}}}(class extends UL{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},"map");!function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];i.reduce(((e,t)=>t(e)),e)}(function(e){return FL((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}(250),GL((()=>performance.now())),function(){return e=>{let t=new WL(e);if(e instanceof xL){let i=FL((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,jL.pipe(i),i}return FL(t.add.bind(t),"share",arguments)}}());var JL=new Map;function KL(e,t){let i=MC(PC({},t),{timestamp:nb()});JL.has(e)?JL.get(e).push(i):JL.set(e,[i])}LN.on(tO.JOIN_SUCCESS,(e=>{let{room:t}=e;KL(t.userId,{eventId:32788})})),LN.on(tO.LEAVE_START,(e=>{let{room:t}=e;KL(t.userId,{eventId:32789})})),LN.on(tO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),KL(t.room.userId,{eventId:e})}})),LN.on(tO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),KL(t.room.userId,{eventId:e})}})),LN.on(tO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Fb.AUDIO?KL(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):KL(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),LN.on(tO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Fb.AUDIO?KL(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):KL(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),LN.on(tO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&KL(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&KL(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&KL(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),LN.on(tO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&KL(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&KL(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&KL(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),LN.on(tO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&KL(t.room.userId,{eventId:t.kind===Fb.VIDEO?32780:32781})})),LN.on(tO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&KL(t.room.userId,{eventId:t.kind===Fb.VIDEO?32782:32783})})),LN.on(tO.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:n}=e;switch(n){case"CONNECTED":t="RECONNECTING"===r?32795:32791;break;case"DISCONNECTED":t="RECONNECTING"===r?32796:32790;break;case"RECONNECTING":t=32794}t&&KL(i.userId,{eventId:t})})),LN.on(tO.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:n,remoteUserId:o}=e,s=!!o;switch(n){case"CONNECTED":t="RECONNECTING"===r?s?32801:32798:s?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===r&&(t=s?32802:32799);break;case"RECONNECTING":t=s?32800:32797}t&&KL(i.userId,{eventId:t,remoteUserId:o})})),LN.on(tO.VIDEO_CODEC_IMPLEMENTATION_CHANGED,(e=>{let{userId:t,remoteUserId:i,codec:r,isHWCodec:n,prevImplementation:o,streamType:s}=e,a=n?1:0;o||(a=n?3:2);let c="h264"===r?0:2,l={eventId:4004,param1:a,param2:c,streamType:s||2};i&&(l.remoteUserId=i,l.eventId=4005),KL(t,l),OP.addEnum({key:i?514701:513701,value:a}),OP.addEnum({key:i?514700:513700,value:c})})),LN.on(tO.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===Fb.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),KL(t.userId,e)}}));var zL=VC(jC(),1),qL=class extends zL.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,FC(this,"userMap",new Map),FC(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find((e=>e.isRobot))}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:r,role:n}=e;if(this.userMap.has(t))return;let o={userId:i,tinyId:r,role:20===n?"anchor":"audience"};this.userMap.set(t,o),this.emit("1",o)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let r="peer leave [".concat(e,"]");_w(t)||(r+=":".concat(Mk[t])),this._log.info(r);let n=this.remotePublishedUserMap.get(e);if(n){let t=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:t,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",i.userId)}setUserList(e){this.userMap.forEach((t=>{e.findIndex((e=>e[this.key]===t[this.key]))<0&&this.deleteUser(t[this.key],0)})),e.forEach((e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)}))}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach((t=>{let i=t[this.key];if(e.findIndex((e=>e[this.key]===t[this.key]))<0){this._log.info("remote [".concat(i,"] unpublish"));let e=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(i),this.emit("6",{prevMuteState:e,muteState:t.muteState,flag:0})}})),e.forEach((e=>{var t;let i=e[this.key];if(i===this.mySelfId)return;let{flag:r,userId:n,tinyId:o}=e,s=Pw(r,n),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==r&&(e.flag=r,this._log.info("remote publish updated: ".concat(JSON.stringify(e.muteState))),this.emit("6",{prevMuteState:a,muteState:s,flag:r}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(s))),this.addUser({userId:n,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:Pw(0,n),muteState:s,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function YL(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return WM(((e,n)=>{let o=new Map;return LN.on(tO.ROOM_DESTROY,(e=>{let{room:t}=e;return o.delete(t)})),function(){let s=o.get(this);for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(s||(s={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,s)),0===s.timestamp?s.timestamp=Date.now():Date.now()-s.timestamp>1e3&&(s.timestamp=Date.now(),s.callCountInSecond=0,s.totalSizeInSecond=0),r&&(s.totalSizeInSecond+=r(...c)),0!==s.timestamp&&Date.now()-s.timestamp<1e3&&(s.callCountInSecond>=t||s.totalSizeInSecond>i))throw new tb({code:ZC.INVALID_OPERATION,message:PN({key:Jk.CALL_FREQUENCY_LIMIT,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>i,name:n,timesInSecond:t,maxSizeInSecond:i}})});s.callCountInSecond++,e.call(this,...c)}}))}var QL,XL=!0,$L={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear"},ZL={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},ex=((QL=ex||{})[QL.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",QL[QL.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",QL[QL.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",QL[QL.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",QL[QL.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",QL[QL.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",QL[QL.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",QL[QL.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",QL[QL.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",QL[QL.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",QL[QL.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",QL[QL.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",QL[QL.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",QL[QL.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",QL[QL.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",QL[QL.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",QL[QL.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",QL[QL.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",QL[QL.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",QL[QL.INVALID_OPERATION=5100]="INVALID_OPERATION",QL[QL.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",QL[QL.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",QL[QL.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",QL[QL.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",QL[QL.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",QL[QL.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",QL[QL.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",QL[QL.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",QL[QL.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",QL[QL.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",QL[QL.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",QL[QL.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",QL[QL.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",QL[QL.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",QL[QL.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",QL[QL.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",QL[QL.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",QL[QL.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",QL[QL.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",QL[QL.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",QL[QL.DEVICE_ERROR=5300]="DEVICE_ERROR",QL[QL.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",QL[QL.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",QL[QL.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",QL[QL.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",QL[QL.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",QL[QL.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",QL[QL.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",QL[QL.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",QL[QL.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",QL[QL.SERVER_ERROR=5400]="SERVER_ERROR",QL[QL.NEED_TO_BUY=5401]="NEED_TO_BUY",QL[QL.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",QL[QL.OPERATION_FAILED=5500]="OPERATION_FAILED",QL[QL.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",QL[QL.REJOIN_FAILED=5502]="REJOIN_FAILED",QL[QL.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",QL[QL.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",QL[QL.OPERATION_ABORT=5998]="OPERATION_ABORT",QL[QL.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",QL);var tx=MC(PC({},Kk),{INVALID_PARAMETER(e){let{fnName:t}=e;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(r,"(), received type: ").concat(pw(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(r,"(), received type: ").concat(pw(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,value:r}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(r,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,value:r}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(r,".")},INVALID_ELEMENT_ID(e){let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE(e){let{key:t,fnName:i,type:r}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(r,".")},INVALID_STREAM_ID(e){let{key:t}=e;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(e){let{key:t}=e;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(e){let{key:t}=e;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(e){let{fnName:t}=e;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(e){let{fnName:t}=e;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing ").concat(i.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(e){let{fnName:t}=e;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the microphone is not turned on.")},INVALID_BUFFER_EMPTY:e=>{let{key:t}=e;return"the buffer size of paramerter '".concat(t,"' cannot be empty")},INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: '".concat("audience","' cannot call this api."),INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:e=>{let{fnName:t}=e;return"you need to call ".concat(t,"() after publish stream.")},ENV_NOT_SUPPORTED(e){let{fnName:t}=e;return"the current browser does not support the capability of the function '".concat(t,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(e){let{fnName:t}=e;return"cannot call ".concat(t," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got device exception").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:i=ix(t),error:r}=e;return"NotFoundError, no ".concat(i," detected, please check your device and the configuration on '").concat(t,"'").concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(e){let{fnName:t,deviceType:i=ix(t),error:r}=e;return"NotAllowedError, you have disabled ".concat(i," access, please allow the current application to use the ").concat(i).concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(e){let{fnName:t,deviceType:i=ix(t),error:r}=e;return"NotReadableError, the ".concat(i," maybe in use by another APP, please check if the device is pre-occupied by another APP.")},DEVICE_OVERCONSTRAINED_ERROR(e){let{fnName:t,deviceType:i=ix(t),error:r}=e;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(e){let{fnName:t,deviceType:i=ix(t),error:r}=e;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(i).concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_SECURITY_ERROR(e){let{fnName:t,deviceType:i=ix(t),error:r}=e;return"SecurityError, check whether the system security policy restricts the use of the ".concat(i,", and it is recommended to turn on the ").concat(i," after the user interacts with the page").concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_ABORT_ERROR(e){let{fnName:t,deviceType:i=ix(t),error:r}=e;return"AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal".concat(r?" error: ".concat(r.toString(),"."):".")},CAMERA_RECOVER_FAILED(e){let{error:t}=e;return"camera recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},MICROPHONE_RECOVER_FAILED(e){let{error:t}=e;return"microphone recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},OPERATION_FAILED(e){let{fnName:t,error:i}=e;return"'".concat(t,"' failed, reason: ").concat(null==i?void 0:i.toString())},FIREWALL_RESTRICTION:()=>"media connection failure due to firewall restrictions, please try to change your network.",EVENT_HANDLER_ERROR(e){let{eventName:t}=e;return"an error was caught on trtc.on('".concat(t,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(e){let{reason:t,error:i}=e;return"video context error ".concat(t," ").concat((null==i?void 0:i.name)||""," ").concat((null==i?void 0:i.message)||"")},SERVER_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got server error: ").concat(null==i?void 0:i.toString(),", please check the SDK documentation.")},NEED_TO_BUY(e){let{value:t,url:i}=e;return"You need to buy packages for ".concat(t,". Refer to: ").concat(i)},ACCOUNT_NO_MONEY:e=>{let{fnParams:t}=e;return"your TRTC account run out of credit, please recharge.".concat(t.sdkAppId?" SDKAppId: ".concat(t.sdkAppId):"")},OPERATION_ABORT(e){let{fnName:t}=e;return"'".concat(t,"' abort")},UNKNOWN_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' throw unknown exception").concat(i?", error: ".concat(i.toString(),"."):".")}});function ix(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var rx=class extends Error{constructor(e){let{code:t,extraCode:i,message:r="",messageParams:n,fnName:o="",originError:s}=e;var a;let c;c=r||function(e){let t,{code:i,params:r,enableDocLink:n=!1}=e,s="",a=ex[i];try{t=tx[a]}catch(o){t=tx.UNKNOWN_ERROR}return mw(t)?s=t(r):fw(t)&&(s=t),r.fnName&&!s.includes(r.fnName)&&("."!==s[s.length-1]&&(s+="."),s+=" thrown from ".concat(r.fnName,"()")),n&&(s+=" doc:"),s}({code:i||t,params:PC({fnName:o,error:s},n)}),super(c),FC(this,"name","RtcError"),FC(this,"code"),FC(this,"extraCode"),FC(this,"functionName"),FC(this,"message"),FC(this,"handler"),FC(this,"originError"),this.name=ex[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");FD?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):BD&&(e.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),e.href.length>0&&e.click()})}static convertFrom(e,t,i){let r=e;if(e instanceof tb){let{stack:n}=e,o={code:ZL.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case ZC.INVALID_PARAMETER:o.code=ZL.INVALID_PARAMETER,o.message=e.message;break;case ZC.INVALID_OPERATION:o.code=ZL.INVALID_OPERATION;break;case ZC.NOT_SUPPORTED:case ZC.NOT_SUPPORTED_H264:o.code=ZL.ENV_NOT_SUPPORTED,e.getCode()===ZC.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(Kk.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case ZC.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case ZC.SERVER_TIMEOUT:case ZC.SWITCH_ROLE_FAILED:o.code=ZL.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case ZC.API_CALL_ABORTED:o.code=ZL.OPERATION_ABORT;break;case ZC.DEVICE_NOT_FOUND:case ZC.DEVICE_AUTO_RECOVER_FAILED:case ZC.INITIALIZE_FAILED:o.code=5300,e.name&&(o.extraCode=function(e){let t;switch(e){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}(e.name));break;case ZC.UNKNOWN:break;default:o.code=ZL.OPERATION_FAILED}r=new rx(o),n&&(r.stack+=n.substr(n.indexOf("\n")))}else{if(e instanceof rx)return e;r=new rx({code:ZL.UNKNOWN_ERROR,fnName:t,originError:e})}return r}};var nx=rx,ox={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}}},sx={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}}},ax={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(fw(e)&&!document.getElementById(e))throw new nx({code:ZL.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},cx={name:"userId",required:!0,type:"string"},lx={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[$L.AUDIO_PROFILE_STANDARD,$L.AUDIO_PROFILE_STANDARD_STEREO,$L.AUDIO_PROFILE_HIGH,$L.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function dx(e,t){if(!e)throw new nx({code:ZL.INVALID_OPERATION,extraCode:5101,fnName:t})}function ux(e,t,i){if(!e)throw new nx({code:ZL.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var hx={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 nx({code:ZL.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(fw(e.roomId))throw new nx({code:ZL.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new nx({code:ZL.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new nx({code:ZL.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new nx({code:ZL.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}})}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:ax,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:ox},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&_O())throw new nx({code:ZL.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:MC(PC({},ax),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:ox}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:lx},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&_O())throw new nx({code:ZL.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:lx}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:ax,publish:{type:"boolean"},option:sx},validate(e,t,i,r,n){var o;if((null==(o=null==e?void 0:e.option)||!o.videoTrack)&&_O())throw new nx({code:ZL.ENV_NOT_SUPPORTED,extraCode:5201});if(!yO())throw new nx({code:ZL.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:ax,publish:{type:"boolean"},option:sx}},muteRemoteAudio:[cx,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[cx,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:ax,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){dx(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(ux(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new nx({code:ZL.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:MC(PC({},ax),{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){dx(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(ux(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new nx({code:ZL.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(e,t,i){if("*"!==e.userId&&_w(e.streamType))throw new nx({code:ZL.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){dx(this._room.isJoining||this._room.isJoined,i)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(e,t,i,r){if(!WO)throw new nx({code:ZL.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new nx({code:ZL.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new nx({code:ZL.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new nx({code:ZL.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});dx(this._room.isJoined,i)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(e,t,i){if(!e&&!this._room.isMainStreamPublished||e&&!this._room.isAuxStreamPublished)throw new nx({code:ZL.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:i})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(e,t,i,r){if(e.byteLength>1e3)throw new nx({code:ZL.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new nx({code:ZL.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(dx(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new nx({code:ZL.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}}},px={TRTC:hx},mx=class extends Error{};function _x(e,t){let i=Vw(e);for(let r=0;r<t.length;r++)xw(i[r],t[r]);return i}function fx(e){this._resolve=Promise.resolve(e)}function gx(e){this._reject=Promise.reject(e)}var Tx=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=_x;let i=Tx.instances.get(e);i?i.set(t,this):Tx.instances.set(e,new Map([[t,this]]))}static get(e,t){if(!t)return;let i=Tx.instances.get(e);return i&&i.get(t)||new Tx(e,t)}static gets(e,t){let i=Tx.instances.get(e),r=[];return i&&i.forEach(((e,i)=>{t.test(i)&&r.push(e)})),r}action(e,t,i){let r=t=>{var i;return 0===e?this.started=!0:3===e&&(this.started=!1),this.ops.shift(),null==(i=this.currentOp)||i.action(),t},n=t=>{var i,r;throw this.ops.shift(),0===e&&2===(null==(i=this.currentOp)?void 0:i.type)&&this.ops.shift().reject(new mx("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:fx,reject:gx};try{switch(this.state){case 1:if(0===e)throw new mx("already started");break;case 4:if(2===e)throw new mx("not started");break;default:return this.cacheOp(o)}}catch(s){return Promise.reject(s)}return this.ops.push(o),o.promise=t(...o.args).then(r,n)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new mx("already start");break;case 3:switch(e.type){case 2:throw new mx("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new mx("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new mx("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 mx("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new mx("start not allowed after update");case 0:throw new mx("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new mx("keep start")),new mx("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}},Ex=Tx;Ex.instances=new WeakMap;var Sx=new WeakMap,yx=(e,t)=>{if(t instanceof mx){let{stack:i}=t;t=new nx({code:ZL.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function vx(e,t){return WM(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let a=Ex.get(this,"string"==typeof e?e:e.call(this,...o));return a?(t&&(a.startSame=t.bind(this)),a.action(0,i.bind(this),o).catch(yx.bind(null,r))):i.apply(this,o)}))}function Ix(e,t){let{merge:i,debounce:r}=t||{};return WM(((t,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=Ex.get(this,"string"==typeof e?e:e.call(this,...s));if(!c)return t.apply(this,s);if(i&&(c.mergeUpdate=i.bind(this)),r&&r.isNeedToDebounce.apply(this,s)){let{delay:e,getKey:i}=r;return new Promise(((r,o)=>{var a,l;let d=null==(a=Sx.get(this))?void 0:a.get(i(...s));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout((()=>{if(3===c.state||4===c.state)return r();c.action(2,t.bind(this),s).catch(yx.bind(null,n)).then(r,o)}),e);Sx.has(this)?null==(l=Sx.get(this))||l.set(i(...s),{timeoutId:u,resolve:r}):Sx.set(this,new Map([[i(...s),{timeoutId:u,resolve:r}]]))}))}return c.action(2,t.bind(this),s).catch(yx.bind(null,n))}))}function Ax(e){return WM(((t,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let s="function"==typeof e?e.call(this,...n):e;if(s instanceof RegExp)return Promise.all(Ex.gets(this,s).map((e=>e.action(3,(()=>Promise.resolve()),n)))).then((()=>t.call(this,...n)));let a=Ex.get(this,s);return a?a.action(3,t.bind(this),n).catch(yx.bind(null,i)):t.apply(this,n)}))}var Rx={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",TRACK:"track",NETWORK_TIME_UPDATED:"network-time-updated"};function Cx(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function bx(e){return e===$L.QOS_PREFERENCE_CLEAR?"detail":e===$L.QOS_PREFERENCE_SMOOTH?"motion":""}var kx=class{constructor(){FC(this,"_log"),this._log=rO.createLogger({id:"fd"})}download(e,t){return HC(this,null,(function*(){let{type:i="blob"}=t||{};try{let t,r=kw();if(t=mw(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let n=kw()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(n,"ms")),OP.addSuccessEvent({key:522700,cost:kw()-r}),t.data}catch(hb){throw this._log.error("failed to download: ".concat(e,", error: ").concat(hb)),OP.addFailedEvent({key:522700,error:hb}),hb}}))}downloadWithFetch(e,t){return HC(this,null,(function*(){this._log.info("download with fetch: ".concat(e,", return type: ").concat(t));try{let i,r=yield fetch(e);if(!r.ok)throw new Error("network response was not ok");return i="arraybuffer"===t?yield r.arrayBuffer():yield r.blob(),{data:i}}catch(uk){throw uk}}))}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType=t,n.onload=()=>{200===n.status||0===n.status&&n.response?i({data:n.response}):r(new Error("XHR failed"))},n.onerror=r,n.send(null)}))}loadWasm(e,t){return HC(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=kw(),r=null,n=null;if(mw(WebAssembly.instantiateStreaming)&&!e.startsWith("data:application/octet-stream;base64,")&&!(e=>e.startsWith("file://"))(e)&&mw(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(pb){n=pb}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(pb){n=pb}if(r){let t=kw()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),OP.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),OP.addFailedEvent({key:522701,error:n}),n}))}};UC([TP({settings:{timeout:0,retries:3},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],kx.prototype,"download",1);var Dx=new kx;function Nx(e){let{TRTC:t,room:i,errorModule:r,assetsPath:n}=e;return{TRTC:t,room:i,assetsPath:n,fileDownloader:Dx,innerEmitter:LN,constants:ab,environment:zk,utils:sb,eventLogger:VN,log:this.room.getLogger(),loggerManager:rO,errorModule:r,kvStatManager:OP,rtcDectection:sO,trtc:this,clearStarted:(e,t)=>{let i=e.getAlias(),r=Ex.instances.get(this);if(r)if(t){let e=r.get(i+t);if(!e)return;e.started=!1}else r.forEach(((e,t)=>{t.startsWith(i)&&(e.started=!1)}))}}}var wx=new WeakMap;function Ox(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return WM(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{Mx.call(this,t,n,i,this._name)}catch(hb){return Promise.reject(hb)}return e.apply(this,n)}))}function Px(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return WM(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{Mx.call(this,t,n,i,this._name)}catch(hb){throw hb}return e.apply(this,n)}))}function Mx(e,t,i,r){if(Sw(e))for(let n=0;n<e.length;n++)Lx.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else Lx.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function Lx(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function s(e){return{code:ZL.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(_w(i)){if(t.required)throw new nx(s(5001));if(_w(t.defaultValue))return void(mw(t.validate)&&t.validate.call(this,i,r,n,o,this));i=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let r=0;r<t.type.length;r++)null===t.type[r]&&null===i&&(e=!0),mw(t.type[r])&&i instanceof t.type[r]&&(e=!0),fw(t.type[r])&&pw(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new nx({code:ZL.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>Aw(e)?Rw(e):fw(e)?e:pw(e)))},value:i}})}else if(!_w(t.type)&&pw(i)!==t.type)throw new nx(s(5002));if(!1===t.allowEmpty){let e=gw(i)&&(0===i||Number.isNaN(i)),t=fw(i)&&""===i.trim();if(e||t)throw new nx(s(5003))}if(t.notLessThanZero&&gw(i)&&i<0)throw new nx(s(5006));if(!_w(t.min)&&gw(i)&&i<t.min)throw new nx(s(5007));if(!_w(t.max)&&gw(i)&&i>t.max)throw new nx(s(5008));if(fw(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new nx(s(5004))}else if(mw(t.instanceOf)&&!(i instanceof t.instanceOf))throw new nx(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new nx(s(5005));let{properties:a}=t;dw(a)&&Ew(i)&&Object.keys(a).forEach((e=>{Lx.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;dw(c)&&Sw(i)&&i.forEach(((e,t)=>{Lx.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),mw(t.validate)&&t.validate.call(this,i,r,n,o,this)}function xx(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r}=e;return WM(((e,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];function c(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...s);if(s[e.argIndex]===t)return e.value}if(t===s||e in s)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(pw(t)):(JSON.stringify(t),t)}catch(n){return"type:".concat(pw(t))}}let l=this._log||rO;s.length>0?l.info("".concat(n,"() ").concat(JSON.stringify(s,((e,t)=>c(e,t,["userSig","privateMapKey"]))))):l.info("".concat(n,"()"));let d=r?r(...s):AP[n];try{let i=e.apply(this,s),r=kw();return Iw(i)?i.then((e=>(l.info("".concat(n,"() success ").concat(t.call(this,...s))),OP.addSuccessEvent({key:d,cost:kw()-r}),e))).catch((e=>{throw e=nx.convertFrom.call(this,e,n,1===s.length?s[0]:s),l.error("".concat(n,"() failed ").concat(t.call(this,...s)," ").concat(e," params: ").concat(JSON.stringify(s,c))),OP.addFailedEvent({key:d,error:e}),e})):(OP.addSuccessEvent({key:d}),i)}catch(u){throw u=nx.convertFrom.call(this,u,n),l.error("".concat(n,"() failed ").concat(u," params: ").concat(JSON.stringify(s,c))),OP.addFailedEvent({key:d,error:u}),u}}))}var Vx=e=>WM(((t,i)=>function(r,n){return HC(this,null,(function*(){let o=this._plugins.get(r);if(!o)throw this._log.error("plugin ".concat(String(r)," is not found")),new nx({code:ZL.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(mw(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new nx({code:ZL.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return Mx.call(this,o.getValidateRule(e),[n],i,"TRTC"),t.call(this,o,n)}))})),Ux=0,Fx=class{constructor(e,t){FC(this,"player"),FC(this,"publisher"),FC(this,"mixInput"),this.mixInput=new lM(t),e.url?(this.player=new Audio(e.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(e.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(e.track),this.mixInput.connect()}updateSettings(e){!this.player||(_w(e.volume)||(this.volume=e.volume),_w(e.loop)||(this.loop=e.loop),_w(e.playbackRate)||(this.playbackRate=e.playbackRate))}updateListener(e){if(this.player){if(e.onDurationChange){let{onDurationChange:t}=e;this.player.ondurationchange=e=>{t(e.target.duration)}}if(e.onTimeUpdate){let t=e.onTimeUpdate,{player:i}=this;i.ontimeupdate=()=>{t(i.currentTime,i.duration)}}e.onEnded&&(this.player.onended=e.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(e){!this.player||e<0&&e>this.player.duration||(this.player.currentTime=e,this.publisher.currentTime=e)}play(){var e,t;return null==(e=this.publisher)||e.play(),null==(t=this.player)?void 0:t.play()}pause(){var e,t;null==(e=this.player)||e.pause(),null==(t=this.publisher)||t.pause()}stop(){var e;null==(e=this.player)||e.pause(),this.mixInput.disconnect()}setOperation(e){"pause"===e&&this.pause(),"resume"===e&&(this.pause(),this.play()),"stop"===e&&(this.pause(),this.seek(0))}set volume(e){!this.player||!this.publisher||(this.player.volume=e,this.publisher.volume=e)}set loop(e){!this.player||!this.publisher||(this.player.loop=e,this.publisher.loop=e)}set playbackRate(e){!this.player||!this.publisher||(this.player.playbackRate=e,this.publisher.playbackRate=e)}};function Bx(e,t){if(t&&"function"!=typeof t)throw new nx({code:ZL.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var Hx=class{constructor(e){this.core=e,FC(this,"log"),FC(this,"mixedMusicMap",new Map),FC(this,"cacheMusicMap",new Map),Ux+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(Ux)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat(Ux)),this.core=e}getName(){return Hx.Name}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(e){switch(e){case"start":return Hx.startValidateRule;case"update":return Hx.updateValidateRule;case"stop":return Hx.stopValidateRule}}start(e){return HC(this,null,(function*(){let{room:t}=this.core;this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:i,url:r}=e;if(this.mixedMusicMap.has(i))return;let n=this.cacheMusicMap.get(i);n?e.url?n.reset():(n.mixInput.replaceSource(e.track),n.mixInput.connect()):(n=new Fx(e,t.audioManager),this.cacheMusicMap.set(i,n)),n.updateListener(e),n.updateSettings(e),yield n.play(),this.mixedMusicMap.set(i,n),this.log.info("start mix audio track ".concat(i," success.")),OP.addEnum({key:502700,value:3}),this.kvUpload(e)}))}update(e){return HC(this,null,(function*(){let{id:t,operation:i,seekFrom:r,playbackRate:n}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let o=this.mixedMusicMap.get(t);o?(o.updateSettings(e),o.updateListener(e),_w(i)||o.setOperation(i),_w(r)||o.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return HC(this,arguments,(function(e){var t=this;let{id:i}=e;return function*(){var e;t.mixedMusicMap.has(i)&&(t.log.info("remove music source, music id: ".concat(i)),null==(e=t.mixedMusicMap.get(i))||e.stop(),t.mixedMusicMap.delete(i)),"*"===i&&t.destroyAllMusic()}()}))}kvUpload(e){let{track:t,loop:i,volume:r,playbackRate:n,operation:o,seekFrom:s,onTimeUpdate:a,onDurationChange:c,onEnded:l}=e;t&&OP.addCount({key:502711}),i&&OP.addCount({key:502703}),r&&OP.addCount({key:502704}),n&&OP.addCount({key:502705}),o&&OP.addCount({key:502706}),s&&OP.addCount({key:502707}),"function"!=typeof a&&OP.addCount({key:502709}),"function"!=typeof l&&OP.addCount({key:502710}),"function"!=typeof c&&OP.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>this.stop({id:t})))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},jx=Hx;FC(jx,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(e,t,i){if(e.url&&"*"!==e.url){let t=e.url.split("?")[0],r=["mp3","ogg","wav","flac"],n=t.split(".").pop(),o=r.indexOf(n)>=0,s=t.startsWith("blob"),a=t.startsWith("data");if(!(o||s||a))throw new nx({code:ZL.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new nx({code:ZL.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});Bx("onTimeUpdate",e.onTimeUpdate),Bx("onEnded",e.onEnded),Bx("onDurationChange",e.onDurationChange)}}),FC(jx,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(e,t,i){Bx("onTimeUpdate",e.onTimeUpdate),Bx("onEnded",e.onEnded),Bx("onDurationChange",e.onDurationChange)}}),FC(jx,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),FC(jx,"Name","AudioMixer");var Wx,Gx=e=>(e=Number(e))>0&&e<14e8,Jx=0,Kx=class{constructor(e){this.core=e,FC(this,"log"),FC(this,"audioContext",oM()),FC(this,"workletNode"),Jx+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(Jx)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(Jx)),e.assetsPath&&this.preload("".concat(e.assetsPath,"/denoiser-wasm.js"))}static startValidateRule(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(t,i,r,n){if(!e.room.audioManager.hasAudioTrack)throw new nx({code:ZL.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return Wx||(Wx=this.doPreload(e)),Wx}doPreload(e){return HC(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield iM(this.audioContext,i)}finally{URL.revokeObjectURL(i)}}))}getName(){return Kx.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(e){switch(e){case"start":return Kx.startValidateRule(this.core);case"update":return Kx.updateValidateRule;case"stop":return Kx.stopValidateRule}}start(e){return HC(this,null,(function*(){let{room:t}=this.core;if(yield this.preload("".concat(e.assetsPath,"/denoiser-wasm.js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:i,sign:r,status:n,message:o}=yield function(e){return HC(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:r,timestamp:n}=e;return function*(){let e="https://".concat(function(e){let t;return t=Gx(e)?qx.MAIN_OVERSEA:qx.MAIN,t}(t),"/api/v1/audioAiAuth?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(r,"&timestamp=").concat(n),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d="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)}}()}))}(MC(PC({},e),{timestamp:t}));if(!i)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(i,". Message: ").concat(o)),new nx({code:ZL.INVALID_PARAMETER,message:o});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(e.sdkAppId),userId:e.userId,timestamp:t,sign:r,status:n}}),this.workletNode.port.onmessage=e=>{let{data:t}=e;"cost"===t.type&&this.log.debug("[RTCAIDenoiser] ".concat(t.value))}}this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})}))}update(){return HC(this,null,(function*(){}))}stop(){return HC(this,null,(function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)}))}destroy(){}},zx=Kx;FC(zx,"updateValidateRule",{type:"object"}),FC(zx,"stopValidateRule",{type:"object"}),FC(zx,"Name","AIDenoiser");var qx={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};var Yx=VC(jC(),1),Qx=class extends Yx.EventEmitter{constructor(){super(),this.state="nominal",this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return HC(this,null,(function*(){if(!this.observer)try{"PressureObserver"in window&&!oD&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(ub){VN.uploadEvent({log:"stat-pressure-detector-start-failed",error:ub})}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&rO.info("".concat(i.source,": ").concat(i.state)),this.emit("state-changed",{type:i.source,state:this.state})}destroy(){var e;try{null==(e=this.observer)||e.disconnect(),this.observer=null}catch(uk){VN.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:uk})}}},Xx=new Qx,$x=0,Zx=class{constructor(e){this.core=e,FC(this,"log"),FC(this,"_seiMessageList",[]),FC(this,"_smallSeiMessageList",[]),FC(this,"_subStreamSeiMessageList",[]),FC(this,"_seiWorker"),$x++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat($x)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat($x)),this.core=e}encode(e,t){try{let i=oV(e,8===t?this._smallSeiMessageList:2===t?this._subStreamSeiMessageList:this._seiMessageList);i&&this.log.debug("".concat(i," sei sent"))}catch(uk){this.log.warn(uk)}return e}decode(e,t){return sV(e).forEach((e=>{this.core.trtc.emit(Rx.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:t.userId,streamType:2===t.mediaType?"sub":"main"})})),e}destroy(){}getValidateRule(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}start(e){jO?(this._seiWorker=function(){let e=[nV,iV,rV,tV,oV,sV,aV,cV],t=()=>{let e=[],t=[],i=[];self.onmessage=r=>{r.data.isMain?(e.push(r.data.message),r.data.small&&i.push(r.data.message)):t.push(r.data.message)},self.onrtctransform=r=>{let{options:n}=r.transformer,o=n.isReceiver?cV(n.userId,n.streamType):aV(n.isMain?n.small?i:e:t);r.transformer.readable.pipeThrough(o).pipeTo(r.transformer.writable)}},i="(()=>{".concat([iL].map((e=>"const ".concat(e.name,"=(()=>").concat(e.toString(),")()"))).join("\n"),"\n").concat(e.map((e=>e.toString())).join("\n"),";(").concat(t,")()})()"),r=new Blob([i],{type:"text/javascript"}),n=URL.createObjectURL(r),o=new Worker(n);return URL.revokeObjectURL(n),o}(),this._seiWorker.onmessage=e=>{this.core.trtc.emit(Rx.SEI_MESSAGE,MC(PC({},e.data),{streamType:Cx(e.data.streamType)}))},this._seiWorker.onerror=e=>{this.log.error("seiWorker error: ",e.message)},this.core.room.videoManager.enableSEI({seiWorker:this._seiWorker})):this.core.room.videoManager.enableSEI({encoder:this.encode.bind(this),decoder:this.decode.bind(this)})}stop(e){this.core.room.videoManager.disableSEI()}update(e){let{buffer:t,options:i}=e;var r;let n=[i.seiPayloadType,t],o=!!i.small;i.toSubStream?this._subStreamSeiMessageList.push(n):(this._seiMessageList.push(n),o&&this._smallSeiMessageList.push(n)),this.core.innerEmitter.emit("265",{room:this.core.room,data:n,isMain:!i.toSubStream}),null==(r=this._seiWorker)||r.postMessage({message:n,isMain:!i.toSubStream,small:o})}getName(){return Zx.Name}getAlias(){return"sei"}getGroup(){return"sei"}},eV=Zx;function tV(e){let[t,i]=e,r=i.byteLength,n=parseInt(String(r/255),10),o=r%255,s=[];s.push(0,0,0,1,6,t);for(let c=0;c<n;c++)s.push(255);s.push(o);let a=new DataView(i);return s.push(...new Uint8Array(a.buffer)),s.push(128),new iL(new DataView(new Uint8Array(s).buffer),!0)}function iV(e){return"empty"===e.type||0===e.data.byteLength}function rV(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}function nV(e){let t=0,i=0,r=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(r.getUint8(n)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}function oV(e,t){if(t.length>0&&e.data.byteLength>0){let i=9-nV(e.data);if(i<=0)return 0;let r=t.splice(0,i).reverse().map(tV),n=r.reduce(((e,t)=>e+t.dataView.byteLength),0),o=new ArrayBuffer(n+e.data.byteLength),s=new DataView(o),a=new DataView(e.data),c=0;for(let e=0;e<r.length;e++)for(let t=0;t<r[e].dataView.byteLength;t++)s.setInt8(c++,r[e].dataView.getInt8(t));for(let t=0;t<e.data.byteLength;t++)s.setInt8(c++,a.getInt8(t));return e.data=o,r.length}return 0}function sV(e){try{let t=new DataView(e.data);if(iV(e)||!rV(t))return[];let i=[],r=0,n=-1,o=-1;for(let s=0;s<e.data.byteLength;s++){let a=t.getUint8(s);if(0===a)r++;else if(1===a){if(2===r||3===r){let a=s-r;if(-1===n?n=a:-1===o&&(o=a,i.push(new iL(new DataView(t.buffer.slice(n,o)))),n=a,o=-1),6!==t.getUint8(s+1)){e.data=t.buffer.slice(a);break}}r=0}else r=0}return i.reverse()}catch(vP){return[]}}function aV(e){return new TransformStream({transform(t,i){oV(t,e),i.enqueue(t)}})}function cV(e,t){return new TransformStream({transform(i,r){sV(i).forEach((i=>{self.postMessage({seiPayloadType:i.seiPayloadType,data:i.seiPayload.buffer,userId:e,streamType:t})})),r.enqueue(i)}})}FC(eV,"Name","SEI");var lV=0,dV=new Set,uV=null;db("5.8.1-ktv.1");var hV={RtcError:nx,ErrorCode:ZL,ErrorCodeDictionary:ex},pV=class extends XC.EventEmitter{constructor(e,t){super(),FC(this,"_room"),FC(this,"_eventListened",new Set),FC(this,"_localVideoTrack",null),FC(this,"_localAudioTrack",null),FC(this,"_localScreenTrack",null),FC(this,"_localScreenAudioTrack",null),FC(this,"_localVideoConfig",null),FC(this,"_localScreenConfig",null),FC(this,"_localAudioConfig",null),FC(this,"_remoteVideoConfigMap",new Map),FC(this,"_remoteAudioConfigMap",new Map),FC(this,"_remoteAudioMuteMap",new Map),FC(this,"_mediaTrackMap",new WeakMap),FC(this,"_log",rO.createLogger({id:"t".concat(++lV)})),FC(this,"_plugins",new Map),FC(this,"_networkQuality",null),FC(this,"_speakerId"),this._room=new e(PC({logger:this._log,frameWorkType:pV.frameWorkType},t)),this._log.debug("TRTC.create() ".concat(JSON.stringify(t,((e,t)=>"plugins"===e?t.map((e=>e.Name)):t)))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(e){return this._room.audioManager.dump(e)}}}),t.plugins&&t.plugins.forEach((e=>{this._use(e,t.assetsPath)})),this._use(jx,t.assetsPath),this._use(zx,t.assetsPath),t.enableSEI&&WO&&(this._use(eV),this.startPlugin("SEI")),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(Rx.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 nx({code:ZL.OPERATION_FAILED,extraCode:5504,messageParams:{reason:t,error:i}}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:i}=e;e.emit=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{return i.apply(e,n)}catch(hb){let i=PN({key:Jk.CATCH_HANDLER_ERROR,data:{name:t,event:n[0]},addDocLink:!1});return rO.warn("".concat(i,"\n\n").concat(hb.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,t){var i;XL&&(XL=!1,5!==rO.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Ib,"/en/index.html")),console.info("* Changelog: ".concat(Ib,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),rO.info("TRTC Web SDK Version:",lb),rO.info("UA:",navigator.userAgent),rO.info("URL: ".concat(location.href).concat("IFRAME"===(null==(i=self.frameElement)?void 0:i.tagName)?" in iframe":"")),AN().then((e=>{e&&rO.info(IN)})));let r=new pV(e,t||{});return dV.add(r),r}get room(){return this._room}_listenEvents(){_P(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(Rx.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(Rx.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(Rx.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(Rx.ERROR,nx.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(Rx.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e,this.emit(Rx.NETWORK_QUALITY,e)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{_P(t,t).add("player-state-changed",(i=>{let r=MC(PC({},i),{userId:e.userId});t.kind===Fb.VIDEO&&(r.streamType=Cx(t.streamType)),this.emit(t.kind===Fb.AUDIO?Rx.AUDIO_PLAY_STATE_CHANGED:Rx.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===ZC.PLAY_NOT_ALLOWED&&this.emit(Rx.AUTOPLAY_FAILED,{userId:t.userId})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{fP(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:r}=i,n=t.audioAvailable,o=t.videoAvailable,{audioAvailable:s,videoAvailable:a}=i;s||this._remoteAudioConfigMap.delete(r),a||this._remoteVideoConfigMap.delete("".concat(r,"_","main")),i.hasAuxiliary||this._remoteVideoConfigMap.delete("".concat(r,"_","sub")),n!==s&&(this.emit(s?Rx.REMOTE_AUDIO_AVAILABLE:Rx.REMOTE_AUDIO_UNAVAILABLE,{userId:r}),s?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i})),o!==a&&(this.emit(a?Rx.REMOTE_VIDEO_AVAILABLE:Rx.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"}),a?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"})),t.hasAuxiliary!==i.hasAuxiliary&&(this.emit(i.hasAuxiliary?Rx.REMOTE_VIDEO_AVAILABLE:Rx.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}),i.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}))})).add("sei-message",(e=>{this.emit(Rx.SEI_MESSAGE,MC(PC({},e),{streamType:Cx(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(Rx.ERROR,new nx({code:ZL.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,i,r,n,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(r=this._networkQuality)?void 0:r.downlinkRTT)||0,upLoss:(null==(n=this._networkQuality)?void 0:n.uplinkLoss)||0,downLoss:(null==(o=this._networkQuality)?void 0:o.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/Gk},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)/Gk},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(Rx.STATISTICS,l)})).add("custom-message",(e=>{this.emit(Rx.CUSTOM_MESSAGE,e)})).add("ntp-time-updated",(()=>{this.emit(Rx.NETWORK_TIME_UPDATED,{networkTime:nb()})})),_P(this,EM).add("audioInputAdded",(e=>{this.emit(Rx.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(Rx.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(Rx.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(Rx.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>HC(this,null,(function*(){if(this.emit(Rx.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),uV&&uV.deviceId===wk){let e=(yield RM()).find((e=>e.deviceId===wk));e&&uV.groupId!==e.groupId&&(uV=e,this.emit(Rx.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>HC(this,null,(function*(){this.emit(Rx.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield RM())[0];t&&uV&&(uV.deviceId===e.deviceId||uV.deviceId===wk&&uV.groupId!==t.groupId)&&(uV=t,this.emit(Rx.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))))}getNetworkTime(){return nb()}use(e){let t,i;"plugin"in e?(t=e.plugin,i=e.assetsPath):t=e,this._use(t,i||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name))return void this._log.warn("duplicate install plugin",e.Name);let i=new e(Nx.call(this,{TRTC:pV,room:this._room,errorModule:hV,assetsPath:t}));this._plugins.set(e.Name,i),e.autoStart&&(this.startPlugin(e.Name),this._log.info("auto start plugin",e.Name))}enterRoom(e){return HC(this,null,(function*(){var t,i;let{scene:r="rtc",enableAutoPlayDialog:n=!0,autoReceiveAudio:o=!0,autoReceiveVideo:s=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!fw(e.proxy)&&e.proxy.turnServer&&(null==(i=(t=this._room).setTurnServer)||i.call(t,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=n,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=s,Tw(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:"audience"===e.role?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,r,pV.frameWorkType),this._checkTrackToPublish(),Xx.start()}))}exitRoom(){return HC(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return HC(this,null,(function*(){null!=t&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),null!=t&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),"anchor"===e&&this._checkTrackToPublish()}))}destroy(){fP(this),this.removeAllListeners(),this._room.destroy(),dV.delete(this),0===dV.size&&Xx.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach((e=>{var t;return null==(t=e.destroy)?void 0:t.call(e)}))}startLocalAudio(){return HC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:i=!0,mute:r,option:n}=t,o=new tL(e._room.audioManager),s={},a={muted:!0};n&&(_w(n.microphoneId)?_w(n.audioTrack)||(s.customSource=n.audioTrack):s.deviceId=n.microphoneId,n&&gw(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),_w(n.profile)||(fw(n.profile)?xb[n.profile]&&o.setProfile(xb[n.profile]):o.setProfile(n.profile)),gw(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),_w(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),_w(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),_w(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",(t=>{e.emit(Rx.ERROR,new nx({code:ZL.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(Rx.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=nx.convertFrom(t.error)),e.emit(Rx.PUBLISH_STATE_CHANGED,MC(PC({},t),{error:i}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),_w(r)||o.setMute(r),_P(o,o).add("player-state-changed",(t=>{e.emit(Rx.AUDIO_PLAY_STATE_CHANGED,MC(PC({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localAudioTrack=o,e._localAudioConfig=MC(PC({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:a,track:o})}()}))}updateLocalAudio(e){return HC(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:r}=e,n={};r&&(r.microphoneId?yield this._localAudioTrack.switchDevice(r.microphoneId):_w(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),_w(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),_w(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!_w(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),_w(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),xw(this._localAudioConfig,e)}))}stopLocalAudio(){return HC(this,null,(function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),fP(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return HC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:i,publish:r=!0,mute:n,option:o}=t,s=new nL(e._room.videoManager),a={},c={};if(o&&(o.cameraId?a.deviceId=o.cameraId:_w(o.useFrontCamera)?_w(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?Fb.FACING_MODE_USER:Fb.FACING_MODE_ENVIRONMENT,_w(o.profile)||(fw(o.profile)?Vb[o.profile]&&s.setProfile(Vb[o.profile]):s.setProfile(o.profile)),_w(o.fillMode)||(c.objectFit=o.fillMode),_w(o.mirror)||(c.mirror=o.mirror),_w(o.small)||(DO()?fw(o.small)?s.small=Vb[o.small]:!0===o.small?s.small=Vb["120p"]:s.small=o.small:e._log.warn("small stream is not supported"))),s.on("5",(t=>{e.emit(Rx.ERROR,new nx({code:ZL.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),s.on("2",(t=>{e.emit(Rx.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),s.on("4",(t=>{let i;t.error&&(i=nx.convertFrom(t.error)),e.emit(Rx.PUBLISH_STATE_CHANGED,MC(PC({},t),{error:i}))})),e._listenOutputTrackChanged(s),yield s.capture(a),_w(n)||(yield s.setMute(n)),s.mediaTrack)if(null!=o&&o.qosPreference){let e=bx(o.qosPreference);s.mediaTrack.contentHint=e}else null!=o&&o.videoTrack||(s.mediaTrack.contentHint=bx($L.QOS_PREFERENCE_SMOOTH));_P(s,s).add("player-state-changed",(t=>{e.emit(Rx.VIDEO_PLAY_STATE_CHANGED,MC(PC({},t),{userId:"",streamType:"main"}))})),r&&e._room.isJoined&&e._room.publish(s).catch((()=>{})),e._localVideoTrack=s,e._localVideoConfig=MC(PC({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:s})}()}))}updateLocalVideo(e){return HC(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:r,option:n}=e,o={};if(n){if(_w(n.profile)||(fw(n.profile)?Vb[n.profile]&&this._localVideoTrack.setProfile(Vb[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&_w(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):_w(n.useFrontCamera)?_w(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?Fb.FACING_MODE_USER:Fb.FACING_MODE_ENVIRONMENT),_w(n.fillMode)||(o.objectFit=n.fillMode),_w(n.mirror)||(o.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let e=bx(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e}if(n.small){let e=!this._localVideoTrack.small;DO()?(!0===n.small?this._localVideoTrack.small=Vb["120p"]:fw(n.small)?this._localVideoTrack.small=Vb[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),e&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else!1===n.small&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!_w(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),_w(r)||(yield this._localVideoTrack.setMute(r)),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),xw(this._localVideoConfig,e)}))}stopLocalVideo(){return HC(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),fP(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return HC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:i=null,publish:r=!0,option:n}=t,o=new cL(e._room.videoManager);o.on("4",(t=>{let i;t.error&&(i=nx.convertFrom(t.error)),e.emit(Rx.PUBLISH_STATE_CHANGED,MC(PC({},t),{error:i}))})),e._listenOutputTrackChanged(o);let s=null,a={},c={};n&&(_w(n.profile)||(fw(n.profile)?Ub[n.profile]&&o.setProfile(Ub[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(a.systemAudio=!0,a.echoCancellation=n.echoCancellation,a.noiseSuppression=n.noiseSuppression,a.autoGainControl=n.autoGainControl),_w(n.fillMode)||(c.objectFit=n.fillMode),n.videoTrack&&(a.videoTrack=n.videoTrack),n.audioTrack&&(a.audioTrack=n.audioTrack),n.captureElement&&(a.captureElement=n.captureElement),n.preferDisplaySurface&&(a.preferDisplaySurface=n.preferDisplaySurface));let l=yield o.capture(a);if(null!=n&&n.qosPreference){let e=bx(n.qosPreference);o.mediaTrack.contentHint=e}else null!=n&&n.videoTrack||(o.mediaTrack.contentHint=bx($L.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(Fb.ENDED,(()=>{e._stopScreenShare(),e.emit(Rx.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(s=new lL(e._room.audioManager),s.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&s.setAudioOutput(e._speakerId)),_P(o,o).add("player-state-changed",(t=>{e.emit(Rx.VIDEO_PLAY_STATE_CHANGED,MC(PC({},t),{userId:"",streamType:"sub"}))})),r&&e._room.isJoined){let t=[o];s&&t.push(s),e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=o,e._localScreenAudioTrack=s,e._localScreenConfig=MC(PC({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:o})}()}))}updateScreenShare(e){return HC(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(_w(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let e=bx(r.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}this._room.isJoined&&!_w(i)&&(i&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch((()=>{}))),this._localScreenConfig.publish&&!i&&(this._room.unpublish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch((()=>{})))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),xw(this._localScreenConfig,e)}))}stopScreenShare(){return HC(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return HC(this,null,(function*(){let{view:t,userId:i,streamType:r,option:n}=e,o="".concat(i,"_").concat(r);if(this._remoteVideoConfigMap.has(o))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(r));let s=this._room.remotePublishedUserMap.get(i);if(!s)return;let a={},c="main"===r?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._listenOutputTrackChanged(c),n&&(_w(n.fillMode)||(a.objectFit=n.fillMode),_w(n.mirror)||(a.mirror=n.mirror),a.canvasRender=n.canvasRender,"main"===r&&!_w(n.small)&&(s.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,c.user))),yield this._room.subscribe(c),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._emitTrackEvent(c),this._remoteVideoConfigMap.set(o,{config:e}),n&&!_w(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return HC(this,null,(function*(){var t,i;let{view:r,userId:n,streamType:o,option:s}=e,a="".concat(n,"_").concat(o),c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(n))return;let l={};s&&(_w(s.fillMode)||(l.objectFit=s.fillMode),_w(s.mirror)||(l.mirror=s.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);if("main"===o&&(null==u?void 0:u.muteState.hasVideo)&&(d=u.remoteVideoTrack),"sub"===o&&(null==u?void 0:u.muteState.hasAuxiliary)&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:h}=c;"main"===o&&s&&!_w(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:h}),xw(h,e);let p=_w(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=_w(r)?h.view:r,_=_w(null==s?void 0:s.viewRoot)?null==(i=h.option)?void 0:i.viewRoot:s.viewRoot;this._observeView({remoteTrack:d,view:m,receiveWhenViewVisible:p,viewRoot:_})}))}stopRemoteVideo(e){return HC(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return HC(this,null,(function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:n,remoteAuxiliaryTrack:o}=r;"main"===e.streamType&&(n.stop(),t.hasVideo&&i.push(n)),"sub"===e.streamType&&(o.stop(),t.hasAuxiliary&&i.push(o))}for(let e of i)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.get(e.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(e.outMediaTrack));let n=this._remoteVideoConfigMap.get("".concat(e.userId,"_").concat(e.streamType));n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete("".concat(e.userId,"_").concat(e.streamType))}))}muteRemoteAudio(e,t){return HC(this,null,(function*(){if("*"===e)if(t)yield this._stopRemoteAudio({userId:e});else{let e=[...this._room.remotePublishedUserMap.values()];for(let t of e)t.muteState.hasAudio&&!this._remoteAudioConfigMap.has(t.userId)&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)}))}setRemoteAudioVolume(e,t){if("*"===e){let e=[...this._room.remotePublishedUserMap.values()];for(let i of e)i.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);i&&i.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}startPlugin(e,t){return HC(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return HC(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return HC(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){return this.listeners(e).includes(t)||(this._log.debug("on",e),super.on(e,t,i),this._eventListened.add(e)),this}off(e,t,i){return this._log.debug("off",e),"*"===e?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,i),this}getAudioTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"};var t,i;let r,n="main";if(fw(e)?r=e:(r=e.userId,e.streamType&&(n=e.streamType)),!r)return"sub"===n?(null==(t=this._localScreenAudioTrack)?void 0:t.mediaTrack)||null:(null==(i=this._localAudioTrack)?void 0:i.mediaTrack)||null;{let e=this._room.remotePublishedUserMap.get(r);if(e)return e.remoteAudioTrack.mediaTrack}return null}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main"}=e;if(""===t){if("main"===i&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let e=this._room.remotePublishedUserMap.get(t);if(e)return"main"===i?e.remoteVideoTrack.mediaTrack:e.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{userId:t,streamType:i="main"}=e;if(t){let e=this._room.remotePublishedUserMap.get(t);if("main"===i&&(null==e?void 0:e.muteState.hasVideo))return e.remoteVideoTrack.getVideoFrame();if("sub"===i&&(null==e?void 0:e.muteState.hasAuxiliary))return e.remoteAuxiliaryTrack.getVideoFrame()}else{if("main"===i&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}setCurrentSpeaker(e){var t,i;this._speakerId=e,null==(t=this._localAudioTrack)||t.setAudioOutput(e),null==(i=this._localScreenAudioTrack)||i.setAudioOutput(e),this._room.remotePublishedUserMap.forEach((t=>t.remoteAudioTrack.setAudioOutput(e)))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return HC(this,null,(function*(){let{userId:t,option:i}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let n={};i&&(_w(i.volume)||(n.volume=i.volume));let o=r.remoteAudioTrack;this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(o),yield this._updateAudioPlayOption({playOption:n,track:o})}catch(uF){throw this._remoteAudioConfigMap.delete(t),uF}this._emitTrackEvent(o)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return HC(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 HC(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),_w(t)&&n&&n.view&&!Ow(i)){let e=Uw(n.view);e.length>0&&(yield r.play(e,i))}if(!_w(t)){let e=Uw(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return HC(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:r}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t)}catch(pb){}_w(t.muted)||i.setPlayerMute(t.muted),_w(t.volume)||i.setAudioVolume(t.volume/100)}()}))}_listenOutputTrackChanged(e){0===e.listeners("output-media-track-changed").length&&e.on("output-media-track-changed",(()=>this._emitTrackEvent(e,!1)))}_emitTrackEvent(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===i||(this._mediaTrackMap.set(e.outMediaTrack,i),this.emit(Rx.TRACK,{userId:i,streamType:Cx(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var e,t,i;let r=[];if((null==(e=this._localAudioConfig)?void 0:e.publish)&&this._localAudioTrack&&r.push(this._localAudioTrack),(null==(t=this._localVideoConfig)?void 0:t.publish)&&this._localVideoTrack&&r.push(this._localVideoTrack),null!=(i=this._localScreenConfig)&&i.publish&&(this._localScreenTrack&&r.push(this._localScreenTrack),this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack)),0!==r.length)return this._room.publish(...r).catch((()=>{}))}_observeView(e){let{remoteTrack:t,view:i,receiveWhenViewVisible:r=!1,viewRoot:n}=e;if(_w(i))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(Cx(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||Sw(i)&&0===i.length||!r)return null==s||s.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch((()=>{})));let a=o.visibleViewMap||new Map,c=-1;(!s||s.root!==n)&&(null==s||s.disconnect(),a.clear(),s=new IntersectionObserver((e=>{e.forEach((e=>{a.set(e.target,e.isIntersecting)})),clearTimeout(c),c=window.setTimeout((()=>{[...a.values()].find((e=>e))?t.isSubscribed||this._room.subscribe(t).catch((()=>{})):t.isSubscribed&&this._room.unsubscribe(t).catch((()=>{}))}),200)}),{root:n}));let l=new Set(Uw(i));a.forEach(((e,t)=>{l.has(t)||(s.unobserve(t),a.delete(t))})),l.forEach((e=>{a.set(e,!0),s.observe(e)})),s.takeRecords().forEach((e=>{a.set(e.target,e.isIntersecting)})),o.visibleViewMap=a,o.observer=s}_exitRoom(){return HC(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach((e=>{this._stopRemoteAudio({userId:e}).catch()})),[...this._remoteVideoConfigMap.keys()].forEach((e=>{let t=e.includes("main")?"main":"sub",i=e.split("_".concat(t))[0];i&&this._stopRemoteVideo({userId:i,streamType:t}).catch()})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach((e=>{fP(e.remoteAudioTrack),fP(e.remoteVideoTrack),fP(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return HC(this,null,(function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield null==(e=this._room)?void 0:e.unpublish(...t).catch((()=>{}))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),fP(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_initActiveSpeaker(){return HC(this,null,(function*(){if(uV&&!SM(uV))this.emit(Rx.DEVICE_CHANGED,{type:"speaker",action:"active",device:uV});else{let e=yield RM();if(e[0]&&!SM(e[0]))uV=e[0],this.emit(Rx.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let e=e=>{let{track:t}=e;"audio"===t.kind&&(!uV||SM(uV))&&(this._initActiveSpeaker(),LN.off("102",this._initActiveSpeaker))};LN.on("102",e)}}}))}_onAudioAvailable(e){let{userId:t}=e,i=this._remoteAudioMuteMap.has(t)?this._remoteAudioMuteMap.get(t):this._remoteAudioMuteMap.get("*");(!1===i||this._room.autoReceiveAudio&&!i)&&this._doStartRemoteAudio({userId:t}).catch((()=>{}))}_onVideoAvailable(e){let{userId:t,streamType:i}=e;if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(t);if(r){let e="main"===i?r.remoteVideoTrack:r.remoteAuxiliaryTrack;this._room.subscribe(e).then((()=>{this._emitTrackEvent(e)})).catch((()=>{}))}}_onAudioUnavailable(e){let{userId:t,muteState:i}=e;i.hasAudio&&i.audioMuted||this._stopRemoteAudio({userId:t},!1).catch((()=>{}))}_onVideoUnavailable(e){let{userId:t,streamType:i}=e;this._stopRemoteVideo({userId:t,streamType:i},!1).catch((()=>{}))}sendSEIMessage(e,t){var i;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:MC(PC({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),OP.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),OP.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){rO.setLogLevel(e),_w(t)||(t?rO.enableUploadLog():rO.disableUploadLog())}static isSupported(){return EO()}static getCameraList(){return IM(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return vM(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return RM(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(e){return HC(this,null,(function*(){(yield RM()).forEach((t=>{t.deviceId===e&&(dV.forEach((i=>{i.setCurrentSpeaker(e),i.emit(Rx.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),uV=t)}))}))}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:o,version:s}=e;switch(s&&(wP.version=s),t){case"count":wP.addCount({key:i,useUV:o});break;case"enum":wP.addEnum({key:i,value:r,useUV:o});break;case"number":wP.addNumber({key:i,value:r,split:n})}}},mV=pV;FC(mV,"_loggerManager",rO),FC(mV,"EVENT",Rx),FC(mV,"ERROR_CODE",ZL),FC(mV,"TYPE",$L),FC(mV,"frameWorkType",30),UC([xx({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?null==e?void 0:e.assetsPath:"default"}})})],mV.prototype,"use",1),UC([Ox(px.TRTC.enterRoom),vx("room",((e,t)=>{let[i]=e,[r]=t;return(i.roomId||i.strRoomId)===(r.roomId||r.strRoomId)&&i.userId===r.userId&&i.sdkAppId===r.sdkAppId})),WM((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),xx()],mV.prototype,"enterRoom",1),UC([xx()],mV.prototype,"exitRoom",1),UC([Ox(px.TRTC.switchRole),Ix("room",{merge:(e,t)=>t}),xx()],mV.prototype,"switchRole",1),UC([xx()],mV.prototype,"destroy",1),UC([Ox(px.TRTC.startLocalAudio),vx("audio",((e,t)=>{let[i]=e,[r]=t;var n,o;return(null==(n=null==i?void 0:i.option)?void 0:n.microphoneId)===(null==(o=null==r?void 0:r.option)?void 0:o.microphoneId)})),xx()],mV.prototype,"startLocalAudio",1),UC([Ox(px.TRTC.updateLocalAudio),Ix("audio",{debounce:{delay:200,getKey:()=>"".concat(lV,"-localAudio"),isNeedToDebounce:e=>{var t;return!_w(null==(t=e.option)?void 0:t.captureVolume)}}}),xx()],mV.prototype,"updateLocalAudio",1),UC([Ax("audio"),xx()],mV.prototype,"stopLocalAudio",1),UC([Ox(px.TRTC.startLocalVideo),vx("video",((e,t)=>{let[i]=e,[r]=t;var n,o;return(null==(n=null==i?void 0:i.option)?void 0:n.cameraId)===(null==(o=null==r?void 0:r.option)?void 0:o.cameraId)})),xx()],mV.prototype,"startLocalVideo",1),UC([Ox(px.TRTC.updateLocalVideo),Ix("video"),xx()],mV.prototype,"updateLocalVideo",1),UC([Ax("video"),xx()],mV.prototype,"stopLocalVideo",1),UC([Ox(px.TRTC.startScreenShare),vx("screen",(()=>!0)),xx()],mV.prototype,"startScreenShare",1),UC([Ox(px.TRTC.updateScreenShare),Ix("screen"),xx()],mV.prototype,"updateScreenShare",1),UC([xx()],mV.prototype,"stopScreenShare",1),UC([Ox(px.TRTC.startRemoteVideo),vx((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),xx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],mV.prototype,"startRemoteVideo",1),UC([Ox(px.TRTC.updateRemoteVideo),Ix((e=>"v".concat(e.userId).concat(e.streamType))),xx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],mV.prototype,"updateRemoteVideo",1),UC([Ox(px.TRTC.stopRemoteVideo),WM((e=>function(t){return HC(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)}))})),xx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],mV.prototype,"stopRemoteVideo",1),UC([Ax((e=>"v".concat(e.userId).concat(e.streamType)))],mV.prototype,"_stopRemoteVideo",1),UC([Ox(...px.TRTC.muteRemoteAudio),xx({getRemoteId:e=>e})],mV.prototype,"muteRemoteAudio",1),UC([Px(...px.TRTC.setRemoteAudioVolume),function(e,t){return WM(((i,r)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];var s,a;let c=null==(s=wx.get(this))?void 0:s.get(t(...n));c&&c>0&&clearTimeout(c);let l=window.setTimeout((()=>{i.apply(this,n)}),e);wx.has(this)?null==(a=wx.get(this))||a.set(t(...n),l):wx.set(this,new Map([[t(...n),l]]))}))}(200,(e=>e)),xx({getRemoteId:e=>e})],mV.prototype,"setRemoteAudioVolume",1),UC([Vx("start"),jM((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),vx(((e,t)=>e.getAlias()+e.getGroup(t))),xx({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>RP[e.getName()]})],mV.prototype,"startPlugin",1),UC([Vx("update"),Ix(((e,t)=>e.getAlias()+e.getGroup(t))),xx({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>CP[e.getName()]})],mV.prototype,"updatePlugin",1),UC([Vx("stop"),Ax(((e,t)=>{let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i})),xx({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>bP[e.getName()]})],mV.prototype,"stopPlugin",1),UC([Px(...px.TRTC.enableAudioVolumeEvaluation)],mV.prototype,"enableAudioVolumeEvaluation",1),UC([xx()],mV.prototype,"getVideoSnapshot",1),UC([xx()],mV.prototype,"setCurrentSpeaker",1),UC([vx((e=>"a".concat(e.userId)),(()=>!0))],mV.prototype,"_startRemoteAudio",1),UC([WM((e=>function(t){return HC(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(MC(PC({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),Ax((e=>"a".concat(e.userId)))],mV.prototype,"_stopRemoteAudio",1),UC([Ax("room")],mV.prototype,"_exitRoom",1),UC([Ax("screen")],mV.prototype,"_stopScreenShare",1),UC([Ox(...px.TRTC.sendSEIMessage),YL({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}})],mV.prototype,"sendSEIMessage",1),UC([Ox(px.TRTC.sendCustomMessage),YL({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],mV.prototype,"sendCustomMessage",1),UC([Ox(px.TRTC.create)],mV,"_create",1);var _V=mV,fV=class{constructor(){this._set=new Set,LN.on(tO.LEAVE_SUCCESS,this.delete,this)}add(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let r=this.getKey(t.userId,i||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let r=this.getKey(t.userId,t.roomId||i,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(e,t,i,r){return"".concat(i,"_").concat(t,"_").concat(e,"_").concat(r)}isJoined(e){let{userId:t,roomId:i,sdkAppId:r,room:n}=e;return"rtc"!==n.scene&&this._set.has(this.getKey(t,i,r,n.useStringRoomId))}};function gV(){return HC(this,null,(function*(){let e,t;try{let t=yield vM();e=t&&t.length}catch(u){}try{let e=yield IM();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:s}=this.checkSystemResult.detail,a=sO.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:r,h264Decode:o,vp8Encode:n,vp8Decode:s},l={browser:a.browser,os:a.os,trtc:c,devices:i},d={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};VN.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),VN.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var TV=VC(jC()),EV="1",SV="5",yV="2",vV="3",IV="5",AV="4",RV={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,UPDATE_NETWORK_TIME_RESULT:5001},CV=[RV.UPDATE_REMOTE_MUTE_STAT,RV.UPLINK_NETWORK_STATS,RV.USER_LIST_RES,RV.MUTE_RESULT,RV.SERVER_FIRST_PACKAGE_RECEIVED,RV.UPDATE_NETWORK_TIME_RESULT],bV={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result"},kV="publish_change",DV="join",NV="leave",wV="quality_report",OV="mute_uplink",PV="publish",MV="publish_state_change",LV="unpublish",xV="subscribe",VV="unsubscribe",UV="subscribe_change",FV="start_publishing",BV="stop_publishing",HV="start_push_user_cdn",jV="stop_push_user_cdn",WV="start_mcu_mix",GV="stop_mcu_mix",JV="start_publish_cdn_stream",KV="update_publish_cdn_stream",zV="stop_publish_cdn_stream",qV="get_user_list",YV="change_role",QV="update_constraint_config",XV="rebuild_pc",$V="join/v2",ZV="publish/v2",eU="subscribe/v3",tU="ability_status_report",iU="reconnect",rU="channel_msg",nU="update_network_time",oU=new Set;var sU=class extends TV.default{constructor(e){var t,i;super(),FC(this,"room"),FC(this,"url"),FC(this,"backupUrl"),FC(this,"race"),FC(this,"destroyed",!1),FC(this,"_socketInUse"),FC(this,"_socket"),FC(this,"_backupSocket"),FC(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),FC(this,"_currentState","DISCONNECTED"),FC(this,"_isReconnecting",!1),FC(this,"_seq",0),FC(this,"_log"),FC(this,"_lastMessageTime",-1),FC(this,"_connnectStartTime",-1),FC(this,"_stopConnectRetry"),FC(this,"bytesSent",0),FC(this,"bytesReceived",0),FC(this,"keepAlive",!1),FC(this,"signalDomainWhenUnifiedProxy"),this.room=e.room,this.race=!!_w(e.race)||e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,((null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0)-oU.size>0&&this.room.enableSPC&&(this.keepAlive=!0,oU.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=rO.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.signalDomainWhenUnifiedProxy&&(e+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy))),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 HC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;return function*(){if(e.isConnected)return Promise.resolve();e._log.info("connect to [".concat(e.url,", ").concat(e.backupUrl,"]").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive))),e.emitConnectionStateChanged("CONNECTING"),e._connnectStartTime=kw();let i=[e.connectWS({url:e._urlWithParam,isMain:!0,timeout:t})];e.race&&e._backupUrlWithParam!==e._urlWithParam&&i.push(e.connectWS({url:e._backupUrlWithParam,isMain:!1,timeout:t})),e._socketInUse=yield bw(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?Fb.BACKUP:Fb.MAIN),e.emitConnectionStateChanged("CONNECTED")}()}))}connectWS(e){let{url:t,timeout:i,isMain:r}=e,n=new WebSocket(t);this.bindSocket(n),r?this._socket=n:this._backupSocket=n;let o=-1;return new Promise(((e,t)=>{n.onclose=t,n.onerror=t,n.onopen=()=>e(n),i&&(o=setTimeout((()=>{this.unbindAndCloseSocket(r?Fb.MAIN:Fb.BACKUP),t(new tb({code:ZC.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),i))})).finally((()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)}))}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===Fb.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(uk){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(uk){}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?Fb.MAIN:Fb.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(Fb.MAIN),this.unbindAndCloseSocket(Fb.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Gw(e.data);let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values(RV),o=Object.keys(RV)[n.indexOf(i)],s=bV[o]||i;switch(CV.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case RV.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,this._log.info("ChannelSetup Success"),OP.addSuccessEvent({key:521701,cost:kw()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(EV,{signalInfo:this._signalInfo});else{let e=new tb({code:ZC.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:PN({key:Jk.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),OP.addFailedEvent({key:521701,error:e}),this.emit(SV,e)}break;case RV.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=r.relayOuterIp,this._signalInfo.relayInnerIp=r.relayInnerIp,this._signalInfo.relayPort=r.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(s,{data:t});break;default:this.emit(String(s),{data:t})}}reGetSignalChannelUrl(){return HC(this,null,(function*(){try{if(!this.room.joinParams)return;BN(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(ub){}}))}reconnect(){return HC(this,null,(function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:i,relayInnerIp:r,relayPort:n}=this._signalInfo,{data:o}=yield this.sendWaitForResponse({command:iU,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:bV.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),OP.addSuccessEvent({key:521702,cost:kw()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(OP.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(ub){this._log.error(ub),this.room.reJoin()}}}))}send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let i={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},r=JSON.stringify(i);return this._socketInUse.send(r),this.bytesSent+=Gw(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:o,enableLog:s=!0,addReceiveTime:a=!1}=e;return new Promise(((e,c)=>{let l=setTimeout((()=>{this.off(n,d);let e=new tb({code:ZC.API_CALL_TIMEOUT,message:PN({key:Jk.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),c(e)}),r),d=t=>{t.data.seq===u&&(clearTimeout(l),this.off(n,d),a&&(t.data.receiveTime=Date.now()),e(t))};this.on(n,d);let u=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:r=0,retryTimeout:n=0}=e;return MN({retryFunction:this.sendWaitForResponse,onError:e=>{let{retry:t}=e;this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(vV,t))},onRetrying:e=>{this._log.warn("".concat(t||i," timeout observed, retrying [").concat(e,"/").concat(r,"]"))},settings:{retries:r,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),oU.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(Fb.MAIN),this.unbindAndCloseSocket(Fb.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(e,"s"));let t=setTimeout((()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close(),this.off(bV.JOIN_ROOM_RESULT,i)}),1e3*e),i=e=>{0===e.data.code&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.off(bV.JOIN_ROOM_RESULT,i))};this.on(bV.JOIN_ROOM_RESULT,i)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(yV,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(vV):"DISCONNECTED"===e&&this.emit(IV))}};UC([TP({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn("retrying to connect ".concat(e)),e>=3&&e%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],sU.prototype,"connect",1);var aU=VC(jC()),cU=0,lU=!1,dU=new Set,uU=!1,hU=class{constructor(e){FC(this,"userId"),FC(this,"tinyId"),FC(this,"_sdpSemantics"),FC(this,"_isUplink"),FC(this,"_room"),FC(this,"_log"),FC(this,"_signalChannel"),FC(this,"_isErrorObserved",!1),FC(this,"_waitForPeerConnectionConnectedPromise"),FC(this,"_waitForPeerConnectionConnectedPromiseReject",null),FC(this,"_peerConnection",null),FC(this,"_emitter",new aU.default),FC(this,"_currentState","DISCONNECTED"),FC(this,"_isReconnecting",!1),FC(this,"_reconnectionCount",0),FC(this,"_reconnectionTimer",-1),FC(this,"_isFirstConnection",!0),FC(this,"_prevTime",-1),FC(this,"_localAddress"),FC(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=rO.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=kw())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,OP.addSuccessEvent({key:521705,cost:Math.min(kw()-this._prevTime,3e4)})):this._isReconnecting&&OP.addSuccessEvent({key:521706,cost:kw()-this._prevTime}),this._prevTime=-1}catch(vP){throw this._isFirstConnection?(this._isFirstConnection=!1,OP.addFailedEvent({key:521705,error:vP})):this._isReconnecting&&this._reconnectionCount>=3&&OP.addFailedEvent({key:521706,error:vP}),vP}}initialize(){let e={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(e),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(e){this._log.info("close connection"),this._emitter.emit("closed",e),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),dU.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 tb({code:ZC.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return sk;let e=null;if(this._isUplink){if(!OO()||0===this._peerConnection.getSenders().length)return sk;e=this._peerConnection.getSenders()[0].transport}else{if(!wO()||0===this._peerConnection.getReceivers().length)return sk;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:sk}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===ak.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===ak.FAILED||e.target.connectionState===ak.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new tb({message:r,code:ZC.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===ak.CONNECTED||e.target.connectionState===ak.COMPLETED)&&(this.logSelectedCandidate(),VN.logSuccessEvent({userId:this._room.userId,eventType:pk.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(cU=0,lU=!1,uU=!0,dU.add(this)):dU.delete(this),LN.emit(tO.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return HC(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(AO(t)){let i=e.get(t.localCandidateId),r=e.get(t.remoteCandidateId);i&&(this._log.info("local candidate: ".concat(i.candidateType," ").concat(i.protocol,":").concat(i.ip||i.address,":").concat(i.port," ").concat(i.networkType||""," ").concat("relay"===i.candidateType?"relayProtocol:".concat(i.relayProtocol):"")),this._localAddress="".concat(i.ip||i.address,":").concat(i.port)),r&&(this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port)),this._remoteAddress="".concat(r.protocol,":").concat(r.ip||r.address));break}}))}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this._currentState)return e();this._waitForPeerConnectionConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new tb({code:ZC.API_CALL_ABORTED,message:PN({key:Jk.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{LN.off(tO.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new tb({code:ZC.API_CALL_TIMEOUT,message:"connection timeout"});var i;cU+=1,i=this._signalChannel.isConnected,cU>2&&!lU&&0===dU.size&&i&&(this._log.warn("firewall restriction"),lU=!0,this._emitter.emit("firewall-restriction")),t(e)}),Rk);LN.on(tO.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",i,this)})),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally((()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}))),this._waitForPeerConnectionConnectedPromise}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(vV,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=dk()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new tb({code:this._isUplink?ZC.UPLINK_RECONNECTION_FAILED:ZC.DOWNLINK_RECONNECTION_FAILED,message:PN({key:this._isUplink?Jk.UPLINK_RECONNECTION_FAILED:Jk.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(vV,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"))}},pU=VC(QC()),mU=function(e){return pU.default.parse(e)},_U=function(e){return pU.default.write(e)};function fU(e){return Object.keys(e).filter((t=>e[t]))}var gU=class extends hU{constructor(e){super(MC(PC({},e),{isUplink:!1})),FC(this,"_flag",0),FC(this,"isRobot",!1),FC(this,"role","anchor"),FC(this,"remoteAudioTrack"),FC(this,"remoteVideoTrack"),FC(this,"remoteAuxiliaryTrack"),FC(this,"ssrc",{audio:0,video:0,auxiliary:0}),FC(this,"_isSDPExchanging",!1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new mL(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new NL(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new wL(this._room,this)}get videoCodec(){var e,t;let i=null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)?void 0:t.sdp;return i?i.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Pw(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===Fb.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let t=e.streams[0],{track:i}=e,r=t.id===Yb?Fb.MAIN:Fb.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=Fb.AUDIO;i.kind===Fb.VIDEO&&(n=r===Fb.MAIN?Fb.VIDEO:Fb.AUXILIARY);let o=this.remoteAudioTrack;n===Fb.VIDEO?o=this.remoteVideoTrack:n===Fb.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}addRRTRLine(e){let t=e.split("\r\n"),i=new Map;t.forEach(((e,r)=>{/^a=rtcp-fb:/.test(e)&&t[r+1]&&!/^a=rtcp-fb:/.test(t[r+1])&&i.set(r+1,"".concat(e.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))}));let r=[...i];for(let n=0;n<r.length;n++){let[e,i]=r[n];t.splice(e+n,0,i)}return t.join("\r\n")}addSPSDescription(e){let t=mU(e);return t.media.forEach((e=>{e.type===Fb.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),_U(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=mU(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),_U(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return HC(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===ak.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===ak.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(t," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else this.initialize(),yield this.connect(e)}catch(pb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(pb.message," ").concat(JSON.stringify(this.muteState))),new tb({code:ZC.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):pb}}))}unsubscribe(e){return HC(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:r}=e;return function*(){if("CONNECTED"===t._currentState&&("main"===r&&!t.isMainStreamSubscribed||"auxiliary"===r&&!t.isAuxStreamSubscribed))return void t._log.info("".concat(r," stream already unsubscribed"));let e=PC({},t.subscribeState);i.forEach((t=>{switch(t.mediaType){case 1:e.audio=!1;break;case 4:e.video=!1;break;case 8:e.smallVideo=!1;break;case 2:e.auxiliary=!1}}));let n="subscribe_change";Object.values(e).find((e=>!0===e))||(n="unsubscribe"),t._log.info("".concat("unsubscribe"===n?n:"subscribe"," ").concat(r," [").concat(fU(e),"]")),yield t.sendSubscription(n,e),"unsubscribe"===n&&(t.closePeerConnection(),t.emitConnectionStateChangedEvent("DISCONNECTED"))}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=VV,n=bV.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=UV,n=bV.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:r,data:i,responseCommand:n,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new tb({code:i.code,message:PN({key:Jk.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return HC(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(uk){throw e.closePeerConnection(!0),uk}}()}))}exchangeSDP(e){return HC(this,null,(function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:i}=this._peerConnection.localDescription,r={type:t,sdp:i,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:xV,commandDesc:"exchange sdp",data:r,responseCommand:bV.SUBSCRIBE_RESULT,timeout:fk});if(!this._peerConnection){let e=new tb({code:ZC.INVALID_OPERATION,message:PN({key:Jk.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(uk){throw this._isSDPExchanging=!1,uk}}))}createOffer(){return HC(this,null,(function*(){let e={voiceActivityDetection:!1};MO()&&this._sdpSemantics===gk?(this._peerConnection.addTransceiver(Fb.AUDIO,{direction:Bb.RECVONLY}),this._peerConnection.addTransceiver(Fb.VIDEO,{direction:Bb.RECVONLY}),this._peerConnection.addTransceiver(Fb.VIDEO,{direction:Bb.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield TO();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=mU(e);return t.media.forEach((e=>{var t,i;if(e.type===Fb.VIDEO){let r=new Set;e.rtp.forEach((e=>{let{payload:t,codec:i}=e;return"H264"===i&&r.add(t)})),e.fmtp.forEach((e=>{let{payload:t,config:i}=e,n=i.match(/apt=(\d+)/);n&&n[1]&&r.has(Number(n[1]))&&r.add(t)}));let n=e=>{let{payload:t}=e;return!r.has(t)};e.rtp=e.rtp.filter(n),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=null==(i=e.payloads)?void 0:i.split(" ").filter((e=>!r.has(Number(e)))).join(" ")}})),_U(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=mU(e);return t.media.forEach((e=>{e.type===Fb.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),_U(t)}(t.sdp),this._sdpSemantics===gk&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)}))}onSubscribeResult(e){return HC(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===Ek)throw new tb({code:ZC.NOT_SUPPORTED_H264,message:PN({key:Jk.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new tb({code:t,message:PN({key:Jk.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(n)),yield this._peerConnection.setRemoteDescription({type:r,sdp:n}),this.updateSSRC(n)}catch(o){throw this._log.error(o),o}}))}updateSSRC(e){try{mU(e).media.forEach((e=>{if(e.ssrcs)if(e.type===Fb.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Yb)}));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(Yb)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Qb)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(uk){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return HC(this,null,(function*(){if(!(BC(gU.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(uk){let t=hw(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}},TU=gU;UC([WM((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this._emitter.off("closed",n),r(new tb({code:ZC.API_CALL_ABORTED,message:PN({key:Jk.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],TU.prototype,"subscribe",1),UC([jM(hU.prototype.afterConnect),HM(hU.prototype.beforeConnect)],TU.prototype,"connect",1);var EU=TU,SU={voiceActivityDetection:!1},yU=class extends hU{constructor(e){super(MC(PC({},e),{isUplink:!0})),FC(this,"localMainAudioTrack",null),FC(this,"localMainVideoTrack",null),FC(this,"localAuxAudioTrack",null),FC(this,"localAuxVideoTrack",null),FC(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),FC(this,"_isPublishingAux",!1),FC(this,"_publishingLocalAudioTrack"),FC(this,"_publishingLocalVideoTrack"),FC(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}),FC(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(PO()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(i=o[2])||!i.track),n.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((e=>{e.track&&(e.track.kind===Fb.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return HC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){let e;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),r&&(t._publishingLocalVideoTrack=r),t._isPublishingAux=n,r&&!n&&r.small&&(e=t._room.videoManager.smallTrack),t.sendMediaSettings(),MO()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:e,isAuxiliary:n}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:r,smallTrack:e}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,n?(r&&(t.localAuxVideoTrack=r),i&&(t.localAuxAudioTrack=i)):(r&&(t.localMainVideoTrack=r),i&&(t.localMainAudioTrack=i)),t.installTrackMuteEvents(i,r),t.sendMutedFlag()}()}))}publishByTransceiver(e){return HC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n,isAuxiliary:o}=e;return function*(){t._log.info("publish by transceiver");let e=new MediaStream,s=null==r?void 0:r.outMediaTrack,a=null==i?void 0:i.outMediaTrack;a&&e.addTrack(a),s&&e.addTrack(s);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||Fb.AUDIO,{direction:Bb.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?Fb.VIDEO:s||Fb.VIDEO,{direction:Bb.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||Fb.VIDEO,{direction:Bb.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||Fb.VIDEO,{direction:Bb.SENDONLY,streams:[e]}),yield t.connect();else{let e=[];if(a&&(c[0].sender.track||e.push(0),yield c[0].sender.replaceTrack(a),yield t.setBandwidth({bandwidth:(null==i?void 0:i.profile.bitrate)||40,type:Fb.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:Fb.VIDEO,videoType:o?Fb.AUXILIARY:Fb.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:Fb.VIDEO,videoType:Fb.SMALL}),e.push(2))}yield t.setTransceiverDirection(Bb.SENDONLY,e),yield t.doPublishChange(),null==r||r.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),null==r||r.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()}))}publishByAddTrack(e){return HC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n}=e;return function*(){t._log.info("publish by addtrack");let e=null==r?void 0:r.outMediaTrack,o=null==i?void 0:i.outMediaTrack;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return i&&o&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(r)));let s=new MediaStream;if(o&&s.addTrack(o),e&&s.addTrack(e),o&&t._peerConnection.addTrack(o,s),e&&(t._peerConnection.addTrack(e,s),n)){let e=new MediaStream;e.addTrack(n),t._peerConnection.addTrack(n,e)}yield t.connect()}()}))}enableSmall(e){return HC(this,null,(function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(Bb.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Bb.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return HC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!PO())return i&&i.outMediaTrack&&!r&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):r&&r.outMediaTrack&&!i&&t.localMainAudioTrack?(yield t.removeTrack(r),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),void t.emitConnectionStateChangedEvent("DISCONNECTED",r));let e=r&&r===t.localAuxVideoTrack,n=null==r?void 0:r.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(yield o[0].replaceTrack(null),s.push(0),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=MC(PC({},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=MC(PC({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.setTransceiverDirection(Bb.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return HC(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:MV,data:t,responseCommand:bV.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:LV,commandDesc:"unpublish",responseCommand:bV.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===ZC.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),FO){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*r.profile.bitrate,r.small&&(this._mediaSettings.smallVideoWidth=r.small.width,this._mediaSettings.smallVideoHeight=r.small.height,this._mediaSettings.smallVideoFps=r.small.frameRate,this._mediaSettings.smallVideoBps=1e3*r.small.bitrate)}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*n.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),r&&r.outMediaTrack&&(this._mediaSettings.videoWidth=r.profile.width,this._mediaSettings.videoHeight=r.profile.height,this._mediaSettings.videoFps=r.profile.frameRate,this._mediaSettings.videoBps=1e3*r.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:QV,data:this._mediaSettings,responseCommand:bV.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return HC(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Fb.AUXILIARY:Fb.MAIN," stream")),MO()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return HC(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Fb.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),1===n&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Bb.INACTIVE&&(yield this.setTransceiverDirection(Bb.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return HC(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;PO()&&this._peerConnection.getTransceivers().findIndex((e=>"stopped"===e.direction))>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let i=this._peerConnection.getSenders().find((e=>e.track&&e.track.kind===t.kind));if(i&&i.track){this._log.warn("sender already exists, remove sender first");let e=i.track;this.removeSender(i),yield this.updateOffer("remove",e)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===Fb.VIDEO&&e instanceof nL&&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===Tk||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=mU(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===Fb.VIDEO)return!0;return!1}removeSender(e){let t=null;PO()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&mw(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return HC(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?Fb.AUXILIARY:Fb.MAIN," stream")),MO()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return HC(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Fb.AUDIO)yield i[0].sender.replaceTrack(null);else{let r=t?3:1;yield i[r].sender.replaceTrack(null),1===r&&e.small&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Bb.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return HC(this,null,(function*(){if(!lD)return;let i=!1,r=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let n=this._peerConnection.getTransceivers();if(t.forEach((t=>{n[t].direction!==e&&(n[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(Bb.INACTIVE,"|").concat(Bb.RECVONLY,"|").concat(Bb.SENDONLY,")")))&&o++,t.includes(o)){if(e===Bb.INACTIVE&&i.includes("a=".concat(Bb.RECVONLY)))return r=!0,"a=".concat(e);if(e===Bb.SENDONLY&&i.includes("a=".concat(Bb.INACTIVE)))return r=!0,"a=".concat(Bb.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}removeTrackBySender(e){return HC(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===Fb.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let t=this._peerConnection.getSenders().find((t=>t.track===e.outMediaTrack));t&&(this.removeSender(t),e.kind===Fb.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===Fb.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return HC(this,null,(function*(){var t;let i,r=null==(t=this._peerConnection)?void 0:t.getSenders();if(!r||0===r.length||!e.mediaTrack)return!1;if(i=MO()?e.kind===Fb.AUDIO?r[0]:r[1]:r.find((t=>t.track&&t.track.kind===e.kind)),!i)return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(e.kind," track on ").concat(n?Fb.AUXILIARY:Fb.MAIN," stream")),e.kind===Fb.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===Fb.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack)),!0}))}updateOffer(e,t){return HC(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(SU);lD&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(i);let r=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===Fb.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:r,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(n.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:kV,data:n,responseCommand:bV.UPDATE_OFFER_RESULT,timeout:_k,commandDesc:"update offer"}),{code:s,message:a}=o.data;0!==s&&this.checkPublishResultCode(s,a),yield this.acceptAnswer(o.data.data),i.sdp&&this.updateSSRC(i.sdp)}catch(hb){throw this._log.error(hb),hb}}))}setBandwidth(e){return HC(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!UO())return o?r===Fb.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(MO()){let t=0;r===Fb.VIDEO&&(t=n===Fb.SMALL?2:n===Fb.AUXILIARY?3:1),e=s[t]}else e=s.find((e=>e.track&&e.track.kind===r));if(e){let s=e.getParameters();(!s.encodings||0===s.encodings.length)&&(s.encodings=[{}]),s.encodings[0].maxBitrate=1e3*i;try{return yield e.setParameters(s),t._log.info("".concat(n||"").concat(r," bandwidth ").concat(i," kbps")),o}catch(a){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(a)),o)return r===Fb.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";lD&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===Fb.SMALL?n=1:i===Fb.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(o+=1,o===n?"".concat(e,"b=").concat(r,":").concat(t,"\r\n"):e)))}updateAudioBandwidthRestriction(e,t){let i="AS";return lD&&(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 HC(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(ub){throw this.closePeerConnection(!0),this.uninstallEvents(),ub}}))}exchangeSDP(){return HC(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(ub){throw ub}}))}createOffer(){return HC(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(SU);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(ub){throw ub}}))}doExchangeSDP(){let e={command:PV,responseCommand:bV.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof cL||this.localAuxVideoTrack instanceof cL,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then((e=>{let{code:t,message:i,data:r}=e.data;return 0===t?this.acceptAnswer(r):this.checkPublishResultCode(t,i)}))}setSDPDirection(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"all",r=mU(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),_U(r)}acceptAnswer(e){return HC(this,null,(function*(){var t,i,r,n,o;try{let s;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let e=(null==(t=this._publishingLocalVideoTrack)?void 0:t.profile.bitrate)||(null==(i=this.localMainVideoTrack)?void 0:i.profile.bitrate),o=(null==(r=this._publishingLocalAudioTrack)?void 0:r.profile.bitrate)||(null==(n=this.localMainAudioTrack)?void 0:n.profile.bitrate);if(e){let t=this._isPublishingAux?Fb.AUXILIARY:Fb.BIG;s=yield this.setBandwidth({bandwidth:e,type:Fb.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:Fb.AUDIO,sdp:s}))}if(s=this.removeVideoOrientation(e.sdp),null!=(o=this._publishingLocalVideoTrack)&&o.small){let{smallStreamConfig:e}=this._room;s=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:Fb.VIDEO,videoType:Fb.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this._peerConnection.setRemoteDescription(a),this._log.debug("accepted answer: ".concat(s))}catch(uF){throw this._log.error("failed to accept remote answer ".concat(uF)),uF}}))}sendMutedFlag(e){var t,i,r;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let n={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(i=this.localMainVideoTrack)||!i.muted),auxVideo:!(null==(r=this.localAuxVideoTrack)||!r.muted)};this._log.info("send muted state: ".concat(JSON.stringify(n))),this._signalChannel.send(OV,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return HC(this,null,(function*(){if(!(BC(yU.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:LV,responseCommand:bV.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(uk){let t=hw(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)&&LN.emit(tO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{mU(e).media.forEach(((e,t)=>{if(e.type===Fb.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===Tk&&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(uk){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Fb.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Fb.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Fb.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Fb.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Fb.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Ek?(this._log.error(Kk.NOT_SUPPORTED_H264ENCODE),new tb({code:ZC.NOT_SUPPORTED_H264,message:PN({key:Jk.NOT_SUPPORTED_H264ENCODE})})):new tb({code:ZC.UNKNOWN,message:PN({key:Jk.SIGNAL_RESPONSE_FAILED,data:{signalResponse:bV.PUBLISH_RESULT,code:e,message:t}})})}},vU=yU;UC([WM((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this._emitter.off("closed",n),r(new tb({code:ZC.API_CALL_ABORTED,message:PN({key:Jk.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],vU.prototype,"publish",1),UC([jM(hU.prototype.afterConnect),HM(hU.prototype.beforeConnect)],vU.prototype,"connect",1);var IU=vU,AU=class{constructor(e,t){this.room=e,FC(this,"_log"),FC(this,"_prevReportTime",0),FC(this,"_prevReport",{}),FC(this,"_prevStats",null),FC(this,"_prevEncoderImplementation",""),FC(this,"_prevAuxEncoderImpl",""),FC(this,"_prevQualityLimitationReason",""),FC(this,"_prevAuxQualityLimitationReason",""),FC(this,"_prevDecoderImplementationMap",new Map),FC(this,"totalBytesSent",0),FC(this,"totalBytesReceived",0),FC(this,"_spcStats",null),this._log=t}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return HC(this,null,(function*(){let t={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},i=e.getPeerConnection(),r=e.getSSRC();if(i)try{if((this._spcStats||(yield i.getStats())).forEach((i=>{var n,o,s;let a,c;if("outbound-rtp"===i.type)if((i.mediaType||i.kind)===Fb.VIDEO){if(i.ssrc===r.video?(a=Fb.VIDEO,c=e.localMainVideoTrack):i.ssrc===r.small?a=Fb.SMALL:i.ssrc===r.auxiliary&&(c=e.localAuxVideoTrack,a=Fb.AUXILIARY),!a)return;if(t[a].bytesSent=i.bytesSent,t[a].packetsSent=i.packetsSent,t[a].framesEncoded=i.framesEncoded,_w(i.keyFramesEncoded)||(t[a].keyFramesEncoded=i.keyFramesEncoded),_w(i.nackCount)||(t[a].nackCount=i.nackCount),_w(i.pliCount)||(t[a].pliCount=i.pliCount),_w(i.retransmittedPacketsSent)||(t[a].retransmittedPacketsSent=i.retransmittedPacketsSent),_w(i.totalEncodeTime)||(t[a].totalEncodeTime=i.totalEncodeTime),_w(i.totalPacketSendDelay)||(t[a].totalPacketSendDelay=i.totalPacketSendDelay),!_w(i.encoderImplementation)&&(a===Fb.VIDEO&&this._prevEncoderImplementation!==i.encoderImplementation||a===Fb.AUXILIARY&&this._prevAuxEncoderImpl!==i.encoderImplementation)){let t=2,r=this._prevEncoderImplementation;a===Fb.AUXILIARY&&(t=7,r=this._prevAuxEncoderImpl),LN.emit("262",{userId:e.userId,streamType:t,prevImplementation:r,implementation:i.encoderImplementation,codec:e.videoCodec,isHWCodec:i.powerEfficientEncoder}),this[a===Fb.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=i.encoderImplementation,this._log.info("".concat(a===Fb.AUXILIARY?"aux ":"","encoderImplementation change to ").concat(i.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(i.powerEfficientEncoder))}i.ssrc===r.video?!_w(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(i.qualityLimitationReason)),LN.emit("263",{userId:e.userId,reason:i.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:null==(n=e.localMainVideoTrack)?void 0:n.isQosClearFirst}),this._prevQualityLimitationReason=i.qualityLimitationReason):i.ssrc===r.auxiliary&&!_w(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevAuxQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(i.qualityLimitationReason)),LN.emit("263",{userId:e.userId,reason:i.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(o=e.localAuxVideoTrack)?void 0:o.isQosClearFirst}),this._prevAuxQualityLimitationReason=i.qualityLimitationReason)}else t.audio.bytesSent=i.bytesSent,t.audio.packetsSent=i.packetsSent;else"candidate-pair"===i.type?AO(i)&&gw(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesSent=i.bytesSent):"media-source"===i.type&&(i.kind===Fb.AUDIO?(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0,i.echoReturnLoss,i.totalSamplesDuration&&(t.audio.totalSamplesDuration=i.totalSamplesDuration)):i.kind===Fb.VIDEO&&(i.trackIdentifier===e.getVideoTrackId(Fb.VIDEO)?t.video.fpsCapture=i.framesPerSecond:i.trackIdentifier===e.getVideoTrackId(Fb.AUXILIARY)?t.auxiliary.fpsCapture=i.framesPerSecond:t.small.fpsCapture=i.framesPerSecond));if(!_w(i.audioLevel)&&(null==(s=e.localMainAudioTrack)?void 0:s.mediaTrack)&&i.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(t.audio.audioLevel=i.audioLevel||0),!_w(i.frameWidth)){let n=Fb.SMALL;i.trackIdentifier===e.getVideoTrackId(Fb.VIDEO)||i.ssrc===r.video?n=Fb.VIDEO:(i.trackIdentifier===e.getVideoTrackId(Fb.AUXILIARY)||i.ssrc===r.auxiliary)&&(n=Fb.AUXILIARY),t[n].frameWidth=i.frameWidth,t[n].frameHeight=i.frameHeight,t[n].framesSent=i.framesSent}})),e.localMainAudioTrack){let i=e.localMainAudioTrack.getInternalAudioLevel();t.audio.micAudioLevel=i,0===t.audio.audioLevel&&(t.audio.audioLevel=i)}this.totalBytesSent||(this.totalBytesSent+=t.audio.bytesSent+t.video.bytesSent+t.auxiliary.bytesSent),Object.keys(t).forEach((i=>{i===Fb.AUDIO?e.localMainAudioTrack&&(e.localMainAudioTrack.stat=t[i]):i===Fb.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=t[i]):i===Fb.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=t[i])}))}catch(n){this._log.warn("failed to getStats on sender connection ".concat(n))}return t}))}getReceiverStats(e){return HC(this,null,(function*(){let t={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},i=e.getPeerConnection();if(i)try{let{ssrc:r}=e,{muteState:n,subscribeState:o}=e;(this._spcStats||(yield i.getStats())).forEach((i=>{if("inbound-rtp"===i.type){let s=(i.mediaType||i.kind)===Fb.AUDIO;if(s){if(i.ssrc!==r.audio||!n.hasAudio)return;t.audio.packetsReceived=i.packetsReceived,t.audio.bytesReceived=i.bytesReceived,t.audio.packetsLost=i.packetsLost,i.insertedSamplesForDeceleration&&(t.audio.insertedSamplesForDeceleration=i.insertedSamplesForDeceleration),i.removedSamplesForAcceleration&&(t.audio.removedSamplesForAcceleration=i.removedSamplesForAcceleration),i.totalSamplesDuration&&(t.audio.totalSamplesDuration=i.totalSamplesDuration),i.totalSamplesReceived&&(t.audio.totalSamplesReceived=i.totalSamplesReceived),i.concealedSamples&&(t.audio.concealedSamples=i.concealedSamples);let{remoteAudioTrack:o}=e;o.stat.packetsReceived=i.packetsReceived,o.stat.bytesReceived=i.bytesReceived,o.stat.packetsLost=i.packetsLost,t.audio.p2pDelay=o.stat.end2EndDelay,t.hasAudio=!0}else{if(lD&&0===i.bytesReceived)return;let s;i.ssrc===r.video&&n.hasVideo&&(t.video.packetsReceived=i.packetsReceived,t.video.bytesReceived=i.bytesReceived,t.video.packetsLost=i.packetsLost,t.video.framesReceived=i.framesReceived,t.video.framesDecoded=i.framesDecoded,t.video.fpsDecoded=i.framesPerSecond,t.hasVideo=!0,s=e.remoteVideoTrack,n.hasSmall&&o.smallVideo&&(t.isSmallSubscribed=!0),i.decoderImplementation&&(!this._prevDecoderImplementationMap.has(t.userId)||this._prevDecoderImplementationMap.get(t.userId)!==i.decoderImplementation)&&(this._log.info("".concat(t.userId," decoderImplementation change to ").concat(i.decoderImplementation," HWDecoder: ").concat(i.powerEfficientDecoder)),LN.emit("262",{userId:this.room.userId,remoteUserId:t.userId,prevImplementation:this._prevDecoderImplementationMap.get(t.userId),implementation:i.decoderImplementation,codec:e.videoCodec,isHWCodec:i.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(t.userId,i.decoderImplementation))),i.ssrc===r.auxiliary&&n.hasAuxiliary&&(t.auxiliary.packetsReceived=i.packetsReceived,t.auxiliary.bytesReceived=i.bytesReceived,t.auxiliary.packetsLost=i.packetsLost,t.auxiliary.framesReceived=i.framesReceived,t.auxiliary.framesDecoded=i.framesDecoded,t.auxiliary.fpsDecoded=i.framesPerSecond,s=e.remoteAuxiliaryTrack,t.hasAuxiliary=!0),s&&(s.stat.packetsReceived=i.packetsReceived,s.stat.bytesReceived=i.bytesReceived,s.stat.packetsLost=i.packetsLost,s.stat.framesReceived=i.framesReceived,s.stat.framesDecoded=i.framesDecoded,i.jitterBufferDelay&&(s.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)))}i.jitterBufferDelay&&(s?(t.audio.totalJitter=i.jitterBufferDelay,t.audio.totalJitterCount=i.jitterBufferEmittedCount):i.ssrc===r.video&&n.hasVideo?(t.video.totalJitter=i.jitterBufferDelay,t.video.totalJitterCount=i.jitterBufferEmittedCount):i.ssrc===r.auxiliary&&n.hasAuxiliary&&(t.auxiliary.totalJitter=i.jitterBufferDelay,t.auxiliary.totalJitterCount=i.jitterBufferEmittedCount))}else"candidate-pair"===i.type&&AO(i)&&gw(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesReceived=i.bytesReceived);_w(i.frameWidth)||((i.trackIdentifier===e.getMainStreamVideoTrackId()||i.ssrc===r.video)&&(t.video.frameWidth=i.frameWidth,t.video.frameHeight=i.frameHeight,e.remoteVideoTrack.stat.frameWidth=i.frameWidth,e.remoteVideoTrack.stat.frameHeight=i.frameHeight),(i.trackIdentifier===e.getAuxStreamVideoTrackId()||i.ssrc===r.auxiliary)&&(t.auxiliary.frameWidth=i.frameWidth,t.auxiliary.frameHeight=i.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=i.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=i.frameHeight)),!_w(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(hb){this._log.warn("failed to getStats on receiver connection ".concat(hb))}return t}))}getStats(e,t){return HC(this,null,(function*(){let i={},r=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:i,receiverStats:r};let t=kw(),n=yield e.getStats(),o=kw();o-t>2e3&&this._log.warn("getStats cost ".concat(o-t,"ms"));let s=[],a=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);n.forEach((e=>a.has(e.type)&&s.push(e))),this._spcStats=s}e&&(i=yield this.getSenderStats(e));for(let[e,n]of t){let e=yield this.getReceiverStats(n);r.push(e)}return{senderStats:i,receiverStats:r}}))}getDifferenceValue(e,t){if(LM(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r}=e;var n;if(!LM(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*Gk,uint32_audio_energy:1e6*(t.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(e.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*Gk),t.senderStats.audio.totalSamplesDuration&&(i.msg_device_info.uint32_audio_capture_cost=t.senderStats.audio.totalSamplesDuration);let r=[];if(t.senderStats.video.bytesSent){let e={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};r.push(e)}if(t.senderStats.small.bytesSent){let e={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};r.push(e)}if(t.senderStats.auxiliary.bytesSent){let e={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};r.push(e)}let n={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:e,msg_video_status:r,msg_network_status:n}}let{statInterval:o}=this;i.msg_down_stream_info=[],t.receiverStats.forEach((e=>{let t={msg_user_info:{str_identifier:e.userId,uint64_tinyid:e.tinyId},msg_network_status:{uint32_rtt:e.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(e.hasAudio){let i={uint32_audio_p2p_delay:e.audio.p2pDelay,uint32_audio_cache_ms:e.audio.totalJitter,uint32_audio_cache_ms_count:e.audio.totalJitterCount,uint32_audio_codec_bitrate:e.audio.bytesReceived,uint32_audio_total_bitrate:e.audio.bytesReceived,uint32_audio_level:1e8*e.audio.audioLevel,uint32_audio_energy:1e6*e.audio.totalAudioEnergy,uint32_audio_receive:e.audio.packetsReceived,uint32_audio_origin_lost:e.audio.packetsLost};t.msg_audio_status=i}if(e.hasVideo){let i=r.get("".concat(e.userId,"_").concat(Xb)),n=i?i.duration:0,o={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.video.framesDecoded,uint32_video_cache_ms:e.video.totalJitter,uint32_video_cache_ms_count:e.video.totalJitterCount};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=r.get("".concat(e.userId,"_").concat($b)),n=i?i.duration:0,o={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.auxiliary.framesDecoded,uint32_video_cache_ms:e.auxiliary.totalJitter,uint32_video_cache_ms_count:e.auxiliary.totalJitterCount};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let s=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(i)),this._prevStats=JSON.parse(JSON.stringify(t)),i.msg_up_stream_info.msg_audio_status&&s.msg_up_stream_info.msg_audio_status){let e=s.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let r=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*r/o),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}null!=(n=s.msg_device_info)&&n.uint32_audio_capture_cost?i.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(s.msg_device_info.uint32_audio_capture_cost,i.msg_device_info.uint32_audio_capture_cost)/o):delete i.msg_device_info.uint32_audio_capture_cost}let c=s.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=c.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type));if(!t||0===t.uint32_video_codec_bitrate)return e.uint32_video_codec_bitrate=0,e.uint32_video_enc_fps=0,void(e.uint32_video_codec_fps=0);let r=0,n=0,s=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(r=t.uint32_video_codec_bitrate,n=t.uint32_video_enc_fps,s=t.uint32_video_codec_fps);let a=this.getDifferenceValue(r,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*a/o),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(n,e.uint32_video_enc_fps)/o),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(s,e.uint32_video_codec_fps)/o),FD&&115===rN()&&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),_w(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),_w(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),_w(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),_w(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),_w(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/o)),_w(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/o))}));let l=s.msg_down_stream_info;i.msg_down_stream_info=i.msg_down_stream_info.filter((e=>l.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid))));let d=i.msg_down_stream_info;return d.forEach((e=>{let t=l.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(LM(e.msg_audio_status)||LM(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,r=t.msg_audio_status,n=this.getDifferenceValue(r.uint32_audio_cache_ms_count,i.uint32_audio_cache_ms_count);delete i.uint32_audio_cache_ms_count,i.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(r.uint32_audio_cache_ms,i.uint32_audio_cache_ms)/n)||0;let s=this.room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);s&&(s.remoteAudioTrack.stat.jitterBufferDelay=i.uint32_audio_cache_ms),i.uint32_audio_origin_lost=this.getDifferenceValue(r.uint32_audio_origin_lost,i.uint32_audio_origin_lost),i.uint32_audio_receive=this.getDifferenceValue(r.uint32_audio_receive,i.uint32_audio_receive),i.uint32_audio_receive+=i.uint32_audio_origin_lost;let a=this.getDifferenceValue(r.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*a/o),i.uint32_audio_total_bitrate=Math.round(8*a/o)}if(e.msg_video_status&&t.msg_video_status){let i=t.msg_video_status;e.msg_video_status=e.msg_video_status.filter((e=>i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)))),e.msg_video_status.forEach((e=>{let t=i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)),r=t.uint32_video_receive,n=t.uint32_video_origin_lost,s=t.uint32_video_codec_bitrate,a=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(n,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(r,e.uint32_video_receive)+e.uint32_video_origin_lost;let l=this.getDifferenceValue(s,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/o);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/o),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/o);let u=this.getDifferenceValue(t.uint32_video_cache_ms_count,e.uint32_video_cache_ms_count);delete e.uint32_video_cache_ms_count,e.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(t.uint32_video_cache_ms,e.uint32_video_cache_ms)/u)||0}))}})),a&&t.receiverStats.forEach((e=>{if(e.audio.concealedSamples&&e.audio.totalSamplesReceived){let t=a.receiverStats.find((t=>t.userId===e.userId));if(t&&t.audio.concealedSamples&&t.audio.totalSamplesReceived){let i=e.audio.concealedSamples-t.audio.concealedSamples,r=e.audio.totalSamplesReceived-t.audio.totalSamplesReceived,n=Math.floor(i/r*1e3*o);if(n>o/5){let t=d.find((t=>t.msg_user_info.str_identifier===e.userId));t&&(t.msg_audio_status.uint32_audio_block_time=n)}}}})),i}getStatsReport(e){return HC(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:r,freezeMap:n}=e;return function*(){let e={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield t.getStats(i,r);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:n}),t._prevReportTime=Date.now(),e.msg_up_stream_info.msg_network_status.uint32_ntp=(65535&nb())>>>0,e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},RU=VC(jC()),CU=class extends RU.default{constructor(e){let{signalChannel:t,room:i}=e;super(),FC(this,"_room"),FC(this,"_signalChannel"),FC(this,"_log"),FC(this,"_uplinkRTT",0),FC(this,"_uplinkLoss",0),FC(this,"_downlinkRTT",0),FC(this,"_downlinkLoss",0),FC(this,"_downlinkPrevStatMap",new Map),FC(this,"_downlinkLossAndRTTMap",new Map),FC(this,"_interval",-1),FC(this,"_uplinkNetworkQuality",0),FC(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=rO.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(bV.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(yV,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,i;if(0!==e.data.code)return;let r=e.data.data;if(r.delay&&this.updateDelay(r.delay),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this._uplinkLoss=0,void(this._uplinkRTT=0);let n=null==(i=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:i.getPeerConnection();if(n&&this.isPeerConnectionDisconnected(n))return this.uplinkNetworkQuality=6,this._uplinkLoss=0,void(this._uplinkRTT=0);let o=r.expectAudPkg+r.expectVidPkg,s=r.recvAudPkg+r.recvVidPkg,a=o-s;0===o&&0===s||(this._uplinkLoss=a<=0?0:Math.round(a/o*100),this._uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return HC(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)===ak.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let n=0;n<t.length;n++){let e=t[n].getPeerConnection();if(!e)return;let{rtt:i,totalPacketsLost:r,totalPacketsReceived:o}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o});continue}let s=0,a=this._downlinkPrevStatMap.get(e),c=r-a.totalPacketsLost,l=o-a.totalPacketsReceived;s=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:s,userId:t[n].getUserId(),audioDelay:t[n].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[n].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach((e=>{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return;let{rtt:i,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=i,this._downlinkLoss=r,this.downlinkNetworkQuality=this.getNetworkQuality(r,i)}))}getStat(e){return HC(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!wO())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&&gw(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===Fb.AUDIO||e.mediaType===Fb.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return t}catch(r){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){"DISCONNECTED"===e.state?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):"CONNECTED"===e.state&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(e){let{state:t}=e;"DISCONNECTED"===t?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):"CONNECTED"===t&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==ak.DISCONNECTED&&e.connectionState!==ak.FAILED&&e.connectionState!==ak.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=uP.run(Vk,(()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];LN.emit(tO.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(CU.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss})}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.debug("stopped"),-1!==this._interval&&(uP.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach((e=>{let{srcTinyId:i,videoDelay:r,audioDelay:n}=e,o=t.get(i);if(o){let e=this._room.remotePublishedUserMap.get(o);null==e||e.setDelay({videoDelay:r,audioDelay:n})}}))}},bU=CU;FC(bU,"EVENT_NETWORK_QUALITY","0");var kU=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._eventMap=new Map,this._captureCostSum=0,this._captureCostCount=0,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=rO.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&mw(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];let o=t.apply(i,r);return Iw(o)?o.catch((e=>rO.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(uk){rO.error("".concat(t.name,"() error observed ").concat(uk))}}}({fn:this[e],context:this}))})),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:lb,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:"live"===this._room.scene?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,AN().then((e=>{this._basicInfo.string_os_version=kN(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),LN.on(e,t),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",(()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId}))),this.addEvent(tO.JOIN_START,this.handleJoinStart).addEvent(tO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(tO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(tO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(tO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(tO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(tO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(tO.JOIN_FAILED,this.handleJoinFailed).addEvent(tO.LEAVE_START,this.handleLeaveStart).addEvent(tO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(tO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(tO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(tO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(tO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(tO.PUBLISH_START,this.handlePublishStart).addEvent(tO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(tO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(tO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(tO.PLAY_TRACK_START,this.handlePlayStart).addEvent(tO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(tO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!vw(t)||!this.hitTest(t.room)||"PLAYING"===i&&(r===Fb.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(tO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(tO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(tO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(tO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let n=i.hasAudio||i.hasVideo||i.hasSmall,o=i.hasAuxiliary,s=r.hasAudio||r.hasVideo||r.hasSmall,a=r.hasAuxiliary;!n&&s&&this.handleRemoteStreamAdded(r.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")})).addEvent(tO.SINGLE_CONNECTION_STAT,(e=>{let{room:t,stat:i}=e;this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=i.ice,this._pathJoinRoom.int32_dtls_cost=i.dtls,this._pathJoinRoom.int32_peer_connection_cost=i.peerConnection)}))}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach(((e,t)=>LN.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),uP.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()),e.params&&(_w(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),_w(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),_w(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(e){let{room:t,detailCost:i}=e;if(this.hitTest(t)&&i){let{totalCost:e,local:t,dns:r,tcp:n,tls:o,request:s,response:a}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=r,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=o,this._pathJoinRoom.int32_schedule_request=s,this._pathJoinRoom.int32_schedule_response=a}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(e){let{room:t,error:i}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=i instanceof tb?Number(i.getExtraCode()||i.getCode()):ZC.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}handleJoinFailed(e){let{room:t,error:i}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=i.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout((()=>{this.report()})))}handleReceivedPublishUserList(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;!this.hitTest(t)||0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(e,t){var i;let r="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(r)){let n={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:MC(PC({},NU),{msg_user_info:new wU({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};n.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(r,n)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:r,subscribeState:n}=e;if(!this.hitTest(t))return;let{userId:o,tinyId:s,role:a}=i,c=new wU({userId:o,tinyId:s,role:"anchor"===a?20:21}),l=Date.now(),d="".concat(o,"_").concat(r),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=l),"main"===r?(i.muteState.hasVideo&&(n.video||n.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),i.muteState.hasAudio&&n.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):i.muteState.hasAuxiliary&&n.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l})}handleSubscribed(e){let{room:t,remotePublishedUser:i,streamType:r}=e;if(this.hitTest(t)){let e="".concat(i.userId,"_").concat(r),t=this._remoteStreamStatMap.get(e);t&&0===t.subscribedTime&&(t.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!vw(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._remoteStreamStatMap.get(i);0===(null==r?void 0:r.playStreamTime)&&(r.playStreamTime=Date.now())}handleVideoLoadedData(e){let{track:t}=e;if(!vw(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._pathMainVideoMap.get(i);r&&0===r.statsToReport.uint64_combine_first_frame_time&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=Date.now(),r=this._pathMainVideoMap.get(t),n=this._remoteStreamStatMap.get(t);if(r&&(0===r.statsToReport.uint64_render_first_frame_time&&(r.statsToReport.uint64_render_first_frame_time=i),n)){let{statsToReport:e,playStreamTime:t,subscribedTime:o}=n;0===e.uint32_video_render_first&&t-o<=100&&(e.uint32_video_render_first=i-r.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(t);if(o&&n){let{statsToReport:e,playStreamTime:t,subscribedTime:r}=n;0===e.uint32_video_render_first&&t-r<=100&&(e.uint32_video_render_first=i-o.sendSubscribeCMDTime)}}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=this._pathMainAudioMap.get(t);i&&0===i.statsToReport.uint64_play_first_frame_time&&(i.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(e){this.hitTest(e.room)&&(this._networkQuality.totalUplinkLoss+=e.uplink.loss,this._networkQuality.totalUplinkRTT+=e.uplink.rtt,this._networkQuality.count++,e.downlinks.forEach((e=>{let{rtt:t,loss:i,userId:r,videoDelay:n,audioDelay:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(s)s.totalRTT+=t,s.totalLoss+=i,n&&(s.totalVideoDelay=(s.totalVideoDelay||0)+n,s.videoDelayCount=(s.videoDelayCount||0)+1),o&&(s.totalAudioDelay=(s.totalAudioDelay||0)+o,s.audioDelayCount=(s.audioDelayCount||0)+1),s.count++;else{let e,s,a,c;n&&(s=n,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_device_info:t,msg_up_stream_info:i,msg_down_stream_info:r}=e.report;if(i.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:t,uint32_video_width:r,uint32_video_height:n}=i.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=t,this._localStreamStat.totalVideoWidth+=r,this._localStreamStat.totalVideoHeight+=n,this._localStreamStat.videoCount++}if(i.msg_audio_status){let{uint32_audio_level:e}=i.msg_audio_status;Math.floor(e/Gk*100)>0&&(this._localStreamStat.totalAudioLevel+=e/Gk,this._localStreamStat.audioLevelCount++)}r.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:r}=e,n=t.str_identifier,o=this._room.remotePublishedUserMap.get(n);if(r.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,r="".concat(n,"_").concat(t?"main":"auxiliary"),s=this._remoteStreamStatMap.get(r);if(s&&(t&&(null==o?void 0:o.remoteVideoTrack.isSubscribed)||i&&(null==o?void 0:o.remoteAuxiliaryTrack))){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*wC(10,6)))}})),i){let e="".concat(n,"_","main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&(null==o?void 0:o.remoteAudioTrack.isSubscribed)&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,o.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=o.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/Gk*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/Gk,t.audioLevelCount++))}})),t.uint32_audio_capture_cost&&(this._captureCostSum+=t.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart(e){let{room:t}=e;this.hitTest(t)&&0===this._localStreamStat.publishStartTime&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof tb?i.getExtraCode()||i.getCode():ZC.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Wb))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Kb))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Jb))>=0}hitTest(e){return e===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach(((e,t)=>{let{userId:i}=e,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(r){let{totalLoss:t,count:i,audioDelayCount:n,videoDelayCount:o,totalAudioDelay:s,totalVideoDelay:a}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),n&&s&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(s/n),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/o))}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:n}=this._room;n&&(e.statsToReport.uint32_audio_play_time=n.getDuration(t,Fb.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,Fb.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,DU);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>DU&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+DU):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>DU&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+DU):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>DU&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+DU)}getReportData(){this._basicInfo.uint32_networkType=iw();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new wU({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Lw(this._signalInfo.relayIp),uint32_client_ip:Lw(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*wC(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map((e=>e.statsToReport)),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map((e=>e.statsToReport)),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map((e=>e.statsToReport)),uint32_info_client_ip:Lw(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return qw(e),e}report(){return HC(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(vP){this._log.warn(vP)}}))}upload(e){return HC(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=yield Wk(e),r=i instanceof ArrayBuffer,n="".concat(XN(t,kb.KEY_POINT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i)),o||jk({url:n,body:i}),this.uploadKVStat(OP),this.uploadKVStat(wP)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return HC(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=MC(PC({},t.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(t);let i=yield Wk(t),r="".concat(XN(+this._room.sdkAppId,kb.KV_STAT),"&gzip=").concat(+(i instanceof ArrayBuffer)),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(r,i)),n||jk({url:r,body:i})}))}};UC([TP({settings:{timeout:500,retries:3}})],kU.prototype,"upload",1);var DU=5e3,NU={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},wU=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},OU=kU,PU=class{constructor(){FC(this,"_startTime"),FC(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=kw())}stop(){0===this._endTime&&(this._endTime=kw())}getDuration(){return 0===this._endTime?kw()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},MU=class{constructor(e){FC(this,"_room",null),FC(this,"_durationMap"),FC(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(tO.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(tO.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(tO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;var n;let{userId:o}=r;if(!this.hitTest(t))return;i.hasAudio&&!r.hasAudio&&this.stopDurationItem("".concat(o,"_","main"),Fb.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_","main"),Fb.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_","auxiliary"),Fb.VIDEO);let s=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);!s||(!i.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,Fb.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,Fb.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,Fb.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>LN.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>LN.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);if(r.muteState.hasAudio&&"main"===i)if(r.remoteAudioTrack.isSubscribed){let e=new PU,t=this._durationMap.get(o);t?this.isRecording(t.audio)||t.audio.push(e):this._durationMap.set(o,{userId:n,type:i,audio:[e],video:[]})}else this.stopDurationItem(o,Fb.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let e=new PU,t=this._durationMap.get(o);t?this.isRecording(t.video)||t.video.push(e):this._durationMap.set(o,{userId:n,type:i,audio:[],video:[e]})}else this.stopDurationItem(o,Fb.VIDEO)}handleStreamStopped(e){let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);this.stopDurationItem(o,Fb.AUDIO),this.stopDurationItem(o,Fb.VIDEO)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new PU,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===Fb.AUDIO?[n]:[],video:t===Fb.AUDIO?[]:[n]})}stopDurationItem(e,t){if(this._durationMap.has(e)){let i=this._durationMap.get(e)[t].find((e=>0===e.endTime));i&&i.stop()}}hitTest(e){return this._room===e}getDuration(e,t){return this._durationMap.has(e)?this._durationMap.get(e)[t].reduce(((e,t)=>e+t.getDuration()),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},LU=class{constructor(e){FC(this,"_room"),FC(this,"_renderFreezeMap",new Map),FC(this,"_isVideoPlayingEventFiredMap",new Map),FC(this,"_dataFreezeMap",new Map),FC(this,"_monitorFreezeData",new Map),FC(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(tO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(tO.PLAY_TRACK_START,this.onPlayTrackStart).set(tO.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);this.stopDataFreeze({key:o,userId:n,type:i})})).set(tO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let{userId:n}=r;if(i.hasVideo&&!r.hasVideo){let e="main",t="".concat(r.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:n,type:e})}if(i.hasAuxiliary&&!r.hasAuxiliary){let e="auxiliary",t="".concat(r.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:n,type:e})}})).set(tO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(vw(t)&&this.hitTest(t.room)&&n===Fb.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===Fb.MUTE?this.onVideoTrackMuted(t):r===Fb.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(tO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>LN.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>LN.off(t,e,this))),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i),n=this._dataFreezeMap.get(r),o=new PU;n?n.durationItemList.push(o):this._dataFreezeMap.set(r,{userId:t,type:i,durationItemList:[o],isFreezing(){let e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i);this.stopDataFreeze({key:r,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;!this.hitTest(t)||i.msg_down_stream_info.forEach((e=>{let t=this._room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);if(!t)return;let{userId:i,muteState:r}=t;e.msg_video_status.forEach((e=>{2===e.uint32_video_stream_type&&r.hasVideo&&!r.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"main"}),7===e.uint32_video_stream_type&&r.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"auxiliary"})}))}))}stopDataFreeze(e){let{key:t,userId:i,type:r}=e,n=this._dataFreezeMap.get(t);if(!n||!n.isFreezing())return;let o=n.durationItemList[n.durationItemList.length-1];o.stop();let s=o.getDuration();s>yk?this._monitorFreezeData.set(t,{userId:i,type:r,duration:s}):n.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return HC(this,arguments,(function(e){var t=this;let{userId:i,fps:r,type:n}=e;return function*(){let e="".concat(i,"_").concat(n),o=t._renderFreezeMap.get(e);if(r<=2){let r=kw();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:r,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(e,{userId:i,type:n,isFreeze:!0,freezeTimeline:[{startTime:r,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let e=o.freezeTimeline.pop();if(e){e.endTime=kw();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!vw(t)||!this.hitTest(t.room)||t.kind!==Fb.VIDEO||t.hasFlag)return;let i="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(i)||this._isVideoPlayingEventFiredMap.set(i,!1)}getDataFreezeDuration(e){let t={dataFreeze:0,count:0},i=this._dataFreezeMap.get(e);if(i){if(i.isFreezing()){let e=i.durationItemList[i.durationItemList.length-1];e.stop(),e.getDuration()<yk&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){let t=this._renderFreezeMap.get(e),i=0,r=0;if(t)if(t.isFreeze){let e=kw()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;i=t.renderFreezeTotal+Math.min(e,5e3),r=t.freezeTimeline.length}else i=t.renderFreezeTotal;return{renderFreeze:i,count:r}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},xU=VC(jC(),1),VU=[1,0,0,0,1,1,0,1],UU=class extends gL{constructor(e){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),e instanceof kL)try{this.setTexBuffer(VU)}catch(ub){e.destroy(ub)}}draw2d(e,t,i,r,n){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let o=super.draw2d(e,t,i,r,n);return this.ctx2d.restore(),o}return!1}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}},FU=class{constructor(e,t){this.node=e,this.layout=t,FC(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}},BU=class extends gL{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0}),FC(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new FU(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 kL&&this.inputs.forEach((e=>{if(e){let t=this.layout2texCoords(e);e.positionBuffer?this.changeBufferData(e.positionBuffer,t):e.positionBuffer=this.createBuffer(t)}}))}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return super.connect(e,...i),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex((t=>(null==t?void 0:t.node)===e))]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&(t.node.useTexture(),this.draw(t.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&this.draw2d(t.node.image,t.x,t.y,t.width,t.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:i,width:r,height:n,name:o}=this,s=Date.now(),a=(e-this.lastInfo.totalFrames)/((s-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:i,width:r,height:n,timestamp:s,fps:a,name:o},PC({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 kL))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(r){}}))}},HU=class extends RL{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log}),FC(this,"ready",!1),FC(this,"_bgTexture"),FC(this,"_waterMarkTexture"),FC(this,"_lastMaskTexture"),FC(this,"_lastMaskFbo"),FC(this,"_textureValid",!1),FC(this,"_selfieTextureValid",!1),FC(this,"_selfieSegmentation"),FC(this,"wasm"),FC(this,"_prePrograme"),FC(this,"_segmentationMask"),FC(this,"_weixin",!1),t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this)),this.init(t).catch((()=>this.context.destroy(new Error("selfie_segmentation init faild"))))}init(e){return HC(this,null,(function*(){var t,i;let r=e.Wasm,n=this.context.ctx;if(this.wasm=new r.AllIn1(n),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:i,width:r,height:n}=e.waterMark;this.wasm.setWaterMark(t,i,r,n)}if(e.beautyParams){let{beauty:r,brightness:n,ruddy:o}=e.beautyParams;this.wasm.setBeauty(r,n,o,null==(t=this.context._canvas)?void 0:t.width,null==(i=this.context._canvas)?void 0:i.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.uniform1i(n.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(n.uniform1i(n.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(n.uniform1i(n.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),n.uniform1i(n.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(n.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\nuniform sampler2D u_texture;\nuniform sampler2D mask;\n\nin vec2 v_texCoord;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);\n}"),t=this.context.createShader(n.VERTEX_SHADER,"#version 300 es\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_texCoord;\nvoid main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n v_texCoord = a_texCoord;\n}");this._prePrograme=this.context.createProgram(t,e),n.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.uniform1i(n.getUniformLocation(this._prePrograme,"mask"),1)}this.ready=!0}))}onPredict(e){var t;let i=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():null==this||this._selfieSegmentation.bindTexture(),i.activeTexture(i.TEXTURE1),null==(t=this._selfieSegmentation)||t.bindTexture2d(e),i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,this._bgTexture||null),i.activeTexture(i.TEXTURE3),i.bindTexture(i.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),i.drawArrays(i.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){var t,i,r;let n=this.context.ctx;if(mw(this.image.getVideoPlaybackQuality)&&nN){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:o,videoHeight:s}=this.image;this.image.width=o,this.image.height=s;let a=!1;if(this.totalFrames)this._weixin?this.useTexture():null==this||this._selfieSegmentation.bindTexture(),a=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),a=this._textureValid,this._textureValid=!0}return this.width===o&&this.height===s&&a?n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,this.image):(this.resize(o,s),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,this.image)),this.ready&&(this._weixin&&(n.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(n.activeTexture(n.TEXTURE1),null==(t=this._selfieSegmentation)||t.bindTexture2d(this._segmentationMask),n.bindFramebuffer(n.FRAMEBUFFER,this._lastMaskFbo||null)),n.drawArrays(n.TRIANGLE_STRIP,0,4),null==(i=this._selfieSegmentation)||i.bindTexture(),this._segmentationMask?n.copyTexSubImage2D(n.TEXTURE_2D,0,0,0,0,0,o,s):n.copyTexImage2D(n.TEXTURE_2D,0,n.RGBA,0,0,o,s,0)),null==(r=this._selfieSegmentation)||r.send(o,s)),this.totalFrames||(n.activeTexture(n.TEXTURE2),n.bindTexture(n.TEXTURE_2D,this._bgTexture||null),n.activeTexture(n.TEXTURE3),n.bindTexture(n.TEXTURE_2D,this._waterMarkTexture||null),n.drawArrays(n.TRIANGLE_STRIP,0,4)),!1}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&t.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&t.deleteProgram(this._prePrograme),null==(e=this.wasm)||e.close()}},jU=class extends xU.EventEmitter{constructor(e){super(),this.room=e,FC(this,"videoContext"),FC(this,"_glVideoContext"),FC(this,"_2dVideoContext"),FC(this,"destination"),FC(this,"smallVideoContext"),FC(this,"smallDestination"),FC(this,"smallTrackSource"),FC(this,"smallImageSource"),FC(this,"_isMirror",!1),FC(this,"cameraTrack"),FC(this,"cameraNode"),FC(this,"mirrorNode"),FC(this,"mixNode"),FC(this,"screenTrack"),FC(this,"screenNode"),FC(this,"selfModel",!1),FC(this,"blurRadius",3),FC(this,"arTrack"),FC(this,"Wasm"),FC(this,"waterMarkNode"),FC(this,"_waterMarkOption"),FC(this,"watermarkImageList",[]),FC(this,"_beautyParams"),FC(this,"isUsingArTrack",!1),FC(this,"_isMixScreen",!1),FC(this,"_virtualBackground"),FC(this,"virtualBackgroundInstance"),FC(this,"_bgAssetPath"),FC(this,"log",rO.createLogger({id:"vm"})),FC(this,"_checkId",0),FC(this,"_use2d",!1),FC(this,"_autoSwitchRenderMode",!0),FC(this,"_selfieSegmentation"),FC(this,"_seiEncodeProcessor"),FC(this,"_seiDecodeProcessor"),FC(this,"seiWorker"),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new DL({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode="auto"===e,this._autoSwitchRenderMode)return;let t="2d"===e;this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new DL({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new kL({frameRate:15,logger:this.log,name:"m"});try{this._glVideoContext.create(),this.sendCreateResult(),this._glVideoContext.on("unavailable",((e,t)=>{this.emit("error",{reason:e,error:t}),this.log.warn("video context unavailable",e,t),this.sendCreateResult("videoCtxGl",t||new Error(e)),this.update()}))}catch(ub){this.emit("error",{reason:"create",error:ub}),this.sendCreateResult("videoCtxGl",ub)}return this._glVideoContext}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=uP.run(Fk,(()=>{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(),uP.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(dN||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(){let e=arguments.length>1?arguments[1]:void 0,t="videoCtxGl"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"videoCtxGl")?512700:512701;e?OP.addFailedEvent({key:t,error:e}):OP.addSuccessEvent({key:t})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else{if(!t)return!0;if(!this._use2d)return!0;this.clear()}}else this.clear(),this._use2d=!0;return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return null==(e=this.smallDestination)?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return null==(e=this.cameraTrack)?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var t;try{let i=this.cameraTrack,{small:r,settings:n,player:o}=i;r?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new vL(this.smallVideoContext,r)),this.smallVideoContext.frameRate=r.frameRate,this.smallDestination.resolution=r,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),dN&&o.setCanvas(e);let s=e&&(null==(t=this.destination)?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),s=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info("set main output ".concat(s?s.label:"no output track")),i.setOutputMediaStreamTrack(s)}catch(hb){this.log.error("set main output failed",hb)}}update(){return HC(this,null,(function*(){var e,t;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:i,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination",logger:this.log})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(i.width,i.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new yL(this.videoContext,{name:"mainDestination",logger:this.log})),this.cameraNode=new HU(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=r.frameRate,this._use2d){let i=this.cameraNode;i.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new UU(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 BU(this.videoContext),i.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),null==(e=this.waterMarkNode)||e.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),null==(t=this.screenNode)||t.connect(this.mixNode,{zIndex:0}),i=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))),i.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext._canvas)}))}changeInput(e){var t,i,r,n;if(e instanceof cL)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof nL)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof NL){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);let t=e.mediaTrack;return this._seiDecodeProcessor&&(e.pipeline[1]=this._seiDecodeProcessor),e.setOutputMediaStreamTrack(t)}this.log.warn("change unknown input",null==(n=e.mediaTrack)?void 0:n.label)}configPipeline(e){e instanceof NL&&this._seiDecodeProcessor&&(e.pipeline[1]=this._seiDecodeProcessor)}removeInput(e){var t;e instanceof cL?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof nL?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof NL&&e.source&&e.source.context.destroy()}setCameraTrack(e){return HC(this,null,(function*(){this.cameraTrack=e,this._seiEncodeProcessor&&(this.cameraTrack.pipeline[0]=this._seiEncodeProcessor),this.update()}))}setScreenTrack(e){return this.screenTrack=e,this._seiEncodeProcessor&&(this.screenTrack.pipeline[0]=this._seiEncodeProcessor),this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return HC(this,null,(function*(){let i=document.createElement("canvas");t&&e&&(i.height=t,i.width=e);let r=i.getContext("2d");if(!r)throw new tb({code:ZC.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort(((e,t)=>e.zIndex-t.zIndex)),this.watermarkImageList.forEach((e=>{let{image:t,x:i,y:n,width:o,height:s}=e;r.drawImage(t,i,n,o,s)})),Kw(i.toDataURL())}))}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some((t=>t.imageUrl===e.imageUrl&&t.height===e.height&&t.width===e.width&&t.x===e.x&&t.y===e.y&&t.type===e.type&&t.zIndex===e.zIndex))||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==t))),this.watermarkImageList.push(e))}setBeautyParams(e){return HC(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return HC(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return HC(this,null,(function*(){let t;try{t=yield Kw((null==e?void 0:e.imageElement)||e.imageUrl)}catch(c){throw new tb({code:ZC.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:i=0,y:r=0,width:n=t.width,height:o=t.height,type:s="watermark",zIndex:a=2}=e;this.pushWaterMarkImageList({x:i,y:r,width:n,height:o,image:t,zIndex:a,type:s,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return HC(this,null,(function*(){this.watermarkImageList=this.watermarkImageList.filter((t=>t.type!==e)),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()}))}freshWatermark(){return HC(this,null,(function*(){var e,t,i;null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let r=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(i=this.cameraTrack)?void 0:i.settings.height);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()}))}setVirtualBackground(e){return HC(this,null,(function*(){if(e){if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,"image"===e.type?this._virtualBackground=yield Kw(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}else this._virtualBackground=void 0;this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat((null==e?void 0:e.type)||"",", ").concat(this.blurRadius||"")),this.update()}))}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return HC(this,null,(function*(){var e;null==(e=this.cameraTrack)||!e.mediaTrack||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))}))}disableAr(){var e;this.isUsingArTrack=!1,null==(e=this.arTrack)||e.stop(),this.arTrack=void 0,this.update()}clear(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}enableSEI(e){let{encoder:t,decoder:i,seiWorker:r}=e;r?this.seiWorker=r:(this._seiEncodeProcessor=t,this._seiDecodeProcessor=i,this.cameraTrack&&(this.cameraTrack.pipeline[0]=this._seiEncodeProcessor),this.screenTrack&&(this.screenTrack.pipeline[0]=this._seiEncodeProcessor))}disableSEI(){var e;null==(e=this.seiWorker)||e.terminate(),delete this.seiWorker,delete this._seiEncodeProcessor,delete this._seiDecodeProcessor,this.cameraTrack&&(this.cameraTrack.pipeline[0]=void 0),this.screenTrack&&(this.screenTrack.pipeline[0]=void 0)}},WU=0,GU=class extends sP{constructor(e){super("room"),this.seq=++WU,this.role="anchor",this.joinParams=null,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=rO.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this.isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,Tw(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Tw(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Tw(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new OU({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new MU({room:this}),this.badCaseDetector=new LU({room:this}),this.audioManager=new dL(this),this.videoManager=new jU(this)}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(4&e.mediaType)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(2&e.mediaType)return e;return null}getLogger(){return this._log}get isJoining(){return"joining"===this.state.toString()}get isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return HC(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return HC(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return HC(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(fw(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(dw(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:r,scheduleProxy:n,unifiedProxy:o}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=o,o?(WN([o,o]),Tb("https://".concat(o))):(r&&Tb(r),n&&WN(n))}LN.once(tO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:jN.main,sched_back_domain:jN.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return HC(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return HC(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 HC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"main";return function*(){let i={};return e.remotePublishedUserMap.forEach((e=>{let r="auxiliary"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;i[e.userId]=r.stat})),i}()}))}checkDestroy(){if(this.isDestroyed)throw new tb({code:ZC.INVALID_OPERATION,message:PN({key:Jk.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Kk.INVALID_DESTROY),new tb({code:ZC.INVALID_OPERATION,message:PN({key:Jk.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,LN.emit(tO.ROOM_DESTROY,{room:this})}schedule(e,t){return HC(this,null,(function*(){var i,r;let n=kw();try{let{isCached:o,result:s,detailCost:a}=yield HN({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:lb,userSig:this.userSig,role:"live"===this.scene?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=o,this._log.info("schedule cache:".concat(+o," ").concat(jw(s,{keysToExclude:["username","credential"]}))),o&&LN.once(tO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=PC(PC({},this.scheduleResult),s),gw(null==(i=s.config)?void 0:i.retryCount)&&lk(s.config.retryCount),fw(null==(r=s.config)?void 0:r.loggerDomain)&&Tb(s.config.loggerDomain),LN.emit(tO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:a}),OP.addSuccessEvent({key:521700,cost:kw()-n,split:50})}catch(o){throw OP.addFailedEvent({key:521700,error:o}),o}}))}},JU=VC(jC(),1),KU=Symbol("instance"),zU=Symbol("cacheResult"),qU=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,ZU.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},YU=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var QU=new Map;function XU(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,n,o)=>{let s=i.action||n;if(!i.context){let i=QU.get(r)||[];QU.has(r)||QU.set(r,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let r=this;for(var n=arguments.length,o=new Array(n),c=0;c<n;c++)o[c]=arguments[c];if(i.context&&(r=eF.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return r[zU];r.state instanceof qU&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;if(Array.isArray(e)?0==e.length?r.state instanceof qU&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new YU(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not in from config"))):e!==r.state&&(l=new YU(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e))),l){if(!i.fail){if(i.ignoreError)return l;throw l}i.fail.call(this,l)}let d=r.state,u=new qU(d,t,s);ZU.call(r,u);let h=e=>{var n;return r[zU]=e,u.aborted||(ZU.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[zU])),e},p=e=>{let t=e instanceof Error?e.message:String(e);if(ZU.call(r,d,e),!i.fail){if(i.ignoreError)return e;throw e}i.fail.call(this,new YU(r._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(h).catch(p):h(e)}catch(m){p(m)}}}}var $U="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 ZU(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(eF.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var eF=class extends JU.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=eF.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let r=i[KU];r?this.name=r.name+"-"+r.count++:i[KU]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=QU.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);QU.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?r.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:o})})):n.push({to:i,action:o})})),r.forEach((e=>{let{from:t,to:r,action:n}=e;o.add(t),o.add(r),o.add(n+"ing"),i.add("".concat(t," --\x3e ").concat(n,"ing : ").concat(n)),i.add("".concat(n,"ing --\x3e ").concat(r," : ").concat(n," 🟢")),i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🔴"))})),n.forEach((e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=eF.instances.get(e),t||eF.instances.set(e,t=new eF(e,void 0,Object.create(eF.prototype)))):(t=eF.instances2.get(e),t||eF.instances2.set(e,t=new eF(e.constructor.name,void 0,Object.create(eF.prototype)))),t}static getState(e){var t;return null===(t=eF.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};$U(eF.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){ZU.call(this,e)}};eF.STATECHANGED="stateChanged",eF.UPDATEAFSM="updateAFSM",eF.INIT="[*]",eF.ON="on",eF.OFF="off",eF.instances=new Map,eF.instances2=new WeakMap;var tF=VC(jC()),iF=VC(QC());function rF(e){var t;let i=[];for(let r=0;r<e.rtp.length;r++){if(["rtx","red","ulpfec"].includes(e.rtp[r].codec))continue;let n=e.fmtp.filter((t=>t.payload===e.rtp[r].payload))[0];i.push({payload:e.rtp[r].payload,codec:e.rtp[r].codec,fmtp:n?n.config:"",rate:e.rtp[r].rate,rtx:"rtx"===(null==(t=e.rtp[r+1])?void 0:t.codec)?e.rtp[r+1].payload:0,rtcpFb:((null==e?void 0:e.rtcpFb)||[]).filter((t=>t.payload===e.rtp[r].payload)).map((e=>{let{type:t,subtype:i}=e;return{id:t,params:i?[i]:[]}}))})}return i}var nF=(e,t)=>HC(void 0,null,(function*(){var i;let r=mU(e),n={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};n.ice.ufrag=String(r.media[0].iceUfrag),n.ice.password=r.media[0].icePwd||"",r.fingerprint&&(n.dtls.hash=r.fingerprint.type,n.dtls.fingerprint=r.fingerprint.hash,n.dtls.setup=r.setup||""),r.media[0].fingerprint&&(n.dtls.hash=r.media[0].fingerprint.type,n.dtls.fingerprint=r.media[0].fingerprint.hash),n.dtls.setup=r.media[0].setup||"";let o=r.media[0],s=r.media[1];o.ext&&(n.audio.extensions=o.ext.map((e=>({id:e.value,uri:e.uri})))),s.ext&&(n.video.extensions=s.ext.map((e=>({id:e.value,uri:e.uri}))));let a={codec:o.rtp[0].codec,fmtp:o.fmtp[0].config,payload:o.fmtp[0].payload,rate:o.rtp[0].rate,channel:o.rtp[0].encoding,rtcpFb:[],rtx:0};null==(i=o.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:r}=e;if(t===a.payload){let e={id:i,params:[]};r&&e.params.push(r),a.rtcpFb.push(e)}})),n.audio.codecs.push(a);let c=["h264","vp8"];return t&&c.shift(),n.video.codecs=[...rF(s)].filter((e=>c.includes(e.codec.toLocaleLowerCase()))),n.video.decoders=(yield function(){return HC(this,null,(function*(){let e=new RTCPeerConnection;e.addTransceiver(Fb.VIDEO,{direction:Fb.TRANSCEIVER_DIRECTION_RECVONLY});let t=yield e.createOffer();if(!t.sdp)return[];let i=rF(mU(t.sdp).media[0]);return e.close(),i}))}()).filter((e=>["h264","vp8"].includes(e.codec.toLocaleLowerCase()))),n})),oF=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,o=mU(r),s={extmapAllowMixed:"extmap-allow-mixed",groups:o.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},a={candidates:t.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:Fb.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:o.media[0].port,protocol:o.media[0].protocol,type:Fb.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map((e=>({payload:t.audio.codecs[0].payload,type:e.id,subtype:e.params[0]}))),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};return s.media.push(a),[1,2,3].forEach((e=>{s.media.push(sF({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),n&&s.media.push(o.media.find((e=>"dc"===e.mid))),_U(s)},sF=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,isDownlink:o=!1}=e,s={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:Fb.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(t),payloads:"",port:n.media[0].port,protocol:n.media[0].protocol,type:Fb.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(o)(i.video.decoders||i.video.codecs).forEach((e=>{aF(s,e)}));else{let e=i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264"))),t=i.video.codecs[e]||r.video.codecs[0];aF(s,t)}return s},aF=(e,t)=>{e.payloads="".concat(e.payloads," ").concat(t.payload).trim(),e.fmtp.push({payload:t.payload,config:t.fmtp}),e.rtcpFb=[...e.rtcpFb||[],...(t.rtcpfb||t.rtcpFb).map((e=>({payload:t.payload,type:e.id,subtype:e.params[0]})))],e.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(e.payloads="".concat(e.payloads," ").concat(t.rtx),e.fmtp.push({payload:t.rtx,config:"apt=".concat(t.payload)}),e.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))};var cF=(e,t,i)=>{let r=iF.default.parse(e);return r.media.forEach(((e,n)=>{var o;(e.type===Fb.AUDIO||e.type===Fb.VIDEO)&&(function(e){if(!e.rtcpFb)return;let t=[];e.rtcpFb.forEach(((i,r)=>{var n;t.push(i),e.rtcpFb&&(null==(n=e.rtcpFb[r+1])?void 0:n.payload)!==i.payload&&"rrtr"!==i.type&&t.push({payload:i.payload,type:"rrtr"})})),e.rtcpFb=t}(e),function(e){e.type===Fb.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===Fb.AUDIO&&e.fmtp&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))}(e),function(e){let t=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}(e),e.type===Fb.VIDEO&&(n<4?(e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach((t=>aF(e,t)))):i&&(e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],(i.video.decoders||i.video.codecs).forEach((t=>aF(e,t)))))),(null==(o=e.payloads)?void 0:o.includes("datachannel"))&&r.groups&&e.mid&&(r.groups[0].mids=r.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),iF.default.write(r)},lF=VC(jC()),dF=class extends lF.EventEmitter{constructor(e){super(),this.room=e,FC(this,"mainFpsHealth",1),FC(this,"mainBitrateHealth",1),FC(this,"badMainBitrateHealthCount",0),FC(this,"lastEmitBadHealthTime",0),FC(this,"log"),!oD&&nN&&LN.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged(e){let{remoteUserId:t,streamType:i,isHWCodec:r,codec:n}=e;if(!t&&7!==i&&"h264"===n){if(!r)return void this.room.off("heartbeat-report",this.onHeartbeatReport,this);this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<3e4||(e.msg_up_stream_info.msg_video_status.forEach((e=>{if(e.uint32_video_enc_fps&&e.uint32_video_capture_fps){let t=e.uint32_video_enc_fps/e.uint32_video_capture_fps;2===e.uint32_video_stream_type&&(this.mainFpsHealth=t)}if(e.uint32_video_codec_bitrate&&2===e.uint32_video_stream_type){let{localMainVideoTrack:t}=this.room;t&&(this.mainBitrateHealth=e.uint32_video_codec_bitrate/1e3/t.profile.bitrate)}})),this.log.debug("mainBitrateHealth: ".concat(this.mainBitrateHealth," mainFpsHealth: ").concat(this.mainFpsHealth)),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn("bad main bitrate health: ".concat(this.mainBitrateHealth)),this.emit("1",{isAux:!1}))))}destroy(){LN.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};FC(dF,"EVENT_BAD_HEALTH","bad_health");var uF,hF=dF,pF=((uF=pF||{}).TRACK="track",uF.DATA_CHANNEL_MESSAGE="data_channel_msg",uF[uF.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",uF[uF.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",uF.RECONNECTED="spc-reconnected",uF.RECONNECT_FAILED="spc-reconnect-failed",uF.ERROR="error",uF.SEI_MESSAGE="sei-message",uF),mF=0,_F=!1,fF=new Set,gF=1,TF=class extends tF.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),FC(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),FC(this,"currentState","DISCONNECTED"),FC(this,"_room"),FC(this,"_signalChannel"),FC(this,"_peerConnection",null),FC(this,"_datachannel",null),FC(this,"_enableCustomMessage"),FC(this,"_log"),FC(this,"_downlinkMIDMap",new Map),FC(this,"_downlinkMIDUserIDMap",new Map),FC(this,"_reconnectionTimer",-1),FC(this,"reconnectionCount",0),FC(this,"clientAbility"),FC(this,"_serverAbility",null),FC(this,"addDownlinkQueue",new Set),FC(this,"removeDownlinkQueue",new Set),FC(this,"_parsedAnswer",null),FC(this,"_updateSDPPromise",null),FC(this,"_waitForPCConnectedPromise"),FC(this,"_waitForPCConnectedPromiseReject",null),FC(this,"_isSDPLogged",!1),FC(this,"enableInsertableStreams",!1),FC(this,"insertableStreamsAbortMap",new Map),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=rO.createLogger({id:"spc".concat(gF++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&HO&&(this.enableInsertableStreams=!0),this._room.healthDetector.on("1",(e=>{let{isAux:t}=e;this.useHWEncoder(!1,t?7:2)}))}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((e=>"h264"===e.codec.toLowerCase()))),e}addAbortController(e,t){var i;null==(i=this.insertableStreamsAbortMap.get(e))||i.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find((e=>"vp8"===e.codec.toLowerCase()))),e}get videoCodec(){var e,t;let i=null==(e=this._parsedAnswer)?void 0:e.media[1].rtp.find((e=>["h264","vp8"].includes(e.codec.toLowerCase())));return i?i.codec.toLowerCase():null!=(t=this._serverAbility)&&t.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return null!=(e=this._serverAbility)&&e.video.decoders.find((e=>"h264"===e.codec.toLowerCase()))?"h264":"vp8"}get isUsingH264(){return"h264"===this.videoCodec}get is42001fSupported(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f")))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=mU(e),i={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach(((e,t)=>{var r;if(e.ssrcs&&!_w(e.ssrcs[0].id)){let n=Number(e.ssrcs[0].id),o=Number(null==(r=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:r.id);switch(t){case 0:i.audioSsrc=n;break;case 1:i.bigVideoSsrc=n,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=n,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=n,i.auxVideoRtxSsrc=o}}})),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}initialize(){return HC(this,null,(function*(){var e;let t;try{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let e=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(e)),"checking"===e&&0===this.stat.iceStartTime?this.stat.iceStartTime=Date.now():"connected"===e&&0===this.stat.iceEndTime&&(this.stat.iceEndTime=Date.now())},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 SF(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(Fb.AUDIO,{direction:Fb.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Fb.VIDEO,{direction:Fb.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Fb.VIDEO,{direction:Fb.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Fb.VIDEO,{direction:Fb.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield nF(t.sdp,(null==(e=this._room.scheduleResult.config)?void 0:e.remove264FromSDP)||!1),yield this.setOffer(t),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;!e||(this._log.debug("dtls state: ".concat(e.state)),"connecting"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():"connected"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()))}),OP.addSuccessEvent({key:521707}),this.clientAbility}catch(hb){throw OP.addFailedEvent({key:521707,error:hb}),this._log.error("initialize failed ".concat(hb," \noffer: ").concat(null==t?void 0:t.sdp)),hb}}))}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return HC(this,null,(function*(){try{if("CONNECTED"===this.currentState)return;let i=kw(),r={type:"answer",sdp:oF({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(r),yield this.waitForPeerConnectionConnected(),t||OP.addSuccessEvent({key:521703,cost:kw()-i})}catch(hb){let i=hb instanceof tb&&hb.code===ZC.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(hb),e),this.reset(),!i&&!this.isReconnecting&&(OP.addFailedEvent({key:521703,error:hb}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),hb}}))}reconnect(){return HC(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(vV,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:XV,responseCommand:bV.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(0!==t.data.code)throw new tb({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),OP.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),LN.emit(tO.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(ub){if(!this.isReconnecting)return;if(null!=ub&&ub.message.includes("timeout")){let e=hw(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==ub?void 0:ub.code," ").concat(ub)),OP.addFailedEvent({key:521704,error:ub}),this.reconnectionCount>=dk()&&this._log.warn("SDK has tried reconnect for ".concat(dk()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")}))}getPeerConnection(){return this._peerConnection}startReconnection(){return HC(this,null,(function*(){this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect()}))}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(vV,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===ak.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===ak.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===ak.FAILED||e.target.connectionState===ak.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===ak.CONNECTED||e.target.connectionState===ak.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),LN.emit(tO.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return sk;let e=null;return OO()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,wO()&&0!==this._peerConnection.getReceivers().length&&e?e.state:sk):sk}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(pF.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return HC(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(AO(i)){let t=e.get(i.localCandidateId),r=e.get(i.remoteCandidateId);t&&(this._log.info("local candidate: ".concat(t.candidateType," ").concat(t.protocol,":").concat(t.ip||t.address,":").concat(t.port," ").concat(t.networkType||""," ").concat("relay"===t.candidateType?"relayProtocol:".concat(t.relayProtocol):"")),t.networkType&&tw(t.networkType)),r&&this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port));break}}))}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this.currentState)return e();this._waitForPCConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new tb({code:ZC.API_CALL_ABORTED,message:PN({key:Jk.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{LN.off(tO.LEAVE_SUCCESS,r,this),this.off(pF.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{n();let e=new tb({code:ZC.API_CALL_TIMEOUT,message:"connection timeout"});var i;mF+=1,i=this._signalChannel.isConnected,mF>2&&!_F&&0===fF.size&&i&&(this._log.warn("firewall restriction"),_F=!0,this.emit(pF.FIREWALL_RESTRICTION)),t(e)}),Rk);LN.on(tO.LEAVE_SUCCESS,r,this),this.on(pF.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 HC(this,null,(function*(){if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),0===this.addDownlinkQueue.size)try{yield this.updateSDP(),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(uk){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(uk)),yield this.startReconnection()}}))}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,userId:i,tinyId:r}=e;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(i," ").concat(JSON.stringify(t)));let n=this._peerConnection.getTransceivers().slice(4).filter((e=>"inactive"===e.direction)).slice(0,3).map((e=>(e.direction=Fb.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=mU(this._peerConnection.remoteDescription.sdp));let o,s,a,c=this._parsedAnswer.media.filter((e=>{var t;return null==(t=e.ssrcs)?void 0:t.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(r)}))}));if(3===c.length)o=c[0],s=c[1],a=c[2];else if(3===n.length)o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[0]))),s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[1]))),a=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[2])));else if(0===n.length){this._peerConnection.addTransceiver(Fb.AUDIO,{direction:Fb.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Fb.VIDEO,{direction:Fb.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Fb.VIDEO,{direction:Fb.TRANSCEIVER_DIRECTION_RECVONLY}),o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=sF({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:mU(this._peerConnection.localDescription.sdp),isDownlink:!0});s=JSON.parse(JSON.stringify(e)),a=JSON.parse(JSON.stringify(e)),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a)}o.direction=Fb.TRANSCEIVER_DIRECTION_SENDONLY;let l="".concat(r,"-").concat(t.audio);o.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(l)},{id:t.audio,attribute:"msid",value:"".concat(l,"-").concat(Fb.MAIN," ").concat(l,"-audio")}],s.direction=Fb.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(Fb.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(Fb.MAIN," ").concat(l,"-bigvideo")}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=Fb.TRANSCEIVER_DIRECTION_SENDONLY;let d="".concat(l,"-aux");a.ssrcs=[{id:t.auxiliary,attribute:"cname",value:d},{id:t.auxiliary,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Fb.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(Fb.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Fb.VIDEO)}],a.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map((e=>e.mid)).join(" ")),this._downlinkMIDMap.set(i,[o.mid,s.mid,a.mid]),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(s.mid,i),this._downlinkMIDUserIDMap.set(a.mid,i)}removeDownlink(e){return HC(this,null,(function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(e,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),i=!1;this._peerConnection.getTransceivers().forEach((e=>{null!=t&&t.includes(Number(e.mid))&&(i=!0,e.direction="inactive")})),this._parsedAnswer||(this._parsedAnswer=mU(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((e=>{null!=t&&t.includes(Number(e.mid))&&(i=!0,e.direction="inactive",e.ssrcs=[],e.ssrcGroups=[])})),0===this.removeDownlinkQueue.size&&i&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),null==t||t.forEach((e=>this._downlinkMIDUserIDMap.delete(e))),this._log.info("removeDownlink(".concat(e,") done"))}))}setBandwidth(e){return HC(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(UO()){let e=this._peerConnection.getSenders().slice(0,4);for(let s=0;s<e.length;s++){let o,a=e[s];0===s&&t?o=t:1===s&&i?o=i:2===s&&r?o=r:3===s&&n&&(o=n),o&&(yield this.setSenderMaxBitrate(a,o))}let o=!1;i&&e[1].track&&(o=this.setStartBitrate(1,i)),n&&e[3].track&&(o=this.setStartBitrate(3,n)||o),o&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info("setBandwidth ".concat(JSON.stringify(e)))}catch(o){this._log.error("failed to set bandwidth: ".concat(o))}}))}setStartBitrate(e,t){var i,r;return!(null==(i=this._peerConnection)||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=mU(this._peerConnection.remoteDescription.sdp)),null==(r=this._parsedAnswer.media[e])||!r.fmtp[0]))&&(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),!0)}setSenderMaxBitrate(e,t){let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),"unlimited"===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,e.setParameters(i)}setBandwidthBySDP(e){let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=mU(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=mU(this._peerConnection.remoteDescription.sdp));let s=lD?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:lD?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:lD?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:lD?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:lD?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:s,limit:lD?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:lD?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:s,limit:lD?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:lD?1e3*n:n}]);let a={type:"offer",sdp:_U(o)};return this.updateSDP({localDescription:a})}setScaleResolutionDownBy(e,t){if(1===t)return;let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),i.encodings[0].scaleResolutionDownBy=t,e.setParameters(i)}updateSDP(){let{localDescription:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=_U(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,r)=>HC(this,null,(function*(){var n,o;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,i()}catch(uF){this._log.error(uF),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection(null==(n=this._peerConnection.localDescription)?void 0:n.sdp)," \nnext offer: ").concat(this.filterSDPDirection(null==e?void 0:e.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection(null==(o=this._peerConnection.remoteDescription)?void 0:o.sdp)," \nnext answer: ").concat(this.filterSDPDirection(t))),this._log.warn("offer: ".concat(null==e?void 0:e.sdp)),this._log.warn("answer: ".concat(t)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map((e=>{let{mid:t,currentDirection:i,direction:r,stopped:n}=e;return{mid:t,currentDirection:i,direction:r,stopped:n}}))))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,r(uF)}})))),this._updateSDPPromise}setTransceiverDirection(e,t){return HC(this,null,(function*(){if(!lD||!this._peerConnection||!this._parsedAnswer)return;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let i=this._peerConnection.getTransceivers();t.forEach((t=>{i[t].direction!==e&&(i[t].direction=e)}));for(let r of t){let t=this._parsedAnswer.media[r].direction;e===Bb.INACTIVE&&t===Bb.RECVONLY&&(this._parsedAnswer.media[r].direction=e),e===Bb.SENDONLY&&t===Bb.INACTIVE&&(this._parsedAnswer.media[r].direction=Bb.RECVONLY)}yield this.updateSDP()}))}filterSDPDirection(){return mU(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((e=>e.direction))}setOffer(e){return this._log.info("setting offer"),this._log.debug(e.sdp),this._peerConnection.setLocalDescription({type:"offer",sdp:cF(e.sdp,this.clientAbility,this._serverAbility)})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return HC(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach((i=>{var r;if(i.type===Fb.VIDEO){let n=this._serverAbility.video.codecs.find((t=>t.codec.toLowerCase()===e));n&&(null==(r=i.payloads)||!r.includes(String(n.payload)))&&(i.fmtp=[],i.payloads="",i.rtp=[],i.rtcpFb=[],aF(i,n),t=!0)}})),t&&(this._log.warn("switch video encoder to ".concat(e)),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:_U(this._parsedAnswer)}))}))}useHWEncoder(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;return HC(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];_w(t)?r=this._parsedAnswer.media.slice(1,4):2===t?r.push(this._parsedAnswer.media[1]):3===t?r.push(this._parsedAnswer.media[2]):7===t&&r.push(this._parsedAnswer.media[3]),r.forEach((t=>{var r;if(t.type===Fb.VIDEO){let n;e&&this.is42001fSupported?n=this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f"))):e||(n=this._serverAbility.video.codecs.find((e=>e.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264")))),n&&(null==(r=t.payloads)||!r.includes(String(n.payload)))&&(t.fmtp=[],t.payloads="",t.rtp=[],t.rtcpFb=[],aF(t,n),i=!0)}})),i&&(this._log.warn("use ".concat(e?"hw":"sw"," encoder")),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:_U(this._parsedAnswer)}))}))}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.insertableStreamsAbortMap.forEach((e=>"function"==typeof e.abort&&e.abort("destroy"))),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map((e=>t[e]))}};UC([QM("reconnect")],TF.prototype,"startReconnection",1),UC([XM((e=>e.userId))],TF.prototype,"addDownlink",1),UC([XM((e=>e))],TF.prototype,"removeDownlink",1),UC([YM(!0)],TF.prototype,"updateSDP",1);var EF=class{constructor(e){FC(this,"tag"),FC(this,"len"),FC(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}},SF=class{constructor(e){FC(this,"tinyId"),FC(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new EF(new Uint8Array(e).slice(i,i+2+2+n).buffer);r.push(o),i+=4+n}r.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},yF=new Set;function vF(){let e=Math.floor(4294967296*Math.random());return yF.has(e)?vF():(yF.add(e),e)}var IF=VC(jC()),AF=class extends IF.default{constructor(e){super(),FC(this,"userId"),FC(this,"tinyId"),FC(this,"_sdpSemantics"),FC(this,"_isUplink"),FC(this,"_room"),FC(this,"_log"),FC(this,"_currentState","DISCONNECTED"),FC(this,"_prevTime",-1),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=rO.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(LN.emit(tO.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}},RF=class extends AF{constructor(e){super(MC(PC({},e),{isUplink:!0})),FC(this,"localMainAudioTrack",null),FC(this,"localMainVideoTrack",null),FC(this,"localAuxAudioTrack",null),FC(this,"localAuxVideoTrack",null),FC(this,"_isPublishingAux",!1),FC(this,"_publishingLocalAudioTrack"),FC(this,"_publishingLocalVideoTrack"),FC(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}),FC(this,"_flag",0),FC(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc:r,smallVideoRtxSsrc:n,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:o||0,auxiliaryRtx:s||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:i}=this,r=Object.keys(t).find((e=>t[e]!==i[e]));if(r){if(!e)return void(this._checkPublishStateTimeoutId=uP.run(Bk,(()=>this.checkPublishState(!0)),{delay:1e4,count:1}));this._log.warn("publish state not matched, ".concat(r," local:").concat(t[r]," server:").concat(i[r]," ").concat(kN()," ").concat(RN())),OP.addCount({key:521e3})}uP.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(PO()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(i=o[2])||!i.track),n.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((e=>{e.track&&(e.track.kind===Fb.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}get serverPublishState(){return{audio:!!(this.flag&Kb),bigVideo:!!(this.flag&Wb),smallVideo:!!(this.flag&Gb),auxVideo:!!(this.flag&Jb)}}get muteState(){var e,t,i;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(i=this.localAuxVideoTrack)||!i.muted)}}initialize(){this.installEvents()}close(e){var t;let i=(null==(t=this._peerConnection)?void 0:t.getSenders())||[];for(let r of i)r.replaceTrack(null);super.close(e),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e,t;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),null!=(e=this.singlePC)&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(t=this.singlePC)||t.on("spc-reconnected",this.onSinglePCReconnected,this),jO&&this._room.enableSEI&&!LN.listeners(tO.SEND_SEI_MESSAGE).includes(this.sendSEIByWorker)&&(this.sendSEIByWorker=this.sendSEIByWorker.bind(this),LN.on(tO.SEND_SEI_MESSAGE,this.sendSEIByWorker))}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this),LN.off(tO.SEND_SEI_MESSAGE,this.sendSEIByWorker)}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}onVideoEncodeFailed(e){var t,i;e&&e.isMediaTrackActive&&"h264"===this.videoCodec&&(this._log.warn("h264 encoder not working"),null!=(t=this.singlePC)&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),null==(i=this.singlePC)||i.switchVideoEncoder("vp8")))}publish(e){return HC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e,o,s,a,c,l,d;if(!t.singlePC)return;yield t.singlePC.waitForPeerConnectionConnected();let u,{publishState:h,muteState:p}=t;if(i&&(t._publishingLocalAudioTrack=i,h.audio=!0,p.audio=i.muted),r){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new tb({code:ZC.NOT_SUPPORTED_H264,message:PN({key:Jk.NOT_SUPPORTED_H264ENCODE})});oD&&115===rN()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to 480p"),r.setProfile(Vb["480p_2"]),yield r.applyProfile()),t._publishingLocalVideoTrack=r,n?(h.auxVideo=!0,p.auxVideo=r.muted):(h.bigVideo=!0,p.bigVideo=r.muted)}if(t._isPublishingAux=n,r&&!n&&r.small&&(u=t._room.videoManager.smallTrack,h.smallVideo=!0),yield t._signalChannel.sendWaitForResponseWithRetry({command:ZV,responseCommand:bV.SPC_PUBLISH_RESULT,data:MC(PC({},t.singlePC.uplinkSSRC),{state:h,muteState:p}),retries:3}),yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:u,isAuxiliary:n}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r){t[n?"localAuxVideoTrack":"localMainVideoTrack"]=r;let{scaleResolutionDownBy:e}=r;e>1&&(t._log.warn("setScaleResolutionDownBy ".concat(r.streamType," ").concat(e)),yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[n?3:1],e))}i&&(t[n?"localAuxAudioTrack":"localMainAudioTrack"]=i),yield t.singlePC.setBandwidth({audio:(null==(e=t.localMainAudioTrack)?void 0:e.profile.bitrate)||(null==(o=t.localAuxAudioTrack)?void 0:o.profile.bitrate),bigVideo:null==(s=t.localMainVideoTrack)?void 0:s.profile.bitrate,smallVideo:null==(c=null==(a=t.localMainVideoTrack)?void 0:a.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),t.sendMediaSettings(),t.installTrackMuteEvents(i,r),!n&&(t._room.preferHW||(null==(d=t._room.scheduleResult.config)?void 0:d.preferHW))&&r&&r.profile.width*r.profile.height>=921600&&t.singlePC.useHWEncoder(!0,2)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!MO())return;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[],d=(e,t,i)=>{var r;let n=a[t].sender.replaceTrack(i);l.push(t),null!=(r=this.singlePC)&&r.enableInsertableStreams&&n.then((()=>this.createEncodedStreams(a[t].sender,e))),c.push(n)};s&&d(t.mediaType,0,s),o&&d(i.mediaType,n?3:1,o),r&&d(8,2,r);let u=this.singlePC.setTransceiverDirection(Bb.SENDONLY,l);return c.push(u),Promise.all(c)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var i,r;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let n=e.createEncodedStreams(),o=new AbortController;null==(i=this.singlePC)||i.addAbortController(e,o),(null!=(r=this.getTrackByMediaType(t))&&r.enableEncodeFrame?n.readable.pipeThrough(new TransformStream({transform:(e,i)=>{var r;let n=this.getTrackByMediaType(t);i.enqueue((null==(r=this.singlePC)?void 0:r.isUsingH264)&&n?n.encodeFrame(e,8===t):e)}}),o):n.readable).pipeTo(n.writable,o).catch((e=>{this._log.debug("encoded stream error",e),"destory"!==e&&this._log.warn(e)}))}sendSEIByWorker(e){let{room:t,isMain:i}=e;var r;if(t!==this._room||!this._peerConnection||!this.singlePC||!this._room.videoManager.seiWorker)return;let n=this._peerConnection.getSenders()[i?1:3];if(n&&(n.transform||(n.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!1,isMain:i})),i&&(null==(r=this.localMainVideoTrack)?void 0:r.small))){let e=this._peerConnection.getSenders()[2];e.transform||(e.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!1,isMain:i,small:!0}))}}enableSmall(e){return HC(this,null,(function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(Bb.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Bb.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return HC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){let e=r&&r===t.localAuxVideoTrack,n=null==r?void 0:r.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(yield o[0].replaceTrack(null),s.push(0),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=MC(PC({},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=MC(PC({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.singlePC.setTransceiverDirection(Bb.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return HC(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:MV,data:t,responseCommand:bV.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(i.data.code,i.data.message)}))}doUnpublish(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._signalChannel.sendWaitForResponse({command:LV,commandDesc:"unpublish",responseCommand:bV.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===ZC.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),FO){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*r.profile.bitrate,r.small&&(this._mediaSettings.smallVideoWidth=r.small.width,this._mediaSettings.smallVideoHeight=r.small.height,this._mediaSettings.smallVideoFps=r.small.frameRate,this._mediaSettings.smallVideoBps=1e3*r.small.bitrate)}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*n.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),r&&r.outMediaTrack&&(this._mediaSettings.videoWidth=r.profile.width,this._mediaSettings.videoHeight=r.profile.height,this._mediaSettings.videoFps=r.profile.frameRate,this._mediaSettings.videoBps=1e3*r.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:QV,data:this._mediaSettings,responseCommand:bV.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return HC(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Fb.AUXILIARY:Fb.MAIN," stream")),PO()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return HC(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Fb.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),1===n&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Bb.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Bb.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return HC(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?Fb.AUXILIARY:Fb.MAIN," stream")),PO()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return HC(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Fb.AUDIO)yield i[0].sender.replaceTrack(null);else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._room.videoManager.hasSmall&&(yield i[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(Bb.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}replaceTrack(e){return HC(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!i||0===i.length||!r||i.find((e=>e.track===r)))return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(r.kind," track ").concat(r.id," on ").concat(n?Fb.AUXILIARY:Fb.MAIN," stream")),r.kind===Fb.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===Fb.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0}))}setBandwidth(e){return HC(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===Fb.AUDIO?e.audio=i:"big"===n?e.bigVideo=i:"small"===n?e.smallVideo=i:e.auxVideo=i,yield t.singlePC.setBandwidth(e)}}()}))}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:OV,responseCommand:bV.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&LN.emit(tO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Fb.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Fb.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Fb.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Fb.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Fb.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Ek?(this._log.error(Kk.NOT_SUPPORTED_H264ENCODE),new tb({code:ZC.NOT_SUPPORTED_H264,message:PN({key:Jk.NOT_SUPPORTED_H264ENCODE})})):new tb({code:ZC.UNKNOWN,message:PN({key:Jk.SIGNAL_RESPONSE_FAILED,data:{signalResponse:bV.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return HC(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}))}))}};UC([jM((function(e){let{localVideoTrack:t}=e;null==t||t.once("6",this.onVideoEncodeFailed,this)}))],RF.prototype,"publish",1),UC([jM((function(e){let{localVideoTrack:t}=e;null==t||t.off("6",this.onVideoEncodeFailed,this)}))],RF.prototype,"unpublish",1);var CF=RF;function bF(e){return Object.keys(e).filter((t=>e[t]))}var kF=class extends AF{constructor(e){super(MC(PC({},e),{isUplink:!1})),FC(this,"_flag",0),FC(this,"isRobot",!1),FC(this,"role","anchor"),FC(this,"remoteAudioTrack"),FC(this,"remoteVideoTrack"),FC(this,"remoteAuxiliaryTrack"),FC(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new mL(this._room,this),this.remoteVideoTrack=new NL(this._room,this),this.remoteAuxiliaryTrack=new wL(this._room,this),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.downlinkVideoCodec)||"h264"}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return Pw(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===Fb.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let t=e.streams[0],{track:i,receiver:r}=e;if(!t.id.includes(this.tinyId))return;let n=t.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(n," ").concat(i.kind));let o=Fb.AUDIO;i.kind===Fb.VIDEO&&(o=n===Fb.MAIN?Fb.VIDEO:Fb.AUXILIARY);let s=this.remoteAudioTrack;o===Fb.VIDEO?s=this.remoteVideoTrack:o===Fb.AUXILIARY&&(s=this.remoteAuxiliaryTrack),this._room.enableSEI&&jO&&this.receiveSEIByWorker(r,n),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s,r),s.setInputMediaStreamTrack(i)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let i=t.createEncodedStreams(),r=new AbortController,n={abortController:r,enqueue:t=>{var i;return null!=(i=this.singlePC)&&i.isUsingH264?e.decodeFrame(t):t}};(e.enableDecodeFrame?i.readable.pipeThrough(new TransformStream({transform:(e,t)=>t.enqueue(n.enqueue(e))})):i.readable).pipeTo(i.writable,r).catch((e=>{"destory"!==e&&this._log.warn(e)})),this.singlePC.addAbortController(t,r)}}receiveSEIByWorker(e,t){e.track.kind===Fb.AUDIO||!this._peerConnection||!this.singlePC||!this._room.videoManager.seiWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!0,userId:this.userId,streamType:t}))}subscribe(e,t){return HC(this,null,(function*(){try{if(this._log.info("subscribe ".concat(t," ").concat(bF(e))),this.hasSSRC){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(hb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(hb.message," ").concat(JSON.stringify(this.muteState))),new tb({code:ZC.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):hb}}))}checkTrackEnded(e){var t,i,r;if((e.audio&&"ended"===(null==(t=this.remoteAudioTrack.mediaTrack)?void 0:t.readyState)||e.video&&"ended"===(null==(i=this.remoteVideoTrack.mediaTrack)?void 0:i.readyState)||e.auxiliary&&"ended"===(null==(r=this.remoteAuxiliaryTrack.mediaTrack)?void 0:r.readState))&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),nN&&aN<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return HC(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:r}=e;return function*(){var e;if("main"===r&&!t.isMainStreamSubscribed||"auxiliary"===r&&!t.isAuxStreamSubscribed)return void t._log.info("".concat(r," stream already unsubscribed"));let n=PC({},t.subscribeState);i.forEach((e=>{switch(e.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1}}));let o="subscribe_change";Object.values(n).find((e=>!0===e))||(o="unsubscribe"),t._log.info("".concat("unsubscribe"===o?o:"subscribe"," ").concat(r," [").concat(bF(n),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,n),"unsubscribe"===o&&(yield t.removeDownlink())}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=VV,n=bV.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=UV,n=bV.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:r,data:i,responseCommand:n,timeout:1e4,retries:3}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new tb({code:i.code,message:PN({key:Jk.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return HC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected();try{if(i||!e.hasSSRC){let i={audioSsrc:vF(),bigVideoSsrc:vF(),bigVideoRtxSsrc:vF(),auxVideoSsrc:vF(),auxVideoRtxSsrc:vF()},{audioSsrc:n,bigVideoSsrc:o,bigVideoRtxSsrc:s,auxVideoSsrc:a,auxVideoRtxSsrc:c}=i;e.ssrc={audio:n,video:o,videoRtx:s,auxiliary:a,auxiliaryRtx:c},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let r=yield e._signalChannel.sendWaitForResponseWithRetry({command:eU,responseCommand:bV.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!1,ssrc:i},retries:3,retryTimeout:0});if(0!==r.data.code)throw new tb({code:r.data.code,message:r.data.message})}catch(r){throw yield e.removeDownlink(),r}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}finally{let t=e._room.scheduleResult.config;((null==t?void 0:t.jitterDelay)||(null==t?void 0:t.jitterDelayAux))&&e.setJitterBufferDelay({mainDelay:t.jitterDelay,auxDelay:t.jitterDelayAux})}}}()}))}removeDownlink(){return HC(this,null,(function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;((null==e?void 0:e.jitterDelay)||(null==e?void 0:e.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)}))}setJitterBufferDelay(e){let{mainDelay:t,auxDelay:i}=e;if(!this.singlePC||!this._peerConnection||$w(t)&&$w(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return gw(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),gw(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,$w(t)&&(this.remoteAudioTrack.jitterBufferDelay=i)),new Promise((e=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:e})}))}doSetJitterBufferDelay(e){let{mainDelay:t,auxDelay:i,receivers:r,resolve:n}=e,o=-1;try{if(0===t&&0===i)return r.forEach((e=>e.jitterBufferTarget=0)),n();if(r.forEach((e=>{var r;let n=e.track===this.remoteAuxiliaryTrack.outMediaTrack||$w(t)&&e.track===this.remoteAudioTrack.outMediaTrack;if(n&&$w(i)||!n&&$w(t))return;let o=n?i||0:t,s=(e.jitterBufferTarget||0)+100;s>o||(e.jitterBufferTarget=s,this._log.debug("set ".concat(n?"aux ":"").concat(null==(r=null==e?void 0:e.track)?void 0:r.kind," jitterBuffer delay ").concat(s," -> ").concat(o)))})),!r.find((e=>{let r=e.track===this.remoteAuxiliaryTrack.outMediaTrack?i||0:t;return e.jitterBufferTarget<r})))return this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i," done")),n();o=setTimeout((()=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:n})}),1e3)}catch(s){this._log.warn("set jitterBuffer delay error: ".concat(s)),clearTimeout(o),n()}}};UC([YM(),WM((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this.off("closed",n),r(new tb({code:ZC.API_CALL_ABORTED,message:PN({key:Jk.CONNECTION_ABORTED,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],kF.prototype,"subscribe",1),UC([YM()],kF.prototype,"unsubscribe",1),UC([XM((()=>"jitter"))],kF.prototype,"setJitterBufferDelay",1);var DF=kF;var NF=VC(jC());var wF=class extends NF.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,FC(this,"log"),FC(this,"cmdIdSeqMap",new Map),FC(this,"messageMap",new Map),this.log=rO.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(bV.RECEIVE_CUSTOM_MSG,this.onReceiveMsg)}send(e){let{cmdId:t,data:i}=e,r=this.cmdIdSeqMap.get(t)||Math.floor(16383*Math.random()),n={cmdId:t,msg:btoa(String.fromCharCode(...new Uint8Array(i))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(t,r+1),this.signalChannel.send(rU,n),this.log.debug("send custom msg: ".concat(JSON.stringify(n)))}onReceiveMsg(e){let{data:t}=e.data,i=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(i){let e={userId:i,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),(e=>e.charCodeAt(0))).buffer};if(t.ordered){let t="".concat(i,"_").concat(e.cmdId),r=this.messageMap.get(t);if(r&&0!==r.lastSeq)if(Math.abs(r.lastSeq-e.seq)>wF.SEQ_INTERVAL)this.messageMap.set(t,{lastSeq:e.seq,cachedMessageMap:new Map}),this.emitMessage(e);else if(e.seq>r.lastSeq){if(e.seq===r.lastSeq+1)this.emitMessage(e);else if(!r.cachedMessageMap.has(e.seq)){let t=setTimeout((()=>this.emitMessage(e,!0)),5e3);r.cachedMessageMap.set(e.seq,{message:e,timeoutId:t})}}else this.log.debug("drop message ".concat(e.userId,"-").concat(e.cmdId,"-").concat(e.seq));else r||(r={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(t,r),setTimeout((()=>this.emitMessage(e,!0)),100)),r.cachedMessageMap.set(e.seq,{message:e})}else this.emit("message",e)}}emitMessage(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i;let r=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),n=e;if(r){if(t){let e=[...r.cachedMessageMap.values()].sort(((e,t)=>e.message.seq-t.message.seq));e[0]&&(n=e[0].message)}0!==r.lastSeq&&n.seq-r.lastSeq>1&&this.log.debug("msg lost userId: ".concat(n.userId," seq: ").concat(r.lastSeq," -> ").concat(n.seq)),r.lastSeq=n.seq,clearTimeout(null==(i=r.cachedMessageMap.get(n.seq))?void 0:i.timeoutId),r.cachedMessageMap.delete(n.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(n))),this.emit("message",n);let o=null==r?void 0:r.cachedMessageMap.get(n.seq+1);o&&this.emitMessage(o.message)}},OF=wF;FC(OF,"SEQ_INTERVAL",300);var PF,{isString:MF,isUndefined:LF,getNetworkType:xF,isEmpty:VF}=sb,UF=class extends GU{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=LO,this._changeBigSmallRecords=new Map,this._networkQuality=null,this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this.enableChorus=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=0,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this.preferHW=!1,this._stats=new AU(this,this._log),this.userManager=new qL(this.userId,this._log),this._version=lb,this.sdpSemantics=Tk,LF(e.sdpSemantics)?sO.isUnifiedPlanDefault()&&(this.sdpSemantics=gk):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(xF())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!LF(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&LO,this.enableChorus=e.enableChorus,!LF(e.enableSPC)&&LO&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new hF(this)}get isMainStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex((e=>e.muteState.hasAuxiliary))>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,i){return HC(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",(e=>{this.emit("peer-join",e)})),this.userManager.on("2",(e=>{this.closeDownLinkConnection(e,"remote user exitRoom"),this.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(e=>{var t=((e,t)=>{var i={};for(var r in e)kC.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&CC)for(var r of CC(e))t.indexOf(r)<0&&DC.call(e,r)&&(i[r]=e[r]);return i})(e,[]);LN.emit(tO.REMOTE_PUBLISH_STATE_CHANGED,PC({room:this},t)),this.emit("remote-publish-state-changed",PC({},t))})),this.joinParams=e,new Promise(((t,i)=>HC(this,null,(function*(){var r,n;this._joinReject=i;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(o){if(!(o instanceof tb&&o.code===ZC.SPC_INITIALIZED_FAILED))return i(o);null==(r=this.signalChannel)||r.destroy(),yield this.initialize()}let s=kw();yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),OP.addSuccessEvent({key:521708,cost:kw()-s}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(SP){OP.addFailedEvent({key:521708,error:SP}),i(SP)}this._joinReject=null}))))}))}initSinglePC(){return HC(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new TF({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",(e=>this.emit("sei-message",e))),this.singlePC.once("error",(()=>this.fallbackToMPC()));try{return yield this.singlePC.initialize()}catch(ub){throw this.fallbackToMPC(),new tb({code:ZC.SPC_INITIALIZED_FAILED,message:null==ub?void 0:ub.message})}}}))}doJoin(e,t){return new Promise(((i,r)=>HC(this,null,(function*(){var n,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(SV,(e=>{this.clearJoinTimeout(),LN.emit(tO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)})),Tw(null==(o=null==(n=this.scheduleResult)?void 0:n.config)?void 0:o.singlePC)&&LO&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let a={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:"live"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:DN(),netType:iw(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;(null==(s=this.scheduleResult.config)?void 0:s.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{r(new tb({code:ZC.JOIN_ROOM_FAILED,message:PN({key:Jk.JOIN_ROOM_TIMEOUT})}))}),c),LN.emit(tO.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?$V:DV,a),this.signalChannel.once(bV.JOIN_ROOM_RESULT,(e=>{this.clearJoinTimeout();let{code:t,message:n,data:o,tinyId:s}=e.data;LN.emit(tO.JOIN_RECEIVED_CMD_RES,{room:this,code:t}),0===t?(this._log.info("Join room success, start heartbeat"),s&&(this.tinyId=s),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=o.publishers,this.singlePC&&this.singlePC.connect(o.ability).catch((()=>{})),i()):(this._log.error("Join room failed result: ".concat(t," error: ").concat(n)),r(new tb({code:ZC.JOIN_ROOM_FAILED,extraCode:t,message:PN({key:Jk.JOIN_ROOM_FAILED,data:{error:n,code:t}})})))}))}))))}reJoin(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return HC(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let t,i=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,i.push(this.initSinglePC().then((e=>(t=e,e))))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),i.push(this.signalChannel.connect())),yield Promise.all(i),yield this.doJoin(MC(PC({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),VN.logSuccessEvent({userId:this.userId,eventType:pk.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(pF.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof CF&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(pF.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof IU&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(uk){this._log.warn("reJoin fail ".concat(uk)),this.reset(),VN.logFailedEvent({userId:this.userId,eventType:pk.REJOIN,error:uk}),this.emit("error",new tb({code:ZC.JOIN_ROOM_FAILED,message:PN({key:Jk.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return HC(this,null,(function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this.signalChannel||function(e){let t=[...oU.values()].find((t=>t.room.userId===e&&!t.room.isJoined));return t||null}(this.userId),n=!!(r&&r.isConnected&&r.keepAlive);return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e=this.scheduleResult.domains[0]),this._log.info("".concat(n?"reuse":"setup"," signal channel")),n?(r.url=t,r.backupUrl=i,r.room=this,this.signalChannel=r):(this.signalChannel=new sU({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:t,backupUrl:i,race:this.enableSPC&&!this.proxy_ws,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?e:void 0}),this._customMessageManager=new OF(this,this.signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this._networkQuality||(this._networkQuality=new bU({signalChannel:this.signalChannel,room:this}),this._networkQuality.on(bU.EVENT_NETWORK_QUALITY,(e=>{this.emit("network-quality",e)}))),_P(this,this.signalChannel).add(yV,(e=>{LN.emit(tO.SIGNAL_CONNECTION_STATE_CHANGED,PC({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(AV,(e=>{this.reset(),this.emit("error",e)})).add(bV.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})).add(bV.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(bV.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(bV.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(VN.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(EV,(e=>{this.tinyId=e.signalInfo.tinyId,LN.emit(tO.JOIN_SIGNAL_CONNECTION_END,{room:this})})),LN.emit(tO.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&LN.emit(tO.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this.signalChannel=e,e||fP(this)}leave(){return HC(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(uk){}this._log.info("leave() => leaving room"),LN.emit(tO.LEAVE_SEND_CMD,{room:this}),null==(e=this.signalChannel)||e.send(NV)}))}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=uP.run(Vk,this.doHeartbeat.bind(this),{delay:2e3}),this.startUpdateNTPTime())}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),uP.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return HC(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});this.badCaseDetector.resetMonitor();let r=null!=(e=this.signalChannel)&&e.isConnected?function(e){if(JL.has(e)){let t=JL.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType})));return JL.delete(e),t}return[]}(this.userId):[],n=MC(PC({str_sdk_version:cb,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i),{msg_device_info:PC({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:iw()},i.msg_device_info)});if(this.heartbeatReport=n,LN.emit(tO.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(wV,n);let e=Date.now();this._lastHeartBeatTime>0&&e-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(e-this._lastHeartBeatTime)),this._lastHeartBeatTime=e}this.emit("heartbeat-report",MC(PC({},n),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map((e=>{let{userId:t,srcTinyId:i,flag:r}=e;t===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=r);let n=this.remotePublishedUserMap.get(t);return n&&this.checkSubscribeBigSmallVideo(n),{userId:t,tinyId:i,flag:r}}));e.data.mixRobotList.forEach((e=>{let{userId:i,srcTinyId:r,flag:n,mixUserList:o}=e;t.unshift({userId:i,tinyId:r,flag:n,isRobot:!0,mixUserList:o})})),LN.emit(tO.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof IU&&(this.uplinkConnection=null)),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r,isRobot:n}=e,o=new(this.singlePC?DF:EU)({userId:t,tinyId:i,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:n});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,t),this.emit("remote-published",o)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",(e=>{let i=e.getCode();i!==ZC.ICE_TRANSPORT_ERROR&&(i===ZC.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",MC(PC({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=uP.run(Vk,this.syncUserList.bind(this)))}stopSyncUserListInterval(){uP.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:qV,responseCommand:bV.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((e=>{let{data:t}=e,{code:i,message:r}=t;if(0===i)return(t.data&&t.data.userList||[]).map((e=>{let{userId:t,srcTinyId:i,role:r}=e;return{userId:t,tinyId:i,role:r}}));throw PN({key:Jk.SIGNAL_RESPONSE_FAILED,data:{signalResponse:bV.USER_LIST_RES,code:i,message:r}})})):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!uU)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?(null==(e=this.singlePC.getPeerConnection())?void 0:e.connectionState)===ak.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof hU&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===ak.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return HC(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),VN.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,null==(e=this.singlePC)||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new IU({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0})),e.close()}this.remotePublishedUserMap.forEach((e=>{let t=new EU({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 tb({code:ZC.INVALID_OPERATION,message:PN({key:Jk.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy())}switchRole(e){return HC(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:YV,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:bV.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(t.data))),this.signalChannel.sendWaitForResponseWithRetry(t).then((t=>{let{code:i,message:r}=t.data;if(0!==i)throw new tb({code:ZC.SWITCH_ROLE_FAILED,message:PN({key:Jk.SWITCH_ROLE_FAILED,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof tb&&e.getCode()===ZC.API_CALL_TIMEOUT&&(e=new tb({code:ZC.SWITCH_ROLE_FAILED,message:PN({key:Jk.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 HC(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof tL&&(t instanceof lL?i.audio=t:e.audio=t),t instanceof nL&&(t instanceof cL&&2===t.mediaType?i.video=t:e.video=t)}));let r=VF(e),n=VF(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new CF({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new IU({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",MC(PC({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==ZC.ICE_TRANSPORT_ERROR&&(t===ZC.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})));let o=t.map((e=>e.kind)).join(",");r||(this._log.info("publish() => main ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:e.audio,localVideoTrack:e.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info("publish() => aux ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:i.audio,localVideoTrack:i.video,isAuxiliary:!0}),this._log.info("aux is published"))}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return HC(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 tL&&(t instanceof lL?i.audio=t:e.audio=t),t instanceof nL&&(t instanceof cL&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");VF(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),VF(i)||(this._log.info("unpublish() => aux ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(r){}0===this.localTracks.size&&this.closeUplink("you unpublished")}))}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return this.uplinkConnection&&e.mediaTrack?this.uplinkConnection.removeTrack(e).then((t=>(e.unpublish(),t))):Promise.resolve()}replaceTrack(e){return this.uplinkConnection&&e.mediaTrack&&VO()?this.uplinkConnection.replaceTrack(e).then((t=>{t&&LN.emit(tO.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return HC(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return HC(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:Fb.VIDEO,videoType:Fb.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)}))}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return HC(this,null,(function*(){if(t=t.filter((e=>!e.isSubscribed)),0===t.length)return;let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let r=t.find((e=>2===e.mediaType))?"auxiliary":"main";try{let n=PC({},i.subscribeState);t.forEach((e=>{switch(e.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0}}));let o=this._changeBigSmallRecords.get(e);o&&o.options.smallVideo&&i.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),LN.emit(tO.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(fU(n),"] prev: [").concat(fU(i.subscribeState),"]")),yield i.subscribe(n,r),this._log.info("subscribe ".concat(e," ").concat(r," done"));for(let e of t)e.mediaTrack||(yield e.waitHasMediaTrack());LN.emit(tO.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(pb){let i=pb instanceof tb?pb.getCode():ZC.UNKNOWN,n=pb;throw pb instanceof tb?i===ZC.REMOTE_STREAM_NOT_EXIST&&(n=new tb({code:ZC.API_CALL_ABORTED,message:PN({key:Jk.API_CALL_ABORTED,data:{message:pb.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new tb({code:i,message:PN({key:Jk.SUBSCRIBE_FAILED,data:{message:pb.message,userId:e,streamType:r}})}),this._log.error(n)),n}}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return HC(this,null,(function*(){let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let r=t.find((e=>2===e.mediaType))?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(e," ").concat(r));try{yield i.unsubscribe({remoteTracks:t,streamType:r})}catch(pb){this._log.warn("unsubscribe() => failed ".concat(pb))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),LN.emit(tO.UNSUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1?arguments[1]:void 0;if(e<=0)return this._enableAudioVolumeEvaluation=!1,void uP.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),LN.emit(tO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&uP.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=uP.run(Uk,(()=>{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 HC(this,null,(function*(){var e;let t={};return t[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},null!=(e=this.uplinkConnection)&&e.localMainAudioTrack&&(t[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),t}))}getLocalVideoStats(){return HC(this,null,(function*(){var e,t;let i={};return i[this.userId]=(null==(t=null==(e=this.uplinkConnection)?void 0:e.localMainVideoTrack)?void 0:t.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},i}))}getTransportStats(){return HC(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 HC(this,null,(function*(){let t={};for(let[i,r]of this.remotePublishedUserMap)"main"===e&&r.muteState.hasVideo&&(t[i]=r.remoteVideoTrack.stat),"auxiliary"===e&&r.muteState.hasAuxiliary&&(t[i]=r.remoteAuxiliaryTrack.stat);return t}))}getRemoteAudioStats(){return HC(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:WV,data:e,timeout:5e3,responseCommand:bV.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:GV,data:e,timeout:5e3,responseCommand:bV.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?FV:HV,data:e,timeout:5e3,responseCommand:t?bV.START_PUBLISH_TENCENT_CDN_RES:bV.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?BV:jV,data:e,timeout:5e3,responseCommand:t?bV.STOP_PUBLISH_TENCENT_CDN_RES:bV.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:JV,data:e,timeout:5e3,responseCommand:bV.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:KV,data:e,timeout:5e3,responseCommand:bV.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:zV,data:e,timeout:5e3,responseCommand:bV.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:tU,data:e,timeout:5e3,responseCommand:bV.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):this.proxy_unified?(e.mainUrl="wss://".concat(this.proxy_unified),e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}getSignalInfo(){var e;return(null==(e=this.signalChannel)?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):this.signalChannel.close(),this.setSignalChannel(null)),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return HC(this,null,(function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:r,hasVideo:n}}=e;if(!r&&!n||!t.video&&!t.smallVideo)return;let o=this._changeBigSmallRecords.get(i);if(!o||o.isSubscribing||o.reSubscribeCount<=0)return;let{options:s,reSubscribeCount:a}=o;if(s.video&&t.video||s.smallVideo&&t.smallVideo&&r)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:s.video,smallVideo:s.smallVideo};try{if(!r&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;o.isSubscribing=!0,o.reSubscribeCount=a-1,yield e.subscribe(c,"main"),e.remoteVideoTrack.setMediaType(c.smallVideo?8:4),this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video successfully. count ").concat(Lk-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=Lk}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(Lk-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:Lk};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(MF(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!LF(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new tb({code:ZC.INVALID_PARAMETER,message:PN({key:Jk.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(!LF(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new tb({code:ZC.INVALID_PARAMETER,message:PN({key:Jk.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!LF(e.userDefinePushArgs)){if(!(MF(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new tb({code:ZC.INVALID_PARAMETER,message:PN({key:Jk.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}VF(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&HO)return this.singlePC.enableInsertableStreams=!0,this.singlePC.startReconnection()}sendSignalMessage(e){var t;return this.signalChannel?null==(t=this.signalChannel)?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new tb({code:ZC.INVALID_OPERATION,message:"not join"}))}startUpdateNTPTime(){let e=[];for(let t=0;t<5;t++)e.push(this.updateNTPTime());return Promise.all(e).then((e=>{let t=e[0].offset,i=e[0].offset;e.forEach((e=>{t=Math.min(e.offset,t),i=Math.max(e.offset,i)}));let r=Math.floor(e.reduce(((e,t)=>e+t.rtt),0)/e.length),n=Math.floor(e.reduce(((e,t)=>e+t.offset),0)/e.length);(i-t>30||r>50)&&setTimeout((()=>this.startUpdateNTPTime()),5e3),function(e){ib=e;let t=new Date;t.setTime(t.getTime()+e),rO[rb?"info":"debug"]("baseTime from server: ".concat(t," offset: ").concat(e)),rb=!1}(n),this.emit("ntp-time-updated")}))}updateNTPTime(){let e=Date.now();return this.signalChannel.sendWaitForResponse({command:nU,responseCommand:bV.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(e)},enableLog:!1}).then((t=>{let i=Number(t.data.data.serverSendTime),r=Number(t.data.data.serverRecvTime),n=t.data.receiveTime||Date.now();return{rtt:n-e-(r-i),offset:(r-e+(i-n))/2}}))}};return UC([XU(["left",eF.INIT],"joined"),TP({settings:{retries:1,timeout:0},onError(e,t,i){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),BN(!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))}}),WM((e=>{let t=new fV;return function(i,r,n){return HC(this,null,(function*(){let o=String(i.roomId||i.strRoomId);if(this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.userSig=i.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,i.privateMapKey=i.privateMapKey||"",this.isJoined)throw new tb({code:ZC.INVALID_OPERATION,message:PN({key:Jk.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new tb({code:ZC.INVALID_OPERATION,message:PN({key:Jk.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)),LN.emit(tO.JOIN_START,{room:this,roomId:o,params:i}),this.checkSystemResult=yield sO.checkSystemRequirementsInternal(),this.checkDestroy();let s=sb.getEnv();s||(s=Db.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Hb.OLD_CLOUD_LADDER)?s=Db.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Hb.WEBRTC)&&(s=Db.WEBRTC))),VN.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),gV.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!sO.isWebRTCSupported()||!a&&!c)throw new tb({code:ZC.NOT_SUPPORTED,message:PN({key:Jk.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!sb.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=sb.performanceNow(),LN.emit(tO.JOIN_SUCCESS,{room:this}),30===n&&!i.component&&VN.uploadEvent({log:"stat-conv-".concat(Number(TN),"-").concat(location.hostname),userId:this.userId}),t}catch(SP){throw t.delete({room:this,roomId:o}),LN.emit(tO.JOIN_FAILED,{room:this,error:SP}),SP}}))}}))],UF.prototype,"join",1),UC([XU("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),WM((e=>function(){return HC(this,null,(function*(){LN.emit(tO.LEAVE_START,{room:this}),yield e.call(this),LN.emit(tO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),QM("leave room"),EP({fnName:"publish",validateArgs:!1}),EP({fnName:"unsubscribe",validateArgs:!1})],UF.prototype,"leave",1),UC([YM(),WM((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return HC(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"capture"===e.state)),!i.length))return;LN.emit("61",{room:this});let t=e.apply(this,i);return i.forEach((e=>e.publish(this,t))),t}))})),TP({settings:{retries:dk,timeout:e=>hw(e)},onError(e,t,i){var r;null!=(r=e.message)&&r.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error("publish failed: ".concat(e)),i(e),LN.emit(tO.PUBLISH_FAILED,{room:this}))}})],UF.prototype,"publish",1),UC([EP({fnName:"publish"}),(PF="api-call",function(e,t,i){let r=i.value;return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let n=zM.get(this);if(n){let e=n.queue.filter(((e,i)=>{if(0===i)return!0;let r=!0;return e.args.forEach((e=>{t.find((t=>t===e))||(r=!1)})),!r||(e.reject(new tb({code:ZC.API_CALL_ABORTED,message:PF})),!1)}));n.queue=e}return r.apply(this,t)},i}),YM(),WM((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let n=e.apply(this,i);return i.forEach((e=>e.unpublish())),n})),jM((function(){var e,t;0===this.localTracks.size&&OO()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((e=>e.track&&e.replaceTrack(null))))}))],UF.prototype,"unpublish",1),UC([XM((e=>e.userId))],UF.prototype,"replaceTrack",1),UC([XM((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),uL(),WM((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let n=e.apply(this,i);return i.forEach((e=>!e.isSubscribed&&e.subscribe(n))),n})),TP({settings:{retries:dk,timeout:e=>hw(e)},onError(e,t,i,r){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),i(e),LN.emit(tO.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],UF.prototype,"subscribe",1),UC([EP({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")}))}}),XM((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],UF.prototype,"unsubscribe",1),_V.create=_V._create.bind(_V,UF),_V}));