trtc-sdk-v5 5.8.5-ef.3 → 5.8.5-ef.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/device-detector/package.json +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/trtc.esm.js +19 -19
- package/trtc.js +1 -1
package/trtc.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TRTC=t()}(this,(function(){function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r=function(e){return e&&e.Math===Math&&e},n=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")(),o={},s=function(e){try{return!!e()}catch(t){return!0}},a=!s((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})),c=!s((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),l=c,d=Function.prototype.call,u=l?d.bind(d):function(){return d.apply(d,arguments)},h={},p={}.propertyIsEnumerable,m=Object.getOwnPropertyDescriptor,_=m&&!p.call({1:2},1);h.f=_?function(e){var t=m(this,e);return!!t&&t.enumerable}:p;var f,g,v=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},y=c,T=Function.prototype,S=T.call,E=y&&T.bind.bind(S,S),I=y?E:function(e){return function(){return S.apply(e,arguments)}},R=I,C=R({}.toString),A=R("".slice),b=function(e){return A(C(e),8,-1)},k=s,w=b,D=Object,N=I("".split),O=k((function(){return!D("z").propertyIsEnumerable(0)}))?function(e){return"String"===w(e)?N(e,""):D(e)}:D,P=function(e){return null==e},M=P,L=TypeError,x=function(e){if(M(e))throw new L("Can't call method on "+e);return e},V=O,U=x,F=function(e){return V(U(e))},B="object"==typeof document&&document.all,H=void 0===B&&void 0!==B?function(e){return"function"==typeof e||e===B}:function(e){return"function"==typeof e},j=H,W=function(e){return"object"==typeof e?null!==e:j(e)},G=n,J=H,z=function(e,t){return arguments.length<2?(i=G[e],J(i)?i:void 0):G[e]&&G[e][t];var i},q=I({}.isPrototypeOf),K=n.navigator,Y=K&&K.userAgent,Q=Y?String(Y):"",X=n,$=Q,Z=X.process,ee=X.Deno,te=Z&&Z.versions||ee&&ee.version,ie=te&&te.v8;ie&&(g=(f=ie.split("."))[0]>0&&f[0]<4?1:+(f[0]+f[1])),!g&&$&&(!(f=$.match(/Edge\/(\d+)/))||f[1]>=74)&&(f=$.match(/Chrome\/(\d+)/))&&(g=+f[1]);var re=g,ne=re,oe=s,se=n.String,ae=!!Object.getOwnPropertySymbols&&!oe((function(){var e=Symbol("symbol detection");return!se(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),ce=ae&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,le=z,de=H,ue=q,he=Object,pe=ce?function(e){return"symbol"==typeof e}:function(e){var t=le("Symbol");return de(t)&&ue(t.prototype,he(e))},me=String,_e=function(e){try{return me(e)}catch(t){return"Object"}},fe=H,ge=_e,ve=TypeError,ye=function(e){if(fe(e))return e;throw new ve(ge(e)+" is not a function")},Te=ye,Se=P,Ee=function(e,t){var i=e[t];return Se(i)?void 0:Te(i)},Ie=u,Re=H,Ce=W,Ae=TypeError,be={exports:{}},ke=n,we=Object.defineProperty,De=function(e,t){try{we(ke,e,{value:t,configurable:!0,writable:!0})}catch(i){ke[e]=t}return t},Ne=n,Oe=De,Pe="__core-js_shared__",Me=be.exports=Ne[Pe]||Oe(Pe,{});(Me.versions||(Me.versions=[])).push({version:"3.40.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.40.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Le=be.exports,xe=Le,Ve=function(e,t){return xe[e]||(xe[e]=t||{})},Ue=x,Fe=Object,Be=function(e){return Fe(Ue(e))},He=Be,je=I({}.hasOwnProperty),We=Object.hasOwn||function(e,t){return je(He(e),t)},Ge=I,Je=0,ze=Math.random(),qe=Ge(1..toString),Ke=function(e){return"Symbol("+(void 0===e?"":e)+")_"+qe(++Je+ze,36)},Ye=Ve,Qe=We,Xe=Ke,$e=ae,Ze=ce,et=n.Symbol,tt=Ye("wks"),it=Ze?et.for||et:et&&et.withoutSetter||Xe,rt=function(e){return Qe(tt,e)||(tt[e]=$e&&Qe(et,e)?et[e]:it("Symbol."+e)),tt[e]},nt=u,ot=W,st=pe,at=Ee,ct=function(e,t){var i,r;if("string"===t&&Re(i=e.toString)&&!Ce(r=Ie(i,e)))return r;if(Re(i=e.valueOf)&&!Ce(r=Ie(i,e)))return r;if("string"!==t&&Re(i=e.toString)&&!Ce(r=Ie(i,e)))return r;throw new Ae("Can't convert object to primitive value")},lt=TypeError,dt=rt("toPrimitive"),ut=function(e,t){if(!ot(e)||st(e))return e;var i,r=at(e,dt);if(r){if(void 0===t&&(t="default"),i=nt(r,e,t),!ot(i)||st(i))return i;throw new lt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ct(e,t)},ht=ut,pt=pe,mt=function(e){var t=ht(e,"string");return pt(t)?t:t+""},_t=W,ft=n.document,gt=_t(ft)&&_t(ft.createElement),vt=function(e){return gt?ft.createElement(e):{}},yt=vt,Tt=!a&&!s((function(){return 7!==Object.defineProperty(yt("div"),"a",{get:function(){return 7}}).a})),St=a,Et=u,It=h,Rt=v,Ct=F,At=mt,bt=We,kt=Tt,wt=Object.getOwnPropertyDescriptor;o.f=St?wt:function(e,t){if(e=Ct(e),t=At(t),kt)try{return wt(e,t)}catch(i){}if(bt(e,t))return Rt(!Et(It.f,e,t),e[t])};var Dt={},Nt=a&&s((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Ot=W,Pt=String,Mt=TypeError,Lt=function(e){if(Ot(e))return e;throw new Mt(Pt(e)+" is not an object")},xt=a,Vt=Tt,Ut=Nt,Ft=Lt,Bt=mt,Ht=TypeError,jt=Object.defineProperty,Wt=Object.getOwnPropertyDescriptor,Gt="enumerable",Jt="configurable",zt="writable";Dt.f=xt?Ut?function(e,t,i){if(Ft(e),t=Bt(t),Ft(i),"function"==typeof e&&"prototype"===t&&"value"in i&&zt in i&&!i[zt]){var r=Wt(e,t);r&&r[zt]&&(e[t]=i.value,i={configurable:Jt in i?i[Jt]:r[Jt],enumerable:Gt in i?i[Gt]:r[Gt],writable:!1})}return jt(e,t,i)}:jt:function(e,t,i){if(Ft(e),t=Bt(t),Ft(i),Vt)try{return jt(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Ht("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var qt=Dt,Kt=v,Yt=a?function(e,t,i){return qt.f(e,t,Kt(1,i))}:function(e,t,i){return e[t]=i,e},Qt={exports:{}},Xt=a,$t=We,Zt=Function.prototype,ei=Xt&&Object.getOwnPropertyDescriptor,ti=$t(Zt,"name"),ii={EXISTS:ti,PROPER:ti&&"something"===function(){}.name,CONFIGURABLE:ti&&(!Xt||Xt&&ei(Zt,"name").configurable)},ri=H,ni=Le,oi=I(Function.toString);ri(ni.inspectSource)||(ni.inspectSource=function(e){return oi(e)});var si,ai,ci,li=ni.inspectSource,di=H,ui=n.WeakMap,hi=di(ui)&&/native code/.test(String(ui)),pi=Ke,mi=Ve("keys"),_i=function(e){return mi[e]||(mi[e]=pi(e))},fi={},gi=hi,vi=n,yi=W,Ti=Yt,Si=We,Ei=Le,Ii=_i,Ri=fi,Ci="Object already initialized",Ai=vi.TypeError,bi=vi.WeakMap;if(gi||Ei.state){var ki=Ei.state||(Ei.state=new bi);ki.get=ki.get,ki.has=ki.has,ki.set=ki.set,si=function(e,t){if(ki.has(e))throw new Ai(Ci);return t.facade=e,ki.set(e,t),t},ai=function(e){return ki.get(e)||{}},ci=function(e){return ki.has(e)}}else{var wi=Ii("state");Ri[wi]=!0,si=function(e,t){if(Si(e,wi))throw new Ai(Ci);return t.facade=e,Ti(e,wi,t),t},ai=function(e){return Si(e,wi)?e[wi]:{}},ci=function(e){return Si(e,wi)}}var Di={set:si,get:ai,has:ci,enforce:function(e){return ci(e)?ai(e):si(e,{})},getterFor:function(e){return function(t){var i;if(!yi(t)||(i=ai(t)).type!==e)throw new Ai("Incompatible receiver, "+e+" required");return i}}},Ni=I,Oi=s,Pi=H,Mi=We,Li=a,xi=ii.CONFIGURABLE,Vi=li,Ui=Di.enforce,Fi=Di.get,Bi=String,Hi=Object.defineProperty,ji=Ni("".slice),Wi=Ni("".replace),Gi=Ni([].join),Ji=Li&&!Oi((function(){return 8!==Hi((function(){}),"length",{value:8}).length})),zi=String(String).split("String"),qi=Qt.exports=function(e,t,i){"Symbol("===ji(Bi(t),0,7)&&(t="["+Wi(Bi(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Mi(e,"name")||xi&&e.name!==t)&&(Li?Hi(e,"name",{value:t,configurable:!0}):e.name=t),Ji&&i&&Mi(i,"arity")&&e.length!==i.arity&&Hi(e,"length",{value:i.arity});try{i&&Mi(i,"constructor")&&i.constructor?Li&&Hi(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var r=Ui(e);return Mi(r,"source")||(r.source=Gi(zi,"string"==typeof t?t:"")),e};Function.prototype.toString=qi((function(){return Pi(this)&&Fi(this).source||Vi(this)}),"toString");var Ki=Qt.exports,Yi=H,Qi=Dt,Xi=Ki,$i=De,Zi=function(e,t,i,r){r||(r={});var n=r.enumerable,o=void 0!==r.name?r.name:t;if(Yi(i)&&Xi(i,o,r),r.global)n?e[t]=i:$i(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch(s){}n?e[t]=i:Qi.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},er={},tr=Math.ceil,ir=Math.floor,rr=Math.trunc||function(e){var t=+e;return(t>0?ir:tr)(t)},nr=rr,or=function(e){var t=+e;return t!=t||0===t?0:nr(t)},sr=or,ar=Math.max,cr=Math.min,lr=function(e,t){var i=sr(e);return i<0?ar(i+t,0):cr(i,t)},dr=or,ur=Math.min,hr=function(e){var t=dr(e);return t>0?ur(t,9007199254740991):0},pr=hr,mr=function(e){return pr(e.length)},_r=F,fr=lr,gr=mr,vr=function(e){return function(t,i,r){var n=_r(t),o=gr(n);if(0===o)return!e&&-1;var s,a=fr(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}},yr={includes:vr(!0),indexOf:vr(!1)},Tr=We,Sr=F,Er=yr.indexOf,Ir=fi,Rr=I([].push),Cr=function(e,t){var i,r=Sr(e),n=0,o=[];for(i in r)!Tr(Ir,i)&&Tr(r,i)&&Rr(o,i);for(;t.length>n;)Tr(r,i=t[n++])&&(~Er(o,i)||Rr(o,i));return o},Ar=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],br=Cr,kr=Ar.concat("length","prototype");er.f=Object.getOwnPropertyNames||function(e){return br(e,kr)};var wr={};wr.f=Object.getOwnPropertySymbols;var Dr=z,Nr=er,Or=wr,Pr=Lt,Mr=I([].concat),Lr=Dr("Reflect","ownKeys")||function(e){var t=Nr.f(Pr(e)),i=Or.f;return i?Mr(t,i(e)):t},xr=We,Vr=Lr,Ur=o,Fr=Dt,Br=function(e,t,i){for(var r=Vr(t),n=Fr.f,o=Ur.f,s=0;s<r.length;s++){var a=r[s];xr(e,a)||i&&xr(i,a)||n(e,a,o(t,a))}},Hr=s,jr=H,Wr=/#|\.prototype\./,Gr=function(e,t){var i=zr[Jr(e)];return i===Kr||i!==qr&&(jr(t)?Hr(t):!!t)},Jr=Gr.normalize=function(e){return String(e).replace(Wr,".").toLowerCase()},zr=Gr.data={},qr=Gr.NATIVE="N",Kr=Gr.POLYFILL="P",Yr=Gr,Qr=n,Xr=o.f,$r=Yt,Zr=Zi,en=De,tn=Br,rn=Yr,nn=function(e,t){var i,r,n,o,s,a=e.target,c=e.global,l=e.stat;if(i=c?Qr:l?Qr[a]||en(a,{}):Qr[a]&&Qr[a].prototype)for(r in t){if(o=t[r],n=e.dontCallGetSet?(s=Xr(i,r))&&s.value:i[r],!rn(c?r:a+(l?".":"#")+r,e.forced)&&void 0!==n){if(typeof o==typeof n)continue;tn(o,n)}(e.sham||n&&n.sham)&&$r(o,"sham",!0),Zr(i,r,o,e)}},on={};on[rt("toStringTag")]="z";var sn="[object z]"===String(on),an=H,cn=b,ln=rt("toStringTag"),dn=Object,un="Arguments"===cn(function(){return arguments}()),hn=sn?cn:function(e){var t,i,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(i){}}(t=dn(e),ln))?i:un?cn(t):"Object"===(r=cn(t))&&an(t.callee)?"Arguments":r},pn=hn,mn=String,_n=function(e){if("Symbol"===pn(e))throw new TypeError("Cannot convert a Symbol value to a string");return mn(e)},fn=Ki,gn=Dt,vn=function(e,t,i){return i.get&&fn(i.get,t,{getter:!0}),i.set&&fn(i.set,t,{setter:!0}),gn.f(e,t,i)},yn=nn,Tn=a,Sn=I,En=We,In=H,Rn=q,Cn=_n,An=vn,bn=Br,kn=n.Symbol,wn=kn&&kn.prototype;if(Tn&&In(kn)&&(!("description"in wn)||void 0!==kn().description)){var Dn={},Nn=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:Cn(arguments[0]),t=Rn(wn,this)?new kn(e):void 0===e?kn():kn(e);return""===e&&(Dn[t]=!0),t};bn(Nn,kn),Nn.prototype=wn,wn.constructor=Nn;var On="Symbol(description detection)"===String(kn("description detection")),Pn=Sn(wn.valueOf),Mn=Sn(wn.toString),Ln=/^Symbol\((.*)\)[^)]+$/,xn=Sn("".replace),Vn=Sn("".slice);An(wn,"description",{configurable:!0,get:function(){var e=Pn(this);if(En(Dn,e))return"";var t=Mn(e),i=On?Vn(t,7,-1):xn(t,Ln,"$1");return""===i?void 0:i}}),yn({global:!0,constructor:!0,forced:!0},{Symbol:Nn})}var Un={},Fn=Cr,Bn=Ar,Hn=Object.keys||function(e){return Fn(e,Bn)},jn=a,Wn=Nt,Gn=Dt,Jn=Lt,zn=F,qn=Hn;Un.f=jn&&!Wn?Object.defineProperties:function(e,t){Jn(e);for(var i,r=zn(t),n=qn(t),o=n.length,s=0;o>s;)Gn.f(e,i=n[s++],r[i]);return e};var Kn,Yn=z("document","documentElement"),Qn=Lt,Xn=Un,$n=Ar,Zn=fi,eo=Yn,to=vt,io="prototype",ro="script",no=_i("IE_PROTO"),oo=function(){},so=function(e){return"<"+ro+">"+e+"</"+ro+">"},ao=function(e){e.write(so("")),e.close();var t=e.parentWindow.Object;return e=null,t},co=function(){try{Kn=new ActiveXObject("htmlfile")}catch(n){}var e,t,i;co="undefined"!=typeof document?document.domain&&Kn?ao(Kn):(t=to("iframe"),i="java"+ro+":",t.style.display="none",eo.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(so("document.F=Object")),e.close(),e.F):ao(Kn);for(var r=$n.length;r--;)delete co[io][$n[r]];return co()};Zn[no]=!0;var lo=Object.create||function(e,t){var i;return null!==e?(oo[io]=Qn(e),i=new oo,oo[io]=null,i[no]=e):i=co(),void 0===t?i:Xn.f(i,t)},uo=rt,ho=lo,po=Dt.f,mo=uo("unscopables"),_o=Array.prototype;void 0===_o[mo]&&po(_o,mo,{configurable:!0,value:ho(null)});var fo=function(e){_o[mo][e]=!0},go=yr.includes,vo=fo;nn({target:"Array",proto:!0,forced:s((function(){return!Array(1).includes()}))},{includes:function(e){return go(this,e,arguments.length>1?arguments[1]:void 0)}}),vo("includes");var yo,To,So,Eo={},Io=!s((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Ro=We,Co=H,Ao=Be,bo=Io,ko=_i("IE_PROTO"),wo=Object,Do=wo.prototype,No=bo?wo.getPrototypeOf:function(e){var t=Ao(e);if(Ro(t,ko))return t[ko];var i=t.constructor;return Co(i)&&t instanceof i?i.prototype:t instanceof wo?Do:null},Oo=s,Po=H,Mo=W,Lo=No,xo=Zi,Vo=rt("iterator"),Uo=!1;[].keys&&("next"in(So=[].keys())?(To=Lo(Lo(So)))!==Object.prototype&&(yo=To):Uo=!0);var Fo=!Mo(yo)||Oo((function(){var e={};return yo[Vo].call(e)!==e}));Fo&&(yo={}),Po(yo[Vo])||xo(yo,Vo,(function(){return this}));var Bo={IteratorPrototype:yo,BUGGY_SAFARI_ITERATORS:Uo},Ho=Dt.f,jo=We,Wo=rt("toStringTag"),Go=function(e,t,i){e&&!i&&(e=e.prototype),e&&!jo(e,Wo)&&Ho(e,Wo,{configurable:!0,value:t})},Jo=Bo.IteratorPrototype,zo=lo,qo=v,Ko=Go,Yo=Eo,Qo=function(){return this},Xo=function(e,t,i,r){var n=t+" Iterator";return e.prototype=zo(Jo,{next:qo(+!r,i)}),Ko(e,n,!1),Yo[n]=Qo,e},$o=I,Zo=ye,es=W,ts=function(e){return es(e)||null===e},is=String,rs=TypeError,ns=function(e,t,i){try{return $o(Zo(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},os=W,ss=x,as=function(e){if(ts(e))return e;throw new rs("Can't set "+is(e)+" as a prototype")},cs=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=ns(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return ss(i),as(r),os(i)?(t?e(i,r):i.__proto__=r,i):i}}():void 0),ls=nn,ds=u,us=H,hs=Xo,ps=No,ms=cs,_s=Go,fs=Yt,gs=Zi,vs=Eo,ys=ii.PROPER,Ts=ii.CONFIGURABLE,Ss=Bo.IteratorPrototype,Es=Bo.BUGGY_SAFARI_ITERATORS,Is=rt("iterator"),Rs="keys",Cs="values",As="entries",bs=function(){return this},ks=function(e,t,i,r,n,o,s){hs(i,t,r);var a,c,l,d=function(e){if(e===n&&_)return _;if(!Es&&e&&e in p)return p[e];switch(e){case Rs:case Cs:case As:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[Is]||p["@@iterator"]||n&&p[n],_=!Es&&m||d(n),f="Array"===t&&p.entries||m;if(f&&(a=ps(f.call(new e)))!==Object.prototype&&a.next&&(ps(a)!==Ss&&(ms?ms(a,Ss):us(a[Is])||gs(a,Is,bs)),_s(a,u,!0)),ys&&n===Cs&&m&&m.name!==Cs&&(Ts?fs(p,"name",Cs):(h=!0,_=function(){return ds(m,this)})),n)if(c={values:d(Cs),keys:o?_:d(Rs),entries:d(As)},s)for(l in c)(Es||h||!(l in p))&&gs(p,l,c[l]);else ls({target:t,proto:!0,forced:Es||h},c);return p[Is]!==_&&gs(p,Is,_,{name:n}),vs[t]=_,c},ws=function(e,t){return{value:e,done:t}},Ds=F,Ns=fo,Os=Eo,Ps=Di,Ms=Dt.f,Ls=ks,xs=ws,Vs=a,Us="Array Iterator",Fs=Ps.set,Bs=Ps.getterFor(Us),Hs=Ls(Array,"Array",(function(e,t){Fs(this,{type:Us,target:Ds(e),index:0,kind:t})}),(function(){var e=Bs(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,xs(void 0,!0);switch(e.kind){case"keys":return xs(i,!1);case"values":return xs(t[i],!1)}return xs([i,t[i]],!1)}),"values"),js=Os.Arguments=Os.Array;if(Ns("keys"),Ns("values"),Ns("entries"),Vs&&"values"!==js.name)try{Ms(js,"name",{value:"values"})}catch(pH){}var Ws=ye,Gs=Be,Js=O,zs=mr,qs=TypeError,Ks="Reduce of empty array with no initial value",Ys=function(e){return function(t,i,r,n){var o=Gs(t),s=Js(o),a=zs(o);if(Ws(i),0===a&&r<2)throw new qs(Ks);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 qs(Ks)}for(;e?c>=0:a>c;c+=l)c in s&&(n=i(n,s[c],c,o));return n}},Qs={left:Ys(!1),right:Ys(!0)},Xs=s,$s=function(e,t){var i=[][e];return!!i&&Xs((function(){i.call(null,t||function(){return 1},1)}))},Zs=n,ea=Q,ta=b,ia=function(e){return ea.slice(0,e.length)===e},ra=ia("Bun/")?"BUN":ia("Cloudflare-Workers")?"CLOUDFLARE":ia("Deno/")?"DENO":ia("Node.js/")?"NODE":Zs.Bun&&"string"==typeof Bun.version?"BUN":Zs.Deno&&"object"==typeof Deno.version?"DENO":"process"===ta(Zs.process)?"NODE":Zs.window&&Zs.document?"BROWSER":"REST",na="NODE"===ra,oa=Qs.left;nn({target:"Array",proto:!0,forced:!na&&re>79&&re<83||!$s("reduce")},{reduce:function(e){var t=arguments.length;return oa(this,e,t,t>1?arguments[1]:void 0)}});var sa=b,aa=Array.isArray||function(e){return"Array"===sa(e)},ca=nn,la=aa,da=I([].reverse),ua=[1,2];ca({target:"Array",proto:!0,forced:String(ua)===String(ua.reverse())},{reverse:function(){return la(this)&&(this.length=this.length),da(this)}});var ha=_e,pa=TypeError,ma=I([].slice),_a=ma,fa=Math.floor,ga=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=fa(i/2),a=ga(_a(e,0,s),t),c=ga(_a(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},va=ga,ya=Q.match(/firefox\/(\d+)/i),Ta=!!ya&&+ya[1],Sa=/MSIE|Trident/.test(Q),Ea=Q.match(/AppleWebKit\/(\d+)\./),Ia=!!Ea&&+Ea[1],Ra=nn,Ca=I,Aa=ye,ba=Be,ka=mr,wa=function(e,t){if(!delete e[t])throw new pa("Cannot delete property "+ha(t)+" of "+ha(e))},Da=_n,Na=s,Oa=va,Pa=$s,Ma=Ta,La=Sa,xa=re,Va=Ia,Ua=[],Fa=Ca(Ua.sort),Ba=Ca(Ua.push),Ha=Na((function(){Ua.sort(void 0)})),ja=Na((function(){Ua.sort(null)})),Wa=Pa("sort"),Ga=!Na((function(){if(xa)return xa<70;if(!(Ma&&Ma>3)){if(La)return!0;if(Va)return Va<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++)Ua.push({k:t+r,v:i})}for(Ua.sort((function(e,t){return t.v-e.v})),r=0;r<Ua.length;r++)t=Ua[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));Ra({target:"Array",proto:!0,forced:Ha||!ja||!Wa||!Ga},{sort:function(e){void 0!==e&&Aa(e);var t=ba(this);if(Ga)return void 0===e?Fa(t):Fa(t,e);var i,r,n=[],o=ka(t);for(r=0;r<o;r++)r in t&&Ba(n,t[r]);for(Oa(n,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:Da(t)>Da(i)?1:-1}}(e)),i=ka(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)wa(t,r++);return t}});var Ja="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,za=Zi,qa=function(e,t,i){for(var r in t)za(e,r,t[r],i);return e},Ka=q,Ya=TypeError,Qa=function(e,t){if(Ka(t,e))return e;throw new Ya("Incorrect invocation")},Xa=or,$a=hr,Za=RangeError,ec=function(e){if(void 0===e)return 0;var t=Xa(e),i=$a(t);if(t!==i)throw new Za("Wrong length or index");return i},tc=Math.sign||function(e){var t=+e;return 0===t||t!=t?t:t<0?-1:1},ic=4503599627370496,rc=tc,nc=function(e){return e+ic-ic},oc=Math.abs,sc=function(e,t,i,r){var n=+e,o=oc(n),s=rc(n);if(o<r)return s*nc(o/r/t)*r*t;var a=(1+t/2220446049250313e-31)*o,c=a-(a-o);return c>i||c!=c?Infinity*s:s*c},ac=Math.fround||function(e){return sc(e,1.1920928955078125e-7,34028234663852886e22,11754943508222875e-54)},cc=Array,lc=Math.abs,dc=Math.pow,uc=Math.floor,hc=Math.log,pc=Math.LN2,mc={pack:function(e,t,i){var r,n,o,s=cc(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?dc(2,-24)-dc(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=lc(e))!=e||Infinity===e?(n=e!=e?1:0,r=c):(r=uc(hc(e)/pc),e*(o=dc(2,-r))<1&&(r--,o*=2),(e+=r+l>=1?d/o:d*dc(2,1-l))*o>=2&&(r++,o/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*o-1)*dc(2,t),r+=l):(n=e*dc(2,l-1)*dc(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+=dc(2,t),d-=s}return(l?-1:1)*i*dc(2,d-t)}},_c=Be,fc=lr,gc=mr,vc=function(e){for(var t=_c(this),i=gc(t),r=arguments.length,n=fc(r>1?arguments[1]:void 0,i),o=r>2?arguments[2]:void 0,s=void 0===o?i:fc(o,i);s>n;)t[n++]=e;return t},yc=H,Tc=W,Sc=cs,Ec=function(e,t,i){var r,n;return Sc&&yc(r=t.constructor)&&r!==i&&Tc(n=r.prototype)&&n!==i.prototype&&Sc(e,n),e},Ic=n,Rc=I,Cc=a,Ac=Ja,bc=Yt,kc=vn,wc=qa,Dc=s,Nc=Qa,Oc=or,Pc=hr,Mc=ec,Lc=ac,xc=mc,Vc=No,Uc=cs,Fc=vc,Bc=ma,Hc=Ec,jc=Br,Wc=Go,Gc=Di,Jc=ii.PROPER,zc=ii.CONFIGURABLE,qc="ArrayBuffer",Kc="DataView",Yc="prototype",Qc="Wrong index",Xc=Gc.getterFor(qc),$c=Gc.getterFor(Kc),Zc=Gc.set,el=Ic[qc],tl=el,il=tl&&tl[Yc],rl=Ic[Kc],nl=rl&&rl[Yc],ol=Object.prototype,sl=Ic.Array,al=Ic.RangeError,cl=Rc(Fc),ll=Rc([].reverse),dl=xc.pack,ul=xc.unpack,hl=function(e){return[255&e]},pl=function(e){return[255&e,e>>8&255]},ml=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},_l=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},fl=function(e){return dl(Lc(e),23,4)},gl=function(e){return dl(e,52,8)},vl=function(e,t,i){kc(e[Yc],t,{configurable:!0,get:function(){return i(this)[t]}})},yl=function(e,t,i,r){var n=$c(e),o=Mc(i),s=!!r;if(o+t>n.byteLength)throw new al(Qc);var a=n.bytes,c=o+n.byteOffset,l=Bc(a,c,c+t);return s?l:ll(l)},Tl=function(e,t,i,r,n,o){var s=$c(e),a=Mc(i),c=r(+n),l=!!o;if(a+t>s.byteLength)throw new al(Qc);for(var d=s.bytes,u=a+s.byteOffset,h=0;h<t;h++)d[u+h]=c[l?h:t-h-1]};if(Ac){var Sl=Jc&&el.name!==qc;Dc((function(){el(1)}))&&Dc((function(){new el(-1)}))&&!Dc((function(){return new el,new el(1.5),new el(NaN),1!==el.length||Sl&&!zc}))?Sl&&zc&&bc(el,"name",qc):((tl=function(e){return Nc(this,il),Hc(new el(Mc(e)),this,tl)})[Yc]=il,il.constructor=tl,jc(tl,el)),Uc&&Vc(nl)!==ol&&Uc(nl,ol);var El=new rl(new tl(2)),Il=Rc(nl.setInt8);El.setInt8(0,2147483648),El.setInt8(1,2147483649),!El.getInt8(0)&&El.getInt8(1)||wc(nl,{setInt8:function(e,t){Il(this,e,t<<24>>24)},setUint8:function(e,t){Il(this,e,t<<24>>24)}},{unsafe:!0})}else il=(tl=function(e){Nc(this,il);var t=Mc(e);Zc(this,{type:qc,bytes:cl(sl(t),0),byteLength:t}),Cc||(this.byteLength=t,this.detached=!1)})[Yc],nl=(rl=function(e,t,i){Nc(this,nl),Nc(e,il);var r=Xc(e),n=r.byteLength,o=Oc(t);if(o<0||o>n)throw new al("Wrong offset");if(o+(i=void 0===i?n-o:Pc(i))>n)throw new al("Wrong length");Zc(this,{type:Kc,buffer:e,byteLength:i,byteOffset:o,bytes:r.bytes}),Cc||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[Yc],Cc&&(vl(tl,"byteLength",Xc),vl(rl,"buffer",$c),vl(rl,"byteLength",$c),vl(rl,"byteOffset",$c)),wc(nl,{getInt8:function(e){return yl(this,1,e)[0]<<24>>24},getUint8:function(e){return yl(this,1,e)[0]},getInt16:function(e){var t=yl(this,2,e,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=yl(this,2,e,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return _l(yl(this,4,e,arguments.length>1&&arguments[1]))},getUint32:function(e){return _l(yl(this,4,e,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(e){return ul(yl(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return ul(yl(this,8,e,arguments.length>1&&arguments[1]),52)},setInt8:function(e,t){Tl(this,1,e,hl,t)},setUint8:function(e,t){Tl(this,1,e,hl,t)},setInt16:function(e,t){Tl(this,2,e,pl,t,arguments.length>2&&arguments[2])},setUint16:function(e,t){Tl(this,2,e,pl,t,arguments.length>2&&arguments[2])},setInt32:function(e,t){Tl(this,4,e,ml,t,arguments.length>2&&arguments[2])},setUint32:function(e,t){Tl(this,4,e,ml,t,arguments.length>2&&arguments[2])},setFloat32:function(e,t){Tl(this,4,e,fl,t,arguments.length>2&&arguments[2])},setFloat64:function(e,t){Tl(this,8,e,gl,t,arguments.length>2&&arguments[2])}});Wc(tl,qc),Wc(rl,Kc);var Rl={ArrayBuffer:tl,DataView:rl},Cl=z,Al=vn,bl=a,kl=rt("species"),wl=function(e){var t=Cl(e);bl&&t&&!t[kl]&&Al(t,kl,{configurable:!0,get:function(){return this}})},Dl=wl,Nl="ArrayBuffer",Ol=Rl[Nl];nn({global:!0,constructor:!0,forced:n[Nl]!==Ol},{ArrayBuffer:Ol}),Dl(Nl);var Pl=b,Ml=I,Ll=function(e){if("Function"===Pl(e))return Ml(e)},xl=nn,Vl=Ll,Ul=s,Fl=Lt,Bl=lr,Hl=hr,jl=Rl.ArrayBuffer,Wl=Rl.DataView,Gl=Wl.prototype,Jl=Vl(jl.prototype.slice),zl=Vl(Gl.getUint8),ql=Vl(Gl.setUint8);xl({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:Ul((function(){return!new jl(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(Jl&&void 0===t)return Jl(Fl(this),e);for(var i=Fl(this).byteLength,r=Bl(e,i),n=Bl(void 0===t?i:t,i),o=new jl(Hl(n-r)),s=new Wl(this),a=new Wl(o),c=0;r<n;)ql(a,c++,zl(s,r++));return o}});var Kl=I,Yl=s,Ql=H,Xl=hn,$l=li,Zl=function(){},ed=z("Reflect","construct"),td=/^\s*(?:class|function)\b/,id=Kl(td.exec),rd=!td.test(Zl),nd=function(e){if(!Ql(e))return!1;try{return ed(Zl,[],e),!0}catch(pH){return!1}},od=function(e){if(!Ql(e))return!1;switch(Xl(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return rd||!!id(td,$l(e))}catch(pH){return!0}};od.sham=!0;var sd,ad,cd,ld,dd=!ed||Yl((function(){var e;return nd(nd.call)||!nd(Object)||!nd((function(){e=!0}))||e}))?od:nd,ud=dd,hd=_e,pd=TypeError,md=function(e){if(ud(e))return e;throw new pd(hd(e)+" is not a constructor")},_d=Lt,fd=md,gd=P,vd=rt("species"),yd=function(e,t){var i,r=_d(e).constructor;return void 0===r||gd(i=_d(r)[vd])?t:fd(i)},Td=c,Sd=Function.prototype,Ed=Sd.apply,Id=Sd.call,Rd="object"==typeof Reflect&&Reflect.apply||(Td?Id.bind(Ed):function(){return Id.apply(Ed,arguments)}),Cd=ye,Ad=c,bd=Ll(Ll.bind),kd=function(e,t){return Cd(e),void 0===t?e:Ad?bd(e,t):function(){return e.apply(t,arguments)}},wd=TypeError,Dd=function(e,t){if(e<t)throw new wd("Not enough arguments");return e},Nd=/(?:ipad|iphone|ipod).*applewebkit/i.test(Q),Od=n,Pd=Rd,Md=kd,Ld=H,xd=We,Vd=s,Ud=Yn,Fd=ma,Bd=vt,Hd=Dd,jd=Nd,Wd=na,Gd=Od.setImmediate,Jd=Od.clearImmediate,zd=Od.process,qd=Od.Dispatch,Kd=Od.Function,Yd=Od.MessageChannel,Qd=Od.String,Xd=0,$d={},Zd="onreadystatechange";Vd((function(){sd=Od.location}));var eu=function(e){if(xd($d,e)){var t=$d[e];delete $d[e],t()}},tu=function(e){return function(){eu(e)}},iu=function(e){eu(e.data)},ru=function(e){Od.postMessage(Qd(e),sd.protocol+"//"+sd.host)};Gd&&Jd||(Gd=function(e){Hd(arguments.length,1);var t=Ld(e)?e:Kd(e),i=Fd(arguments,1);return $d[++Xd]=function(){Pd(t,void 0,i)},ad(Xd),Xd},Jd=function(e){delete $d[e]},Wd?ad=function(e){zd.nextTick(tu(e))}:qd&&qd.now?ad=function(e){qd.now(tu(e))}:Yd&&!jd?(ld=(cd=new Yd).port2,cd.port1.onmessage=iu,ad=Md(ld.postMessage,ld)):Od.addEventListener&&Ld(Od.postMessage)&&!Od.importScripts&&sd&&"file:"!==sd.protocol&&!Vd(ru)?(ad=ru,Od.addEventListener("message",iu,!1)):ad=Zd in Bd("script")?function(e){Ud.appendChild(Bd("script"))[Zd]=function(){Ud.removeChild(this),eu(e)}}:function(e){setTimeout(tu(e),0)});var nu={set:Gd,clear:Jd},ou=n,su=a,au=Object.getOwnPropertyDescriptor,cu=function(e){if(!su)return ou[e];var t=au(ou,e);return t&&t.value},lu=function(){this.head=null,this.tail=null};lu.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var du,uu,hu,pu,mu,_u=lu,fu=/ipad|iphone|ipod/i.test(Q)&&"undefined"!=typeof Pebble,gu=/web0s(?!.*chrome)/i.test(Q),vu=n,yu=cu,Tu=kd,Su=nu.set,Eu=_u,Iu=Nd,Ru=fu,Cu=gu,Au=na,bu=vu.MutationObserver||vu.WebKitMutationObserver,ku=vu.document,wu=vu.process,Du=vu.Promise,Nu=yu("queueMicrotask");if(!Nu){var Ou=new Eu,Pu=function(){var e,t;for(Au&&(e=wu.domain)&&e.exit();t=Ou.get();)try{t()}catch(pH){throw Ou.head&&du(),pH}e&&e.enter()};Iu||Au||Cu||!bu||!ku?!Ru&&Du&&Du.resolve?((pu=Du.resolve(void 0)).constructor=Du,mu=Tu(pu.then,pu),du=function(){mu(Pu)}):Au?du=function(){wu.nextTick(Pu)}:(Su=Tu(Su,vu),du=function(){Su(Pu)}):(uu=!0,hu=ku.createTextNode(""),new bu(Pu).observe(hu,{characterData:!0}),du=function(){hu.data=uu=!uu}),Nu=function(e){Ou.head||du(),Ou.add(e)}}var Mu=Nu,Lu=function(e){try{return{error:!1,value:e()}}catch(pH){return{error:!0,value:pH}}},xu=n.Promise,Vu=n,Uu=xu,Fu=H,Bu=Yr,Hu=li,ju=rt,Wu=ra,Gu=re;Uu&&Uu.prototype;var Ju=ju("species"),zu=!1,qu=Fu(Vu.PromiseRejectionEvent),Ku=Bu("Promise",(function(){var e=Hu(Uu),t=e!==String(Uu);if(!t&&66===Gu)return!0;if(!Gu||Gu<51||!/native code/.test(e)){var i=new Uu((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((i.constructor={})[Ju]=r,!(zu=i.then((function(){}))instanceof r))return!0}return!(t||"BROWSER"!==Wu&&"DENO"!==Wu||qu)})),Yu={CONSTRUCTOR:Ku,REJECTION_EVENT:qu,SUBCLASSING:zu},Qu={},Xu=ye,$u=TypeError,Zu=function(e){var t,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw new $u("Bad Promise constructor");t=e,i=r})),this.resolve=Xu(t),this.reject=Xu(i)};Qu.f=function(e){return new Zu(e)};var eh,th,ih,rh=nn,nh=na,oh=n,sh=u,ah=Zi,ch=cs,lh=Go,dh=wl,uh=ye,hh=H,ph=W,mh=Qa,_h=yd,fh=nu.set,gh=Mu,vh=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(pH){}},yh=Lu,Th=_u,Sh=Di,Eh=xu,Ih=Qu,Rh="Promise",Ch=Yu.CONSTRUCTOR,Ah=Yu.REJECTION_EVENT,bh=Yu.SUBCLASSING,kh=Sh.getterFor(Rh),wh=Sh.set,Dh=Eh&&Eh.prototype,Nh=Eh,Oh=Dh,Ph=oh.TypeError,Mh=oh.document,Lh=oh.process,xh=Ih.f,Vh=xh,Uh=!!(Mh&&Mh.createEvent&&oh.dispatchEvent),Fh="unhandledrejection",Bh=function(e){var t;return!(!ph(e)||!hh(t=e.then))&&t},Hh=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&&zh(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),n=!0)),i===e.promise?l(new Ph("Promise-chain cycle")):(r=Bh(i))?sh(r,i,c,l):c(i)):l(o)}catch(pH){d&&!n&&d.exit(),l(pH)}},jh=function(e,t){e.notified||(e.notified=!0,gh((function(){for(var i,r=e.reactions;i=r.get();)Hh(i,e);e.notified=!1,t&&!e.rejection&&Gh(e)})))},Wh=function(e,t,i){var r,n;Uh?((r=Mh.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),oh.dispatchEvent(r)):r={promise:t,reason:i},!Ah&&(n=oh["on"+e])?n(r):e===Fh&&vh("Unhandled promise rejection",i)},Gh=function(e){sh(fh,oh,(function(){var t,i=e.facade,r=e.value;if(Jh(e)&&(t=yh((function(){nh?Lh.emit("unhandledRejection",r,i):Wh(Fh,i,r)})),e.rejection=nh||Jh(e)?2:1,t.error))throw t.value}))},Jh=function(e){return 1!==e.rejection&&!e.parent},zh=function(e){sh(fh,oh,(function(){var t=e.facade;nh?Lh.emit("rejectionHandled",t):Wh("rejectionhandled",t,e.value)}))},qh=function(e,t,i){return function(r){e(t,r,i)}},Kh=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,jh(e,!0))},Yh=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new Ph("Promise can't be resolved itself");var r=Bh(t);r?gh((function(){var i={done:!1};try{sh(r,t,qh(Yh,i,e),qh(Kh,i,e))}catch(pH){Kh(i,pH,e)}})):(e.value=t,e.state=1,jh(e,!1))}catch(pH){Kh({done:!1},pH,e)}}};if(Ch&&(Oh=(Nh=function(e){mh(this,Oh),uh(e),sh(eh,this);var t=kh(this);try{e(qh(Yh,t),qh(Kh,t))}catch(pH){Kh(t,pH)}}).prototype,(eh=function(e){wh(this,{type:Rh,done:!1,notified:!1,parent:!1,reactions:new Th,rejection:!1,state:0,value:null})}).prototype=ah(Oh,"then",(function(e,t){var i=kh(this),r=xh(_h(this,Nh));return i.parent=!0,r.ok=!hh(e)||e,r.fail=hh(t)&&t,r.domain=nh?Lh.domain:void 0,0===i.state?i.reactions.add(r):gh((function(){Hh(r,i)})),r.promise})),th=function(){var e=new eh,t=kh(e);this.promise=e,this.resolve=qh(Yh,t),this.reject=qh(Kh,t)},Ih.f=xh=function(e){return e===Nh||undefined===e?new th(e):Vh(e)},hh(Eh)&&Dh!==Object.prototype)){ih=Dh.then,bh||ah(Dh,"then",(function(e,t){var i=this;return new Nh((function(e,t){sh(ih,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete Dh.constructor}catch(pH){}ch&&ch(Dh,Oh)}rh({global:!0,constructor:!0,wrap:!0,forced:Ch},{Promise:Nh}),lh(Nh,Rh,!1),dh(Rh);var Qh=Eo,Xh=rt("iterator"),$h=Array.prototype,Zh=function(e){return void 0!==e&&(Qh.Array===e||$h[Xh]===e)},ep=hn,tp=Ee,ip=P,rp=Eo,np=rt("iterator"),op=function(e){if(!ip(e))return tp(e,np)||tp(e,"@@iterator")||rp[ep(e)]},sp=u,ap=ye,cp=Lt,lp=_e,dp=op,up=TypeError,hp=function(e,t){var i=arguments.length<2?dp(e):t;if(ap(i))return cp(sp(i,e));throw new up(lp(e)+" is not iterable")},pp=u,mp=Lt,_p=Ee,fp=function(e,t,i){var r,n;mp(e);try{if(!(r=_p(e,"return"))){if("throw"===t)throw i;return i}r=pp(r,e)}catch(pH){n=!0,r=pH}if("throw"===t)throw i;if(n)throw r;return mp(r),i},gp=kd,vp=u,yp=Lt,Tp=_e,Sp=Zh,Ep=mr,Ip=q,Rp=hp,Cp=op,Ap=fp,bp=TypeError,kp=function(e,t){this.stopped=e,this.result=t},wp=kp.prototype,Dp=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),_=gp(t,d),f=function(e){return r&&Ap(r,"normal",e),new kp(!0,e)},g=function(e){return u?(yp(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=Cp(e)))throw new bp(Tp(e)+" is not iterable");if(Sp(n)){for(o=0,s=Ep(e);s>o;o++)if((a=g(e[o]))&&Ip(wp,a))return a;return new kp(!1)}r=Rp(e,n)}for(c=h?e.next:r.next;!(l=vp(c,r)).done;){try{a=g(l.value)}catch(pH){Ap(r,"throw",pH)}if("object"==typeof a&&a&&Ip(wp,a))return a}return new kp(!1)},Np=rt("iterator"),Op=!1;try{var Pp=0,Mp={next:function(){return{done:!!Pp++}},return:function(){Op=!0}};Mp[Np]=function(){return this},Array.from(Mp,(function(){throw 2}))}catch(pH){}var Lp=function(e,t){try{if(!t&&!Op)return!1}catch(pH){return!1}var i=!1;try{var r={};r[Np]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(pH){}return i},xp=xu,Vp=Yu.CONSTRUCTOR||!Lp((function(e){xp.all(e).then(void 0,(function(){}))})),Up=u,Fp=ye,Bp=Qu,Hp=Lu,jp=Dp;nn({target:"Promise",stat:!0,forced:Vp},{all:function(e){var t=this,i=Bp.f(t),r=i.resolve,n=i.reject,o=Hp((function(){var i=Fp(t.resolve),o=[],s=0,a=1;jp(e,(function(e){var c=s++,l=!1;a++,Up(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 Wp=nn,Gp=Yu.CONSTRUCTOR,Jp=xu,zp=z,qp=H,Kp=Zi,Yp=Jp&&Jp.prototype;if(Wp({target:"Promise",proto:!0,forced:Gp,real:!0},{catch:function(e){return this.then(void 0,e)}}),qp(Jp)){var Qp=zp("Promise").prototype.catch;Yp.catch!==Qp&&Kp(Yp,"catch",Qp,{unsafe:!0})}var Xp=u,$p=ye,Zp=Qu,em=Lu,tm=Dp;nn({target:"Promise",stat:!0,forced:Vp},{race:function(e){var t=this,i=Zp.f(t),r=i.reject,n=em((function(){var n=$p(t.resolve);tm(e,(function(e){Xp(n,t,e).then(i.resolve,r)}))}));return n.error&&r(n.value),i.promise}});var im=Qu;nn({target:"Promise",stat:!0,forced:Yu.CONSTRUCTOR},{reject:function(e){var t=im.f(this);return(0,t.reject)(e),t.promise}});var rm=Lt,nm=W,om=Qu,sm=function(e,t){if(rm(e),nm(t)&&t.constructor===e)return t;var i=om.f(e);return(0,i.resolve)(t),i.promise},am=nn,cm=Yu.CONSTRUCTOR,lm=sm;z("Promise"),am({target:"Promise",stat:!0,forced:cm},{resolve:function(e){return lm(this,e)}});var dm=nn,um=xu,hm=s,pm=z,mm=H,_m=yd,fm=sm,gm=Zi,vm=um&&um.prototype;if(dm({target:"Promise",proto:!0,real:!0,forced:!!um&&hm((function(){vm.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=_m(this,pm("Promise")),i=mm(e);return this.then(i?function(i){return fm(t,e()).then((function(){return i}))}:e,i?function(i){return fm(t,e()).then((function(){throw i}))}:e)}}),mm(um)){var ym=pm("Promise").prototype.finally;vm.finally!==ym&&gm(vm,"finally",ym,{unsafe:!0})}var Tm=W,Sm=b,Em=rt("match"),Im=Lt,Rm=function(){var e=Im(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},Cm=u,Am=We,bm=q,km=Rm,wm=RegExp.prototype,Dm=s,Nm=n.RegExp,Om=Dm((function(){var e=Nm("a","y");return e.lastIndex=2,null!==e.exec("abcd")})),Pm=Om||Dm((function(){return!Nm("a","y").sticky})),Mm=Om||Dm((function(){var e=Nm("^r","gy");return e.lastIndex=2,null!==e.exec("str")})),Lm={BROKEN_CARET:Mm,MISSED_STICKY:Pm,UNSUPPORTED_Y:Om},xm=Dt.f,Vm=s,Um=n.RegExp,Fm=Vm((function(){var e=Um(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)})),Bm=s,Hm=n.RegExp,jm=Bm((function(){var e=Hm("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Wm=a,Gm=n,Jm=I,zm=Yr,qm=Ec,Km=Yt,Ym=lo,Qm=er.f,Xm=q,$m=function(e){var t;return Tm(e)&&(void 0!==(t=e[Em])?!!t:"RegExp"===Sm(e))},Zm=_n,e_=function(e){var t=e.flags;return void 0!==t||"flags"in wm||Am(e,"flags")||!bm(wm,e)?t:Cm(km,e)},t_=Lm,i_=function(e,t,i){i in e||xm(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},r_=Zi,n_=s,o_=We,s_=Di.enforce,a_=wl,c_=Fm,l_=jm,d_=rt("match"),u_=Gm.RegExp,h_=u_.prototype,p_=Gm.SyntaxError,m_=Jm(h_.exec),__=Jm("".charAt),f_=Jm("".replace),g_=Jm("".indexOf),v_=Jm("".slice),y_=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,T_=/a/g,S_=/a/g,E_=new u_(T_)!==T_,I_=t_.MISSED_STICKY,R_=t_.UNSUPPORTED_Y,C_=Wm&&(!E_||I_||c_||l_||n_((function(){return S_[d_]=!1,u_(T_)!==T_||u_(S_)===S_||"/a/i"!==String(u_(T_,"i"))})));if(zm("RegExp",C_)){for(var A_=function(e,t){var i,r,n,o,s,a,c=Xm(h_,this),l=$m(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===A_)return e;if((l||Xm(h_,e))&&(e=e.source,d&&(t=e_(h))),e=void 0===e?"":Zm(e),t=void 0===t?"":Zm(t),h=e,c_&&"dotAll"in T_&&(r=!!t&&g_(t,"s")>-1)&&(t=f_(t,/s/g,"")),i=t,I_&&"sticky"in T_&&(n=!!t&&g_(t,"y")>-1)&&R_&&(t=f_(t,/y/g,"")),l_&&(o=function(e){for(var t,i=e.length,r=0,n="",o=[],s=Ym(null),a=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=__(e,r)))t+=__(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:if(n+=t,"?:"===v_(e,r+1,r+3))continue;m_(y_,v_(e,r+1))&&(r+=2,c=!0),l++;continue;case">"===t&&c:if(""===d||o_(s,d))throw new p_("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=qm(u_(e,t),c?this:h_,A_),(r||n||u.length)&&(a=s_(s),r&&(a.dotAll=!0,a.raw=A_(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=__(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+__(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Km(s,"source",""===h?"(?:)":h)}catch(pH){}return s},b_=Qm(u_),k_=0;b_.length>k_;)i_(A_,u_,b_[k_++]);h_.constructor=A_,A_.prototype=h_,r_(Gm,"RegExp",A_,{constructor:!0})}a_("RegExp");var w_=u,D_=I,N_=_n,O_=Rm,P_=Lm,M_=lo,L_=Di.get,x_=Fm,V_=jm,U_=Ve("native-string-replace",String.prototype.replace),F_=RegExp.prototype.exec,B_=F_,H_=D_("".charAt),j_=D_("".indexOf),W_=D_("".replace),G_=D_("".slice),J_=function(){var e=/a/,t=/b*/g;return w_(F_,e,"a"),w_(F_,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),z_=P_.BROKEN_CARET,q_=void 0!==/()??/.exec("")[1];(J_||q_||z_||x_||V_)&&(B_=function(e){var t,i,r,n,o,s,a,c=this,l=L_(c),d=N_(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=w_(B_,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=z_&&c.sticky,m=w_(O_,c),_=c.source,f=0,g=d;if(p&&(m=W_(m,"y",""),-1===j_(m,"g")&&(m+="g"),g=G_(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==H_(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),q_&&(i=new RegExp("^"+_+"$(?!\\s)",m)),J_&&(r=c.lastIndex),n=w_(F_,p?i:c,g),p?n?(n.input=G_(n.input,f),n[0]=G_(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:J_&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),q_&&n&&n.length>1&&w_(U_,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=M_(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=n[a[1]];return n});var K_=B_;nn({target:"RegExp",proto:!0,forced:/./.exec!==K_},{exec:K_});var Y_=or,Q_=_n,X_=x,$_=RangeError,Z_=I,ef=hr,tf=_n,rf=function(e){var t=Q_(X_(this)),i="",r=Y_(e);if(r<0||Infinity===r)throw new $_("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},nf=x,of=Z_(rf),sf=Z_("".slice),af=Math.ceil,cf=function(e){return function(t,i,r){var n,o,s=tf(nf(t)),a=ef(i),c=s.length,l=void 0===r?" ":tf(r);return a<=c||""===l?s:((o=of(l,af((n=a-c)/l.length))).length>n&&(o=sf(o,0,n)),e?s+o:o+s)}},lf={start:cf(!1),end:cf(!0)},df=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Q),uf=lf.start;nn({target:"String",proto:!0,forced:df},{padStart:function(e){return uf(this,e,arguments.length>1?arguments[1]:void 0)}});var hf=u,pf=Zi,mf=K_,_f=s,ff=rt,gf=Yt,vf=ff("species"),yf=RegExp.prototype,Tf=I,Sf=or,Ef=_n,If=x,Rf=Tf("".charAt),Cf=Tf("".charCodeAt),Af=Tf("".slice),bf=function(e){return function(t,i){var r,n,o=Ef(If(t)),s=Sf(i),a=o.length;return s<0||s>=a?e?"":void 0:(r=Cf(o,s))<55296||r>56319||s+1===a||(n=Cf(o,s+1))<56320||n>57343?e?Rf(o,s):r:e?Af(o,s,s+2):n-56320+(r-55296<<10)+65536}},kf={codeAt:bf(!1),charAt:bf(!0)},wf=kf.charAt,Df=I,Nf=Be,Of=Math.floor,Pf=Df("".charAt),Mf=Df("".replace),Lf=Df("".slice),xf=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Vf=/\$([$&'`]|\d{1,2})/g,Uf=u,Ff=Lt,Bf=H,Hf=b,jf=K_,Wf=TypeError,Gf=Rd,Jf=u,zf=I,qf=function(e,t,i,r){var n=ff(e),o=!_f((function(){var t={};return t[n]=function(){return 7},7!==""[e](t)})),s=o&&!_f((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[vf]=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===mf||s===yf.exec?o&&!n?{done:!0,value:hf(a,t,i,r)}:{done:!0,value:hf(e,i,t,r)}:{done:!1}}));pf(String.prototype,e,c[0]),pf(yf,n,c[1])}r&&gf(yf[n],"sham",!0)},Kf=s,Yf=Lt,Qf=H,Xf=P,$f=or,Zf=hr,eg=_n,tg=x,ig=function(e,t,i){return t+(i?wf(e,t).length:1)},rg=Ee,ng=function(e,t,i,r,n,o){var s=i+e.length,a=r.length,c=Vf;return void 0!==n&&(n=Nf(n),c=xf),Mf(o,c,(function(o,c){var l;switch(Pf(c,0)){case"$":return"$";case"&":return e;case"`":return Lf(t,0,i);case"'":return Lf(t,s);case"<":l=n[Lf(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Of(d/10);return 0===u?o:u<=a?void 0===r[u-1]?Pf(c,1):r[u-1]+Pf(c,1):o}l=r[d-1]}return void 0===l?"":l}))},og=function(e,t){var i=e.exec;if(Bf(i)){var r=Uf(i,e,t);return null!==r&&Ff(r),r}if("RegExp"===Hf(e))return Uf(jf,e,t);throw new Wf("RegExp#exec called on incompatible receiver")},sg=rt("replace"),ag=Math.max,cg=Math.min,lg=zf([].concat),dg=zf([].push),ug=zf("".indexOf),hg=zf("".slice),pg="$0"==="a".replace(/./,"$0"),mg=!!/./[sg]&&""===/./[sg]("a","$0"),_g=!Kf((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));qf("replace",(function(e,t,i){var r=mg?"$":"$0";return[function(e,i){var r=tg(this),n=Xf(e)?void 0:rg(e,sg);return n?Jf(n,e,r,i):Jf(t,eg(r),e,i)},function(e,n){var o=Yf(this),s=eg(e);if("string"==typeof n&&-1===ug(n,r)&&-1===ug(n,"$<")){var a=i(t,o,s,n);if(a.done)return a.value}var c=Qf(n);c||(n=eg(n));var l,d=o.global;d&&(l=o.unicode,o.lastIndex=0);for(var u,h=[];null!==(u=og(o,s))&&(dg(h,u),d);){""===eg(u[0])&&(o.lastIndex=ig(s,Zf(o.lastIndex),l))}for(var p,m="",_=0,f=0;f<h.length;f++){for(var g,v=eg((u=h[f])[0]),y=ag(cg($f(u.index),s.length),0),T=[],S=1;S<u.length;S++)dg(T,void 0===(p=u[S])?p:String(p));var E=u.groups;if(c){var I=lg([v],T,y,s);void 0!==E&&dg(I,E),g=eg(Gf(n,void 0,I))}else g=ng(v,s,y,T,E,n);y>=_&&(m+=hg(s,_,y)+g,_=y+v.length)}return m+hg(s,_)}]}),!_g||!pg||mg);var fg="\t\n\v\f\r \u2028\u2029\ufeff",gg=x,vg=_n,yg=fg,Tg=I("".replace),Sg=RegExp("^["+yg+"]+"),Eg=RegExp("(^|[^"+yg+"])["+yg+"]+$"),Ig=function(e){return function(t){var i=vg(gg(t));return 1&e&&(i=Tg(i,Sg,"")),2&e&&(i=Tg(i,Eg,"$1")),i}},Rg={start:Ig(1),end:Ig(2),trim:Ig(3)},Cg=ii.PROPER,Ag=s,bg=fg,kg=Rg.trim;nn({target:"String",proto:!0,forced:function(e){return Ag((function(){return!!bg[e]()||"
"!=="
"[e]()||Cg&&bg[e].name!==e}))}("trim")},{trim:function(){return kg(this)}});var wg,Dg,Ng,Og={exports:{}},Pg=Ja,Mg=a,Lg=n,xg=H,Vg=W,Ug=We,Fg=hn,Bg=_e,Hg=Yt,jg=Zi,Wg=vn,Gg=q,Jg=No,zg=cs,qg=rt,Kg=Ke,Yg=Di.enforce,Qg=Di.get,Xg=Lg.Int8Array,$g=Xg&&Xg.prototype,Zg=Lg.Uint8ClampedArray,ev=Zg&&Zg.prototype,tv=Xg&&Jg(Xg),iv=$g&&Jg($g),rv=Object.prototype,nv=Lg.TypeError,ov=qg("toStringTag"),sv=Kg("TYPED_ARRAY_TAG"),av="TypedArrayConstructor",cv=Pg&&!!zg&&"Opera"!==Fg(Lg.opera),lv=!1,dv={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},uv={BigInt64Array:8,BigUint64Array:8},hv=function(e){var t=Jg(e);if(Vg(t)){var i=Qg(t);return i&&Ug(i,av)?i[av]:hv(t)}},pv=function(e){if(!Vg(e))return!1;var t=Fg(e);return Ug(dv,t)||Ug(uv,t)};for(wg in dv)(Ng=(Dg=Lg[wg])&&Dg.prototype)?Yg(Ng)[av]=Dg:cv=!1;for(wg in uv)(Ng=(Dg=Lg[wg])&&Dg.prototype)&&(Yg(Ng)[av]=Dg);if((!cv||!xg(tv)||tv===Function.prototype)&&(tv=function(){throw new nv("Incorrect invocation")},cv))for(wg in dv)Lg[wg]&&zg(Lg[wg],tv);if((!cv||!iv||iv===rv)&&(iv=tv.prototype,cv))for(wg in dv)Lg[wg]&&zg(Lg[wg].prototype,iv);if(cv&&Jg(ev)!==iv&&zg(ev,iv),Mg&&!Ug(iv,ov))for(wg in lv=!0,Wg(iv,ov,{configurable:!0,get:function(){return Vg(this)?this[sv]:void 0}}),dv)Lg[wg]&&Hg(Lg[wg],sv,wg);var mv={NATIVE_ARRAY_BUFFER_VIEWS:cv,TYPED_ARRAY_TAG:lv&&sv,aTypedArray:function(e){if(pv(e))return e;throw new nv("Target is not a typed array")},aTypedArrayConstructor:function(e){if(xg(e)&&(!zg||Gg(tv,e)))return e;throw new nv(Bg(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(Mg){if(i)for(var n in dv){var o=Lg[n];if(o&&Ug(o.prototype,e))try{delete o.prototype[e]}catch(pH){try{o.prototype[e]=t}catch(s){}}}iv[e]&&!i||jg(iv,e,i?t:cv&&$g[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(Mg){if(zg){if(i)for(r in dv)if((n=Lg[r])&&Ug(n,e))try{delete n[e]}catch(pH){}if(tv[e]&&!i)return;try{return jg(tv,e,i?t:cv&&tv[e]||t)}catch(pH){}}for(r in dv)!(n=Lg[r])||n[e]&&!i||jg(n,e,t)}},getTypedArrayConstructor:hv,isView:function(e){if(!Vg(e))return!1;var t=Fg(e);return"DataView"===t||Ug(dv,t)||Ug(uv,t)},isTypedArray:pv,TypedArray:tv,TypedArrayPrototype:iv},_v=n,fv=s,gv=Lp,vv=mv.NATIVE_ARRAY_BUFFER_VIEWS,yv=_v.ArrayBuffer,Tv=_v.Int8Array,Sv=!vv||!fv((function(){Tv(1)}))||!fv((function(){new Tv(-1)}))||!gv((function(e){new Tv,new Tv(null),new Tv(1.5),new Tv(e)}),!0)||fv((function(){return 1!==new Tv(new yv(2),1,void 0).length})),Ev=W,Iv=Math.floor,Rv=Number.isInteger||function(e){return!Ev(e)&&isFinite(e)&&Iv(e)===e},Cv=or,Av=RangeError,bv=function(e){var t=Cv(e);if(t<0)throw new Av("The argument can't be less than 0");return t},kv=RangeError,wv=function(e,t){var i=bv(e);if(i%t)throw new kv("Wrong offset");return i},Dv=Math.round,Nv=hn,Ov=ut,Pv=TypeError,Mv=function(e){var t=Ov(e,"number");if("number"==typeof t)throw new Pv("Can't convert number to bigint");return BigInt(t)},Lv=kd,xv=u,Vv=md,Uv=Be,Fv=mr,Bv=hp,Hv=op,jv=Zh,Wv=function(e){var t=Nv(e);return"BigInt64Array"===t||"BigUint64Array"===t},Gv=mv.aTypedArrayConstructor,Jv=Mv,zv=function(e){var t,i,r,n,o,s,a,c,l=Vv(this),d=Uv(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=Hv(d);if(m&&!jv(m))for(c=(a=Bv(d,m)).next,d=[];!(s=xv(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=Lv(h,arguments[2])),i=Fv(d),r=new(Gv(l))(i),n=Wv(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?Jv(o):+o;return r},qv=aa,Kv=dd,Yv=W,Qv=rt("species"),Xv=Array,$v=function(e){var t;return qv(e)&&(t=e.constructor,(Kv(t)&&(t===Xv||qv(t.prototype))||Yv(t)&&null===(t=t[Qv]))&&(t=void 0)),void 0===t?Xv:t},Zv=kd,ey=O,ty=Be,iy=mr,ry=function(e,t){return new($v(e))(0===t?0:t)},ny=I([].push),oy=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=ty(c),_=ey(m),f=iy(_),g=Zv(l,d),v=0,y=u||ry,T=t?y(c,f):i||s?y(c,0):void 0;f>v;v++)if((a||v in _)&&(p=g(h=_[v],v,m),e))if(t)T[v]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return v;case 2:ny(T,h)}else switch(e){case 4:return!1;case 7:ny(T,h)}return o?-1:r||n?n:T}},sy={forEach:oy(0),map:oy(1),filter:oy(2),some:oy(3),every:oy(4),find:oy(5),findIndex:oy(6),filterReject:oy(7)},ay=mr,cy=nn,ly=n,dy=u,uy=a,hy=Sv,py=mv,my=Rl,_y=Qa,fy=v,gy=Yt,vy=Rv,yy=hr,Ty=ec,Sy=wv,Ey=function(e){var t=Dv(e);return t<0?0:t>255?255:255&t},Iy=mt,Ry=We,Cy=hn,Ay=W,by=pe,ky=lo,wy=q,Dy=cs,Ny=er.f,Oy=zv,Py=sy.forEach,My=wl,Ly=vn,xy=Dt,Vy=o,Uy=function(e,t,i){for(var r=0,n=arguments.length>2?i:ay(t),o=new e(n);n>r;)o[r]=t[r++];return o},Fy=Ec,By=Di.get,Hy=Di.set,jy=Di.enforce,Wy=xy.f,Gy=Vy.f,Jy=ly.RangeError,zy=my.ArrayBuffer,qy=zy.prototype,Ky=my.DataView,Yy=py.NATIVE_ARRAY_BUFFER_VIEWS,Qy=py.TYPED_ARRAY_TAG,Xy=py.TypedArray,$y=py.TypedArrayPrototype,Zy=py.isTypedArray,eT="BYTES_PER_ELEMENT",tT="Wrong length",iT=function(e,t){Ly(e,t,{configurable:!0,get:function(){return By(this)[t]}})},rT=function(e){var t;return wy(qy,e)||"ArrayBuffer"===(t=Cy(e))||"SharedArrayBuffer"===t},nT=function(e,t){return Zy(e)&&!by(t)&&t in e&&vy(+t)&&t>=0},oT=function(e,t){return t=Iy(t),nT(e,t)?fy(2,e[t]):Gy(e,t)},sT=function(e,t,i){return t=Iy(t),!(nT(e,t)&&Ay(i)&&Ry(i,"value"))||Ry(i,"get")||Ry(i,"set")||i.configurable||Ry(i,"writable")&&!i.writable||Ry(i,"enumerable")&&!i.enumerable?Wy(e,t,i):(e[t]=i.value,e)};uy?(Yy||(Vy.f=oT,xy.f=sT,iT($y,"buffer"),iT($y,"byteOffset"),iT($y,"byteLength"),iT($y,"length")),cy({target:"Object",stat:!0,forced:!Yy},{getOwnPropertyDescriptor:oT,defineProperty:sT}),Og.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=ly[n],c=a,l=c&&c.prototype,d={},u=function(e,t){Wy(e,t,{get:function(){return function(e,t){var i=By(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=By(e);o.view[s](t*r+o.byteOffset,i?Ey(n):n,!0)}(this,t,e)},enumerable:!0})};Yy?hy&&(c=t((function(e,t,i,n){return _y(e,l),Fy(Ay(t)?rT(t)?void 0!==n?new a(t,Sy(i,r),n):void 0!==i?new a(t,Sy(i,r)):new a(t):Zy(t)?Uy(c,t):dy(Oy,c,t):new a(Ty(t)),e,c)})),Dy&&Dy(c,Xy),Py(Ny(a),(function(e){e in c||gy(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,n){_y(e,l);var o,s,a,d=0,h=0;if(Ay(t)){if(!rT(t))return Zy(t)?Uy(c,t):dy(Oy,c,t);o=t,h=Sy(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw new Jy(tT);if((s=p-h)<0)throw new Jy(tT)}else if((s=yy(n)*r)+h>p)throw new Jy(tT);a=s/r}else a=Ty(t),o=new zy(s=a*r);for(Hy(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new Ky(o)});d<a;)u(e,d++)})),Dy&&Dy(c,Xy),l=c.prototype=ky($y)),l.constructor!==c&&gy(l,"constructor",c),jy(l).TypedArrayConstructor=c,Qy&&gy(l,Qy,n);var h=c!==a;d[n]=c,cy({global:!0,constructor:!0,forced:h,sham:!Yy},d),eT in c||gy(c,eT,r),eT in l||gy(l,eT,r),My(n)}):Og.exports=function(){};var aT=Og.exports;aT("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}})),aT("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var cT=vc,lT=Mv,dT=hn,uT=u,hT=s,pT=mv.aTypedArray,mT=mv.exportTypedArrayMethod,_T=I("".slice);mT("fill",(function(e){var t=arguments.length;pT(this);var i="Big"===_T(dT(this),0,3)?lT(e):+e;return uT(cT,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),hT((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e}))),(0,mv.exportTypedArrayStaticMethod)("from",zv,Sv);var fT=n,gT=u,vT=mv,yT=mr,TT=wv,ST=Be,ET=s,IT=fT.RangeError,RT=fT.Int8Array,CT=RT&&RT.prototype,AT=CT&&CT.set,bT=vT.aTypedArray,kT=vT.exportTypedArrayMethod,wT=!ET((function(){var e=new Uint8ClampedArray(2);return gT(AT,e,{length:1,0:3},1),3!==e[1]})),DT=wT&&vT.NATIVE_ARRAY_BUFFER_VIEWS&&ET((function(){var e=new RT(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));kT("set",(function(e){bT(this);var t=TT(arguments.length>1?arguments[1]:void 0,1),i=ST(e);if(wT)return gT(AT,this,i,t);var r=this.length,n=yT(i),o=0;if(n+t>r)throw new IT("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!wT||DT);var NT=Ll,OT=s,PT=ye,MT=va,LT=Ta,xT=Sa,VT=re,UT=Ia,FT=mv.aTypedArray,BT=mv.exportTypedArrayMethod,HT=n.Uint16Array,jT=HT&&NT(HT.prototype.sort),WT=!(!jT||OT((function(){jT(new HT(2),null)}))&&OT((function(){jT(new HT(2),{})}))),GT=!!jT&&!OT((function(){if(VT)return VT<74;if(LT)return LT<67;if(xT)return!0;if(UT)return UT<602;var e,t,i=new HT(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(jT(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));BT("sort",(function(e){return void 0!==e&&PT(e),GT?jT(this,e):MT(FT(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))}),!GT||WT);var JT={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},zT=vt("span").classList,qT=zT&&zT.constructor&&zT.constructor.prototype,KT=qT===Object.prototype?void 0:qT,YT=sy.forEach,QT=$s("forEach")?[].forEach:function(e){return YT(this,e,arguments.length>1?arguments[1]:void 0)},XT=n,$T=JT,ZT=KT,eS=QT,tS=Yt,iS=function(e){if(e&&e.forEach!==eS)try{tS(e,"forEach",eS)}catch(pH){e.forEach=eS}};for(var rS in $T)$T[rS]&&iS(XT[rS]&&XT[rS].prototype);iS(ZT);var nS=n,oS=JT,sS=KT,aS=Hs,cS=Yt,lS=Go,dS=rt("iterator"),uS=aS.values,hS=function(e,t){if(e){if(e[dS]!==uS)try{cS(e,dS,uS)}catch(pH){e[dS]=uS}if(lS(e,t,!0),oS[t])for(var i in aS)if(e[i]!==aS[i])try{cS(e,i,aS[i])}catch(pH){e[i]=aS[i]}}};for(var pS in oS)hS(nS[pS]&&nS[pS].prototype,pS);hS(sS,"DOMTokenList");var mS=kf.charAt,_S=_n,fS=Di,gS=ks,vS=ws,yS="String Iterator",TS=fS.set,SS=fS.getterFor(yS);gS(String,"String",(function(e){TS(this,{type:yS,string:_S(e),index:0})}),(function(){var e,t=SS(this),i=t.string,r=t.index;return r>=i.length?vS(void 0,!0):(e=mS(i,r),t.index+=e.length,vS(e,!1))}));var ES=s,IS=a,RS=rt("iterator"),CS=!ES((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&&!IS||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[RS]||"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})),AS=a,bS=I,kS=u,wS=s,DS=Hn,NS=wr,OS=h,PS=Be,MS=O,LS=Object.assign,xS=Object.defineProperty,VS=bS([].concat),US=!LS||wS((function(){if(AS&&1!==LS({b:1},LS(xS({},"a",{enumerable:!0,get:function(){xS(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!==LS({},e)[i]||DS(LS({},t)).join("")!==r}))?function(e,t){for(var i=PS(e),r=arguments.length,n=1,o=NS.f,s=OS.f;r>n;)for(var a,c=MS(arguments[n++]),l=o?VS(DS(c),o(c)):DS(c),d=l.length,u=0;d>u;)a=l[u++],AS&&!kS(s,c,a)||(i[a]=c[a]);return i}:LS,FS=Lt,BS=fp,HS=a,jS=Dt,WS=v,GS=kd,JS=u,zS=Be,qS=function(e,t,i,r){try{return r?t(FS(i)[0],i[1]):t(i)}catch(pH){BS(e,"throw",pH)}},KS=Zh,YS=dd,QS=mr,XS=function(e,t,i){HS?jS.f(e,t,WS(0,i)):e[t]=i},$S=hp,ZS=op,eE=Array,tE=I,iE=2147483647,rE=/[^\0-\u007E]/,nE=/[.\u3002\uFF0E\uFF61]/g,oE="Overflow: input needs wider integers to process",sE=RangeError,aE=tE(nE.exec),cE=Math.floor,lE=String.fromCharCode,dE=tE("".charCodeAt),uE=tE([].join),hE=tE([].push),pE=tE("".replace),mE=tE("".split),_E=tE("".toLowerCase),fE=function(e){return e+22+75*(e<26)},gE=function(e,t,i){var r=0;for(e=i?cE(e/700):e>>1,e+=cE(e/t);e>455;)e=cE(e/35),r+=36;return cE(r+36*e/(e+38))},vE=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=dE(e,i++);if(n>=55296&&n<=56319&&i<r){var o=dE(e,i++);56320==(64512&o)?hE(t,((1023&n)<<10)+(1023&o)+65536):(hE(t,n),i--)}else hE(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&&hE(t,lE(r));var c=t.length,l=c;for(c&&hE(t,"-");l<n;){var d=iE;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>cE((iE-s)/u))throw new sE(oE);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++s>iE)throw new sE(oE);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;hE(t,lE(fE(m+_%f))),h=cE(_/f),p+=36}hE(t,lE(fE(h))),a=gE(s,u,l===c),s=0,l++}}s++,o++}return uE(t,"")},yE=nn,TE=I,SE=lr,EE=RangeError,IE=String.fromCharCode,RE=String.fromCodePoint,CE=TE([].join);yE({target:"String",stat:!0,arity:1,forced:!!RE&&1!==RE.length},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,n=0;r>n;){if(t=+arguments[n++],SE(t,1114111)!==t)throw new EE(t+" is not a valid code point");i[n]=t<65536?IE(t):IE(55296+((t-=65536)>>10),t%1024+56320)}return CE(i,"")}});var AE=nn,bE=n,kE=cu,wE=z,DE=u,NE=I,OE=a,PE=CS,ME=Zi,LE=vn,xE=qa,VE=Go,UE=Xo,FE=Di,BE=Qa,HE=H,jE=We,WE=kd,GE=hn,JE=Lt,zE=W,qE=_n,KE=lo,YE=v,QE=hp,XE=op,$E=ws,ZE=Dd,eI=va,tI=rt("iterator"),iI="URLSearchParams",rI=iI+"Iterator",nI=FE.set,oI=FE.getterFor(iI),sI=FE.getterFor(rI),aI=kE("fetch"),cI=kE("Request"),lI=kE("Headers"),dI=cI&&cI.prototype,uI=lI&&lI.prototype,hI=bE.TypeError,pI=bE.encodeURIComponent,mI=String.fromCharCode,_I=wE("String","fromCodePoint"),fI=parseInt,gI=NE("".charAt),vI=NE([].join),yI=NE([].push),TI=NE("".replace),SI=NE([].shift),EI=NE([].splice),II=NE("".split),RI=NE("".slice),CI=NE(/./.exec),AI=/\+/g,bI=/^[0-9a-f]+$/i,kI=function(e,t){var i=RI(e,t,t+2);return CI(bI,i)?fI(i,16):NaN},wI=function(e){for(var t=0,i=128;i>0&&e&i;i>>=1)t++;return t},DI=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},NI=function(e){for(var t=(e=TI(e,AI," ")).length,i="",r=0;r<t;){var n=gI(e,r);if("%"===n){if("%"===gI(e,r+1)||r+3>t){i+="%",r++;continue}var o=kI(e,r+1);if(o!=o){i+=n,r++;continue}r+=2;var s=wI(o);if(0===s)n=mI(o);else{if(1===s||s>4){i+="�",r++;continue}for(var a=[o],c=1;c<s&&!(++r+3>t||"%"!==gI(e,r));){var l=kI(e,r+1);if(l!=l){r+=3;break}if(l>191||l<128)break;yI(a,l),r+=2,c++}if(a.length!==s){i+="�";continue}var d=DI(a);null===d?i+="�":n=_I(d)}}i+=n,r++}return i},OI=/[!'()~]|%20/g,PI={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},MI=function(e){return PI[e]},LI=function(e){return TI(pI(e),OI,MI)},xI=UE((function(e,t){nI(this,{type:rI,target:oI(e).entries,index:0,kind:t})}),iI,(function(){var e=sI(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,$E(void 0,!0);var r=t[i];switch(e.kind){case"keys":return $E(r.key,!1);case"values":return $E(r.value,!1)}return $E([r.key,r.value],!1)}),!0),VI=function(e){this.entries=[],this.url=null,void 0!==e&&(zE(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===gI(e,0)?RI(e,1):e:qE(e)))};VI.prototype={type:iI,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,s,a,c=this.entries,l=XE(e);if(l)for(i=(t=QE(e,l)).next;!(r=DE(i,t)).done;){if(o=(n=QE(JE(r.value))).next,(s=DE(o,n)).done||(a=DE(o,n)).done||!DE(o,n).done)throw new hI("Expected sequence with length 2");yI(c,{key:qE(s.value),value:qE(a.value)})}else for(var d in e)jE(e,d)&&yI(c,{key:d,value:qE(e[d])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,n=II(e,"&"),o=0;o<n.length;)(t=n[o++]).length&&(i=II(t,"="),yI(r,{key:NI(SI(i)),value:NI(vI(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],yI(i,LI(e.key)+"="+LI(e.value));return vI(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var UI=function(){BE(this,FI);var e=nI(this,new VI(arguments.length>0?arguments[0]:void 0));OE||(this.size=e.entries.length)},FI=UI.prototype;if(xE(FI,{append:function(e,t){var i=oI(this);ZE(arguments.length,2),yI(i.entries,{key:qE(e),value:qE(t)}),OE||this.length++,i.updateURL()},delete:function(e){for(var t=oI(this),i=ZE(arguments.length,1),r=t.entries,n=qE(e),o=i<2?void 0:arguments[1],s=void 0===o?o:qE(o),a=0;a<r.length;){var c=r[a];if(c.key!==n||void 0!==s&&c.value!==s)a++;else if(EI(r,a,1),void 0!==s)break}OE||(this.size=r.length),t.updateURL()},get:function(e){var t=oI(this).entries;ZE(arguments.length,1);for(var i=qE(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=oI(this).entries;ZE(arguments.length,1);for(var i=qE(e),r=[],n=0;n<t.length;n++)t[n].key===i&&yI(r,t[n].value);return r},has:function(e){for(var t=oI(this).entries,i=ZE(arguments.length,1),r=qE(e),n=i<2?void 0:arguments[1],o=void 0===n?n:qE(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=oI(this);ZE(arguments.length,1);for(var r,n=i.entries,o=!1,s=qE(e),a=qE(t),c=0;c<n.length;c++)(r=n[c]).key===s&&(o?EI(n,c--,1):(o=!0,r.value=a));o||yI(n,{key:s,value:a}),OE||(this.size=n.length),i.updateURL()},sort:function(){var e=oI(this);eI(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=oI(this).entries,r=WE(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 xI(this,"keys")},values:function(){return new xI(this,"values")},entries:function(){return new xI(this,"entries")}},{enumerable:!0}),ME(FI,tI,FI.entries,{name:"entries"}),ME(FI,"toString",(function(){return oI(this).serialize()}),{enumerable:!0}),OE&&LE(FI,"size",{get:function(){return oI(this).entries.length},configurable:!0,enumerable:!0}),VE(UI,iI),AE({global:!0,constructor:!0,forced:!PE},{URLSearchParams:UI}),!PE&&HE(lI)){var BI=NE(uI.has),HI=NE(uI.set),jI=function(e){if(zE(e)){var t,i=e.body;if(GE(i)===iI)return t=e.headers?new lI(e.headers):new lI,BI(t,"content-type")||HI(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),KE(e,{body:YE(0,qE(i)),headers:YE(0,t)})}return e};if(HE(aI)&&AE({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return aI(e,arguments.length>1?jI(arguments[1]):{})}}),HE(cI)){var WI=function(e){return BE(this,dI),new cI(e,arguments.length>1?jI(arguments[1]):{})};dI.constructor=WI,WI.prototype=dI,AE({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:WI})}}var GI,JI=nn,zI=a,qI=CS,KI=n,YI=kd,QI=I,XI=Zi,$I=vn,ZI=Qa,eR=We,tR=US,iR=function(e){var t=zS(e),i=YS(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=GS(n,r>2?arguments[2]:void 0));var s,a,c,l,d,u,h=ZS(t),p=0;if(!h||this===eE&&KS(h))for(s=QS(t),a=i?new this(s):eE(s);s>p;p++)u=o?n(t[p],p):t[p],XS(a,p,u);else for(a=i?new this:[],d=(l=$S(t,h)).next;!(c=JS(d,l)).done;p++)u=o?qS(l,n,[c.value,p],!0):c.value,XS(a,p,u);return a.length=p,a},rR=ma,nR=kf.codeAt,oR=function(e){var t,i,r=[],n=mE(pE(_E(e),nE,"."),".");for(t=0;t<n.length;t++)i=n[t],hE(r,aE(rE,i)?"xn--"+vE(i):i);return uE(r,".")},sR=_n,aR=Go,cR=Dd,lR={URLSearchParams:UI,getState:oI},dR=Di,uR=dR.set,hR=dR.getterFor("URL"),pR=lR.URLSearchParams,mR=lR.getState,_R=KI.URL,fR=KI.TypeError,gR=KI.parseInt,vR=Math.floor,yR=Math.pow,TR=QI("".charAt),SR=QI(/./.exec),ER=QI([].join),IR=QI(1..toString),RR=QI([].pop),CR=QI([].push),AR=QI("".replace),bR=QI([].shift),kR=QI("".split),wR=QI("".slice),DR=QI("".toLowerCase),NR=QI([].unshift),OR="Invalid scheme",PR="Invalid host",MR="Invalid port",LR=/[a-z]/i,xR=/[\d+-.a-z]/i,VR=/\d/,UR=/^0x/i,FR=/^[0-7]+$/,BR=/^\d+$/,HR=/^[\da-f]+$/i,jR=/[\0\t\n\r #%/:<>?@[\\\]^|]/,WR=/[\0\t\n\r #/:<>?@[\\\]^|]/,GR=/^[\u0000-\u0020]+/,JR=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,zR=/[\t\n\r]/g,qR=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)NR(t,e%256),e=vR(e/256);return ER(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+=IR(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},KR={},YR=tR({},KR,{" ":1,'"':1,"<":1,">":1,"`":1}),QR=tR({},YR,{"#":1,"?":1,"{":1,"}":1}),XR=tR({},QR,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),$R=function(e,t){var i=nR(e,0);return i>32&&i<127&&!eR(t,e)?e:encodeURIComponent(e)},ZR={ftp:21,file:null,http:80,https:443,ws:80,wss:443},eC=function(e,t){var i;return 2===e.length&&SR(LR,TR(e,0))&&(":"===(i=TR(e,1))||!t&&"|"===i)},tC=function(e){var t;return e.length>1&&eC(wR(e,0,2))&&(2===e.length||"/"===(t=TR(e,2))||"\\"===t||"?"===t||"#"===t)},iC=function(e){return"."===e||"%2e"===DR(e)},rC={},nC={},oC={},sC={},aC={},cC={},lC={},dC={},uC={},hC={},pC={},mC={},_C={},fC={},gC={},vC={},yC={},TC={},SC={},EC={},IC={},RC=function(e,t,i){var r,n,o,s=sR(e);if(t){if(n=this.parse(s))throw new fR(n);this.searchParams=null}else{if(void 0!==i&&(r=new RC(i,!0)),n=this.parse(s,null,r))throw new fR(n);(o=mR(new pR)).bindURL(this),this.searchParams=o}};RC.prototype={type:"URL",parse:function(e,t,i){var r,n,o,s,a,c=this,l=t||rC,d=0,u="",h=!1,p=!1,m=!1;for(e=sR(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=AR(e,GR,""),e=AR(e,JR,"$1")),e=AR(e,zR,""),r=iR(e);d<=r.length;){switch(n=r[d],l){case rC:if(!n||!SR(LR,n)){if(t)return OR;l=oC;continue}u+=DR(n),l=nC;break;case nC:if(n&&(SR(xR,n)||"+"===n||"-"===n||"."===n))u+=DR(n);else{if(":"!==n){if(t)return OR;u="",l=oC,d=0;continue}if(t&&(c.isSpecial()!==eR(ZR,u)||"file"===u&&(c.includesCredentials()||null!==c.port)||"file"===c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&ZR[c.scheme]===c.port&&(c.port=null));u="","file"===c.scheme?l=fC:c.isSpecial()&&i&&i.scheme===c.scheme?l=sC:c.isSpecial()?l=dC:"/"===r[d+1]?(l=aC,d++):(c.cannotBeABaseURL=!0,CR(c.path,""),l=SC)}break;case oC:if(!i||i.cannotBeABaseURL&&"#"!==n)return OR;if(i.cannotBeABaseURL&&"#"===n){c.scheme=i.scheme,c.path=rR(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=IC;break}l="file"===i.scheme?fC:cC;continue;case sC:if("/"!==n||"/"!==r[d+1]){l=cC;continue}l=uC,d++;break;case aC:if("/"===n){l=hC;break}l=TC;continue;case cC:if(c.scheme=i.scheme,n===GI)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=rR(i.path),c.query=i.query;else if("/"===n||"\\"===n&&c.isSpecial())l=lC;else if("?"===n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=rR(i.path),c.query="",l=EC;else{if("#"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=rR(i.path),c.path.length--,l=TC;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=rR(i.path),c.query=i.query,c.fragment="",l=IC}break;case lC:if(!c.isSpecial()||"/"!==n&&"\\"!==n){if("/"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=TC;continue}l=hC}else l=uC;break;case dC:if(l=uC,"/"!==n||"/"!==TR(u,d+1))continue;d++;break;case uC:if("/"!==n&&"\\"!==n){l=hC;continue}break;case hC:if("@"===n){h&&(u="%40"+u),h=!0,o=iR(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!==f||m){var g=$R(f,XR);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n===GI||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(h&&""===u)return"Invalid authority";d-=iR(u).length+1,u="",l=pC}else u+=n;break;case pC:case mC:if(t&&"file"===c.scheme){l=vC;continue}if(":"!==n||p){if(n===GI||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(c.isSpecial()&&""===u)return PR;if(t&&""===u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=yC,t)return;continue}"["===n?p=!0:"]"===n&&(p=!1),u+=n}else{if(""===u)return PR;if(s=c.parseHost(u))return s;if(u="",l=_C,t===mC)return}break;case _C:if(!SR(VR,n)){if(n===GI||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()||t){if(""!==u){var v=gR(u,10);if(v>65535)return MR;c.port=c.isSpecial()&&v===ZR[c.scheme]?null:v,u=""}if(t)return;l=yC;continue}return MR}u+=n;break;case fC:if(c.scheme="file","/"===n||"\\"===n)l=gC;else{if(!i||"file"!==i.scheme){l=TC;continue}switch(n){case GI:c.host=i.host,c.path=rR(i.path),c.query=i.query;break;case"?":c.host=i.host,c.path=rR(i.path),c.query="",l=EC;break;case"#":c.host=i.host,c.path=rR(i.path),c.query=i.query,c.fragment="",l=IC;break;default:tC(ER(rR(r,d),""))||(c.host=i.host,c.path=rR(i.path),c.shortenPath()),l=TC;continue}}break;case gC:if("/"===n||"\\"===n){l=vC;break}i&&"file"===i.scheme&&!tC(ER(rR(r,d),""))&&(eC(i.path[0],!0)?CR(c.path,i.path[0]):c.host=i.host),l=TC;continue;case vC:if(n===GI||"/"===n||"\\"===n||"?"===n||"#"===n){if(!t&&eC(u))l=TC;else if(""===u){if(c.host="",t)return;l=yC}else{if(s=c.parseHost(u))return s;if("localhost"===c.host&&(c.host=""),t)return;u="",l=yC}continue}u+=n;break;case yC:if(c.isSpecial()){if(l=TC,"/"!==n&&"\\"!==n)continue}else if(t||"?"!==n)if(t||"#"!==n){if(n!==GI&&(l=TC,"/"!==n))continue}else c.fragment="",l=IC;else c.query="",l=EC;break;case TC:if(n===GI||"/"===n||"\\"===n&&c.isSpecial()||!t&&("?"===n||"#"===n)){if(".."===(a=DR(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"===n||"\\"===n&&c.isSpecial()||CR(c.path,"")):iC(u)?"/"===n||"\\"===n&&c.isSpecial()||CR(c.path,""):("file"===c.scheme&&!c.path.length&&eC(u)&&(c.host&&(c.host=""),u=TR(u,0)+":"),CR(c.path,u)),u="","file"===c.scheme&&(n===GI||"?"===n||"#"===n))for(;c.path.length>1&&""===c.path[0];)bR(c.path);"?"===n?(c.query="",l=EC):"#"===n&&(c.fragment="",l=IC)}else u+=$R(n,QR);break;case SC:"?"===n?(c.query="",l=EC):"#"===n?(c.fragment="",l=IC):n!==GI&&(c.path[0]+=$R(n,KR));break;case EC:t||"#"!==n?n!==GI&&("'"===n&&c.isSpecial()?c.query+="%27":c.query+="#"===n?"%23":$R(n,KR)):(c.fragment="",l=IC);break;case IC:n!==GI&&(c.fragment+=$R(n,YR))}d++}},parseHost:function(e){var t,i,r;if("["===TR(e,0)){if("]"!==TR(e,e.length-1))return PR;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 TR(e,u)};if(":"===h()){if(":"!==TR(e,1))return;u+=2,d=++l}for(;h();){if(8===l)return;if(":"!==h()){for(t=i=0;i<4&&SR(HR,h());)t=16*t+gR(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(!SR(VR,h()))return;for(;SR(VR,h());){if(o=gR(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}(wR(e,1,-1)),!t)return PR;this.host=t}else if(this.isSpecial()){if(e=oR(e),SR(jR,e))return PR;if(t=function(e){var t,i,r,n,o,s,a,c=kR(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"===TR(n,0)&&(o=SR(UR,n)?16:8,n=wR(n,8===o?1:2)),""===n)s=0;else{if(!SR(10===o?BR:8===o?FR:HR,n))return e;s=gR(n,o)}CR(i,s)}for(r=0;r<t;r++)if(s=i[r],r===t-1){if(s>=yR(256,5-t))return null}else if(s>255)return null;for(a=RR(i),r=0;r<i.length;r++)a+=i[r]*yR(256,3-r);return a}(e),null===t)return PR;this.host=t}else{if(SR(WR,e))return PR;for(t="",i=iR(e),r=0;r<i.length;r++)t+=$R(i[r],KR);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return eR(ZR,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&eC(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+=qR(n),null!==o&&(l+=":"+o)):"file"===t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+ER(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw new fR(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new CC(e.path[0]).origin}catch(pH){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+qR(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(sR(e)+":",rC)},getUsername:function(){return this.username},setUsername:function(e){var t=iR(sR(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=$R(t[i],XR)}},getPassword:function(){return this.password},setPassword:function(e){var t=iR(sR(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=$R(t[i],XR)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?qR(e):qR(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,pC)},getHostname:function(){var e=this.host;return null===e?"":qR(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,mC)},getPort:function(){var e=this.port;return null===e?"":sR(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=sR(e))?this.port=null:this.parse(e,_C))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+ER(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,yC))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=sR(e))?this.query=null:("?"===TR(e,0)&&(e=wR(e,1)),this.query="",this.parse(e,EC)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=sR(e))?("#"===TR(e,0)&&(e=wR(e,1)),this.fragment="",this.parse(e,IC)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var CC=function(e){var t=ZI(this,AC),i=cR(arguments.length,1)>1?arguments[1]:void 0,r=uR(t,new RC(e,!1,i));zI||(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())},AC=CC.prototype,bC=function(e,t){return{get:function(){return hR(this)[e]()},set:t&&function(e){return hR(this)[t](e)},configurable:!0,enumerable:!0}};if(zI&&($I(AC,"href",bC("serialize","setHref")),$I(AC,"origin",bC("getOrigin")),$I(AC,"protocol",bC("getProtocol","setProtocol")),$I(AC,"username",bC("getUsername","setUsername")),$I(AC,"password",bC("getPassword","setPassword")),$I(AC,"host",bC("getHost","setHost")),$I(AC,"hostname",bC("getHostname","setHostname")),$I(AC,"port",bC("getPort","setPort")),$I(AC,"pathname",bC("getPathname","setPathname")),$I(AC,"search",bC("getSearch","setSearch")),$I(AC,"searchParams",bC("getSearchParams")),$I(AC,"hash",bC("getHash","setHash"))),XI(AC,"toJSON",(function(){return hR(this).serialize()}),{enumerable:!0}),XI(AC,"toString",(function(){return hR(this).serialize()}),{enumerable:!0}),_R){var kC=_R.createObjectURL,wC=_R.revokeObjectURL;kC&&XI(CC,"createObjectURL",YI(kC,_R)),wC&&XI(CC,"revokeObjectURL",YI(wC,_R))}aR(CC,"URL"),JI({global:!0,constructor:!0,forced:!qI,sham:!zI},{URL:CC});var DC=u;nn({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return DC(URL.prototype.toString,this)}});let NC=!0,OC=!0;function PC(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function MC(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 LC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(NC=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function xC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(OC=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function VC(){if("object"==typeof window){if(NC)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function UC(e,t){OC&&console.warn(e+" is deprecated, please use "+t+" instead.")}function FC(e){return"[object Object]"===Object.prototype.toString.call(e)}function BC(e){return FC(e)?Object.keys(e).reduce((function(t,i){const r=FC(e[i]),n=r?BC(e[i]):e[i],o=r&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[i]:n})}),{}):e}function HC(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?HC(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{HC(e,e.get(t),i)}))})))}function jC(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&&HC(e,i,n)}))})),n}const WC=VC;function GC(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),WC("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return WC("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 JC(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function zC(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 MC(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function qC(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 KC(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 YC(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=>jC(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}),MC(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>jC(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 QC(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 XC(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return QC(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 $C(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 ZC(e,t){MC(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var eA=Object.freeze({__proto__:null,shimMediaStream:JC,shimOnTrack:zC,shimGetSendersWithDtmf:qC,shimGetStats:KC,shimSenderReceiverGetStats:YC,shimAddTrackRemoveTrackWithNative:QC,shimAddTrackRemoveTrack:XC,shimPeerConnection:$C,fixNegotiationNeeded:ZC,shimGetUserMedia:GC,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 tA(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){UC("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 iA(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 rA(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(bb){if("TypeError"!==bb.name)throw bb;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,o)}}function nA(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 oA(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}),MC(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function sA(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){UC("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function aA(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function cA(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 lA(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 dA(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 uA(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 hA=Object.freeze({__proto__:null,shimOnTrack:iA,shimPeerConnection:rA,shimSenderGetStats:nA,shimReceiverGetStats:oA,shimRemoveStream:sA,shimRTCDataChannel:aA,shimAddTransceiver:cA,shimGetParameters:lA,shimCreateOffer:dA,shimCreateAnswer:uA,shimGetUserMedia:tA,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 pA(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 mA(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 _A(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 fA(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(gA(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function gA(e){return e&&void 0!==e.video?Object.assign({},e,{video:BC(e.video)}):e}function vA(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?(UC("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 yA(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 TA(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 SA(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var EA=Object.freeze({__proto__:null,shimLocalStreamsAPI:pA,shimRemoteStreamsAPI:mA,shimCallbacksAPI:_A,shimGetUserMedia:fA,shimConstraints:gA,shimRTCIceServerUrls:vA,shimTrackEventTransceiver:yA,shimCreateOfferLegacy:TA,shimAudioContext:SA}),IA={exports:{}};!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}(IA);var RA=IA.exports,CA=i(RA),AA=e({__proto__:null,default:CA},[RA]);function bA(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=CA.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,MC(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function kA(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||MC(e,"icecandidate",(e=>{if(e.candidate){const t=CA.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function wA(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=CA.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=CA.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=CA.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 DA(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},MC(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function NA(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 OA(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 PA(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 MA(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 LA=Object.freeze({__proto__:null,shimRTCIceCandidate:bA,shimRTCIceCandidateRelayProtocol:kA,shimMaxMessageSize:wA,shimSendThrowTypeError:DA,shimConnectionState:NA,removeExtmapAllowMixed:OA,shimAddIceCandidateNullOrEmpty:PA,shimParameterlessSetLocalDescription:MA});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=VC,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=PC(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=PC(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=PC(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:LA,extractVersion:PC,disableLog:LC,disableWarnings:xC,sdp:AA};switch(r.browser){case"chrome":if(!eA||!$C||!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=eA,PA(e,r),MA(e),GC(e,r),JC(e),$C(e,r),zC(e),XC(e,r),qC(e),KC(e),YC(e),ZC(e,r),bA(e),kA(e),NA(e),wA(e,r),DA(e),OA(e,r);break;case"firefox":if(!hA||!rA||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=hA,PA(e,r),MA(e),tA(e,r),rA(e,r),iA(e),sA(e),nA(e),oA(e),aA(e),cA(e),lA(e),dA(e),uA(e),bA(e),NA(e),wA(e,r),DA(e);break;case"safari":if(!EA||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=EA,PA(e,r),MA(e),vA(e),TA(e),_A(e),pA(e),mA(e),yA(e),fA(e),SA(e),bA(e),kA(e),wA(e,r),DA(e),OA(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var xA,VA=Object.create,UA=Object.defineProperty,FA=Object.defineProperties,BA=Object.getOwnPropertyDescriptor,HA=Object.getOwnPropertyDescriptors,jA=Object.getOwnPropertyNames,WA=Object.getOwnPropertySymbols,GA=Object.getPrototypeOf,JA=Object.prototype.hasOwnProperty,zA=Object.prototype.propertyIsEnumerable,qA=Reflect.get,KA=Math.pow,YA=(e,t,i)=>t in e?UA(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,QA=(e,t)=>{for(var i in t||(t={}))JA.call(t,i)&&YA(e,i,t[i]);if(WA)for(var i of WA(t))zA.call(t,i)&&YA(e,i,t[i]);return e},XA=(e,t)=>FA(e,HA(t)),$A=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ZA=(e,t)=>{for(var i in t)UA(e,i,{get:t[i],enumerable:!0})},eb=(e,t,i)=>(i=null!=e?VA(GA(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of jA(t))!JA.call(e,n)&&n!==i&&UA(e,n,{get:()=>t[n],enumerable:!(r=BA(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:UA(i,"default",{value:e,enumerable:!0}),e)),tb=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?BA(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&&UA(t,i,o),o},ib=(e,t,i)=>(YA(e,"symbol"!=typeof t?t+"":t,i),i),rb=(e,t,i)=>qA(GA(e),i,t),nb=(e,t,i)=>new Promise(((r,n)=>{var o=e=>{try{a(i.next(e))}catch(oP){n(oP)}},s=e=>{try{a(i.throw(e))}catch(oP){n(oP)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),ob=$A(((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)})),sb=$A(((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")}))}))})),ab=$A((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=sb(),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}}))}))}})),cb=$A(((e,t)=>{var i=sb(),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"}})),lb=$A((e=>{var t=ab(),i=cb(),r=sb();e.grammar=r,e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),db=$A(((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),ub=$A((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var n=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:n&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=db(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),hb=$A(((e,t)=>{var i=db(),r=/%[sdv%]/g,n=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},o=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||s,n=t.innerOrder||a,c=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),pb=$A((e=>{var t=ub(),i=hb();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),mb=eb(ob()),_b=((xA=_b||{})[xA.INVALID_PARAMETER=4096]="INVALID_PARAMETER",xA[xA.INVALID_OPERATION=4097]="INVALID_OPERATION",xA[xA.NOT_SUPPORTED=4098]="NOT_SUPPORTED",xA[xA.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",xA[xA.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",xA[xA.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",xA[xA.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",xA[xA.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",xA[xA.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",xA[xA.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",xA[xA.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",xA[xA.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",xA[xA.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",xA[xA.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",xA[xA.CLIENT_BANNED=16448]="CLIENT_BANNED",xA[xA.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",xA[xA.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",xA[xA.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",xA[xA.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",xA[xA.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",xA[xA.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",xA[xA.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",xA[xA.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",xA[xA.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",xA[xA.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",xA[xA.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",xA[xA.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",xA[xA.API_CALL_ABORTED=16461]="API_CALL_ABORTED",xA[xA.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",xA[xA.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",xA[xA.UNKNOWN=65535]="UNKNOWN",xA),fb=_b,gb=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=fb.UNKNOWN,extraCode:n=0,constraint:o}=e,s="<".concat(function(e){for(let t in fb)if(fb[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),ib(this,"code"),ib(this,"extraCode"),ib(this,"message"),ib(this,"originMessage"),ib(this,"name"),ib(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}},vb=gb,yb=((new Date).getTime(),0),Tb=function(){return(new Date).getTime()+yb},Sb=function(){let e=new Date;return e.setTime(Tb()),e.toLocaleString()},Eb={};ZA(Eb,{bytes2ms:()=>sO,convertObjectNumberToInt:()=>YO,copyProperties:()=>oO,deepClone:()=>FO,deepMerge:()=>UO,delay:()=>QO,fibonacci:()=>pO,formatedTime:()=>jO,getAbilityConfigUrl:()=>qN,getConstructorName:()=>bO,getContainerFromElement:()=>HO,getEnv:()=>XN,getInternalVersion:()=>OO,getLoggerUrl:()=>ZN,getMuteStateFromFlag:()=>LO,getNetworkType:()=>tO,getNumNetworkType:()=>nO,getReconnectionTimeout:()=>mO,getStringByteLength:()=>JO,getTurnServer:()=>xO,getUint32Version:()=>KO,getValueType:()=>_O,getViewListFromView:()=>BO,glog:()=>dO,ipv4ToUint32:()=>VO,isArray:()=>EO,isAudioWorkletSupported:()=>kO,isBoolean:()=>TO,isConstructor:()=>AO,isEmpty:()=>MO,isFunction:()=>fO,isLangChinese:()=>uO,isMediaStreamTrack:()=>IO,isNumber:()=>yO,isObject:()=>SO,isOverseaSdkAppId:()=>$N,isPlainObject:()=>hO,isPortrait:()=>zO,isPromise:()=>CO,isRemoteTrack:()=>RO,isString:()=>vO,isUndefined:()=>gO,loadImage:()=>qO,ms2bytes:()=>cO,ms2samples:()=>lO,performanceNow:()=>DO,promiseAny:()=>wO,samples2ms:()=>aO,setNetworkType:()=>rO,stringify:()=>WO,stringifyIncludeValue:()=>GO,throttlePromise:()=>XO});var Ib={};ZA(Ib,{AUDIO_MUTE_BIT:()=>lk,AUDIO_STAT_BIT:()=>ck,AUX_STAT_BIT:()=>ak,AUX_STREAM_MSID:()=>mk,BACKEND_ENV:()=>rk,BASE_DOC_URL:()=>Fb,BASE_HOST:()=>Lb,CAPABILITIES_KEYS:()=>ow,CLASS_NAME:()=>zk,CLOUD_CONSOLE_URL:()=>Ub,CROSS_ROOM_BIT:()=>hk,DATA_FREEZE_TIMING:()=>Fk,DOC_URL:()=>Bb,DTLS_STATE_UNKNOWN:()=>Rk,ENV_NAME:()=>Jb,EXCHANGE_SDP_TIMEOUT:()=>Mk,INTERVAL:()=>rw,IS_WORKER:()=>Db,IS_WORKLET:()=>Nb,KIBANA_EVENT:()=>Nk,LOCAL_STREAM_PUBLISH_STATE:()=>Uk,LOGGER_CMD_TYPE:()=>Gb,LOGGER_DOMAIN:()=>Hb,LOGGER_DOMAIN_OVERSEA:()=>jb,LOG_LEVEL:()=>zb,LOG_LEVEL_NAME:()=>Xk,MAIN_STREAM_MSID:()=>pk,MAX_RTT:()=>sw,MICROPHONE_COMMUNICATIONS:()=>Qk,MICROPHONE_DEFAULT:()=>Kk,MUTE_ALL_BIT:()=>uk,NAME:()=>tk,NETWORK_TYPE:()=>Yb,NOT_SUPPORTED_H264:()=>Vk,PAUSED_RETRY_COUNT:()=>qk,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Wk,PEER_CONNECTION_STATE:()=>Ck,PEER_LEAVE_REASON:()=>$k,RAF:()=>iw,RECOVER_CAPTURE_INTERVAL:()=>ew,REMOTE_STREAM_TYPE_AUX:()=>fk,REMOTE_STREAM_TYPE_MAIN:()=>_k,RENDER_FREEZE_TIMING:()=>Bk,RIC:()=>tw,SCHEDULE_DOMAIN:()=>Gk,SCHEDULE_TIMEOUT:()=>Jk,SDP_SEMANTICS_PLAN_B:()=>xk,SDP_SEMANTICS_UNIFIED_PLAN:()=>Lk,SECOND_HOST:()=>xb,SIGNAL_PING_PONG_INTERVAL:()=>Kb,SIGNAL_PING_TIMEOUT:()=>qb,SIGNAL_RECONNECTION_COUNT:()=>Dk,SMALL_STAT_BIT:()=>sk,SPEAKER_DEFAULT:()=>Yk,STORAGE_EXPIRES_TIME:()=>Qb,STREAM_TYPE_BIG:()=>Hk,STREAM_TYPE_SMALL:()=>jk,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Zk,SYNC_USER_LIST_INTERVAL:()=>Ok,Scene:()=>nk,Switch:()=>Xb,THIRD_HOST:()=>Vb,TIMEOUT:()=>nw,TRANSPORT_DIRECTION:()=>ik,TRTC_ERROR_ASSISTANCE:()=>Wb,TRTC_QUALITY_BAD:()=>Sk,TRTC_QUALITY_DISCONNECTED:()=>Ik,TRTC_QUALITY_EXCELLENT:()=>vk,TRTC_QUALITY_GOOD:()=>yk,TRTC_QUALITY_POOR:()=>Tk,TRTC_QUALITY_UNKNOWN:()=>gk,TRTC_QUALITY_VERY_BAD:()=>Ek,UPDATE_OFFER_TIMEOUT:()=>Pk,VIDEO_MUTE_BIT:()=>dk,VIDEO_STAT_BIT:()=>ok,audioProfileMap:()=>$b,getRetryCount:()=>kk,getScriptDir:()=>Ob,innerVersion:()=>Rb,loggerProxy:()=>Pb,screenProfileMap:()=>ek,setLoggerProxy:()=>Mb,setRetryCount:()=>bk,setVersion:()=>Ab,version:()=>Cb,videoProfileMap:()=>Zb});var Rb="4.15.00.1600",Cb="5.0.0";function Ab(e){Cb=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));Rb="".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 bb,kb,wb,Db="undefined"!=typeof importScripts,Nb="undefined"!=typeof registerProcessor,Ob=()=>{let e=Db?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Pb="",Mb=e=>Pb=e,Lb="web.sdk.qcloud.com",xb="web.sdk.tencent.cn",Vb="web.sdk.cloud.tencent.cn",Ub="https://console.cloud.tencent.com/trtc",Fb="https://".concat(Lb,"/trtc/webrtc/v5/doc"),Bb="".concat(Fb,"/zh-cn/"),Hb="https://yun.tim.qq.com",jb="https://apisgp.my-imcloud.com",Wb="trtc_error_assistance",Gb={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Jb={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},zb=((wb=zb||{})[wb.TRACE=0]="TRACE",wb[wb.DEBUG=1]="DEBUG",wb[wb.INFO=2]="INFO",wb[wb.WARN=3]="WARN",wb[wb.ERROR=4]="ERROR",wb[wb.NONE=5]="NONE",wb),qb=18e3,Kb=2e3,Yb={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Qb=6048e5,Xb=((kb=Xb||{}).USEAINS="useAINS",kb.ENABLEDEBUG="enableDebug",kb.USEV2="useV2",kb.USEWT="useWt",kb),$b={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}},Zb={"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}},ek={"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}},tk={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"},ik={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},rk={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},nk=((bb=nk||{}).LIVE="live",bb.RTC="rtc",bb),ok=1,sk=2,ak=4,ck=8,lk=64,dk=16,uk=112,hk=128,pk="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",mk="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",_k=tk.MAIN,fk=tk.AUXILIARY,gk=0,vk=1,yk=2,Tk=3,Sk=4,Ek=5,Ik=6,Rk="unknown",Ck={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Ak=1/0;function bk(e){Ak=e}function kk(){return Ak}var wk,Dk=30,Nk={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"},Ok=1e4,Pk=1e4,Mk=1e4,Lk="unified-plan",xk="plan-b",Vk=1028,Uk=((wk=Uk||{})[wk.UNPUBLISH=-1]="UNPUBLISH",wk[wk.PUBLISHING=0]="PUBLISHING",wk[wk.PUBLISHED=1]="PUBLISHED",wk),Fk=500,Bk=1e3,Hk=tk.BIG,jk=tk.SMALL,Wk=1e4,Gk={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"},Jk=2e3,zk={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},qk=5,Kk="default",Yk=Kk,Qk="communications",Xk=Object.keys(zb),$k=["normal leave","timeout leave","kick","role change"],Zk=10,ew=2e3,tw="ric",iw="raf",rw="interval",nw="timeout",ow=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],sw=1e4;function aw(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 cw(e){return nb(this,null,(function*(){let t=DO(),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 tP.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(DO()-t,"ms")),r}catch(wk){return i}}))}var lw=1e8,dw="API_CALL_TIMEOUT",uw="SIGNAL_CHANNEL_SETUP_FAILED",hw="ERROR_MESSAGE",pw="DOWNLINK_RECONNECTION_FAILED",mw="EXCHANGE_SDP_FAILED",_w="UPLINK_RECONNECTION_FAILED",fw="INVALID_PURE_AUDIO",gw="INVALID_USER_DEFINE_RECORDID",vw="INVALID_USER_DEFINE_PUSH_ARGS",yw="INVALID_JOIN",Tw="JOIN_ROOM_TIMEOUT",Sw="JOIN_ROOM_FAILED",Ew="REJOIN_ROOM_FAILED",Iw="INVALID_DESTROY",Rw="SUBSCRIBE_FAILED",Cw="SWITCH_ROLE_TIMEOUT",Aw="SWITCH_ROLE_FAILED",bw="REPEAT_JOIN",kw="CLIENT_DESTROYED",ww="PLAY_FAILED",Dw="NOT_SUPPORTED_HTTP",Nw="NOT_SUPPORTED_H264ENCODE",Ow="NOT_SUPPORTED_H264DECODE",Pw="MICROPHONE_NOT_FOUND",Mw="CAMERA_NOT_FOUND",Lw="SIGNAL_RESPONSE_FAILED",xw="CATCH_HANDLER_ERROR",Vw="CONNECTION_CLOSED",Uw="CALL_FREQUENCY_LIMIT",Fw="CONNECTION_ABORTED",Bw="API_CALL_ABORTED",Hw={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(_O(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(_O(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,"()")},jw={};ZA(jw,{ANDROID_VERSION:()=>tD,CHROME_MAJOR_VERSION:()=>iN,CHROME_VERSION:()=>rN,EDGE_VERSION:()=>cD,EDG_MAJOR_VERSION:()=>uD,EDG_VERSION:()=>dD,FIREFOX_MAJOR_VERSION:()=>sD,FIREFOX_VERSION:()=>oD,HUAWEI_VERSION:()=>JD,IE_VERSION:()=>ED,IOS_MAIN_VERSION:()=>lN,IOS_VERSION:()=>cN,IPADQQB_VERSION:()=>PD,IS_ANDROID:()=>eD,IS_ANDROID_WEBVIEW:()=>aN,IS_ANY_SAFARI:()=>oN,IS_CHROME:()=>eN,IS_CHROME_OS:()=>VD,IS_CHROMIUM_BASE:()=>ZD,IS_EDG:()=>lD,IS_EDGE:()=>aD,IS_ELECTRON:()=>BD,IS_FIREFOX:()=>nD,IS_HEADLESS_CHROME:()=>tN,IS_HUAWEI:()=>GD,IS_HUAWEIBROWSER:()=>WD,IS_IE:()=>SD,IS_IE8:()=>TD,IS_IOS:()=>Zw,IS_IOS_13_OR_14:()=>hN,IS_IOS_15_1:()=>uN,IS_IPAD:()=>Yw,IS_IPADQQB:()=>OD,IS_IPAD_PRO:()=>Qw,IS_IPHONE:()=>Xw,IS_IPOD:()=>$w,IS_LINUX:()=>xD,IS_LOCAL:()=>pN,IS_MAC:()=>LD,IS_MACQQB:()=>DD,IS_MIBROWSER:()=>HD,IS_MQQB:()=>AD,IS_NATIVE_ANDROID:()=>rD,IS_OLD_ANDROID:()=>iD,IS_OPPOBROWSER:()=>KD,IS_SAFARI:()=>nN,IS_SAFARI_15_1:()=>dN,IS_SAMSUNGBROWSER:()=>zD,IS_SOGOU:()=>mD,IS_SOGOUM:()=>hD,IS_TBS:()=>fD,IS_UCBROWSER:()=>FD,IS_VIVOBROWSER:()=>QD,IS_WECHAT:()=>ID,IS_WIN:()=>MD,IS_WQQB:()=>kD,IS_WX:()=>UD,IS_X5MQQB:()=>CD,IS_XWEB:()=>vD,MACQQB_VERSION:()=>ND,MI_VERSION:()=>jD,MQQB_VERSION:()=>bD,OPPO_VERSION:()=>YD,SAFARI_VERSION:()=>sN,SAMSUNG_VERSION:()=>qD,SOGOUM_VERSION:()=>pD,SOGOU_VERSION:()=>_D,TBS_VERSION:()=>gD,UA_DATA_STRING:()=>vN,USER_AGENT:()=>Ww,VIVO_VERSION:()=>XD,WECHAT_VERSION:()=>RD,WQQB_VERSION:()=>wD,XWEB_VERSION:()=>yD,browserInfo:()=>_N,getBrowserInfo:()=>fN,getChromeMajorVersion:()=>$D,getDeviceModel:()=>SN,getDeviceModelFromUA:()=>EN,getGPUInfo:()=>TN,getOSName:()=>RN,getOSNumber:()=>CN,getOSString:()=>AN,getOSType:()=>kN,getTerminalType:()=>bN,getUserAgentData:()=>yN,isLocalStorageEnabled:()=>mN});var Ww="undefined"==typeof navigator?"":navigator.userAgent,Gw=e=>new RegExp(e,"i").test(Ww),Jw=e=>{if(Gw(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=Ww.match(t);if(i&&i[1])return i[1]}return""},zw=e=>{if(Gw(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=Ww.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},qw=/AppleWebKit\/([\d.]+)/i.exec(Ww),Kw=qw?parseFloat(qw[1]):NaN,Yw=Gw("iPad"),Qw="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Gw("Macintosh"),Xw=Gw("iPhone")&&!Yw,$w=Gw("iPod"),Zw=Xw||Yw||$w||Qw,eD=Gw("Android"),tD=function(){if(eD){let e=Ww.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}(),iD=eD&&Gw("webkit")&&tD<2.3,rD=eD&&tD<5&&Kw<537,nD=Gw("Firefox"),oD=Jw("Firefox"),sD=zw("Firefox"),aD=Gw("Edge"),cD=Jw("Edge"),lD=Gw("Edg"),dD=Jw("Edg"),uD=zw("Edg"),hD=Gw("SogouMobileBrowser"),pD=Jw("SogouMobileBrowser"),mD=Gw("MetaSr\\s"),_D=Jw("MetaSr\\s"),fD=Gw("TBS"),gD=Jw("TBS"),vD=Gw("XWEB"),yD=Jw("XWEB"),TD=Gw("MSIE\\s8\\.0"),SD=Gw("MSIE\\/\\d+"),ED=function(){if(SD){let e=/MSIE\s(\d+)\.\d/.exec(Ww),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(Ww)&&/rv:11.0/.test(Ww)&&(t=11),t}return NaN}(),ID=Gw("(micromessenger|webbrowser)"),RD=Jw("MicroMessenger"),CD=!fD&&Gw("MQQBrowser")&&Gw("COVC"),AD=!fD&&Gw("MQQBrowser")&&!Gw("COVC"),bD=AD||CD?Jw("MQQBrowser"):"",kD=!fD&&Gw(" QQBrowser"),wD=Jw(" QQBrowser"),DD=!fD&&Gw("QQBrowserLite"),ND=Jw("QQBrowserLite"),OD=!fD&&Gw("MQBHD"),PD=Jw("MQBHD"),MD=Gw("Windows"),LD=!Zw&&Gw("MAC OS X"),xD=!eD&&Gw("Linux"),VD=Gw("CrOS"),UD=Gw("MicroMessenger"),FD=Gw("UCBrowser"),BD=Gw("Electron"),HD=Gw("MiuiBrowser"),jD=Jw("MiuiBrowser"),WD=Gw("HuaweiBrowser"),GD=Gw("Huawei"),JD=Jw("HuaweiBrowser"),zD=Gw("SamsungBrowser"),qD=Jw("SamsungBrowser"),KD=Gw("HeyTapBrowser"),YD=Jw("HeyTapBrowser"),QD=Gw("VivoBrowser"),XD=Jw("VivoBrowser"),$D=()=>zw("Chrome"),ZD=Gw("Chrome"),eN=!aD&&!mD&&!hD&&!fD&&!vD&&!lD&&!kD&&!HD&&!WD&&!zD&&!KD&&!QD&&ZD,tN=Gw("HeadlessChrome"),iN=$D(),rN=Jw("Chrome"),nN=!ZD&&!AD&&!CD&&!DD&&!OD&&Gw("Safari"),oN=nN||Zw,sN=Jw("Version"),aN=/Android.*(wv|.0.0.0)/.test(Ww),cN=(()=>{if(Qw)return sN;if(Zw){let e=Ww.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),lN=Number(cN.split(".")[0]),dN="15.1"===sN,uN="15.1"===cN,hN=(()=>{let e=Number(cN.split(".")[0]);return 14===e||13===e})(),pN="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),mN=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(sP){e=!1}return e}})(),_N=fN();function fN(){let e=new Map([[nD,["Firefox",oD]],[lD,["Edg",dD]],[eN,["Chrome",rN]],[nN,["Safari",sN]],[fD,["TBS",gD]],[vD,["XWEB",yD]],[ID&&Xw,["WeChat",RD]],[kD,["QQ(Win)",wD]],[AD,["QQ(Mobile)",bD]],[CD,["QQ(Mobile X5)",bD]],[DD,["QQ(Mac)",ND]],[OD,["QQ(iPad)",PD]],[HD,["MI",jD]],[WD,["HW",JD]],[zD,["Samsung",qD]],[KD,["OPPO",YD]],[QD,["VIVO",XD]],[aD,["EDGE",cD]],[hD,["SogouMobile",pD]],[mD,["Sogou",_D]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var gN=null,vN="";function yN(){return nb(this,null,(function*(){if(gN)return gN;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(gN=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!vN&&(vN="UAData: ".concat(gN.platform,"/").concat(gN.platformVersion),gN.architecture&&gN.bitness&&(vN+=" ".concat(gN.architecture,"/").concat(gN.bitness)),gN.mobile&&(vN+=" mobile"),gN.model&&(vN+=" model: ".concat(gN.model)),gN.fullVersionList&&(vN+=" ".concat(gN.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),gN}catch($x){return null}}))}function TN(){try{let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"";let i=t.getExtension("WEBGL_debug_renderer_info");if(i){let e=t.getParameter(i.UNMASKED_VENDOR_WEBGL),r=t.getParameter(i.UNMASKED_RENDERER_WEBGL);return"".concat(e," ").concat(r)}return""}catch($x){return""}}function SN(){return(null==gN?void 0:gN.model)||EN()||""}function EN(){let e=Ww.match(/;\s*([^;)]+)\s+Build\//);return null!=e&&e[1]?e[1].trim():null}var IN=new Map([[eD,"Android"],[Zw,"iOS"],[MD,"Windows"],[LD,"MacOS"],[xD,"Linux"],[VD,"ChromeOS"]]),RN=function(){return IN.get(!0)?IN.get(!0):gN?gN.platform:"unknown"};function CN(){return MD?1:eD?2:LD?3:Zw?4:xD?5:VD?6:0}var AN=()=>{let e=RN();return e+="/".concat(_N.name,"/").concat(nN?_N.version:_N.version.split(".")[0]),null!=gN&&gN.platformVersion&&(e+="/".concat(gN.platformVersion)),null!=gN&&gN.architecture&&(e+="/".concat(gN.architecture)),e};function bN(){return eD?4:Xw?2:Yw?3:LD?12:MD?5:xD?13:1}function kN(){return eD?"Android":Xw?"iPhone":Yw?"iPad":LD?"Mac":MD?"Windows":xD?"Linux":"unknown"}var wN=(e,t)=>t?"".concat(Fb,"/").concat(e,"/").concat(t):"".concat(Fb,"/").concat(e,"/index.html");function DN(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",s="",a="";fO(Hw[t])?o=Hw[t](i):vO(Hw[t])&&(o=Hw[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=(()=>{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(Wb);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{}})();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(fO(l[t])?a=l[t](i):vO(l[t])&&(a=l[t]));let d=o;return uO()&&(c&&c[t]&&(fO(c[t])?s=c[t](i):vO(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 NN=Object.prototype.hasOwnProperty,ON=e=>"function"==typeof e,PN=e=>void 0===e;function MN(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(NN.call(e,t))return!1;return!0}return!1}var LN,xN=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)=>nb(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<(ON(d)?d():d)?(h++,m=1,ON(n)&&n.call(this,h,t),p=window.setTimeout((()=>{p=-1,_(e,i)}),ON(u)?u(h):u)):(t(),ON(o)&&o.call(this,f))};ON(r)?r.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(_)}},VN=new(eb(ob(),1).default),UN=((LN=UN||{}).ROOM_DESTROY="1",LN.JOIN_START="21",LN.JOIN_SCHEDULE_SUCCESS="22",LN.JOIN_SIGNAL_CONNECTION_START="23",LN.JOIN_SIGNAL_CONNECTION_END="24",LN.JOIN_SEND_CMD="25",LN.JOIN_RECEIVED_CMD_RES="26",LN.JOIN_SUCCESS="27",LN.JOIN_FAILED="28",LN.LEAVE_START="51",LN.LEAVE_SEND_CMD="52",LN.LEAVE_SUCCESS="53",LN.PUBLISH_START="61",LN.SEND_FIRST_VIDEO_FRAME="62",LN.PUBLISH_FAILED="63",LN.SUBSCRIBE_START="81",LN.SUBSCRIBE_SUCCESS="82",LN.SUBSCRIBE_FAILED="84",LN.UNSUBSCRIBE_SUCCESS="83",LN.LOCAL_TRACK_CAPTURE_START="101",LN.LOCAL_TRACK_CAPTURE_SUCCESS="102",LN.LOCAL_TRACK_CAPTURE_FAILED="103",LN.LOCAL_TRACK_PUBLISHED="104",LN.LOCAL_TRACK_UNPUBLISHED="105",LN.LOCAL_TRACK_REPLACED="106",LN.SWITCH_DEVICE_SUCCESS="107",LN.TRACK_MUTED="108",LN.TRACK_UNMUTED="109",LN.REMOTE_TRACK_SUBSCRIBED="110",LN.REMOTE_TRACK_UNSUBSCRIBED="111",LN.LOCAL_TRACK_RECAPTURE="112",LN.PLAY_TRACK_START="151",LN.PLAYER_STATE_CHANGED="152",LN.VIDEO_LOADED_DATA="153",LN.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",LN.SIGNAL_CONNECTION_STATE_CHANGED="201",LN.PEER_CONNECTION_STATE_CHANGED="202",LN.SINGLE_CONNECTION_STAT="203",LN.SPC_RECONNECTED="204",LN.HEARTBEAT_REPORT="251",LN.RECEIVED_PUBLISHED_USER_LIST="252",LN.REMOTE_PUBLISH_STATE_CHANGED="253",LN.AUDIO_LEVEL_INTERVAL="260",LN.NETWORK_QUALITY="261",LN.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",LN.QUALITY_LIMITATION_CHANGED="263",LN.LOG="264",LN),FN=new class{constructor(){this._roomIdMap=new Map,"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:Cb,env:Jb.QCLOUD,browserVersion:_N.name+_N.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){pN||!tP.isAbleToUpload||this._configs.env===Jb.QCLOUD&&this.uploadEventToKibana(XA(QA({},e),{result:"success"}))}logFailedEvent(e){if(pN||!tP.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)||fb.UNKNOWN};this._configs.env===Jb.QCLOUD&&this.uploadEventToKibana(XA(QA({},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:Sb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:Cb,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+="\n".concat(r.stack))),this.sendRequest(ZN(this._configs.sdkAppId,Gb.LOG),n)}sendRequest(e,t){tP.isAbleToUpload?aw({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},BN=null,HN=!0;function jN(e){TO(e)&&e!==HN&&(HN=e,tP.info("setIsNeedToSchedule ".concat(e)))}function WN(e){return nb(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(!HN&&BN)return{isCached:!0,result:BN};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=DO(),h=yield function(e,t,i){return new Promise(((r,n)=>{let o=null;wO([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]=zN(i,tk.MAIN,!0)),n())}))(zN(i,tk.MAIN),e,{get timeout(){return 1e3*pO(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]=zN(i,tk.BACKUP,!0)),n())}))(zN(i,tk.BACKUP),e,{get timeout(){return 1e3*pO(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}(d,e,i);h.config&&(h.config.loggerDomain&&Mb(h.config.loggerDomain),TO(h.config.scheduleCache)&&jN(!h.config.scheduleCache)),e.delta=DO()-u;let p=function(e,t,i){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let n=performance.getEntriesByType("resource"),o=zN(e,tk.MAIN),s=zN(e,tk.BACKUP);for(let e of n)if(e.startTime>=i&&(e.name===o||e.name===s)&&e.transferSize>0){let i=e.name===o?tk.MAIN:tk.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];FN.uploadEvent({log:"stat-schedule-net:".concat(n,"(").concat(s,"(").concat(a,"->").concat(c,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=XA(QA({},r),{totalCost:n,local:s,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(o){tP.error("getScheduleDetailCost error",o)}return r}(Number(i),t,u);return BN=h,{isCached:!1,result:h,detailCost:p}}catch(d){let e=EO(d)?d[0]:d,t=yO(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),r=new vb({code:fb.SCHEDULE_FAILED,extraCode:t,message:DN({key:Sw,data:{error:i,code:t}})});throw tP.error(i,t),r}}()}))}document&&document.head.insertAdjacentHTML("beforeend",Object.values(Gk).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),VN.on("28",(()=>jN(!0))),VN.on("63",(()=>jN(!0))),VN.on("84",(()=>jN(!0))),VN.on("201",(e=>{"RECONNECTING"===e.state&&jN(!0)})),VN.on("202",(e=>{"RECONNECTING"===e.state&&jN(!0)}));var GN={main:"",backup:""};function JN(e){EO(e)?(GN.main=e[0],GN.backup=e[1]):GN.main=e}function zN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tk.MAIN,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return"https://".concat(GN[t]||KN(e,t,i),"/api/v1/config")}function qN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tk.MAIN;return"https://".concat(GN[t]||KN(e,t),"/api/v1/trtcAutoConf")}function KN(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tk.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return $N(e)?i===tk.MAIN?Gk.MAIN_OVERSEA:Gk.BACKUP_OVERSEA:(t=$N(e)?r?i===tk.MAIN?Gk.MAIN_OVERSEA_OLD:Gk.BACKUP_OVERSEA_OLD:i===tk.MAIN?Gk.MAIN_OVERSEA:Gk.BACKUP_OVERSEA:i===tk.MAIN?Gk.MAIN:Gk.BACKUP,t)}function YN(e,t,i){return new Promise(((r,n)=>{aw({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)=>xN({retryFunction:YN,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var XN=function(){return new URLSearchParams(location.search).get("trtc_env")||""},$N=e=>Number(e)<14e8,ZN=function(e,t){let i;i=Pb||($N(e)?jb:Hb);let r=Math.floor(Math.random()*KA(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},eO="unknown";function tO(){if("unknown"!==eO)return eO;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&&(eO=iO(r,n)),eO}function iO(e,t){if(Yb[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function rO(e){eO=iO(e)}function nO(){return Yb[tO()]}function oO(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 sO(e){return aO(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function aO(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function cO(e){return 4*lO(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function lO(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var dO="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},uO=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},hO=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 pO(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:pO(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function mO(e){return e>8?3e4:1e3*pO(e)}function _O(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var fO=e=>"function"==typeof e,gO=e=>void 0===e,vO=e=>"string"==typeof e,yO=e=>"number"==typeof e,TO=e=>"boolean"==typeof e,SO=e=>"object"===_O(e),EO=e=>"array"===_O(e),IO=e=>_O(e)==="MediaStreamTrack".toLowerCase(),RO=e=>e.isRemote,CO=e=>"promise"===_O(e),AO=e=>fO(e)&&e.prototype.constructor===e,bO=e=>AO(e)?e.prototype.constructor.name:"",kO="undefined"!=typeof AudioWorkletNode;function wO(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 DO(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var NO=e=>+e<10?"0".concat(e):e,OO=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=NO(i[1])+NO(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},PO=Object.prototype.hasOwnProperty;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(hO(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(PO.call(e,t))return!1;return!0}return!1}function LO(e,t){return{userId:t,hasAudio:!!(e&ck),hasVideo:!!(e&ok),hasAuxiliary:!!(e&ak),hasSmall:!!(e&sk),audioMuted:!!(e&lk),videoMuted:!!(e&dk),audioAvailable:!(!(e&ck)||e&lk),videoAvailable:!(!(e&ok)||e&dk)}}function xO(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!gO(e.username)&&!gO(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",gO(e.credentialType)||(t.credentialType=e.credentialType)),t}function VO(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!vO(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 UO=function(e,t,i,r){if(!SO(e)||!SO(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],!(gO(t[n])||i&&i.includes(n)))if(SO(e[n])&&SO(t[n]))o+=UO(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=FO(t[n]),o+=1)}return o};function FO(e){if(EO(e)){let t=[];return e.forEach(((e,i)=>{t[i]=FO(e)})),t}if(SO(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=FO(e[i])})),t}return e}var BO=e=>{let t=[];if(EO(e))t=[...e];else if(vO(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},HO=e=>vO(e)?document.getElementById(e):e,jO=()=>(e=>{let t=e=>e<10?"0".concat(e):"".concat(e),i=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),o=t(e.getHours()),s=t(e.getMinutes()),a=t(e.getSeconds());return"".concat(i,"/").concat(r,"/").concat(n," ").concat(o,":").concat(s,":").concat(a)})(new Date);function WO(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(EO(e))return"[".concat(e.map((e=>WO(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!hO(e)||!EO(i)&&!EO(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]=hO(e[s])||EO(e[s])?JSON.parse(WO(e[s],{keysToExclude:r,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(wk){return"{}"}}function GO(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)})),WO(e,{keysToInclude:i})}function JO(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var zO=()=>{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},qO=e=>nb(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(vO(e))r=new Image,r.crossOrigin="anonymous",r.src=e;else if(r=e,r.complete)return void t(r);r.onload=()=>t(r),r.onerror=()=>{i(new vb({code:fb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}}))})),KO=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},YO=e=>(Object.keys(e).forEach((t=>{yO(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(hO(e[t])||EO(e[t]))&&YO(e[t])})),e);function QO(e,t){return new Promise((i=>{let r=setTimeout(i,e);t&&t(r)}))}var XO=(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)}},$O=class{constructor(e){ib(this,"userId"),ib(this,"remoteUserId"),ib(this,"id"),ib(this,"sdkAppId"),ib(this,"type"),ib(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):"","]")),tP.log(e,t,PN(this.userId)||MN(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)}},ZO=UN,eP=!(Zw||eD||tN),tP=new class{constructor(){ib(this,"_isEnableUploadLog",!0),ib(this,"_localJoinedUser",new Map),ib(this,"_queue",[]),ib(this,"_timeoutId",-1),ib(this,"_logLevel",1),ib(this,"_logLevelToUpload",2),!Db&&!Nb&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){VN.on(ZO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&zb[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),VN.on(ZO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),VN.once(ZO.JOIN_FAILED,(()=>{this.startUpload()})),VN.on(ZO.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(vO(i.userId)&&yO(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 nb(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:Sb(),sdkAppId:String(r),userId:i,version:Cb,log:n.map((e=>e.log)).join("\n")}),r),n.forEach((e=>e.uploaded=!0))}}catch(kb){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return xN({retryFunction:()=>aw({url:ZN(t,Gb.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(zb[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){gO(zb[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(vO(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(bb){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(VN.emit(ZO.LOG,{log:s}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(s),e<this._logLevel)return;let a=(null==(o=zb[e])?void 0:o.toLowerCase())||"info";eP?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;zb[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}},iP=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)}))},rP=new class{constructor(){ib(this,"_prefix","TRTC"),ib(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){mN()&&(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(mN())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(sP){tP.warn(sP)}}getItem(e){if(!mN())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(bb){tP.warn(bb)}}setItem(e,t){if(mN())try{let i={expiresIn:Date.now()+Qb,value:t};this._queue.set(this.getRealKey(e),i)}catch(wk){tP.warn(wk)}}deleteItem(e){if(!mN())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(bb){return tP.warn(bb),!1}}clear(){if(mN())try{localStorage.clear()}catch(sP){tP.warn(sP)}}},nP={};ZA(nP,{HTTPS_API:()=>PP,IS_GET_CAPABILITIES_SUPPORTED:()=>$P,IS_GET_SETTINGS_SUPPORTED:()=>XP,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>QP,IS_INSERTABLE_STREAM_SUPPORTED:()=>ZP,IS_RTC_RTP_SENDER_SUPPORTED:()=>qP,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>eM,IS_SEI_SUPPORTED:()=>tM,IS_SPC_SUPPORTED:()=>JP,basis:()=>aM,checkSystemRequirementsInternal:()=>wP,decodeSupportStatus:()=>kP,encodeSupportStatus:()=>bP,getBrowserInfo:()=>TP,getDisplayResolution:()=>LP,isAddTransceiverSupported:()=>GP,isBrowserSupported:()=>SP,isGetReceiversSupported:()=>HP,isGetSendersSupported:()=>jP,isGetTransceiversSupported:()=>WP,isGetUserMediaSupported:()=>xP,isMediaDevicesSupported:()=>IP,isMediaSessionSupported:()=>nM,isMediaStreamTrackProcessorSupported:()=>AP,isReplaceTrackSupported:()=>KP,isRequestVideoFrameCallbackSupported:()=>lM,isSIMDSupported:()=>sM,isScreenCaptureApiAvailable:()=>NP,isSelectedCandidatePair:()=>MP,isSetParametersSupported:()=>YP,isSmallStreamAPISupported:()=>UP,isSmallStreamSupported:()=>FP,isStopTransceiverSupported:()=>zP,isTRTCSupported:()=>DP,isUnifiedPlanDefault:()=>BP,isUsedInHttpProtocol:()=>CP,isWebAudioSupported:()=>VP,isWebCodecSupported:()=>rM,isWebCodecsSupported:()=>EP,isWebRTCSupported:()=>iM,isWebTransportSupported:()=>oM});var oP,sP,aP=eb(lb(),1),cP=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.countMap=new Map,this.distributionMap=new Map,this.log=tP.createLogger({id:"kv"}),e&&(VN.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===tk.AUDIO?pP.START_MICROPHONE:mP.START_CAMERA,cost:i})})),VN.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===tk.AUDIO?pP.START_MICROPHONE:mP.START_CAMERA,error:i})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:KO(this.version||Cb),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(yO(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=fb.UNKNOWN;i&&(yO(i)?r=i:(!gO(i.extraCode)||!gO(i.code))&&(r=i.extraCode||i.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:r,useUV:!1})}},lP=(e=>(e[e.enterRoom=500700]="enterRoom",e[e.exitRoom=500701]="exitRoom",e[e.switchRole=500702]="switchRole",e[e.destroy=500703]="destroy",e[e.startLocalAudio=500704]="startLocalAudio",e[e.updateLocalAudio=500705]="updateLocalAudio",e[e.stopLocalAudio=500706]="stopLocalAudio",e[e.startLocalVideo=500707]="startLocalVideo",e[e.updateLocalVideo=500708]="updateLocalVideo",e[e.stopLocalVideo=500709]="stopLocalVideo",e[e.startScreenShare=500710]="startScreenShare",e[e.updateScreenShare=500711]="updateScreenShare",e[e.stopScreenShare=500712]="stopScreenShare",e[e.startRemoteVideo=500713]="startRemoteVideo",e[e.updateRemoteVideo=500714]="updateRemoteVideo",e[e.stopRemoteVideo=500715]="stopRemoteVideo",e[e.muteRemoteAudio=500716]="muteRemoteAudio",e[e.setRemoteAudioVolume=500717]="setRemoteAudioVolume",e[e.use=500718]="use",e[e.sendSEIMessage=5e5]="sendSEIMessage",e[e.sendCustomMessage=500001]="sendCustomMessage",e))(lP||{}),dP=((oP=dP||{})[oP.AudioMixer=550700]="AudioMixer",oP[oP.AIDenoiser=551700]="AIDenoiser",oP[oP.VirtualBackground=570700]="VirtualBackground",oP[oP.Beauty=571700]="Beauty",oP[oP.Watermark=572700]="Watermark",oP[oP.BasicBeauty=574700]="BasicBeauty",oP[oP.CDNStreaming=590700]="CDNStreaming",oP[oP.DeviceDetector=591700]="DeviceDetector",oP[oP.Debug=592700]="Debug",oP),uP=(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))(uP||{}),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||{}),pP=(e=>(e[e.START_MICROPHONE=501700]="START_MICROPHONE",e[e.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",e[e.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",e))(pP||{}),mP=((sP=mP||{})[sP.START_CAMERA=511700]="START_CAMERA",sP),_P=new cP(!0),fP=new cP(!1),gP=_P,vP={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},yP=new Map([[nD,["Firefox",oD]],[lD,["Edg",dD]],[eN,["Chrome",rN]],[nN,["Safari",sN]],[fD,["TBS",gD]],[vD,["XWEB",yD]],[ID&&Xw,["WeChat",RD]],[kD,["QQ(Win)",wD]],[AD,["QQ(Mobile)",bD]],[CD,["QQ(Mobile X5)",bD]],[DD,["QQ(Mac)",ND]],[OD,["QQ(iPad)",PD]],[HD,["MI",jD]],[WD,["HW",JD]],[zD,["Samsung",qD]],[KD,["OPPO",YD]],[QD,["VIVO",XD]],[aD,["EDGE",cD]],[hD,["SogouMobile",pD]],[mD,["Sogou",_D]]]);function TP(){let e=yP.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var SP=function(){return!(FD||aD||lD&&uD<80||nD&&sD<56)},EP=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},IP=function(){if(!navigator.mediaDevices)return CP()||tP.error(Hw.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},RP=!1;function CP(){return"http:"===location.protocol&&!pN&&(RP||tP.error(DN({key:Dw})),RP=!0,!0)}var AP=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},bP=function(){return nb(this,null,(function*(){if(vP.detail.isH264EncodeSupported&&vP.detail.isVp8EncodeSupported)return{isH264EncodeSupported:vP.detail.isH264EncodeSupported,isVp8EncodeSupported:vP.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection,n=document.createElement(tk.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(),vP.detail.isH264EncodeSupported=t,vP.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:vP.detail.isH264EncodeSupported,isVp8EncodeSupported:vP.detail.isVp8EncodeSupported}}catch(wk){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},kP=function(){return nb(this,null,(function*(){if(vP.detail.isH264DecodeSupported&&vP.detail.isVp8DecodeSupported)return{isH264DecodeSupported:vP.detail.isH264DecodeSupported,isVp8DecodeSupported:vP.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection;return e=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch(wk){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},wP=XO((()=>nb(void 0,null,(function*(){if(vP.result&&vP.detail.isH264EncodeSupported&&vP.detail.isVp8EncodeSupported&&vP.detail.isH264DecodeSupported&&vP.detail.isVp8DecodeSupported)return vP;let e=Date.now(),t=SP(),i=iM(),r=EP(),n=IP(),{isH264EncodeSupported:o,isVp8EncodeSupported:s}=yield bP(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield kP();if(!o||!s){let e=yield bP();tP.warn("detect encode again h264:".concat(o," vp8:").concat(s," result: ").concat(JSON.stringify(e))),o=e.isH264EncodeSupported,s=e.isVp8EncodeSupported}if(o&&a&&(KD||QD||aN)&&!fD&&$D()<79){let{encode:e,decode:t}=yield function(){return nb(this,null,(function*(){return OP||(OP=new Promise((e=>nb(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{tP.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=aP.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=aP.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval((()=>nb(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===tk.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===tk.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(r){i(),tP.warn(r),e(t)}})))).then((e=>((!e.encode||!e.decode)&&tP.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(vN)),e))),OP)}))}();o=e,a=t}return vP.result=t&&i&&n&&(o||s)&&(a||c),vP.detail.isBrowserSupported=t,vP.detail.isWebRTCSupported=i,vP.detail.isWebCodecsSupported=r,vP.detail.isMediaDevicesSupported=n,vP.detail.isScreenShareSupported=NP(),vP.detail.isSmallStreamSupported=FP(),vP.detail.isH264EncodeSupported=o,vP.detail.isVp8EncodeSupported=s,vP.detail.isH264DecodeSupported=a,vP.detail.isVp8DecodeSupported=c,vP.result||tP.error("".concat(navigator.userAgent," ").concat(GO(vP.detail,!1))),rP.setItem(cM,{ua:navigator.userAgent,checkResult:vP}),gP.addNumber({key:523800,value:Date.now()-e}),vP})))),DP=function(){return vP.result},NP=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},OP=null;var PP=(e,t,i)=>{"http:"===location.protocol&&!pN&&(e[t]=()=>{throw new vb({code:fb.INVALID_OPERATION,message:Hw.NOT_SUPPORTED_HTTP})})},MP=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(TO(e.selected)&&!e.selected)};function LP(){let e="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",i=screen.height?screen.height*window.devicePixelRatio:"";e+="".concat(t," * ").concat(i)}return e}function xP(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function VP(){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 UP(){return"captureStream"in HTMLCanvasElement.prototype}function FP(){return!(ID||Zw||iN&&iN<63)&&!(!SP()||!UP())}var BP=function(){if(gO(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:Lk}),e.addTransceiver(tk.AUDIO),t=!0}catch(bb){}return null==e||e.close(),t};function HP(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function jP(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function WP(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function GP(){return 11!==lN&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var JP=!(!GP()||ZD&&iN<86);function zP(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var qP="RTCRtpSender"in window;function KP(){return qP&&"replaceTrack"in window.RTCRtpSender.prototype}function YP(){return qP&&"setParameters"in window.RTCRtpSender.prototype&&jP()}var QP="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,XP=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,$P=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,ZP=qP&&"createEncodedStreams"in window.RTCRtpSender.prototype&&$D()>=86,eM="RTCRtpScriptTransform"in window,tM=qP&&(ZP||eM),iM=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function rM(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return gO(window.AudioDecoder)||(e.AudioDecoder=!0),gO(window.AudioEncoder)||(e.AudioEncoder=!0),gO(window.VideoDecoder)||(e.VideoDecoder=!0),gO(window.VideoEncoder)||(e.VideoEncoder=!0),gO(window.ImageDecoder)||(e.ImageDecoder=!0),e}function nM(){return"mediaSession"in navigator&&!gO(navigator.mediaSession.setActionHandler)}function oM(){return!gO(window.WebTransport)}function sM(){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 aM(){let e={browser:"".concat(_N.name,"/").concat(_N.version),os:RN(),displayResolution:LP(),isScreenShareSupported:NP(),isWebRTCSupported:iM(),isGetUserMediaSupported:xP(),isWebAudioSupported:VP(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:rM(),isMediaSessionSupported:nM(),isWebTransportSupported:oM()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var cM="checkResult";function lM(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}!function(){CP();let e=rP.getItem(cM);e&&e.ua===navigator.userAgent&&(vP=e.checkResult),wP()}();var dM=eb(ob(),1),uM=Symbol("instance"),hM=Symbol("cacheResult"),pM=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,vM.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},mM=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var _M=new Map;function fM(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=_M.get(r)||[];_M.has(r)||_M.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=yM.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return i.sync?r[hM]:Promise.resolve(r[hM]);r.state instanceof pM&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof pM&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new mM(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 mM(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 pM(u,t,s);vM.call(r,h);let p=e=>{var n;return r[hM]=e,h.aborted||(vM.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[hM])),e},m=e=>{let t=e instanceof Error?e.message:String(e);return vM.call(r,u,e),d(new mM(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 gM="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 vM(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(yM.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var yM=class extends dM.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=yM.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[uM];r?this.name=r.name+"-"+r.count++:i[uM]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=_M.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);_M.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=yM.instances.get(e),t||yM.instances.set(e,t=new yM(e,void 0,Object.create(yM.prototype)))):(t=yM.instances2.get(e),t||yM.instances2.set(e,t=new yM(e.constructor.name,void 0,Object.create(yM.prototype)))),t}static getState(e){var t;return null===(t=yM.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};gM(yM.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){vM.call(this,e)}};yM.STATECHANGED="stateChanged",yM.UPDATEAFSM="updateAFSM",yM.INIT="[*]",yM.ON="on",yM.OFF="off",yM.instances=new Map,yM.instances2=new WeakMap;var TM=(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)},SM=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},EM=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),IM=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nw,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=QA(e===rw?{delay:2e3,count:0,backgroundTask:!0}:e===tw?{delay:1e4,count:0}:e===iw?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),SO(t)&&(i=QA(QA({},i),t)),fO(e)&&(t=e,e=nw);let r=QA({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=DO(),r=()=>{if(t=DO()-i,t>=e.delay&&(i=DO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=TM(r,{timeout:e.delay})};return e.ricID=TM(r,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=DO(),r=()=>document.hidden&&e.backgroundTask?(t=DO()-i,i=DO(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(r,e.delay-Math.floor(t%e.delay))):(t=DO()-i,t>=e.delay&&(i=DO()-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=DO()-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&&EM(r),n&&SM(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)}};IM.taskMap=new Map,IM.currentTaskID=1;var RM=IM;tk.SEI_MESSAGE;var CM={LOADED_DATA:tk.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},AM={};ZA(AM,{create:()=>kM,remove:()=>wM});var bM=new WeakMap;function kM(e,t){bM.has(e)||bM.set(e,[]);let i=bM.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 wM(e){let t=bM.get(e);t&&(t.forEach((e=>e())),bM.delete(e))}var DM=new WeakMap;function NM(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,s){let a=xN({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=DM.get(e))&&t.has(o)?n():s(r)}),s,a):null!=(c=DM.get(e))&&c.has(o)?n():s(r)},onRetrying(t,i){var n;ON(r)&&r.call(this,t,i),null!=(n=DM.get(e))&&n.has(o)&&(DM.get(e).get(o).stopRetry=i)},onRetryFailed:n});return s.value=function(){let t=DM.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}):DM.set(e,new Map([[o,{args:r}]])),a.apply(this,r).finally((()=>{var t;return null==(t=DM.get(e))?void 0:t.delete(o)}))},s}}function OM(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=DM.get(e))&&n.has(t)){let{stopRetry:n,args:s}=DM.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=DM.get(e))||o.delete(t))}return s.apply(this,c)},o}}var PM=class extends yM{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,ib(this,"id"),ib(this,"element",null),ib(this,"track"),ib(this,"url"),ib(this,"attr"),ib(this,"muted"),ib(this,"_log"),ib(this,"_pausedRetryCount"),ib(this,"_isElementPlayingFired",!1),ib(this,"_interval"),ib(this,"_delayDestroyTimeoutId",0),ib(this,"_isReplayByRecreateMediaStreamCalled",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=qk,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){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 nb(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(bb){let t=DN({key:ww,data:{media:this.kind,error:bb}});if(this.track&&!this.track.muted&&this._log.warn(bb),t.includes("NotAllowedError"))throw new vb({code:fb.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(tk.ENDED),this._interval>0&&RM.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():uN?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 kM(this.element,this.element).add(tk.PLAYING,e).add(tk.ENDED,e).add(tk.PAUSE,e).add(tk.ERROR,e).add(tk.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==AM||AM.create(this.track,this.track).add(tk.ENDED,e).add(tk.MUTE,e).add(tk.UNMUTE,e),this.track.readyState===tk.ENDED&&this.handleTrackEvent({type:tk.ENDED}),this.track.muted&&this.handleTrackEvent({type:tk.MUTE})}}bindAutoPlayEvent(){VN.on(ZO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&wM(this.track)}unbindEvents(){this.element&&wM(this.element),this.unbindTrackEvents(),VN.off(ZO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case tk.PLAYING:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(tk.PLAYING),this._interval&&(RM.clearTask(this._interval),this._interval=-1);break;case tk.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(tk.ENDED);break;case tk.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(tk.PAUSE),Zw&&(this._interval=RM.run(nw,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case tk.ERROR:if(this.element&&this.element.error){this.handlePaused(tk.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)),FN.uploadEvent({log:"stat-".concat(this.kind,"-").concat(Nk.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),this.replayByRecreateMediaStream(this.element.error)}break;case tk.LOADEDDATA:this.kind===tk.VIDEO&&this.emit(CM.LOADED_DATA)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),FN.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),gP.addSuccessEvent({key:this.kind===tk.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),FN.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),gP.addFailedEvent({key:this.kind===tk.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(CM.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,i)=>{QO(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)}),QO(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 tk.ENDED:this.handleStopped(tk.ENDED);break;case tk.MUTE:this.handlePaused(tk.MUTE);break;case tk.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(tk.UNMUTE)}}handlePlaying(e){this.emit(CM.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(CM.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(CM.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};tb([NM({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],PM.prototype,"doReplayByRecreateMediaStream",1),tb([fM([],"PLAYING",{sync:!0})],PM.prototype,"handlePlaying",1),tb([fM("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],PM.prototype,"handlePaused",1),tb([fM([],"STOPPED",{sync:!0})],PM.prototype,"handleStopped",1);var MM="trtc_autoplay",LM="".concat(MM,"_mask"),xM="".concat(MM,"_wrapper"),VM="".concat(MM,"_header"),UM="".concat(MM,"_content"),FM="".concat(MM,"_action_wrapper"),BM="".concat(MM,"_question"),HM="".concat(MM,"_collapse"),jM="".concat(MM,"_action_confirm"),WM="".concat(MM,"_detail"),GM="#2473E8",JM="dialog",zM="".concat(JM,"-show"),qM="".concat(JM,"-1"),KM="".concat(JM,"-2"),YM=!1,QM=()=>!!document.querySelector(".".concat(xM)),XM="".concat(Fb,"/").concat(uO()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),$M="<br><a href='".concat(XM,"' target='_blank'>").concat(uO()?"其他方案?":"Any other solution?","</a>"),ZM="".concat(uO()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat($M):"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($M)),eL=class{constructor(){if(ib(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),ib(this,"_dialogNode",null),ib(this,"_bodyPosition",""),ib(this,"_showDetail",!1),ib(this,"_isCollapseClicked",!1),ib(this,"_isQuestionClicked",!1),uO()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!YM){let e=document.createElement("style");e.innerHTML=".".concat(LM,"{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(LM," div:not(.").concat(FM,"){display:block !important;}.").concat(xM,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(xM," a{color:").concat(GM,";}.").concat(VM,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(UM,"{margin:8px 0;}.").concat(FM,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(HM,"{margin-right:auto;cursor:pointer}.").concat(BM,"{height:100%;line-height:16px;cursor:pointer;}.").concat(jM,"{margin-left:8px;color:#fff;background:").concat(GM,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(jM,":hover{opacity:0.9;}.").concat(HM,",.").concat(jM,",.").concat(UM,",.").concat(BM,"{font-size:14px;}@media screen and (max-width:750px){.").concat(xM,"{width:80vw;}}"),document.head.appendChild(e),YM=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(LM,"\"><div class='").concat(xM,"'><div class='").concat(VM,"'>").concat(location.host,"</div><div class='").concat(UM,"'>").concat(this.content,"</div><div class='").concat(WM,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(ZM,"</div><div class='").concat(FM,"'></div></div></div>").trim();let t=document.createElement("button");t.className=jM,t.innerText=uO()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=BM,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=HM,r.innerText="".concat(uO()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(FM));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){QM()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(xM)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",tP.info("show autoplay dialog"),FN.uploadEvent({log:zM}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){tP.warn("confirm clicked, try resume stream"),VN.emit(ZO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(WM));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||FN.uploadEvent({log:qM}),this._isCollapseClicked=!0}onQuestionClick(){window.open(XM,"_blank"),this._isQuestionClicked||FN.uploadEvent({log:KM}),this._isQuestionClicked=!0}},tL=class extends PM{constructor(e){super(e,tk.VIDEO),ib(this,"viewMirror",!1),ib(this,"objectFit"),ib(this,"container"),ib(this,"canvas"),this.container=e.container,this.canvas=e.canvas,gO(e.viewMirror)||(this.viewMirror=e.viewMirror),gO(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var e;let t=document.createElement(tk.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(tk.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(tk.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){var t;super.handleElementEvent(e);let i=e.type;if(i===tk.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&&!QM()&&(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===tk.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):i===tk.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(CM.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 iL(e,t){return nb(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),tP.info("worklet addModule success")}catch(bb){throw tP.info("worklet addModule catch error. ".concat(bb.message)),bb}}))}"undefined"!=typeof window&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var rL=new window.AudioContext({sampleRate:48e3}),nL=()=>{"suspended"===rL.state?(rL.resume(),document.addEventListener("click",nL)):"interrupted"===rL.state?rL.resume():document.removeEventListener("click",nL)};document.addEventListener("click",nL),rL.onstatechange=()=>{tP.info("context state: ".concat(rL.state)),nL()};var oL=e=>rL,sL=class{constructor(){ib(this,"node"),ib(this,"pre",new Set),ib(this,"next",new Set),ib(this,"context"),ib(this,"connectedNodes",new Set),ib(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(),gP.addSuccessEvent({key:502701})}catch(wk){tP.error(wk),gP.addFailedEvent({key:502701,error:wk})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),gP.addSuccessEvent({key:502702})}catch(bb){tP.error(bb),gP.addFailedEvent({key:502702,error:bb})}}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}},aL=class extends sL{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,ib(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}},cL=class{constructor(){ib(this,"source",new sL),ib(this,"gain",new sL),ib(this,"destination",new sL)}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(hL(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}},lL=class extends cL{constructor(e){super(),this.context=e,ib(this,"denoiser",new sL),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()}},dL=class{constructor(){ib(this,"audioContext",oL()),ib(this,"destination",this.audioContext.createMediaStreamDestination()),ib(this,"inputs",new Set),ib(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]}},uL=new WeakMap;function hL(e){let t=uL.get(e);if(t)return t;let i=oL();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return uL.set(e,t),t}window.AudioWorkletProcessor||(window.AudioWorkletProcessor=class{constructor(){ib(this,"port")}});var pL=class extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=e=>{let{data:t}=e;switch(t.name){case"chunk":this.cache.push.apply(this.cache,t.data),this.sentFirstInfo1||(this.port.postMessage({cl:t.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=t.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(e,t){let i=e[0],r=t[0];if(!i&&!r)return!0;if(this.isStop)return!1;let n=r?r[0].length:0,o=this.cache.length;o>n?(r[0].set(this.cache.slice(0,n)),this.cache=this.cache.slice(n)):this.unmute&&r[0].set(i[0]);let s=o>n?r[0]:i[0];if(!s)return!0;let a=0;for(let c=0;c<s.length;++c)a=Math.max(Math.abs(s[c]),a);return this.volume=a,this.tick-=s.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,cacheLen:o,outputLen:n})),!0}},mL=pL.toString();delete window.AudioWorkletProcessor;var _L=class{constructor(e){this._volume=0,this._scriptProcessorNode=null,this._audioWorkletNode=null,this._interval=200,this.ready=this.preload();let{log:t}=e;this._log=t,VN.on(ZO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-_L.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!_L.workletReady){let e="".concat(mL.slice(0,5)," VolumeMeterWorklet ").concat(mL.slice(6),";registerProcessor('volume-meter', VolumeMeterWorklet);");_L.workletReady=iL(_L.audioContext,URL.createObjectURL(new Blob([e],{type:"application/javascript"})))}return _L.workletReady.then((()=>this.initAudioWorklet())).catch((e=>(this._log.error("volumeMeter preload error: ".concat(e)),this.initScriptProcessor())))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(_L.audioContext,"volume-meter");let e=!1;this._audioWorkletNode.port.onmessage=t=>{_L.lastMessageTime=Date.now(),this._volume=t.data.volume||0,!e&&t.data.cacheLen&&t.data.outputLen&&(this._log.warn("worklet play success"),e=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(sP){this._log.error("volumeMeter init audio worklet error: ".concat(sP)),FN.logFailedEvent({userId:this._log.userId,eventType:Nk.LOAD_WORKLET,error:sP}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=oL().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{_L.lastMessageTime=Date.now();let t=e.inputBuffer.getChannelData(0),i=0;for(let r=0;r<t.length;++r)i+=t[r]*t[r];this._volume=Math.sqrt(i/t.length)||0}}catch(sP){this._log.error("volumeMeter init script processor error: ".concat(sP))}}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,VN.off(ZO.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})}},fL=_L;fL.lastMessageTime=0,fL.audioContext=oL();var gL=class extends sL{constructor(e){super(),this._volumeMeter=new fL(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return nb(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()}}},vL=fL,yL=eb(ob(),1),TL=e=>t=>t.deviceId===e,SL=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";ib(this,"kind"),ib(this,"type"),ib(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&&RL(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(TL(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");tP.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(TL(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");tP.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},EL=class extends yL.EventEmitter{constructor(){super(),ib(this,"audioInputs",new SL(tk.AUDIO)),ib(this,"videoInputs",new SL(tk.VIDEO)),ib(this,"audioOutputs",new SL(tk.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||RM.run(rw,(()=>{this.update()}),{delay:1e4}))}init(){CL().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return nb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield CL(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},IL=Nb||Db?null:new EL;function RL(e){return e.deviceId===e.groupId&&""===e.groupId}function CL(){return nb(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(CP()||!IP())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{RL(e)&&(e.kind===tk.AUDIO_INPUT?i.audio=!0:e.kind===tk.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(kb){tP.debug("capture before getDevices failed: ",kb)}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&&DL.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function AL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return IL.update(e?1:0).then((e=>e.audioInputs.devices))}function bL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return IL.update(e?2:0).then((e=>e.videoInputs.devices))}var kL=!1;function wL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return nb(this,null,(function*(){return IL.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var DL=new Set;function NL(e,t){return nb(this,null,(function*(){let i=(yield AL()).find((e=>e.deviceId===Kk));return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t}))}var OL,PL=class extends cL{constructor(e){super(),this.log=e,ib(this,"volumeMeter"),ib(this,"volumeDestination"),ib(this,"analyser",new aL),this.volumeMeter=new gL({log:this.log}),this.volumeDestination=new sL,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},ML=class extends PM{constructor(e){super(e,tk.AUDIO),ib(this,"_outputDeviceId"),ib(this,"_volume",1),ib(this,"_destination",oL().createMediaStreamDestination()),ib(this,"pipeline"),ib(this,"volumeMeterMode","worklet"),this.pipeline=new PL(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if(("15.2"===cN||"15.3"===cN||"15.4"===cN)&&this.muted)return void this._log.info("audioElement is muted.");let e=OL||new Audio;e.setAttribute("autoplay","autoplay"),e.srcObject=this.getMediaStream(),e.muted=this.muted,this.element=e,e===OL&&(OL=void 0),this.bindElementEvents()}play(){return nb(this,null,(function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(oL().createAnalyser()),this.setVolume(this._volume),function(){nb(this,null,(function*(){try{kL||(kL=!0,tP.info("speakers:".concat((yield wL()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch($x){}}))}(),rb(ML.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 nb(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()}},LL=class extends ML{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(CM.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)}},xL=class extends ML{constructor(e){super(e),ib(this,"_sourceElement"),ib(this,"_output",new sL),this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this._output.setNode(oL().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(CM.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),wM(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&&oN&&(OL=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},VL=class extends yM{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:o=(1===r?xL:tL)}=e;var s;super(),ib(this,"id",iP()),ib(this,"userId",""),ib(this,"isRemote"),ib(this,"mediaType"),ib(this,"room"),ib(this,"user"),ib(this,"_log"),ib(this,"_inputTrack"),ib(this,"_outputTrack"),ib(this,"isPlayCalled"),ib(this,"container",null),ib(this,"player"),ib(this,"subVideoPlayerMap"),ib(this,"muted",!1),ib(this,"abortCtrl"),ib(this,"objectFit","cover"),ib(this,"mirror"),ib(this,"isScreen",!1),ib(this,"manager"),ib(this,"trackSettings"),this.userId=t||"",this.mediaType=r,this._log=tP.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=n||this.room)?void 0:s.userId,remoteUserId:this instanceof nx?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof nx}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(CM.PLAYER_STATE_CHANGED,(e=>{VN.emit(ZO.PLAYER_STATE_CHANGED,QA({track:this},e)),this.emit("player-state-changed",e)})),this.kind===tk.VIDEO&&(this.player.on(CM.LOADED_DATA,(()=>{VN.emit(ZO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(CM.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(CM.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||tP}get kind(){return 1===this.mediaType?tk.AUDIO:tk.VIDEO}get strMediaType(){return 4===this.mediaType?tk.VIDEO:2===this.mediaType?tk.SCREEN:tk.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 nb(this,null,(function*(){let i=EO(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!gO(t.muted)&&this.setPlayerMute(t.muted),t&&!gO(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof tL&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),EO(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!gO(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===tk.VIDEO)&&this.setPlayerMute(!0),t&&!gO(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof tL&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof tL&&this.player.setContainer(i)),VN.emit(ZO.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(),EO(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!==tk.VIDEO||gO(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(TO(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 nb(this,null,(function*(){if(!this._outputTrack||this.kind===tk.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&&(gO(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new tL({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(r+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let e of i)e.setViewMirror(this.player.mirror),yield e.play()}))}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return(null==(e=this.player)?void 0:e.getInternalAudioLevel())||0}stop(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(RO(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return nb(this,null,(function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),VN.emit(e?ZO.TRACK_MUTED:ZO.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){kM(e,e).add(tk.MUTE,this.onTrackMuted).add(tk.UNMUTE,this.onTrackUnmuted).add(tk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===tk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){wM(e)}setInputMediaStreamTrack(e){var t;let i=this._inputTrack;if(e!==i)return this._inputTrack=e,this.trackSettings=null==(t=e.getSettings)?void 0:t.call(e),e.enabled=!this.muted,i&&this.uninstallTrackEvent(i),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,i||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(t=e.getSettings)?void 0:t.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled)if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch((()=>this.handleAutoPlayFailed())),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(RO(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 eL;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof tL?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"))}};tb([fM([],yM.INIT,{sync:!0})],VL.prototype,"close",1);var UL=Object.prototype.hasOwnProperty;var FL=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(hO(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(UL.call(e,t))return!1;return!0}return!1},BL=xN({retryFunction:function(e){return nb(this,null,(function*(){let t=function(e){return{audio:jL(e),video:WL(e)}}(e);tP.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId"];t.audio&&(i=yield AL(),tP.info("microphones: ".concat(WO(i,{keysToInclude:n})))),t.video&&(r=yield bL(),tP.info("cameras: ".concat(WO(r,{keysToInclude:n}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return $P&&e.getTracks().forEach((e=>{tP.info("".concat(e.kind," capabilities: ").concat(WO(e.getCapabilities(),{keysToInclude:ow})))})),e}catch(o){let{message:t}=o;throw"NotFoundError"===o.name&&(e.video&&r&&0===r.length&&(t=DN({key:Mw})),e.audio&&i&&0===i.length&&(t=DN({key:Pw}))),new vb({code:fb.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,(!nN||n[0].width*n[0].height<=2073600)&&n[0].frameRate&&(n[0].frameRate=n[0].frameRate>10?10:5)),n[0].retryWhenExactFailed&&n[0].useExactDeviceId&&(n[0].useExactDeviceId=!1)):2===s?n[0].useDeviceIdOnly=!0:3===s&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&HL(n[0].microphoneId,!1),n[0].cameraId&&HL(n[0].cameraId,!0)},onRetrying:e=>{tP.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{FN.logFailedEvent({eventType:Nk.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{FN.logSuccessEvent({eventType:Nk.GET_USER_MEDIA_RETRY}),FN.uploadEvent({log:"stat-".concat(Nk.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function HL(e,t){return nb(this,null,(function*(){let i=(t?yield bL():yield AL()).find((t=>t.deviceId===e));i&&fO(i.getCapabilities)&&tP.warn(WO(i.getCapabilities(),{keysToInclude:ow}))}))}function jL(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!FL(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(yO(e.channelCount)&&(t.channelCount=e.channelCount),TO(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),TO(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),TO(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!FL(t)||t)}function WL(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&&!FL(i)?i:(e.width&&(i.width={ideal:e.width},t&&!nD&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!nD&&(i.height.max=e.height)),nD&&LD&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!FL(i)||i)}var GL=BL;function JL(e){return qL(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return nb(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function zL(e){return qL(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return nb(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function qL(e){return function(t,i,r){return r.value=e(r.value,i),r}}var KL=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&tP.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{tP.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),YL=0,QL=class{constructor(){this.log=tP.createLogger({id:"fq".concat(++YL)}),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=QA({},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()}))}},XL=new WeakMap,$L=new WeakMap;function ZL(){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=XL.get(this)||new QL;for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return XL.set(this,t),t.push({fn:n,args:r,context:this},e)},r}}function ex(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=XL.get(this))?void 0:t.queue)||i.forEach((e=>o.push(e))),null==(r=$L.get(this))||r.forEach((e=>null==e?void 0:e.queue.forEach((e=>o.push(e))))),o.forEach((t=>{t.reject(new vb({code:fb.API_CALL_ABORTED,message:e}))})),XL.delete(this),$L.delete(this),n.apply(this,a)},r}}function tx(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=$L.get(this)||new Map,s=r.get(o(t))||new QL;return r.set(o(t),s),$L.set(this,r),s.push({fn:n,args:t,context:this})},r}}function ix(e,t){return qL(((i,r)=>function(){let r=e;try{for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let e=i.apply(this,o),a=DO();return CO(e)?e.then((e=>(t?gP.addSuccessEvent({key:r,cost:DO()-a}):gP.addSuccessEvent({key:r}),e))).catch((e=>{throw gP.addFailedEvent({key:r,error:e}),e})):(gP.addSuccessEvent({key:r}),e)}catch(wb){throw gP.addFailedEvent({key:r,error:wb}),wb}}))}var rx=class extends VL{constructor(e,t){super({mediaType:e,PlayerClass:t}),ib(this,"isRemote",!1),ib(this,"deviceId"),ib(this,"groupId",""),ib(this,"label",""),ib(this,"_isRecapturing",!1),ib(this,"_lastRecaptureTime",0),ib(this,"_onMuteTimeoutId",-1),ib(this,"_encodeCheckTimeoutId",-1),ib(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return"publishing"===this.state.toString()}get isPublished(){return"publish"===this.state}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){kM(e,e).add(tk.MUTE,this.onTrackMuted).add(tk.UNMUTE,this.onTrackUnmuted).add(tk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===tk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){wM(e)}setStateToCapture(){}capture(e){return nb(this,null,(function*(){var t;try{let i,r=DO();VN.emit(ZO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield GL(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),VN.emit(ZO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:DO()-r}),i}catch(kb){throw VN.emit(ZO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:kb}),this.log.error("getUserMedia error observed ".concat(kb)),kb}}))}setInputMediaStreamTrack(e){return this.state===yM.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return null==(t=this.room)?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),VN.emit(ZO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return nb(this,null,(function*(){if(this.mediaTrack&&XP){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return nb(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==tk.AUDIO||t!==Kk||(yield NL(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),CL().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===tk.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(tk.AUDIO_INPUT);return!!DL.has(i)}(this.mediaTrack)||this.kind===tk.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(tk.VIDEO_INPUT);return!!DL.has(i)}(this.mediaTrack)||this._isRecapturing||e&&LD&&nN)}onTrackMuted(){if(super.onTrackMuted(),KL(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ew)return void setTimeout((()=>this.onTrackMuted()),ew);this._onMuteTimeoutId=setTimeout((()=>nb(this,null,(function*(){var e;if(null!=(e=this.mediaTrack)&&e.muted){if((Zw||eD)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return nb(this,null,(function*(){if(rb(rx.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<ew)return void setTimeout((()=>this.onTrackEnded()),ew);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return nb(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 AL():yield bL()).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}),VN.emit(ZO.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),VN.emit(ZO.LOCAL_TRACK_RECAPTURE,{track:this,error:e})}))}))}getRecoverCaptureDeviceId(){return nb(this,null,(function*(){let e=this instanceof lx;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(ox.get(t)||0)+1;if(ox.set(t,i),i>=3){let r=e?(yield bL()).find((e=>!ox.has(e.deviceId))):(yield AL()).find((e=>!ox.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)}},nx=rx;tb([fM(yM.INIT,"capture",{ignoreError:!0,sync:!0})],nx.prototype,"setStateToCapture",1),tb([ZL()],nx.prototype,"capture",1),tb([fM("capture","publish",{ignoreError:!0,success(){var e,t;this.room.localTracks.add(this),VN.emit(ZO.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout((()=>{var e,t;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let e=this.kind===tk.AUDIO,t=this.stat.bytesSent>0;gP[t?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),t||(gP.addEnum({key:e?503701:513703,value:CN()}),FN.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(SN()||AN()),userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}}),5e3))},fail(e){let t="error",i=e.cause;i.message.includes("timeout")?t="timeout":i.code===fb.API_CALL_ABORTED&&(t="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:i})}}),ix(521714,!1)],nx.prototype,"publish",1),tb([qL((e=>function(){return nb(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)}))})),fM([],"capture",{sync:!0})],nx.prototype,"unpublish",1);var ox=new Map;VN.on(ZO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&ox.delete(e.track.deviceId)}));var sx=class extends nx{constructor(e){super(1,LL),ib(this,"mediaType",1),ib(this,"volume",0),ib(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),ib(this,"playerMuted",!0),ib(this,"pipeline"),ib(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),this.manager=e,this.pipeline=new lL(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 nb(this,null,(function*(){yield rb(sx.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};gP.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),gP.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),gP.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=!0}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,customSource:i})}switchDevice(e){return nb(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==Kk)return;if(yield NL(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),this.room&&(yield this.room.replaceTrack(this)),VN.emit(ZO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(wk){throw this.log.error("switch microphone failed ".concat(wk)),this.deviceId&&this.recapture(this.deviceId),wk}}}))}listenDeviceChange(){IL&&!IL.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&IL.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return nb(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e))),gV(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield AL();t[0]?this.recapture(t[0].deviceId):IL.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return nb(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:n}=e;return function*(){let e=!1;!gO(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!gO(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,e=!0),!gO(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&&gP.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;iN<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(gP.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(),IL.off("audioInputAdded",this.handleMicrophoneAdded,this),IL.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return nb(this,null,(function*(){try{yield rb(sx.prototype,this,"recapture").call(this,e)}catch(wk){let i=(yield AL()).find((t=>t.deviceId!==e));if(!i)throw wk;yield rb(sx.prototype,this,"recapture").call(this,i.deviceId)}}))}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduce(((e,t)=>t?t({frame:e}):e),e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}},ax=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}},cx=class{constructor(){ib(this,"_seiMessageList",[]),ib(this,"_smallSeiMessageList",[]),ib(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 ax(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}},lx=class extends nx{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,tL),ib(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),ib(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0}),ib(this,"small"),ib(this,"isNeedToSetBandwidth"),ib(this,"muteImage"),ib(this,"manager"),ib(this,"_seiCodec",new cx),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(XA(QA({},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(XP&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}setMute(e){return nb(this,null,(function*(){var t,i,r;if(vO(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,rb(lx.prototype,this,"setMute").call(this,!1)}else yield null==(r=this.manager)?void 0:r.deleteWatermark("mute"),this.muteImage=void 0,rb(lx.prototype,this,"setMute").call(this,e)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:r=!0,customSource:n,retryWhenExactFailed:o=!0}=e;return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:o,customSource:n})}setProfile(e){let t=QA({},e),i=t.width>t.height;t.width*t.height<=19200&&eD&&ZD&&(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&&hN&&(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(XA(QA({},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:tk.VIDEO,videoType:tk.BIG})})):void 0}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return XP&&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:zO()&&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 nb(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),VN.emit(ZO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(wk){throw this.log.error("switch camera failed ".concat(wk)),this.deviceId&&this.recapture(this.deviceId),wk}}))}listenDeviceChange(){IL&&!IL.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&IL.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return nb(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e))),gV(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield bL();t[0]?this.recapture(t[0].deviceId):IL.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return nb(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}encodeFrame(e,t){if(!this.manager)return e;let i=t?8:this.mediaType;return this.manager.encodePipeline.reduce(((e,t)=>t?t({frame:e,mediaType:i}):e),e)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}play(e,t){return nb(this,null,(function*(){return gO(this.mirror)&&!this.isScreen&&this.setMirror("view"),rb(lx.prototype,this,"play").call(this,e,t)}))}close(){IL.off("videoInputAdded",this.handleCameraAdded,this),IL.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return nb(this,null,(function*(){try{yield rb(lx.prototype,this,"recapture").call(this,e)}catch(wk){let i=(yield bL()).find((t=>t.deviceId!==e));if(!i)throw wk;yield rb(lx.prototype,this,"recapture").call(this,i.deviceId)}}))}},dx=iP();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:dx,exposeOrigin:!0,permittedOrigins:["*"]})}catch($x){}var ux,hx=function(e){return nb(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:nN?{max:e.width}:{ideal:e.width,max:e.width},height:nN?{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);tP.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(eN&&iN<74||nN||nD)&&tP.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){tP.warn("screen applyConstraints failed: ".concat(o))}e.captureElement&&(yield function(e,t){return nb(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&fO(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==dx)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){tP.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 gO(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);tP.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},px=class extends lx{constructor(e){super(e,2),ib(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),ib(this,"objectFit","contain"),ib(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return nb(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 hx({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 vb?e:new vb({code:fb.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return nb(this,null,(function*(){throw new Error("Method not implemented.")}))}},mx=class extends sx{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}};function _x(e){return nb(this,null,(function*(){let t=oL();ux||(ux=iL(t,URL.createObjectURL(new Blob(["registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});"],{type:"application/javascript"})))),yield ux;let i=new AudioWorkletNode(t,"dumper",{numberOfInputs:e.length,numberOfOutputs:0});return e.forEach(((e,t)=>e.connect(i,0,t))),new ReadableStream({start(e){i.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach((e=>e.disconnect(i))),i.port.close()}})}))}var fx=class extends dL{constructor(e){super(),this.room=e,ib(this,"_localAudioTrack"),ib(this,"_localScreenAudioTrack"),ib(this,"log",tP.createLogger({id:"am"})),ib(this,"denoiser"),ib(this,"mixChangedDebounce"),ib(this,"encodePipeline",[]),ib(this,"decodePipeline",[]),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}dump(e){var t,i;if(!this._localAudioTrack)return;let r=[],n=[];null!=(t=this._localAudioPipline)&&t.source.node&&(r.push(this._localAudioPipline.source.node),n.push("mic")),null!=(i=this._localAudioPipline)&&i.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),n.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),n.push("mix")),this.log.info("dump audio track ".concat(n,", duration: ").concat(e));let o=new AbortController,s=[],a=setTimeout((()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")}),1e3*e),c=()=>{for(let e=0;e<n.length;e++){let t=URL.createObjectURL(new Blob(s[e])),i=document.createElement("a");i.href=t,i.download="".concat(n[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(a),o.abort("download")},l=_x(r).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>s[t]=s[t]?s[t].concat(e[0]):[e[0]]))}}),o).catch((e=>c))));return{then:l.then.bind(l),download:c}}getPCM(e){var t;if(gO(WritableStream))return void this.log.warn("getPCM failed: browser not support WritableStream");if(null==(t=this._localAudioPipline)||!t.source.node)return void this.log.warn("getPCM failed: no local audio track");let i=new Float32Array(1920),r=0,n=new AbortController;return _x([this._localAudioPipline.source.node]).then((t=>t.pipeTo(new WritableStream({write(t){!t[0][0]||(i.set(t[0][0],r),r+=t[0][0].length,r>=1920&&(r=0,e(i),i=new Float32Array(1920)))}}),n).catch((e=>this.log.error("stop getPCM reason:".concat(e)))))),n}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}changeInput(e){return e instanceof mx?(this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange()):e instanceof sx?(this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange()):e instanceof Tx?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then((()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([null==(e=this._localAudioTrack)?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),null==(t=this._localScreenAudioTrack)?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])}))),this.mixChangedDebounce}removeInput(e){e instanceof mx?delete this._localScreenAudioTrack:e instanceof sx&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}removeDenoiser(e){var t;if(delete this.denoiser,null==(t=this._localAudioTrack)||t.removeDenoiser(e),this.mixChangedDebounce)return this.mixChangedDebounce}destroy(){this.close()}addEncodeProcessor(e){let{processor:t,type:i}=e;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t)}addDecodeProcessor(e){let{processor:t,type:i}=e;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t)}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}};function gx(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return qL(((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 vb({code:fb.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});tP.warn(i),2===t?s(i):1===t&&n()}),1e3*e);i.apply(this,o).then(n,s).finally((()=>{clearTimeout(a)}))}))}))}var vx=class extends VL{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,ib(this,"tinyId"),ib(this,"isRemote",!0),ib(this,"jitterBufferDelay",0),ib(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===vx.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)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},yx=vx;ib(yx,"STATE_SUBSCRIBE","subscribe"),tb([gx(5,1)],yx.prototype,"waitHasMediaTrack",1),tb([fM(yM.INIT,yx.STATE_SUBSCRIBE,{success(){var e,t;this.log.info("subscribed"),VN.emit(ZO.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3)&&(this._decodeCheckTimeoutId=setTimeout((()=>{var e,t;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3)&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let e=this.kind===tk.AUDIO,t=this.player.isPlaying||(e?this.getAudioLevel()>0:this.stat.framesDecoded>0);gP[t?"addSuccessEvent":"addFailedEvent"]({key:e?504700:514702}),t||(gP.addEnum({key:e?504701:514703,value:CN()}),FN.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(SN()||AN()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===tk.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))))}}),5e3))},ignoreError:!0}),ix(521716,!1)],yx.prototype,"subscribe",1),tb([fM(yx.STATE_SUBSCRIBE,yM.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),VN.emit(ZO.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],yx.prototype,"unsubscribe",1);var Tx=class extends yx{constructor(e,t){super(e,t,1),ib(this,"volume",0),ib(this,"mediaType",1),ib(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),ib(this,"audioDecoder"),this.manager=e.audioManager}onPlayerError(e){if(this.enableDecodeFrame){this._log.warn("use audio decoder"),this.room.enableInsertableStreams(),this.player.setOutput();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!!this.manager&&(this.manager.decodePipeline.some((e=>e))||(null==(t=null==(e=this.player.element)?void 0:e.error)?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&rM().AudioDecoder&&ZP)}decodeFrame(e){var t;if(!this.manager)return e;let i=this.manager.decodePipeline.reduce(((e,t)=>t?t({frame:e}):e),e);return"configured"===(null==(t=this.audioDecoder)?void 0:t.state)&&this.audioDecoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"})),i}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}},Sx=[-1,-1,1,-1,-1,1,1,1],Ex=[0,0,1,0,0,1,1,1],Ix=class extends yM{constructor(e,t){if(super(),this.context=e,ib(this,"name"),ib(this,"input"),ib(this,"output"),ib(this,"texture"),ib(this,"ctx2d",null),ib(this,"fbo"),ib(this,"width",0),ib(this,"height",0),ib(this,"x",0),ib(this,"y",0),ib(this,"program"),ib(this,"vertexShader"),ib(this,"fragmentShader"),ib(this,"totalFrames",0),ib(this,"dropFrames",0),ib(this,"matchInputSize",!0),ib(this,"texCoordBuffer"),ib(this,"positionBuffer"),ib(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),ib(this,"cost",0),ib(this,"_canvas",null),ib(this,"_image"),ib(this,"log"),this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof pV){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(Ex),this.positionBuffer=this.createBuffer(Sx),!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(kb){this.context.destroy(new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(kb.message||kb)}))}}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 hV&&this.render(e)||this.context instanceof pV&&this.render2d(e))&&(this.totalFrames++,this.cost=Date.now()-t,!0)}render2d(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&this.draw2d(this.input.image,0,0,this.width,this.height)}update(e){var t;null==(t=this.output)||t.update(e)}disconnect(){for(var e,t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];null==(e=this.output)||e.removeInput(this,...i),delete this.output}removeInput(e){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),null==(e=this.output)||e.removeInput(this),delete this.output,null==(t=this.input)||t.disconnect(),this.context instanceof hV){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},QA({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,i=t.createTexture();return this.useTextures(i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};function Rx(){}tb([fM(yM.INIT,"connected",{sync:!0})],Ix.prototype,"connect",1),tb([fM("connected",yM.INIT,{ignoreError:!0,sync:!0})],Ix.prototype,"disconnect",1),tb([fM([],"closed",{sync:!0})],Ix.prototype,"close",1);var Cx=e=>e();function Ax(){this.dispose()}var bx=1,kx=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new xx(e,this,this.streamId++);return Vx.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},wx=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=Rx,this.error=Rx,this.next=Rx,this.dispose=Rx,this.subscribe=Rx,this.doDefer()}subscribe(e){return e instanceof kx?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(Cx),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}},Dx=class extends wx{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)}},Nx=class extends wx{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Rx,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Rx,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Rx;if(super(),this._next=t,this._error=i,this._complete=r,this.then=Rx,e instanceof kx){let n={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{Vx.defer(n,0)})),Vx.create(n),Vx.pipe(n),this.sourceId=n.id,this.subscribe(e),Vx.subscribe({id:n.id,end:!0}),t==Rx?this._next=e=>Vx.next(n,0,e):this.next=e=>{Vx.next(n,0,e),t(e)},r==Rx?this._complete=()=>Vx.complete(n,0):this.complete=()=>{this.dispose(),Vx.complete(n,0),r()},i==Rx?this._error=e=>Vx.complete(n,0,e):this.error=e=>{this.dispose(),Vx.complete(n,0,e),i()}}else this.subscribe(e)}next(e){this._next(e)}complete(){this.dispose(),this._complete()}error(e){this.dispose(),this._error(e)}};function Ox(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return i.reduce(((e,t)=>t(e)),e)}function Px(e,t,i){if("undefined"!=typeof __FASTRX_DEVTOOLS__){let r=Object.defineProperties(Object.setPrototypeOf(e,kx.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}});Vx.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof kx&&Vx.addSource(r,t)}return r}return e}function Mx(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 kx){let n=Px((t=>{let o=new e(t,...r);o.sourceId=n.id,o.subscribe(i)}),t,arguments);return n.source=i,Vx.pipe(n),n}return t=>i(new e(t,...r))}}}function Lx(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var xx=class extends Dx{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{Vx.defer(this.source,this.id)}))}next(e){Vx.next(this.source,this.id,e),this.sink.next(e)}complete(){Vx.complete(this.source,this.id),this.sink.complete()}error(e){Vx.complete(this.source,this.id,e),this.sink.error(e)}},Vx={addSource(e,t){Lx("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){Lx("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;Lx("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){Lx("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){Lx("defer",{id:e.id,streamId:t})},pipe(e){Lx("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){Lx("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=bx++),Lx("create",{name:e.toString(),id:e.id})}},Ux=class extends wx{constructor(e){super(),this.source=e,this.sinks=new Set}add(e){e.defer((()=>this.remove(e))),1===this.sinks.add(e).size&&(this.reset(),this.subscribe(this.source))}remove(e){this.sinks.delete(e),0===this.sinks.size&&this.dispose()}next(e){this.sinks.forEach((t=>t.next(e)))}complete(){this.sinks.forEach((e=>e.complete())),this.sinks.clear()}error(e){this.sinks.forEach((t=>t.error(e))),this.sinks.clear()}};function Fx(){return e=>{let t=new Ux(e);if(e instanceof kx){let i=Px((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,Vx.pipe(i),i}return Px(t.add.bind(t),"share",arguments)}}function Bx(e,t){return i=>{let r=e=>i.next(e);i.defer((()=>t(r))),e(r)}}function Hx(e,t){if("on"in e&&"off"in e)return Px(Bx((i=>e.on(t,i)),(i=>e.off(t,i))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return Px(Bx((i=>e.addListener(t,i)),(i=>e.removeListener(t,i))),"fromEvent",arguments);if("addEventListener"in e)return Px(Bx((i=>e.addEventListener(t,i)),(i=>e.removeEventListener(t,i))),"fromEvent",arguments);throw"target is not a EventDispachter"}var jx=Mx(class extends Dx{constructor(e,t,i){super(e),this.filter=t,this.thisArg=i}next(e){this.filter.call(this.thisArg,e)&&this.sink.next(e)}},"filter"),Wx=Mx(class extends Dx{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&this.complete()}},"take"),Gx=Mx(class extends Dx{constructor(e,t){super(e);let i=new Dx(e);i.next=()=>e.complete(),i.complete=Ax,i.subscribe(t)}},"takeUntil"),Jx=Mx(class extends Dx{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),zx=Mx(class extends Dx{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},"map"),qx=class extends Dx{constructor(e,t,i){super(e),this.data=t,this.context=i}next(e){let t=this.context.combineResults;t?this.sink.next(t(this.data,e)):this.sink.next(e)}tryComplete(){this.context.resetComplete(),this.dispose()}},Kx=class extends Dx{constructor(e,t,i){super(e),this.makeSource=t,this.combineResults=i,this.index=0}subInner(e,t){let i=this.currentSink=new t(this.sink,e,this);this.complete=this.tryComplete,i.complete=i.tryComplete,i.subscribe(this.makeSource(e,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Yx=class extends qx{},Qx=class extends Kx{next(e){this.subInner(e,Yx),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Yx)}}},Xx=Mx(Qx,"switchMap");var $x,Zx=($x=Mx(Qx,"switchMapTo"),(e,t)=>$x((()=>e),t)),eV=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Rx,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Rx,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Rx;return r=>new Nx(r,e,t,i)},tV=Ox(function(e){return Px((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}(250),zx((()=>performance.now())),Fx()),iV=[0,1,1,1,0,0,1,0],rV=class extends Ix{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),ib(this,"_intervalId",0),ib(this,"_sequence",0),ib(this,"checkGLError",!1),ib(this,"checkVisibilityChange"),e instanceof pV?this.ctx2d=e.ctx||null:e.available&&(null==t?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(iV)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),RM.clearTask(this._intervalId),this._intervalId=RM.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(RM.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof hV){let e=this.context.ctx.getError();e&&this.context.destroy(new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:5,message:"".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)}))}}),{fps:this.context.frameRate})}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];super.addInput(e,...i),this.start(this.context.frameRate)}update(e){if(this._intervalId&&(RM.clearTask(this._intervalId),this._intervalId=0,1===e)){this.log.info("".concat(this.name," use requestVideoFrameCallback"));let e=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",e))};document.addEventListener("visibilitychange",e)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),RM.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),RM.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},nV=class extends rV{constructor(e,t){super(e,t),ib(this,"_videoTrack"),ib(this,"_muteOb"),ib(this,"_closedOb",Hx(this,"closed")),ib(this,"_subscription"),ib(this,"_canvasContainer"),Number(sN)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=Hx(this._videoTrack,"mute"),Ox(Hx(this._videoTrack,"ended"),Gx(this._closedOb),eV((()=>{this.context.destroy(new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){this._subscription=Ox(this._muteOb,Gx(this._closedOb),Zx((e=>t=>{let i=performance.now();Ox(tV,Jx((t=>t-i<e)),Wx(1))(t)})(5e3)),eV((()=>{var e;null==(e=this._videoTrack)||!e.muted||this.context.destroy(new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))})))}disableCheckMute(){var e;null==(e=this._subscription)||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info("".concat(this.name," put canvas to body")),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack,null==(t=this._canvasContainer)||t.remove()}},oV=class extends nV{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},sV=class extends nV{constructor(e,t,i){super(e,{name:"smallDestination",logger:i}),this.resolution=t}resize(e,t){let i,r=e*t,n=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),r>n?i=r/n:(this.log.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(e," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),i=r/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},aV=class extends Ix{constructor(e,t){super(e,QA({name:"imageSource"},t)),ib(this,"_lastImage"),ib(this,"_totalFrames",0),ib(this,"_autoResize",!1),ib(this,"_canvasRendered"),ib(this,"_videoCallbackId",0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===lN&&(this._canvasRendered=function(e){let t=arguments,i=Fx()(Px((t=>{i.next=e=>t.next(e),i.complete=()=>t.complete(),i.error=e=>t.error(e),e&&t.subscribe(e)}),"subject",t));return i.next=Rx,i.complete=Rx,i.error=Rx,i}(),Ox(this._canvasRendered,function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>Px((function(i){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.length;for(;r<n&&!i.disposed;)i.next(t[r++]);i.disposed||i.subscribe(e)}),"startWith",arguments)}(this._image),Xx((e=>e instanceof HTMLCanvasElement?Hx(e,"rendered"):function(){return Px((e=>e.complete()),"empty",arguments)}())),Gx(Hx(this,"closed")),eV((()=>{this.update(0)}))))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),lM()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback(((e,t)=>{document.hidden||(this._totalFrames=t.presentedFrames,this.update(1))})))}_render(e,t){let{width:i,height:r}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(n),({videoWidth:i,videoHeight:r}=n),!i||!r)return!1;n.width=i,n.height=r}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if(({width:i,height:r}=n),n!==this._lastImage)this._lastImage=n;else if(i===this.width&&r===this.height)return!1}else(n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas)&&(({width:i,height:r}=n),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===i&&this.height===r&&this.totalFrames){if(t){this.useTexture();let e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)}this.resize(i,r)}return!0}get image(){return this._image}set image(e){var t;null==(t=this._canvasRendered)||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},cV=class extends aV{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",Ox(Hx(this._player,CM.PLAYER_STATE_CHANGED),Gx(Hx(this,"closed")),jx((e=>{let{state:t}=e;return"PLAYING"===t})),eV((()=>{this.tryVideoFrameCallback(this._player.element)})))}get image(){return this._player.element}},lV=class extends cV{constructor(e,t,i){super(e,new tL({id:i.name,track:t,muted:!0,container:null,objectFit:"contain",log:i.logger}),i),this.name="videoTrackSource",this._player.play()}replaceTrack(e){this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},dV=class extends yM{constructor(e){super(),ib(this,"frameRate"),ib(this,"_canvas"),ib(this,"log"),ib(this,"hasAlpha",!1),ib(this,"name"),ib(this,"error"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new lV(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new nV(this,e)}createVideoImageSource(e,t){return new aV(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new cV(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};ib(dV,"_ids",0);var uV={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},hV=class extends dV{constructor(){super(...arguments),ib(this,"defaultProgam"),ib(this,"defaultVShader"),ib(this,"defaultFShader"),ib(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(dV._ids++)),this.ctx=this._canvas.getContext("webgl2",uV),!this.ctx)throw new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,"\n// 顶点着色器\nattribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main() {\n gl_Position = a_position;\n v_texCoord = a_texCoord;\n}\n"),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,"\n// 片元着色器\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\n\nvoid main() {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n} "),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",(()=>{this.destroy(new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})),this.log.info("video context created use webgl")}destroy(e){let t="";return e&&(t=e.message,this.error=e,gP.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info("video context destroy".concat(t)?": ".concat(t):""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;null==(t=this.ctx)||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let i=this.ctx,r=i.createShader(e);return i.shaderSource(r,t),i.compileShader(r),r}createProgram(e,t){let i=this.ctx,r=i.createProgram();return i.attachShader(r,e),i.attachShader(r,t),i.linkProgram(r),i.getProgramParameter(r,i.LINK_STATUS)||this.log.error(i.getProgramInfoLog(r)),r}};tb([fM(yM.INIT,"created",{sync:!0,fail(e){gP.addFailedEvent({key:512700,error:e.cause})},success(){gP.addSuccessEvent({key:512700})}})],hV.prototype,"create",1),tb([fM("created",yM.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit("unavailable",e),this.removeAllListeners()}})],hV.prototype,"destroy",1);var pV=class extends dV{constructor(){super(...arguments),ib(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(dV._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this.log.info("video context created use 2d")}destroy(e){let t="";e&&(t=e.message,this.error=e,gP.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info("video context destroy ".concat(t?": ".concat(t):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),gP.addSuccessEvent({key:512703})}};tb([fM(yM.INIT,"created",{sync:!0,fail(e){gP.addFailedEvent({key:512701,error:e.cause})},success(){gP.addSuccessEvent({key:512701})}})],pV.prototype,"create",1),tb([fM("created",yM.INIT,{ignoreError:!0,sync:!0})],pV.prototype,"destroy",1);var mV=class extends yx{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),ib(this,"mediaType",4),ib(this,"source"),ib(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager}play(e,t){return(TO(null==t?void 0:t.canvasRender)?t.canvasRender:17===lN)&&!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 pV({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=e.createVideoPlayerSource(this.player);this.source=t;let i=new rV(e,{name:"remotePlayer",logger:this.log});t.connect(i),this.player.setCanvas(e._canvas),lM()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,i=function(e){return[15,30,45,60].reduce(((t,i)=>Math.abs(i-e)<Math.abs(t-e)?i:t))}(t);!yO(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&&this.manager.decodePipeline.some((e=>e))}decodeFrame(e){return this.manager?this.manager.decodePipeline.reduce(((e,t)=>t?t({frame:e,track:this}):e),e):e}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}},_V=class extends mV{constructor(e,t){super(e,t,2),ib(this,"mediaType",2),ib(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}},fV=new Map;function gV(e,t){let i=XA(QA({},t),{timestamp:Tb()});fV.has(e)?fV.get(e).push(i):fV.set(e,[i])}VN.on(ZO.JOIN_SUCCESS,(e=>{let{room:t}=e;gV(t.userId,{eventId:32788})})),VN.on(ZO.LEAVE_START,(e=>{let{room:t}=e;gV(t.userId,{eventId:32789})})),VN.on(ZO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),gV(t.room.userId,{eventId:e})}})),VN.on(ZO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),gV(t.room.userId,{eventId:e})}})),VN.on(ZO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===tk.AUDIO?gV(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):gV(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),VN.on(ZO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===tk.AUDIO?gV(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):gV(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),VN.on(ZO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&gV(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&gV(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&gV(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),VN.on(ZO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&gV(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&gV(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&gV(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),VN.on(ZO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&gV(t.room.userId,{eventId:t.kind===tk.VIDEO?32780:32781})})),VN.on(ZO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&gV(t.room.userId,{eventId:t.kind===tk.VIDEO?32782:32783})})),VN.on(ZO.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&&gV(i.userId,{eventId:t})})),VN.on(ZO.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&&gV(i.userId,{eventId:t,remoteUserId:o})})),VN.on(ZO.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),gV(t,l),gP.addEnum({key:i?514701:513701,value:a}),gP.addEnum({key:i?514700:513700,value:c})})),VN.on(ZO.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===tk.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),gV(t.userId,e)}}));var vV=eb(ob(),1),yV=class extends vV.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,ib(this,"userMap",new Map),ib(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,"]");gO(t)||(r+=":".concat($k[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=LO(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:LO(0,n),muteState:s,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function TV(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return qL(((e,n)=>{let o=new WeakMap;return VN.on(ZO.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 vb({code:fb.INVALID_OPERATION,message:DN({key:Uw,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>i,name:n,timesInSecond:t,maxSizeInSecond:i}})});s.callCountInSecond++,e.call(this,...c)}}))}var SV,EV=!0,IV={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"},RV={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},CV=((SV=CV||{})[SV.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",SV[SV.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",SV[SV.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",SV[SV.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",SV[SV.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",SV[SV.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",SV[SV.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",SV[SV.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",SV[SV.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",SV[SV.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",SV[SV.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",SV[SV.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",SV[SV.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",SV[SV.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",SV[SV.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",SV[SV.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",SV[SV.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",SV[SV.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",SV[SV.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",SV[SV.INVALID_OPERATION=5100]="INVALID_OPERATION",SV[SV.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",SV[SV.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",SV[SV.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",SV[SV.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",SV[SV.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",SV[SV.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",SV[SV.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",SV[SV.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",SV[SV.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",SV[SV.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",SV[SV.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",SV[SV.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",SV[SV.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",SV[SV.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",SV[SV.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",SV[SV.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",SV[SV.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",SV[SV.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",SV[SV.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",SV[SV.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",SV[SV.DEVICE_ERROR=5300]="DEVICE_ERROR",SV[SV.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",SV[SV.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",SV[SV.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",SV[SV.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",SV[SV.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",SV[SV.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",SV[SV.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",SV[SV.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",SV[SV.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",SV[SV.SERVER_ERROR=5400]="SERVER_ERROR",SV[SV.NEED_TO_BUY=5401]="NEED_TO_BUY",SV[SV.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",SV[SV.OPERATION_FAILED=5500]="OPERATION_FAILED",SV[SV.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",SV[SV.REJOIN_FAILED=5502]="REJOIN_FAILED",SV[SV.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",SV[SV.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",SV[SV.OPERATION_ABORT=5998]="OPERATION_ABORT",SV[SV.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",SV);var AV=XA(QA({},Hw),{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(_O(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(_O(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=bV(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=bV(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=bV(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=bV(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=bV(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=bV(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=bV(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 bV(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var kV=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=CV[i];try{t=AV[a]}catch(o){t=AV.UNKNOWN_ERROR}return fO(t)?s=t(r):vO(t)&&(s=t),r.fnName&&!s.includes(r.fnName)&&("."!==s[s.length-1]&&(s+="."),s+=" thrown from ".concat(r.fnName,"()")),n&&(s+=" doc:"),s}({code:t===RV.SERVER_ERROR?t:i||t,params:QA({fnName:o,error:s},n)}),super(c),ib(this,"name","RtcError"),ib(this,"code"),ib(this,"extraCode"),ib(this,"functionName"),ib(this,"message"),ib(this,"handler"),ib(this,"originError"),this.name=CV[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");MD?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):LD&&(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 vb){let{stack:n}=e,o={code:RV.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case fb.INVALID_PARAMETER:o.code=RV.INVALID_PARAMETER,o.message=e.message;break;case fb.INVALID_OPERATION:o.code=RV.INVALID_OPERATION;break;case fb.NOT_SUPPORTED:case fb.NOT_SUPPORTED_H264:o.code=RV.ENV_NOT_SUPPORTED,e.getCode()===fb.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(Hw.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case fb.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case fb.SERVER_TIMEOUT:case fb.SWITCH_ROLE_FAILED:o.code=RV.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case fb.API_CALL_ABORTED:o.code=RV.OPERATION_ABORT;break;case fb.DEVICE_NOT_FOUND:case fb.DEVICE_AUTO_RECOVER_FAILED:case fb.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 fb.UNKNOWN:break;default:o.code=RV.OPERATION_FAILED}r=new kV(o),n&&(r.stack+=n.substr(n.indexOf("\n")))}else{if(e instanceof kV)return e;r=new kV({code:RV.UNKNOWN_ERROR,fnName:t,originError:e})}return r}};var wV=kV,DV={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}}},NV={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}}},OV={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(vO(e)&&!document.getElementById(e))throw new wV({code:RV.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},PV={name:"userId",required:!0,type:"string"},MV={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[IV.AUDIO_PROFILE_STANDARD,IV.AUDIO_PROFILE_STANDARD_STEREO,IV.AUDIO_PROFILE_HIGH,IV.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function LV(e,t){if(!e)throw new wV({code:RV.INVALID_OPERATION,extraCode:5101,fnName:t})}function xV(e,t,i){if(!e)throw new wV({code:RV.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var VV={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 wV({code:RV.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(vO(e.roomId))throw new wV({code:RV.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new wV({code:RV.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new wV({code:RV.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new wV({code:RV.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:OV,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:DV},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&CP())throw new wV({code:RV.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:XA(QA({},OV),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:DV}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:MV},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&CP())throw new wV({code:RV.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:MV}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:OV,publish:{type:"boolean"},option:NV},validate(e,t,i,r,n){var o;if((null==(o=null==e?void 0:e.option)||!o.videoTrack)&&CP())throw new wV({code:RV.ENV_NOT_SUPPORTED,extraCode:5201});if(!NP())throw new wV({code:RV.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:OV,publish:{type:"boolean"},option:NV}},muteRemoteAudio:[PV,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[PV,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:OV,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){LV(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(xV(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new wV({code:RV.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:XA(QA({},OV),{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){LV(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(xV(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new wV({code:RV.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&&gO(e.streamType))throw new wV({code:RV.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){LV(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(!tM)throw new wV({code:RV.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new wV({code:RV.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new wV({code:RV.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new wV({code:RV.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});LV(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 wV({code:RV.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 wV({code:RV.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new wV({code:RV.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(LV(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new wV({code:RV.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}}},UV={TRTC:VV},FV=class extends Error{};function BV(e,t){let i=FO(e);for(let r=0;r<t.length;r++)UO(i[r],t[r]);return i}function HV(e){this._resolve=Promise.resolve(e)}function jV(e){this._reject=Promise.reject(e)}var WV=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=BV;let i=WV.instances.get(e);i?i.set(t,this):WV.instances.set(e,new Map([[t,this]]))}static get(e,t){if(!t)return;let i=WV.instances.get(e);return i&&i.get(t)||new WV(e,t)}static gets(e,t){let i=WV.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 FV("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:HV,reject:jV};try{switch(this.state){case 1:if(0===e)throw new FV("already started");break;case 4:if(2===e)throw new FV("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 FV("already start");break;case 3:switch(e.type){case 2:throw new FV("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new FV("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new FV("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 FV("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new FV("start not allowed after update");case 0:throw new FV("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new FV("keep start")),new FV("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}},GV=WV;GV.instances=new WeakMap;var JV=new WeakMap,zV=(e,t)=>{if(t instanceof FV){let{stack:i}=t;t=new wV({code:RV.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function qV(e,t){return qL(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let a=GV.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(zV.bind(null,r))):i.apply(this,o)}))}function KV(e,t){let{merge:i,debounce:r}=t||{};return qL(((t,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=GV.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=JV.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(zV.bind(null,n)).then(r,o)}),e);JV.has(this)?null==(l=JV.get(this))||l.set(i(...s),{timeoutId:u,resolve:r}):JV.set(this,new Map([[i(...s),{timeoutId:u,resolve:r}]]))}))}return c.action(2,t.bind(this),s).catch(zV.bind(null,n))}))}function YV(e){return qL(((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(GV.gets(this,s).map((e=>e.action(3,(()=>Promise.resolve()),n)))).then((()=>t.call(this,...n)));let a=GV.get(this,s);return a?a.action(3,t.bind(this),n).catch(zV.bind(null,i)):t.apply(this,n)}))}var QV={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message"},XV=new Set([QV.ERROR,QV.AUTOPLAY_FAILED,QV.KICKED_OUT,QV.REMOTE_USER_ENTER,QV.REMOTE_USER_EXIT,QV.REMOTE_AUDIO_AVAILABLE,QV.REMOTE_AUDIO_UNAVAILABLE,QV.REMOTE_VIDEO_AVAILABLE,QV.REMOTE_VIDEO_UNAVAILABLE,QV.CONNECTION_STATE_CHANGED,QV.PUBLISH_STATE_CHANGED,QV.SCREEN_SHARE_STOPPED,QV.DEVICE_CHANGED]);function $V(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function ZV(e){return e===IV.QOS_PREFERENCE_CLEAR?"detail":e===IV.QOS_PREFERENCE_SMOOTH?"motion":""}var eU=class{constructor(){ib(this,"_log"),this._log=tP.createLogger({id:"fd"})}download(e,t){return nb(this,null,(function*(){let{type:i="blob"}=t||{};try{let t,r=DO();if(t=fO(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let n=DO()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(n,"ms")),gP.addSuccessEvent({key:522700,cost:DO()-r}),t.data}catch(kb){throw this._log.error("failed to download: ".concat(e,", error: ").concat(kb)),gP.addFailedEvent({key:522700,error:kb}),kb}}))}downloadWithFetch(e,t){return nb(this,null,(function*(){this._log.info("download with fetch: ".concat(e,", return type: ").concat(t));try{let i,r=yield fetch(e);if(!r.ok)throw new Error("network response was not ok");return i="arraybuffer"===t?yield r.arrayBuffer():yield r.blob(),{data:i}}catch(wk){throw wk}}))}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType=t,n.onload=()=>{200===n.status||0===n.status&&n.response?i({data:n.response}):r(new Error("XHR failed"))},n.onerror=r,n.send(null)}))}loadWasm(e,t){return nb(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=DO(),r=null,n=null;if(fO(WebAssembly.instantiateStreaming)&&!(e=>e.startsWith("data:application/octet-stream;base64,"))(e)&&!(e=>e.startsWith("file://"))(e)&&fO(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(wb){n=wb}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(wb){n=wb}if(r){let t=DO()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),gP.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),gP.addFailedEvent({key:522701,error:n}),n}))}};tb([NM({settings:{timeout:0,retries:3},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],eU.prototype,"download",1);var tU=new eU;function iU(e){let{TRTC:t,room:i,errorModule:r,assetsPath:n}=e;return{TRTC:t,room:i,assetsPath:n,fileDownloader:tU,innerEmitter:VN,constants:Ib,environment:jw,utils:Eb,eventLogger:FN,log:this.room.getLogger(),loggerManager:tP,errorModule:r,kvStatManager:gP,rtcDectection:nP,trtc:this,clearStarted:(e,t)=>{let i=e.getAlias(),r=GV.instances.get(this);if(r)if(t){let e=r.get(i+t);if(!e)return;e.started=!1}else r.forEach(((e,t)=>{t.startsWith(i)&&(e.started=!1)}))},startGetPCM:_x,createAudioNode:hL}}var rU=new WeakMap;function nU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return qL(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{sU.call(this,t,n,i,this._name)}catch(kb){return Promise.reject(kb)}return e.apply(this,n)}))}function oU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return qL(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{sU.call(this,t,n,i,this._name)}catch(kb){throw kb}return e.apply(this,n)}))}function sU(e,t,i,r){if(EO(e))for(let n=0;n<e.length;n++)aU.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else aU.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function aU(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function s(e){return{code:RV.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(gO(i)){if(t.required)throw new wV(s(5001));if(gO(t.defaultValue))return void(fO(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),fO(t.type[r])&&i instanceof t.type[r]&&(e=!0),vO(t.type[r])&&_O(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new wV({code:RV.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>AO(e)?bO(e):vO(e)?e:_O(e)))},value:i}})}else if(!gO(t.type)&&_O(i)!==t.type)throw new wV(s(5002));if(!1===t.allowEmpty){let e=yO(i)&&(0===i||Number.isNaN(i)),t=vO(i)&&""===i.trim();if(e||t)throw new wV(s(5003))}if(t.notLessThanZero&&yO(i)&&i<0)throw new wV(s(5006));if(!gO(t.min)&&yO(i)&&i<t.min)throw new wV(s(5007));if(!gO(t.max)&&yO(i)&&i>t.max)throw new wV(s(5008));if(vO(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new wV(s(5004))}else if(fO(t.instanceOf)&&!(i instanceof t.instanceOf))throw new wV(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new wV(s(5005));let{properties:a}=t;hO(a)&&SO(i)&&Object.keys(a).forEach((e=>{aU.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;hO(c)&&EO(i)&&i.forEach(((e,t)=>{aU.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),fO(t.validate)&&t.validate.call(this,i,r,n,o,this)}function cU(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r}=e;return qL(((e,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];var c;function l(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(_O(t)):(JSON.stringify(t),t)}catch(n){return"type:".concat(_O(t))}}let d=this._log||tP;s.length>0?d.info("".concat(n,"() ").concat(JSON.stringify(s,((e,t)=>l(e,t,["userSig","privateMapKey"]))))):d.info("".concat(n,"()"));let u=r?r(...s):lP[n];try{let i=e.apply(this,s),r=DO();return CO(i)?i.then((e=>(d.info("".concat(n,"() success ").concat(t.call(this,...s))),gP.addSuccessEvent({key:u,cost:DO()-r}),e))).catch((e=>{var i;let r=(e=wV.convertFrom.call(this,e,n,1===s.length?s[0]:s)).extraCode||e.code,o=null!=(i=e.message)&&i.includes(r)?"":" code:".concat(r);throw d.error("".concat(n,"() failed ").concat(t.call(this,...s)," ").concat(e).concat(o," params: ").concat(JSON.stringify(s,l))),gP.addFailedEvent({key:u,error:e}),e})):(gP.addSuccessEvent({key:u}),i)}catch(h){let e=(h=wV.convertFrom.call(this,h,n)).extraCode||h.code,t=null!=(c=h.message)&&c.includes(e)?"":" code:".concat(e);throw d.error("".concat(n,"() failed ").concat(h).concat(t," params: ").concat(JSON.stringify(s,l))),gP.addFailedEvent({key:u,error:h}),h}}))}var lU=e=>qL(((t,i)=>function(r,n){return nb(this,null,(function*(){let o=this._plugins.get(r);if(!o)throw this._log.error("plugin ".concat(String(r)," is not found")),new wV({code:RV.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(fO(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new wV({code:RV.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return sU.call(this,o.getValidateRule(e),[n],i,"TRTC"),t.call(this,o,n)}))})),dU=0,uU=class{constructor(e,t){ib(this,"player"),ib(this,"publisher"),ib(this,"mixInput"),this.mixInput=new lL(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||(gO(e.volume)||(this.volume=e.volume),gO(e.loop)||(this.loop=e.loop),gO(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 hU(e,t){if(t&&"function"!=typeof t)throw new wV({code:RV.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var pU=class{constructor(e){this.core=e,ib(this,"log"),ib(this,"mixedMusicMap",new Map),ib(this,"cacheMusicMap",new Map),dU+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(dU)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat(dU)),this.core=e}getName(){return pU.Name}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(e){switch(e){case"start":return pU.startValidateRule;case"update":return pU.updateValidateRule;case"stop":return pU.stopValidateRule}}start(e){return nb(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 uU(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.")),gP.addEnum({key:502700,value:3}),this.kvUpload(e)}))}update(e){return nb(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),gO(i)||o.setOperation(i),gO(r)||o.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return nb(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&&gP.addCount({key:502711}),i&&gP.addCount({key:502703}),r&&gP.addCount({key:502704}),n&&gP.addCount({key:502705}),o&&gP.addCount({key:502706}),s&&gP.addCount({key:502707}),"function"!=typeof a&&gP.addCount({key:502709}),"function"!=typeof l&&gP.addCount({key:502710}),"function"!=typeof c&&gP.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()}},mU=pU;ib(mU,"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 wV({code:RV.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new wV({code:RV.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});hU("onTimeUpdate",e.onTimeUpdate),hU("onEnded",e.onEnded),hU("onDurationChange",e.onDurationChange)}}),ib(mU,"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){hU("onTimeUpdate",e.onTimeUpdate),hU("onEnded",e.onEnded),hU("onDurationChange",e.onDurationChange)}}),ib(mU,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),ib(mU,"Name","AudioMixer");var _U,fU=0,gU=class{constructor(e){this.core=e,ib(this,"log"),ib(this,"audioContext",oL()),ib(this,"workletNode"),fU+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(fU)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(fU)),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 wV({code:RV.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return _U||(_U=this.doPreload(e)),_U}doPreload(e){return nb(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield iL(this.audioContext,i)}finally{URL.revokeObjectURL(i)}}))}getName(){return gU.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(e){switch(e){case"start":return gU.startValidateRule(this.core);case"update":return gU.updateValidateRule;case"stop":return gU.stopValidateRule}}start(e){return nb(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 nb(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=(e=>(e=Number(e))>0&&e<14e8)(e)?yU.MAIN_OVERSEA:yU.MAIN,t}(t),"/api/v1/audioAiAuth?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(r,"×tamp=").concat(n),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d="Init RTCAIDenoiser failed.",u="";switch(s){case 1:u="Please check your params.";break;case 2:u="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:u="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:u="Your version is not supported."}return{auth:!1,status:l,message:a?"".concat(d," Reason: ").concat(a,". ").concat(u):"".concat(d,", ").concat(u)}}()}))}(XA(QA({},e),{timestamp:t}));if(!i)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(i,". Message: ").concat(o)),new wV({code:RV.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 nb(this,null,(function*(){}))}stop(){return nb(this,null,(function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)}))}destroy(){!this.workletNode||(this.workletNode.port.onmessage=null)}},vU=gU;ib(vU,"updateValidateRule",{type:"object"}),ib(vU,"stopValidateRule",{type:"object"}),ib(vU,"Name","AIDenoiser");var yU={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};var TU=eb(ob(),1),SU=class extends TU.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 nb(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(bb){FN.uploadEvent({log:"stat-pressure-detector-start-failed",error:bb})}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&tP.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(wk){FN.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:wk})}}},EU=new SU;function IU(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 ax(new DataView(new Uint8Array(s).buffer),!0)}function RU(e){return"empty"===e.type||0===e.data.byteLength}function CU(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}function AU(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 bU(e){let{frame:t,seiMessageList:i}=e;if(!i||0===i.length||0===t.data.byteLength)return t;let r=9-AU(t.data);if(r<=0)return t;let n=i.splice(0,r).reverse().map(IU),o=n.reduce(((e,t)=>e+t.dataView.byteLength),0),s=new ArrayBuffer(o+t.data.byteLength),a=new DataView(s),c=new DataView(t.data),l=0;for(let d=0;d<n.length;d++)for(let e=0;e<n[d].dataView.byteLength;e++)a.setInt8(l++,n[d].dataView.getInt8(e));for(let d=0;d<t.data.byteLength;d++)a.setInt8(l++,c.getInt8(d));return t.data=s,t}function kU(e){let{frame:t,onSEI:i}=e;try{let e=new DataView(t.data);if(RU(t)||!CU(e))return t;let r=[],n=0,o=-1,s=-1;for(let i=0;i<t.data.byteLength;i++){let a=e.getUint8(i);if(0===a)n++;else if(1===a){if(2===n||3===n){let a=i-n;if(-1===o?o=a:-1===s&&(s=a,r.push(new ax(new DataView(e.buffer.slice(o,s)))),o=a,s=-1),6!==e.getUint8(i+1)){t.data=e.buffer.slice(a);break}}n=0}else n=0}null==i||i(r.reverse())}catch(bb){}return t}var wU=0,DU=class{constructor(e){this.core=e,ib(this,"log"),ib(this,"_seiMessageList",[]),ib(this,"_smallSeiMessageList",[]),ib(this,"_subStreamSeiMessageList",[]),wU++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(wU)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(wU)),this.core=e,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:t,mediaType:i}=e;try{return bU({frame:t,seiMessageList:8===i?this._smallSeiMessageList:2===i?this._subStreamSeiMessageList:this._seiMessageList})}catch(wk){this.log.warn(wk)}return t}decode(e){let{frame:t,track:i}=e;return kU({frame:t,onSEI:e=>{e.forEach((e=>{this.core.trtc.emit(QV.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:i.userId,streamType:2===i.mediaType?"sub":"main"})}))}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:ZP?this.encode:bU,type:1}),this.core.room.videoManager.addDecodeProcessor({processor:ZP?this.decode:kU,type:1})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:1}),this.core.room.videoManager.removeDecodeProcessor({type:1})}update(e){let{buffer:t,options:i}=e;var r;let n=[i.seiPayloadType,t],o=!!i.small;i.toSubStream?this._subStreamSeiMessageList.push(n):(this._seiMessageList.push(n),o&&this._smallSeiMessageList.push(n)),null==(r=this.core.room.scriptTransformWorker)||r.postMessage({type:"sei",data:n,isMain:!i.toSubStream,small:o})}getName(){return DU.Name}getAlias(){return"sei"}getGroup(){return"sei"}},NU=DU;ib(NU,"autoStart",!0),ib(NU,"Name","SEI");var OU,PU=0,MU=class{constructor(e){this.core=e,ib(this,"_core"),ib(this,"log"),ib(this,"dumpLocalVideoMap",{}),ib(this,"dumpRemoteVideoMap",{}),ib(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++PU)}),this.log.info("created")}getName(){return MU.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(e){switch(e){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return nb(this,null,(function*(){!new URLSearchParams(location.search).has("trtcDebug")||(yield this.openDebugDiaLog(),this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED&&this.addVideoProcessor())}))}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return nb(this,null,(function*(){try{if(OU)yield OU;else{let e=Date.now();OU=this.loadScript("https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@".concat(Cb,".js")),yield OU,this.log.info("download debug dialog script cost: ".concat(Date.now()-e,"ms"))}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(sP){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(sP))}}))}closeDebugDiaLog(){var e;null==(e=this.dialog)||e.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):this.encodeVideoDump,type:2}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):this.decodeVideoDump,type:2})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:2}),this._core.room.videoManager.removeDecodeProcessor({type:2})}encodeVideo(e){let{frame:t,mediaType:i}=e;return this.encodeVideoDump({frame:t,onDump:()=>{if(!i)return;let e=2===i?"sub":"main",r=this.dumpLocalVideoMap[e];r&&(r.data.push(t.data),r.duration>0&&Date.now()-r.startTimestamp>1e3*r.duration&&r.onDumpEnd())}})}decodeVideo(e){let{frame:t,track:i}=e;return this.decodeVideoDump({frame:t,onDump:()=>{if(!i)return;let e=this.dumpRemoteVideoMap["".concat(i.userId,"-").concat(i.streamType)];e&&(e.data.push(t.data),e.duration>0&&Date.now()-e.startTimestamp>1e3*e.duration&&e.onDumpEnd())}})}encodeVideoDump(e){let{frame:t,onDump:i}=e;return null==i||i(),t}decodeVideoDump(e){let{frame:t,onDump:i}=e;return null==i||i(),t}loadScript(e){return new Promise(((t,i)=>{this.log.info("loading debug dialog from ".concat(e));let r=document.createElement("script");r.type="text/javascript",r.onload=t,r.onerror=i,r.crossOrigin="anonymous",r.src=e,document.head.append?document.head.append(r):document.getElementsByTagName("head")[0].appendChild(r)}))}},LU=MU;ib(LU,"Name","Debug"),ib(LU,"autoStart",!0),tb([NM({settings:{timeout:3e3,retries:3},onError(e,t,i){var r;null!=(r=null==e?void 0:e.message)&&r.includes("timeout")?t():i(e)}})],LU.prototype,"loadScript",1);var xU=0,VU=new Set,UU=null;Ab("5.8.5-ef.3");var FU={RtcError:wV,ErrorCode:RV,ErrorCodeDictionary:CV},BU=class extends mb.EventEmitter{constructor(e,t){super(),ib(this,"_room"),ib(this,"_eventListened",new Set),ib(this,"_localVideoTrack",null),ib(this,"_localAudioTrack",null),ib(this,"_localScreenTrack",null),ib(this,"_localScreenAudioTrack",null),ib(this,"_localVideoConfig",null),ib(this,"_localScreenConfig",null),ib(this,"_localAudioConfig",null),ib(this,"_remoteVideoConfigMap",new Map),ib(this,"_remoteAudioConfigMap",new Map),ib(this,"_remoteAudioMuteMap",new Map),ib(this,"_mediaTrackMap",new WeakMap),ib(this,"_log",tP.createLogger({id:"t".concat(++xU)})),ib(this,"_plugins",new Map),ib(this,"_networkQuality",null),ib(this,"_speakerId"),ib(this,"_getPCMAbortCtrl"),this._room=new e(QA({logger:this._log,frameWorkType:BU.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(mU,t.assetsPath),this._use(vU,t.assetsPath),this._use(LU),t.enableSEI&&tM&&this._use(NU),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(QV.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{this._log.error(new wV({code:RV.OPERATION_FAILED,extraCode:5504,message:e.message,originError:e}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:i}=e;e.emit=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{return i.apply(e,n)}catch(kb){let i=DN({key:xw,data:{name:t,event:n[0]},addDocLink:!1});return tP.warn("".concat(i,"\n\n").concat(kb.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,t){!function(){var e;EV&&(EV=!1,5!==tP.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Fb,"/en/index.html")),console.info("* Changelog: ".concat(Fb,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),tP.info("TRTC Web SDK Version:",Cb),tP.info("UA:",navigator.userAgent),tP.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),yN().then((e=>{e&&tP.info(vN)})))}();let i=new BU(e,t||{});return VU.add(i),i}get room(){return this._room}_listenEvents(){kM(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(QV.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(QV.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(QV.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(QV.ERROR,wV.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(QV.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e;let t=XA(QA({},e),{uplinkRTT:Math.min(e.uplinkRTT,sw),downlinkRTT:Math.min(e.downlinkRTT,sw)});this.emit(QV.NETWORK_QUALITY,t)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{kM(t,t).add("player-state-changed",(i=>{let r=XA(QA({},i),{userId:e.userId});t.kind===tk.VIDEO&&(r.streamType=$V(t.streamType)),this.emit(t.kind===tk.AUDIO?QV.AUDIO_PLAY_STATE_CHANGED:QV.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===fb.PLAY_NOT_ALLOWED&&this.emit(QV.AUTOPLAY_FAILED,{userId:t.userId})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{wM(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?QV.REMOTE_AUDIO_AVAILABLE:QV.REMOTE_AUDIO_UNAVAILABLE,{userId:r}),s?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i})),o!==a&&(this.emit(a?QV.REMOTE_VIDEO_AVAILABLE:QV.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?QV.REMOTE_VIDEO_AVAILABLE:QV.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(QV.SEI_MESSAGE,XA(QA({},e),{streamType:$V(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(QV.ERROR,new wV({code:RV.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,i,r,n,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(r=this._networkQuality)?void 0:r.downlinkRTT)||0,sw),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)/lw},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)/lw},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(QV.STATISTICS,l)})).add("custom-message",(e=>{this.emit(QV.CUSTOM_MESSAGE,e)})),kM(this,IL).add("audioInputAdded",(e=>{this.emit(QV.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(QV.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(QV.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(QV.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>nb(this,null,(function*(){if(this.emit(QV.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),UU&&UU.deviceId===Yk){let e=(yield wL()).find((e=>e.deviceId===Yk));e&&UU.groupId!==e.groupId&&(UU=e,this.emit(QV.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>nb(this,null,(function*(){this.emit(QV.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield wL())[0];if(!t||!UU||UU.groupId===t.groupId)return;let i=UU.deviceId===e.deviceId,r=UU.deviceId===Yk&&UU.deviceId===t.deviceId;(i||r)&&(UU=t,this.emit(QV.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(iU.call(this,{TRTC:BU,room:this._room,errorModule:FU,assetsPath:t}));this._plugins.set(e.Name,i),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return nb(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),!vO(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,TO(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:"audience"===e.role?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,r,BU.frameWorkType),this._checkTrackToPublish(),EU.start()}))}exitRoom(){return nb(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return nb(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(){wM(this),this.removeAllListeners(),this._room.destroy(),VU.delete(this),0===VU.size&&EU.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 nb(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 sx(e._room.audioManager),s={},a={muted:!0};n&&(gO(n.microphoneId)?gO(n.audioTrack)||(s.customSource=n.audioTrack):s.deviceId=n.microphoneId,n&&yO(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),gO(n.profile)||(vO(n.profile)?$b[n.profile]&&o.setProfile($b[n.profile]):o.setProfile(n.profile)),yO(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),gO(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),gO(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),gO(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",(t=>{e.emit(QV.ERROR,new wV({code:RV.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(QV.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=wV.convertFrom(t.error)),e.emit(QV.PUBLISH_STATE_CHANGED,XA(QA({},t),{error:i}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),gO(r)||o.setMute(r),kM(o,o).add("player-state-changed",(t=>{e.emit(QV.AUDIO_PLAY_STATE_CHANGED,XA(QA({},t),{userId:""}))})),e.listeners(QV.AUDIO_FRAME).length>0&&(e._getPCMAbortCtrl=e._room.audioManager.getPCM((t=>{e.emit(BU.EVENT.AUDIO_FRAME,{data:t})}))),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localAudioTrack=o,e._localAudioConfig=XA(QA({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:a,track:o})}()}))}updateLocalAudio(e){return nb(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):gO(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),gO(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),gO(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!gO(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),gO(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),UO(this._localAudioConfig,e)}))}stopLocalAudio(){return nb(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),wM(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))}))}startLocalVideo(){return nb(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 lx(e._room.videoManager),a={},c={};if(o&&(o.cameraId?a.deviceId=o.cameraId:gO(o.useFrontCamera)?gO(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?tk.FACING_MODE_USER:tk.FACING_MODE_ENVIRONMENT,gO(o.profile)||(vO(o.profile)?Zb[o.profile]&&s.setProfile(Zb[o.profile]):s.setProfile(o.profile)),gO(o.fillMode)||(c.objectFit=o.fillMode),gO(o.mirror)||(c.mirror=o.mirror),gO(o.small)||(FP()?vO(o.small)?s.small=Zb[o.small]:!0===o.small?s.small=Zb["120p"]:s.small=o.small:e._log.warn("small stream is not supported"))),s.on("5",(t=>{e.emit(QV.ERROR,new wV({code:RV.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),s.on("2",(t=>{e.emit(QV.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),s.on("4",(t=>{let i;t.error&&(i=wV.convertFrom(t.error)),e.emit(QV.PUBLISH_STATE_CHANGED,XA(QA({},t),{error:i}))})),e._listenOutputTrackChanged(s),yield s.capture(a),gO(n)||(yield s.setMute(n)),s.mediaTrack){if(null!=o&&o.qosPreference){let e=ZV(o.qosPreference);s.mediaTrack.contentHint=e}else null!=o&&o.videoTrack||(s.mediaTrack.contentHint=ZV(IV.QOS_PREFERENCE_SMOOTH));s.outMediaTrack&&(s.outMediaTrack.contentHint=s.mediaTrack.contentHint)}kM(s,s).add("player-state-changed",(t=>{e.emit(QV.VIDEO_PLAY_STATE_CHANGED,XA(QA({},t),{userId:"",streamType:"main"}))})),r&&e._room.isJoined&&e._room.publish(s).catch((()=>{})),e._localVideoTrack=s,e._localVideoConfig=XA(QA({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:s})}()}))}updateLocalVideo(e){return nb(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:r,option:n}=e,o={};if(n){if(gO(n.profile)||(vO(n.profile)?Zb[n.profile]&&this._localVideoTrack.setProfile(Zb[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&gO(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):gO(n.useFrontCamera)?gO(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?tk.FACING_MODE_USER:tk.FACING_MODE_ENVIRONMENT),gO(n.fillMode)||(o.objectFit=n.fillMode),gO(n.mirror)||(o.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let e=ZV(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e,this._localVideoTrack.outMediaTrack&&(this._localVideoTrack.outMediaTrack.contentHint=e)}if(n.small){let e=!this._localVideoTrack.small;FP()?(!0===n.small?this._localVideoTrack.small=Zb["120p"]:vO(n.small)?this._localVideoTrack.small=Zb[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&&!gO(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),gO(r)||(yield this._localVideoTrack.setMute(r)),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),UO(this._localVideoConfig,e)}))}stopLocalVideo(){return nb(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),wM(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return nb(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 px(e._room.videoManager);o.on("4",(t=>{let i;t.error&&(i=wV.convertFrom(t.error)),e.emit(QV.PUBLISH_STATE_CHANGED,XA(QA({},t),{error:i}))})),e._listenOutputTrackChanged(o),"main"===t.streamType&&(o.mediaType=4);let s=null,a={},c={};n&&(gO(n.profile)||(vO(n.profile)?ek[n.profile]&&o.setProfile(ek[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(a.systemAudio=!0,a.echoCancellation=n.echoCancellation,a.noiseSuppression=n.noiseSuppression,a.autoGainControl=n.autoGainControl),gO(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=ZV(n.qosPreference);o.mediaTrack.contentHint=e}else null!=n&&n.videoTrack||(o.mediaTrack.contentHint=ZV(IV.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(tk.ENDED,(()=>{e._stopScreenShare(),e.emit(QV.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(s=new mx(e._room.audioManager),s.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&s.setAudioOutput(e._speakerId)),kM(o,o).add("player-state-changed",(t=>{e.emit(QV.VIDEO_PLAY_STATE_CHANGED,XA(QA({},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=XA(QA({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:o})}()}))}updateScreenShare(e){return nb(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(gO(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let e=ZV(r.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}this._room.isJoined&&!gO(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}),UO(this._localScreenConfig,e)}))}stopScreenShare(){return nb(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return nb(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&&(gO(n.fillMode)||(a.objectFit=n.fillMode),gO(n.mirror)||(a.mirror=n.mirror),a.canvasRender=n.canvasRender,"main"===r&&!gO(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&&!gO(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return nb(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&&(gO(s.fillMode)||(l.objectFit=s.fillMode),gO(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&&!gO(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:h}),UO(h,e);let p=gO(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=gO(r)?h.view:r,_=gO(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 nb(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return nb(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 nb(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 nb(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return nb(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return nb(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){return this.listeners(e).includes(t)||(this._log.debug("on",e),super.on(e,t,i),this._eventListened.add(e),e===BU.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM((e=>{this.emit(BU.EVENT.AUDIO_FRAME,{data:e})})))),this}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];try{XV.has(e)&&this._log.debug("emit ".concat(e," ").concat(JSON.stringify(i)))}catch(kb){}return super.emit(e,...i)}off(e,t,i){var r,n;return this._log.debug("off",e),"*"===e?(this._eventListened.clear(),this.removeAllListeners(),null==(r=this._getPCMAbortCtrl)||r.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,i),e===BU.EVENT.AUDIO_FRAME&&(null==(n=this._getPCMAbortCtrl)||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},i=null,r="main",n=!1;if(vO(t)?e=t:(e=t.userId,n=!0===t.processed,t.streamType&&(r=t.streamType)),e){let t=this._room.remotePublishedUserMap.get(e);t&&(i=t.remoteAudioTrack)}else i="sub"===r?this._localScreenAudioTrack:this._localAudioTrack;return i?n&&i.outMediaTrack&&i.outMediaTrack!==i.mediaTrack?i.outMediaTrack.clone():i.mediaTrack:null}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main",processed:r=!1}=e,n=null;if(""===t)"main"===i&&this._localVideoTrack&&(n=this._localVideoTrack),"sub"===i&&this._localScreenTrack&&(n=this._localScreenTrack);else{let e=this._room.remotePublishedUserMap.get(t);e&&(n="main"===i?e.remoteVideoTrack:e.remoteAuxiliaryTrack)}return n?r&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{userId:t,streamType:i="main"}=e;if(t){let e=this._room.remotePublishedUserMap.get(t);if("main"===i&&(null==e?void 0:e.muteState.hasVideo))return e.remoteVideoTrack.getVideoFrame();if("sub"===i&&(null==e?void 0:e.muteState.hasAuxiliary))return e.remoteAuxiliaryTrack.getVideoFrame()}else{if("main"===i&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,i;this._speakerId=e,null==(t=this._localAudioTrack)||t.setAudioOutput(e),null==(i=this._localScreenAudioTrack)||i.setAudioOutput(e),this._room.remotePublishedUserMap.forEach((t=>t.remoteAudioTrack.setAudioOutput(e)))}setCurrentSpeaker(e){return nb(this,null,(function*(){(yield wL()).forEach((t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(QV.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),UU=t)})),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')}))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return nb(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&&(gO(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(HB){throw this._remoteAudioConfigMap.delete(t),HB}this._emitTrackEvent(o)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return nb(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 nb(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),gO(t)&&n&&n.view&&!MO(i)){let e=BO(n.view);e.length>0&&(yield r.play(e,i))}if(!gO(t)){let e=BO(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return nb(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:r}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t)}catch(wb){}gO(t.muted)||i.setPlayerMute(t.muted),gO(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(QV.TRACK,{userId:i,streamType:$V(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(gO(i))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat($V(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||EO(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(BO(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 nb(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=>{wM(e.remoteAudioTrack),wM(e.remoteVideoTrack),wM(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return nb(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),wM(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_initActiveSpeaker(){return nb(this,null,(function*(){if(UU&&!RL(UU))this.emit(QV.DEVICE_CHANGED,{type:"speaker",action:"active",device:UU});else{let e=yield wL();if(e[0]&&!RL(e[0]))UU=e[0],this.emit(QV.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let e=e=>{let{track:t}=e;"audio"===t.kind&&(!UU||RL(UU))&&(this._initActiveSpeaker(),VN.off("102",this._initActiveSpeaker))};VN.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:XA(QA({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),gP.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),gP.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){tP.setLogLevel(e),gO(t)||(t?tP.enableUploadLog():tP.disableUploadLog())}static isSupported(){return wP()}static getCameraList(){return bL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return AL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return wL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(e){return nb(this,null,(function*(){(yield wL()).forEach((t=>{t.deviceId===e&&(VU.forEach((i=>{i._setCurrentSpeaker(e),i.emit(QV.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),UU=t)}))}))}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:o,version:s}=e;switch(s&&(fP.version=s),t){case"count":fP.addCount({key:i,useUV:o});break;case"enum":fP.addEnum({key:i,value:r,useUV:o});break;case"number":fP.addNumber({key:i,value:r,split:n})}}},HU=BU;ib(HU,"_loggerManager",tP),ib(HU,"EVENT",QV),ib(HU,"ERROR_CODE",RV),ib(HU,"TYPE",IV),ib(HU,"frameWorkType",30),tb([cU({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"}})})],HU.prototype,"use",1),tb([nU(UV.TRTC.enterRoom),qV("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})),qL((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),cU()],HU.prototype,"enterRoom",1),tb([cU()],HU.prototype,"exitRoom",1),tb([nU(UV.TRTC.switchRole),KV("room",{merge:(e,t)=>t}),cU()],HU.prototype,"switchRole",1),tb([cU()],HU.prototype,"destroy",1),tb([nU(UV.TRTC.startLocalAudio),qV("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)})),cU()],HU.prototype,"startLocalAudio",1),tb([nU(UV.TRTC.updateLocalAudio),KV("audio",{debounce:{delay:200,getKey:()=>"".concat(xU,"-localAudio"),isNeedToDebounce:e=>{var t;return!gO(null==(t=e.option)?void 0:t.captureVolume)}}}),cU()],HU.prototype,"updateLocalAudio",1),tb([YV("audio"),cU()],HU.prototype,"stopLocalAudio",1),tb([nU(UV.TRTC.startLocalVideo),qV("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)})),cU()],HU.prototype,"startLocalVideo",1),tb([nU(UV.TRTC.updateLocalVideo),KV("video"),cU()],HU.prototype,"updateLocalVideo",1),tb([YV("video"),cU()],HU.prototype,"stopLocalVideo",1),tb([nU(UV.TRTC.startScreenShare),qV("screen",(()=>!0)),cU()],HU.prototype,"startScreenShare",1),tb([nU(UV.TRTC.updateScreenShare),KV("screen"),cU()],HU.prototype,"updateScreenShare",1),tb([cU()],HU.prototype,"stopScreenShare",1),tb([nU(UV.TRTC.startRemoteVideo),qV((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),cU({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],HU.prototype,"startRemoteVideo",1),tb([nU(UV.TRTC.updateRemoteVideo),KV((e=>"v".concat(e.userId).concat(e.streamType))),cU({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],HU.prototype,"updateRemoteVideo",1),tb([nU(UV.TRTC.stopRemoteVideo),qL((e=>function(t){return nb(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)}))})),cU({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],HU.prototype,"stopRemoteVideo",1),tb([YV((e=>"v".concat(e.userId).concat(e.streamType)))],HU.prototype,"_stopRemoteVideo",1),tb([nU(...UV.TRTC.muteRemoteAudio),cU({getRemoteId:e=>e})],HU.prototype,"muteRemoteAudio",1),tb([oU(...UV.TRTC.setRemoteAudioVolume),function(e,t){return qL(((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=rU.get(this))?void 0:s.get(t(...n));c&&c>0&&clearTimeout(c);let l=window.setTimeout((()=>{i.apply(this,n)}),e);rU.has(this)?null==(a=rU.get(this))||a.set(t(...n),l):rU.set(this,new Map([[t(...n),l]]))}))}(200,(e=>e)),cU({getRemoteId:e=>e})],HU.prototype,"setRemoteAudioVolume",1),tb([lU("start"),zL((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),qV(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),cU({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>dP[e.getName()]})],HU.prototype,"startPlugin",1),tb([lU("update"),KV(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),cU({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>uP[e.getName()]})],HU.prototype,"updatePlugin",1),tb([lU("stop"),YV(((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i})),cU({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>hP[e.getName()]})],HU.prototype,"stopPlugin",1),tb([oU(...UV.TRTC.enableAudioVolumeEvaluation)],HU.prototype,"enableAudioVolumeEvaluation",1),tb([cU()],HU.prototype,"getVideoSnapshot",1),tb([cU()],HU.prototype,"_setCurrentSpeaker",1),tb([qV((e=>"a".concat(e.userId)),(()=>!0))],HU.prototype,"_startRemoteAudio",1),tb([qL((e=>function(t){return nb(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(XA(QA({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),YV((e=>"a".concat(e.userId)))],HU.prototype,"_stopRemoteAudio",1),tb([YV("room")],HU.prototype,"_exitRoom",1),tb([YV("screen")],HU.prototype,"_stopScreenShare",1),tb([nU(...UV.TRTC.sendSEIMessage),TV({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}})],HU.prototype,"sendSEIMessage",1),tb([nU(UV.TRTC.sendCustomMessage),TV({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],HU.prototype,"sendCustomMessage",1),tb([nU(UV.TRTC.create)],HU,"_create",1);var jU=HU,WU=class{constructor(){this._set=new Set,VN.on(ZO.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 GU(){return nb(this,null,(function*(){let e,t;try{let t=yield AL();e=t&&t.length}catch(u){}try{let e=yield bL();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:s}=this.checkSystemResult.detail,a=nP.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};FN.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),FN.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var JU=eb(ob()),zU="1",qU="2",KU="3",YU="4",QU="5",XU="6",$U={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},ZU=[$U.UPDATE_REMOTE_MUTE_STAT,$U.UPLINK_NETWORK_STATS,$U.USER_LIST_RES,$U.MUTE_RESULT,$U.SERVER_FIRST_PACKAGE_RECEIVED,$U.RECEIVE_CUSTOM_MSG],eF={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"},tF="publish_change",iF="join",rF="leave",nF="quality_report",oF="mute_uplink",sF="publish",aF="publish_state_change",cF="unpublish",lF="subscribe",dF="unsubscribe",uF="subscribe_change",hF="start_publishing",pF="stop_publishing",mF="start_push_user_cdn",_F="stop_push_user_cdn",fF="start_mcu_mix",gF="stop_mcu_mix",vF="start_publish_cdn_stream",yF="update_publish_cdn_stream",TF="stop_publish_cdn_stream",SF="get_user_list",EF="change_role",IF="update_constraint_config",RF="rebuild_pc",CF="join/v2",AF="publish/v2",bF="subscribe/v3",kF="ability_status_report",wF="reconnect",DF="channel_msg",NF=new Set;var OF=class extends JU.default{constructor(e){var t,i;super(),ib(this,"room"),ib(this,"url"),ib(this,"backupUrl"),ib(this,"race"),ib(this,"destroyed",!1),ib(this,"_socketInUse"),ib(this,"_socket"),ib(this,"_backupSocket"),ib(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),ib(this,"_currentState","DISCONNECTED"),ib(this,"_isReconnecting",!1),ib(this,"_seq",0),ib(this,"_log"),ib(this,"_lastMessageTime",-1),ib(this,"_connnectStartTime",-1),ib(this,"_stopConnectRetry"),ib(this,"bytesSent",0),ib(this,"bytesReceived",0),ib(this,"keepAlive",!1),ib(this,"signalDomainWhenUnifiedProxy"),ib(this,"stopKeepAliveTimeout"),ib(this,"rtt",0),this.room=e.room,this.race=!!gO(e.race)||e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,((null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0)-NF.size>0&&this.room.enableSPC&&(this.keepAlive=!0,NF.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=tP.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));this.signalDomainWhenUnifiedProxy&&(e+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy)));let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+="&clientIp=".concat(t)),this.race?"".concat(e,"&race=1"):e}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return"CONNECTED"===this._currentState}get isConnecting(){return"CONNECTING"===this._currentState}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return nb(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=DO();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 wO(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?tk.BACKUP:tk.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?tk.MAIN:tk.BACKUP),t(new vb({code:fb.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===tk.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(wk){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(wk){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse){if(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?tk.MAIN:tk.BACKUP),this._socketInUse=null,this.reconnect()}this.room.isJoining&&this.emit(QU,new vb({code:fb.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"}))}}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(tk.MAIN),this.unbindAndCloseSocket(tk.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(QU,new vb({code:fb.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=JO(e.data);let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values($U),o=Object.keys($U)[n.indexOf(i)],s=eF[o]||i;switch(ZU.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case $U.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,r.svrTime&&function(e){yb=e-(new Date).getTime();let t=new Date;t.setTime(e),tP.info("baseTime from server: ".concat(t," offset: ").concat(yb))}(r.svrTime),this._log.info("ChannelSetup Success"),gP.addSuccessEvent({key:521701,cost:DO()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(zU,{signalInfo:this._signalInfo});else{let e=new vb({code:fb.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:DN({key:uw,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),gP.addFailedEvent({key:521701,error:e}),this.emit(QU,e)}break;case $U.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 nb(this,null,(function*(){try{if(!this.room.joinParams)return;jN(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(bb){}}))}reconnect(){return nb(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:wF,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:eF.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),gP.addSuccessEvent({key:521702,cost:DO()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(gP.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(bb){this._log.error(bb),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+=JO(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 vb({code:fb.API_CALL_TIMEOUT,message:DN({key:dw,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 xN({retryFunction:this.sendWaitForResponse,onError:e=>{let{retry:t}=e;this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(KU,t))},onRetrying:e=>{this._log.warn("".concat(t||i," timeout observed, retrying [").concat(e,"/").concat(r,"]"))},settings:{retries:r,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),NF.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(tk.MAIN),this.unbindAndCloseSocket(tk.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(e,"s")),this.stopKeepAliveTimeout=setTimeout((()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close(),this.off(eF.JOIN_ROOM_RESULT,t)}),1e3*e);let t=e=>{0===e.data.code&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(eF.JOIN_ROOM_RESULT,t))};this.on(eF.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(qU,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(KU):"DISCONNECTED"===e&&this.emit(XU))}};tb([NM({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())}})],OF.prototype,"connect",1);var PF=eb(ob()),MF=0,LF=!1,xF=new Set,VF=!1,UF=class{constructor(e){ib(this,"userId"),ib(this,"tinyId"),ib(this,"_sdpSemantics"),ib(this,"_isUplink"),ib(this,"_room"),ib(this,"_log"),ib(this,"_signalChannel"),ib(this,"_isErrorObserved",!1),ib(this,"_waitForPeerConnectionConnectedPromise"),ib(this,"_waitForPeerConnectionConnectedPromiseReject",null),ib(this,"_peerConnection",null),ib(this,"_emitter",new PF.default),ib(this,"_currentState","DISCONNECTED"),ib(this,"_isReconnecting",!1),ib(this,"_reconnectionCount",0),ib(this,"_reconnectionTimer",-1),ib(this,"_isFirstConnection",!0),ib(this,"_prevTime",-1),ib(this,"_localAddress"),ib(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=tP.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=DO())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,gP.addSuccessEvent({key:521705,cost:Math.min(DO()-this._prevTime,3e4)})):this._isReconnecting&&gP.addSuccessEvent({key:521706,cost:DO()-this._prevTime}),this._prevTime=-1}catch(sP){throw this._isFirstConnection?(this._isFirstConnection=!1,gP.addFailedEvent({key:521705,error:sP})):this._isReconnecting&&this._reconnectionCount>=3&&gP.addFailedEvent({key:521706,error:sP}),sP}}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(),xF.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 vb({code:fb.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Rk;let e=null;if(this._isUplink){if(!jP()||0===this._peerConnection.getSenders().length)return Rk;e=this._peerConnection.getSenders()[0].transport}else{if(!HP()||0===this._peerConnection.getReceivers().length)return Rk;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:Rk}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===Ck.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===Ck.FAILED||e.target.connectionState===Ck.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new vb({message:r,code:fb.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===Ck.CONNECTED||e.target.connectionState===Ck.COMPLETED)&&(this.logSelectedCandidate(),FN.logSuccessEvent({userId:this._room.userId,eventType:Nk.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(MF=0,LF=!1,VF=!0,xF.add(this)):xF.delete(this),VN.emit(ZO.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 nb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(MP(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 vb({code:fb.API_CALL_ABORTED,message:DN({key:Fw,data:"leave room"})})))},n=()=>{VN.off(ZO.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new vb({code:fb.API_CALL_TIMEOUT,message:"connection timeout"});MF+=1,(e=>MF>2&&!LF&&0===xF.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),LF=!0,this._emitter.emit("firewall-restriction")),t(e)}),Wk);VN.on(ZO.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(KU,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=kk()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new vb({code:this._isUplink?fb.UPLINK_RECONNECTION_FAILED:fb.DOWNLINK_RECONNECTION_FAILED,message:DN({key:this._isUplink?_w:pw})});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(KU,this.reconnect,this),-1)}on(e,t,i){this._emitter.on(e,t,i)}off(e,t,i){this._emitter.off(e,t,i)}getIsReconnecting(){return this._isReconnecting}get isH264(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}setOffer(e){var t;return null==(t=this._peerConnection)?void 0:t.setLocalDescription(e)}setAnswer(e){var t;return null==(t=this._peerConnection)?void 0:t.setRemoteDescription(e)}};tb([ix(521712,!1)],UF.prototype,"setOffer",1),tb([ix(521713,!1)],UF.prototype,"setAnswer",1);var FF=eb(pb()),BF=function(e){return FF.default.parse(e)},HF=function(e){return FF.default.write(e)};function jF(e){return Object.keys(e).filter((t=>e[t]))}var WF=class extends UF{constructor(e){super(XA(QA({},e),{isUplink:!1})),ib(this,"_flag",0),ib(this,"isRobot",!1),ib(this,"role","anchor"),ib(this,"remoteAudioTrack"),ib(this,"remoteVideoTrack"),ib(this,"remoteAuxiliaryTrack"),ib(this,"ssrc",{audio:0,video:0,auxiliary:0}),ib(this,"_isSDPExchanging",!1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Tx(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new mV(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new _V(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 LO(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===tk.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===pk?tk.MAIN:tk.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=tk.AUDIO;i.kind===tk.VIDEO&&(n=r===tk.MAIN?tk.VIDEO:tk.AUXILIARY);let o=this.remoteAudioTrack;n===tk.VIDEO?o=this.remoteVideoTrack:n===tk.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=BF(e);return t.media.forEach((e=>{e.type===tk.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),HF(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=BF(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),HF(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return nb(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===Ck.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===Ck.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(wb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(wb.message," ").concat(JSON.stringify(this.muteState))),new vb({code:fb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):wb}}))}unsubscribe(e){return nb(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=QA({},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(jF(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=dF,n=eF.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=uF,n=eF.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 vb({code:i.code,message:DN({key:hw,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return nb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(t),yield e.waitForPeerConnectionConnected()}catch(wk){throw e.closePeerConnection(!0),wk}}()}))}exchangeSDP(e){return nb(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:lF,commandDesc:"exchange sdp",data:r,responseCommand:eF.SUBSCRIBE_RESULT,timeout:Mk});if(!this._peerConnection){let e=new vb({code:fb.INVALID_OPERATION,message:DN({key:Vw})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(wk){throw this._isSDPExchanging=!1,wk}}))}createOffer(){return nb(this,null,(function*(){let e={voiceActivityDetection:!1};GP()&&this._sdpSemantics===Lk?(this._peerConnection.addTransceiver(tk.AUDIO,{direction:ik.RECVONLY}),this._peerConnection.addTransceiver(tk.VIDEO,{direction:ik.RECVONLY}),this._peerConnection.addTransceiver(tk.VIDEO,{direction:ik.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield kP();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=BF(e);return t.media.forEach((e=>{var t,i;if(e.type===tk.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(" ")}})),HF(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=BF(e);return t.media.forEach((e=>{e.type===tk.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),HF(t)}(t.sdp),this._sdpSemantics===Lk&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)}))}onSubscribeResult(e){return nb(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===Vk)throw new vb({code:fb.NOT_SUPPORTED_H264,message:DN({key:Ow})});try{if(0!==t)throw new vb({code:t,message:DN({key:mw,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(n)),yield this.setAnswer({type:r,sdp:n}),this.updateSSRC(n)}catch(o){throw this._log.error(o),o}}))}updateSSRC(e){try{BF(e).media.forEach((e=>{if(e.ssrcs)if(e.type===tk.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(pk)}));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(pk)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(mk)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(wk){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return nb(this,null,(function*(){if(!(rb(WF.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(wk){let t=mO(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),t)}}))}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}get audioReceiver(){var e;return(null==(e=this._peerConnection)?void 0:e.getReceivers()[0])||null}},GF=WF;tb([qL((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 vb({code:fb.API_CALL_ABORTED,message:DN({key:Fw,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],GF.prototype,"subscribe",1),tb([ix(521717,!1)],GF.prototype,"unsubscribe",1),tb([zL(UF.prototype.afterConnect),JL(UF.prototype.beforeConnect)],GF.prototype,"connect",1);var JF=GF,zF={voiceActivityDetection:!1},qF=class extends UF{constructor(e){super(XA(QA({},e),{isUplink:!0})),ib(this,"localMainAudioTrack",null),ib(this,"localMainVideoTrack",null),ib(this,"localAuxAudioTrack",null),ib(this,"localAuxVideoTrack",null),ib(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),ib(this,"_isPublishingAux",!1),ib(this,"_publishingLocalAudioTrack"),ib(this,"_publishingLocalVideoTrack"),ib(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}),ib(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&&(WP()?(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===tk.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 nb(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(),GP()?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 nb(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||tk.AUDIO,{direction:ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?tk.VIDEO:s||tk.VIDEO,{direction:ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||tk.VIDEO,{direction:ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||tk.VIDEO,{direction:ik.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:tk.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:tk.VIDEO,videoType:o?tk.AUXILIARY:tk.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:tk.VIDEO,videoType:tk.SMALL}),e.push(2))}yield t.setTransceiverDirection(ik.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 nb(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 nb(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(ik.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ik.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 nb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!WP())return i&&i.outMediaTrack&&!r&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):r&&r.outMediaTrack&&!i&&t.localMainAudioTrack?(yield t.removeTrack(r),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),void t.emitConnectionStateChangedEvent("DISCONNECTED",r));let e=r&&r===t.localAuxVideoTrack,n=null==r?void 0:r.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localAuxAudioTrack&&!t.localMainAudioTrack&&(yield o[0].replaceTrack(null),s.push(0))),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=XA(QA({},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=XA(QA({},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(ik.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 nb(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:aF,data:t,responseCommand:eF.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:cF,commandDesc:"unpublish",responseCommand:eF.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===fb.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),XP){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:IF,data:this._mediaSettings,responseCommand:eF.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return nb(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?tk.AUXILIARY:tk.MAIN," stream")),GP()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return nb(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===tk.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===ik.INACTIVE&&(yield this.setTransceiverDirection(ik.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return nb(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;WP()&&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===tk.VIDEO&&e instanceof lx&&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===xk||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=BF(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===tk.VIDEO)return!0;return!1}removeSender(e){let t=null;WP()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&fO(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return nb(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?tk.AUXILIARY:tk.MAIN," stream")),GP()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return nb(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===tk.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(ik.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return nb(this,null,(function*(){if(!nD)return;let i=!1,r=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let n=this._peerConnection.getTransceivers();if(t.forEach((t=>{n[t].direction!==e&&(n[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this.setOffer(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(ik.INACTIVE,"|").concat(ik.RECVONLY,"|").concat(ik.SENDONLY,")")))&&o++,t.includes(o)){if(e===ik.INACTIVE&&i.includes("a=".concat(ik.RECVONLY)))return r=!0,"a=".concat(e);if(e===ik.SENDONLY&&i.includes("a=".concat(ik.INACTIVE)))return r=!0,"a=".concat(ik.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:s}))}))}removeTrackBySender(e){return nb(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===tk.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===tk.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===tk.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return nb(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=GP()?e.kind===tk.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?tk.AUXILIARY:tk.MAIN," stream")),e.kind===tk.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===tk.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack)),!0}))}updateOffer(e,t){return nb(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(zF);nD&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this.setOffer(i);let r=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===tk.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:tF,data:n,responseCommand:eF.UPDATE_OFFER_RESULT,timeout:Pk,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(kb){throw this._log.error(kb),kb}}))}setBandwidth(e){return nb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!YP())return o?r===tk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(GP()){let t=0;r===tk.VIDEO&&(t=n===tk.SMALL?2:n===tk.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===tk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";nD&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===tk.SMALL?n=1:i===tk.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 nD&&(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 nb(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(bb){throw this.closePeerConnection(!0),this.uninstallEvents(),bb}}))}exchangeSDP(){return nb(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(bb){throw bb}}))}createOffer(){return nb(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(zF);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(bb){throw bb}}))}doExchangeSDP(){let e={command:sF,responseCommand:eF.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof px||this.localAuxVideoTrack instanceof px,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=BF(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),HF(r)}acceptAnswer(e){return nb(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?tk.AUXILIARY:tk.BIG;s=yield this.setBandwidth({bandwidth:e,type:tk.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:tk.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:tk.VIDEO,videoType:tk.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this.setAnswer(a),this._log.debug("accepted answer: ".concat(s))}catch(HB){throw this._log.error("failed to accept remote answer ".concat(HB)),HB}}))}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(oF,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return nb(this,null,(function*(){if(!(rb(qF.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:cF,responseCommand:eF.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(wk){let t=mO(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)&&VN.emit(ZO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{BF(e).media.forEach(((e,t)=>{if(e.type===tk.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===xk&&e.ssrcGroups)return void e.ssrcGroups.forEach(((e,t)=>{let i=Number(e.ssrcs.split(" ")[0]);0===t?this.ssrc.video=i:1===t&&(this.ssrc.small=i)}));let i=e.ssrcs&&e.ssrcs[0];if(!i)return;switch(t){case 1:this.ssrc.video=Number(i.id);break;case 2:this.ssrc.small=Number(i.id);break;case 3:this.ssrc.auxiliary=Number(i.id)}}}))}catch(wk){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===tk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===tk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===tk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===tk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Vk?(this._log.error(Hw.NOT_SUPPORTED_H264ENCODE),new vb({code:fb.NOT_SUPPORTED_H264,message:DN({key:Nw})})):new vb({code:fb.UNKNOWN,message:DN({key:Lw,data:{signalResponse:eF.PUBLISH_RESULT,code:e,message:t}})})}},KF=qF;tb([qL((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 vb({code:fb.API_CALL_ABORTED,message:DN({key:Fw,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],KF.prototype,"publish",1),tb([ix(521715,!1)],KF.prototype,"unpublish",1),tb([zL(UF.prototype.afterConnect),JL(UF.prototype.beforeConnect)],KF.prototype,"connect",1);var YF=KF,QF=class{constructor(e,t){this.room=e,ib(this,"_log"),ib(this,"_prevReportTime",0),ib(this,"_prevReport",{}),ib(this,"_prevStats",null),ib(this,"_prevEncoderImplementation",""),ib(this,"_prevAuxEncoderImpl",""),ib(this,"_prevQualityLimitationReason",""),ib(this,"_prevAuxQualityLimitationReason",""),ib(this,"_prevDecoderImplementationMap",new Map),ib(this,"totalBytesSent",0),ib(this,"totalBytesReceived",0),ib(this,"_spcStats",null),this._log=t}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return nb(this,null,(function*(){var t;let i={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},r=e.getPeerConnection(),n=e.getSSRC();if(r)try{if((this._spcStats||(yield r.getStats())).forEach((t=>{var r,o,s;let a,c;if("outbound-rtp"===t.type)if((t.mediaType||t.kind)===tk.VIDEO){if(t.ssrc===n.video?(a=tk.VIDEO,c=e.localMainVideoTrack):t.ssrc===n.small?a=tk.SMALL:t.ssrc===n.auxiliary&&(c=e.localAuxVideoTrack,a=tk.AUXILIARY),!a)return;if(i[a].bytesSent=t.bytesSent,i[a].packetsSent=t.packetsSent,i[a].framesEncoded=t.framesEncoded,gO(t.keyFramesEncoded)||(i[a].keyFramesEncoded=t.keyFramesEncoded),gO(t.nackCount)||(i[a].nackCount=t.nackCount),gO(t.pliCount)||(i[a].pliCount=t.pliCount),gO(t.retransmittedPacketsSent)||(i[a].retransmittedPacketsSent=t.retransmittedPacketsSent),gO(t.totalEncodeTime)||(i[a].totalEncodeTime=t.totalEncodeTime),gO(t.totalPacketSendDelay)||(i[a].totalPacketSendDelay=t.totalPacketSendDelay),!gO(t.encoderImplementation)&&(a===tk.VIDEO&&this._prevEncoderImplementation!==t.encoderImplementation||a===tk.AUXILIARY&&this._prevAuxEncoderImpl!==t.encoderImplementation)){let i=2,r=this._prevEncoderImplementation;a===tk.AUXILIARY&&(i=7,r=this._prevAuxEncoderImpl),VN.emit("262",{userId:e.userId,streamType:i,prevImplementation:r,implementation:t.encoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientEncoder}),this[a===tk.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=t.encoderImplementation,this._log.info("".concat(a===tk.AUXILIARY?"aux ":"","encoderImplementation change to ").concat(t.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(t.powerEfficientEncoder))}t.ssrc===n.video?!gO(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),VN.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:null==(r=e.localMainVideoTrack)?void 0:r.isQosClearFirst}),this._prevQualityLimitationReason=t.qualityLimitationReason):t.ssrc===n.auxiliary&&!gO(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),VN.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(o=e.localAuxVideoTrack)?void 0:o.isQosClearFirst}),this._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else i.audio.bytesSent=t.bytesSent,i.audio.packetsSent=t.packetsSent;else"candidate-pair"===t.type?MP(t)&&(this.totalBytesSent=t.bytesSent,yO(t.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*t.currentRoundTripTime))):"media-source"===t.type&&(t.kind===tk.AUDIO?(i.audio.audioLevel=t.audioLevel||0,i.audio.totalAudioEnergy=t.totalAudioEnergy||0,t.echoReturnLoss,t.totalSamplesDuration&&(i.audio.totalSamplesDuration=t.totalSamplesDuration)):t.kind===tk.VIDEO&&(t.trackIdentifier===e.getVideoTrackId(tk.VIDEO)?i.video.fpsCapture=t.framesPerSecond:t.trackIdentifier===e.getVideoTrackId(tk.AUXILIARY)?i.auxiliary.fpsCapture=t.framesPerSecond:i.small.fpsCapture=t.framesPerSecond));if(!gO(t.audioLevel)&&(null==(s=e.localMainAudioTrack)?void 0:s.mediaTrack)&&t.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(i.audio.audioLevel=t.audioLevel||0),!gO(t.frameWidth)){let r=tk.SMALL;t.trackIdentifier===e.getVideoTrackId(tk.VIDEO)||t.ssrc===n.video?r=tk.VIDEO:(t.trackIdentifier===e.getVideoTrackId(tk.AUXILIARY)||t.ssrc===n.auxiliary)&&(r=tk.AUXILIARY),i[r].frameWidth=t.frameWidth,i[r].frameHeight=t.frameHeight,i[r].framesSent=t.framesSent}})),e.localMainAudioTrack){let t=e.localMainAudioTrack.getInternalAudioLevel();i.audio.micAudioLevel=t,0===i.audio.audioLevel&&(i.audio.audioLevel=t)}this.totalBytesSent||(this.totalBytesSent+=i.audio.bytesSent+i.video.bytesSent+i.auxiliary.bytesSent),Object.keys(i).forEach((t=>{t===tk.AUDIO?(e.localMainAudioTrack&&(e.localMainAudioTrack.stat=i[t]),e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=i[t])):t===tk.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=i[t]):t===tk.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=i[t])}))}catch(wb){this._log.warn("failed to getStats on sender connection ".concat(wb))}return 0===i.rtt&&(i.rtt=(null==(t=this.room.networkQuality)?void 0:t.uplinkRTT)||0),i}))}getReceiverStats(e){return nb(this,null,(function*(){var t;let i={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}},r=e.getPeerConnection();if(r)try{let{ssrc:t}=e,{muteState:n,subscribeState:o}=e;(this._spcStats||(yield r.getStats())).forEach((r=>{if("inbound-rtp"===r.type){let s=(r.mediaType||r.kind)===tk.AUDIO;if(s){if(r.ssrc!==t.audio||!n.hasAudio)return;i.audio.packetsReceived=r.packetsReceived,i.audio.bytesReceived=r.bytesReceived,i.audio.packetsLost=r.packetsLost,r.insertedSamplesForDeceleration&&(i.audio.insertedSamplesForDeceleration=r.insertedSamplesForDeceleration),r.removedSamplesForAcceleration&&(i.audio.removedSamplesForAcceleration=r.removedSamplesForAcceleration),r.totalSamplesDuration&&(i.audio.totalSamplesDuration=r.totalSamplesDuration),r.totalSamplesReceived&&(i.audio.totalSamplesReceived=r.totalSamplesReceived),r.concealedSamples&&(i.audio.concealedSamples=r.concealedSamples);let{remoteAudioTrack:o}=e;o.stat.packetsReceived=r.packetsReceived,o.stat.bytesReceived=r.bytesReceived,o.stat.packetsLost=r.packetsLost,i.audio.p2pDelay=o.stat.end2EndDelay,i.hasAudio=!0}else{if(nD&&0===r.bytesReceived)return;let s;r.ssrc===t.video&&n.hasVideo&&(i.video.packetsReceived=r.packetsReceived,i.video.bytesReceived=r.bytesReceived,i.video.packetsLost=r.packetsLost,i.video.framesReceived=r.framesReceived,i.video.framesDecoded=r.framesDecoded,i.video.fpsDecoded=r.framesPerSecond,i.hasVideo=!0,s=e.remoteVideoTrack,n.hasSmall&&o.smallVideo&&(i.isSmallSubscribed=!0),r.decoderImplementation&&(!this._prevDecoderImplementationMap.has(i.userId)||this._prevDecoderImplementationMap.get(i.userId)!==r.decoderImplementation)&&(this._log.info("".concat(i.userId," decoderImplementation change to ").concat(r.decoderImplementation," HWDecoder: ").concat(r.powerEfficientDecoder)),VN.emit("262",{userId:this.room.userId,remoteUserId:i.userId,prevImplementation:this._prevDecoderImplementationMap.get(i.userId),implementation:r.decoderImplementation,codec:e.videoCodec,isHWCodec:r.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(i.userId,r.decoderImplementation))),r.ssrc===t.auxiliary&&n.hasAuxiliary&&(i.auxiliary.packetsReceived=r.packetsReceived,i.auxiliary.bytesReceived=r.bytesReceived,i.auxiliary.packetsLost=r.packetsLost,i.auxiliary.framesReceived=r.framesReceived,i.auxiliary.framesDecoded=r.framesDecoded,i.auxiliary.fpsDecoded=r.framesPerSecond,s=e.remoteAuxiliaryTrack,i.hasAuxiliary=!0),s&&(s.stat.packetsReceived=r.packetsReceived,s.stat.bytesReceived=r.bytesReceived,s.stat.packetsLost=r.packetsLost,s.stat.framesReceived=r.framesReceived,s.stat.framesDecoded=r.framesDecoded,r.jitterBufferDelay&&(s.stat.jitterBufferDelay=Math.floor(r.jitterBufferDelay/r.jitterBufferEmittedCount*1e3)))}r.jitterBufferDelay&&(s?(i.audio.totalJitter=r.jitterBufferDelay,i.audio.totalJitterCount=r.jitterBufferEmittedCount):r.ssrc===t.video&&n.hasVideo?(i.video.totalJitter=r.jitterBufferDelay,i.video.totalJitterCount=r.jitterBufferEmittedCount):r.ssrc===t.auxiliary&&n.hasAuxiliary&&(i.auxiliary.totalJitter=r.jitterBufferDelay,i.auxiliary.totalJitterCount=r.jitterBufferEmittedCount))}else"candidate-pair"===r.type&&MP(r)&&(this.totalBytesReceived=r.bytesReceived,yO(r.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*r.currentRoundTripTime)));gO(r.frameWidth)||((r.trackIdentifier===e.getMainStreamVideoTrackId()||r.ssrc===t.video)&&(i.video.frameWidth=r.frameWidth,i.video.frameHeight=r.frameHeight,e.remoteVideoTrack.stat.frameWidth=r.frameWidth,e.remoteVideoTrack.stat.frameHeight=r.frameHeight),(r.trackIdentifier===e.getAuxStreamVideoTrackId()||r.ssrc===t.auxiliary)&&(i.auxiliary.frameWidth=r.frameWidth,i.auxiliary.frameHeight=r.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=r.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=r.frameHeight)),!gO(r.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&r.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(i.audio.audioLevel=r.audioLevel||0,i.audio.totalAudioEnergy=r.totalAudioEnergy||0)})),0===i.audio.audioLevel&&e.muteState.audioAvailable&&(i.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=i.audio.bytesReceived+i.video.bytesReceived+i.auxiliary.bytesReceived)}catch(n){this._log.warn("failed to getStats on receiver connection ".concat(n))}return 0===i.rtt&&(i.rtt=(null==(t=this.room.networkQuality)?void 0:t.uplinkRTT)||0),i}))}getStats(e,t){return nb(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=DO(),n=yield e.getStats(),o=DO();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(FL(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(!FL(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*lw,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*lw),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(_k)),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(fk)),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),MD&&115===$D()&&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),gO(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),gO(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),gO(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),gO(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),gO(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/o)),gO(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(FL(e.msg_audio_status)||FL(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 nb(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}},XF=eb(ob());function $F(e){return new Promise((t=>nb(this,null,(function*(){let i=setTimeout((()=>{t({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})}),1e4),r=Date.now(),n="https://".concat(e,"/?t=").concat(r);try{yield fetch(n)}catch(wb){}clearTimeout(i);let o=function(e){let t={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let i=performance.getEntriesByType("resource").reverse();for(let r of i)if(r.name===e){let e=Math.round(r.duration),i=Math.max(Math.round(r.domainLookupStart-r.startTime),0),n=r.redirectStart>0?Math.max(Math.round(r.redirectEnd-r.redirectStart),0):0,o=r.fetchStart>0?Math.max(Math.round(r.domainLookupStart-r.fetchStart),0):0,s=Math.round(r.domainLookupEnd-r.domainLookupStart),a=Math.round(r.requestStart-r.secureConnectionStart),c=Math.round(r.secureConnectionStart-r.connectStart),l=Math.round(r.responseStart-r.requestStart),d=Math.round(r.responseEnd-(r.responseStart||r.startTime));t=XA(QA({},t),{totalCost:e,local:i,redirect:n,httpCache:o,dns:s,tcp:c,tls:a,request:l,response:d});break}}catch(i){}return t}(n);0===o.totalCost&&(o.totalCost=Date.now()-r),t(o)}))))}var ZF=class extends XF.default{constructor(e){let{signalChannel:t,room:i}=e;super(),ib(this,"_room"),ib(this,"_signalChannel"),ib(this,"_log"),ib(this,"uplinkRTT",0),ib(this,"uplinkLoss",0),ib(this,"downlinkRTT",0),ib(this,"downlinkLoss",0),ib(this,"pingResults",{}),ib(this,"_downlinkPrevStatMap",new Map),ib(this,"_downlinkLossAndRTTMap",new Map),ib(this,"_interval",-1),ib(this,"_uplinkNetworkQuality",0),ib(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=tP.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:i}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(t,", loss: ").concat(i," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(eF.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(qU,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,i;if(0!==e.data.code)return;let r=e.data.data;if(r.delay&&this.updateDelay(r.delay),this._room.signalChannel&&r.wsRtt&&(this._room.signalChannel.rtt=r.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);let n=null==(i=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:i.getPeerConnection();if(n&&this.isPeerConnectionDisconnected(n))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);let o=r.expectAudPkg+r.expectVidPkg,s=r.recvAudPkg+r.recvVidPkg,a=o-s;0===o&&0===s||(this.uplinkLoss=a<=0?0:Math.round(a/o*100),this.uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return nb(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)===Ck.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let n=0;n<t.length;n++){let e=t[n].getPeerConnection();if(!e)return;let{rtt:i,totalPacketsLost:r,totalPacketsReceived:o}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o});continue}let s=0,a=this._downlinkPrevStatMap.get(e),c=r-a.totalPacketsLost,l=o-a.totalPacketsReceived;s=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:s,userId:t[n].getUserId(),audioDelay:t[n].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[n].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach((e=>{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:i,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=i,this.downlinkLoss=r,this.downlinkNetworkQuality=this.getNetworkQuality(r,i)}))}getStat(e){return nb(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!HP())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&&yO(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===tk.AUDIO||e.mediaType===tk.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return 0===t.rtt&&(t.rtt=this.uplinkRTT),t}catch(r){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){"DISCONNECTED"===e.state?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):"CONNECTED"===e.state&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(e){let{state:t}=e;"DISCONNECTED"===t?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):"CONNECTED"===t&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==Ck.DISCONNECTED&&e.connectionState!==Ck.FAILED&&e.connectionState!==Ck.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=RM.run(tw,(()=>{var e;this.handleDownlinkNetworkQuality();let t=[...this._downlinkLossAndRTTMap.values()];VN.emit(ZO.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:t});let i=null==(e=this._room.scheduleResult.config)?void 0:e.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};i&&(r=XA(QA({},r),{pingResults:this.uplinkRTT>i.rttThreshold||this.downlinkRTT>i.rttThreshold?this.pingResults:{}})),this.emit(ZF.EVENT_NETWORK_QUALITY,r);let n=Date.now();if(i&&(this.uplinkRTT>i.rttThreshold||this.downlinkRTT>i.rttThreshold)&&n-ZF.lastPingTime>1e3*i.interval){ZF.lastPingTime=Date.now();let e=i.domain.map((e=>$F(e).then((t=>({domain:e,cost:t.totalCost})))));Promise.all(e).then((e=>{this.pingResults.isPoorNetwork=e.some((e=>e.cost>700)),this.pingResults.timestamp=n,this.pingResults.data=e,e.forEach((e=>{kvStatManager.addSuccessEvent({key:KV_REPORT_KEY_NETWORK.PING,cost:e.cost})})),this._log.warn("All ping results: ".concat(JSON.stringify(e)))})).catch((e=>{this._log.warn("Error during pinging domains: ".concat(e))}))}}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.debug("stopped"),-1!==this._interval&&(RM.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})}}))}},eB=ZF;ib(eB,"EVENT_NETWORK_QUALITY","0"),ib(eB,"lastPingTime",0);var tB=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.isDestroyed=!1,this._frameWorkType=e.frameWorkType||30,this._component=e.component||0,this.connectionType=e.connectionType||1,this._language=e.language||0,this._room=e.room,this._keyPrefix="key_point",this._log=tP.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&fO(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 CO(o)?o.catch((e=>tP.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(wk){tP.error("".concat(t.name,"() error observed ").concat(wk))}}}({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:Cb,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,yN().then((e=>{this._basicInfo.string_os_version=AN(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),VN.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(ZO.JOIN_START,this.handleJoinStart).addEvent(ZO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(ZO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(ZO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(ZO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(ZO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(ZO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(ZO.JOIN_FAILED,this.handleJoinFailed).addEvent(ZO.LEAVE_START,this.handleLeaveStart).addEvent(ZO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(ZO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(ZO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(ZO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(ZO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(ZO.PUBLISH_START,this.handlePublishStart).addEvent(ZO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(ZO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(ZO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(ZO.PLAY_TRACK_START,this.handlePlayStart).addEvent(ZO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(ZO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!RO(t)||!this.hitTest(t.room)||"PLAYING"===i&&(r===tk.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(ZO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(ZO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(ZO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(ZO.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(ZO.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)=>VN.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),RM.clearTask(this._intervalId),0===this._pathJoinRoom.uint64_start_time&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(e){this.hitTest(e.room)&&(0===this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_start_time=Date.now()),e.params&&(gO(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),gO(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),gO(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 vb?Number(i.getExtraCode()||i.getCode()):fb.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:XA(QA({},rB),{msg_user_info:new nB({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 nB({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(!RO(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(!RO(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/lw*100)>0&&(this._localStreamStat.totalAudioLevel+=e/lw,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*KA(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/lw*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/lw,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 vb?i.getExtraCode()||i.getCode():fb.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&ok))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&ck))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&ak))>=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,tk.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,tk.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,iB);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>iB&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+iB):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>iB&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+iB):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>iB&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+iB)}getReportData(){this._basicInfo.uint32_networkType=nO();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new nB({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:VO(this._signalInfo.relayIp),uint32_client_ip:VO(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*KA(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:VO(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return YO(e),e}report(){return nb(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(sP){this._log.warn(sP)}finally{this.isDestroyed&&(this._room=null)}}))}upload(e){return nb(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=yield cw(e),r=i instanceof ArrayBuffer,n="".concat(ZN(t,Gb.KEY_POINT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i));let s=[this.uploadKVStat(gP),this.uploadKVStat(fP)];o||s.push(aw({url:n,body:i})),yield Promise.all(s)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return nb(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=XA(QA({},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 cw(t),r="".concat(ZN(+this._room.sdkAppId,Gb.KV_STAT),"&gzip=").concat(+(i instanceof ArrayBuffer)),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(r,i)),n||aw({url:r,body:i})}))}};tb([NM({settings:{timeout:500,retries:3}})],tB.prototype,"upload",1);var iB=5e3,rB={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},nB=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},oB=tB,sB=class{constructor(){ib(this,"_startTime"),ib(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=DO())}stop(){0===this._endTime&&(this._endTime=DO())}getDuration(){return 0===this._endTime?DO()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},aB=class{constructor(e){ib(this,"_room",null),ib(this,"_durationMap"),ib(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(ZO.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(ZO.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(ZO.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"),tk.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_","main"),tk.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_","auxiliary"),tk.VIDEO);let s=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);!s||(!i.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,tk.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,tk.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,tk.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>VN.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>VN.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 sB,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,tk.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let e=new sB,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,tk.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,tk.AUDIO),this.stopDurationItem(o,tk.VIDEO)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new sB,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===tk.AUDIO?[n]:[],video:t===tk.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()}},cB=class{constructor(e){ib(this,"_room"),ib(this,"_renderFreezeMap",new Map),ib(this,"_isVideoPlayingEventFiredMap",new Map),ib(this,"_dataFreezeMap",new Map),ib(this,"_monitorFreezeData",new Map),ib(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(ZO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(ZO.PLAY_TRACK_START,this.onPlayTrackStart).set(ZO.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(ZO.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(ZO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(RO(t)&&this.hitTest(t.room)&&n===tk.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===tk.MUTE?this.onVideoTrackMuted(t):r===tk.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(ZO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>VN.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>VN.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 sB;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>Fk?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 nb(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=DO();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=DO();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!RO(t)||!this.hitTest(t.room)||t.kind!==tk.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()<Fk&&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=DO()-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()}},lB=eb(ob(),1),dB=[1,0,0,0,1,1,0,1],uB=class extends Ix{constructor(e,t){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:t}),e instanceof hV)try{this.setTexBuffer(dB)}catch(wk){e.destroy(new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(wk.message||wk)}))}}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)}},hB=class{constructor(e,t){this.node=e,this.layout=t,ib(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}},pB=class extends Ix{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),ib(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new hB(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 hV&&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},QA({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 hV))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(r){}}))}},mB=class extends lV{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log}),ib(this,"_bgTexture"),ib(this,"_waterMarkTexture"),ib(this,"_lastMaskTexture"),ib(this,"_lastMaskFbo"),ib(this,"_textureValid",!1),ib(this,"_selfieTextureValid",!1),ib(this,"_selfieSegmentation"),ib(this,"wasm"),ib(this,"_prePrograme"),ib(this,"_segmentationMask"),ib(this,"_weixin",!1),t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(t)}catch(kb){e.log.error(kb),e.destroy(new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(kb.message||kb)}))}}init(e){var t,i;let r=e.Wasm,n=this.context.ctx;if(this.wasm=new r.AllIn1(n),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:i,width:r,height:n}=e.waterMark;this.wasm.setWaterMark(t,i,r,n)}if(e.beautyParams){let{beauty:r,brightness:n,ruddy:o}=e.beautyParams;this.wasm.setBeauty(r,n,o,null==(t=this.context._canvas)?void 0:t.width,null==(i=this.context._canvas)?void 0:i.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.uniform1i(n.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(n.uniform1i(n.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(n.uniform1i(n.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),n.uniform1i(n.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(n.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\nuniform sampler2D u_texture;\nuniform sampler2D mask;\n\nin vec2 v_texCoord;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);\n}"),t=this.context.createShader(n.VERTEX_SHADER,"#version 300 es\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_texCoord;\nvoid main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n v_texCoord = a_texCoord;\n}");this._prePrograme=this.context.createProgram(t,e),n.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.uniform1i(n.getUniformLocation(this._prePrograme,"mask"),1)}}onPredict(e){var t;let i=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():null==this||this._selfieSegmentation.bindTexture(),i.activeTexture(i.TEXTURE1),null==(t=this._selfieSegmentation)||t.bindTexture2d(e),i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,this._bgTexture||null),i.activeTexture(i.TEXTURE3),i.bindTexture(i.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),i.drawArrays(i.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){var t,i,r,n;let o=this.context.ctx,{image:s}=this;this.tryVideoFrameCallback(s);let{videoWidth:a,videoHeight:c}=s;s.width=a,s.height=c;let l=!1;if(this.totalFrames)this._weixin?this.useTexture():null==(t=this._selfieSegmentation)||t.bindTexture(),l=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),l=this._textureValid,this._textureValid=!0}return this.width===a&&this.height===c&&l?o.texSubImage2D(o.TEXTURE_2D,0,0,0,o.RGBA,o.UNSIGNED_BYTE,s):(this.resize(a,c),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,s)),this._weixin&&(o.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(o.activeTexture(o.TEXTURE1),null==(i=this._selfieSegmentation)||i.bindTexture2d(this._segmentationMask),o.bindFramebuffer(o.FRAMEBUFFER,this._lastMaskFbo||null)),o.drawArrays(o.TRIANGLE_STRIP,0,4),null==(r=this._selfieSegmentation)||r.bindTexture(),this._segmentationMask?o.copyTexSubImage2D(o.TEXTURE_2D,0,0,0,0,0,a,c):o.copyTexImage2D(o.TEXTURE_2D,0,o.RGBA,0,0,a,c,0)),null==(n=this._selfieSegmentation)||n.send(a,c),this.totalFrames||(o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this._bgTexture||null),o.activeTexture(o.TEXTURE3),o.bindTexture(o.TEXTURE_2D,this._waterMarkTexture||null),o.drawArrays(o.TRIANGLE_STRIP,0,4)),!1}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&t.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&t.deleteProgram(this._prePrograme),null==(e=this.wasm)||e.close()}},_B=class extends lB.EventEmitter{constructor(e){super(),this.room=e,ib(this,"videoContext"),ib(this,"_glVideoContext"),ib(this,"_2dVideoContext"),ib(this,"destination"),ib(this,"smallVideoContext"),ib(this,"smallDestination"),ib(this,"smallTrackSource"),ib(this,"smallImageSource"),ib(this,"_isMirror",!1),ib(this,"cameraTrack"),ib(this,"cameraNode"),ib(this,"mirrorNode"),ib(this,"mixNode"),ib(this,"screenTrack"),ib(this,"screenNode"),ib(this,"selfModel",!1),ib(this,"blurRadius",3),ib(this,"arTrack"),ib(this,"Wasm"),ib(this,"waterMarkNode"),ib(this,"_waterMarkOption"),ib(this,"watermarkImageList",[]),ib(this,"_beautyParams"),ib(this,"isUsingArTrack",!1),ib(this,"_isMixScreen",!1),ib(this,"_virtualBackground"),ib(this,"_virtualBackgroundAbortCallback"),ib(this,"virtualBackgroundInstance"),ib(this,"_bgAssetPath"),ib(this,"log",tP.createLogger({id:"vm"})),ib(this,"_checkId",0),ib(this,"_use2d",!1),ib(this,"_autoSwitchRenderMode",!0),ib(this,"_selfieSegmentation"),ib(this,"encodePipeline",[]),ib(this,"decodePipeline",[]),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new pV({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 pV({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new hV({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on("unavailable",(e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),null==(t=this._virtualBackgroundAbortCallback)||t.call(this,e),this.update()}))}catch(bb){this.emit("error",bb)}}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=RM.run(rw,(()=>{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(),RM.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(oN||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?gP.addFailedEvent({key:t,error:e}):gP.addSuccessEvent({key:t})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else{if(!t)return!0;if(!this._use2d)return!0;this.clear()}}else{if(this._glVideoContext=new hV({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return null==(e=this.smallDestination)?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return null==(e=this.cameraTrack)?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var t;try{let i=this.cameraTrack,{small:r,settings:n,player:o}=i;r?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new sV(this.smallVideoContext,r,this.log)),this.smallVideoContext.frameRate=r.frameRate,this.smallDestination.resolution=r,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),oN&&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(kb){this.log.error("set main output failed",kb)}}update(){return nb(this,null,(function*(){var e,t;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:i,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),16===lN?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof lV?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof lV?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(i.width,i.height)):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new oV(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new mB(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=r.frameRate,this._use2d){let i=this.cameraNode;i.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new uB(this.videoContext,this.log)),i=i.connect(this.mirrorNode),i.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new pB(this.videoContext,this.log),i.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),null==(e=this.waterMarkNode)||e.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),null==(t=this.screenNode)||t.connect(this.mixNode,{zIndex:0}),i=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))),i.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext._canvas)}))}changeInput(e){var t,i,r,n;if(e instanceof px)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof lx)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof mV){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);let t=e.mediaTrack;return e.setOutputMediaStreamTrack(t)}this.log.warn("change unknown input",null==(n=e.mediaTrack)?void 0:n.label)}configPipeline(e){}removeInput(e){var t;e instanceof px?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof lx?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof mV&&e.source&&e.source.context.destroy()}setCameraTrack(e){return nb(this,null,(function*(){this.cameraTrack=e,this.update()}))}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return nb(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 vb({code:fb.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)})),qO(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 nb(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return nb(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return nb(this,null,(function*(){let t;try{t=yield qO((null==e?void 0:e.imageElement)||e.imageUrl)}catch(c){throw new vb({code:fb.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 nb(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 nb(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 nb(this,null,(function*(){if(e){if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,"image"===e.type?this._virtualBackground=yield qO(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}else delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;if(this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat((null==e?void 0:e.type)||"",", ").concat(this.blurRadius||"")),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new vb({code:fb.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})}))}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return nb(this,null,(function*(){var e;null==(e=this.cameraTrack)||!e.mediaTrack||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))}))}disableAr(){var e;this.isUsingArTrack=!1,null==(e=this.arTrack)||e.stop(),this.arTrack=void 0,this.update()}clear(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(e){let{processor:t,type:i}=e;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t)}addDecodeProcessor(e){let{processor:t,type:i}=e;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t)}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}},fB=0,gB=class extends yM{constructor(e){super("room"),this.seq=++fB,this.role="anchor",this.joinParams=null,this.localTracks=new Set,this.enableAutoPlayDialog=!0,this.autoReceiveAudio=!0,this.autoReceiveVideo=!0,this.checkSystemResult={result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0}},this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this._isUsingCachedSchedule=!1,this._log=tP.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this.isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,TO(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),TO(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),TO(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new oB({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new aB({room:this}),this.badCaseDetector=new cB({room:this}),this.audioManager=new fx(this),this.videoManager=new _B(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(4&e.mediaType)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(2&e.mediaType)return e;return null}getLogger(){return this._log}get isJoining(){return"joining"===this.state.toString()}get isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return nb(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return nb(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return nb(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(vO(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(hO(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?(JN([o,o]),Mb("https://".concat(o))):(r&&Mb(r),n&&JN(n))}VN.once(ZO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:GN.main,sched_back_domain:GN.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return nb(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return nb(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 nb(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 vb({code:fb.INVALID_OPERATION,message:DN({key:kw,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Hw.INVALID_DESTROY),new vb({code:fb.INVALID_OPERATION,message:DN({key:Iw})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,VN.emit(ZO.ROOM_DESTROY,{room:this})}schedule(e,t){return nb(this,null,(function*(){var i,r;let n=DO();try{let{isCached:o,result:s,detailCost:a}=yield WN({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Cb,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(WO(s,{keysToExclude:["username","credential"]}))),o&&VN.once(ZO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=QA(QA({},this.scheduleResult),s),yO(null==(i=s.config)?void 0:i.retryCount)&&bk(s.config.retryCount),vO(null==(r=s.config)?void 0:r.loggerDomain)&&Mb(s.config.loggerDomain),VN.emit(ZO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:a}),gP.addSuccessEvent({key:521700,cost:DO()-n,split:50})}catch(o){throw gP.addFailedEvent({key:521700,error:o}),o}}))}},vB=eb(ob(),1),yB=Symbol("instance"),TB=Symbol("cacheResult"),SB=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,AB.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},EB=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var IB=new Map;function RB(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=IB.get(r)||[];IB.has(r)||IB.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=bB.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return r[TB];r.state instanceof SB&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;if(Array.isArray(e)?0==e.length?r.state instanceof SB&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new EB(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 EB(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 SB(d,t,s);AB.call(r,u);let h=e=>{var n;return r[TB]=e,u.aborted||(AB.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[TB])),e},p=e=>{let t=e instanceof Error?e.message:String(e);if(AB.call(r,d,e),!i.fail){if(i.ignoreError)return e;throw e}i.fail.call(this,new EB(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 CB="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 AB(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(bB.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var bB=class extends vB.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=bB.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[yB];r?this.name=r.name+"-"+r.count++:i[yB]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=IB.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);IB.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=bB.instances.get(e),t||bB.instances.set(e,t=new bB(e,void 0,Object.create(bB.prototype)))):(t=bB.instances2.get(e),t||bB.instances2.set(e,t=new bB(e.constructor.name,void 0,Object.create(bB.prototype)))),t}static getState(e){var t;return null===(t=bB.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};CB(bB.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){AB.call(this,e)}};bB.STATECHANGED="stateChanged",bB.UPDATEAFSM="updateAFSM",bB.INIT="[*]",bB.ON="on",bB.OFF="off",bB.instances=new Map,bB.instances2=new WeakMap;var kB=eb(ob()),wB=eb(pb());function DB(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 NB=(e,t)=>nb(void 0,null,(function*(){var i;let r=BF(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=[...DB(s)].filter((e=>c.includes(e.codec.toLocaleLowerCase()))),n.video.decoders=(yield function(){return nb(this,null,(function*(){let e=new RTCPeerConnection;e.addTransceiver(tk.VIDEO,{direction:tk.TRANSCEIVER_DIRECTION_RECVONLY});let t=yield e.createOffer();if(!t.sdp)return[];let i=DB(BF(t.sdp).media[0]);return e.close(),i}))}()).filter((e=>["h264","vp8"].includes(e.codec.toLocaleLowerCase()))),n})),OB=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,o=BF(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:tk.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:tk.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(PB({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),n&&s.media.push(o.media.find((e=>"dc"===e.mid))),HF(s)},PB=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:tk.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:tk.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(o)(i.video.decoders||i.video.codecs).forEach((e=>{MB(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];MB(s,t)}return s},MB=(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 LB=(e,t,i)=>{let r=wB.default.parse(e);return r.media.forEach(((e,n)=>{var o;(e.type===tk.AUDIO||e.type===tk.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===tk.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===tk.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===tk.VIDEO&&(n<4?(e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach((t=>MB(e,t)))):i&&(e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],(i.video.decoders||i.video.codecs).forEach((t=>MB(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")})),wB.default.write(r)},xB=eb(ob()),VB=class extends xB.EventEmitter{constructor(e){super(),this.room=e,ib(this,"mainFpsHealth",1),ib(this,"mainBitrateHealth",1),ib(this,"badMainBitrateHealthCount",0),ib(this,"lastEmitBadHealthTime",0),ib(this,"log"),!eD&&ZD&&VN.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(){VN.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};ib(VB,"EVENT_BAD_HEALTH","bad_health");var UB=VB;function FB(e){let{seiMessageList:t,isAudio:i}=e;return new TransformStream({transform(e,r){let n=e;i?audioEncodePipeline.forEach((e=>{n=e({frame:n})})):videoEncodePipeline.forEach((e=>{n=e({frame:n,seiMessageList:t})})),r.enqueue(n)}})}function BB(e,t){return new TransformStream({transform(i,r){let n=i;videoDecodePipeline.forEach((i=>{n=i({frame:n,onSEI:i=>{i.forEach((i=>{self.postMessage({type:"sei",seiPayloadType:i.seiPayloadType,data:i.seiPayload.buffer,userId:e,streamType:t})}))}})})),r.enqueue(n)}})}var HB,jB=((HB=jB||{}).TRACK="track",HB.DATA_CHANNEL_MESSAGE="data_channel_msg",HB[HB.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",HB[HB.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",HB.RECONNECTED="spc-reconnected",HB.RECONNECT_FAILED="spc-reconnect-failed",HB.ERROR="error",HB.SEI_MESSAGE="sei-message",HB),WB=0,GB=!1,JB=new Set,zB=1,qB=class extends kB.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),ib(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),ib(this,"currentState","DISCONNECTED"),ib(this,"_room"),ib(this,"_signalChannel"),ib(this,"_peerConnection",null),ib(this,"_datachannel",null),ib(this,"_enableCustomMessage"),ib(this,"_log"),ib(this,"_downlinkMIDMap",new Map),ib(this,"_downlinkMIDUserIDMap",new Map),ib(this,"_reconnectionTimer",-1),ib(this,"reconnectionCount",0),ib(this,"clientAbility"),ib(this,"_serverAbility",null),ib(this,"addDownlinkQueue",new Set),ib(this,"removeDownlinkQueue",new Set),ib(this,"_parsedAnswer",null),ib(this,"_updateSDPPromise",null),ib(this,"_waitForPCConnectedPromise"),ib(this,"clearConnectTimeout"),ib(this,"_isSDPLogged",!1),ib(this,"enableInsertableStreams",!1),ib(this,"insertableStreamsAbortMap",new Map),ib(this,"scriptTransformWorker"),ib(this,"_isRelayTried",!1),ib(this,"_rttOverCount",0),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=tP.createLogger({id:"spc".concat(zB++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(ZP?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((e=>"h264"===e.codec.toLowerCase()))),e}addAbortController(e,t){var i;null==(i=this.insertableStreamsAbortMap.get(e))||i.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find((e=>"vp8"===e.codec.toLowerCase()))),e}get videoCodec(){var e,t;let i=null==(e=this._parsedAnswer)?void 0:e.media[1].rtp.find((e=>["h264","vp8"].includes(e.codec.toLowerCase())));return i?i.codec.toLowerCase():null!=(t=this._serverAbility)&&t.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return null!=(e=this._serverAbility)&&e.video.decoders.find((e=>"h264"===e.codec.toLowerCase()))?"h264":"vp8"}get isUsingH264(){return"h264"===this.videoCodec}get is42001fSupported(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f")))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=BF(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&&!gO(e.ssrcs[0].id)){let n=Number(e.ssrcs[0].id),o=Number(null==(r=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:r.id);switch(t){case 0:i.audioSsrc=n;break;case 1:i.bigVideoSsrc=n,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=n,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=n,i.auxVideoRtxSsrc=o}}})),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(e){let{isAux:t}=e;this.useHWEncoder(!1,t?7:2)}initScriptTransformWorker(){eM&&(this.scriptTransformWorker=function(e){let t=[ax],i=[AU,RU,CU,IU,FB,BB],r="const videoEncodePipeline=[".concat(e.videoEncodePipeline.toString(),"];\n const videoDecodePipeline=[").concat(e.videoDecodePipeline.toString(),"];\n const audioEncodePipeline = [").concat(e.audioEncodePipeline.toString(),"];\n const audioDecodePipeline = [").concat(e.audioDecodePipeline.toString(),"];"),n="(()=>{".concat(t.map((e=>"const ".concat(e.name,"=(()=>").concat(e.toString(),")()"))).join("\n"),"\n").concat(i.map((e=>e.toString())).join("\n"),";(").concat((()=>{let e=[],t=[],i=[];self.onmessage=r=>{"sei"===r.data.type&&(r.data.isMain?(e.push(r.data.data),r.data.small&&i.push(r.data.data)):t.push(r.data.data))},self.onrtctransform=r=>{let{options:n}=r.transformer,o=n.isReceiver?BB(n.userId,n.streamType):FB({seiMessageList:n.isMain?n.small?i:e:t});r.transformer.readable.pipeThrough(o).pipeTo(r.transformer.writable)}}),")();").concat(r,"})()"),o=new Blob([n],{type:"text/javascript"}),s=URL.createObjectURL(o),a=new Worker(s);return URL.revokeObjectURL(s),a}({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{"sei"===e.data.type&&this.emit("sei-message",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e)})}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}initialize(){return nb(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(),gP.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):"failed"===e&&gP.addFailedEvent({key:521711})},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=e=>this.emit("track",e),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=e=>{let t=new YB(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(tk.AUDIO,{direction:tk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(tk.VIDEO,{direction:tk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(tk.VIDEO,{direction:tk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(tk.VIDEO,{direction:tk.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield NB(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()))}),gP.addSuccessEvent({key:521707}),this.clientAbility}catch(kb){throw gP.addFailedEvent({key:521707,error:kb}),this._log.error("initialize failed ".concat(kb," \noffer: ").concat(null==t?void 0:t.sdp)),kb}}))}setPriority(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"high";if(this._peerConnection)try{this._peerConnection.getSenders().forEach((t=>{let i=t.getParameters();i.encodings[0]&&(i.encodings[0].priority=e,i.encodings[0].networkPriority=e,t.setParameters(i).catch((e=>{this._log.warn("setPriority error ",e)})))}))}catch(wk){this._log.warn("setPriority error ",wk)}}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return nb(this,null,(function*(){var i,r;try{if("CONNECTED"===this.currentState)return;let n=DO(),o={type:"answer",sdp:OB({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(o),yield this.waitForPeerConnectionConnected();let s=(null==(i=this._room.scheduleResult.config)?void 0:i.priority)||(null==(r=this._room.joinParams)?void 0:r.priority)||new URLSearchParams(location.search).get("priority");s&&this.setPriority(s),t||gP.addSuccessEvent({key:521703,cost:DO()-n})}catch(wb){let i=wb instanceof vb&&wb.code===fb.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(wb),e),this.reset(),!i&&!this.isReconnecting&&(gP.addFailedEvent({key:521703,error:wb}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),wb}}))}reconnect(){return nb(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(KU,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:RF,responseCommand:eF.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(0!==t.data.code)throw new vb({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),gP.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),VN.emit(ZO.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(bb){if(!this.isReconnecting)return;if(null!=bb&&bb.message.includes("timeout")){let e=mO(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield QO(e,(e=>{this._reconnectionTimer=e})),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(null==bb?void 0:bb.code," ").concat(bb)),gP.addFailedEvent({key:521704,error:bb}),this.reconnectionCount>=kk()&&this._log.warn("SDK has tried reconnect for ".concat(kk()," 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 nb(this,null,(function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())}))}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),null==(e=this.clearConnectTimeout)||e.call(this),this._signalChannel.off(KU,this.reconnect,this),"RECONNECTING"===this.currentState&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===Ck.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===Ck.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===Ck.FAILED||e.target.connectionState===Ck.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===Ck.CONNECTED||e.target.connectionState===Ck.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),VN.emit(ZO.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 Rk;let e=null;return jP()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,HP()&&0!==this._peerConnection.getReceivers().length&&e?e.state:Rk):Rk}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(jB.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return nb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(MP(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&&rO(t.networkType)),r&&this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port));break}}))}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this.currentState)return e();let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new vb({code:fb.API_CALL_ABORTED,message:DN({key:Fw,data:"leave room"})})))},n=()=>{VN.off(ZO.LEAVE_SUCCESS,r,this),this.off(jB.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{n();let e=new vb({code:fb.API_CALL_TIMEOUT,message:"connection timeout"});WB+=1,(e=>WB>2&&!GB&&0===JB.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),GB=!0,this.emit(jB.FIREWALL_RESTRICTION)),t(e)}),Wk);this.clearConnectTimeout=()=>{n(),clearTimeout(o),delete this.clearConnectTimeout},VN.on(ZO.LEAVE_SUCCESS,r,this),this.on(jB.CONNECTION_STATE_CHANGED,i,this)})),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally((()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}))),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise(((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)})):Promise.resolve()}addDownlink(e){return nb(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(wk){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(wk)),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=tk.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=BF(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(tk.AUDIO,{direction:tk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(tk.VIDEO,{direction:tk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(tk.VIDEO,{direction:tk.TRANSCEIVER_DIRECTION_RECVONLY}),o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=PB({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:BF(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=tk.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(tk.MAIN," ").concat(l,"-audio")}],s.direction=tk.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(tk.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(tk.MAIN," ").concat(l,"-bigvideo")}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=tk.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(tk.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(tk.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(tk.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 nb(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=BF(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 nb(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(YP()){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=BF(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=BF(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=BF(this._peerConnection.remoteDescription.sdp));let s=nD?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:nD?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:nD?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:nD?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:nD?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:s,limit:nD?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:nD?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:s,limit:nD?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:nD?1e3*n:n}]);let a={type:"offer",sdp:HF(o)};return this.updateSDP({localDescription:a})}setScaleResolutionDownBy(e,t,i){let r=e.getParameters();(!r.encodings||0===r.encodings.length)&&(r.encodings=[{}]);let n=r.encodings[0].scaleResolutionDownBy;if(gO(n)?1===t:t===n)return;let o="setScaleResolutionDownBy ".concat(i," ").concat(t);return n&&(o+=" prevScale: ".concat(n)),this._log.warn(o),r.encodings[0].scaleResolutionDownBy=t,e.setParameters(r)}updateSDP(){let{localDescription:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=HF(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,r)=>nb(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(HB){this._log.error(HB),!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(HB)}})))),this._updateSDPPromise}setTransceiverDirection(e,t){return nb(this,null,(function*(){if(!nD||!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===ik.INACTIVE&&t===ik.RECVONLY&&(this._parsedAnswer.media[r].direction=e),e===ik.SENDONLY&&t===ik.INACTIVE&&(this._parsedAnswer.media[r].direction=ik.RECVONLY)}yield this.updateSDP()}))}filterSDPDirection(){return BF(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:LB(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 nb(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach((i=>{var r;if(i.type===tk.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=[],MB(i,n),t=!0)}})),t&&(this._log.warn("switch video encoder to ".concat(e)),yield this.updateSDP())}))}useHWEncoder(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;return nb(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];gO(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===tk.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=[],MB(t,n),i=!0)}})),i&&(this._log.warn("use ".concat(e?"hw":"sw"," encoder")),yield this.updateSDP())}))}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;null==(e=this._peerConnection)||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach((e=>ON(e.abort)&&e.abort("destroy"))),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map((e=>t[e]))}get isUsingRelay(){return"relay"===this._room.getIceTransportPolicy()}detectTCPAndUDP(e){let{uplinkRTT:t,downlinkRTT:i}=e;var r;if("CONNECTED"!==this.currentState||this._isRelayTried&&!this._room.forceRelay||0===this._room.getIceServers().length)return;let n=this._signalChannel.rtt,o=Math.max(t,i),{rttRatioThreshold:s,rttThreshold:a}=(null==(r=this._room.scheduleResult.config)?void 0:r.useTurnTcpInfo)||{};if(!(s&&a&&n&&o))return;let c=Math.floor(o/n),l=(this._isRelayTried||c>s)&&o>a;l?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(n," upRTT: ").concat(t," downRTT: ").concat(i," ratio: ").concat(c," over-count: ").concat(this._rttOverCount," isOver: ").concat(l," isRelayTried: ").concat(this._isRelayTried," force-relay: ").concat(this._room.forceRelay)),this.isUsingRelay||this._isRelayTried?this._room.forceRelay&&this.switchRelay(!1):(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0))):this._rttOverCount=0}switchRelay(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return nb(this,null,(function*(){if(this.isUsingRelay===e)return;let i=e?"relay":"udp",r=e?521709:521710;try{this._room.forceRelay=e,this._log.warn("switchRelay ".concat(i));let t=Date.now();yield this.doSwitchRelay(i),this._log.warn("switchRelay ".concat(i," success")),gP.addSuccessEvent({key:r,cost:Date.now()-t})}catch(wb){this._log.warn("switchRelay ".concat(i," failed"),wb),gP.addFailedEvent({key:r,error:wb}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}}))}doSwitchRelay(e){return new Promise(((t,i)=>{let r=setTimeout((()=>{this.stopReconnection(),i(new Error("switch ".concat(e," timeout")))}),1e4);this.startReconnection().then(t,i).finally((()=>clearTimeout(r)))}))}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}setProfileLevelId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"42e01f",t=arguments.length>1?arguments[1]:void 0;return nb(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];gO(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===tk.VIDEO){let n;e&&(n=this.clientAbility.video.codecs.find((t=>t.fmtp.includes(e)))),n&&(null==(r=t.payloads)||!r.includes(String(n.payload)))&&(t.fmtp=[],t.payloads="",t.rtp=[],t.rtcpFb=[],MB(t,n),i=!0)}})),i&&(this._log.warn("use ".concat(e)),yield this.updateSDP())}))}};tb([ex("reconnect")],qB.prototype,"startReconnection",1),tb([tx((e=>e.userId))],qB.prototype,"addDownlink",1),tb([tx((e=>e))],qB.prototype,"removeDownlink",1),tb([ZL(!0)],qB.prototype,"updateSDP",1),tb([ix(521712,!1)],qB.prototype,"setOffer",1),tb([ix(521713,!1)],qB.prototype,"setAnswer",1);var KB=class{constructor(e){ib(this,"tag"),ib(this,"len"),ib(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}},YB=class{constructor(e){ib(this,"tinyId"),ib(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new KB(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)}))}},QB=new Set;function XB(){let e=Math.floor(4294967296*Math.random());return QB.has(e)?XB():(QB.add(e),e)}var $B=eb(ob()),ZB=class extends $B.default{constructor(e){super(),ib(this,"userId"),ib(this,"tinyId"),ib(this,"_sdpSemantics"),ib(this,"_isUplink"),ib(this,"_room"),ib(this,"_log"),ib(this,"_currentState","DISCONNECTED"),ib(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=tP.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&&(VN.emit(ZO.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"))}},eH=class extends ZB{constructor(e){super(XA(QA({},e),{isUplink:!0})),ib(this,"localMainAudioTrack",null),ib(this,"localMainVideoTrack",null),ib(this,"localAuxAudioTrack",null),ib(this,"localAuxVideoTrack",null),ib(this,"_isPublishingAux",!1),ib(this,"_publishingLocalAudioTrack"),ib(this,"_publishingLocalVideoTrack"),ib(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}),ib(this,"_flag",0),ib(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=RM.run(nw,(()=>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(AN()," ").concat(SN())),gP.addCount({key:521e3})}RM.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&&(WP()?(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===tk.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}get serverPublishState(){return{audio:!!(this.flag&ck),bigVideo:!!(this.flag&ok),smallVideo:!!(this.flag&sk),auxVideo:!!(this.flag&ak)}}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)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}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 nb(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,u;if(!t.singlePC)return;yield t.singlePC.waitForPeerConnectionConnected();let h,{publishState:p,muteState:m}=t;if(i&&(t._publishingLocalAudioTrack=i,p.audio=!0,m.audio=i.muted),r){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new vb({code:fb.NOT_SUPPORTED_H264,message:DN({key:Nw})});eD&&115===$D()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to 480p"),r.setProfile(Zb["480p_2"]),yield r.applyProfile()),t._publishingLocalVideoTrack=r,n?(p.auxVideo=!0,m.auxVideo=r.muted):(p.bigVideo=!0,m.bigVideo=r.muted)}if(t._isPublishingAux=n,r&&!n&&r.small&&(h=t._room.videoManager.smallTrack,p.smallVideo=!0),yield t._signalChannel.sendWaitForResponseWithRetry({command:AF,responseCommand:eF.SPC_PUBLISH_RESULT,data:XA(QA({},t.singlePC.uplinkSSRC),{state:p,muteState:m}),retries:3}),yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:h,isAuxiliary:n}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r){t[n?"localAuxVideoTrack":"localMainVideoTrack"]=r;let{scaleResolutionDownBy:e}=r;yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[n?3:1],e,r.streamType)}i&&(t[n?"localAuxAudioTrack":"localMainAudioTrack"]=i),yield t.singlePC.setBandwidth({audio:(null==(e=t.localMainAudioTrack)?void 0:e.profile.bitrate)||(null==(o=t.localAuxAudioTrack)?void 0:o.profile.bitrate),bigVideo:null==(s=t.localMainVideoTrack)?void 0:s.profile.bitrate,smallVideo:null==(c=null==(a=t.localMainVideoTrack)?void 0:a.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),t.sendMediaSettings(),t.installTrackMuteEvents(i,r),!n&&(t._room.preferHW||(null==(d=t._room.scheduleResult.config)?void 0:d.preferHW))&&r&&r.profile.width*r.profile.height>=921600&&t.singlePC.useHWEncoder(!0,2);let _=new URLSearchParams(location.search).get("profileLevelId"),f=SN();if("SM-A032F"===f||(null==(u=t._room.options.profileLevelIdModelList)?void 0:u.includes(f))){r&&r.profile.width*r.profile.height<=76800&&(t._log.warn("fallback profile to 240p_2 on ".concat(f)),r.setProfile(Zb["240p_2"]),yield r.applyProfile());let e=new Set;t.singlePC.clientAbility.video.codecs.forEach((t=>{if("H264"===t.codec){let i=t.fmtp.match(/profile-level-id=([0-9a-fA-F]+)/);i&&i[1]&&e.add(i[1])}})),_=[...e.values()].find((e=>"42e01f"!==e)),_&&t._log.warn("set profileLevelId to ".concat(_," on ").concat(f))}_&&t.singlePC.setProfileLevelId(_)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!GP())return;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[],d=(e,t,i)=>{var r,n;let o=a[t].sender.replaceTrack(i);l.push(t),null!=(r=this.singlePC)&&r.enableInsertableStreams&&o.then((()=>this.createEncodedStreams(a[t].sender,e))),null!=(n=this.singlePC)&&n.scriptTransformWorker&&this.initSenderTransfrom(a[t].sender,e),c.push(o)};s&&d(t.mediaType,0,s),o&&d(i.mediaType,n?3:1,o),r&&d(8,2,r);let u=this.singlePC.setTransceiverDirection(ik.SENDONLY,l);return c.push(u),Promise.all(c)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var i,r;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let n=e.createEncodedStreams(),o=new AbortController;null==(i=this.singlePC)||i.addAbortController(e,o),(null!=(r=this.getTrackByMediaType(t))&&r.enableEncodeFrame?n.readable.pipeThrough(new TransformStream({transform:(e,i)=>{var r;let n=this.getTrackByMediaType(t);i.enqueue((null==(r=this.singlePC)?void 0:r.isUsingH264)&&n?n.encodeFrame(e,8===t):e)}}),o):n.readable).pipeTo(n.writable,o).catch((e=>{this._log.debug("encoded stream error",e),"destory"!==e&&this._log.warn(e)}))}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)return;let i=2!==t,r=8===t;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:1===t,isMain:i,isSmall:r}))}enableSmall(e){return nb(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(ik.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(ik.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 nb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){let e=r&&r===t.localAuxVideoTrack,n=null==r?void 0:r.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localMainAudioTrack&&!t.localAuxAudioTrack&&(yield o[0].replaceTrack(null),s.push(0))),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=XA(QA({},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=XA(QA({},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(ik.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 nb(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:aF,data:t,responseCommand:eF.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:cF,commandDesc:"unpublish",responseCommand:eF.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===fb.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),XP){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:IF,data:this._mediaSettings,responseCommand:eF.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return nb(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?tk.AUXILIARY:tk.MAIN," stream")),WP()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return nb(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===tk.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===ik.INACTIVE&&(yield this.singlePC.setTransceiverDirection(ik.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return nb(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?tk.AUXILIARY:tk.MAIN," stream")),WP()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return nb(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===tk.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(ik.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}replaceTrack(e){return nb(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?tk.AUXILIARY:tk.MAIN," stream")),r.kind===tk.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===tk.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0}))}setBandwidth(e){return nb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===tk.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:oF,responseCommand:eF.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&VN.emit(ZO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===tk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===tk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===tk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===tk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Vk?(this._log.error(Hw.NOT_SUPPORTED_H264ENCODE),new vb({code:fb.NOT_SUPPORTED_H264,message:DN({key:Nw})})):new vb({code:fb.UNKNOWN,message:DN({key:Lw,data:{signalResponse:eF.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return nb(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}))}))}};tb([zL((function(e){let{localVideoTrack:t}=e;null==t||t.once("6",this.onVideoEncodeFailed,this)}))],eH.prototype,"publish",1),tb([zL((function(e){let{localVideoTrack:t}=e;null==t||t.off("6",this.onVideoEncodeFailed,this)}))],eH.prototype,"unpublish",1);var tH=eH;function iH(e){return Object.keys(e).filter((t=>e[t]))}var rH=class extends ZB{constructor(e){super(XA(QA({},e),{isUplink:!1})),ib(this,"_flag",0),ib(this,"isRobot",!1),ib(this,"role","anchor"),ib(this,"remoteAudioTrack"),ib(this,"remoteVideoTrack"),ib(this,"remoteAuxiliaryTrack"),ib(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),ib(this,"jitterBufferTimeoutId",-1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Tx(this._room,this),this.remoteVideoTrack=new mV(this._room,this),this.remoteAuxiliaryTrack=new _V(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 LO(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===tk.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){var t;let i=e.streams[0],{track:r,receiver:n}=e;if(!i.id.includes(this.tinyId))return;let o=i.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(o," ").concat(r.kind));let s=tk.AUDIO;r.kind===tk.VIDEO&&(s=o===tk.MAIN?tk.VIDEO:tk.AUXILIARY);let a=this.remoteAudioTrack;s===tk.VIDEO?a=this.remoteVideoTrack:s===tk.AUXILIARY&&(a=this.remoteAuxiliaryTrack),null!=(t=this.singlePC)&&t.scriptTransformWorker&&this.initReceiverTransform(n,o,r.kind===tk.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(a,n),a.setInputMediaStreamTrack(r)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let i=t.createEncodedStreams(),r=new AbortController,n={abortController:r,enqueue:t=>{var i;return null!=(i=this.singlePC)&&i.isUsingH264?e.decodeFrame(t):t}};(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)}}initReceiverTransform(e,t,i){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:i,userId:this.userId,streamType:t}))}subscribe(e,t){return nb(this,null,(function*(){try{if(this._log.info("subscribe ".concat(t," ").concat(iH(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(kb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(kb.message," ").concat(JSON.stringify(this.muteState))),new vb({code:fb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):kb}}))}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"),ZD&&iN<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return nb(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=QA({},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(iH(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=dF,n=eF.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=uF,n=eF.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 vb({code:i.code,message:DN({key:hw,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 nb(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:XB(),bigVideoSsrc:XB(),bigVideoRtxSsrc:XB(),auxVideoSsrc:XB(),auxVideoRtxSsrc:XB()},{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:bF,responseCommand:eF.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 vb({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 nb(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||PN(t)&&PN(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return yO(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),yO(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,PN(t)&&(this.remoteAudioTrack.jitterBufferDelay=i)),new Promise((e=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:e})}))}doSetJitterBufferDelay(e){let{mainDelay:t,auxDelay:i,receivers:r,resolve:n}=e;try{if(0===t&&0===i)return r.forEach((e=>e.jitterBufferTarget=0)),n();if(r.forEach((e=>{var r;let n=e.track===this.remoteAuxiliaryTrack.outMediaTrack||PN(t)&&e.track===this.remoteAudioTrack.outMediaTrack;if(n&&PN(i)||!n&&PN(t))return;let o=n?i||0:t,s=(e.jitterBufferTarget||0)+100;s>o||(e.jitterBufferTarget=s,this._log.debug("set ".concat(n?"aux ":"").concat(null==(r=null==e?void 0:e.track)?void 0:r.kind," jitterBuffer delay ").concat(s," -> ").concat(o)))})),!r.find((e=>{let r=e.track===this.remoteAuxiliaryTrack.outMediaTrack?i||0:t;return e.jitterBufferTarget<r})))return this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i," done")),n();this.jitterBufferTimeoutId=setTimeout((()=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:n})}),1e3)}catch(wb){this._log.warn("set jitterBuffer delay error: ".concat(wb)),clearTimeout(this.jitterBufferTimeoutId),n()}}get audioReceiver(){var e;return(null==(e=this.singlePC)?void 0:e.getReceiversByUserId(this.userId)[0])||null}};tb([ZL(),qL((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 vb({code:fb.API_CALL_ABORTED,message:DN({key:Fw,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],rH.prototype,"subscribe",1),tb([ZL()],rH.prototype,"unsubscribe",1),tb([tx((()=>"jitter"))],rH.prototype,"setJitterBufferDelay",1);var nH=rH;var oH=eb(ob());var sH=class extends oH.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,ib(this,"log"),ib(this,"cmdIdSeqMap",new Map),ib(this,"messageMap",new Map),this.log=tP.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(eF.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",(e=>{[...this.messageMap.keys()].forEach((t=>{t.split("_").slice(0,-1).join("_")===e&&this.messageMap.delete(t)}))}))}send(e){let{cmdId:t,data:i}=e,r=this.cmdIdSeqMap.get(t)||Math.floor(16383*Math.random()),n={cmdId:t,msg:btoa(String.fromCharCode(...new Uint8Array(i))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(t,r+1),this.signalChannel.send(DF,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)>sH.SEQ_INTERVAL)this.messageMap.set(t,{lastSeq:e.seq,cachedMessageMap:new Map}),this.emitMessage(e);else if(e.seq>r.lastSeq){if(e.seq===r.lastSeq+1)this.emitMessage(e);else if(!r.cachedMessageMap.has(e.seq)){let t=setTimeout((()=>this.emitMessage(e,!0)),5e3);r.cachedMessageMap.set(e.seq,{message:e,timeoutId:t})}}else this.log.debug("drop message ".concat(e.userId,"-").concat(e.cmdId,"-").concat(e.seq));else r||(r={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(t,r),setTimeout((()=>this.emitMessage(e,!0)),100)),r.cachedMessageMap.set(e.seq,{message:e})}else this.emit("message",e)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(t.srcTinyId));let i=r=>{r.tinyId===t.srcTinyId&&(this.room.off("peer-join",i),this.onReceiveMsg(e))};this.room.on("peer-join",i),QO(2e3).then((()=>this.room.off("peer-join",i)))}}emitMessage(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i;let r=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),n=e;if(r){if(t){let e=[...r.cachedMessageMap.values()].sort(((e,t)=>e.message.seq-t.message.seq));e[0]&&(n=e[0].message)}0!==r.lastSeq&&n.seq-r.lastSeq>1&&this.log.debug("msg lost userId: ".concat(n.userId," seq: ").concat(r.lastSeq," -> ").concat(n.seq)),r.lastSeq=n.seq,clearTimeout(null==(i=r.cachedMessageMap.get(n.seq))?void 0:i.timeoutId),r.cachedMessageMap.delete(n.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(n))),this.emit("message",n);let o=null==r?void 0:r.cachedMessageMap.get(n.seq+1);o&&this.emitMessage(o.message)}},aH=sH;ib(aH,"SEQ_INTERVAL",300);var{isString:cH,isUndefined:lH,getNetworkType:dH,isEmpty:uH}=Eb,hH=class extends gB{constructor(e){super(e),this.options=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=JP,this._changeBigSmallRecords=new Map,this.forceRelay=!1,this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=0,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this.preferHW=!1,this._updateAudioLevelTaskId=-1,this._stats=new QF(this,this._log),this.userManager=new yV(this.userId,this._log),this._version=Cb,this.sdpSemantics=xk,lH(e.sdpSemantics)?nP.isUnifiedPlanDefault()&&(this.sdpSemantics=Lk):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(dH())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!lH(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&JP,!lH(e.enableSPC)&&JP&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new UB(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 nb(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)JA.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&WA)for(var r of WA(e))t.indexOf(r)<0&&zA.call(e,r)&&(i[r]=e[r]);return i})(e,[]);VN.emit(ZO.REMOTE_PUBLISH_STATE_CHANGED,QA({room:this},t)),this.emit("remote-publish-state-changed",QA({},t))})),this.joinParams=e,new Promise(((t,i)=>nb(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 vb&&o.code===fb.SPC_INITIALIZED_FAILED))return i(o);null==(r=this.signalChannel)||r.destroy(),yield this.initialize()}let s=DO();yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),gP.addSuccessEvent({key:521708,cost:DO()-s}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(oP){gP.addFailedEvent({key:521708,error:oP}),i(oP)}this._joinReject=null}))))}))}initSinglePC(){return nb(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new qB({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(bb){throw this.fallbackToMPC(),new vb({code:fb.SPC_INITIALIZED_FAILED,message:null==bb?void 0:bb.message})}}}))}doJoin(e,t){return new Promise(((i,r)=>nb(this,null,(function*(){var n,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(QU,(e=>{this.clearJoinTimeout(),VN.emit(ZO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)})),TO(null==(o=null==(n=this.scheduleResult)?void 0:n.config)?void 0:o.singlePC)&&JP&&(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:bN(),netType:nO(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;(null==(s=this.scheduleResult.config)?void 0:s.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{r(new vb({code:fb.JOIN_ROOM_FAILED,message:DN({key:Tw})}))}),c),VN.emit(ZO.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?CF:iF,a),this.signalChannel.once(eF.JOIN_ROOM_RESULT,(t=>{this.clearJoinTimeout();let{code:n,message:o,data:s,tinyId:a}=t.data;VN.emit(ZO.JOIN_RECEIVED_CMD_RES,{room:this,code:n}),0===n?(this._log.info("Join room success, start heartbeat"),a&&(this.tinyId=a),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=s.publishers,this.singlePC&&this.singlePC.connect(XA(QA({},s.ability),{useVp8:s.ability.useVp8||!!e.useVp8})).catch((()=>{})),i()):(this._log.error("Join room failed result: ".concat(n," error: ").concat(o)),r(new vb({code:fb.JOIN_ROOM_FAILED,extraCode:n,message:DN({key:Sw,data:{error:o,code:n}})})))}))}))))}reJoin(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return nb(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(XA(QA({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),FN.logSuccessEvent({userId:this.userId,eventType:Nk.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(jB.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof tH&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(jB.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof YF&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(wk){this._log.warn("reJoin fail ".concat(wk)),this.reset(),FN.logFailedEvent({userId:this.userId,eventType:Nk.REJOIN,error:wk}),this.emit("error",new vb({code:fb.JOIN_ROOM_FAILED,message:DN({key:Ew,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return nb(this,null,(function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this.signalChannel||function(e){let t=[...NF.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 OF({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 aH(this,this.signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this.networkQuality||(this.networkQuality=new eB({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(eB.EVENT_NETWORK_QUALITY,(e=>{var t;this.emit("network-quality",e),null==(t=this.singlePC)||t.detectTCPAndUDP(e)}))),kM(this,this.signalChannel).add(qU,(e=>{VN.emit(ZO.SIGNAL_CONNECTION_STATE_CHANGED,QA({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(YU,(e=>{this.reset(),this.emit("error",e)})).add(eF.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})).add(eF.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(eF.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(eF.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(FN.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(zU,(e=>{this.tinyId=e.signalInfo.tinyId,VN.emit(ZO.JOIN_SIGNAL_CONNECTION_END,{room:this})})),VN.emit(ZO.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&VN.emit(ZO.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this.signalChannel=e,e||wM(this)}leave(){return nb(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(wk){}this._log.info("leave() => leaving room"),VN.emit(ZO.LEAVE_SEND_CMD,{room:this}),null==(e=this.signalChannel)||e.send(rF)}))}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach((e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")}))}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){-1===this._heartbeat&&(this._heartbeat=RM.run(tw,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),RM.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return nb(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(fV.has(e)){let t=fV.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 fV.delete(e),t}return[]}(this.userId):[],n=XA(QA({str_sdk_version:Rb,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:QA({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:nO()},i.msg_device_info)});if(this.heartbeatReport=n,VN.emit(ZO.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(nF,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",XA(QA({},n),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter((e=>e.flag!==hk)).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})})),VN.emit(ZO.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 YF&&(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?nH:JF)({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!==fb.ICE_TRANSPORT_ERROR&&(i===fb.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",XA(QA({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=RM.run(tw,this.syncUserList.bind(this)))}stopSyncUserListInterval(){RM.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:SF,responseCommand:eF.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 DN({key:Lw,data:{signalResponse:eF.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||!VF)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)===Ck.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof UF&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===Ck.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return nb(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),FN.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 YF({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0})),e.close()}for(let t of[...this.remotePublishedUserMap.values()]){let e=new JF({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(e,t.userId),this.remotePublishedUserMap.set(t.userId,e),t.isMainStreamSubscribed&&(yield e.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield e.subscribe(t.subscribeState,"auxiliary"))}}))}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new vb({code:fb.INVALID_OPERATION,message:DN({key:kw,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),RM.clearTask(this._audioVolumeIntervalId))}switchRole(e){return nb(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:EF,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:eF.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 vb({code:fb.SWITCH_ROLE_FAILED,message:DN({key:Aw,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof vb&&e.getCode()===fb.API_CALL_TIMEOUT&&(e=new vb({code:fb.SWITCH_ROLE_FAILED,message:DN({key:Cw})})),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 nb(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof sx&&(t instanceof mx?i.audio=t:e.audio=t),t instanceof lx&&(t instanceof px&&2===t.mediaType?i.video=t:e.video=t)}));let r=uH(e),n=uH(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new tH({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new YF({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",(e=>{this.emit("media-connection-state-changed",XA(QA({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==fb.ICE_TRANSPORT_ERROR&&(t===fb.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 nb(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 sx&&(t instanceof mx?i.audio=t:e.audio=t),t instanceof lx&&(t instanceof px&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");uH(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),uH(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&&KP()?this.uplinkConnection.replaceTrack(e).then((t=>{t&&VN.emit(ZO.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return nb(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return nb(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:tk.VIDEO,videoType:tk.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 nb(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=QA({},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),VN.emit(ZO.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(jF(n),"] prev: [").concat(jF(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());VN.emit(ZO.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(wb){let i=wb instanceof vb?wb.getCode():fb.UNKNOWN,n=wb;throw wb instanceof vb?i===fb.REMOTE_STREAM_NOT_EXIST&&(n=new vb({code:fb.API_CALL_ABORTED,message:DN({key:Bw,data:{message:wb.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new vb({code:i,message:DN({key:Rw,data:{message:wb.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 nb(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(wb){this._log.warn("unsubscribe() => failed ".concat(wb))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),VN.emit(ZO.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 RM.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),VN.emit(ZO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&RM.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=RM.run(iw,(()=>{var i;vL.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];null==(i=this.remotePublishedUserMap)||i.forEach((e=>{if(e.muteState.hasAudio){vL.isRunning?e.remoteAudioTrack.volume=0:this.updateDownlinkAudioLevelFromReceiver(e);let t=Math.floor(100*e.remoteAudioTrack.getAudioLevel());r.push({userId:e.userId,volume:t})}})),this.emit("audio-volume",r)}),{fps:1e3/e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return nb(this,null,(function*(){var i;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||-1!==this._updateAudioLevelTaskId)return;let r=null==(i=this.uplinkConnection.getPeerConnection())?void 0:i.getSenders()[0];if(!r)return;let n=Math.max(e,500);this._log.warn("updateAudioLevelFromSenderStat ".concat(n)),this._updateAudioLevelTaskId=RM.run(iw,(()=>nb(this,null,(function*(){let e=yield r.getStats();this._updateAudioLevelTaskId<0||e.forEach((e=>{"media-source"===e.type&&e.audioLevel&&(this.uplinkConnection.localMainAudioTrack.volume=e.audioLevel)}))}))),{delay:n,backgroundTask:t})}))}stopUpdateAudioLevelFromSenderStat(){var e;-1!==this._updateAudioLevelTaskId&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),RM.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,null!=(e=this.uplinkConnection)&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var t;let{audioReceiver:i}=e;if(!QP||!i)return;let r=null==(t=i.getSynchronizationSources()[0])?void 0:t.audioLevel;this._log.debug("updateDownlinkAudioLevelFromReceiver"),r&&(e.remoteAudioTrack.volume=Math.min(2*r,1))}getLocalAudioStats(){return nb(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 nb(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 nb(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 nb(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 nb(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(Eb.getTurnServer(e)))):Eb.isPlainObject(e)&&i.push(Eb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:fF,data:e,timeout:5e3,responseCommand:eF.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:gF,data:e,timeout:5e3,responseCommand:eF.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?hF:mF,data:e,timeout:5e3,responseCommand:t?eF.START_PUBLISH_TENCENT_CDN_RES:eF.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?pF:_F,data:e,timeout:5e3,responseCommand:t?eF.STOP_PUBLISH_TENCENT_CDN_RES:eF.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:vF,data:e,timeout:5e3,responseCommand:eF.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:yF,data:e,timeout:5e3,responseCommand:eF.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:TF,data:e,timeout:5e3,responseCommand:eF.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:kF,data:e,timeout:5e3,responseCommand:eF.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch((e=>{}))}getIceServers(){return 0===this._turnServers.length&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=Eb.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 nb(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(Zk-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=Zk}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(Zk-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:Zk};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(cH(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!lH(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new vb({code:fb.INVALID_PARAMETER,message:DN({key:fw})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!lH(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new vb({code:fb.INVALID_PARAMETER,message:DN({key:gw})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!lH(e.userDefinePushArgs)){if(!(cH(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new vb({code:fb.INVALID_PARAMETER,message:DN({key:vw})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}uH(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&ZP)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 vb({code:fb.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return null==(e=this.singlePC)?void 0:e.scriptTransformWorker}};return tb([RB(["left",bB.INIT],"joined"),NM({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn("join retry ".concat(e))},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),jN(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),qL((e=>{let t=new WU;return function(i,r,n){return nb(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 vb({code:fb.INVALID_OPERATION,message:DN({key:yw})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new vb({code:fb.INVALID_OPERATION,message:DN({key:bw,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)),VN.emit(ZO.JOIN_START,{room:this,roomId:o,params:i});let s=Eb.getEnv();s||(s=Jb.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(rk.OLD_CLOUD_LADDER)?s=Jb.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(rk.WEBRTC)&&(s=Jb.WEBRTC))),FN.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),nP.checkSystemRequirementsInternal().then((e=>{this.checkSystemResult=e,GU.call(this)}));try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Eb.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=Eb.performanceNow(),VN.emit(ZO.JOIN_SUCCESS,{room:this}),30===n&&!i.component&&FN.uploadEvent({log:"stat-conv-".concat(Number(pN),"-").concat(location.hostname),userId:this.userId}),t}catch(a){throw t.delete({room:this,roomId:o}),VN.emit(ZO.JOIN_FAILED,{room:this,error:a}),a}}))}}))],hH.prototype,"join",1),tb([RB("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),qL((e=>function(){return nb(this,null,(function*(){VN.emit(ZO.LEAVE_START,{room:this}),yield e.call(this),VN.emit(ZO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),ex("leave room"),OM({fnName:"publish",validateArgs:!1}),OM({fnName:"unsubscribe",validateArgs:!1})],hH.prototype,"leave",1),tb([ZL(),qL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return nb(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"capture"===e.state)),!i.length))return;VN.emit("61",{room:this});let t=e.apply(this,i);return i.forEach((e=>e.publish(this,t))),t}))})),NM({settings:{retries:kk,timeout:e=>mO(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),VN.emit(ZO.PUBLISH_FAILED,{room:this}))}})],hH.prototype,"publish",1),tb([OM({fnName:"publish"}),function(e){return function(t,i,r){let n=r.value;return r.value=function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let o=XL.get(this);if(o){let t=o.queue.filter(((t,r)=>{if(0===r)return!0;let n=!0;return t.args.forEach((e=>{i.find((t=>t===e))||(n=!1)})),!n||(t.reject(new vb({code:fb.API_CALL_ABORTED,message:e})),!1)}));o.queue=t}return n.apply(this,i)},r}}("api-call"),ZL(),qL((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})),zL((function(){var e,t;0===this.localTracks.size&&jP()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((e=>e.track&&e.replaceTrack(null))))}))],hH.prototype,"unpublish",1),tb([tx((e=>e.userId))],hH.prototype,"replaceTrack",1),tb([tx((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),gx(),qL((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})),NM({settings:{retries:kk,timeout:e=>mO(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),VN.emit(ZO.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],hH.prototype,"subscribe",1),tb([OM({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")}))}}),tx((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],hH.prototype,"unsubscribe",1),jU.create=jU._create.bind(jU,hH),jU}));
|
|
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:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r=function(e){return e&&e.Math===Math&&e},n=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")(),o={},s=function(e){try{return!!e()}catch(t){return!0}},a=!s((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})),c=!s((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),l=c,d=Function.prototype.call,u=l?d.bind(d):function(){return d.apply(d,arguments)},h={},p={}.propertyIsEnumerable,m=Object.getOwnPropertyDescriptor,_=m&&!p.call({1:2},1);h.f=_?function(e){var t=m(this,e);return!!t&&t.enumerable}:p;var f,g,v=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},y=c,T=Function.prototype,S=T.call,E=y&&T.bind.bind(S,S),I=y?E:function(e){return function(){return S.apply(e,arguments)}},R=I,C=R({}.toString),A=R("".slice),b=function(e){return A(C(e),8,-1)},k=s,w=b,D=Object,N=I("".split),O=k((function(){return!D("z").propertyIsEnumerable(0)}))?function(e){return"String"===w(e)?N(e,""):D(e)}:D,P=function(e){return null==e},M=P,L=TypeError,x=function(e){if(M(e))throw new L("Can't call method on "+e);return e},V=O,U=x,F=function(e){return V(U(e))},B="object"==typeof document&&document.all,H=void 0===B&&void 0!==B?function(e){return"function"==typeof e||e===B}:function(e){return"function"==typeof e},j=H,W=function(e){return"object"==typeof e?null!==e:j(e)},G=n,J=H,z=function(e,t){return arguments.length<2?(i=G[e],J(i)?i:void 0):G[e]&&G[e][t];var i},q=I({}.isPrototypeOf),K=n.navigator,Y=K&&K.userAgent,Q=Y?String(Y):"",X=n,$=Q,Z=X.process,ee=X.Deno,te=Z&&Z.versions||ee&&ee.version,ie=te&&te.v8;ie&&(g=(f=ie.split("."))[0]>0&&f[0]<4?1:+(f[0]+f[1])),!g&&$&&(!(f=$.match(/Edge\/(\d+)/))||f[1]>=74)&&(f=$.match(/Chrome\/(\d+)/))&&(g=+f[1]);var re=g,ne=re,oe=s,se=n.String,ae=!!Object.getOwnPropertySymbols&&!oe((function(){var e=Symbol("symbol detection");return!se(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),ce=ae&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,le=z,de=H,ue=q,he=Object,pe=ce?function(e){return"symbol"==typeof e}:function(e){var t=le("Symbol");return de(t)&&ue(t.prototype,he(e))},me=String,_e=function(e){try{return me(e)}catch(t){return"Object"}},fe=H,ge=_e,ve=TypeError,ye=function(e){if(fe(e))return e;throw new ve(ge(e)+" is not a function")},Te=ye,Se=P,Ee=function(e,t){var i=e[t];return Se(i)?void 0:Te(i)},Ie=u,Re=H,Ce=W,Ae=TypeError,be={exports:{}},ke=n,we=Object.defineProperty,De=function(e,t){try{we(ke,e,{value:t,configurable:!0,writable:!0})}catch(i){ke[e]=t}return t},Ne=n,Oe=De,Pe="__core-js_shared__",Me=be.exports=Ne[Pe]||Oe(Pe,{});(Me.versions||(Me.versions=[])).push({version:"3.40.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.40.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Le=be.exports,xe=Le,Ve=function(e,t){return xe[e]||(xe[e]=t||{})},Ue=x,Fe=Object,Be=function(e){return Fe(Ue(e))},He=Be,je=I({}.hasOwnProperty),We=Object.hasOwn||function(e,t){return je(He(e),t)},Ge=I,Je=0,ze=Math.random(),qe=Ge(1..toString),Ke=function(e){return"Symbol("+(void 0===e?"":e)+")_"+qe(++Je+ze,36)},Ye=Ve,Qe=We,Xe=Ke,$e=ae,Ze=ce,et=n.Symbol,tt=Ye("wks"),it=Ze?et.for||et:et&&et.withoutSetter||Xe,rt=function(e){return Qe(tt,e)||(tt[e]=$e&&Qe(et,e)?et[e]:it("Symbol."+e)),tt[e]},nt=u,ot=W,st=pe,at=Ee,ct=function(e,t){var i,r;if("string"===t&&Re(i=e.toString)&&!Ce(r=Ie(i,e)))return r;if(Re(i=e.valueOf)&&!Ce(r=Ie(i,e)))return r;if("string"!==t&&Re(i=e.toString)&&!Ce(r=Ie(i,e)))return r;throw new Ae("Can't convert object to primitive value")},lt=TypeError,dt=rt("toPrimitive"),ut=function(e,t){if(!ot(e)||st(e))return e;var i,r=at(e,dt);if(r){if(void 0===t&&(t="default"),i=nt(r,e,t),!ot(i)||st(i))return i;throw new lt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ct(e,t)},ht=ut,pt=pe,mt=function(e){var t=ht(e,"string");return pt(t)?t:t+""},_t=W,ft=n.document,gt=_t(ft)&&_t(ft.createElement),vt=function(e){return gt?ft.createElement(e):{}},yt=vt,Tt=!a&&!s((function(){return 7!==Object.defineProperty(yt("div"),"a",{get:function(){return 7}}).a})),St=a,Et=u,It=h,Rt=v,Ct=F,At=mt,bt=We,kt=Tt,wt=Object.getOwnPropertyDescriptor;o.f=St?wt:function(e,t){if(e=Ct(e),t=At(t),kt)try{return wt(e,t)}catch(i){}if(bt(e,t))return Rt(!Et(It.f,e,t),e[t])};var Dt={},Nt=a&&s((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Ot=W,Pt=String,Mt=TypeError,Lt=function(e){if(Ot(e))return e;throw new Mt(Pt(e)+" is not an object")},xt=a,Vt=Tt,Ut=Nt,Ft=Lt,Bt=mt,Ht=TypeError,jt=Object.defineProperty,Wt=Object.getOwnPropertyDescriptor,Gt="enumerable",Jt="configurable",zt="writable";Dt.f=xt?Ut?function(e,t,i){if(Ft(e),t=Bt(t),Ft(i),"function"==typeof e&&"prototype"===t&&"value"in i&&zt in i&&!i[zt]){var r=Wt(e,t);r&&r[zt]&&(e[t]=i.value,i={configurable:Jt in i?i[Jt]:r[Jt],enumerable:Gt in i?i[Gt]:r[Gt],writable:!1})}return jt(e,t,i)}:jt:function(e,t,i){if(Ft(e),t=Bt(t),Ft(i),Vt)try{return jt(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Ht("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var qt=Dt,Kt=v,Yt=a?function(e,t,i){return qt.f(e,t,Kt(1,i))}:function(e,t,i){return e[t]=i,e},Qt={exports:{}},Xt=a,$t=We,Zt=Function.prototype,ei=Xt&&Object.getOwnPropertyDescriptor,ti=$t(Zt,"name"),ii={EXISTS:ti,PROPER:ti&&"something"===function(){}.name,CONFIGURABLE:ti&&(!Xt||Xt&&ei(Zt,"name").configurable)},ri=H,ni=Le,oi=I(Function.toString);ri(ni.inspectSource)||(ni.inspectSource=function(e){return oi(e)});var si,ai,ci,li=ni.inspectSource,di=H,ui=n.WeakMap,hi=di(ui)&&/native code/.test(String(ui)),pi=Ke,mi=Ve("keys"),_i=function(e){return mi[e]||(mi[e]=pi(e))},fi={},gi=hi,vi=n,yi=W,Ti=Yt,Si=We,Ei=Le,Ii=_i,Ri=fi,Ci="Object already initialized",Ai=vi.TypeError,bi=vi.WeakMap;if(gi||Ei.state){var ki=Ei.state||(Ei.state=new bi);ki.get=ki.get,ki.has=ki.has,ki.set=ki.set,si=function(e,t){if(ki.has(e))throw new Ai(Ci);return t.facade=e,ki.set(e,t),t},ai=function(e){return ki.get(e)||{}},ci=function(e){return ki.has(e)}}else{var wi=Ii("state");Ri[wi]=!0,si=function(e,t){if(Si(e,wi))throw new Ai(Ci);return t.facade=e,Ti(e,wi,t),t},ai=function(e){return Si(e,wi)?e[wi]:{}},ci=function(e){return Si(e,wi)}}var Di={set:si,get:ai,has:ci,enforce:function(e){return ci(e)?ai(e):si(e,{})},getterFor:function(e){return function(t){var i;if(!yi(t)||(i=ai(t)).type!==e)throw new Ai("Incompatible receiver, "+e+" required");return i}}},Ni=I,Oi=s,Pi=H,Mi=We,Li=a,xi=ii.CONFIGURABLE,Vi=li,Ui=Di.enforce,Fi=Di.get,Bi=String,Hi=Object.defineProperty,ji=Ni("".slice),Wi=Ni("".replace),Gi=Ni([].join),Ji=Li&&!Oi((function(){return 8!==Hi((function(){}),"length",{value:8}).length})),zi=String(String).split("String"),qi=Qt.exports=function(e,t,i){"Symbol("===ji(Bi(t),0,7)&&(t="["+Wi(Bi(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Mi(e,"name")||xi&&e.name!==t)&&(Li?Hi(e,"name",{value:t,configurable:!0}):e.name=t),Ji&&i&&Mi(i,"arity")&&e.length!==i.arity&&Hi(e,"length",{value:i.arity});try{i&&Mi(i,"constructor")&&i.constructor?Li&&Hi(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var r=Ui(e);return Mi(r,"source")||(r.source=Gi(zi,"string"==typeof t?t:"")),e};Function.prototype.toString=qi((function(){return Pi(this)&&Fi(this).source||Vi(this)}),"toString");var Ki=Qt.exports,Yi=H,Qi=Dt,Xi=Ki,$i=De,Zi=function(e,t,i,r){r||(r={});var n=r.enumerable,o=void 0!==r.name?r.name:t;if(Yi(i)&&Xi(i,o,r),r.global)n?e[t]=i:$i(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch(s){}n?e[t]=i:Qi.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},er={},tr=Math.ceil,ir=Math.floor,rr=Math.trunc||function(e){var t=+e;return(t>0?ir:tr)(t)},nr=rr,or=function(e){var t=+e;return t!=t||0===t?0:nr(t)},sr=or,ar=Math.max,cr=Math.min,lr=function(e,t){var i=sr(e);return i<0?ar(i+t,0):cr(i,t)},dr=or,ur=Math.min,hr=function(e){var t=dr(e);return t>0?ur(t,9007199254740991):0},pr=hr,mr=function(e){return pr(e.length)},_r=F,fr=lr,gr=mr,vr=function(e){return function(t,i,r){var n=_r(t),o=gr(n);if(0===o)return!e&&-1;var s,a=fr(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}},yr={includes:vr(!0),indexOf:vr(!1)},Tr=We,Sr=F,Er=yr.indexOf,Ir=fi,Rr=I([].push),Cr=function(e,t){var i,r=Sr(e),n=0,o=[];for(i in r)!Tr(Ir,i)&&Tr(r,i)&&Rr(o,i);for(;t.length>n;)Tr(r,i=t[n++])&&(~Er(o,i)||Rr(o,i));return o},Ar=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],br=Cr,kr=Ar.concat("length","prototype");er.f=Object.getOwnPropertyNames||function(e){return br(e,kr)};var wr={};wr.f=Object.getOwnPropertySymbols;var Dr=z,Nr=er,Or=wr,Pr=Lt,Mr=I([].concat),Lr=Dr("Reflect","ownKeys")||function(e){var t=Nr.f(Pr(e)),i=Or.f;return i?Mr(t,i(e)):t},xr=We,Vr=Lr,Ur=o,Fr=Dt,Br=function(e,t,i){for(var r=Vr(t),n=Fr.f,o=Ur.f,s=0;s<r.length;s++){var a=r[s];xr(e,a)||i&&xr(i,a)||n(e,a,o(t,a))}},Hr=s,jr=H,Wr=/#|\.prototype\./,Gr=function(e,t){var i=zr[Jr(e)];return i===Kr||i!==qr&&(jr(t)?Hr(t):!!t)},Jr=Gr.normalize=function(e){return String(e).replace(Wr,".").toLowerCase()},zr=Gr.data={},qr=Gr.NATIVE="N",Kr=Gr.POLYFILL="P",Yr=Gr,Qr=n,Xr=o.f,$r=Yt,Zr=Zi,en=De,tn=Br,rn=Yr,nn=function(e,t){var i,r,n,o,s,a=e.target,c=e.global,l=e.stat;if(i=c?Qr:l?Qr[a]||en(a,{}):Qr[a]&&Qr[a].prototype)for(r in t){if(o=t[r],n=e.dontCallGetSet?(s=Xr(i,r))&&s.value:i[r],!rn(c?r:a+(l?".":"#")+r,e.forced)&&void 0!==n){if(typeof o==typeof n)continue;tn(o,n)}(e.sham||n&&n.sham)&&$r(o,"sham",!0),Zr(i,r,o,e)}},on={};on[rt("toStringTag")]="z";var sn="[object z]"===String(on),an=H,cn=b,ln=rt("toStringTag"),dn=Object,un="Arguments"===cn(function(){return arguments}()),hn=sn?cn:function(e){var t,i,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(i){}}(t=dn(e),ln))?i:un?cn(t):"Object"===(r=cn(t))&&an(t.callee)?"Arguments":r},pn=hn,mn=String,_n=function(e){if("Symbol"===pn(e))throw new TypeError("Cannot convert a Symbol value to a string");return mn(e)},fn=Ki,gn=Dt,vn=function(e,t,i){return i.get&&fn(i.get,t,{getter:!0}),i.set&&fn(i.set,t,{setter:!0}),gn.f(e,t,i)},yn=nn,Tn=a,Sn=I,En=We,In=H,Rn=q,Cn=_n,An=vn,bn=Br,kn=n.Symbol,wn=kn&&kn.prototype;if(Tn&&In(kn)&&(!("description"in wn)||void 0!==kn().description)){var Dn={},Nn=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:Cn(arguments[0]),t=Rn(wn,this)?new kn(e):void 0===e?kn():kn(e);return""===e&&(Dn[t]=!0),t};bn(Nn,kn),Nn.prototype=wn,wn.constructor=Nn;var On="Symbol(description detection)"===String(kn("description detection")),Pn=Sn(wn.valueOf),Mn=Sn(wn.toString),Ln=/^Symbol\((.*)\)[^)]+$/,xn=Sn("".replace),Vn=Sn("".slice);An(wn,"description",{configurable:!0,get:function(){var e=Pn(this);if(En(Dn,e))return"";var t=Mn(e),i=On?Vn(t,7,-1):xn(t,Ln,"$1");return""===i?void 0:i}}),yn({global:!0,constructor:!0,forced:!0},{Symbol:Nn})}var Un={},Fn=Cr,Bn=Ar,Hn=Object.keys||function(e){return Fn(e,Bn)},jn=a,Wn=Nt,Gn=Dt,Jn=Lt,zn=F,qn=Hn;Un.f=jn&&!Wn?Object.defineProperties:function(e,t){Jn(e);for(var i,r=zn(t),n=qn(t),o=n.length,s=0;o>s;)Gn.f(e,i=n[s++],r[i]);return e};var Kn,Yn=z("document","documentElement"),Qn=Lt,Xn=Un,$n=Ar,Zn=fi,eo=Yn,to=vt,io="prototype",ro="script",no=_i("IE_PROTO"),oo=function(){},so=function(e){return"<"+ro+">"+e+"</"+ro+">"},ao=function(e){e.write(so("")),e.close();var t=e.parentWindow.Object;return e=null,t},co=function(){try{Kn=new ActiveXObject("htmlfile")}catch(n){}var e,t,i;co="undefined"!=typeof document?document.domain&&Kn?ao(Kn):(t=to("iframe"),i="java"+ro+":",t.style.display="none",eo.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(so("document.F=Object")),e.close(),e.F):ao(Kn);for(var r=$n.length;r--;)delete co[io][$n[r]];return co()};Zn[no]=!0;var lo=Object.create||function(e,t){var i;return null!==e?(oo[io]=Qn(e),i=new oo,oo[io]=null,i[no]=e):i=co(),void 0===t?i:Xn.f(i,t)},uo=rt,ho=lo,po=Dt.f,mo=uo("unscopables"),_o=Array.prototype;void 0===_o[mo]&&po(_o,mo,{configurable:!0,value:ho(null)});var fo=function(e){_o[mo][e]=!0},go=yr.includes,vo=fo;nn({target:"Array",proto:!0,forced:s((function(){return!Array(1).includes()}))},{includes:function(e){return go(this,e,arguments.length>1?arguments[1]:void 0)}}),vo("includes");var yo,To,So,Eo={},Io=!s((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Ro=We,Co=H,Ao=Be,bo=Io,ko=_i("IE_PROTO"),wo=Object,Do=wo.prototype,No=bo?wo.getPrototypeOf:function(e){var t=Ao(e);if(Ro(t,ko))return t[ko];var i=t.constructor;return Co(i)&&t instanceof i?i.prototype:t instanceof wo?Do:null},Oo=s,Po=H,Mo=W,Lo=No,xo=Zi,Vo=rt("iterator"),Uo=!1;[].keys&&("next"in(So=[].keys())?(To=Lo(Lo(So)))!==Object.prototype&&(yo=To):Uo=!0);var Fo=!Mo(yo)||Oo((function(){var e={};return yo[Vo].call(e)!==e}));Fo&&(yo={}),Po(yo[Vo])||xo(yo,Vo,(function(){return this}));var Bo={IteratorPrototype:yo,BUGGY_SAFARI_ITERATORS:Uo},Ho=Dt.f,jo=We,Wo=rt("toStringTag"),Go=function(e,t,i){e&&!i&&(e=e.prototype),e&&!jo(e,Wo)&&Ho(e,Wo,{configurable:!0,value:t})},Jo=Bo.IteratorPrototype,zo=lo,qo=v,Ko=Go,Yo=Eo,Qo=function(){return this},Xo=function(e,t,i,r){var n=t+" Iterator";return e.prototype=zo(Jo,{next:qo(+!r,i)}),Ko(e,n,!1),Yo[n]=Qo,e},$o=I,Zo=ye,es=W,ts=function(e){return es(e)||null===e},is=String,rs=TypeError,ns=function(e,t,i){try{return $o(Zo(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},os=W,ss=x,as=function(e){if(ts(e))return e;throw new rs("Can't set "+is(e)+" as a prototype")},cs=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=ns(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return ss(i),as(r),os(i)?(t?e(i,r):i.__proto__=r,i):i}}():void 0),ls=nn,ds=u,us=H,hs=Xo,ps=No,ms=cs,_s=Go,fs=Yt,gs=Zi,vs=Eo,ys=ii.PROPER,Ts=ii.CONFIGURABLE,Ss=Bo.IteratorPrototype,Es=Bo.BUGGY_SAFARI_ITERATORS,Is=rt("iterator"),Rs="keys",Cs="values",As="entries",bs=function(){return this},ks=function(e,t,i,r,n,o,s){hs(i,t,r);var a,c,l,d=function(e){if(e===n&&_)return _;if(!Es&&e&&e in p)return p[e];switch(e){case Rs:case Cs:case As:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[Is]||p["@@iterator"]||n&&p[n],_=!Es&&m||d(n),f="Array"===t&&p.entries||m;if(f&&(a=ps(f.call(new e)))!==Object.prototype&&a.next&&(ps(a)!==Ss&&(ms?ms(a,Ss):us(a[Is])||gs(a,Is,bs)),_s(a,u,!0)),ys&&n===Cs&&m&&m.name!==Cs&&(Ts?fs(p,"name",Cs):(h=!0,_=function(){return ds(m,this)})),n)if(c={values:d(Cs),keys:o?_:d(Rs),entries:d(As)},s)for(l in c)(Es||h||!(l in p))&&gs(p,l,c[l]);else ls({target:t,proto:!0,forced:Es||h},c);return p[Is]!==_&&gs(p,Is,_,{name:n}),vs[t]=_,c},ws=function(e,t){return{value:e,done:t}},Ds=F,Ns=fo,Os=Eo,Ps=Di,Ms=Dt.f,Ls=ks,xs=ws,Vs=a,Us="Array Iterator",Fs=Ps.set,Bs=Ps.getterFor(Us),Hs=Ls(Array,"Array",(function(e,t){Fs(this,{type:Us,target:Ds(e),index:0,kind:t})}),(function(){var e=Bs(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,xs(void 0,!0);switch(e.kind){case"keys":return xs(i,!1);case"values":return xs(t[i],!1)}return xs([i,t[i]],!1)}),"values"),js=Os.Arguments=Os.Array;if(Ns("keys"),Ns("values"),Ns("entries"),Vs&&"values"!==js.name)try{Ms(js,"name",{value:"values"})}catch(pH){}var Ws=ye,Gs=Be,Js=O,zs=mr,qs=TypeError,Ks="Reduce of empty array with no initial value",Ys=function(e){return function(t,i,r,n){var o=Gs(t),s=Js(o),a=zs(o);if(Ws(i),0===a&&r<2)throw new qs(Ks);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 qs(Ks)}for(;e?c>=0:a>c;c+=l)c in s&&(n=i(n,s[c],c,o));return n}},Qs={left:Ys(!1),right:Ys(!0)},Xs=s,$s=function(e,t){var i=[][e];return!!i&&Xs((function(){i.call(null,t||function(){return 1},1)}))},Zs=n,ea=Q,ta=b,ia=function(e){return ea.slice(0,e.length)===e},ra=ia("Bun/")?"BUN":ia("Cloudflare-Workers")?"CLOUDFLARE":ia("Deno/")?"DENO":ia("Node.js/")?"NODE":Zs.Bun&&"string"==typeof Bun.version?"BUN":Zs.Deno&&"object"==typeof Deno.version?"DENO":"process"===ta(Zs.process)?"NODE":Zs.window&&Zs.document?"BROWSER":"REST",na="NODE"===ra,oa=Qs.left;nn({target:"Array",proto:!0,forced:!na&&re>79&&re<83||!$s("reduce")},{reduce:function(e){var t=arguments.length;return oa(this,e,t,t>1?arguments[1]:void 0)}});var sa=b,aa=Array.isArray||function(e){return"Array"===sa(e)},ca=nn,la=aa,da=I([].reverse),ua=[1,2];ca({target:"Array",proto:!0,forced:String(ua)===String(ua.reverse())},{reverse:function(){return la(this)&&(this.length=this.length),da(this)}});var ha=_e,pa=TypeError,ma=I([].slice),_a=ma,fa=Math.floor,ga=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=fa(i/2),a=ga(_a(e,0,s),t),c=ga(_a(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},va=ga,ya=Q.match(/firefox\/(\d+)/i),Ta=!!ya&&+ya[1],Sa=/MSIE|Trident/.test(Q),Ea=Q.match(/AppleWebKit\/(\d+)\./),Ia=!!Ea&&+Ea[1],Ra=nn,Ca=I,Aa=ye,ba=Be,ka=mr,wa=function(e,t){if(!delete e[t])throw new pa("Cannot delete property "+ha(t)+" of "+ha(e))},Da=_n,Na=s,Oa=va,Pa=$s,Ma=Ta,La=Sa,xa=re,Va=Ia,Ua=[],Fa=Ca(Ua.sort),Ba=Ca(Ua.push),Ha=Na((function(){Ua.sort(void 0)})),ja=Na((function(){Ua.sort(null)})),Wa=Pa("sort"),Ga=!Na((function(){if(xa)return xa<70;if(!(Ma&&Ma>3)){if(La)return!0;if(Va)return Va<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++)Ua.push({k:t+r,v:i})}for(Ua.sort((function(e,t){return t.v-e.v})),r=0;r<Ua.length;r++)t=Ua[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));Ra({target:"Array",proto:!0,forced:Ha||!ja||!Wa||!Ga},{sort:function(e){void 0!==e&&Aa(e);var t=ba(this);if(Ga)return void 0===e?Fa(t):Fa(t,e);var i,r,n=[],o=ka(t);for(r=0;r<o;r++)r in t&&Ba(n,t[r]);for(Oa(n,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:Da(t)>Da(i)?1:-1}}(e)),i=ka(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)wa(t,r++);return t}});var Ja="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,za=Zi,qa=function(e,t,i){for(var r in t)za(e,r,t[r],i);return e},Ka=q,Ya=TypeError,Qa=function(e,t){if(Ka(t,e))return e;throw new Ya("Incorrect invocation")},Xa=or,$a=hr,Za=RangeError,ec=function(e){if(void 0===e)return 0;var t=Xa(e),i=$a(t);if(t!==i)throw new Za("Wrong length or index");return i},tc=Math.sign||function(e){var t=+e;return 0===t||t!=t?t:t<0?-1:1},ic=4503599627370496,rc=tc,nc=function(e){return e+ic-ic},oc=Math.abs,sc=function(e,t,i,r){var n=+e,o=oc(n),s=rc(n);if(o<r)return s*nc(o/r/t)*r*t;var a=(1+t/2220446049250313e-31)*o,c=a-(a-o);return c>i||c!=c?Infinity*s:s*c},ac=Math.fround||function(e){return sc(e,1.1920928955078125e-7,34028234663852886e22,11754943508222875e-54)},cc=Array,lc=Math.abs,dc=Math.pow,uc=Math.floor,hc=Math.log,pc=Math.LN2,mc={pack:function(e,t,i){var r,n,o,s=cc(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?dc(2,-24)-dc(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=lc(e))!=e||Infinity===e?(n=e!=e?1:0,r=c):(r=uc(hc(e)/pc),e*(o=dc(2,-r))<1&&(r--,o*=2),(e+=r+l>=1?d/o:d*dc(2,1-l))*o>=2&&(r++,o/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*o-1)*dc(2,t),r+=l):(n=e*dc(2,l-1)*dc(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+=dc(2,t),d-=s}return(l?-1:1)*i*dc(2,d-t)}},_c=Be,fc=lr,gc=mr,vc=function(e){for(var t=_c(this),i=gc(t),r=arguments.length,n=fc(r>1?arguments[1]:void 0,i),o=r>2?arguments[2]:void 0,s=void 0===o?i:fc(o,i);s>n;)t[n++]=e;return t},yc=H,Tc=W,Sc=cs,Ec=function(e,t,i){var r,n;return Sc&&yc(r=t.constructor)&&r!==i&&Tc(n=r.prototype)&&n!==i.prototype&&Sc(e,n),e},Ic=n,Rc=I,Cc=a,Ac=Ja,bc=Yt,kc=vn,wc=qa,Dc=s,Nc=Qa,Oc=or,Pc=hr,Mc=ec,Lc=ac,xc=mc,Vc=No,Uc=cs,Fc=vc,Bc=ma,Hc=Ec,jc=Br,Wc=Go,Gc=Di,Jc=ii.PROPER,zc=ii.CONFIGURABLE,qc="ArrayBuffer",Kc="DataView",Yc="prototype",Qc="Wrong index",Xc=Gc.getterFor(qc),$c=Gc.getterFor(Kc),Zc=Gc.set,el=Ic[qc],tl=el,il=tl&&tl[Yc],rl=Ic[Kc],nl=rl&&rl[Yc],ol=Object.prototype,sl=Ic.Array,al=Ic.RangeError,cl=Rc(Fc),ll=Rc([].reverse),dl=xc.pack,ul=xc.unpack,hl=function(e){return[255&e]},pl=function(e){return[255&e,e>>8&255]},ml=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},_l=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},fl=function(e){return dl(Lc(e),23,4)},gl=function(e){return dl(e,52,8)},vl=function(e,t,i){kc(e[Yc],t,{configurable:!0,get:function(){return i(this)[t]}})},yl=function(e,t,i,r){var n=$c(e),o=Mc(i),s=!!r;if(o+t>n.byteLength)throw new al(Qc);var a=n.bytes,c=o+n.byteOffset,l=Bc(a,c,c+t);return s?l:ll(l)},Tl=function(e,t,i,r,n,o){var s=$c(e),a=Mc(i),c=r(+n),l=!!o;if(a+t>s.byteLength)throw new al(Qc);for(var d=s.bytes,u=a+s.byteOffset,h=0;h<t;h++)d[u+h]=c[l?h:t-h-1]};if(Ac){var Sl=Jc&&el.name!==qc;Dc((function(){el(1)}))&&Dc((function(){new el(-1)}))&&!Dc((function(){return new el,new el(1.5),new el(NaN),1!==el.length||Sl&&!zc}))?Sl&&zc&&bc(el,"name",qc):((tl=function(e){return Nc(this,il),Hc(new el(Mc(e)),this,tl)})[Yc]=il,il.constructor=tl,jc(tl,el)),Uc&&Vc(nl)!==ol&&Uc(nl,ol);var El=new rl(new tl(2)),Il=Rc(nl.setInt8);El.setInt8(0,2147483648),El.setInt8(1,2147483649),!El.getInt8(0)&&El.getInt8(1)||wc(nl,{setInt8:function(e,t){Il(this,e,t<<24>>24)},setUint8:function(e,t){Il(this,e,t<<24>>24)}},{unsafe:!0})}else il=(tl=function(e){Nc(this,il);var t=Mc(e);Zc(this,{type:qc,bytes:cl(sl(t),0),byteLength:t}),Cc||(this.byteLength=t,this.detached=!1)})[Yc],nl=(rl=function(e,t,i){Nc(this,nl),Nc(e,il);var r=Xc(e),n=r.byteLength,o=Oc(t);if(o<0||o>n)throw new al("Wrong offset");if(o+(i=void 0===i?n-o:Pc(i))>n)throw new al("Wrong length");Zc(this,{type:Kc,buffer:e,byteLength:i,byteOffset:o,bytes:r.bytes}),Cc||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[Yc],Cc&&(vl(tl,"byteLength",Xc),vl(rl,"buffer",$c),vl(rl,"byteLength",$c),vl(rl,"byteOffset",$c)),wc(nl,{getInt8:function(e){return yl(this,1,e)[0]<<24>>24},getUint8:function(e){return yl(this,1,e)[0]},getInt16:function(e){var t=yl(this,2,e,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=yl(this,2,e,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return _l(yl(this,4,e,arguments.length>1&&arguments[1]))},getUint32:function(e){return _l(yl(this,4,e,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(e){return ul(yl(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return ul(yl(this,8,e,arguments.length>1&&arguments[1]),52)},setInt8:function(e,t){Tl(this,1,e,hl,t)},setUint8:function(e,t){Tl(this,1,e,hl,t)},setInt16:function(e,t){Tl(this,2,e,pl,t,arguments.length>2&&arguments[2])},setUint16:function(e,t){Tl(this,2,e,pl,t,arguments.length>2&&arguments[2])},setInt32:function(e,t){Tl(this,4,e,ml,t,arguments.length>2&&arguments[2])},setUint32:function(e,t){Tl(this,4,e,ml,t,arguments.length>2&&arguments[2])},setFloat32:function(e,t){Tl(this,4,e,fl,t,arguments.length>2&&arguments[2])},setFloat64:function(e,t){Tl(this,8,e,gl,t,arguments.length>2&&arguments[2])}});Wc(tl,qc),Wc(rl,Kc);var Rl={ArrayBuffer:tl,DataView:rl},Cl=z,Al=vn,bl=a,kl=rt("species"),wl=function(e){var t=Cl(e);bl&&t&&!t[kl]&&Al(t,kl,{configurable:!0,get:function(){return this}})},Dl=wl,Nl="ArrayBuffer",Ol=Rl[Nl];nn({global:!0,constructor:!0,forced:n[Nl]!==Ol},{ArrayBuffer:Ol}),Dl(Nl);var Pl=b,Ml=I,Ll=function(e){if("Function"===Pl(e))return Ml(e)},xl=nn,Vl=Ll,Ul=s,Fl=Lt,Bl=lr,Hl=hr,jl=Rl.ArrayBuffer,Wl=Rl.DataView,Gl=Wl.prototype,Jl=Vl(jl.prototype.slice),zl=Vl(Gl.getUint8),ql=Vl(Gl.setUint8);xl({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:Ul((function(){return!new jl(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(Jl&&void 0===t)return Jl(Fl(this),e);for(var i=Fl(this).byteLength,r=Bl(e,i),n=Bl(void 0===t?i:t,i),o=new jl(Hl(n-r)),s=new Wl(this),a=new Wl(o),c=0;r<n;)ql(a,c++,zl(s,r++));return o}});var Kl=I,Yl=s,Ql=H,Xl=hn,$l=li,Zl=function(){},ed=z("Reflect","construct"),td=/^\s*(?:class|function)\b/,id=Kl(td.exec),rd=!td.test(Zl),nd=function(e){if(!Ql(e))return!1;try{return ed(Zl,[],e),!0}catch(pH){return!1}},od=function(e){if(!Ql(e))return!1;switch(Xl(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return rd||!!id(td,$l(e))}catch(pH){return!0}};od.sham=!0;var sd,ad,cd,ld,dd=!ed||Yl((function(){var e;return nd(nd.call)||!nd(Object)||!nd((function(){e=!0}))||e}))?od:nd,ud=dd,hd=_e,pd=TypeError,md=function(e){if(ud(e))return e;throw new pd(hd(e)+" is not a constructor")},_d=Lt,fd=md,gd=P,vd=rt("species"),yd=function(e,t){var i,r=_d(e).constructor;return void 0===r||gd(i=_d(r)[vd])?t:fd(i)},Td=c,Sd=Function.prototype,Ed=Sd.apply,Id=Sd.call,Rd="object"==typeof Reflect&&Reflect.apply||(Td?Id.bind(Ed):function(){return Id.apply(Ed,arguments)}),Cd=ye,Ad=c,bd=Ll(Ll.bind),kd=function(e,t){return Cd(e),void 0===t?e:Ad?bd(e,t):function(){return e.apply(t,arguments)}},wd=TypeError,Dd=function(e,t){if(e<t)throw new wd("Not enough arguments");return e},Nd=/(?:ipad|iphone|ipod).*applewebkit/i.test(Q),Od=n,Pd=Rd,Md=kd,Ld=H,xd=We,Vd=s,Ud=Yn,Fd=ma,Bd=vt,Hd=Dd,jd=Nd,Wd=na,Gd=Od.setImmediate,Jd=Od.clearImmediate,zd=Od.process,qd=Od.Dispatch,Kd=Od.Function,Yd=Od.MessageChannel,Qd=Od.String,Xd=0,$d={},Zd="onreadystatechange";Vd((function(){sd=Od.location}));var eu=function(e){if(xd($d,e)){var t=$d[e];delete $d[e],t()}},tu=function(e){return function(){eu(e)}},iu=function(e){eu(e.data)},ru=function(e){Od.postMessage(Qd(e),sd.protocol+"//"+sd.host)};Gd&&Jd||(Gd=function(e){Hd(arguments.length,1);var t=Ld(e)?e:Kd(e),i=Fd(arguments,1);return $d[++Xd]=function(){Pd(t,void 0,i)},ad(Xd),Xd},Jd=function(e){delete $d[e]},Wd?ad=function(e){zd.nextTick(tu(e))}:qd&&qd.now?ad=function(e){qd.now(tu(e))}:Yd&&!jd?(ld=(cd=new Yd).port2,cd.port1.onmessage=iu,ad=Md(ld.postMessage,ld)):Od.addEventListener&&Ld(Od.postMessage)&&!Od.importScripts&&sd&&"file:"!==sd.protocol&&!Vd(ru)?(ad=ru,Od.addEventListener("message",iu,!1)):ad=Zd in Bd("script")?function(e){Ud.appendChild(Bd("script"))[Zd]=function(){Ud.removeChild(this),eu(e)}}:function(e){setTimeout(tu(e),0)});var nu={set:Gd,clear:Jd},ou=n,su=a,au=Object.getOwnPropertyDescriptor,cu=function(e){if(!su)return ou[e];var t=au(ou,e);return t&&t.value},lu=function(){this.head=null,this.tail=null};lu.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var du,uu,hu,pu,mu,_u=lu,fu=/ipad|iphone|ipod/i.test(Q)&&"undefined"!=typeof Pebble,gu=/web0s(?!.*chrome)/i.test(Q),vu=n,yu=cu,Tu=kd,Su=nu.set,Eu=_u,Iu=Nd,Ru=fu,Cu=gu,Au=na,bu=vu.MutationObserver||vu.WebKitMutationObserver,ku=vu.document,wu=vu.process,Du=vu.Promise,Nu=yu("queueMicrotask");if(!Nu){var Ou=new Eu,Pu=function(){var e,t;for(Au&&(e=wu.domain)&&e.exit();t=Ou.get();)try{t()}catch(pH){throw Ou.head&&du(),pH}e&&e.enter()};Iu||Au||Cu||!bu||!ku?!Ru&&Du&&Du.resolve?((pu=Du.resolve(void 0)).constructor=Du,mu=Tu(pu.then,pu),du=function(){mu(Pu)}):Au?du=function(){wu.nextTick(Pu)}:(Su=Tu(Su,vu),du=function(){Su(Pu)}):(uu=!0,hu=ku.createTextNode(""),new bu(Pu).observe(hu,{characterData:!0}),du=function(){hu.data=uu=!uu}),Nu=function(e){Ou.head||du(),Ou.add(e)}}var Mu=Nu,Lu=function(e){try{return{error:!1,value:e()}}catch(pH){return{error:!0,value:pH}}},xu=n.Promise,Vu=n,Uu=xu,Fu=H,Bu=Yr,Hu=li,ju=rt,Wu=ra,Gu=re;Uu&&Uu.prototype;var Ju=ju("species"),zu=!1,qu=Fu(Vu.PromiseRejectionEvent),Ku=Bu("Promise",(function(){var e=Hu(Uu),t=e!==String(Uu);if(!t&&66===Gu)return!0;if(!Gu||Gu<51||!/native code/.test(e)){var i=new Uu((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((i.constructor={})[Ju]=r,!(zu=i.then((function(){}))instanceof r))return!0}return!(t||"BROWSER"!==Wu&&"DENO"!==Wu||qu)})),Yu={CONSTRUCTOR:Ku,REJECTION_EVENT:qu,SUBCLASSING:zu},Qu={},Xu=ye,$u=TypeError,Zu=function(e){var t,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw new $u("Bad Promise constructor");t=e,i=r})),this.resolve=Xu(t),this.reject=Xu(i)};Qu.f=function(e){return new Zu(e)};var eh,th,ih,rh=nn,nh=na,oh=n,sh=u,ah=Zi,ch=cs,lh=Go,dh=wl,uh=ye,hh=H,ph=W,mh=Qa,_h=yd,fh=nu.set,gh=Mu,vh=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(pH){}},yh=Lu,Th=_u,Sh=Di,Eh=xu,Ih=Qu,Rh="Promise",Ch=Yu.CONSTRUCTOR,Ah=Yu.REJECTION_EVENT,bh=Yu.SUBCLASSING,kh=Sh.getterFor(Rh),wh=Sh.set,Dh=Eh&&Eh.prototype,Nh=Eh,Oh=Dh,Ph=oh.TypeError,Mh=oh.document,Lh=oh.process,xh=Ih.f,Vh=xh,Uh=!!(Mh&&Mh.createEvent&&oh.dispatchEvent),Fh="unhandledrejection",Bh=function(e){var t;return!(!ph(e)||!hh(t=e.then))&&t},Hh=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&&zh(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),n=!0)),i===e.promise?l(new Ph("Promise-chain cycle")):(r=Bh(i))?sh(r,i,c,l):c(i)):l(o)}catch(pH){d&&!n&&d.exit(),l(pH)}},jh=function(e,t){e.notified||(e.notified=!0,gh((function(){for(var i,r=e.reactions;i=r.get();)Hh(i,e);e.notified=!1,t&&!e.rejection&&Gh(e)})))},Wh=function(e,t,i){var r,n;Uh?((r=Mh.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),oh.dispatchEvent(r)):r={promise:t,reason:i},!Ah&&(n=oh["on"+e])?n(r):e===Fh&&vh("Unhandled promise rejection",i)},Gh=function(e){sh(fh,oh,(function(){var t,i=e.facade,r=e.value;if(Jh(e)&&(t=yh((function(){nh?Lh.emit("unhandledRejection",r,i):Wh(Fh,i,r)})),e.rejection=nh||Jh(e)?2:1,t.error))throw t.value}))},Jh=function(e){return 1!==e.rejection&&!e.parent},zh=function(e){sh(fh,oh,(function(){var t=e.facade;nh?Lh.emit("rejectionHandled",t):Wh("rejectionhandled",t,e.value)}))},qh=function(e,t,i){return function(r){e(t,r,i)}},Kh=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,jh(e,!0))},Yh=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new Ph("Promise can't be resolved itself");var r=Bh(t);r?gh((function(){var i={done:!1};try{sh(r,t,qh(Yh,i,e),qh(Kh,i,e))}catch(pH){Kh(i,pH,e)}})):(e.value=t,e.state=1,jh(e,!1))}catch(pH){Kh({done:!1},pH,e)}}};if(Ch&&(Oh=(Nh=function(e){mh(this,Oh),uh(e),sh(eh,this);var t=kh(this);try{e(qh(Yh,t),qh(Kh,t))}catch(pH){Kh(t,pH)}}).prototype,(eh=function(e){wh(this,{type:Rh,done:!1,notified:!1,parent:!1,reactions:new Th,rejection:!1,state:0,value:null})}).prototype=ah(Oh,"then",(function(e,t){var i=kh(this),r=xh(_h(this,Nh));return i.parent=!0,r.ok=!hh(e)||e,r.fail=hh(t)&&t,r.domain=nh?Lh.domain:void 0,0===i.state?i.reactions.add(r):gh((function(){Hh(r,i)})),r.promise})),th=function(){var e=new eh,t=kh(e);this.promise=e,this.resolve=qh(Yh,t),this.reject=qh(Kh,t)},Ih.f=xh=function(e){return e===Nh||undefined===e?new th(e):Vh(e)},hh(Eh)&&Dh!==Object.prototype)){ih=Dh.then,bh||ah(Dh,"then",(function(e,t){var i=this;return new Nh((function(e,t){sh(ih,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete Dh.constructor}catch(pH){}ch&&ch(Dh,Oh)}rh({global:!0,constructor:!0,wrap:!0,forced:Ch},{Promise:Nh}),lh(Nh,Rh,!1),dh(Rh);var Qh=Eo,Xh=rt("iterator"),$h=Array.prototype,Zh=function(e){return void 0!==e&&(Qh.Array===e||$h[Xh]===e)},ep=hn,tp=Ee,ip=P,rp=Eo,np=rt("iterator"),op=function(e){if(!ip(e))return tp(e,np)||tp(e,"@@iterator")||rp[ep(e)]},sp=u,ap=ye,cp=Lt,lp=_e,dp=op,up=TypeError,hp=function(e,t){var i=arguments.length<2?dp(e):t;if(ap(i))return cp(sp(i,e));throw new up(lp(e)+" is not iterable")},pp=u,mp=Lt,_p=Ee,fp=function(e,t,i){var r,n;mp(e);try{if(!(r=_p(e,"return"))){if("throw"===t)throw i;return i}r=pp(r,e)}catch(pH){n=!0,r=pH}if("throw"===t)throw i;if(n)throw r;return mp(r),i},gp=kd,vp=u,yp=Lt,Tp=_e,Sp=Zh,Ep=mr,Ip=q,Rp=hp,Cp=op,Ap=fp,bp=TypeError,kp=function(e,t){this.stopped=e,this.result=t},wp=kp.prototype,Dp=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),_=gp(t,d),f=function(e){return r&&Ap(r,"normal",e),new kp(!0,e)},g=function(e){return u?(yp(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=Cp(e)))throw new bp(Tp(e)+" is not iterable");if(Sp(n)){for(o=0,s=Ep(e);s>o;o++)if((a=g(e[o]))&&Ip(wp,a))return a;return new kp(!1)}r=Rp(e,n)}for(c=h?e.next:r.next;!(l=vp(c,r)).done;){try{a=g(l.value)}catch(pH){Ap(r,"throw",pH)}if("object"==typeof a&&a&&Ip(wp,a))return a}return new kp(!1)},Np=rt("iterator"),Op=!1;try{var Pp=0,Mp={next:function(){return{done:!!Pp++}},return:function(){Op=!0}};Mp[Np]=function(){return this},Array.from(Mp,(function(){throw 2}))}catch(pH){}var Lp=function(e,t){try{if(!t&&!Op)return!1}catch(pH){return!1}var i=!1;try{var r={};r[Np]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(pH){}return i},xp=xu,Vp=Yu.CONSTRUCTOR||!Lp((function(e){xp.all(e).then(void 0,(function(){}))})),Up=u,Fp=ye,Bp=Qu,Hp=Lu,jp=Dp;nn({target:"Promise",stat:!0,forced:Vp},{all:function(e){var t=this,i=Bp.f(t),r=i.resolve,n=i.reject,o=Hp((function(){var i=Fp(t.resolve),o=[],s=0,a=1;jp(e,(function(e){var c=s++,l=!1;a++,Up(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 Wp=nn,Gp=Yu.CONSTRUCTOR,Jp=xu,zp=z,qp=H,Kp=Zi,Yp=Jp&&Jp.prototype;if(Wp({target:"Promise",proto:!0,forced:Gp,real:!0},{catch:function(e){return this.then(void 0,e)}}),qp(Jp)){var Qp=zp("Promise").prototype.catch;Yp.catch!==Qp&&Kp(Yp,"catch",Qp,{unsafe:!0})}var Xp=u,$p=ye,Zp=Qu,em=Lu,tm=Dp;nn({target:"Promise",stat:!0,forced:Vp},{race:function(e){var t=this,i=Zp.f(t),r=i.reject,n=em((function(){var n=$p(t.resolve);tm(e,(function(e){Xp(n,t,e).then(i.resolve,r)}))}));return n.error&&r(n.value),i.promise}});var im=Qu;nn({target:"Promise",stat:!0,forced:Yu.CONSTRUCTOR},{reject:function(e){var t=im.f(this);return(0,t.reject)(e),t.promise}});var rm=Lt,nm=W,om=Qu,sm=function(e,t){if(rm(e),nm(t)&&t.constructor===e)return t;var i=om.f(e);return(0,i.resolve)(t),i.promise},am=nn,cm=Yu.CONSTRUCTOR,lm=sm;z("Promise"),am({target:"Promise",stat:!0,forced:cm},{resolve:function(e){return lm(this,e)}});var dm=nn,um=xu,hm=s,pm=z,mm=H,_m=yd,fm=sm,gm=Zi,vm=um&&um.prototype;if(dm({target:"Promise",proto:!0,real:!0,forced:!!um&&hm((function(){vm.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=_m(this,pm("Promise")),i=mm(e);return this.then(i?function(i){return fm(t,e()).then((function(){return i}))}:e,i?function(i){return fm(t,e()).then((function(){throw i}))}:e)}}),mm(um)){var ym=pm("Promise").prototype.finally;vm.finally!==ym&&gm(vm,"finally",ym,{unsafe:!0})}var Tm=W,Sm=b,Em=rt("match"),Im=Lt,Rm=function(){var e=Im(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},Cm=u,Am=We,bm=q,km=Rm,wm=RegExp.prototype,Dm=s,Nm=n.RegExp,Om=Dm((function(){var e=Nm("a","y");return e.lastIndex=2,null!==e.exec("abcd")})),Pm=Om||Dm((function(){return!Nm("a","y").sticky})),Mm=Om||Dm((function(){var e=Nm("^r","gy");return e.lastIndex=2,null!==e.exec("str")})),Lm={BROKEN_CARET:Mm,MISSED_STICKY:Pm,UNSUPPORTED_Y:Om},xm=Dt.f,Vm=s,Um=n.RegExp,Fm=Vm((function(){var e=Um(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)})),Bm=s,Hm=n.RegExp,jm=Bm((function(){var e=Hm("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Wm=a,Gm=n,Jm=I,zm=Yr,qm=Ec,Km=Yt,Ym=lo,Qm=er.f,Xm=q,$m=function(e){var t;return Tm(e)&&(void 0!==(t=e[Em])?!!t:"RegExp"===Sm(e))},Zm=_n,e_=function(e){var t=e.flags;return void 0!==t||"flags"in wm||Am(e,"flags")||!bm(wm,e)?t:Cm(km,e)},t_=Lm,i_=function(e,t,i){i in e||xm(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},r_=Zi,n_=s,o_=We,s_=Di.enforce,a_=wl,c_=Fm,l_=jm,d_=rt("match"),u_=Gm.RegExp,h_=u_.prototype,p_=Gm.SyntaxError,m_=Jm(h_.exec),__=Jm("".charAt),f_=Jm("".replace),g_=Jm("".indexOf),v_=Jm("".slice),y_=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,T_=/a/g,S_=/a/g,E_=new u_(T_)!==T_,I_=t_.MISSED_STICKY,R_=t_.UNSUPPORTED_Y,C_=Wm&&(!E_||I_||c_||l_||n_((function(){return S_[d_]=!1,u_(T_)!==T_||u_(S_)===S_||"/a/i"!==String(u_(T_,"i"))})));if(zm("RegExp",C_)){for(var A_=function(e,t){var i,r,n,o,s,a,c=Xm(h_,this),l=$m(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===A_)return e;if((l||Xm(h_,e))&&(e=e.source,d&&(t=e_(h))),e=void 0===e?"":Zm(e),t=void 0===t?"":Zm(t),h=e,c_&&"dotAll"in T_&&(r=!!t&&g_(t,"s")>-1)&&(t=f_(t,/s/g,"")),i=t,I_&&"sticky"in T_&&(n=!!t&&g_(t,"y")>-1)&&R_&&(t=f_(t,/y/g,"")),l_&&(o=function(e){for(var t,i=e.length,r=0,n="",o=[],s=Ym(null),a=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=__(e,r)))t+=__(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:if(n+=t,"?:"===v_(e,r+1,r+3))continue;m_(y_,v_(e,r+1))&&(r+=2,c=!0),l++;continue;case">"===t&&c:if(""===d||o_(s,d))throw new p_("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=qm(u_(e,t),c?this:h_,A_),(r||n||u.length)&&(a=s_(s),r&&(a.dotAll=!0,a.raw=A_(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=__(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+__(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Km(s,"source",""===h?"(?:)":h)}catch(pH){}return s},b_=Qm(u_),k_=0;b_.length>k_;)i_(A_,u_,b_[k_++]);h_.constructor=A_,A_.prototype=h_,r_(Gm,"RegExp",A_,{constructor:!0})}a_("RegExp");var w_=u,D_=I,N_=_n,O_=Rm,P_=Lm,M_=lo,L_=Di.get,x_=Fm,V_=jm,U_=Ve("native-string-replace",String.prototype.replace),F_=RegExp.prototype.exec,B_=F_,H_=D_("".charAt),j_=D_("".indexOf),W_=D_("".replace),G_=D_("".slice),J_=function(){var e=/a/,t=/b*/g;return w_(F_,e,"a"),w_(F_,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),z_=P_.BROKEN_CARET,q_=void 0!==/()??/.exec("")[1];(J_||q_||z_||x_||V_)&&(B_=function(e){var t,i,r,n,o,s,a,c=this,l=L_(c),d=N_(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=w_(B_,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=z_&&c.sticky,m=w_(O_,c),_=c.source,f=0,g=d;if(p&&(m=W_(m,"y",""),-1===j_(m,"g")&&(m+="g"),g=G_(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==H_(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),q_&&(i=new RegExp("^"+_+"$(?!\\s)",m)),J_&&(r=c.lastIndex),n=w_(F_,p?i:c,g),p?n?(n.input=G_(n.input,f),n[0]=G_(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:J_&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),q_&&n&&n.length>1&&w_(U_,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=M_(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=n[a[1]];return n});var K_=B_;nn({target:"RegExp",proto:!0,forced:/./.exec!==K_},{exec:K_});var Y_=or,Q_=_n,X_=x,$_=RangeError,Z_=I,ef=hr,tf=_n,rf=function(e){var t=Q_(X_(this)),i="",r=Y_(e);if(r<0||Infinity===r)throw new $_("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},nf=x,of=Z_(rf),sf=Z_("".slice),af=Math.ceil,cf=function(e){return function(t,i,r){var n,o,s=tf(nf(t)),a=ef(i),c=s.length,l=void 0===r?" ":tf(r);return a<=c||""===l?s:((o=of(l,af((n=a-c)/l.length))).length>n&&(o=sf(o,0,n)),e?s+o:o+s)}},lf={start:cf(!1),end:cf(!0)},df=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Q),uf=lf.start;nn({target:"String",proto:!0,forced:df},{padStart:function(e){return uf(this,e,arguments.length>1?arguments[1]:void 0)}});var hf=u,pf=Zi,mf=K_,_f=s,ff=rt,gf=Yt,vf=ff("species"),yf=RegExp.prototype,Tf=I,Sf=or,Ef=_n,If=x,Rf=Tf("".charAt),Cf=Tf("".charCodeAt),Af=Tf("".slice),bf=function(e){return function(t,i){var r,n,o=Ef(If(t)),s=Sf(i),a=o.length;return s<0||s>=a?e?"":void 0:(r=Cf(o,s))<55296||r>56319||s+1===a||(n=Cf(o,s+1))<56320||n>57343?e?Rf(o,s):r:e?Af(o,s,s+2):n-56320+(r-55296<<10)+65536}},kf={codeAt:bf(!1),charAt:bf(!0)},wf=kf.charAt,Df=I,Nf=Be,Of=Math.floor,Pf=Df("".charAt),Mf=Df("".replace),Lf=Df("".slice),xf=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Vf=/\$([$&'`]|\d{1,2})/g,Uf=u,Ff=Lt,Bf=H,Hf=b,jf=K_,Wf=TypeError,Gf=Rd,Jf=u,zf=I,qf=function(e,t,i,r){var n=ff(e),o=!_f((function(){var t={};return t[n]=function(){return 7},7!==""[e](t)})),s=o&&!_f((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[vf]=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===mf||s===yf.exec?o&&!n?{done:!0,value:hf(a,t,i,r)}:{done:!0,value:hf(e,i,t,r)}:{done:!1}}));pf(String.prototype,e,c[0]),pf(yf,n,c[1])}r&&gf(yf[n],"sham",!0)},Kf=s,Yf=Lt,Qf=H,Xf=P,$f=or,Zf=hr,eg=_n,tg=x,ig=function(e,t,i){return t+(i?wf(e,t).length:1)},rg=Ee,ng=function(e,t,i,r,n,o){var s=i+e.length,a=r.length,c=Vf;return void 0!==n&&(n=Nf(n),c=xf),Mf(o,c,(function(o,c){var l;switch(Pf(c,0)){case"$":return"$";case"&":return e;case"`":return Lf(t,0,i);case"'":return Lf(t,s);case"<":l=n[Lf(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Of(d/10);return 0===u?o:u<=a?void 0===r[u-1]?Pf(c,1):r[u-1]+Pf(c,1):o}l=r[d-1]}return void 0===l?"":l}))},og=function(e,t){var i=e.exec;if(Bf(i)){var r=Uf(i,e,t);return null!==r&&Ff(r),r}if("RegExp"===Hf(e))return Uf(jf,e,t);throw new Wf("RegExp#exec called on incompatible receiver")},sg=rt("replace"),ag=Math.max,cg=Math.min,lg=zf([].concat),dg=zf([].push),ug=zf("".indexOf),hg=zf("".slice),pg="$0"==="a".replace(/./,"$0"),mg=!!/./[sg]&&""===/./[sg]("a","$0"),_g=!Kf((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));qf("replace",(function(e,t,i){var r=mg?"$":"$0";return[function(e,i){var r=tg(this),n=Xf(e)?void 0:rg(e,sg);return n?Jf(n,e,r,i):Jf(t,eg(r),e,i)},function(e,n){var o=Yf(this),s=eg(e);if("string"==typeof n&&-1===ug(n,r)&&-1===ug(n,"$<")){var a=i(t,o,s,n);if(a.done)return a.value}var c=Qf(n);c||(n=eg(n));var l,d=o.global;d&&(l=o.unicode,o.lastIndex=0);for(var u,h=[];null!==(u=og(o,s))&&(dg(h,u),d);){""===eg(u[0])&&(o.lastIndex=ig(s,Zf(o.lastIndex),l))}for(var p,m="",_=0,f=0;f<h.length;f++){for(var g,v=eg((u=h[f])[0]),y=ag(cg($f(u.index),s.length),0),T=[],S=1;S<u.length;S++)dg(T,void 0===(p=u[S])?p:String(p));var E=u.groups;if(c){var I=lg([v],T,y,s);void 0!==E&&dg(I,E),g=eg(Gf(n,void 0,I))}else g=ng(v,s,y,T,E,n);y>=_&&(m+=hg(s,_,y)+g,_=y+v.length)}return m+hg(s,_)}]}),!_g||!pg||mg);var fg="\t\n\v\f\r \u2028\u2029\ufeff",gg=x,vg=_n,yg=fg,Tg=I("".replace),Sg=RegExp("^["+yg+"]+"),Eg=RegExp("(^|[^"+yg+"])["+yg+"]+$"),Ig=function(e){return function(t){var i=vg(gg(t));return 1&e&&(i=Tg(i,Sg,"")),2&e&&(i=Tg(i,Eg,"$1")),i}},Rg={start:Ig(1),end:Ig(2),trim:Ig(3)},Cg=ii.PROPER,Ag=s,bg=fg,kg=Rg.trim;nn({target:"String",proto:!0,forced:function(e){return Ag((function(){return!!bg[e]()||"
"!=="
"[e]()||Cg&&bg[e].name!==e}))}("trim")},{trim:function(){return kg(this)}});var wg,Dg,Ng,Og={exports:{}},Pg=Ja,Mg=a,Lg=n,xg=H,Vg=W,Ug=We,Fg=hn,Bg=_e,Hg=Yt,jg=Zi,Wg=vn,Gg=q,Jg=No,zg=cs,qg=rt,Kg=Ke,Yg=Di.enforce,Qg=Di.get,Xg=Lg.Int8Array,$g=Xg&&Xg.prototype,Zg=Lg.Uint8ClampedArray,ev=Zg&&Zg.prototype,tv=Xg&&Jg(Xg),iv=$g&&Jg($g),rv=Object.prototype,nv=Lg.TypeError,ov=qg("toStringTag"),sv=Kg("TYPED_ARRAY_TAG"),av="TypedArrayConstructor",cv=Pg&&!!zg&&"Opera"!==Fg(Lg.opera),lv=!1,dv={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},uv={BigInt64Array:8,BigUint64Array:8},hv=function(e){var t=Jg(e);if(Vg(t)){var i=Qg(t);return i&&Ug(i,av)?i[av]:hv(t)}},pv=function(e){if(!Vg(e))return!1;var t=Fg(e);return Ug(dv,t)||Ug(uv,t)};for(wg in dv)(Ng=(Dg=Lg[wg])&&Dg.prototype)?Yg(Ng)[av]=Dg:cv=!1;for(wg in uv)(Ng=(Dg=Lg[wg])&&Dg.prototype)&&(Yg(Ng)[av]=Dg);if((!cv||!xg(tv)||tv===Function.prototype)&&(tv=function(){throw new nv("Incorrect invocation")},cv))for(wg in dv)Lg[wg]&&zg(Lg[wg],tv);if((!cv||!iv||iv===rv)&&(iv=tv.prototype,cv))for(wg in dv)Lg[wg]&&zg(Lg[wg].prototype,iv);if(cv&&Jg(ev)!==iv&&zg(ev,iv),Mg&&!Ug(iv,ov))for(wg in lv=!0,Wg(iv,ov,{configurable:!0,get:function(){return Vg(this)?this[sv]:void 0}}),dv)Lg[wg]&&Hg(Lg[wg],sv,wg);var mv={NATIVE_ARRAY_BUFFER_VIEWS:cv,TYPED_ARRAY_TAG:lv&&sv,aTypedArray:function(e){if(pv(e))return e;throw new nv("Target is not a typed array")},aTypedArrayConstructor:function(e){if(xg(e)&&(!zg||Gg(tv,e)))return e;throw new nv(Bg(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(Mg){if(i)for(var n in dv){var o=Lg[n];if(o&&Ug(o.prototype,e))try{delete o.prototype[e]}catch(pH){try{o.prototype[e]=t}catch(s){}}}iv[e]&&!i||jg(iv,e,i?t:cv&&$g[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(Mg){if(zg){if(i)for(r in dv)if((n=Lg[r])&&Ug(n,e))try{delete n[e]}catch(pH){}if(tv[e]&&!i)return;try{return jg(tv,e,i?t:cv&&tv[e]||t)}catch(pH){}}for(r in dv)!(n=Lg[r])||n[e]&&!i||jg(n,e,t)}},getTypedArrayConstructor:hv,isView:function(e){if(!Vg(e))return!1;var t=Fg(e);return"DataView"===t||Ug(dv,t)||Ug(uv,t)},isTypedArray:pv,TypedArray:tv,TypedArrayPrototype:iv},_v=n,fv=s,gv=Lp,vv=mv.NATIVE_ARRAY_BUFFER_VIEWS,yv=_v.ArrayBuffer,Tv=_v.Int8Array,Sv=!vv||!fv((function(){Tv(1)}))||!fv((function(){new Tv(-1)}))||!gv((function(e){new Tv,new Tv(null),new Tv(1.5),new Tv(e)}),!0)||fv((function(){return 1!==new Tv(new yv(2),1,void 0).length})),Ev=W,Iv=Math.floor,Rv=Number.isInteger||function(e){return!Ev(e)&&isFinite(e)&&Iv(e)===e},Cv=or,Av=RangeError,bv=function(e){var t=Cv(e);if(t<0)throw new Av("The argument can't be less than 0");return t},kv=RangeError,wv=function(e,t){var i=bv(e);if(i%t)throw new kv("Wrong offset");return i},Dv=Math.round,Nv=hn,Ov=ut,Pv=TypeError,Mv=function(e){var t=Ov(e,"number");if("number"==typeof t)throw new Pv("Can't convert number to bigint");return BigInt(t)},Lv=kd,xv=u,Vv=md,Uv=Be,Fv=mr,Bv=hp,Hv=op,jv=Zh,Wv=function(e){var t=Nv(e);return"BigInt64Array"===t||"BigUint64Array"===t},Gv=mv.aTypedArrayConstructor,Jv=Mv,zv=function(e){var t,i,r,n,o,s,a,c,l=Vv(this),d=Uv(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=Hv(d);if(m&&!jv(m))for(c=(a=Bv(d,m)).next,d=[];!(s=xv(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=Lv(h,arguments[2])),i=Fv(d),r=new(Gv(l))(i),n=Wv(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?Jv(o):+o;return r},qv=aa,Kv=dd,Yv=W,Qv=rt("species"),Xv=Array,$v=function(e){var t;return qv(e)&&(t=e.constructor,(Kv(t)&&(t===Xv||qv(t.prototype))||Yv(t)&&null===(t=t[Qv]))&&(t=void 0)),void 0===t?Xv:t},Zv=kd,ey=O,ty=Be,iy=mr,ry=function(e,t){return new($v(e))(0===t?0:t)},ny=I([].push),oy=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=ty(c),_=ey(m),f=iy(_),g=Zv(l,d),v=0,y=u||ry,T=t?y(c,f):i||s?y(c,0):void 0;f>v;v++)if((a||v in _)&&(p=g(h=_[v],v,m),e))if(t)T[v]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return v;case 2:ny(T,h)}else switch(e){case 4:return!1;case 7:ny(T,h)}return o?-1:r||n?n:T}},sy={forEach:oy(0),map:oy(1),filter:oy(2),some:oy(3),every:oy(4),find:oy(5),findIndex:oy(6),filterReject:oy(7)},ay=mr,cy=nn,ly=n,dy=u,uy=a,hy=Sv,py=mv,my=Rl,_y=Qa,fy=v,gy=Yt,vy=Rv,yy=hr,Ty=ec,Sy=wv,Ey=function(e){var t=Dv(e);return t<0?0:t>255?255:255&t},Iy=mt,Ry=We,Cy=hn,Ay=W,by=pe,ky=lo,wy=q,Dy=cs,Ny=er.f,Oy=zv,Py=sy.forEach,My=wl,Ly=vn,xy=Dt,Vy=o,Uy=function(e,t,i){for(var r=0,n=arguments.length>2?i:ay(t),o=new e(n);n>r;)o[r]=t[r++];return o},Fy=Ec,By=Di.get,Hy=Di.set,jy=Di.enforce,Wy=xy.f,Gy=Vy.f,Jy=ly.RangeError,zy=my.ArrayBuffer,qy=zy.prototype,Ky=my.DataView,Yy=py.NATIVE_ARRAY_BUFFER_VIEWS,Qy=py.TYPED_ARRAY_TAG,Xy=py.TypedArray,$y=py.TypedArrayPrototype,Zy=py.isTypedArray,eT="BYTES_PER_ELEMENT",tT="Wrong length",iT=function(e,t){Ly(e,t,{configurable:!0,get:function(){return By(this)[t]}})},rT=function(e){var t;return wy(qy,e)||"ArrayBuffer"===(t=Cy(e))||"SharedArrayBuffer"===t},nT=function(e,t){return Zy(e)&&!by(t)&&t in e&&vy(+t)&&t>=0},oT=function(e,t){return t=Iy(t),nT(e,t)?fy(2,e[t]):Gy(e,t)},sT=function(e,t,i){return t=Iy(t),!(nT(e,t)&&Ay(i)&&Ry(i,"value"))||Ry(i,"get")||Ry(i,"set")||i.configurable||Ry(i,"writable")&&!i.writable||Ry(i,"enumerable")&&!i.enumerable?Wy(e,t,i):(e[t]=i.value,e)};uy?(Yy||(Vy.f=oT,xy.f=sT,iT($y,"buffer"),iT($y,"byteOffset"),iT($y,"byteLength"),iT($y,"length")),cy({target:"Object",stat:!0,forced:!Yy},{getOwnPropertyDescriptor:oT,defineProperty:sT}),Og.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=ly[n],c=a,l=c&&c.prototype,d={},u=function(e,t){Wy(e,t,{get:function(){return function(e,t){var i=By(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=By(e);o.view[s](t*r+o.byteOffset,i?Ey(n):n,!0)}(this,t,e)},enumerable:!0})};Yy?hy&&(c=t((function(e,t,i,n){return _y(e,l),Fy(Ay(t)?rT(t)?void 0!==n?new a(t,Sy(i,r),n):void 0!==i?new a(t,Sy(i,r)):new a(t):Zy(t)?Uy(c,t):dy(Oy,c,t):new a(Ty(t)),e,c)})),Dy&&Dy(c,Xy),Py(Ny(a),(function(e){e in c||gy(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,n){_y(e,l);var o,s,a,d=0,h=0;if(Ay(t)){if(!rT(t))return Zy(t)?Uy(c,t):dy(Oy,c,t);o=t,h=Sy(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw new Jy(tT);if((s=p-h)<0)throw new Jy(tT)}else if((s=yy(n)*r)+h>p)throw new Jy(tT);a=s/r}else a=Ty(t),o=new zy(s=a*r);for(Hy(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new Ky(o)});d<a;)u(e,d++)})),Dy&&Dy(c,Xy),l=c.prototype=ky($y)),l.constructor!==c&&gy(l,"constructor",c),jy(l).TypedArrayConstructor=c,Qy&&gy(l,Qy,n);var h=c!==a;d[n]=c,cy({global:!0,constructor:!0,forced:h,sham:!Yy},d),eT in c||gy(c,eT,r),eT in l||gy(l,eT,r),My(n)}):Og.exports=function(){};var aT=Og.exports;aT("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}})),aT("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var cT=vc,lT=Mv,dT=hn,uT=u,hT=s,pT=mv.aTypedArray,mT=mv.exportTypedArrayMethod,_T=I("".slice);mT("fill",(function(e){var t=arguments.length;pT(this);var i="Big"===_T(dT(this),0,3)?lT(e):+e;return uT(cT,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),hT((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e}))),(0,mv.exportTypedArrayStaticMethod)("from",zv,Sv);var fT=n,gT=u,vT=mv,yT=mr,TT=wv,ST=Be,ET=s,IT=fT.RangeError,RT=fT.Int8Array,CT=RT&&RT.prototype,AT=CT&&CT.set,bT=vT.aTypedArray,kT=vT.exportTypedArrayMethod,wT=!ET((function(){var e=new Uint8ClampedArray(2);return gT(AT,e,{length:1,0:3},1),3!==e[1]})),DT=wT&&vT.NATIVE_ARRAY_BUFFER_VIEWS&&ET((function(){var e=new RT(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));kT("set",(function(e){bT(this);var t=TT(arguments.length>1?arguments[1]:void 0,1),i=ST(e);if(wT)return gT(AT,this,i,t);var r=this.length,n=yT(i),o=0;if(n+t>r)throw new IT("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!wT||DT);var NT=Ll,OT=s,PT=ye,MT=va,LT=Ta,xT=Sa,VT=re,UT=Ia,FT=mv.aTypedArray,BT=mv.exportTypedArrayMethod,HT=n.Uint16Array,jT=HT&&NT(HT.prototype.sort),WT=!(!jT||OT((function(){jT(new HT(2),null)}))&&OT((function(){jT(new HT(2),{})}))),GT=!!jT&&!OT((function(){if(VT)return VT<74;if(LT)return LT<67;if(xT)return!0;if(UT)return UT<602;var e,t,i=new HT(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(jT(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));BT("sort",(function(e){return void 0!==e&&PT(e),GT?jT(this,e):MT(FT(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))}),!GT||WT);var JT={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},zT=vt("span").classList,qT=zT&&zT.constructor&&zT.constructor.prototype,KT=qT===Object.prototype?void 0:qT,YT=sy.forEach,QT=$s("forEach")?[].forEach:function(e){return YT(this,e,arguments.length>1?arguments[1]:void 0)},XT=n,$T=JT,ZT=KT,eS=QT,tS=Yt,iS=function(e){if(e&&e.forEach!==eS)try{tS(e,"forEach",eS)}catch(pH){e.forEach=eS}};for(var rS in $T)$T[rS]&&iS(XT[rS]&&XT[rS].prototype);iS(ZT);var nS=n,oS=JT,sS=KT,aS=Hs,cS=Yt,lS=Go,dS=rt("iterator"),uS=aS.values,hS=function(e,t){if(e){if(e[dS]!==uS)try{cS(e,dS,uS)}catch(pH){e[dS]=uS}if(lS(e,t,!0),oS[t])for(var i in aS)if(e[i]!==aS[i])try{cS(e,i,aS[i])}catch(pH){e[i]=aS[i]}}};for(var pS in oS)hS(nS[pS]&&nS[pS].prototype,pS);hS(sS,"DOMTokenList");var mS=kf.charAt,_S=_n,fS=Di,gS=ks,vS=ws,yS="String Iterator",TS=fS.set,SS=fS.getterFor(yS);gS(String,"String",(function(e){TS(this,{type:yS,string:_S(e),index:0})}),(function(){var e,t=SS(this),i=t.string,r=t.index;return r>=i.length?vS(void 0,!0):(e=mS(i,r),t.index+=e.length,vS(e,!1))}));var ES=s,IS=a,RS=rt("iterator"),CS=!ES((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&&!IS||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[RS]||"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})),AS=a,bS=I,kS=u,wS=s,DS=Hn,NS=wr,OS=h,PS=Be,MS=O,LS=Object.assign,xS=Object.defineProperty,VS=bS([].concat),US=!LS||wS((function(){if(AS&&1!==LS({b:1},LS(xS({},"a",{enumerable:!0,get:function(){xS(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!==LS({},e)[i]||DS(LS({},t)).join("")!==r}))?function(e,t){for(var i=PS(e),r=arguments.length,n=1,o=NS.f,s=OS.f;r>n;)for(var a,c=MS(arguments[n++]),l=o?VS(DS(c),o(c)):DS(c),d=l.length,u=0;d>u;)a=l[u++],AS&&!kS(s,c,a)||(i[a]=c[a]);return i}:LS,FS=Lt,BS=fp,HS=a,jS=Dt,WS=v,GS=kd,JS=u,zS=Be,qS=function(e,t,i,r){try{return r?t(FS(i)[0],i[1]):t(i)}catch(pH){BS(e,"throw",pH)}},KS=Zh,YS=dd,QS=mr,XS=function(e,t,i){HS?jS.f(e,t,WS(0,i)):e[t]=i},$S=hp,ZS=op,eE=Array,tE=I,iE=2147483647,rE=/[^\0-\u007E]/,nE=/[.\u3002\uFF0E\uFF61]/g,oE="Overflow: input needs wider integers to process",sE=RangeError,aE=tE(nE.exec),cE=Math.floor,lE=String.fromCharCode,dE=tE("".charCodeAt),uE=tE([].join),hE=tE([].push),pE=tE("".replace),mE=tE("".split),_E=tE("".toLowerCase),fE=function(e){return e+22+75*(e<26)},gE=function(e,t,i){var r=0;for(e=i?cE(e/700):e>>1,e+=cE(e/t);e>455;)e=cE(e/35),r+=36;return cE(r+36*e/(e+38))},vE=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=dE(e,i++);if(n>=55296&&n<=56319&&i<r){var o=dE(e,i++);56320==(64512&o)?hE(t,((1023&n)<<10)+(1023&o)+65536):(hE(t,n),i--)}else hE(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&&hE(t,lE(r));var c=t.length,l=c;for(c&&hE(t,"-");l<n;){var d=iE;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>cE((iE-s)/u))throw new sE(oE);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++s>iE)throw new sE(oE);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;hE(t,lE(fE(m+_%f))),h=cE(_/f),p+=36}hE(t,lE(fE(h))),a=gE(s,u,l===c),s=0,l++}}s++,o++}return uE(t,"")},yE=nn,TE=I,SE=lr,EE=RangeError,IE=String.fromCharCode,RE=String.fromCodePoint,CE=TE([].join);yE({target:"String",stat:!0,arity:1,forced:!!RE&&1!==RE.length},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,n=0;r>n;){if(t=+arguments[n++],SE(t,1114111)!==t)throw new EE(t+" is not a valid code point");i[n]=t<65536?IE(t):IE(55296+((t-=65536)>>10),t%1024+56320)}return CE(i,"")}});var AE=nn,bE=n,kE=cu,wE=z,DE=u,NE=I,OE=a,PE=CS,ME=Zi,LE=vn,xE=qa,VE=Go,UE=Xo,FE=Di,BE=Qa,HE=H,jE=We,WE=kd,GE=hn,JE=Lt,zE=W,qE=_n,KE=lo,YE=v,QE=hp,XE=op,$E=ws,ZE=Dd,eI=va,tI=rt("iterator"),iI="URLSearchParams",rI=iI+"Iterator",nI=FE.set,oI=FE.getterFor(iI),sI=FE.getterFor(rI),aI=kE("fetch"),cI=kE("Request"),lI=kE("Headers"),dI=cI&&cI.prototype,uI=lI&&lI.prototype,hI=bE.TypeError,pI=bE.encodeURIComponent,mI=String.fromCharCode,_I=wE("String","fromCodePoint"),fI=parseInt,gI=NE("".charAt),vI=NE([].join),yI=NE([].push),TI=NE("".replace),SI=NE([].shift),EI=NE([].splice),II=NE("".split),RI=NE("".slice),CI=NE(/./.exec),AI=/\+/g,bI=/^[0-9a-f]+$/i,kI=function(e,t){var i=RI(e,t,t+2);return CI(bI,i)?fI(i,16):NaN},wI=function(e){for(var t=0,i=128;i>0&&e&i;i>>=1)t++;return t},DI=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},NI=function(e){for(var t=(e=TI(e,AI," ")).length,i="",r=0;r<t;){var n=gI(e,r);if("%"===n){if("%"===gI(e,r+1)||r+3>t){i+="%",r++;continue}var o=kI(e,r+1);if(o!=o){i+=n,r++;continue}r+=2;var s=wI(o);if(0===s)n=mI(o);else{if(1===s||s>4){i+="�",r++;continue}for(var a=[o],c=1;c<s&&!(++r+3>t||"%"!==gI(e,r));){var l=kI(e,r+1);if(l!=l){r+=3;break}if(l>191||l<128)break;yI(a,l),r+=2,c++}if(a.length!==s){i+="�";continue}var d=DI(a);null===d?i+="�":n=_I(d)}}i+=n,r++}return i},OI=/[!'()~]|%20/g,PI={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},MI=function(e){return PI[e]},LI=function(e){return TI(pI(e),OI,MI)},xI=UE((function(e,t){nI(this,{type:rI,target:oI(e).entries,index:0,kind:t})}),iI,(function(){var e=sI(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,$E(void 0,!0);var r=t[i];switch(e.kind){case"keys":return $E(r.key,!1);case"values":return $E(r.value,!1)}return $E([r.key,r.value],!1)}),!0),VI=function(e){this.entries=[],this.url=null,void 0!==e&&(zE(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===gI(e,0)?RI(e,1):e:qE(e)))};VI.prototype={type:iI,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,s,a,c=this.entries,l=XE(e);if(l)for(i=(t=QE(e,l)).next;!(r=DE(i,t)).done;){if(o=(n=QE(JE(r.value))).next,(s=DE(o,n)).done||(a=DE(o,n)).done||!DE(o,n).done)throw new hI("Expected sequence with length 2");yI(c,{key:qE(s.value),value:qE(a.value)})}else for(var d in e)jE(e,d)&&yI(c,{key:d,value:qE(e[d])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,n=II(e,"&"),o=0;o<n.length;)(t=n[o++]).length&&(i=II(t,"="),yI(r,{key:NI(SI(i)),value:NI(vI(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],yI(i,LI(e.key)+"="+LI(e.value));return vI(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var UI=function(){BE(this,FI);var e=nI(this,new VI(arguments.length>0?arguments[0]:void 0));OE||(this.size=e.entries.length)},FI=UI.prototype;if(xE(FI,{append:function(e,t){var i=oI(this);ZE(arguments.length,2),yI(i.entries,{key:qE(e),value:qE(t)}),OE||this.length++,i.updateURL()},delete:function(e){for(var t=oI(this),i=ZE(arguments.length,1),r=t.entries,n=qE(e),o=i<2?void 0:arguments[1],s=void 0===o?o:qE(o),a=0;a<r.length;){var c=r[a];if(c.key!==n||void 0!==s&&c.value!==s)a++;else if(EI(r,a,1),void 0!==s)break}OE||(this.size=r.length),t.updateURL()},get:function(e){var t=oI(this).entries;ZE(arguments.length,1);for(var i=qE(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=oI(this).entries;ZE(arguments.length,1);for(var i=qE(e),r=[],n=0;n<t.length;n++)t[n].key===i&&yI(r,t[n].value);return r},has:function(e){for(var t=oI(this).entries,i=ZE(arguments.length,1),r=qE(e),n=i<2?void 0:arguments[1],o=void 0===n?n:qE(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=oI(this);ZE(arguments.length,1);for(var r,n=i.entries,o=!1,s=qE(e),a=qE(t),c=0;c<n.length;c++)(r=n[c]).key===s&&(o?EI(n,c--,1):(o=!0,r.value=a));o||yI(n,{key:s,value:a}),OE||(this.size=n.length),i.updateURL()},sort:function(){var e=oI(this);eI(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=oI(this).entries,r=WE(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 xI(this,"keys")},values:function(){return new xI(this,"values")},entries:function(){return new xI(this,"entries")}},{enumerable:!0}),ME(FI,tI,FI.entries,{name:"entries"}),ME(FI,"toString",(function(){return oI(this).serialize()}),{enumerable:!0}),OE&&LE(FI,"size",{get:function(){return oI(this).entries.length},configurable:!0,enumerable:!0}),VE(UI,iI),AE({global:!0,constructor:!0,forced:!PE},{URLSearchParams:UI}),!PE&&HE(lI)){var BI=NE(uI.has),HI=NE(uI.set),jI=function(e){if(zE(e)){var t,i=e.body;if(GE(i)===iI)return t=e.headers?new lI(e.headers):new lI,BI(t,"content-type")||HI(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),KE(e,{body:YE(0,qE(i)),headers:YE(0,t)})}return e};if(HE(aI)&&AE({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return aI(e,arguments.length>1?jI(arguments[1]):{})}}),HE(cI)){var WI=function(e){return BE(this,dI),new cI(e,arguments.length>1?jI(arguments[1]):{})};dI.constructor=WI,WI.prototype=dI,AE({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:WI})}}var GI,JI=nn,zI=a,qI=CS,KI=n,YI=kd,QI=I,XI=Zi,$I=vn,ZI=Qa,eR=We,tR=US,iR=function(e){var t=zS(e),i=YS(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=GS(n,r>2?arguments[2]:void 0));var s,a,c,l,d,u,h=ZS(t),p=0;if(!h||this===eE&&KS(h))for(s=QS(t),a=i?new this(s):eE(s);s>p;p++)u=o?n(t[p],p):t[p],XS(a,p,u);else for(a=i?new this:[],d=(l=$S(t,h)).next;!(c=JS(d,l)).done;p++)u=o?qS(l,n,[c.value,p],!0):c.value,XS(a,p,u);return a.length=p,a},rR=ma,nR=kf.codeAt,oR=function(e){var t,i,r=[],n=mE(pE(_E(e),nE,"."),".");for(t=0;t<n.length;t++)i=n[t],hE(r,aE(rE,i)?"xn--"+vE(i):i);return uE(r,".")},sR=_n,aR=Go,cR=Dd,lR={URLSearchParams:UI,getState:oI},dR=Di,uR=dR.set,hR=dR.getterFor("URL"),pR=lR.URLSearchParams,mR=lR.getState,_R=KI.URL,fR=KI.TypeError,gR=KI.parseInt,vR=Math.floor,yR=Math.pow,TR=QI("".charAt),SR=QI(/./.exec),ER=QI([].join),IR=QI(1..toString),RR=QI([].pop),CR=QI([].push),AR=QI("".replace),bR=QI([].shift),kR=QI("".split),wR=QI("".slice),DR=QI("".toLowerCase),NR=QI([].unshift),OR="Invalid scheme",PR="Invalid host",MR="Invalid port",LR=/[a-z]/i,xR=/[\d+-.a-z]/i,VR=/\d/,UR=/^0x/i,FR=/^[0-7]+$/,BR=/^\d+$/,HR=/^[\da-f]+$/i,jR=/[\0\t\n\r #%/:<>?@[\\\]^|]/,WR=/[\0\t\n\r #/:<>?@[\\\]^|]/,GR=/^[\u0000-\u0020]+/,JR=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,zR=/[\t\n\r]/g,qR=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)NR(t,e%256),e=vR(e/256);return ER(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+=IR(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},KR={},YR=tR({},KR,{" ":1,'"':1,"<":1,">":1,"`":1}),QR=tR({},YR,{"#":1,"?":1,"{":1,"}":1}),XR=tR({},QR,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),$R=function(e,t){var i=nR(e,0);return i>32&&i<127&&!eR(t,e)?e:encodeURIComponent(e)},ZR={ftp:21,file:null,http:80,https:443,ws:80,wss:443},eC=function(e,t){var i;return 2===e.length&&SR(LR,TR(e,0))&&(":"===(i=TR(e,1))||!t&&"|"===i)},tC=function(e){var t;return e.length>1&&eC(wR(e,0,2))&&(2===e.length||"/"===(t=TR(e,2))||"\\"===t||"?"===t||"#"===t)},iC=function(e){return"."===e||"%2e"===DR(e)},rC={},nC={},oC={},sC={},aC={},cC={},lC={},dC={},uC={},hC={},pC={},mC={},_C={},fC={},gC={},vC={},yC={},TC={},SC={},EC={},IC={},RC=function(e,t,i){var r,n,o,s=sR(e);if(t){if(n=this.parse(s))throw new fR(n);this.searchParams=null}else{if(void 0!==i&&(r=new RC(i,!0)),n=this.parse(s,null,r))throw new fR(n);(o=mR(new pR)).bindURL(this),this.searchParams=o}};RC.prototype={type:"URL",parse:function(e,t,i){var r,n,o,s,a,c=this,l=t||rC,d=0,u="",h=!1,p=!1,m=!1;for(e=sR(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=AR(e,GR,""),e=AR(e,JR,"$1")),e=AR(e,zR,""),r=iR(e);d<=r.length;){switch(n=r[d],l){case rC:if(!n||!SR(LR,n)){if(t)return OR;l=oC;continue}u+=DR(n),l=nC;break;case nC:if(n&&(SR(xR,n)||"+"===n||"-"===n||"."===n))u+=DR(n);else{if(":"!==n){if(t)return OR;u="",l=oC,d=0;continue}if(t&&(c.isSpecial()!==eR(ZR,u)||"file"===u&&(c.includesCredentials()||null!==c.port)||"file"===c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&ZR[c.scheme]===c.port&&(c.port=null));u="","file"===c.scheme?l=fC:c.isSpecial()&&i&&i.scheme===c.scheme?l=sC:c.isSpecial()?l=dC:"/"===r[d+1]?(l=aC,d++):(c.cannotBeABaseURL=!0,CR(c.path,""),l=SC)}break;case oC:if(!i||i.cannotBeABaseURL&&"#"!==n)return OR;if(i.cannotBeABaseURL&&"#"===n){c.scheme=i.scheme,c.path=rR(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=IC;break}l="file"===i.scheme?fC:cC;continue;case sC:if("/"!==n||"/"!==r[d+1]){l=cC;continue}l=uC,d++;break;case aC:if("/"===n){l=hC;break}l=TC;continue;case cC:if(c.scheme=i.scheme,n===GI)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=rR(i.path),c.query=i.query;else if("/"===n||"\\"===n&&c.isSpecial())l=lC;else if("?"===n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=rR(i.path),c.query="",l=EC;else{if("#"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=rR(i.path),c.path.length--,l=TC;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=rR(i.path),c.query=i.query,c.fragment="",l=IC}break;case lC:if(!c.isSpecial()||"/"!==n&&"\\"!==n){if("/"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=TC;continue}l=hC}else l=uC;break;case dC:if(l=uC,"/"!==n||"/"!==TR(u,d+1))continue;d++;break;case uC:if("/"!==n&&"\\"!==n){l=hC;continue}break;case hC:if("@"===n){h&&(u="%40"+u),h=!0,o=iR(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!==f||m){var g=$R(f,XR);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n===GI||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(h&&""===u)return"Invalid authority";d-=iR(u).length+1,u="",l=pC}else u+=n;break;case pC:case mC:if(t&&"file"===c.scheme){l=vC;continue}if(":"!==n||p){if(n===GI||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(c.isSpecial()&&""===u)return PR;if(t&&""===u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=yC,t)return;continue}"["===n?p=!0:"]"===n&&(p=!1),u+=n}else{if(""===u)return PR;if(s=c.parseHost(u))return s;if(u="",l=_C,t===mC)return}break;case _C:if(!SR(VR,n)){if(n===GI||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()||t){if(""!==u){var v=gR(u,10);if(v>65535)return MR;c.port=c.isSpecial()&&v===ZR[c.scheme]?null:v,u=""}if(t)return;l=yC;continue}return MR}u+=n;break;case fC:if(c.scheme="file","/"===n||"\\"===n)l=gC;else{if(!i||"file"!==i.scheme){l=TC;continue}switch(n){case GI:c.host=i.host,c.path=rR(i.path),c.query=i.query;break;case"?":c.host=i.host,c.path=rR(i.path),c.query="",l=EC;break;case"#":c.host=i.host,c.path=rR(i.path),c.query=i.query,c.fragment="",l=IC;break;default:tC(ER(rR(r,d),""))||(c.host=i.host,c.path=rR(i.path),c.shortenPath()),l=TC;continue}}break;case gC:if("/"===n||"\\"===n){l=vC;break}i&&"file"===i.scheme&&!tC(ER(rR(r,d),""))&&(eC(i.path[0],!0)?CR(c.path,i.path[0]):c.host=i.host),l=TC;continue;case vC:if(n===GI||"/"===n||"\\"===n||"?"===n||"#"===n){if(!t&&eC(u))l=TC;else if(""===u){if(c.host="",t)return;l=yC}else{if(s=c.parseHost(u))return s;if("localhost"===c.host&&(c.host=""),t)return;u="",l=yC}continue}u+=n;break;case yC:if(c.isSpecial()){if(l=TC,"/"!==n&&"\\"!==n)continue}else if(t||"?"!==n)if(t||"#"!==n){if(n!==GI&&(l=TC,"/"!==n))continue}else c.fragment="",l=IC;else c.query="",l=EC;break;case TC:if(n===GI||"/"===n||"\\"===n&&c.isSpecial()||!t&&("?"===n||"#"===n)){if(".."===(a=DR(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"===n||"\\"===n&&c.isSpecial()||CR(c.path,"")):iC(u)?"/"===n||"\\"===n&&c.isSpecial()||CR(c.path,""):("file"===c.scheme&&!c.path.length&&eC(u)&&(c.host&&(c.host=""),u=TR(u,0)+":"),CR(c.path,u)),u="","file"===c.scheme&&(n===GI||"?"===n||"#"===n))for(;c.path.length>1&&""===c.path[0];)bR(c.path);"?"===n?(c.query="",l=EC):"#"===n&&(c.fragment="",l=IC)}else u+=$R(n,QR);break;case SC:"?"===n?(c.query="",l=EC):"#"===n?(c.fragment="",l=IC):n!==GI&&(c.path[0]+=$R(n,KR));break;case EC:t||"#"!==n?n!==GI&&("'"===n&&c.isSpecial()?c.query+="%27":c.query+="#"===n?"%23":$R(n,KR)):(c.fragment="",l=IC);break;case IC:n!==GI&&(c.fragment+=$R(n,YR))}d++}},parseHost:function(e){var t,i,r;if("["===TR(e,0)){if("]"!==TR(e,e.length-1))return PR;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 TR(e,u)};if(":"===h()){if(":"!==TR(e,1))return;u+=2,d=++l}for(;h();){if(8===l)return;if(":"!==h()){for(t=i=0;i<4&&SR(HR,h());)t=16*t+gR(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(!SR(VR,h()))return;for(;SR(VR,h());){if(o=gR(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}(wR(e,1,-1)),!t)return PR;this.host=t}else if(this.isSpecial()){if(e=oR(e),SR(jR,e))return PR;if(t=function(e){var t,i,r,n,o,s,a,c=kR(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"===TR(n,0)&&(o=SR(UR,n)?16:8,n=wR(n,8===o?1:2)),""===n)s=0;else{if(!SR(10===o?BR:8===o?FR:HR,n))return e;s=gR(n,o)}CR(i,s)}for(r=0;r<t;r++)if(s=i[r],r===t-1){if(s>=yR(256,5-t))return null}else if(s>255)return null;for(a=RR(i),r=0;r<i.length;r++)a+=i[r]*yR(256,3-r);return a}(e),null===t)return PR;this.host=t}else{if(SR(WR,e))return PR;for(t="",i=iR(e),r=0;r<i.length;r++)t+=$R(i[r],KR);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return eR(ZR,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&eC(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+=qR(n),null!==o&&(l+=":"+o)):"file"===t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+ER(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw new fR(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new CC(e.path[0]).origin}catch(pH){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+qR(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(sR(e)+":",rC)},getUsername:function(){return this.username},setUsername:function(e){var t=iR(sR(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=$R(t[i],XR)}},getPassword:function(){return this.password},setPassword:function(e){var t=iR(sR(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=$R(t[i],XR)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?qR(e):qR(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,pC)},getHostname:function(){var e=this.host;return null===e?"":qR(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,mC)},getPort:function(){var e=this.port;return null===e?"":sR(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=sR(e))?this.port=null:this.parse(e,_C))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+ER(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,yC))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=sR(e))?this.query=null:("?"===TR(e,0)&&(e=wR(e,1)),this.query="",this.parse(e,EC)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=sR(e))?("#"===TR(e,0)&&(e=wR(e,1)),this.fragment="",this.parse(e,IC)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var CC=function(e){var t=ZI(this,AC),i=cR(arguments.length,1)>1?arguments[1]:void 0,r=uR(t,new RC(e,!1,i));zI||(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())},AC=CC.prototype,bC=function(e,t){return{get:function(){return hR(this)[e]()},set:t&&function(e){return hR(this)[t](e)},configurable:!0,enumerable:!0}};if(zI&&($I(AC,"href",bC("serialize","setHref")),$I(AC,"origin",bC("getOrigin")),$I(AC,"protocol",bC("getProtocol","setProtocol")),$I(AC,"username",bC("getUsername","setUsername")),$I(AC,"password",bC("getPassword","setPassword")),$I(AC,"host",bC("getHost","setHost")),$I(AC,"hostname",bC("getHostname","setHostname")),$I(AC,"port",bC("getPort","setPort")),$I(AC,"pathname",bC("getPathname","setPathname")),$I(AC,"search",bC("getSearch","setSearch")),$I(AC,"searchParams",bC("getSearchParams")),$I(AC,"hash",bC("getHash","setHash"))),XI(AC,"toJSON",(function(){return hR(this).serialize()}),{enumerable:!0}),XI(AC,"toString",(function(){return hR(this).serialize()}),{enumerable:!0}),_R){var kC=_R.createObjectURL,wC=_R.revokeObjectURL;kC&&XI(CC,"createObjectURL",YI(kC,_R)),wC&&XI(CC,"revokeObjectURL",YI(wC,_R))}aR(CC,"URL"),JI({global:!0,constructor:!0,forced:!qI,sham:!zI},{URL:CC});var DC=u;nn({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return DC(URL.prototype.toString,this)}});let NC=!0,OC=!0;function PC(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function MC(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 LC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(NC=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function xC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(OC=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function VC(){if("object"==typeof window){if(NC)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function UC(e,t){OC&&console.warn(e+" is deprecated, please use "+t+" instead.")}function FC(e){return"[object Object]"===Object.prototype.toString.call(e)}function BC(e){return FC(e)?Object.keys(e).reduce((function(t,i){const r=FC(e[i]),n=r?BC(e[i]):e[i],o=r&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[i]:n})}),{}):e}function HC(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?HC(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{HC(e,e.get(t),i)}))})))}function jC(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&&HC(e,i,n)}))})),n}const WC=VC;function GC(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),WC("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return WC("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 JC(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function zC(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 MC(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function qC(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 KC(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 YC(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=>jC(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}),MC(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>jC(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 QC(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 XC(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return QC(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 $C(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 ZC(e,t){MC(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var eA=Object.freeze({__proto__:null,shimMediaStream:JC,shimOnTrack:zC,shimGetSendersWithDtmf:qC,shimGetStats:KC,shimSenderReceiverGetStats:YC,shimAddTrackRemoveTrackWithNative:QC,shimAddTrackRemoveTrack:XC,shimPeerConnection:$C,fixNegotiationNeeded:ZC,shimGetUserMedia:GC,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 tA(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){UC("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 iA(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 rA(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(bb){if("TypeError"!==bb.name)throw bb;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,o)}}function nA(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 oA(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}),MC(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function sA(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){UC("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function aA(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function cA(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 lA(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 dA(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 uA(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 hA=Object.freeze({__proto__:null,shimOnTrack:iA,shimPeerConnection:rA,shimSenderGetStats:nA,shimReceiverGetStats:oA,shimRemoveStream:sA,shimRTCDataChannel:aA,shimAddTransceiver:cA,shimGetParameters:lA,shimCreateOffer:dA,shimCreateAnswer:uA,shimGetUserMedia:tA,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 pA(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 mA(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 _A(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 fA(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(gA(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function gA(e){return e&&void 0!==e.video?Object.assign({},e,{video:BC(e.video)}):e}function vA(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?(UC("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 yA(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 TA(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 SA(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var EA=Object.freeze({__proto__:null,shimLocalStreamsAPI:pA,shimRemoteStreamsAPI:mA,shimCallbacksAPI:_A,shimGetUserMedia:fA,shimConstraints:gA,shimRTCIceServerUrls:vA,shimTrackEventTransceiver:yA,shimCreateOfferLegacy:TA,shimAudioContext:SA}),IA={exports:{}};!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}(IA);var RA=IA.exports,CA=i(RA),AA=e({__proto__:null,default:CA},[RA]);function bA(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=CA.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,MC(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function kA(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||MC(e,"icecandidate",(e=>{if(e.candidate){const t=CA.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function wA(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=CA.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=CA.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=CA.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 DA(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},MC(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function NA(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 OA(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 PA(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 MA(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 LA=Object.freeze({__proto__:null,shimRTCIceCandidate:bA,shimRTCIceCandidateRelayProtocol:kA,shimMaxMessageSize:wA,shimSendThrowTypeError:DA,shimConnectionState:NA,removeExtmapAllowMixed:OA,shimAddIceCandidateNullOrEmpty:PA,shimParameterlessSetLocalDescription:MA});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=VC,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=PC(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=PC(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=PC(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:LA,extractVersion:PC,disableLog:LC,disableWarnings:xC,sdp:AA};switch(r.browser){case"chrome":if(!eA||!$C||!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=eA,PA(e,r),MA(e),GC(e,r),JC(e),$C(e,r),zC(e),XC(e,r),qC(e),KC(e),YC(e),ZC(e,r),bA(e),kA(e),NA(e),wA(e,r),DA(e),OA(e,r);break;case"firefox":if(!hA||!rA||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=hA,PA(e,r),MA(e),tA(e,r),rA(e,r),iA(e),sA(e),nA(e),oA(e),aA(e),cA(e),lA(e),dA(e),uA(e),bA(e),NA(e),wA(e,r),DA(e);break;case"safari":if(!EA||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=EA,PA(e,r),MA(e),vA(e),TA(e),_A(e),pA(e),mA(e),yA(e),fA(e),SA(e),bA(e),kA(e),wA(e,r),DA(e),OA(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var xA,VA=Object.create,UA=Object.defineProperty,FA=Object.defineProperties,BA=Object.getOwnPropertyDescriptor,HA=Object.getOwnPropertyDescriptors,jA=Object.getOwnPropertyNames,WA=Object.getOwnPropertySymbols,GA=Object.getPrototypeOf,JA=Object.prototype.hasOwnProperty,zA=Object.prototype.propertyIsEnumerable,qA=Reflect.get,KA=Math.pow,YA=(e,t,i)=>t in e?UA(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,QA=(e,t)=>{for(var i in t||(t={}))JA.call(t,i)&&YA(e,i,t[i]);if(WA)for(var i of WA(t))zA.call(t,i)&&YA(e,i,t[i]);return e},XA=(e,t)=>FA(e,HA(t)),$A=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ZA=(e,t)=>{for(var i in t)UA(e,i,{get:t[i],enumerable:!0})},eb=(e,t,i)=>(i=null!=e?VA(GA(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of jA(t))!JA.call(e,n)&&n!==i&&UA(e,n,{get:()=>t[n],enumerable:!(r=BA(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:UA(i,"default",{value:e,enumerable:!0}),e)),tb=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?BA(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&&UA(t,i,o),o},ib=(e,t,i)=>(YA(e,"symbol"!=typeof t?t+"":t,i),i),rb=(e,t,i)=>qA(GA(e),i,t),nb=(e,t,i)=>new Promise(((r,n)=>{var o=e=>{try{a(i.next(e))}catch(oP){n(oP)}},s=e=>{try{a(i.throw(e))}catch(oP){n(oP)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),ob=$A(((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)})),sb=$A(((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")}))}))})),ab=$A((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=sb(),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}}))}))}})),cb=$A(((e,t)=>{var i=sb(),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"}})),lb=$A((e=>{var t=ab(),i=cb(),r=sb();e.grammar=r,e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),db=$A(((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),ub=$A((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var n=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:n&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=db(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),hb=$A(((e,t)=>{var i=db(),r=/%[sdv%]/g,n=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},o=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||s,n=t.innerOrder||a,c=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),pb=$A((e=>{var t=ub(),i=hb();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),mb=eb(ob()),_b=((xA=_b||{})[xA.INVALID_PARAMETER=4096]="INVALID_PARAMETER",xA[xA.INVALID_OPERATION=4097]="INVALID_OPERATION",xA[xA.NOT_SUPPORTED=4098]="NOT_SUPPORTED",xA[xA.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",xA[xA.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",xA[xA.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",xA[xA.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",xA[xA.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",xA[xA.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",xA[xA.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",xA[xA.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",xA[xA.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",xA[xA.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",xA[xA.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",xA[xA.CLIENT_BANNED=16448]="CLIENT_BANNED",xA[xA.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",xA[xA.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",xA[xA.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",xA[xA.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",xA[xA.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",xA[xA.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",xA[xA.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",xA[xA.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",xA[xA.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",xA[xA.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",xA[xA.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",xA[xA.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",xA[xA.API_CALL_ABORTED=16461]="API_CALL_ABORTED",xA[xA.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",xA[xA.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",xA[xA.UNKNOWN=65535]="UNKNOWN",xA),fb=_b,gb=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=fb.UNKNOWN,extraCode:n=0,constraint:o}=e,s="<".concat(function(e){for(let t in fb)if(fb[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),ib(this,"code"),ib(this,"extraCode"),ib(this,"message"),ib(this,"originMessage"),ib(this,"name"),ib(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}},vb=gb,yb=((new Date).getTime(),0),Tb=function(){return(new Date).getTime()+yb},Sb=function(){let e=new Date;return e.setTime(Tb()),e.toLocaleString()},Eb={};ZA(Eb,{bytes2ms:()=>sO,convertObjectNumberToInt:()=>YO,copyProperties:()=>oO,deepClone:()=>FO,deepMerge:()=>UO,delay:()=>QO,fibonacci:()=>pO,formatedTime:()=>jO,getAbilityConfigUrl:()=>qN,getConstructorName:()=>bO,getContainerFromElement:()=>HO,getEnv:()=>XN,getInternalVersion:()=>OO,getLoggerUrl:()=>ZN,getMuteStateFromFlag:()=>LO,getNetworkType:()=>tO,getNumNetworkType:()=>nO,getReconnectionTimeout:()=>mO,getStringByteLength:()=>JO,getTurnServer:()=>xO,getUint32Version:()=>KO,getValueType:()=>_O,getViewListFromView:()=>BO,glog:()=>dO,ipv4ToUint32:()=>VO,isArray:()=>EO,isAudioWorkletSupported:()=>kO,isBoolean:()=>TO,isConstructor:()=>AO,isEmpty:()=>MO,isFunction:()=>fO,isLangChinese:()=>uO,isMediaStreamTrack:()=>IO,isNumber:()=>yO,isObject:()=>SO,isOverseaSdkAppId:()=>$N,isPlainObject:()=>hO,isPortrait:()=>zO,isPromise:()=>CO,isRemoteTrack:()=>RO,isString:()=>vO,isUndefined:()=>gO,loadImage:()=>qO,ms2bytes:()=>cO,ms2samples:()=>lO,performanceNow:()=>DO,promiseAny:()=>wO,samples2ms:()=>aO,setNetworkType:()=>rO,stringify:()=>WO,stringifyIncludeValue:()=>GO,throttlePromise:()=>XO});var Ib={};ZA(Ib,{AUDIO_MUTE_BIT:()=>lk,AUDIO_STAT_BIT:()=>ck,AUX_STAT_BIT:()=>ak,AUX_STREAM_MSID:()=>mk,BACKEND_ENV:()=>rk,BASE_DOC_URL:()=>Fb,BASE_HOST:()=>Lb,CAPABILITIES_KEYS:()=>ow,CLASS_NAME:()=>zk,CLOUD_CONSOLE_URL:()=>Ub,CROSS_ROOM_BIT:()=>hk,DATA_FREEZE_TIMING:()=>Fk,DOC_URL:()=>Bb,DTLS_STATE_UNKNOWN:()=>Rk,ENV_NAME:()=>Jb,EXCHANGE_SDP_TIMEOUT:()=>Mk,INTERVAL:()=>rw,IS_WORKER:()=>Db,IS_WORKLET:()=>Nb,KIBANA_EVENT:()=>Nk,LOCAL_STREAM_PUBLISH_STATE:()=>Uk,LOGGER_CMD_TYPE:()=>Gb,LOGGER_DOMAIN:()=>Hb,LOGGER_DOMAIN_OVERSEA:()=>jb,LOG_LEVEL:()=>zb,LOG_LEVEL_NAME:()=>Xk,MAIN_STREAM_MSID:()=>pk,MAX_RTT:()=>sw,MICROPHONE_COMMUNICATIONS:()=>Qk,MICROPHONE_DEFAULT:()=>Kk,MUTE_ALL_BIT:()=>uk,NAME:()=>tk,NETWORK_TYPE:()=>Yb,NOT_SUPPORTED_H264:()=>Vk,PAUSED_RETRY_COUNT:()=>qk,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Wk,PEER_CONNECTION_STATE:()=>Ck,PEER_LEAVE_REASON:()=>$k,RAF:()=>iw,RECOVER_CAPTURE_INTERVAL:()=>ew,REMOTE_STREAM_TYPE_AUX:()=>fk,REMOTE_STREAM_TYPE_MAIN:()=>_k,RENDER_FREEZE_TIMING:()=>Bk,RIC:()=>tw,SCHEDULE_DOMAIN:()=>Gk,SCHEDULE_TIMEOUT:()=>Jk,SDP_SEMANTICS_PLAN_B:()=>xk,SDP_SEMANTICS_UNIFIED_PLAN:()=>Lk,SECOND_HOST:()=>xb,SIGNAL_PING_PONG_INTERVAL:()=>Kb,SIGNAL_PING_TIMEOUT:()=>qb,SIGNAL_RECONNECTION_COUNT:()=>Dk,SMALL_STAT_BIT:()=>sk,SPEAKER_DEFAULT:()=>Yk,STORAGE_EXPIRES_TIME:()=>Qb,STREAM_TYPE_BIG:()=>Hk,STREAM_TYPE_SMALL:()=>jk,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Zk,SYNC_USER_LIST_INTERVAL:()=>Ok,Scene:()=>nk,Switch:()=>Xb,THIRD_HOST:()=>Vb,TIMEOUT:()=>nw,TRANSPORT_DIRECTION:()=>ik,TRTC_ERROR_ASSISTANCE:()=>Wb,TRTC_QUALITY_BAD:()=>Sk,TRTC_QUALITY_DISCONNECTED:()=>Ik,TRTC_QUALITY_EXCELLENT:()=>vk,TRTC_QUALITY_GOOD:()=>yk,TRTC_QUALITY_POOR:()=>Tk,TRTC_QUALITY_UNKNOWN:()=>gk,TRTC_QUALITY_VERY_BAD:()=>Ek,UPDATE_OFFER_TIMEOUT:()=>Pk,VIDEO_MUTE_BIT:()=>dk,VIDEO_STAT_BIT:()=>ok,audioProfileMap:()=>$b,getRetryCount:()=>kk,getScriptDir:()=>Ob,innerVersion:()=>Rb,loggerProxy:()=>Pb,screenProfileMap:()=>ek,setLoggerProxy:()=>Mb,setRetryCount:()=>bk,setVersion:()=>Ab,version:()=>Cb,videoProfileMap:()=>Zb});var Rb="4.15.00.1600",Cb="5.0.0";function Ab(e){Cb=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));Rb="".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 bb,kb,wb,Db="undefined"!=typeof importScripts,Nb="undefined"!=typeof registerProcessor,Ob=()=>{let e=Db?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Pb="",Mb=e=>Pb=e,Lb="web.sdk.qcloud.com",xb="web.sdk.tencent.cn",Vb="web.sdk.cloud.tencent.cn",Ub="https://console.cloud.tencent.com/trtc",Fb="https://".concat(Lb,"/trtc/webrtc/v5/doc"),Bb="".concat(Fb,"/zh-cn/"),Hb="https://yun.tim.qq.com",jb="https://apisgp.my-imcloud.com",Wb="trtc_error_assistance",Gb={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Jb={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},zb=((wb=zb||{})[wb.TRACE=0]="TRACE",wb[wb.DEBUG=1]="DEBUG",wb[wb.INFO=2]="INFO",wb[wb.WARN=3]="WARN",wb[wb.ERROR=4]="ERROR",wb[wb.NONE=5]="NONE",wb),qb=18e3,Kb=2e3,Yb={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Qb=6048e5,Xb=((kb=Xb||{}).USEAINS="useAINS",kb.ENABLEDEBUG="enableDebug",kb.USEV2="useV2",kb.USEWT="useWt",kb),$b={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}},Zb={"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}},ek={"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}},tk={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"},ik={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},rk={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},nk=((bb=nk||{}).LIVE="live",bb.RTC="rtc",bb),ok=1,sk=2,ak=4,ck=8,lk=64,dk=16,uk=112,hk=128,pk="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",mk="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",_k=tk.MAIN,fk=tk.AUXILIARY,gk=0,vk=1,yk=2,Tk=3,Sk=4,Ek=5,Ik=6,Rk="unknown",Ck={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Ak=1/0;function bk(e){Ak=e}function kk(){return Ak}var wk,Dk=30,Nk={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"},Ok=1e4,Pk=1e4,Mk=1e4,Lk="unified-plan",xk="plan-b",Vk=1028,Uk=((wk=Uk||{})[wk.UNPUBLISH=-1]="UNPUBLISH",wk[wk.PUBLISHING=0]="PUBLISHING",wk[wk.PUBLISHED=1]="PUBLISHED",wk),Fk=500,Bk=1e3,Hk=tk.BIG,jk=tk.SMALL,Wk=1e4,Gk={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"},Jk=2e3,zk={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},qk=5,Kk="default",Yk=Kk,Qk="communications",Xk=Object.keys(zb),$k=["normal leave","timeout leave","kick","role change"],Zk=10,ew=2e3,tw="ric",iw="raf",rw="interval",nw="timeout",ow=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],sw=1e4;function aw(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 cw(e){return nb(this,null,(function*(){let t=DO(),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 tP.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(DO()-t,"ms")),r}catch(wk){return i}}))}var lw=1e8,dw="API_CALL_TIMEOUT",uw="SIGNAL_CHANNEL_SETUP_FAILED",hw="ERROR_MESSAGE",pw="DOWNLINK_RECONNECTION_FAILED",mw="EXCHANGE_SDP_FAILED",_w="UPLINK_RECONNECTION_FAILED",fw="INVALID_PURE_AUDIO",gw="INVALID_USER_DEFINE_RECORDID",vw="INVALID_USER_DEFINE_PUSH_ARGS",yw="INVALID_JOIN",Tw="JOIN_ROOM_TIMEOUT",Sw="JOIN_ROOM_FAILED",Ew="REJOIN_ROOM_FAILED",Iw="INVALID_DESTROY",Rw="SUBSCRIBE_FAILED",Cw="SWITCH_ROLE_TIMEOUT",Aw="SWITCH_ROLE_FAILED",bw="REPEAT_JOIN",kw="CLIENT_DESTROYED",ww="PLAY_FAILED",Dw="NOT_SUPPORTED_HTTP",Nw="NOT_SUPPORTED_H264ENCODE",Ow="NOT_SUPPORTED_H264DECODE",Pw="MICROPHONE_NOT_FOUND",Mw="CAMERA_NOT_FOUND",Lw="SIGNAL_RESPONSE_FAILED",xw="CATCH_HANDLER_ERROR",Vw="CONNECTION_CLOSED",Uw="CALL_FREQUENCY_LIMIT",Fw="CONNECTION_ABORTED",Bw="API_CALL_ABORTED",Hw={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(_O(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(_O(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,"()")},jw={};ZA(jw,{ANDROID_VERSION:()=>tD,CHROME_MAJOR_VERSION:()=>iN,CHROME_VERSION:()=>rN,EDGE_VERSION:()=>cD,EDG_MAJOR_VERSION:()=>uD,EDG_VERSION:()=>dD,FIREFOX_MAJOR_VERSION:()=>sD,FIREFOX_VERSION:()=>oD,HUAWEI_VERSION:()=>JD,IE_VERSION:()=>ED,IOS_MAIN_VERSION:()=>lN,IOS_VERSION:()=>cN,IPADQQB_VERSION:()=>PD,IS_ANDROID:()=>eD,IS_ANDROID_WEBVIEW:()=>aN,IS_ANY_SAFARI:()=>oN,IS_CHROME:()=>eN,IS_CHROME_OS:()=>VD,IS_CHROMIUM_BASE:()=>ZD,IS_EDG:()=>lD,IS_EDGE:()=>aD,IS_ELECTRON:()=>BD,IS_FIREFOX:()=>nD,IS_HEADLESS_CHROME:()=>tN,IS_HUAWEI:()=>GD,IS_HUAWEIBROWSER:()=>WD,IS_IE:()=>SD,IS_IE8:()=>TD,IS_IOS:()=>Zw,IS_IOS_13_OR_14:()=>hN,IS_IOS_15_1:()=>uN,IS_IPAD:()=>Yw,IS_IPADQQB:()=>OD,IS_IPAD_PRO:()=>Qw,IS_IPHONE:()=>Xw,IS_IPOD:()=>$w,IS_LINUX:()=>xD,IS_LOCAL:()=>pN,IS_MAC:()=>LD,IS_MACQQB:()=>DD,IS_MIBROWSER:()=>HD,IS_MQQB:()=>AD,IS_NATIVE_ANDROID:()=>rD,IS_OLD_ANDROID:()=>iD,IS_OPPOBROWSER:()=>KD,IS_SAFARI:()=>nN,IS_SAFARI_15_1:()=>dN,IS_SAMSUNGBROWSER:()=>zD,IS_SOGOU:()=>mD,IS_SOGOUM:()=>hD,IS_TBS:()=>fD,IS_UCBROWSER:()=>FD,IS_VIVOBROWSER:()=>QD,IS_WECHAT:()=>ID,IS_WIN:()=>MD,IS_WQQB:()=>kD,IS_WX:()=>UD,IS_X5MQQB:()=>CD,IS_XWEB:()=>vD,MACQQB_VERSION:()=>ND,MI_VERSION:()=>jD,MQQB_VERSION:()=>bD,OPPO_VERSION:()=>YD,SAFARI_VERSION:()=>sN,SAMSUNG_VERSION:()=>qD,SOGOUM_VERSION:()=>pD,SOGOU_VERSION:()=>_D,TBS_VERSION:()=>gD,UA_DATA_STRING:()=>vN,USER_AGENT:()=>Ww,VIVO_VERSION:()=>XD,WECHAT_VERSION:()=>RD,WQQB_VERSION:()=>wD,XWEB_VERSION:()=>yD,browserInfo:()=>_N,getBrowserInfo:()=>fN,getChromeMajorVersion:()=>$D,getDeviceModel:()=>SN,getDeviceModelFromUA:()=>EN,getGPUInfo:()=>TN,getOSName:()=>RN,getOSNumber:()=>CN,getOSString:()=>AN,getOSType:()=>kN,getTerminalType:()=>bN,getUserAgentData:()=>yN,isLocalStorageEnabled:()=>mN});var Ww="undefined"==typeof navigator?"":navigator.userAgent,Gw=e=>new RegExp(e,"i").test(Ww),Jw=e=>{if(Gw(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=Ww.match(t);if(i&&i[1])return i[1]}return""},zw=e=>{if(Gw(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=Ww.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},qw=/AppleWebKit\/([\d.]+)/i.exec(Ww),Kw=qw?parseFloat(qw[1]):NaN,Yw=Gw("iPad"),Qw="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Gw("Macintosh"),Xw=Gw("iPhone")&&!Yw,$w=Gw("iPod"),Zw=Xw||Yw||$w||Qw,eD=Gw("Android"),tD=function(){if(eD){let e=Ww.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}(),iD=eD&&Gw("webkit")&&tD<2.3,rD=eD&&tD<5&&Kw<537,nD=Gw("Firefox"),oD=Jw("Firefox"),sD=zw("Firefox"),aD=Gw("Edge"),cD=Jw("Edge"),lD=Gw("Edg"),dD=Jw("Edg"),uD=zw("Edg"),hD=Gw("SogouMobileBrowser"),pD=Jw("SogouMobileBrowser"),mD=Gw("MetaSr\\s"),_D=Jw("MetaSr\\s"),fD=Gw("TBS"),gD=Jw("TBS"),vD=Gw("XWEB"),yD=Jw("XWEB"),TD=Gw("MSIE\\s8\\.0"),SD=Gw("MSIE\\/\\d+"),ED=function(){if(SD){let e=/MSIE\s(\d+)\.\d/.exec(Ww),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(Ww)&&/rv:11.0/.test(Ww)&&(t=11),t}return NaN}(),ID=Gw("(micromessenger|webbrowser)"),RD=Jw("MicroMessenger"),CD=!fD&&Gw("MQQBrowser")&&Gw("COVC"),AD=!fD&&Gw("MQQBrowser")&&!Gw("COVC"),bD=AD||CD?Jw("MQQBrowser"):"",kD=!fD&&Gw(" QQBrowser"),wD=Jw(" QQBrowser"),DD=!fD&&Gw("QQBrowserLite"),ND=Jw("QQBrowserLite"),OD=!fD&&Gw("MQBHD"),PD=Jw("MQBHD"),MD=Gw("Windows"),LD=!Zw&&Gw("MAC OS X"),xD=!eD&&Gw("Linux"),VD=Gw("CrOS"),UD=Gw("MicroMessenger"),FD=Gw("UCBrowser"),BD=Gw("Electron"),HD=Gw("MiuiBrowser"),jD=Jw("MiuiBrowser"),WD=Gw("HuaweiBrowser"),GD=Gw("Huawei"),JD=Jw("HuaweiBrowser"),zD=Gw("SamsungBrowser"),qD=Jw("SamsungBrowser"),KD=Gw("HeyTapBrowser"),YD=Jw("HeyTapBrowser"),QD=Gw("VivoBrowser"),XD=Jw("VivoBrowser"),$D=()=>zw("Chrome"),ZD=Gw("Chrome"),eN=!aD&&!mD&&!hD&&!fD&&!vD&&!lD&&!kD&&!HD&&!WD&&!zD&&!KD&&!QD&&ZD,tN=Gw("HeadlessChrome"),iN=$D(),rN=Jw("Chrome"),nN=!ZD&&!AD&&!CD&&!DD&&!OD&&Gw("Safari"),oN=nN||Zw,sN=Jw("Version"),aN=/Android.*(wv|.0.0.0)/.test(Ww),cN=(()=>{if(Qw)return sN;if(Zw){let e=Ww.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),lN=Number(cN.split(".")[0]),dN="15.1"===sN,uN="15.1"===cN,hN=(()=>{let e=Number(cN.split(".")[0]);return 14===e||13===e})(),pN="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),mN=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(sP){e=!1}return e}})(),_N=fN();function fN(){let e=new Map([[nD,["Firefox",oD]],[lD,["Edg",dD]],[eN,["Chrome",rN]],[nN,["Safari",sN]],[fD,["TBS",gD]],[vD,["XWEB",yD]],[ID&&Xw,["WeChat",RD]],[kD,["QQ(Win)",wD]],[AD,["QQ(Mobile)",bD]],[CD,["QQ(Mobile X5)",bD]],[DD,["QQ(Mac)",ND]],[OD,["QQ(iPad)",PD]],[HD,["MI",jD]],[WD,["HW",JD]],[zD,["Samsung",qD]],[KD,["OPPO",YD]],[QD,["VIVO",XD]],[aD,["EDGE",cD]],[hD,["SogouMobile",pD]],[mD,["Sogou",_D]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var gN=null,vN="";function yN(){return nb(this,null,(function*(){if(gN)return gN;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(gN=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!vN&&(vN="UAData: ".concat(gN.platform,"/").concat(gN.platformVersion),gN.architecture&&gN.bitness&&(vN+=" ".concat(gN.architecture,"/").concat(gN.bitness)),gN.mobile&&(vN+=" mobile"),gN.model&&(vN+=" model: ".concat(gN.model)),gN.fullVersionList&&(vN+=" ".concat(gN.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),gN}catch($x){return null}}))}function TN(){try{let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"";let i=t.getExtension("WEBGL_debug_renderer_info");if(i){let e=t.getParameter(i.UNMASKED_VENDOR_WEBGL),r=t.getParameter(i.UNMASKED_RENDERER_WEBGL);return"".concat(e," ").concat(r)}return""}catch($x){return""}}function SN(){return(null==gN?void 0:gN.model)||EN()||""}function EN(){let e=Ww.match(/;\s*([^;)]+)\s+Build\//);return null!=e&&e[1]?e[1].trim():null}var IN=new Map([[eD,"Android"],[Zw,"iOS"],[MD,"Windows"],[LD,"MacOS"],[xD,"Linux"],[VD,"ChromeOS"]]),RN=function(){return IN.get(!0)?IN.get(!0):gN?gN.platform:"unknown"};function CN(){return MD?1:eD?2:LD?3:Zw?4:xD?5:VD?6:0}var AN=()=>{let e=RN();return e+="/".concat(_N.name,"/").concat(nN?_N.version:_N.version.split(".")[0]),null!=gN&&gN.platformVersion&&(e+="/".concat(gN.platformVersion)),null!=gN&&gN.architecture&&(e+="/".concat(gN.architecture)),e};function bN(){return eD?4:Xw?2:Yw?3:LD?12:MD?5:xD?13:1}function kN(){return eD?"Android":Xw?"iPhone":Yw?"iPad":LD?"Mac":MD?"Windows":xD?"Linux":"unknown"}var wN=(e,t)=>t?"".concat(Fb,"/").concat(e,"/").concat(t):"".concat(Fb,"/").concat(e,"/index.html");function DN(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",s="",a="";fO(Hw[t])?o=Hw[t](i):vO(Hw[t])&&(o=Hw[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=(()=>{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(Wb);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{}})();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(fO(l[t])?a=l[t](i):vO(l[t])&&(a=l[t]));let d=o;return uO()&&(c&&c[t]&&(fO(c[t])?s=c[t](i):vO(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 NN=Object.prototype.hasOwnProperty,ON=e=>"function"==typeof e,PN=e=>void 0===e;function MN(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(NN.call(e,t))return!1;return!0}return!1}var LN,xN=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)=>nb(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<(ON(d)?d():d)?(h++,m=1,ON(n)&&n.call(this,h,t),p=window.setTimeout((()=>{p=-1,_(e,i)}),ON(u)?u(h):u)):(t(),ON(o)&&o.call(this,f))};ON(r)?r.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(_)}},VN=new(eb(ob(),1).default),UN=((LN=UN||{}).ROOM_DESTROY="1",LN.JOIN_START="21",LN.JOIN_SCHEDULE_SUCCESS="22",LN.JOIN_SIGNAL_CONNECTION_START="23",LN.JOIN_SIGNAL_CONNECTION_END="24",LN.JOIN_SEND_CMD="25",LN.JOIN_RECEIVED_CMD_RES="26",LN.JOIN_SUCCESS="27",LN.JOIN_FAILED="28",LN.LEAVE_START="51",LN.LEAVE_SEND_CMD="52",LN.LEAVE_SUCCESS="53",LN.PUBLISH_START="61",LN.SEND_FIRST_VIDEO_FRAME="62",LN.PUBLISH_FAILED="63",LN.SUBSCRIBE_START="81",LN.SUBSCRIBE_SUCCESS="82",LN.SUBSCRIBE_FAILED="84",LN.UNSUBSCRIBE_SUCCESS="83",LN.LOCAL_TRACK_CAPTURE_START="101",LN.LOCAL_TRACK_CAPTURE_SUCCESS="102",LN.LOCAL_TRACK_CAPTURE_FAILED="103",LN.LOCAL_TRACK_PUBLISHED="104",LN.LOCAL_TRACK_UNPUBLISHED="105",LN.LOCAL_TRACK_REPLACED="106",LN.SWITCH_DEVICE_SUCCESS="107",LN.TRACK_MUTED="108",LN.TRACK_UNMUTED="109",LN.REMOTE_TRACK_SUBSCRIBED="110",LN.REMOTE_TRACK_UNSUBSCRIBED="111",LN.LOCAL_TRACK_RECAPTURE="112",LN.PLAY_TRACK_START="151",LN.PLAYER_STATE_CHANGED="152",LN.VIDEO_LOADED_DATA="153",LN.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",LN.SIGNAL_CONNECTION_STATE_CHANGED="201",LN.PEER_CONNECTION_STATE_CHANGED="202",LN.SINGLE_CONNECTION_STAT="203",LN.SPC_RECONNECTED="204",LN.HEARTBEAT_REPORT="251",LN.RECEIVED_PUBLISHED_USER_LIST="252",LN.REMOTE_PUBLISH_STATE_CHANGED="253",LN.AUDIO_LEVEL_INTERVAL="260",LN.NETWORK_QUALITY="261",LN.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",LN.QUALITY_LIMITATION_CHANGED="263",LN.LOG="264",LN),FN=new class{constructor(){this._roomIdMap=new Map,"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:Cb,env:Jb.QCLOUD,browserVersion:_N.name+_N.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){pN||!tP.isAbleToUpload||this._configs.env===Jb.QCLOUD&&this.uploadEventToKibana(XA(QA({},e),{result:"success"}))}logFailedEvent(e){if(pN||!tP.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)||fb.UNKNOWN};this._configs.env===Jb.QCLOUD&&this.uploadEventToKibana(XA(QA({},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:Sb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:Cb,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+="\n".concat(r.stack))),this.sendRequest(ZN(this._configs.sdkAppId,Gb.LOG),n)}sendRequest(e,t){tP.isAbleToUpload?aw({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},BN=null,HN=!0;function jN(e){TO(e)&&e!==HN&&(HN=e,tP.info("setIsNeedToSchedule ".concat(e)))}function WN(e){return nb(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(!HN&&BN)return{isCached:!0,result:BN};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=DO(),h=yield function(e,t,i){return new Promise(((r,n)=>{let o=null;wO([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]=zN(i,tk.MAIN,!0)),n())}))(zN(i,tk.MAIN),e,{get timeout(){return 1e3*pO(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]=zN(i,tk.BACKUP,!0)),n())}))(zN(i,tk.BACKUP),e,{get timeout(){return 1e3*pO(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}(d,e,i);h.config&&(h.config.loggerDomain&&Mb(h.config.loggerDomain),TO(h.config.scheduleCache)&&jN(!h.config.scheduleCache)),e.delta=DO()-u;let p=function(e,t,i){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let n=performance.getEntriesByType("resource"),o=zN(e,tk.MAIN),s=zN(e,tk.BACKUP);for(let e of n)if(e.startTime>=i&&(e.name===o||e.name===s)&&e.transferSize>0){let i=e.name===o?tk.MAIN:tk.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];FN.uploadEvent({log:"stat-schedule-net:".concat(n,"(").concat(s,"(").concat(a,"->").concat(c,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=XA(QA({},r),{totalCost:n,local:s,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(o){tP.error("getScheduleDetailCost error",o)}return r}(Number(i),t,u);return BN=h,{isCached:!1,result:h,detailCost:p}}catch(d){let e=EO(d)?d[0]:d,t=yO(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),r=new vb({code:fb.SCHEDULE_FAILED,extraCode:t,message:DN({key:Sw,data:{error:i,code:t}})});throw tP.error(i,t),r}}()}))}document&&document.head.insertAdjacentHTML("beforeend",Object.values(Gk).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),VN.on("28",(()=>jN(!0))),VN.on("63",(()=>jN(!0))),VN.on("84",(()=>jN(!0))),VN.on("201",(e=>{"RECONNECTING"===e.state&&jN(!0)})),VN.on("202",(e=>{"RECONNECTING"===e.state&&jN(!0)}));var GN={main:"",backup:""};function JN(e){EO(e)?(GN.main=e[0],GN.backup=e[1]):GN.main=e}function zN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tk.MAIN,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return"https://".concat(GN[t]||KN(e,t,i),"/api/v1/config")}function qN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tk.MAIN;return"https://".concat(GN[t]||KN(e,t),"/api/v1/trtcAutoConf")}function KN(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tk.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return $N(e)?i===tk.MAIN?Gk.MAIN_OVERSEA:Gk.BACKUP_OVERSEA:(t=$N(e)?r?i===tk.MAIN?Gk.MAIN_OVERSEA_OLD:Gk.BACKUP_OVERSEA_OLD:i===tk.MAIN?Gk.MAIN_OVERSEA:Gk.BACKUP_OVERSEA:i===tk.MAIN?Gk.MAIN:Gk.BACKUP,t)}function YN(e,t,i){return new Promise(((r,n)=>{aw({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)=>xN({retryFunction:YN,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var XN=function(){return new URLSearchParams(location.search).get("trtc_env")||""},$N=e=>Number(e)<14e8,ZN=function(e,t){let i;i=Pb||($N(e)?jb:Hb);let r=Math.floor(Math.random()*KA(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},eO="unknown";function tO(){if("unknown"!==eO)return eO;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&&(eO=iO(r,n)),eO}function iO(e,t){if(Yb[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function rO(e){eO=iO(e)}function nO(){return Yb[tO()]}function oO(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 sO(e){return aO(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function aO(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function cO(e){return 4*lO(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function lO(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var dO="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},uO=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},hO=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 pO(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:pO(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function mO(e){return e>8?3e4:1e3*pO(e)}function _O(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var fO=e=>"function"==typeof e,gO=e=>void 0===e,vO=e=>"string"==typeof e,yO=e=>"number"==typeof e,TO=e=>"boolean"==typeof e,SO=e=>"object"===_O(e),EO=e=>"array"===_O(e),IO=e=>_O(e)==="MediaStreamTrack".toLowerCase(),RO=e=>e.isRemote,CO=e=>"promise"===_O(e),AO=e=>fO(e)&&e.prototype.constructor===e,bO=e=>AO(e)?e.prototype.constructor.name:"",kO="undefined"!=typeof AudioWorkletNode;function wO(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 DO(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var NO=e=>+e<10?"0".concat(e):e,OO=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=NO(i[1])+NO(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},PO=Object.prototype.hasOwnProperty;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(hO(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(PO.call(e,t))return!1;return!0}return!1}function LO(e,t){return{userId:t,hasAudio:!!(e&ck),hasVideo:!!(e&ok),hasAuxiliary:!!(e&ak),hasSmall:!!(e&sk),audioMuted:!!(e&lk),videoMuted:!!(e&dk),audioAvailable:!(!(e&ck)||e&lk),videoAvailable:!(!(e&ok)||e&dk)}}function xO(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!gO(e.username)&&!gO(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",gO(e.credentialType)||(t.credentialType=e.credentialType)),t}function VO(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!vO(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 UO=function(e,t,i,r){if(!SO(e)||!SO(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],!(gO(t[n])||i&&i.includes(n)))if(SO(e[n])&&SO(t[n]))o+=UO(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=FO(t[n]),o+=1)}return o};function FO(e){if(EO(e)){let t=[];return e.forEach(((e,i)=>{t[i]=FO(e)})),t}if(SO(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=FO(e[i])})),t}return e}var BO=e=>{let t=[];if(EO(e))t=[...e];else if(vO(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},HO=e=>vO(e)?document.getElementById(e):e,jO=()=>(e=>{let t=e=>e<10?"0".concat(e):"".concat(e),i=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),o=t(e.getHours()),s=t(e.getMinutes()),a=t(e.getSeconds());return"".concat(i,"/").concat(r,"/").concat(n," ").concat(o,":").concat(s,":").concat(a)})(new Date);function WO(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(EO(e))return"[".concat(e.map((e=>WO(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!hO(e)||!EO(i)&&!EO(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]=hO(e[s])||EO(e[s])?JSON.parse(WO(e[s],{keysToExclude:r,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(wk){return"{}"}}function GO(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)})),WO(e,{keysToInclude:i})}function JO(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var zO=()=>{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},qO=e=>nb(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(vO(e))r=new Image,r.crossOrigin="anonymous",r.src=e;else if(r=e,r.complete)return void t(r);r.onload=()=>t(r),r.onerror=()=>{i(new vb({code:fb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}}))})),KO=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},YO=e=>(Object.keys(e).forEach((t=>{yO(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(hO(e[t])||EO(e[t]))&&YO(e[t])})),e);function QO(e,t){return new Promise((i=>{let r=setTimeout(i,e);t&&t(r)}))}var XO=(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)}},$O=class{constructor(e){ib(this,"userId"),ib(this,"remoteUserId"),ib(this,"id"),ib(this,"sdkAppId"),ib(this,"type"),ib(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):"","]")),tP.log(e,t,PN(this.userId)||MN(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)}},ZO=UN,eP=!(Zw||eD||tN),tP=new class{constructor(){ib(this,"_isEnableUploadLog",!0),ib(this,"_localJoinedUser",new Map),ib(this,"_queue",[]),ib(this,"_timeoutId",-1),ib(this,"_logLevel",1),ib(this,"_logLevelToUpload",2),!Db&&!Nb&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){VN.on(ZO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&zb[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),VN.on(ZO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),VN.once(ZO.JOIN_FAILED,(()=>{this.startUpload()})),VN.on(ZO.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(vO(i.userId)&&yO(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 nb(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:Sb(),sdkAppId:String(r),userId:i,version:Cb,log:n.map((e=>e.log)).join("\n")}),r),n.forEach((e=>e.uploaded=!0))}}catch(kb){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return xN({retryFunction:()=>aw({url:ZN(t,Gb.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(zb[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){gO(zb[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(vO(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(bb){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(VN.emit(ZO.LOG,{log:s}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(s),e<this._logLevel)return;let a=(null==(o=zb[e])?void 0:o.toLowerCase())||"info";eP?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;zb[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}},iP=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)}))},rP=new class{constructor(){ib(this,"_prefix","TRTC"),ib(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){mN()&&(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(mN())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(sP){tP.warn(sP)}}getItem(e){if(!mN())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(bb){tP.warn(bb)}}setItem(e,t){if(mN())try{let i={expiresIn:Date.now()+Qb,value:t};this._queue.set(this.getRealKey(e),i)}catch(wk){tP.warn(wk)}}deleteItem(e){if(!mN())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(bb){return tP.warn(bb),!1}}clear(){if(mN())try{localStorage.clear()}catch(sP){tP.warn(sP)}}},nP={};ZA(nP,{HTTPS_API:()=>PP,IS_GET_CAPABILITIES_SUPPORTED:()=>$P,IS_GET_SETTINGS_SUPPORTED:()=>XP,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>QP,IS_INSERTABLE_STREAM_SUPPORTED:()=>ZP,IS_RTC_RTP_SENDER_SUPPORTED:()=>qP,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>eM,IS_SEI_SUPPORTED:()=>tM,IS_SPC_SUPPORTED:()=>JP,basis:()=>aM,checkSystemRequirementsInternal:()=>wP,decodeSupportStatus:()=>kP,encodeSupportStatus:()=>bP,getBrowserInfo:()=>TP,getDisplayResolution:()=>LP,isAddTransceiverSupported:()=>GP,isBrowserSupported:()=>SP,isGetReceiversSupported:()=>HP,isGetSendersSupported:()=>jP,isGetTransceiversSupported:()=>WP,isGetUserMediaSupported:()=>xP,isMediaDevicesSupported:()=>IP,isMediaSessionSupported:()=>nM,isMediaStreamTrackProcessorSupported:()=>AP,isReplaceTrackSupported:()=>KP,isRequestVideoFrameCallbackSupported:()=>lM,isSIMDSupported:()=>sM,isScreenCaptureApiAvailable:()=>NP,isSelectedCandidatePair:()=>MP,isSetParametersSupported:()=>YP,isSmallStreamAPISupported:()=>UP,isSmallStreamSupported:()=>FP,isStopTransceiverSupported:()=>zP,isTRTCSupported:()=>DP,isUnifiedPlanDefault:()=>BP,isUsedInHttpProtocol:()=>CP,isWebAudioSupported:()=>VP,isWebCodecSupported:()=>rM,isWebCodecsSupported:()=>EP,isWebRTCSupported:()=>iM,isWebTransportSupported:()=>oM});var oP,sP,aP=eb(lb(),1),cP=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.countMap=new Map,this.distributionMap=new Map,this.log=tP.createLogger({id:"kv"}),e&&(VN.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===tk.AUDIO?pP.START_MICROPHONE:mP.START_CAMERA,cost:i})})),VN.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===tk.AUDIO?pP.START_MICROPHONE:mP.START_CAMERA,error:i})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:KO(this.version||Cb),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(yO(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=fb.UNKNOWN;i&&(yO(i)?r=i:(!gO(i.extraCode)||!gO(i.code))&&(r=i.extraCode||i.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:r,useUV:!1})}},lP=(e=>(e[e.enterRoom=500700]="enterRoom",e[e.exitRoom=500701]="exitRoom",e[e.switchRole=500702]="switchRole",e[e.destroy=500703]="destroy",e[e.startLocalAudio=500704]="startLocalAudio",e[e.updateLocalAudio=500705]="updateLocalAudio",e[e.stopLocalAudio=500706]="stopLocalAudio",e[e.startLocalVideo=500707]="startLocalVideo",e[e.updateLocalVideo=500708]="updateLocalVideo",e[e.stopLocalVideo=500709]="stopLocalVideo",e[e.startScreenShare=500710]="startScreenShare",e[e.updateScreenShare=500711]="updateScreenShare",e[e.stopScreenShare=500712]="stopScreenShare",e[e.startRemoteVideo=500713]="startRemoteVideo",e[e.updateRemoteVideo=500714]="updateRemoteVideo",e[e.stopRemoteVideo=500715]="stopRemoteVideo",e[e.muteRemoteAudio=500716]="muteRemoteAudio",e[e.setRemoteAudioVolume=500717]="setRemoteAudioVolume",e[e.use=500718]="use",e[e.sendSEIMessage=5e5]="sendSEIMessage",e[e.sendCustomMessage=500001]="sendCustomMessage",e))(lP||{}),dP=((oP=dP||{})[oP.AudioMixer=550700]="AudioMixer",oP[oP.AIDenoiser=551700]="AIDenoiser",oP[oP.VirtualBackground=570700]="VirtualBackground",oP[oP.Beauty=571700]="Beauty",oP[oP.Watermark=572700]="Watermark",oP[oP.BasicBeauty=574700]="BasicBeauty",oP[oP.CDNStreaming=590700]="CDNStreaming",oP[oP.DeviceDetector=591700]="DeviceDetector",oP[oP.Debug=592700]="Debug",oP),uP=(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))(uP||{}),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||{}),pP=(e=>(e[e.START_MICROPHONE=501700]="START_MICROPHONE",e[e.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",e[e.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",e))(pP||{}),mP=((sP=mP||{})[sP.START_CAMERA=511700]="START_CAMERA",sP),_P=new cP(!0),fP=new cP(!1),gP=_P,vP={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},yP=new Map([[nD,["Firefox",oD]],[lD,["Edg",dD]],[eN,["Chrome",rN]],[nN,["Safari",sN]],[fD,["TBS",gD]],[vD,["XWEB",yD]],[ID&&Xw,["WeChat",RD]],[kD,["QQ(Win)",wD]],[AD,["QQ(Mobile)",bD]],[CD,["QQ(Mobile X5)",bD]],[DD,["QQ(Mac)",ND]],[OD,["QQ(iPad)",PD]],[HD,["MI",jD]],[WD,["HW",JD]],[zD,["Samsung",qD]],[KD,["OPPO",YD]],[QD,["VIVO",XD]],[aD,["EDGE",cD]],[hD,["SogouMobile",pD]],[mD,["Sogou",_D]]]);function TP(){let e=yP.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var SP=function(){return!(FD||aD||lD&&uD<80||nD&&sD<56)},EP=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},IP=function(){if(!navigator.mediaDevices)return CP()||tP.error(Hw.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},RP=!1;function CP(){return"http:"===location.protocol&&!pN&&(RP||tP.error(DN({key:Dw})),RP=!0,!0)}var AP=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},bP=function(){return nb(this,null,(function*(){if(vP.detail.isH264EncodeSupported&&vP.detail.isVp8EncodeSupported)return{isH264EncodeSupported:vP.detail.isH264EncodeSupported,isVp8EncodeSupported:vP.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection,n=document.createElement(tk.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(),vP.detail.isH264EncodeSupported=t,vP.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:vP.detail.isH264EncodeSupported,isVp8EncodeSupported:vP.detail.isVp8EncodeSupported}}catch(wk){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},kP=function(){return nb(this,null,(function*(){if(vP.detail.isH264DecodeSupported&&vP.detail.isVp8DecodeSupported)return{isH264DecodeSupported:vP.detail.isH264DecodeSupported,isVp8DecodeSupported:vP.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection;return e=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch(wk){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},wP=XO((()=>nb(void 0,null,(function*(){if(vP.result&&vP.detail.isH264EncodeSupported&&vP.detail.isVp8EncodeSupported&&vP.detail.isH264DecodeSupported&&vP.detail.isVp8DecodeSupported)return vP;let e=Date.now(),t=SP(),i=iM(),r=EP(),n=IP(),{isH264EncodeSupported:o,isVp8EncodeSupported:s}=yield bP(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield kP();if(!o||!s){let e=yield bP();tP.warn("detect encode again h264:".concat(o," vp8:").concat(s," result: ").concat(JSON.stringify(e))),o=e.isH264EncodeSupported,s=e.isVp8EncodeSupported}if(o&&a&&(KD||QD||aN)&&!fD&&$D()<79){let{encode:e,decode:t}=yield function(){return nb(this,null,(function*(){return OP||(OP=new Promise((e=>nb(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{tP.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=aP.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=aP.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval((()=>nb(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===tk.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===tk.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(r){i(),tP.warn(r),e(t)}})))).then((e=>((!e.encode||!e.decode)&&tP.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(vN)),e))),OP)}))}();o=e,a=t}return vP.result=t&&i&&n&&(o||s)&&(a||c),vP.detail.isBrowserSupported=t,vP.detail.isWebRTCSupported=i,vP.detail.isWebCodecsSupported=r,vP.detail.isMediaDevicesSupported=n,vP.detail.isScreenShareSupported=NP(),vP.detail.isSmallStreamSupported=FP(),vP.detail.isH264EncodeSupported=o,vP.detail.isVp8EncodeSupported=s,vP.detail.isH264DecodeSupported=a,vP.detail.isVp8DecodeSupported=c,vP.result||tP.error("".concat(navigator.userAgent," ").concat(GO(vP.detail,!1))),rP.setItem(cM,{ua:navigator.userAgent,checkResult:vP}),gP.addNumber({key:523800,value:Date.now()-e}),vP})))),DP=function(){return vP.result},NP=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},OP=null;var PP=(e,t,i)=>{"http:"===location.protocol&&!pN&&(e[t]=()=>{throw new vb({code:fb.INVALID_OPERATION,message:Hw.NOT_SUPPORTED_HTTP})})},MP=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(TO(e.selected)&&!e.selected)};function LP(){let e="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",i=screen.height?screen.height*window.devicePixelRatio:"";e+="".concat(t," * ").concat(i)}return e}function xP(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function VP(){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 UP(){return"captureStream"in HTMLCanvasElement.prototype}function FP(){return!(ID||Zw||iN&&iN<63)&&!(!SP()||!UP())}var BP=function(){if(gO(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:Lk}),e.addTransceiver(tk.AUDIO),t=!0}catch(bb){}return null==e||e.close(),t};function HP(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function jP(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function WP(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function GP(){return 11!==lN&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var JP=!(!GP()||ZD&&iN<86);function zP(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var qP="RTCRtpSender"in window;function KP(){return qP&&"replaceTrack"in window.RTCRtpSender.prototype}function YP(){return qP&&"setParameters"in window.RTCRtpSender.prototype&&jP()}var QP="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,XP=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,$P=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,ZP=qP&&"createEncodedStreams"in window.RTCRtpSender.prototype&&$D()>=86,eM="RTCRtpScriptTransform"in window,tM=qP&&(ZP||eM),iM=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function rM(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return gO(window.AudioDecoder)||(e.AudioDecoder=!0),gO(window.AudioEncoder)||(e.AudioEncoder=!0),gO(window.VideoDecoder)||(e.VideoDecoder=!0),gO(window.VideoEncoder)||(e.VideoEncoder=!0),gO(window.ImageDecoder)||(e.ImageDecoder=!0),e}function nM(){return"mediaSession"in navigator&&!gO(navigator.mediaSession.setActionHandler)}function oM(){return!gO(window.WebTransport)}function sM(){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 aM(){let e={browser:"".concat(_N.name,"/").concat(_N.version),os:RN(),displayResolution:LP(),isScreenShareSupported:NP(),isWebRTCSupported:iM(),isGetUserMediaSupported:xP(),isWebAudioSupported:VP(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:rM(),isMediaSessionSupported:nM(),isWebTransportSupported:oM()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var cM="checkResult";function lM(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}!function(){CP();let e=rP.getItem(cM);e&&e.ua===navigator.userAgent&&(vP=e.checkResult),wP()}();var dM=eb(ob(),1),uM=Symbol("instance"),hM=Symbol("cacheResult"),pM=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,vM.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},mM=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var _M=new Map;function fM(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=_M.get(r)||[];_M.has(r)||_M.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=yM.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return i.sync?r[hM]:Promise.resolve(r[hM]);r.state instanceof pM&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof pM&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new mM(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 mM(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 pM(u,t,s);vM.call(r,h);let p=e=>{var n;return r[hM]=e,h.aborted||(vM.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[hM])),e},m=e=>{let t=e instanceof Error?e.message:String(e);return vM.call(r,u,e),d(new mM(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 gM="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 vM(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(yM.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var yM=class extends dM.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=yM.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[uM];r?this.name=r.name+"-"+r.count++:i[uM]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=_M.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);_M.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=yM.instances.get(e),t||yM.instances.set(e,t=new yM(e,void 0,Object.create(yM.prototype)))):(t=yM.instances2.get(e),t||yM.instances2.set(e,t=new yM(e.constructor.name,void 0,Object.create(yM.prototype)))),t}static getState(e){var t;return null===(t=yM.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};gM(yM.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){vM.call(this,e)}};yM.STATECHANGED="stateChanged",yM.UPDATEAFSM="updateAFSM",yM.INIT="[*]",yM.ON="on",yM.OFF="off",yM.instances=new Map,yM.instances2=new WeakMap;var TM=(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)},SM=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},EM=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),IM=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nw,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=QA(e===rw?{delay:2e3,count:0,backgroundTask:!0}:e===tw?{delay:1e4,count:0}:e===iw?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),SO(t)&&(i=QA(QA({},i),t)),fO(e)&&(t=e,e=nw);let r=QA({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=DO(),r=()=>{if(t=DO()-i,t>=e.delay&&(i=DO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=TM(r,{timeout:e.delay})};return e.ricID=TM(r,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=DO(),r=()=>document.hidden&&e.backgroundTask?(t=DO()-i,i=DO(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(r,e.delay-Math.floor(t%e.delay))):(t=DO()-i,t>=e.delay&&(i=DO()-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=DO()-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&&EM(r),n&&SM(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)}};IM.taskMap=new Map,IM.currentTaskID=1;var RM=IM;tk.SEI_MESSAGE;var CM={LOADED_DATA:tk.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},AM={};ZA(AM,{create:()=>kM,remove:()=>wM});var bM=new WeakMap;function kM(e,t){bM.has(e)||bM.set(e,[]);let i=bM.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 wM(e){let t=bM.get(e);t&&(t.forEach((e=>e())),bM.delete(e))}var DM=new WeakMap;function NM(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,s){let a=xN({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=DM.get(e))&&t.has(o)?n():s(r)}),s,a):null!=(c=DM.get(e))&&c.has(o)?n():s(r)},onRetrying(t,i){var n;ON(r)&&r.call(this,t,i),null!=(n=DM.get(e))&&n.has(o)&&(DM.get(e).get(o).stopRetry=i)},onRetryFailed:n});return s.value=function(){let t=DM.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}):DM.set(e,new Map([[o,{args:r}]])),a.apply(this,r).finally((()=>{var t;return null==(t=DM.get(e))?void 0:t.delete(o)}))},s}}function OM(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=DM.get(e))&&n.has(t)){let{stopRetry:n,args:s}=DM.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=DM.get(e))||o.delete(t))}return s.apply(this,c)},o}}var PM=class extends yM{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,ib(this,"id"),ib(this,"element",null),ib(this,"track"),ib(this,"url"),ib(this,"attr"),ib(this,"muted"),ib(this,"_log"),ib(this,"_pausedRetryCount"),ib(this,"_isElementPlayingFired",!1),ib(this,"_interval"),ib(this,"_delayDestroyTimeoutId",0),ib(this,"_isReplayByRecreateMediaStreamCalled",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=qk,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){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 nb(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(bb){let t=DN({key:ww,data:{media:this.kind,error:bb}});if(this.track&&!this.track.muted&&this._log.warn(bb),t.includes("NotAllowedError"))throw new vb({code:fb.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(tk.ENDED),this._interval>0&&RM.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():uN?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 kM(this.element,this.element).add(tk.PLAYING,e).add(tk.ENDED,e).add(tk.PAUSE,e).add(tk.ERROR,e).add(tk.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==AM||AM.create(this.track,this.track).add(tk.ENDED,e).add(tk.MUTE,e).add(tk.UNMUTE,e),this.track.readyState===tk.ENDED&&this.handleTrackEvent({type:tk.ENDED}),this.track.muted&&this.handleTrackEvent({type:tk.MUTE})}}bindAutoPlayEvent(){VN.on(ZO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&wM(this.track)}unbindEvents(){this.element&&wM(this.element),this.unbindTrackEvents(),VN.off(ZO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case tk.PLAYING:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(tk.PLAYING),this._interval&&(RM.clearTask(this._interval),this._interval=-1);break;case tk.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(tk.ENDED);break;case tk.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(tk.PAUSE),Zw&&(this._interval=RM.run(nw,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case tk.ERROR:if(this.element&&this.element.error){this.handlePaused(tk.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)),FN.uploadEvent({log:"stat-".concat(this.kind,"-").concat(Nk.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),this.replayByRecreateMediaStream(this.element.error)}break;case tk.LOADEDDATA:this.kind===tk.VIDEO&&this.emit(CM.LOADED_DATA)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),FN.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),gP.addSuccessEvent({key:this.kind===tk.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),FN.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),gP.addFailedEvent({key:this.kind===tk.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(CM.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,i)=>{QO(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)}),QO(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 tk.ENDED:this.handleStopped(tk.ENDED);break;case tk.MUTE:this.handlePaused(tk.MUTE);break;case tk.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(tk.UNMUTE)}}handlePlaying(e){this.emit(CM.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(CM.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(CM.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};tb([NM({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],PM.prototype,"doReplayByRecreateMediaStream",1),tb([fM([],"PLAYING",{sync:!0})],PM.prototype,"handlePlaying",1),tb([fM("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],PM.prototype,"handlePaused",1),tb([fM([],"STOPPED",{sync:!0})],PM.prototype,"handleStopped",1);var MM="trtc_autoplay",LM="".concat(MM,"_mask"),xM="".concat(MM,"_wrapper"),VM="".concat(MM,"_header"),UM="".concat(MM,"_content"),FM="".concat(MM,"_action_wrapper"),BM="".concat(MM,"_question"),HM="".concat(MM,"_collapse"),jM="".concat(MM,"_action_confirm"),WM="".concat(MM,"_detail"),GM="#2473E8",JM="dialog",zM="".concat(JM,"-show"),qM="".concat(JM,"-1"),KM="".concat(JM,"-2"),YM=!1,QM=()=>!!document.querySelector(".".concat(xM)),XM="".concat(Fb,"/").concat(uO()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),$M="<br><a href='".concat(XM,"' target='_blank'>").concat(uO()?"其他方案?":"Any other solution?","</a>"),ZM="".concat(uO()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat($M):"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($M)),eL=class{constructor(){if(ib(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),ib(this,"_dialogNode",null),ib(this,"_bodyPosition",""),ib(this,"_showDetail",!1),ib(this,"_isCollapseClicked",!1),ib(this,"_isQuestionClicked",!1),uO()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!YM){let e=document.createElement("style");e.innerHTML=".".concat(LM,"{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(LM," div:not(.").concat(FM,"){display:block !important;}.").concat(xM,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(xM," a{color:").concat(GM,";}.").concat(VM,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(UM,"{margin:8px 0;}.").concat(FM,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(HM,"{margin-right:auto;cursor:pointer}.").concat(BM,"{height:100%;line-height:16px;cursor:pointer;}.").concat(jM,"{margin-left:8px;color:#fff;background:").concat(GM,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(jM,":hover{opacity:0.9;}.").concat(HM,",.").concat(jM,",.").concat(UM,",.").concat(BM,"{font-size:14px;}@media screen and (max-width:750px){.").concat(xM,"{width:80vw;}}"),document.head.appendChild(e),YM=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(LM,"\"><div class='").concat(xM,"'><div class='").concat(VM,"'>").concat(location.host,"</div><div class='").concat(UM,"'>").concat(this.content,"</div><div class='").concat(WM,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(ZM,"</div><div class='").concat(FM,"'></div></div></div>").trim();let t=document.createElement("button");t.className=jM,t.innerText=uO()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=BM,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=HM,r.innerText="".concat(uO()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(FM));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){QM()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(xM)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",tP.info("show autoplay dialog"),FN.uploadEvent({log:zM}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){tP.warn("confirm clicked, try resume stream"),VN.emit(ZO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(WM));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||FN.uploadEvent({log:qM}),this._isCollapseClicked=!0}onQuestionClick(){window.open(XM,"_blank"),this._isQuestionClicked||FN.uploadEvent({log:KM}),this._isQuestionClicked=!0}},tL=class extends PM{constructor(e){super(e,tk.VIDEO),ib(this,"viewMirror",!1),ib(this,"objectFit"),ib(this,"container"),ib(this,"canvas"),this.container=e.container,this.canvas=e.canvas,gO(e.viewMirror)||(this.viewMirror=e.viewMirror),gO(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var e;let t=document.createElement(tk.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(tk.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(tk.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){var t;super.handleElementEvent(e);let i=e.type;if(i===tk.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&&!QM()&&(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===tk.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):i===tk.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(CM.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 iL(e,t){return nb(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),tP.info("worklet addModule success")}catch(bb){throw tP.info("worklet addModule catch error. ".concat(bb.message)),bb}}))}"undefined"!=typeof window&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var rL=new window.AudioContext({sampleRate:48e3}),nL=()=>{"suspended"===rL.state?(rL.resume(),document.addEventListener("click",nL)):"interrupted"===rL.state?rL.resume():document.removeEventListener("click",nL)};document.addEventListener("click",nL),rL.onstatechange=()=>{tP.info("context state: ".concat(rL.state)),nL()};var oL=e=>rL,sL=class{constructor(){ib(this,"node"),ib(this,"pre",new Set),ib(this,"next",new Set),ib(this,"context"),ib(this,"connectedNodes",new Set),ib(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(),gP.addSuccessEvent({key:502701})}catch(wk){tP.error(wk),gP.addFailedEvent({key:502701,error:wk})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),gP.addSuccessEvent({key:502702})}catch(bb){tP.error(bb),gP.addFailedEvent({key:502702,error:bb})}}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}},aL=class extends sL{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,ib(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}},cL=class{constructor(){ib(this,"source",new sL),ib(this,"gain",new sL),ib(this,"destination",new sL)}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(hL(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}},lL=class extends cL{constructor(e){super(),this.context=e,ib(this,"denoiser",new sL),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()}},dL=class{constructor(){ib(this,"audioContext",oL()),ib(this,"destination",this.audioContext.createMediaStreamDestination()),ib(this,"inputs",new Set),ib(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]}},uL=new WeakMap;function hL(e){let t=uL.get(e);if(t)return t;let i=oL();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return uL.set(e,t),t}window.AudioWorkletProcessor||(window.AudioWorkletProcessor=class{constructor(){ib(this,"port")}});var pL=class extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=e=>{let{data:t}=e;switch(t.name){case"chunk":this.cache.push.apply(this.cache,t.data),this.sentFirstInfo1||(this.port.postMessage({cl:t.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=t.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(e,t){let i=e[0],r=t[0];if(!i&&!r)return!0;if(this.isStop)return!1;let n=r?r[0].length:0,o=this.cache.length;o>n?(r[0].set(this.cache.slice(0,n)),this.cache=this.cache.slice(n)):this.unmute&&r[0].set(i[0]);let s=o>n?r[0]:i[0];if(!s)return!0;let a=0;for(let c=0;c<s.length;++c)a=Math.max(Math.abs(s[c]),a);return this.volume=a,this.tick-=s.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,cacheLen:o,outputLen:n})),!0}},mL=pL.toString();delete window.AudioWorkletProcessor;var _L=class{constructor(e){this._volume=0,this._scriptProcessorNode=null,this._audioWorkletNode=null,this._interval=200,this.ready=this.preload();let{log:t}=e;this._log=t,VN.on(ZO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-_L.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!_L.workletReady){let e="".concat(mL.slice(0,5)," VolumeMeterWorklet ").concat(mL.slice(6),";registerProcessor('volume-meter', VolumeMeterWorklet);");_L.workletReady=iL(_L.audioContext,URL.createObjectURL(new Blob([e],{type:"application/javascript"})))}return _L.workletReady.then((()=>this.initAudioWorklet())).catch((e=>(this._log.error("volumeMeter preload error: ".concat(e)),this.initScriptProcessor())))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(_L.audioContext,"volume-meter");let e=!1;this._audioWorkletNode.port.onmessage=t=>{_L.lastMessageTime=Date.now(),this._volume=t.data.volume||0,!e&&t.data.cacheLen&&t.data.outputLen&&(this._log.warn("worklet play success"),e=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(sP){this._log.error("volumeMeter init audio worklet error: ".concat(sP)),FN.logFailedEvent({userId:this._log.userId,eventType:Nk.LOAD_WORKLET,error:sP}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=oL().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{_L.lastMessageTime=Date.now();let t=e.inputBuffer.getChannelData(0),i=0;for(let r=0;r<t.length;++r)i+=t[r]*t[r];this._volume=Math.sqrt(i/t.length)||0}}catch(sP){this._log.error("volumeMeter init script processor error: ".concat(sP))}}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,VN.off(ZO.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})}},fL=_L;fL.lastMessageTime=0,fL.audioContext=oL();var gL=class extends sL{constructor(e){super(),this._volumeMeter=new fL(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return nb(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()}}},vL=fL,yL=eb(ob(),1),TL=e=>t=>t.deviceId===e,SL=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";ib(this,"kind"),ib(this,"type"),ib(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&&RL(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(TL(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");tP.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(TL(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");tP.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},EL=class extends yL.EventEmitter{constructor(){super(),ib(this,"audioInputs",new SL(tk.AUDIO)),ib(this,"videoInputs",new SL(tk.VIDEO)),ib(this,"audioOutputs",new SL(tk.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||RM.run(rw,(()=>{this.update()}),{delay:1e4}))}init(){CL().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return nb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield CL(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},IL=Nb||Db?null:new EL;function RL(e){return e.deviceId===e.groupId&&""===e.groupId}function CL(){return nb(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(CP()||!IP())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{RL(e)&&(e.kind===tk.AUDIO_INPUT?i.audio=!0:e.kind===tk.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(kb){tP.debug("capture before getDevices failed: ",kb)}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&&DL.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function AL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return IL.update(e?1:0).then((e=>e.audioInputs.devices))}function bL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return IL.update(e?2:0).then((e=>e.videoInputs.devices))}var kL=!1;function wL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return nb(this,null,(function*(){return IL.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var DL=new Set;function NL(e,t){return nb(this,null,(function*(){let i=(yield AL()).find((e=>e.deviceId===Kk));return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t}))}var OL,PL=class extends cL{constructor(e){super(),this.log=e,ib(this,"volumeMeter"),ib(this,"volumeDestination"),ib(this,"analyser",new aL),this.volumeMeter=new gL({log:this.log}),this.volumeDestination=new sL,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},ML=class extends PM{constructor(e){super(e,tk.AUDIO),ib(this,"_outputDeviceId"),ib(this,"_volume",1),ib(this,"_destination",oL().createMediaStreamDestination()),ib(this,"pipeline"),ib(this,"volumeMeterMode","worklet"),this.pipeline=new PL(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if(("15.2"===cN||"15.3"===cN||"15.4"===cN)&&this.muted)return void this._log.info("audioElement is muted.");let e=OL||new Audio;e.setAttribute("autoplay","autoplay"),e.srcObject=this.getMediaStream(),e.muted=this.muted,this.element=e,e===OL&&(OL=void 0),this.bindElementEvents()}play(){return nb(this,null,(function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(oL().createAnalyser()),this.setVolume(this._volume),function(){nb(this,null,(function*(){try{kL||(kL=!0,tP.info("speakers:".concat((yield wL()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch($x){}}))}(),rb(ML.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 nb(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()}},LL=class extends ML{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(CM.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)}},xL=class extends ML{constructor(e){super(e),ib(this,"_sourceElement"),ib(this,"_output",new sL),this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this._output.setNode(oL().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(CM.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),wM(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&&oN&&(OL=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},VL=class extends yM{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:o=(1===r?xL:tL)}=e;var s;super(),ib(this,"id",iP()),ib(this,"userId",""),ib(this,"isRemote"),ib(this,"mediaType"),ib(this,"room"),ib(this,"user"),ib(this,"_log"),ib(this,"_inputTrack"),ib(this,"_outputTrack"),ib(this,"isPlayCalled"),ib(this,"container",null),ib(this,"player"),ib(this,"subVideoPlayerMap"),ib(this,"muted",!1),ib(this,"abortCtrl"),ib(this,"objectFit","cover"),ib(this,"mirror"),ib(this,"isScreen",!1),ib(this,"manager"),ib(this,"trackSettings"),this.userId=t||"",this.mediaType=r,this._log=tP.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=n||this.room)?void 0:s.userId,remoteUserId:this instanceof nx?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof nx}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(CM.PLAYER_STATE_CHANGED,(e=>{VN.emit(ZO.PLAYER_STATE_CHANGED,QA({track:this},e)),this.emit("player-state-changed",e)})),this.kind===tk.VIDEO&&(this.player.on(CM.LOADED_DATA,(()=>{VN.emit(ZO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(CM.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(CM.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||tP}get kind(){return 1===this.mediaType?tk.AUDIO:tk.VIDEO}get strMediaType(){return 4===this.mediaType?tk.VIDEO:2===this.mediaType?tk.SCREEN:tk.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 nb(this,null,(function*(){let i=EO(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!gO(t.muted)&&this.setPlayerMute(t.muted),t&&!gO(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof tL&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),EO(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!gO(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===tk.VIDEO)&&this.setPlayerMute(!0),t&&!gO(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof tL&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof tL&&this.player.setContainer(i)),VN.emit(ZO.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(),EO(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!==tk.VIDEO||gO(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(TO(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 nb(this,null,(function*(){if(!this._outputTrack||this.kind===tk.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&&(gO(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new tL({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(r+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let e of i)e.setViewMirror(this.player.mirror),yield e.play()}))}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return(null==(e=this.player)?void 0:e.getInternalAudioLevel())||0}stop(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(RO(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return nb(this,null,(function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),VN.emit(e?ZO.TRACK_MUTED:ZO.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){kM(e,e).add(tk.MUTE,this.onTrackMuted).add(tk.UNMUTE,this.onTrackUnmuted).add(tk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===tk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){wM(e)}setInputMediaStreamTrack(e){var t;let i=this._inputTrack;if(e!==i)return this._inputTrack=e,this.trackSettings=null==(t=e.getSettings)?void 0:t.call(e),e.enabled=!this.muted,i&&this.uninstallTrackEvent(i),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,i||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(t=e.getSettings)?void 0:t.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled)if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch((()=>this.handleAutoPlayFailed())),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(RO(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 eL;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof tL?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"))}};tb([fM([],yM.INIT,{sync:!0})],VL.prototype,"close",1);var UL=Object.prototype.hasOwnProperty;var FL=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(hO(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(UL.call(e,t))return!1;return!0}return!1},BL=xN({retryFunction:function(e){return nb(this,null,(function*(){let t=function(e){return{audio:jL(e),video:WL(e)}}(e);tP.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId"];t.audio&&(i=yield AL(),tP.info("microphones: ".concat(WO(i,{keysToInclude:n})))),t.video&&(r=yield bL(),tP.info("cameras: ".concat(WO(r,{keysToInclude:n}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return $P&&e.getTracks().forEach((e=>{tP.info("".concat(e.kind," capabilities: ").concat(WO(e.getCapabilities(),{keysToInclude:ow})))})),e}catch(o){let{message:t}=o;throw"NotFoundError"===o.name&&(e.video&&r&&0===r.length&&(t=DN({key:Mw})),e.audio&&i&&0===i.length&&(t=DN({key:Pw}))),new vb({code:fb.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,(!nN||n[0].width*n[0].height<=2073600)&&n[0].frameRate&&(n[0].frameRate=n[0].frameRate>10?10:5)),n[0].retryWhenExactFailed&&n[0].useExactDeviceId&&(n[0].useExactDeviceId=!1)):2===s?n[0].useDeviceIdOnly=!0:3===s&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&HL(n[0].microphoneId,!1),n[0].cameraId&&HL(n[0].cameraId,!0)},onRetrying:e=>{tP.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{FN.logFailedEvent({eventType:Nk.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{FN.logSuccessEvent({eventType:Nk.GET_USER_MEDIA_RETRY}),FN.uploadEvent({log:"stat-".concat(Nk.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function HL(e,t){return nb(this,null,(function*(){let i=(t?yield bL():yield AL()).find((t=>t.deviceId===e));i&&fO(i.getCapabilities)&&tP.warn(WO(i.getCapabilities(),{keysToInclude:ow}))}))}function jL(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!FL(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(yO(e.channelCount)&&(t.channelCount=e.channelCount),TO(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),TO(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),TO(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!FL(t)||t)}function WL(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&&!FL(i)?i:(e.width&&(i.width={ideal:e.width},t&&!nD&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!nD&&(i.height.max=e.height)),nD&&LD&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!FL(i)||i)}var GL=BL;function JL(e){return qL(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return nb(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function zL(e){return qL(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return nb(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function qL(e){return function(t,i,r){return r.value=e(r.value,i),r}}var KL=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&tP.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{tP.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),YL=0,QL=class{constructor(){this.log=tP.createLogger({id:"fq".concat(++YL)}),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=QA({},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()}))}},XL=new WeakMap,$L=new WeakMap;function ZL(){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=XL.get(this)||new QL;for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return XL.set(this,t),t.push({fn:n,args:r,context:this},e)},r}}function ex(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=XL.get(this))?void 0:t.queue)||i.forEach((e=>o.push(e))),null==(r=$L.get(this))||r.forEach((e=>null==e?void 0:e.queue.forEach((e=>o.push(e))))),o.forEach((t=>{t.reject(new vb({code:fb.API_CALL_ABORTED,message:e}))})),XL.delete(this),$L.delete(this),n.apply(this,a)},r}}function tx(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=$L.get(this)||new Map,s=r.get(o(t))||new QL;return r.set(o(t),s),$L.set(this,r),s.push({fn:n,args:t,context:this})},r}}function ix(e,t){return qL(((i,r)=>function(){let r=e;try{for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let e=i.apply(this,o),a=DO();return CO(e)?e.then((e=>(t?gP.addSuccessEvent({key:r,cost:DO()-a}):gP.addSuccessEvent({key:r}),e))).catch((e=>{throw gP.addFailedEvent({key:r,error:e}),e})):(gP.addSuccessEvent({key:r}),e)}catch(wb){throw gP.addFailedEvent({key:r,error:wb}),wb}}))}var rx=class extends VL{constructor(e,t){super({mediaType:e,PlayerClass:t}),ib(this,"isRemote",!1),ib(this,"deviceId"),ib(this,"groupId",""),ib(this,"label",""),ib(this,"_isRecapturing",!1),ib(this,"_lastRecaptureTime",0),ib(this,"_onMuteTimeoutId",-1),ib(this,"_encodeCheckTimeoutId",-1),ib(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return"publishing"===this.state.toString()}get isPublished(){return"publish"===this.state}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){kM(e,e).add(tk.MUTE,this.onTrackMuted).add(tk.UNMUTE,this.onTrackUnmuted).add(tk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===tk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){wM(e)}setStateToCapture(){}capture(e){return nb(this,null,(function*(){var t;try{let i,r=DO();VN.emit(ZO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield GL(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),VN.emit(ZO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:DO()-r}),i}catch(kb){throw VN.emit(ZO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:kb}),this.log.error("getUserMedia error observed ".concat(kb)),kb}}))}setInputMediaStreamTrack(e){return this.state===yM.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return null==(t=this.room)?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),VN.emit(ZO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return nb(this,null,(function*(){if(this.mediaTrack&&XP){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return nb(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==tk.AUDIO||t!==Kk||(yield NL(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),CL().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===tk.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(tk.AUDIO_INPUT);return!!DL.has(i)}(this.mediaTrack)||this.kind===tk.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(tk.VIDEO_INPUT);return!!DL.has(i)}(this.mediaTrack)||this._isRecapturing||e&&LD&&nN)}onTrackMuted(){if(super.onTrackMuted(),KL(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ew)return void setTimeout((()=>this.onTrackMuted()),ew);this._onMuteTimeoutId=setTimeout((()=>nb(this,null,(function*(){var e;if(null!=(e=this.mediaTrack)&&e.muted){if((Zw||eD)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return nb(this,null,(function*(){if(rb(rx.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<ew)return void setTimeout((()=>this.onTrackEnded()),ew);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return nb(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 AL():yield bL()).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}),VN.emit(ZO.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),VN.emit(ZO.LOCAL_TRACK_RECAPTURE,{track:this,error:e})}))}))}getRecoverCaptureDeviceId(){return nb(this,null,(function*(){let e=this instanceof lx;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(ox.get(t)||0)+1;if(ox.set(t,i),i>=3){let r=e?(yield bL()).find((e=>!ox.has(e.deviceId))):(yield AL()).find((e=>!ox.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)}},nx=rx;tb([fM(yM.INIT,"capture",{ignoreError:!0,sync:!0})],nx.prototype,"setStateToCapture",1),tb([ZL()],nx.prototype,"capture",1),tb([fM("capture","publish",{ignoreError:!0,success(){var e,t;this.room.localTracks.add(this),VN.emit(ZO.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout((()=>{var e,t;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let e=this.kind===tk.AUDIO,t=this.stat.bytesSent>0;gP[t?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),t||(gP.addEnum({key:e?503701:513703,value:CN()}),FN.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(SN()||AN()),userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}}),5e3))},fail(e){let t="error",i=e.cause;i.message.includes("timeout")?t="timeout":i.code===fb.API_CALL_ABORTED&&(t="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:i})}}),ix(521714,!1)],nx.prototype,"publish",1),tb([qL((e=>function(){return nb(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)}))})),fM([],"capture",{sync:!0})],nx.prototype,"unpublish",1);var ox=new Map;VN.on(ZO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&ox.delete(e.track.deviceId)}));var sx=class extends nx{constructor(e){super(1,LL),ib(this,"mediaType",1),ib(this,"volume",0),ib(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),ib(this,"playerMuted",!0),ib(this,"pipeline"),ib(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),this.manager=e,this.pipeline=new lL(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 nb(this,null,(function*(){yield rb(sx.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};gP.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),gP.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),gP.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=!0}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,customSource:i})}switchDevice(e){return nb(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==Kk)return;if(yield NL(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),this.room&&(yield this.room.replaceTrack(this)),VN.emit(ZO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(wk){throw this.log.error("switch microphone failed ".concat(wk)),this.deviceId&&this.recapture(this.deviceId),wk}}}))}listenDeviceChange(){IL&&!IL.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&IL.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return nb(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e))),gV(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield AL();t[0]?this.recapture(t[0].deviceId):IL.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return nb(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:n}=e;return function*(){let e=!1;!gO(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!gO(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,e=!0),!gO(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&&gP.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;iN<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(gP.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(),IL.off("audioInputAdded",this.handleMicrophoneAdded,this),IL.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return nb(this,null,(function*(){try{yield rb(sx.prototype,this,"recapture").call(this,e)}catch(wk){let i=(yield AL()).find((t=>t.deviceId!==e));if(!i)throw wk;yield rb(sx.prototype,this,"recapture").call(this,i.deviceId)}}))}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduce(((e,t)=>t?t({frame:e}):e),e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}},ax=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}},cx=class{constructor(){ib(this,"_seiMessageList",[]),ib(this,"_smallSeiMessageList",[]),ib(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 ax(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}},lx=class extends nx{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,tL),ib(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),ib(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0}),ib(this,"small"),ib(this,"isNeedToSetBandwidth"),ib(this,"muteImage"),ib(this,"manager"),ib(this,"_seiCodec",new cx),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(XA(QA({},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(XP&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}setMute(e){return nb(this,null,(function*(){var t,i,r;if(vO(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,rb(lx.prototype,this,"setMute").call(this,!1)}else yield null==(r=this.manager)?void 0:r.deleteWatermark("mute"),this.muteImage=void 0,rb(lx.prototype,this,"setMute").call(this,e)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:r=!0,customSource:n,retryWhenExactFailed:o=!0}=e;return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:o,customSource:n})}setProfile(e){let t=QA({},e),i=t.width>t.height;t.width*t.height<=19200&&eD&&ZD&&(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));let r=SN();"SM-A032F"===r&&t.width*t.height<=76800&&(this._log.warn("fallback profile to 240p_2 on ".concat(r)),t.width=i?320:240,t.height=i?240:320,t.bitrate=200),t.width*t.height>921600&&hN&&(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(XA(QA({},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:tk.VIDEO,videoType:tk.BIG})})):void 0}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return XP&&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:zO()&&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 nb(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),VN.emit(ZO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(wk){throw this.log.error("switch camera failed ".concat(wk)),this.deviceId&&this.recapture(this.deviceId),wk}}))}listenDeviceChange(){IL&&!IL.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&IL.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return nb(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e))),gV(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield bL();t[0]?this.recapture(t[0].deviceId):IL.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return nb(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}encodeFrame(e,t){if(!this.manager)return e;let i=t?8:this.mediaType;return this.manager.encodePipeline.reduce(((e,t)=>t?t({frame:e,mediaType:i}):e),e)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}play(e,t){return nb(this,null,(function*(){return gO(this.mirror)&&!this.isScreen&&this.setMirror("view"),rb(lx.prototype,this,"play").call(this,e,t)}))}close(){IL.off("videoInputAdded",this.handleCameraAdded,this),IL.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return nb(this,null,(function*(){try{yield rb(lx.prototype,this,"recapture").call(this,e)}catch(wk){let i=(yield bL()).find((t=>t.deviceId!==e));if(!i)throw wk;yield rb(lx.prototype,this,"recapture").call(this,i.deviceId)}}))}},dx=iP();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:dx,exposeOrigin:!0,permittedOrigins:["*"]})}catch($x){}var ux,hx=function(e){return nb(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:nN?{max:e.width}:{ideal:e.width,max:e.width},height:nN?{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);tP.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(eN&&iN<74||nN||nD)&&tP.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){tP.warn("screen applyConstraints failed: ".concat(o))}e.captureElement&&(yield function(e,t){return nb(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&fO(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==dx)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){tP.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 gO(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);tP.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},px=class extends lx{constructor(e){super(e,2),ib(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),ib(this,"objectFit","contain"),ib(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return nb(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 hx({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 vb?e:new vb({code:fb.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return nb(this,null,(function*(){throw new Error("Method not implemented.")}))}},mx=class extends sx{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}};function _x(e){return nb(this,null,(function*(){let t=oL();ux||(ux=iL(t,URL.createObjectURL(new Blob(["registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});"],{type:"application/javascript"})))),yield ux;let i=new AudioWorkletNode(t,"dumper",{numberOfInputs:e.length,numberOfOutputs:0});return e.forEach(((e,t)=>e.connect(i,0,t))),new ReadableStream({start(e){i.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach((e=>e.disconnect(i))),i.port.close()}})}))}var fx=class extends dL{constructor(e){super(),this.room=e,ib(this,"_localAudioTrack"),ib(this,"_localScreenAudioTrack"),ib(this,"log",tP.createLogger({id:"am"})),ib(this,"denoiser"),ib(this,"mixChangedDebounce"),ib(this,"encodePipeline",[]),ib(this,"decodePipeline",[]),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}dump(e){var t,i;if(!this._localAudioTrack)return;let r=[],n=[];null!=(t=this._localAudioPipline)&&t.source.node&&(r.push(this._localAudioPipline.source.node),n.push("mic")),null!=(i=this._localAudioPipline)&&i.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),n.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),n.push("mix")),this.log.info("dump audio track ".concat(n,", duration: ").concat(e));let o=new AbortController,s=[],a=setTimeout((()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")}),1e3*e),c=()=>{for(let e=0;e<n.length;e++){let t=URL.createObjectURL(new Blob(s[e])),i=document.createElement("a");i.href=t,i.download="".concat(n[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(a),o.abort("download")},l=_x(r).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>s[t]=s[t]?s[t].concat(e[0]):[e[0]]))}}),o).catch((e=>c))));return{then:l.then.bind(l),download:c}}getPCM(e){var t;if(gO(WritableStream))return void this.log.warn("getPCM failed: browser not support WritableStream");if(null==(t=this._localAudioPipline)||!t.source.node)return void this.log.warn("getPCM failed: no local audio track");let i=new Float32Array(1920),r=0,n=new AbortController;return _x([this._localAudioPipline.source.node]).then((t=>t.pipeTo(new WritableStream({write(t){!t[0][0]||(i.set(t[0][0],r),r+=t[0][0].length,r>=1920&&(r=0,e(i),i=new Float32Array(1920)))}}),n).catch((e=>this.log.error("stop getPCM reason:".concat(e)))))),n}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}changeInput(e){return e instanceof mx?(this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange()):e instanceof sx?(this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange()):e instanceof Tx?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then((()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([null==(e=this._localAudioTrack)?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),null==(t=this._localScreenAudioTrack)?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])}))),this.mixChangedDebounce}removeInput(e){e instanceof mx?delete this._localScreenAudioTrack:e instanceof sx&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}removeDenoiser(e){var t;if(delete this.denoiser,null==(t=this._localAudioTrack)||t.removeDenoiser(e),this.mixChangedDebounce)return this.mixChangedDebounce}destroy(){this.close()}addEncodeProcessor(e){let{processor:t,type:i}=e;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t)}addDecodeProcessor(e){let{processor:t,type:i}=e;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t)}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}};function gx(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return qL(((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 vb({code:fb.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});tP.warn(i),2===t?s(i):1===t&&n()}),1e3*e);i.apply(this,o).then(n,s).finally((()=>{clearTimeout(a)}))}))}))}var vx=class extends VL{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,ib(this,"tinyId"),ib(this,"isRemote",!0),ib(this,"jitterBufferDelay",0),ib(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===vx.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)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},yx=vx;ib(yx,"STATE_SUBSCRIBE","subscribe"),tb([gx(5,1)],yx.prototype,"waitHasMediaTrack",1),tb([fM(yM.INIT,yx.STATE_SUBSCRIBE,{success(){var e,t;this.log.info("subscribed"),VN.emit(ZO.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3)&&(this._decodeCheckTimeoutId=setTimeout((()=>{var e,t;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3)&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let e=this.kind===tk.AUDIO,t=this.player.isPlaying||(e?this.getAudioLevel()>0:this.stat.framesDecoded>0);gP[t?"addSuccessEvent":"addFailedEvent"]({key:e?504700:514702}),t||(gP.addEnum({key:e?504701:514703,value:CN()}),FN.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(SN()||AN()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===tk.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))))}}),5e3))},ignoreError:!0}),ix(521716,!1)],yx.prototype,"subscribe",1),tb([fM(yx.STATE_SUBSCRIBE,yM.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),VN.emit(ZO.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],yx.prototype,"unsubscribe",1);var Tx=class extends yx{constructor(e,t){super(e,t,1),ib(this,"volume",0),ib(this,"mediaType",1),ib(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),ib(this,"audioDecoder"),this.manager=e.audioManager}onPlayerError(e){if(this.enableDecodeFrame){this._log.warn("use audio decoder"),this.room.enableInsertableStreams(),this.player.setOutput();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!!this.manager&&(this.manager.decodePipeline.some((e=>e))||(null==(t=null==(e=this.player.element)?void 0:e.error)?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&rM().AudioDecoder&&ZP)}decodeFrame(e){var t;if(!this.manager)return e;let i=this.manager.decodePipeline.reduce(((e,t)=>t?t({frame:e}):e),e);return"configured"===(null==(t=this.audioDecoder)?void 0:t.state)&&this.audioDecoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"})),i}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}},Sx=[-1,-1,1,-1,-1,1,1,1],Ex=[0,0,1,0,0,1,1,1],Ix=class extends yM{constructor(e,t){if(super(),this.context=e,ib(this,"name"),ib(this,"input"),ib(this,"output"),ib(this,"texture"),ib(this,"ctx2d",null),ib(this,"fbo"),ib(this,"width",0),ib(this,"height",0),ib(this,"x",0),ib(this,"y",0),ib(this,"program"),ib(this,"vertexShader"),ib(this,"fragmentShader"),ib(this,"totalFrames",0),ib(this,"dropFrames",0),ib(this,"matchInputSize",!0),ib(this,"texCoordBuffer"),ib(this,"positionBuffer"),ib(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),ib(this,"cost",0),ib(this,"_canvas",null),ib(this,"_image"),ib(this,"log"),this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof pV){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(Ex),this.positionBuffer=this.createBuffer(Sx),!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(kb){this.context.destroy(new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(kb.message||kb)}))}}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 hV&&this.render(e)||this.context instanceof pV&&this.render2d(e))&&(this.totalFrames++,this.cost=Date.now()-t,!0)}render2d(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&this.draw2d(this.input.image,0,0,this.width,this.height)}update(e){var t;null==(t=this.output)||t.update(e)}disconnect(){for(var e,t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];null==(e=this.output)||e.removeInput(this,...i),delete this.output}removeInput(e){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),null==(e=this.output)||e.removeInput(this),delete this.output,null==(t=this.input)||t.disconnect(),this.context instanceof hV){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},QA({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,i=t.createTexture();return this.useTextures(i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};function Rx(){}tb([fM(yM.INIT,"connected",{sync:!0})],Ix.prototype,"connect",1),tb([fM("connected",yM.INIT,{ignoreError:!0,sync:!0})],Ix.prototype,"disconnect",1),tb([fM([],"closed",{sync:!0})],Ix.prototype,"close",1);var Cx=e=>e();function Ax(){this.dispose()}var bx=1,kx=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new xx(e,this,this.streamId++);return Vx.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},wx=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=Rx,this.error=Rx,this.next=Rx,this.dispose=Rx,this.subscribe=Rx,this.doDefer()}subscribe(e){return e instanceof kx?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(Cx),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}},Dx=class extends wx{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)}},Nx=class extends wx{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Rx,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Rx,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Rx;if(super(),this._next=t,this._error=i,this._complete=r,this.then=Rx,e instanceof kx){let n={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{Vx.defer(n,0)})),Vx.create(n),Vx.pipe(n),this.sourceId=n.id,this.subscribe(e),Vx.subscribe({id:n.id,end:!0}),t==Rx?this._next=e=>Vx.next(n,0,e):this.next=e=>{Vx.next(n,0,e),t(e)},r==Rx?this._complete=()=>Vx.complete(n,0):this.complete=()=>{this.dispose(),Vx.complete(n,0),r()},i==Rx?this._error=e=>Vx.complete(n,0,e):this.error=e=>{this.dispose(),Vx.complete(n,0,e),i()}}else this.subscribe(e)}next(e){this._next(e)}complete(){this.dispose(),this._complete()}error(e){this.dispose(),this._error(e)}};function Ox(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return i.reduce(((e,t)=>t(e)),e)}function Px(e,t,i){if("undefined"!=typeof __FASTRX_DEVTOOLS__){let r=Object.defineProperties(Object.setPrototypeOf(e,kx.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}});Vx.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof kx&&Vx.addSource(r,t)}return r}return e}function Mx(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 kx){let n=Px((t=>{let o=new e(t,...r);o.sourceId=n.id,o.subscribe(i)}),t,arguments);return n.source=i,Vx.pipe(n),n}return t=>i(new e(t,...r))}}}function Lx(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var xx=class extends Dx{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{Vx.defer(this.source,this.id)}))}next(e){Vx.next(this.source,this.id,e),this.sink.next(e)}complete(){Vx.complete(this.source,this.id),this.sink.complete()}error(e){Vx.complete(this.source,this.id,e),this.sink.error(e)}},Vx={addSource(e,t){Lx("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){Lx("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;Lx("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){Lx("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){Lx("defer",{id:e.id,streamId:t})},pipe(e){Lx("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){Lx("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=bx++),Lx("create",{name:e.toString(),id:e.id})}},Ux=class extends wx{constructor(e){super(),this.source=e,this.sinks=new Set}add(e){e.defer((()=>this.remove(e))),1===this.sinks.add(e).size&&(this.reset(),this.subscribe(this.source))}remove(e){this.sinks.delete(e),0===this.sinks.size&&this.dispose()}next(e){this.sinks.forEach((t=>t.next(e)))}complete(){this.sinks.forEach((e=>e.complete())),this.sinks.clear()}error(e){this.sinks.forEach((t=>t.error(e))),this.sinks.clear()}};function Fx(){return e=>{let t=new Ux(e);if(e instanceof kx){let i=Px((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,Vx.pipe(i),i}return Px(t.add.bind(t),"share",arguments)}}function Bx(e,t){return i=>{let r=e=>i.next(e);i.defer((()=>t(r))),e(r)}}function Hx(e,t){if("on"in e&&"off"in e)return Px(Bx((i=>e.on(t,i)),(i=>e.off(t,i))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return Px(Bx((i=>e.addListener(t,i)),(i=>e.removeListener(t,i))),"fromEvent",arguments);if("addEventListener"in e)return Px(Bx((i=>e.addEventListener(t,i)),(i=>e.removeEventListener(t,i))),"fromEvent",arguments);throw"target is not a EventDispachter"}var jx=Mx(class extends Dx{constructor(e,t,i){super(e),this.filter=t,this.thisArg=i}next(e){this.filter.call(this.thisArg,e)&&this.sink.next(e)}},"filter"),Wx=Mx(class extends Dx{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&this.complete()}},"take"),Gx=Mx(class extends Dx{constructor(e,t){super(e);let i=new Dx(e);i.next=()=>e.complete(),i.complete=Ax,i.subscribe(t)}},"takeUntil"),Jx=Mx(class extends Dx{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),zx=Mx(class extends Dx{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},"map"),qx=class extends Dx{constructor(e,t,i){super(e),this.data=t,this.context=i}next(e){let t=this.context.combineResults;t?this.sink.next(t(this.data,e)):this.sink.next(e)}tryComplete(){this.context.resetComplete(),this.dispose()}},Kx=class extends Dx{constructor(e,t,i){super(e),this.makeSource=t,this.combineResults=i,this.index=0}subInner(e,t){let i=this.currentSink=new t(this.sink,e,this);this.complete=this.tryComplete,i.complete=i.tryComplete,i.subscribe(this.makeSource(e,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Yx=class extends qx{},Qx=class extends Kx{next(e){this.subInner(e,Yx),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Yx)}}},Xx=Mx(Qx,"switchMap");var $x,Zx=($x=Mx(Qx,"switchMapTo"),(e,t)=>$x((()=>e),t)),eV=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Rx,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Rx,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Rx;return r=>new Nx(r,e,t,i)},tV=Ox(function(e){return Px((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}(250),zx((()=>performance.now())),Fx()),iV=[0,1,1,1,0,0,1,0],rV=class extends Ix{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),ib(this,"_intervalId",0),ib(this,"_sequence",0),ib(this,"checkGLError",!1),ib(this,"checkVisibilityChange"),e instanceof pV?this.ctx2d=e.ctx||null:e.available&&(null==t?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(iV)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),RM.clearTask(this._intervalId),this._intervalId=RM.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(RM.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof hV){let e=this.context.ctx.getError();e&&this.context.destroy(new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:5,message:"".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)}))}}),{fps:this.context.frameRate})}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];super.addInput(e,...i),this.start(this.context.frameRate)}update(e){if(this._intervalId&&(RM.clearTask(this._intervalId),this._intervalId=0,1===e)){this.log.info("".concat(this.name," use requestVideoFrameCallback"));let e=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",e))};document.addEventListener("visibilitychange",e)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),RM.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),RM.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},nV=class extends rV{constructor(e,t){super(e,t),ib(this,"_videoTrack"),ib(this,"_muteOb"),ib(this,"_closedOb",Hx(this,"closed")),ib(this,"_subscription"),ib(this,"_canvasContainer"),Number(sN)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=Hx(this._videoTrack,"mute"),Ox(Hx(this._videoTrack,"ended"),Gx(this._closedOb),eV((()=>{this.context.destroy(new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){this._subscription=Ox(this._muteOb,Gx(this._closedOb),Zx((e=>t=>{let i=performance.now();Ox(tV,Jx((t=>t-i<e)),Wx(1))(t)})(5e3)),eV((()=>{var e;null==(e=this._videoTrack)||!e.muted||this.context.destroy(new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))})))}disableCheckMute(){var e;null==(e=this._subscription)||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info("".concat(this.name," put canvas to body")),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack,null==(t=this._canvasContainer)||t.remove()}},oV=class extends nV{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},sV=class extends nV{constructor(e,t,i){super(e,{name:"smallDestination",logger:i}),this.resolution=t}resize(e,t){let i,r=e*t,n=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),r>n?i=r/n:(this.log.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(e," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),i=r/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},aV=class extends Ix{constructor(e,t){super(e,QA({name:"imageSource"},t)),ib(this,"_lastImage"),ib(this,"_totalFrames",0),ib(this,"_autoResize",!1),ib(this,"_canvasRendered"),ib(this,"_videoCallbackId",0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===lN&&(this._canvasRendered=function(e){let t=arguments,i=Fx()(Px((t=>{i.next=e=>t.next(e),i.complete=()=>t.complete(),i.error=e=>t.error(e),e&&t.subscribe(e)}),"subject",t));return i.next=Rx,i.complete=Rx,i.error=Rx,i}(),Ox(this._canvasRendered,function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>Px((function(i){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.length;for(;r<n&&!i.disposed;)i.next(t[r++]);i.disposed||i.subscribe(e)}),"startWith",arguments)}(this._image),Xx((e=>e instanceof HTMLCanvasElement?Hx(e,"rendered"):function(){return Px((e=>e.complete()),"empty",arguments)}())),Gx(Hx(this,"closed")),eV((()=>{this.update(0)}))))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),lM()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback(((e,t)=>{document.hidden||(this._totalFrames=t.presentedFrames,this.update(1))})))}_render(e,t){let{width:i,height:r}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(n),({videoWidth:i,videoHeight:r}=n),!i||!r)return!1;n.width=i,n.height=r}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if(({width:i,height:r}=n),n!==this._lastImage)this._lastImage=n;else if(i===this.width&&r===this.height)return!1}else(n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas)&&(({width:i,height:r}=n),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===i&&this.height===r&&this.totalFrames){if(t){this.useTexture();let e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)}this.resize(i,r)}return!0}get image(){return this._image}set image(e){var t;null==(t=this._canvasRendered)||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},cV=class extends aV{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",Ox(Hx(this._player,CM.PLAYER_STATE_CHANGED),Gx(Hx(this,"closed")),jx((e=>{let{state:t}=e;return"PLAYING"===t})),eV((()=>{this.tryVideoFrameCallback(this._player.element)})))}get image(){return this._player.element}},lV=class extends cV{constructor(e,t,i){super(e,new tL({id:i.name,track:t,muted:!0,container:null,objectFit:"contain",log:i.logger}),i),this.name="videoTrackSource",this._player.play()}replaceTrack(e){this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},dV=class extends yM{constructor(e){super(),ib(this,"frameRate"),ib(this,"_canvas"),ib(this,"log"),ib(this,"hasAlpha",!1),ib(this,"name"),ib(this,"error"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new lV(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new nV(this,e)}createVideoImageSource(e,t){return new aV(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new cV(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};ib(dV,"_ids",0);var uV={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},hV=class extends dV{constructor(){super(...arguments),ib(this,"defaultProgam"),ib(this,"defaultVShader"),ib(this,"defaultFShader"),ib(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(dV._ids++)),this.ctx=this._canvas.getContext("webgl2",uV),!this.ctx)throw new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,"\n// 顶点着色器\nattribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main() {\n gl_Position = a_position;\n v_texCoord = a_texCoord;\n}\n"),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,"\n// 片元着色器\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\n\nvoid main() {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n} "),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",(()=>{this.destroy(new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})),this.log.info("video context created use webgl")}destroy(e){let t="";return e&&(t=e.message,this.error=e,gP.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info("video context destroy".concat(t)?": ".concat(t):""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;null==(t=this.ctx)||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let i=this.ctx,r=i.createShader(e);return i.shaderSource(r,t),i.compileShader(r),r}createProgram(e,t){let i=this.ctx,r=i.createProgram();return i.attachShader(r,e),i.attachShader(r,t),i.linkProgram(r),i.getProgramParameter(r,i.LINK_STATUS)||this.log.error(i.getProgramInfoLog(r)),r}};tb([fM(yM.INIT,"created",{sync:!0,fail(e){gP.addFailedEvent({key:512700,error:e.cause})},success(){gP.addSuccessEvent({key:512700})}})],hV.prototype,"create",1),tb([fM("created",yM.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit("unavailable",e),this.removeAllListeners()}})],hV.prototype,"destroy",1);var pV=class extends dV{constructor(){super(...arguments),ib(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(dV._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this.log.info("video context created use 2d")}destroy(e){let t="";e&&(t=e.message,this.error=e,gP.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info("video context destroy ".concat(t?": ".concat(t):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),gP.addSuccessEvent({key:512703})}};tb([fM(yM.INIT,"created",{sync:!0,fail(e){gP.addFailedEvent({key:512701,error:e.cause})},success(){gP.addSuccessEvent({key:512701})}})],pV.prototype,"create",1),tb([fM("created",yM.INIT,{ignoreError:!0,sync:!0})],pV.prototype,"destroy",1);var mV=class extends yx{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),ib(this,"mediaType",4),ib(this,"source"),ib(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager}play(e,t){return(TO(null==t?void 0:t.canvasRender)?t.canvasRender:17===lN)&&!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 pV({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=e.createVideoPlayerSource(this.player);this.source=t;let i=new rV(e,{name:"remotePlayer",logger:this.log});t.connect(i),this.player.setCanvas(e._canvas),lM()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,i=function(e){return[15,30,45,60].reduce(((t,i)=>Math.abs(i-e)<Math.abs(t-e)?i:t))}(t);!yO(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&&this.manager.decodePipeline.some((e=>e))}decodeFrame(e){return this.manager?this.manager.decodePipeline.reduce(((e,t)=>t?t({frame:e,track:this}):e),e):e}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}},_V=class extends mV{constructor(e,t){super(e,t,2),ib(this,"mediaType",2),ib(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}},fV=new Map;function gV(e,t){let i=XA(QA({},t),{timestamp:Tb()});fV.has(e)?fV.get(e).push(i):fV.set(e,[i])}VN.on(ZO.JOIN_SUCCESS,(e=>{let{room:t}=e;gV(t.userId,{eventId:32788})})),VN.on(ZO.LEAVE_START,(e=>{let{room:t}=e;gV(t.userId,{eventId:32789})})),VN.on(ZO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),gV(t.room.userId,{eventId:e})}})),VN.on(ZO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),gV(t.room.userId,{eventId:e})}})),VN.on(ZO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===tk.AUDIO?gV(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):gV(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),VN.on(ZO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===tk.AUDIO?gV(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):gV(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),VN.on(ZO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&gV(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&gV(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&gV(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),VN.on(ZO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&gV(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&gV(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&gV(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),VN.on(ZO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&gV(t.room.userId,{eventId:t.kind===tk.VIDEO?32780:32781})})),VN.on(ZO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&gV(t.room.userId,{eventId:t.kind===tk.VIDEO?32782:32783})})),VN.on(ZO.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&&gV(i.userId,{eventId:t})})),VN.on(ZO.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&&gV(i.userId,{eventId:t,remoteUserId:o})})),VN.on(ZO.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),gV(t,l),gP.addEnum({key:i?514701:513701,value:a}),gP.addEnum({key:i?514700:513700,value:c})})),VN.on(ZO.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===tk.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),gV(t.userId,e)}}));var vV=eb(ob(),1),yV=class extends vV.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,ib(this,"userMap",new Map),ib(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,"]");gO(t)||(r+=":".concat($k[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=LO(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:LO(0,n),muteState:s,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function TV(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return qL(((e,n)=>{let o=new WeakMap;return VN.on(ZO.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 vb({code:fb.INVALID_OPERATION,message:DN({key:Uw,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>i,name:n,timesInSecond:t,maxSizeInSecond:i}})});s.callCountInSecond++,e.call(this,...c)}}))}var SV,EV=!0,IV={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"},RV={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},CV=((SV=CV||{})[SV.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",SV[SV.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",SV[SV.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",SV[SV.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",SV[SV.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",SV[SV.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",SV[SV.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",SV[SV.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",SV[SV.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",SV[SV.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",SV[SV.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",SV[SV.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",SV[SV.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",SV[SV.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",SV[SV.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",SV[SV.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",SV[SV.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",SV[SV.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",SV[SV.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",SV[SV.INVALID_OPERATION=5100]="INVALID_OPERATION",SV[SV.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",SV[SV.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",SV[SV.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",SV[SV.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",SV[SV.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",SV[SV.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",SV[SV.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",SV[SV.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",SV[SV.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",SV[SV.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",SV[SV.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",SV[SV.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",SV[SV.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",SV[SV.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",SV[SV.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",SV[SV.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",SV[SV.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",SV[SV.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",SV[SV.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",SV[SV.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",SV[SV.DEVICE_ERROR=5300]="DEVICE_ERROR",SV[SV.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",SV[SV.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",SV[SV.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",SV[SV.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",SV[SV.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",SV[SV.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",SV[SV.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",SV[SV.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",SV[SV.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",SV[SV.SERVER_ERROR=5400]="SERVER_ERROR",SV[SV.NEED_TO_BUY=5401]="NEED_TO_BUY",SV[SV.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",SV[SV.OPERATION_FAILED=5500]="OPERATION_FAILED",SV[SV.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",SV[SV.REJOIN_FAILED=5502]="REJOIN_FAILED",SV[SV.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",SV[SV.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",SV[SV.OPERATION_ABORT=5998]="OPERATION_ABORT",SV[SV.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",SV);var AV=XA(QA({},Hw),{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(_O(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(_O(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=bV(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=bV(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=bV(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=bV(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=bV(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=bV(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=bV(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 bV(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var kV=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=CV[i];try{t=AV[a]}catch(o){t=AV.UNKNOWN_ERROR}return fO(t)?s=t(r):vO(t)&&(s=t),r.fnName&&!s.includes(r.fnName)&&("."!==s[s.length-1]&&(s+="."),s+=" thrown from ".concat(r.fnName,"()")),n&&(s+=" doc:"),s}({code:t===RV.SERVER_ERROR?t:i||t,params:QA({fnName:o,error:s},n)}),super(c),ib(this,"name","RtcError"),ib(this,"code"),ib(this,"extraCode"),ib(this,"functionName"),ib(this,"message"),ib(this,"handler"),ib(this,"originError"),this.name=CV[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");MD?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):LD&&(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 vb){let{stack:n}=e,o={code:RV.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case fb.INVALID_PARAMETER:o.code=RV.INVALID_PARAMETER,o.message=e.message;break;case fb.INVALID_OPERATION:o.code=RV.INVALID_OPERATION;break;case fb.NOT_SUPPORTED:case fb.NOT_SUPPORTED_H264:o.code=RV.ENV_NOT_SUPPORTED,e.getCode()===fb.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(Hw.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case fb.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case fb.SERVER_TIMEOUT:case fb.SWITCH_ROLE_FAILED:o.code=RV.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case fb.API_CALL_ABORTED:o.code=RV.OPERATION_ABORT;break;case fb.DEVICE_NOT_FOUND:case fb.DEVICE_AUTO_RECOVER_FAILED:case fb.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 fb.UNKNOWN:break;default:o.code=RV.OPERATION_FAILED}r=new kV(o),n&&(r.stack+=n.substr(n.indexOf("\n")))}else{if(e instanceof kV)return e;r=new kV({code:RV.UNKNOWN_ERROR,fnName:t,originError:e})}return r}};var wV=kV,DV={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}}},NV={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}}},OV={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(vO(e)&&!document.getElementById(e))throw new wV({code:RV.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},PV={name:"userId",required:!0,type:"string"},MV={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[IV.AUDIO_PROFILE_STANDARD,IV.AUDIO_PROFILE_STANDARD_STEREO,IV.AUDIO_PROFILE_HIGH,IV.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function LV(e,t){if(!e)throw new wV({code:RV.INVALID_OPERATION,extraCode:5101,fnName:t})}function xV(e,t,i){if(!e)throw new wV({code:RV.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var VV={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 wV({code:RV.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(vO(e.roomId))throw new wV({code:RV.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new wV({code:RV.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new wV({code:RV.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new wV({code:RV.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:OV,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:DV},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&CP())throw new wV({code:RV.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:XA(QA({},OV),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:DV}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:MV},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&CP())throw new wV({code:RV.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:MV}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:OV,publish:{type:"boolean"},option:NV},validate(e,t,i,r,n){var o;if((null==(o=null==e?void 0:e.option)||!o.videoTrack)&&CP())throw new wV({code:RV.ENV_NOT_SUPPORTED,extraCode:5201});if(!NP())throw new wV({code:RV.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:OV,publish:{type:"boolean"},option:NV}},muteRemoteAudio:[PV,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[PV,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:OV,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){LV(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(xV(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new wV({code:RV.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:XA(QA({},OV),{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){LV(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(xV(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new wV({code:RV.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&&gO(e.streamType))throw new wV({code:RV.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){LV(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(!tM)throw new wV({code:RV.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new wV({code:RV.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new wV({code:RV.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new wV({code:RV.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});LV(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 wV({code:RV.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 wV({code:RV.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new wV({code:RV.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(LV(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new wV({code:RV.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}}},UV={TRTC:VV},FV=class extends Error{};function BV(e,t){let i=FO(e);for(let r=0;r<t.length;r++)UO(i[r],t[r]);return i}function HV(e){this._resolve=Promise.resolve(e)}function jV(e){this._reject=Promise.reject(e)}var WV=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=BV;let i=WV.instances.get(e);i?i.set(t,this):WV.instances.set(e,new Map([[t,this]]))}static get(e,t){if(!t)return;let i=WV.instances.get(e);return i&&i.get(t)||new WV(e,t)}static gets(e,t){let i=WV.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 FV("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:HV,reject:jV};try{switch(this.state){case 1:if(0===e)throw new FV("already started");break;case 4:if(2===e)throw new FV("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 FV("already start");break;case 3:switch(e.type){case 2:throw new FV("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new FV("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new FV("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 FV("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new FV("start not allowed after update");case 0:throw new FV("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new FV("keep start")),new FV("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}},GV=WV;GV.instances=new WeakMap;var JV=new WeakMap,zV=(e,t)=>{if(t instanceof FV){let{stack:i}=t;t=new wV({code:RV.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function qV(e,t){return qL(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let a=GV.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(zV.bind(null,r))):i.apply(this,o)}))}function KV(e,t){let{merge:i,debounce:r}=t||{};return qL(((t,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=GV.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=JV.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(zV.bind(null,n)).then(r,o)}),e);JV.has(this)?null==(l=JV.get(this))||l.set(i(...s),{timeoutId:u,resolve:r}):JV.set(this,new Map([[i(...s),{timeoutId:u,resolve:r}]]))}))}return c.action(2,t.bind(this),s).catch(zV.bind(null,n))}))}function YV(e){return qL(((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(GV.gets(this,s).map((e=>e.action(3,(()=>Promise.resolve()),n)))).then((()=>t.call(this,...n)));let a=GV.get(this,s);return a?a.action(3,t.bind(this),n).catch(zV.bind(null,i)):t.apply(this,n)}))}var QV={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message"},XV=new Set([QV.ERROR,QV.AUTOPLAY_FAILED,QV.KICKED_OUT,QV.REMOTE_USER_ENTER,QV.REMOTE_USER_EXIT,QV.REMOTE_AUDIO_AVAILABLE,QV.REMOTE_AUDIO_UNAVAILABLE,QV.REMOTE_VIDEO_AVAILABLE,QV.REMOTE_VIDEO_UNAVAILABLE,QV.CONNECTION_STATE_CHANGED,QV.PUBLISH_STATE_CHANGED,QV.SCREEN_SHARE_STOPPED,QV.DEVICE_CHANGED]);function $V(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function ZV(e){return e===IV.QOS_PREFERENCE_CLEAR?"detail":e===IV.QOS_PREFERENCE_SMOOTH?"motion":""}var eU=class{constructor(){ib(this,"_log"),this._log=tP.createLogger({id:"fd"})}download(e,t){return nb(this,null,(function*(){let{type:i="blob"}=t||{};try{let t,r=DO();if(t=fO(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let n=DO()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(n,"ms")),gP.addSuccessEvent({key:522700,cost:DO()-r}),t.data}catch(kb){throw this._log.error("failed to download: ".concat(e,", error: ").concat(kb)),gP.addFailedEvent({key:522700,error:kb}),kb}}))}downloadWithFetch(e,t){return nb(this,null,(function*(){this._log.info("download with fetch: ".concat(e,", return type: ").concat(t));try{let i,r=yield fetch(e);if(!r.ok)throw new Error("network response was not ok");return i="arraybuffer"===t?yield r.arrayBuffer():yield r.blob(),{data:i}}catch(wk){throw wk}}))}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType=t,n.onload=()=>{200===n.status||0===n.status&&n.response?i({data:n.response}):r(new Error("XHR failed"))},n.onerror=r,n.send(null)}))}loadWasm(e,t){return nb(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=DO(),r=null,n=null;if(fO(WebAssembly.instantiateStreaming)&&!(e=>e.startsWith("data:application/octet-stream;base64,"))(e)&&!(e=>e.startsWith("file://"))(e)&&fO(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(wb){n=wb}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(wb){n=wb}if(r){let t=DO()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),gP.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),gP.addFailedEvent({key:522701,error:n}),n}))}};tb([NM({settings:{timeout:0,retries:3},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],eU.prototype,"download",1);var tU=new eU;function iU(e){let{TRTC:t,room:i,errorModule:r,assetsPath:n}=e;return{TRTC:t,room:i,assetsPath:n,fileDownloader:tU,innerEmitter:VN,constants:Ib,environment:jw,utils:Eb,eventLogger:FN,log:this.room.getLogger(),loggerManager:tP,errorModule:r,kvStatManager:gP,rtcDectection:nP,trtc:this,clearStarted:(e,t)=>{let i=e.getAlias(),r=GV.instances.get(this);if(r)if(t){let e=r.get(i+t);if(!e)return;e.started=!1}else r.forEach(((e,t)=>{t.startsWith(i)&&(e.started=!1)}))},startGetPCM:_x,createAudioNode:hL}}var rU=new WeakMap;function nU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return qL(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{sU.call(this,t,n,i,this._name)}catch(kb){return Promise.reject(kb)}return e.apply(this,n)}))}function oU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return qL(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{sU.call(this,t,n,i,this._name)}catch(kb){throw kb}return e.apply(this,n)}))}function sU(e,t,i,r){if(EO(e))for(let n=0;n<e.length;n++)aU.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else aU.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function aU(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function s(e){return{code:RV.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(gO(i)){if(t.required)throw new wV(s(5001));if(gO(t.defaultValue))return void(fO(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),fO(t.type[r])&&i instanceof t.type[r]&&(e=!0),vO(t.type[r])&&_O(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new wV({code:RV.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>AO(e)?bO(e):vO(e)?e:_O(e)))},value:i}})}else if(!gO(t.type)&&_O(i)!==t.type)throw new wV(s(5002));if(!1===t.allowEmpty){let e=yO(i)&&(0===i||Number.isNaN(i)),t=vO(i)&&""===i.trim();if(e||t)throw new wV(s(5003))}if(t.notLessThanZero&&yO(i)&&i<0)throw new wV(s(5006));if(!gO(t.min)&&yO(i)&&i<t.min)throw new wV(s(5007));if(!gO(t.max)&&yO(i)&&i>t.max)throw new wV(s(5008));if(vO(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new wV(s(5004))}else if(fO(t.instanceOf)&&!(i instanceof t.instanceOf))throw new wV(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new wV(s(5005));let{properties:a}=t;hO(a)&&SO(i)&&Object.keys(a).forEach((e=>{aU.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;hO(c)&&EO(i)&&i.forEach(((e,t)=>{aU.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),fO(t.validate)&&t.validate.call(this,i,r,n,o,this)}function cU(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r}=e;return qL(((e,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];var c;function l(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(_O(t)):(JSON.stringify(t),t)}catch(n){return"type:".concat(_O(t))}}let d=this._log||tP;s.length>0?d.info("".concat(n,"() ").concat(JSON.stringify(s,((e,t)=>l(e,t,["userSig","privateMapKey"]))))):d.info("".concat(n,"()"));let u=r?r(...s):lP[n];try{let i=e.apply(this,s),r=DO();return CO(i)?i.then((e=>(d.info("".concat(n,"() success ").concat(t.call(this,...s))),gP.addSuccessEvent({key:u,cost:DO()-r}),e))).catch((e=>{var i;let r=(e=wV.convertFrom.call(this,e,n,1===s.length?s[0]:s)).extraCode||e.code,o=null!=(i=e.message)&&i.includes(r)?"":" code:".concat(r);throw d.error("".concat(n,"() failed ").concat(t.call(this,...s)," ").concat(e).concat(o," params: ").concat(JSON.stringify(s,l))),gP.addFailedEvent({key:u,error:e}),e})):(gP.addSuccessEvent({key:u}),i)}catch(h){let e=(h=wV.convertFrom.call(this,h,n)).extraCode||h.code,t=null!=(c=h.message)&&c.includes(e)?"":" code:".concat(e);throw d.error("".concat(n,"() failed ").concat(h).concat(t," params: ").concat(JSON.stringify(s,l))),gP.addFailedEvent({key:u,error:h}),h}}))}var lU=e=>qL(((t,i)=>function(r,n){return nb(this,null,(function*(){let o=this._plugins.get(r);if(!o)throw this._log.error("plugin ".concat(String(r)," is not found")),new wV({code:RV.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(fO(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new wV({code:RV.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return sU.call(this,o.getValidateRule(e),[n],i,"TRTC"),t.call(this,o,n)}))})),dU=0,uU=class{constructor(e,t){ib(this,"player"),ib(this,"publisher"),ib(this,"mixInput"),this.mixInput=new lL(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||(gO(e.volume)||(this.volume=e.volume),gO(e.loop)||(this.loop=e.loop),gO(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 hU(e,t){if(t&&"function"!=typeof t)throw new wV({code:RV.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var pU=class{constructor(e){this.core=e,ib(this,"log"),ib(this,"mixedMusicMap",new Map),ib(this,"cacheMusicMap",new Map),dU+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(dU)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat(dU)),this.core=e}getName(){return pU.Name}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(e){switch(e){case"start":return pU.startValidateRule;case"update":return pU.updateValidateRule;case"stop":return pU.stopValidateRule}}start(e){return nb(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 uU(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.")),gP.addEnum({key:502700,value:3}),this.kvUpload(e)}))}update(e){return nb(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),gO(i)||o.setOperation(i),gO(r)||o.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return nb(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&&gP.addCount({key:502711}),i&&gP.addCount({key:502703}),r&&gP.addCount({key:502704}),n&&gP.addCount({key:502705}),o&&gP.addCount({key:502706}),s&&gP.addCount({key:502707}),"function"!=typeof a&&gP.addCount({key:502709}),"function"!=typeof l&&gP.addCount({key:502710}),"function"!=typeof c&&gP.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()}},mU=pU;ib(mU,"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 wV({code:RV.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new wV({code:RV.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});hU("onTimeUpdate",e.onTimeUpdate),hU("onEnded",e.onEnded),hU("onDurationChange",e.onDurationChange)}}),ib(mU,"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){hU("onTimeUpdate",e.onTimeUpdate),hU("onEnded",e.onEnded),hU("onDurationChange",e.onDurationChange)}}),ib(mU,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),ib(mU,"Name","AudioMixer");var _U,fU=0,gU=class{constructor(e){this.core=e,ib(this,"log"),ib(this,"audioContext",oL()),ib(this,"workletNode"),fU+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(fU)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(fU)),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 wV({code:RV.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return _U||(_U=this.doPreload(e)),_U}doPreload(e){return nb(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield iL(this.audioContext,i)}finally{URL.revokeObjectURL(i)}}))}getName(){return gU.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(e){switch(e){case"start":return gU.startValidateRule(this.core);case"update":return gU.updateValidateRule;case"stop":return gU.stopValidateRule}}start(e){return nb(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 nb(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=(e=>(e=Number(e))>0&&e<14e8)(e)?yU.MAIN_OVERSEA:yU.MAIN,t}(t),"/api/v1/audioAiAuth?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(r,"×tamp=").concat(n),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d="Init RTCAIDenoiser failed.",u="";switch(s){case 1:u="Please check your params.";break;case 2:u="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:u="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:u="Your version is not supported."}return{auth:!1,status:l,message:a?"".concat(d," Reason: ").concat(a,". ").concat(u):"".concat(d,", ").concat(u)}}()}))}(XA(QA({},e),{timestamp:t}));if(!i)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(i,". Message: ").concat(o)),new wV({code:RV.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 nb(this,null,(function*(){}))}stop(){return nb(this,null,(function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)}))}destroy(){!this.workletNode||(this.workletNode.port.onmessage=null)}},vU=gU;ib(vU,"updateValidateRule",{type:"object"}),ib(vU,"stopValidateRule",{type:"object"}),ib(vU,"Name","AIDenoiser");var yU={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};var TU=eb(ob(),1),SU=class extends TU.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 nb(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(bb){FN.uploadEvent({log:"stat-pressure-detector-start-failed",error:bb})}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&tP.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(wk){FN.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:wk})}}},EU=new SU;function IU(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 ax(new DataView(new Uint8Array(s).buffer),!0)}function RU(e){return"empty"===e.type||0===e.data.byteLength}function CU(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}function AU(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 bU(e){let{frame:t,seiMessageList:i}=e;if(!i||0===i.length||0===t.data.byteLength)return t;let r=9-AU(t.data);if(r<=0)return t;let n=i.splice(0,r).reverse().map(IU),o=n.reduce(((e,t)=>e+t.dataView.byteLength),0),s=new ArrayBuffer(o+t.data.byteLength),a=new DataView(s),c=new DataView(t.data),l=0;for(let d=0;d<n.length;d++)for(let e=0;e<n[d].dataView.byteLength;e++)a.setInt8(l++,n[d].dataView.getInt8(e));for(let d=0;d<t.data.byteLength;d++)a.setInt8(l++,c.getInt8(d));return t.data=s,t}function kU(e){let{frame:t,onSEI:i}=e;try{let e=new DataView(t.data);if(RU(t)||!CU(e))return t;let r=[],n=0,o=-1,s=-1;for(let i=0;i<t.data.byteLength;i++){let a=e.getUint8(i);if(0===a)n++;else if(1===a){if(2===n||3===n){let a=i-n;if(-1===o?o=a:-1===s&&(s=a,r.push(new ax(new DataView(e.buffer.slice(o,s)))),o=a,s=-1),6!==e.getUint8(i+1)){t.data=e.buffer.slice(a);break}}n=0}else n=0}null==i||i(r.reverse())}catch(bb){}return t}var wU=0,DU=class{constructor(e){this.core=e,ib(this,"log"),ib(this,"_seiMessageList",[]),ib(this,"_smallSeiMessageList",[]),ib(this,"_subStreamSeiMessageList",[]),wU++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(wU)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(wU)),this.core=e,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:t,mediaType:i}=e;try{return bU({frame:t,seiMessageList:8===i?this._smallSeiMessageList:2===i?this._subStreamSeiMessageList:this._seiMessageList})}catch(wk){this.log.warn(wk)}return t}decode(e){let{frame:t,track:i}=e;return kU({frame:t,onSEI:e=>{e.forEach((e=>{this.core.trtc.emit(QV.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:i.userId,streamType:2===i.mediaType?"sub":"main"})}))}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:ZP?this.encode:bU,type:1}),this.core.room.videoManager.addDecodeProcessor({processor:ZP?this.decode:kU,type:1})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:1}),this.core.room.videoManager.removeDecodeProcessor({type:1})}update(e){let{buffer:t,options:i}=e;var r;let n=[i.seiPayloadType,t],o=!!i.small;i.toSubStream?this._subStreamSeiMessageList.push(n):(this._seiMessageList.push(n),o&&this._smallSeiMessageList.push(n)),null==(r=this.core.room.scriptTransformWorker)||r.postMessage({type:"sei",data:n,isMain:!i.toSubStream,small:o})}getName(){return DU.Name}getAlias(){return"sei"}getGroup(){return"sei"}},NU=DU;ib(NU,"autoStart",!0),ib(NU,"Name","SEI");var OU,PU=0,MU=class{constructor(e){this.core=e,ib(this,"_core"),ib(this,"log"),ib(this,"dumpLocalVideoMap",{}),ib(this,"dumpRemoteVideoMap",{}),ib(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++PU)}),this.log.info("created")}getName(){return MU.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(e){switch(e){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return nb(this,null,(function*(){!new URLSearchParams(location.search).has("trtcDebug")||(yield this.openDebugDiaLog(),this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED&&this.addVideoProcessor())}))}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return nb(this,null,(function*(){try{if(OU)yield OU;else{let e=Date.now();OU=this.loadScript("https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@".concat(Cb,".js")),yield OU,this.log.info("download debug dialog script cost: ".concat(Date.now()-e,"ms"))}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(sP){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(sP))}}))}closeDebugDiaLog(){var e;null==(e=this.dialog)||e.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):this.encodeVideoDump,type:2}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):this.decodeVideoDump,type:2})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:2}),this._core.room.videoManager.removeDecodeProcessor({type:2})}encodeVideo(e){let{frame:t,mediaType:i}=e;return this.encodeVideoDump({frame:t,onDump:()=>{if(!i)return;let e=2===i?"sub":"main",r=this.dumpLocalVideoMap[e];r&&(r.data.push(t.data),r.duration>0&&Date.now()-r.startTimestamp>1e3*r.duration&&r.onDumpEnd())}})}decodeVideo(e){let{frame:t,track:i}=e;return this.decodeVideoDump({frame:t,onDump:()=>{if(!i)return;let e=this.dumpRemoteVideoMap["".concat(i.userId,"-").concat(i.streamType)];e&&(e.data.push(t.data),e.duration>0&&Date.now()-e.startTimestamp>1e3*e.duration&&e.onDumpEnd())}})}encodeVideoDump(e){let{frame:t,onDump:i}=e;return null==i||i(),t}decodeVideoDump(e){let{frame:t,onDump:i}=e;return null==i||i(),t}loadScript(e){return new Promise(((t,i)=>{this.log.info("loading debug dialog from ".concat(e));let r=document.createElement("script");r.type="text/javascript",r.onload=t,r.onerror=i,r.crossOrigin="anonymous",r.src=e,document.head.append?document.head.append(r):document.getElementsByTagName("head")[0].appendChild(r)}))}},LU=MU;ib(LU,"Name","Debug"),ib(LU,"autoStart",!0),tb([NM({settings:{timeout:3e3,retries:3},onError(e,t,i){var r;null!=(r=null==e?void 0:e.message)&&r.includes("timeout")?t():i(e)}})],LU.prototype,"loadScript",1);var xU=0,VU=new Set,UU=null;Ab("5.8.5-ef.4");var FU={RtcError:wV,ErrorCode:RV,ErrorCodeDictionary:CV},BU=class extends mb.EventEmitter{constructor(e,t){super(),ib(this,"_room"),ib(this,"_eventListened",new Set),ib(this,"_localVideoTrack",null),ib(this,"_localAudioTrack",null),ib(this,"_localScreenTrack",null),ib(this,"_localScreenAudioTrack",null),ib(this,"_localVideoConfig",null),ib(this,"_localScreenConfig",null),ib(this,"_localAudioConfig",null),ib(this,"_remoteVideoConfigMap",new Map),ib(this,"_remoteAudioConfigMap",new Map),ib(this,"_remoteAudioMuteMap",new Map),ib(this,"_mediaTrackMap",new WeakMap),ib(this,"_log",tP.createLogger({id:"t".concat(++xU)})),ib(this,"_plugins",new Map),ib(this,"_networkQuality",null),ib(this,"_speakerId"),ib(this,"_getPCMAbortCtrl"),this._room=new e(QA({logger:this._log,frameWorkType:BU.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(mU,t.assetsPath),this._use(vU,t.assetsPath),this._use(LU),t.enableSEI&&tM&&this._use(NU),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(QV.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{this._log.error(new wV({code:RV.OPERATION_FAILED,extraCode:5504,message:e.message,originError:e}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:i}=e;e.emit=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{return i.apply(e,n)}catch(kb){let i=DN({key:xw,data:{name:t,event:n[0]},addDocLink:!1});return tP.warn("".concat(i,"\n\n").concat(kb.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,t){!function(){var e;EV&&(EV=!1,5!==tP.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Fb,"/en/index.html")),console.info("* Changelog: ".concat(Fb,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),tP.info("TRTC Web SDK Version:",Cb),tP.info("UA:",navigator.userAgent),tP.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),yN().then((e=>{e&&tP.info(vN)})))}();let i=new BU(e,t||{});return VU.add(i),i}get room(){return this._room}_listenEvents(){kM(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(QV.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(QV.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(QV.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(QV.ERROR,wV.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(QV.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e;let t=XA(QA({},e),{uplinkRTT:Math.min(e.uplinkRTT,sw),downlinkRTT:Math.min(e.downlinkRTT,sw)});this.emit(QV.NETWORK_QUALITY,t)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{kM(t,t).add("player-state-changed",(i=>{let r=XA(QA({},i),{userId:e.userId});t.kind===tk.VIDEO&&(r.streamType=$V(t.streamType)),this.emit(t.kind===tk.AUDIO?QV.AUDIO_PLAY_STATE_CHANGED:QV.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===fb.PLAY_NOT_ALLOWED&&this.emit(QV.AUTOPLAY_FAILED,{userId:t.userId})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{wM(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?QV.REMOTE_AUDIO_AVAILABLE:QV.REMOTE_AUDIO_UNAVAILABLE,{userId:r}),s?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i})),o!==a&&(this.emit(a?QV.REMOTE_VIDEO_AVAILABLE:QV.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?QV.REMOTE_VIDEO_AVAILABLE:QV.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(QV.SEI_MESSAGE,XA(QA({},e),{streamType:$V(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(QV.ERROR,new wV({code:RV.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,i,r,n,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(r=this._networkQuality)?void 0:r.downlinkRTT)||0,sw),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)/lw},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)/lw},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(QV.STATISTICS,l)})).add("custom-message",(e=>{this.emit(QV.CUSTOM_MESSAGE,e)})),kM(this,IL).add("audioInputAdded",(e=>{this.emit(QV.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(QV.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(QV.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(QV.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>nb(this,null,(function*(){if(this.emit(QV.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),UU&&UU.deviceId===Yk){let e=(yield wL()).find((e=>e.deviceId===Yk));e&&UU.groupId!==e.groupId&&(UU=e,this.emit(QV.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>nb(this,null,(function*(){this.emit(QV.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield wL())[0];if(!t||!UU||UU.groupId===t.groupId)return;let i=UU.deviceId===e.deviceId,r=UU.deviceId===Yk&&UU.deviceId===t.deviceId;(i||r)&&(UU=t,this.emit(QV.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(iU.call(this,{TRTC:BU,room:this._room,errorModule:FU,assetsPath:t}));this._plugins.set(e.Name,i),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return nb(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),!vO(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,TO(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:"audience"===e.role?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,r,BU.frameWorkType),this._checkTrackToPublish(),EU.start()}))}exitRoom(){return nb(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return nb(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(){wM(this),this.removeAllListeners(),this._room.destroy(),VU.delete(this),0===VU.size&&EU.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 nb(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 sx(e._room.audioManager),s={},a={muted:!0};n&&(gO(n.microphoneId)?gO(n.audioTrack)||(s.customSource=n.audioTrack):s.deviceId=n.microphoneId,n&&yO(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),gO(n.profile)||(vO(n.profile)?$b[n.profile]&&o.setProfile($b[n.profile]):o.setProfile(n.profile)),yO(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),gO(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),gO(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),gO(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",(t=>{e.emit(QV.ERROR,new wV({code:RV.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(QV.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=wV.convertFrom(t.error)),e.emit(QV.PUBLISH_STATE_CHANGED,XA(QA({},t),{error:i}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),gO(r)||o.setMute(r),kM(o,o).add("player-state-changed",(t=>{e.emit(QV.AUDIO_PLAY_STATE_CHANGED,XA(QA({},t),{userId:""}))})),e.listeners(QV.AUDIO_FRAME).length>0&&(e._getPCMAbortCtrl=e._room.audioManager.getPCM((t=>{e.emit(BU.EVENT.AUDIO_FRAME,{data:t})}))),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localAudioTrack=o,e._localAudioConfig=XA(QA({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:a,track:o})}()}))}updateLocalAudio(e){return nb(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):gO(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),gO(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),gO(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!gO(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),gO(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),UO(this._localAudioConfig,e)}))}stopLocalAudio(){return nb(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),wM(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))}))}startLocalVideo(){return nb(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 lx(e._room.videoManager),a={},c={};if(o&&(o.cameraId?a.deviceId=o.cameraId:gO(o.useFrontCamera)?gO(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?tk.FACING_MODE_USER:tk.FACING_MODE_ENVIRONMENT,gO(o.profile)||(vO(o.profile)?Zb[o.profile]&&s.setProfile(Zb[o.profile]):s.setProfile(o.profile)),gO(o.fillMode)||(c.objectFit=o.fillMode),gO(o.mirror)||(c.mirror=o.mirror),gO(o.small)||(FP()?vO(o.small)?s.small=Zb[o.small]:!0===o.small?s.small=Zb["120p"]:s.small=o.small:e._log.warn("small stream is not supported"))),s.on("5",(t=>{e.emit(QV.ERROR,new wV({code:RV.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),s.on("2",(t=>{e.emit(QV.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),s.on("4",(t=>{let i;t.error&&(i=wV.convertFrom(t.error)),e.emit(QV.PUBLISH_STATE_CHANGED,XA(QA({},t),{error:i}))})),e._listenOutputTrackChanged(s),yield s.capture(a),gO(n)||(yield s.setMute(n)),s.mediaTrack){if(null!=o&&o.qosPreference){let e=ZV(o.qosPreference);s.mediaTrack.contentHint=e}else null!=o&&o.videoTrack||(s.mediaTrack.contentHint=ZV(IV.QOS_PREFERENCE_SMOOTH));s.outMediaTrack&&(s.outMediaTrack.contentHint=s.mediaTrack.contentHint)}kM(s,s).add("player-state-changed",(t=>{e.emit(QV.VIDEO_PLAY_STATE_CHANGED,XA(QA({},t),{userId:"",streamType:"main"}))})),r&&e._room.isJoined&&e._room.publish(s).catch((()=>{})),e._localVideoTrack=s,e._localVideoConfig=XA(QA({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:s})}()}))}updateLocalVideo(e){return nb(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:r,option:n}=e,o={};if(n){if(gO(n.profile)||(vO(n.profile)?Zb[n.profile]&&this._localVideoTrack.setProfile(Zb[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&gO(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):gO(n.useFrontCamera)?gO(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?tk.FACING_MODE_USER:tk.FACING_MODE_ENVIRONMENT),gO(n.fillMode)||(o.objectFit=n.fillMode),gO(n.mirror)||(o.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let e=ZV(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e,this._localVideoTrack.outMediaTrack&&(this._localVideoTrack.outMediaTrack.contentHint=e)}if(n.small){let e=!this._localVideoTrack.small;FP()?(!0===n.small?this._localVideoTrack.small=Zb["120p"]:vO(n.small)?this._localVideoTrack.small=Zb[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&&!gO(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),gO(r)||(yield this._localVideoTrack.setMute(r)),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),UO(this._localVideoConfig,e)}))}stopLocalVideo(){return nb(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),wM(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return nb(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 px(e._room.videoManager);o.on("4",(t=>{let i;t.error&&(i=wV.convertFrom(t.error)),e.emit(QV.PUBLISH_STATE_CHANGED,XA(QA({},t),{error:i}))})),e._listenOutputTrackChanged(o),"main"===t.streamType&&(o.mediaType=4);let s=null,a={},c={};n&&(gO(n.profile)||(vO(n.profile)?ek[n.profile]&&o.setProfile(ek[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(a.systemAudio=!0,a.echoCancellation=n.echoCancellation,a.noiseSuppression=n.noiseSuppression,a.autoGainControl=n.autoGainControl),gO(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=ZV(n.qosPreference);o.mediaTrack.contentHint=e}else null!=n&&n.videoTrack||(o.mediaTrack.contentHint=ZV(IV.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(tk.ENDED,(()=>{e._stopScreenShare(),e.emit(QV.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(s=new mx(e._room.audioManager),s.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&s.setAudioOutput(e._speakerId)),kM(o,o).add("player-state-changed",(t=>{e.emit(QV.VIDEO_PLAY_STATE_CHANGED,XA(QA({},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=XA(QA({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:o})}()}))}updateScreenShare(e){return nb(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(gO(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let e=ZV(r.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}this._room.isJoined&&!gO(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}),UO(this._localScreenConfig,e)}))}stopScreenShare(){return nb(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return nb(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&&(gO(n.fillMode)||(a.objectFit=n.fillMode),gO(n.mirror)||(a.mirror=n.mirror),a.canvasRender=n.canvasRender,"main"===r&&!gO(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&&!gO(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return nb(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&&(gO(s.fillMode)||(l.objectFit=s.fillMode),gO(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&&!gO(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:h}),UO(h,e);let p=gO(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=gO(r)?h.view:r,_=gO(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 nb(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return nb(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 nb(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 nb(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return nb(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return nb(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){return this.listeners(e).includes(t)||(this._log.debug("on",e),super.on(e,t,i),this._eventListened.add(e),e===BU.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM((e=>{this.emit(BU.EVENT.AUDIO_FRAME,{data:e})})))),this}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];try{XV.has(e)&&this._log.debug("emit ".concat(e," ").concat(JSON.stringify(i)))}catch(kb){}return super.emit(e,...i)}off(e,t,i){var r,n;return this._log.debug("off",e),"*"===e?(this._eventListened.clear(),this.removeAllListeners(),null==(r=this._getPCMAbortCtrl)||r.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,i),e===BU.EVENT.AUDIO_FRAME&&(null==(n=this._getPCMAbortCtrl)||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},i=null,r="main",n=!1;if(vO(t)?e=t:(e=t.userId,n=!0===t.processed,t.streamType&&(r=t.streamType)),e){let t=this._room.remotePublishedUserMap.get(e);t&&(i=t.remoteAudioTrack)}else i="sub"===r?this._localScreenAudioTrack:this._localAudioTrack;return i?n&&i.outMediaTrack&&i.outMediaTrack!==i.mediaTrack?i.outMediaTrack.clone():i.mediaTrack:null}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main",processed:r=!1}=e,n=null;if(""===t)"main"===i&&this._localVideoTrack&&(n=this._localVideoTrack),"sub"===i&&this._localScreenTrack&&(n=this._localScreenTrack);else{let e=this._room.remotePublishedUserMap.get(t);e&&(n="main"===i?e.remoteVideoTrack:e.remoteAuxiliaryTrack)}return n?r&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{userId:t,streamType:i="main"}=e;if(t){let e=this._room.remotePublishedUserMap.get(t);if("main"===i&&(null==e?void 0:e.muteState.hasVideo))return e.remoteVideoTrack.getVideoFrame();if("sub"===i&&(null==e?void 0:e.muteState.hasAuxiliary))return e.remoteAuxiliaryTrack.getVideoFrame()}else{if("main"===i&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,i;this._speakerId=e,null==(t=this._localAudioTrack)||t.setAudioOutput(e),null==(i=this._localScreenAudioTrack)||i.setAudioOutput(e),this._room.remotePublishedUserMap.forEach((t=>t.remoteAudioTrack.setAudioOutput(e)))}setCurrentSpeaker(e){return nb(this,null,(function*(){(yield wL()).forEach((t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(QV.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),UU=t)})),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')}))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return nb(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&&(gO(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(HB){throw this._remoteAudioConfigMap.delete(t),HB}this._emitTrackEvent(o)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return nb(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 nb(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),gO(t)&&n&&n.view&&!MO(i)){let e=BO(n.view);e.length>0&&(yield r.play(e,i))}if(!gO(t)){let e=BO(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return nb(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:r}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t)}catch(wb){}gO(t.muted)||i.setPlayerMute(t.muted),gO(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(QV.TRACK,{userId:i,streamType:$V(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(gO(i))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat($V(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||EO(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(BO(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 nb(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=>{wM(e.remoteAudioTrack),wM(e.remoteVideoTrack),wM(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return nb(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),wM(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_initActiveSpeaker(){return nb(this,null,(function*(){if(UU&&!RL(UU))this.emit(QV.DEVICE_CHANGED,{type:"speaker",action:"active",device:UU});else{let e=yield wL();if(e[0]&&!RL(e[0]))UU=e[0],this.emit(QV.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let e=e=>{let{track:t}=e;"audio"===t.kind&&(!UU||RL(UU))&&(this._initActiveSpeaker(),VN.off("102",this._initActiveSpeaker))};VN.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:XA(QA({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),gP.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),gP.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){tP.setLogLevel(e),gO(t)||(t?tP.enableUploadLog():tP.disableUploadLog())}static isSupported(){return wP()}static getCameraList(){return bL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return AL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return wL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(e){return nb(this,null,(function*(){(yield wL()).forEach((t=>{t.deviceId===e&&(VU.forEach((i=>{i._setCurrentSpeaker(e),i.emit(QV.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),UU=t)}))}))}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:o,version:s}=e;switch(s&&(fP.version=s),t){case"count":fP.addCount({key:i,useUV:o});break;case"enum":fP.addEnum({key:i,value:r,useUV:o});break;case"number":fP.addNumber({key:i,value:r,split:n})}}},HU=BU;ib(HU,"_loggerManager",tP),ib(HU,"EVENT",QV),ib(HU,"ERROR_CODE",RV),ib(HU,"TYPE",IV),ib(HU,"frameWorkType",30),tb([cU({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"}})})],HU.prototype,"use",1),tb([nU(UV.TRTC.enterRoom),qV("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})),qL((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),cU()],HU.prototype,"enterRoom",1),tb([cU()],HU.prototype,"exitRoom",1),tb([nU(UV.TRTC.switchRole),KV("room",{merge:(e,t)=>t}),cU()],HU.prototype,"switchRole",1),tb([cU()],HU.prototype,"destroy",1),tb([nU(UV.TRTC.startLocalAudio),qV("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)})),cU()],HU.prototype,"startLocalAudio",1),tb([nU(UV.TRTC.updateLocalAudio),KV("audio",{debounce:{delay:200,getKey:()=>"".concat(xU,"-localAudio"),isNeedToDebounce:e=>{var t;return!gO(null==(t=e.option)?void 0:t.captureVolume)}}}),cU()],HU.prototype,"updateLocalAudio",1),tb([YV("audio"),cU()],HU.prototype,"stopLocalAudio",1),tb([nU(UV.TRTC.startLocalVideo),qV("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)})),cU()],HU.prototype,"startLocalVideo",1),tb([nU(UV.TRTC.updateLocalVideo),KV("video"),cU()],HU.prototype,"updateLocalVideo",1),tb([YV("video"),cU()],HU.prototype,"stopLocalVideo",1),tb([nU(UV.TRTC.startScreenShare),qV("screen",(()=>!0)),cU()],HU.prototype,"startScreenShare",1),tb([nU(UV.TRTC.updateScreenShare),KV("screen"),cU()],HU.prototype,"updateScreenShare",1),tb([cU()],HU.prototype,"stopScreenShare",1),tb([nU(UV.TRTC.startRemoteVideo),qV((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),cU({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],HU.prototype,"startRemoteVideo",1),tb([nU(UV.TRTC.updateRemoteVideo),KV((e=>"v".concat(e.userId).concat(e.streamType))),cU({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],HU.prototype,"updateRemoteVideo",1),tb([nU(UV.TRTC.stopRemoteVideo),qL((e=>function(t){return nb(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)}))})),cU({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],HU.prototype,"stopRemoteVideo",1),tb([YV((e=>"v".concat(e.userId).concat(e.streamType)))],HU.prototype,"_stopRemoteVideo",1),tb([nU(...UV.TRTC.muteRemoteAudio),cU({getRemoteId:e=>e})],HU.prototype,"muteRemoteAudio",1),tb([oU(...UV.TRTC.setRemoteAudioVolume),function(e,t){return qL(((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=rU.get(this))?void 0:s.get(t(...n));c&&c>0&&clearTimeout(c);let l=window.setTimeout((()=>{i.apply(this,n)}),e);rU.has(this)?null==(a=rU.get(this))||a.set(t(...n),l):rU.set(this,new Map([[t(...n),l]]))}))}(200,(e=>e)),cU({getRemoteId:e=>e})],HU.prototype,"setRemoteAudioVolume",1),tb([lU("start"),zL((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),qV(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),cU({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>dP[e.getName()]})],HU.prototype,"startPlugin",1),tb([lU("update"),KV(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),cU({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>uP[e.getName()]})],HU.prototype,"updatePlugin",1),tb([lU("stop"),YV(((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i})),cU({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>hP[e.getName()]})],HU.prototype,"stopPlugin",1),tb([oU(...UV.TRTC.enableAudioVolumeEvaluation)],HU.prototype,"enableAudioVolumeEvaluation",1),tb([cU()],HU.prototype,"getVideoSnapshot",1),tb([cU()],HU.prototype,"_setCurrentSpeaker",1),tb([qV((e=>"a".concat(e.userId)),(()=>!0))],HU.prototype,"_startRemoteAudio",1),tb([qL((e=>function(t){return nb(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(XA(QA({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),YV((e=>"a".concat(e.userId)))],HU.prototype,"_stopRemoteAudio",1),tb([YV("room")],HU.prototype,"_exitRoom",1),tb([YV("screen")],HU.prototype,"_stopScreenShare",1),tb([nU(...UV.TRTC.sendSEIMessage),TV({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}})],HU.prototype,"sendSEIMessage",1),tb([nU(UV.TRTC.sendCustomMessage),TV({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],HU.prototype,"sendCustomMessage",1),tb([nU(UV.TRTC.create)],HU,"_create",1);var jU=HU,WU=class{constructor(){this._set=new Set,VN.on(ZO.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 GU(){return nb(this,null,(function*(){let e,t;try{let t=yield AL();e=t&&t.length}catch(u){}try{let e=yield bL();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:s}=this.checkSystemResult.detail,a=nP.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};FN.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),FN.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var JU=eb(ob()),zU="1",qU="2",KU="3",YU="4",QU="5",XU="6",$U={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},ZU=[$U.UPDATE_REMOTE_MUTE_STAT,$U.UPLINK_NETWORK_STATS,$U.USER_LIST_RES,$U.MUTE_RESULT,$U.SERVER_FIRST_PACKAGE_RECEIVED,$U.RECEIVE_CUSTOM_MSG],eF={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"},tF="publish_change",iF="join",rF="leave",nF="quality_report",oF="mute_uplink",sF="publish",aF="publish_state_change",cF="unpublish",lF="subscribe",dF="unsubscribe",uF="subscribe_change",hF="start_publishing",pF="stop_publishing",mF="start_push_user_cdn",_F="stop_push_user_cdn",fF="start_mcu_mix",gF="stop_mcu_mix",vF="start_publish_cdn_stream",yF="update_publish_cdn_stream",TF="stop_publish_cdn_stream",SF="get_user_list",EF="change_role",IF="update_constraint_config",RF="rebuild_pc",CF="join/v2",AF="publish/v2",bF="subscribe/v3",kF="ability_status_report",wF="reconnect",DF="channel_msg",NF=new Set;var OF=class extends JU.default{constructor(e){var t,i;super(),ib(this,"room"),ib(this,"url"),ib(this,"backupUrl"),ib(this,"race"),ib(this,"destroyed",!1),ib(this,"_socketInUse"),ib(this,"_socket"),ib(this,"_backupSocket"),ib(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),ib(this,"_currentState","DISCONNECTED"),ib(this,"_isReconnecting",!1),ib(this,"_seq",0),ib(this,"_log"),ib(this,"_lastMessageTime",-1),ib(this,"_connnectStartTime",-1),ib(this,"_stopConnectRetry"),ib(this,"bytesSent",0),ib(this,"bytesReceived",0),ib(this,"keepAlive",!1),ib(this,"signalDomainWhenUnifiedProxy"),ib(this,"stopKeepAliveTimeout"),ib(this,"rtt",0),this.room=e.room,this.race=!!gO(e.race)||e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,((null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0)-NF.size>0&&this.room.enableSPC&&(this.keepAlive=!0,NF.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=tP.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));this.signalDomainWhenUnifiedProxy&&(e+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy)));let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+="&clientIp=".concat(t)),this.race?"".concat(e,"&race=1"):e}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return"CONNECTED"===this._currentState}get isConnecting(){return"CONNECTING"===this._currentState}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return nb(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=DO();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 wO(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?tk.BACKUP:tk.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?tk.MAIN:tk.BACKUP),t(new vb({code:fb.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===tk.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(wk){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(wk){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse){if(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?tk.MAIN:tk.BACKUP),this._socketInUse=null,this.reconnect()}this.room.isJoining&&this.emit(QU,new vb({code:fb.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"}))}}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(tk.MAIN),this.unbindAndCloseSocket(tk.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(QU,new vb({code:fb.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=JO(e.data);let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values($U),o=Object.keys($U)[n.indexOf(i)],s=eF[o]||i;switch(ZU.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case $U.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,r.svrTime&&function(e){yb=e-(new Date).getTime();let t=new Date;t.setTime(e),tP.info("baseTime from server: ".concat(t," offset: ").concat(yb))}(r.svrTime),this._log.info("ChannelSetup Success"),gP.addSuccessEvent({key:521701,cost:DO()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(zU,{signalInfo:this._signalInfo});else{let e=new vb({code:fb.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:DN({key:uw,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),gP.addFailedEvent({key:521701,error:e}),this.emit(QU,e)}break;case $U.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 nb(this,null,(function*(){try{if(!this.room.joinParams)return;jN(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(bb){}}))}reconnect(){return nb(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:wF,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:eF.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),gP.addSuccessEvent({key:521702,cost:DO()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(gP.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(bb){this._log.error(bb),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+=JO(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 vb({code:fb.API_CALL_TIMEOUT,message:DN({key:dw,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 xN({retryFunction:this.sendWaitForResponse,onError:e=>{let{retry:t}=e;this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(KU,t))},onRetrying:e=>{this._log.warn("".concat(t||i," timeout observed, retrying [").concat(e,"/").concat(r,"]"))},settings:{retries:r,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),NF.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(tk.MAIN),this.unbindAndCloseSocket(tk.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(e,"s")),this.stopKeepAliveTimeout=setTimeout((()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close(),this.off(eF.JOIN_ROOM_RESULT,t)}),1e3*e);let t=e=>{0===e.data.code&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(eF.JOIN_ROOM_RESULT,t))};this.on(eF.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(qU,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(KU):"DISCONNECTED"===e&&this.emit(XU))}};tb([NM({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())}})],OF.prototype,"connect",1);var PF=eb(ob()),MF=0,LF=!1,xF=new Set,VF=!1,UF=class{constructor(e){ib(this,"userId"),ib(this,"tinyId"),ib(this,"_sdpSemantics"),ib(this,"_isUplink"),ib(this,"_room"),ib(this,"_log"),ib(this,"_signalChannel"),ib(this,"_isErrorObserved",!1),ib(this,"_waitForPeerConnectionConnectedPromise"),ib(this,"_waitForPeerConnectionConnectedPromiseReject",null),ib(this,"_peerConnection",null),ib(this,"_emitter",new PF.default),ib(this,"_currentState","DISCONNECTED"),ib(this,"_isReconnecting",!1),ib(this,"_reconnectionCount",0),ib(this,"_reconnectionTimer",-1),ib(this,"_isFirstConnection",!0),ib(this,"_prevTime",-1),ib(this,"_localAddress"),ib(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=tP.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=DO())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,gP.addSuccessEvent({key:521705,cost:Math.min(DO()-this._prevTime,3e4)})):this._isReconnecting&&gP.addSuccessEvent({key:521706,cost:DO()-this._prevTime}),this._prevTime=-1}catch(sP){throw this._isFirstConnection?(this._isFirstConnection=!1,gP.addFailedEvent({key:521705,error:sP})):this._isReconnecting&&this._reconnectionCount>=3&&gP.addFailedEvent({key:521706,error:sP}),sP}}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(),xF.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 vb({code:fb.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Rk;let e=null;if(this._isUplink){if(!jP()||0===this._peerConnection.getSenders().length)return Rk;e=this._peerConnection.getSenders()[0].transport}else{if(!HP()||0===this._peerConnection.getReceivers().length)return Rk;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:Rk}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===Ck.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===Ck.FAILED||e.target.connectionState===Ck.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new vb({message:r,code:fb.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===Ck.CONNECTED||e.target.connectionState===Ck.COMPLETED)&&(this.logSelectedCandidate(),FN.logSuccessEvent({userId:this._room.userId,eventType:Nk.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(MF=0,LF=!1,VF=!0,xF.add(this)):xF.delete(this),VN.emit(ZO.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 nb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(MP(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 vb({code:fb.API_CALL_ABORTED,message:DN({key:Fw,data:"leave room"})})))},n=()=>{VN.off(ZO.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new vb({code:fb.API_CALL_TIMEOUT,message:"connection timeout"});MF+=1,(e=>MF>2&&!LF&&0===xF.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),LF=!0,this._emitter.emit("firewall-restriction")),t(e)}),Wk);VN.on(ZO.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(KU,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=kk()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new vb({code:this._isUplink?fb.UPLINK_RECONNECTION_FAILED:fb.DOWNLINK_RECONNECTION_FAILED,message:DN({key:this._isUplink?_w:pw})});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(KU,this.reconnect,this),-1)}on(e,t,i){this._emitter.on(e,t,i)}off(e,t,i){this._emitter.off(e,t,i)}getIsReconnecting(){return this._isReconnecting}get isH264(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}setOffer(e){var t;return null==(t=this._peerConnection)?void 0:t.setLocalDescription(e)}setAnswer(e){var t;return null==(t=this._peerConnection)?void 0:t.setRemoteDescription(e)}};tb([ix(521712,!1)],UF.prototype,"setOffer",1),tb([ix(521713,!1)],UF.prototype,"setAnswer",1);var FF=eb(pb()),BF=function(e){return FF.default.parse(e)},HF=function(e){return FF.default.write(e)};function jF(e){return Object.keys(e).filter((t=>e[t]))}var WF=class extends UF{constructor(e){super(XA(QA({},e),{isUplink:!1})),ib(this,"_flag",0),ib(this,"isRobot",!1),ib(this,"role","anchor"),ib(this,"remoteAudioTrack"),ib(this,"remoteVideoTrack"),ib(this,"remoteAuxiliaryTrack"),ib(this,"ssrc",{audio:0,video:0,auxiliary:0}),ib(this,"_isSDPExchanging",!1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Tx(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new mV(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new _V(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 LO(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===tk.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===pk?tk.MAIN:tk.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=tk.AUDIO;i.kind===tk.VIDEO&&(n=r===tk.MAIN?tk.VIDEO:tk.AUXILIARY);let o=this.remoteAudioTrack;n===tk.VIDEO?o=this.remoteVideoTrack:n===tk.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=BF(e);return t.media.forEach((e=>{e.type===tk.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),HF(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=BF(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),HF(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return nb(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===Ck.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===Ck.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(wb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(wb.message," ").concat(JSON.stringify(this.muteState))),new vb({code:fb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):wb}}))}unsubscribe(e){return nb(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=QA({},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(jF(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=dF,n=eF.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=uF,n=eF.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 vb({code:i.code,message:DN({key:hw,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return nb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(t),yield e.waitForPeerConnectionConnected()}catch(wk){throw e.closePeerConnection(!0),wk}}()}))}exchangeSDP(e){return nb(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:lF,commandDesc:"exchange sdp",data:r,responseCommand:eF.SUBSCRIBE_RESULT,timeout:Mk});if(!this._peerConnection){let e=new vb({code:fb.INVALID_OPERATION,message:DN({key:Vw})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(wk){throw this._isSDPExchanging=!1,wk}}))}createOffer(){return nb(this,null,(function*(){let e={voiceActivityDetection:!1};GP()&&this._sdpSemantics===Lk?(this._peerConnection.addTransceiver(tk.AUDIO,{direction:ik.RECVONLY}),this._peerConnection.addTransceiver(tk.VIDEO,{direction:ik.RECVONLY}),this._peerConnection.addTransceiver(tk.VIDEO,{direction:ik.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield kP();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=BF(e);return t.media.forEach((e=>{var t,i;if(e.type===tk.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(" ")}})),HF(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=BF(e);return t.media.forEach((e=>{e.type===tk.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),HF(t)}(t.sdp),this._sdpSemantics===Lk&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)}))}onSubscribeResult(e){return nb(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===Vk)throw new vb({code:fb.NOT_SUPPORTED_H264,message:DN({key:Ow})});try{if(0!==t)throw new vb({code:t,message:DN({key:mw,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(n)),yield this.setAnswer({type:r,sdp:n}),this.updateSSRC(n)}catch(o){throw this._log.error(o),o}}))}updateSSRC(e){try{BF(e).media.forEach((e=>{if(e.ssrcs)if(e.type===tk.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(pk)}));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(pk)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(mk)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(wk){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return nb(this,null,(function*(){if(!(rb(WF.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(wk){let t=mO(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),t)}}))}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}get audioReceiver(){var e;return(null==(e=this._peerConnection)?void 0:e.getReceivers()[0])||null}},GF=WF;tb([qL((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 vb({code:fb.API_CALL_ABORTED,message:DN({key:Fw,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],GF.prototype,"subscribe",1),tb([ix(521717,!1)],GF.prototype,"unsubscribe",1),tb([zL(UF.prototype.afterConnect),JL(UF.prototype.beforeConnect)],GF.prototype,"connect",1);var JF=GF,zF={voiceActivityDetection:!1},qF=class extends UF{constructor(e){super(XA(QA({},e),{isUplink:!0})),ib(this,"localMainAudioTrack",null),ib(this,"localMainVideoTrack",null),ib(this,"localAuxAudioTrack",null),ib(this,"localAuxVideoTrack",null),ib(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),ib(this,"_isPublishingAux",!1),ib(this,"_publishingLocalAudioTrack"),ib(this,"_publishingLocalVideoTrack"),ib(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}),ib(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&&(WP()?(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===tk.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 nb(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(),GP()?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 nb(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||tk.AUDIO,{direction:ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?tk.VIDEO:s||tk.VIDEO,{direction:ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||tk.VIDEO,{direction:ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||tk.VIDEO,{direction:ik.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:tk.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:tk.VIDEO,videoType:o?tk.AUXILIARY:tk.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:tk.VIDEO,videoType:tk.SMALL}),e.push(2))}yield t.setTransceiverDirection(ik.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 nb(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 nb(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(ik.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ik.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 nb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!WP())return i&&i.outMediaTrack&&!r&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):r&&r.outMediaTrack&&!i&&t.localMainAudioTrack?(yield t.removeTrack(r),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),void t.emitConnectionStateChangedEvent("DISCONNECTED",r));let e=r&&r===t.localAuxVideoTrack,n=null==r?void 0:r.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localAuxAudioTrack&&!t.localMainAudioTrack&&(yield o[0].replaceTrack(null),s.push(0))),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=XA(QA({},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=XA(QA({},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(ik.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 nb(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:aF,data:t,responseCommand:eF.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:cF,commandDesc:"unpublish",responseCommand:eF.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===fb.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),XP){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:IF,data:this._mediaSettings,responseCommand:eF.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return nb(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?tk.AUXILIARY:tk.MAIN," stream")),GP()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return nb(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===tk.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===ik.INACTIVE&&(yield this.setTransceiverDirection(ik.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return nb(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;WP()&&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===tk.VIDEO&&e instanceof lx&&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===xk||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=BF(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===tk.VIDEO)return!0;return!1}removeSender(e){let t=null;WP()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&fO(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return nb(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?tk.AUXILIARY:tk.MAIN," stream")),GP()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return nb(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===tk.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(ik.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return nb(this,null,(function*(){if(!nD)return;let i=!1,r=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let n=this._peerConnection.getTransceivers();if(t.forEach((t=>{n[t].direction!==e&&(n[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this.setOffer(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(ik.INACTIVE,"|").concat(ik.RECVONLY,"|").concat(ik.SENDONLY,")")))&&o++,t.includes(o)){if(e===ik.INACTIVE&&i.includes("a=".concat(ik.RECVONLY)))return r=!0,"a=".concat(e);if(e===ik.SENDONLY&&i.includes("a=".concat(ik.INACTIVE)))return r=!0,"a=".concat(ik.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:s}))}))}removeTrackBySender(e){return nb(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===tk.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===tk.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===tk.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return nb(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=GP()?e.kind===tk.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?tk.AUXILIARY:tk.MAIN," stream")),e.kind===tk.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===tk.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack)),!0}))}updateOffer(e,t){return nb(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(zF);nD&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this.setOffer(i);let r=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===tk.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:tF,data:n,responseCommand:eF.UPDATE_OFFER_RESULT,timeout:Pk,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(kb){throw this._log.error(kb),kb}}))}setBandwidth(e){return nb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!YP())return o?r===tk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(GP()){let t=0;r===tk.VIDEO&&(t=n===tk.SMALL?2:n===tk.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===tk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";nD&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===tk.SMALL?n=1:i===tk.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 nD&&(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 nb(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(bb){throw this.closePeerConnection(!0),this.uninstallEvents(),bb}}))}exchangeSDP(){return nb(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(bb){throw bb}}))}createOffer(){return nb(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(zF);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(bb){throw bb}}))}doExchangeSDP(){let e={command:sF,responseCommand:eF.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof px||this.localAuxVideoTrack instanceof px,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=BF(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),HF(r)}acceptAnswer(e){return nb(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?tk.AUXILIARY:tk.BIG;s=yield this.setBandwidth({bandwidth:e,type:tk.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:tk.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:tk.VIDEO,videoType:tk.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this.setAnswer(a),this._log.debug("accepted answer: ".concat(s))}catch(HB){throw this._log.error("failed to accept remote answer ".concat(HB)),HB}}))}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(oF,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return nb(this,null,(function*(){if(!(rb(qF.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:cF,responseCommand:eF.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(wk){let t=mO(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)&&VN.emit(ZO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{BF(e).media.forEach(((e,t)=>{if(e.type===tk.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===xk&&e.ssrcGroups)return void e.ssrcGroups.forEach(((e,t)=>{let i=Number(e.ssrcs.split(" ")[0]);0===t?this.ssrc.video=i:1===t&&(this.ssrc.small=i)}));let i=e.ssrcs&&e.ssrcs[0];if(!i)return;switch(t){case 1:this.ssrc.video=Number(i.id);break;case 2:this.ssrc.small=Number(i.id);break;case 3:this.ssrc.auxiliary=Number(i.id)}}}))}catch(wk){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===tk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===tk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===tk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===tk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Vk?(this._log.error(Hw.NOT_SUPPORTED_H264ENCODE),new vb({code:fb.NOT_SUPPORTED_H264,message:DN({key:Nw})})):new vb({code:fb.UNKNOWN,message:DN({key:Lw,data:{signalResponse:eF.PUBLISH_RESULT,code:e,message:t}})})}},KF=qF;tb([qL((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 vb({code:fb.API_CALL_ABORTED,message:DN({key:Fw,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],KF.prototype,"publish",1),tb([ix(521715,!1)],KF.prototype,"unpublish",1),tb([zL(UF.prototype.afterConnect),JL(UF.prototype.beforeConnect)],KF.prototype,"connect",1);var YF=KF,QF=class{constructor(e,t){this.room=e,ib(this,"_log"),ib(this,"_prevReportTime",0),ib(this,"_prevReport",{}),ib(this,"_prevStats",null),ib(this,"_prevEncoderImplementation",""),ib(this,"_prevAuxEncoderImpl",""),ib(this,"_prevQualityLimitationReason",""),ib(this,"_prevAuxQualityLimitationReason",""),ib(this,"_prevDecoderImplementationMap",new Map),ib(this,"totalBytesSent",0),ib(this,"totalBytesReceived",0),ib(this,"_spcStats",null),this._log=t}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return nb(this,null,(function*(){var t;let i={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},r=e.getPeerConnection(),n=e.getSSRC();if(r)try{if((this._spcStats||(yield r.getStats())).forEach((t=>{var r,o,s;let a,c;if("outbound-rtp"===t.type)if((t.mediaType||t.kind)===tk.VIDEO){if(t.ssrc===n.video?(a=tk.VIDEO,c=e.localMainVideoTrack):t.ssrc===n.small?a=tk.SMALL:t.ssrc===n.auxiliary&&(c=e.localAuxVideoTrack,a=tk.AUXILIARY),!a)return;if(i[a].bytesSent=t.bytesSent,i[a].packetsSent=t.packetsSent,i[a].framesEncoded=t.framesEncoded,gO(t.keyFramesEncoded)||(i[a].keyFramesEncoded=t.keyFramesEncoded),gO(t.nackCount)||(i[a].nackCount=t.nackCount),gO(t.pliCount)||(i[a].pliCount=t.pliCount),gO(t.retransmittedPacketsSent)||(i[a].retransmittedPacketsSent=t.retransmittedPacketsSent),gO(t.totalEncodeTime)||(i[a].totalEncodeTime=t.totalEncodeTime),gO(t.totalPacketSendDelay)||(i[a].totalPacketSendDelay=t.totalPacketSendDelay),!gO(t.encoderImplementation)&&(a===tk.VIDEO&&this._prevEncoderImplementation!==t.encoderImplementation||a===tk.AUXILIARY&&this._prevAuxEncoderImpl!==t.encoderImplementation)){let i=2,r=this._prevEncoderImplementation;a===tk.AUXILIARY&&(i=7,r=this._prevAuxEncoderImpl),VN.emit("262",{userId:e.userId,streamType:i,prevImplementation:r,implementation:t.encoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientEncoder}),this[a===tk.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=t.encoderImplementation,this._log.info("".concat(a===tk.AUXILIARY?"aux ":"","encoderImplementation change to ").concat(t.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(t.powerEfficientEncoder))}t.ssrc===n.video?!gO(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),VN.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:null==(r=e.localMainVideoTrack)?void 0:r.isQosClearFirst}),this._prevQualityLimitationReason=t.qualityLimitationReason):t.ssrc===n.auxiliary&&!gO(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),VN.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(o=e.localAuxVideoTrack)?void 0:o.isQosClearFirst}),this._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else i.audio.bytesSent=t.bytesSent,i.audio.packetsSent=t.packetsSent;else"candidate-pair"===t.type?MP(t)&&(this.totalBytesSent=t.bytesSent,yO(t.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*t.currentRoundTripTime))):"media-source"===t.type&&(t.kind===tk.AUDIO?(i.audio.audioLevel=t.audioLevel||0,i.audio.totalAudioEnergy=t.totalAudioEnergy||0,t.echoReturnLoss,t.totalSamplesDuration&&(i.audio.totalSamplesDuration=t.totalSamplesDuration)):t.kind===tk.VIDEO&&(t.trackIdentifier===e.getVideoTrackId(tk.VIDEO)?i.video.fpsCapture=t.framesPerSecond:t.trackIdentifier===e.getVideoTrackId(tk.AUXILIARY)?i.auxiliary.fpsCapture=t.framesPerSecond:i.small.fpsCapture=t.framesPerSecond));if(!gO(t.audioLevel)&&(null==(s=e.localMainAudioTrack)?void 0:s.mediaTrack)&&t.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(i.audio.audioLevel=t.audioLevel||0),!gO(t.frameWidth)){let r=tk.SMALL;t.trackIdentifier===e.getVideoTrackId(tk.VIDEO)||t.ssrc===n.video?r=tk.VIDEO:(t.trackIdentifier===e.getVideoTrackId(tk.AUXILIARY)||t.ssrc===n.auxiliary)&&(r=tk.AUXILIARY),i[r].frameWidth=t.frameWidth,i[r].frameHeight=t.frameHeight,i[r].framesSent=t.framesSent}})),e.localMainAudioTrack){let t=e.localMainAudioTrack.getInternalAudioLevel();i.audio.micAudioLevel=t,0===i.audio.audioLevel&&(i.audio.audioLevel=t)}this.totalBytesSent||(this.totalBytesSent+=i.audio.bytesSent+i.video.bytesSent+i.auxiliary.bytesSent),Object.keys(i).forEach((t=>{t===tk.AUDIO?(e.localMainAudioTrack&&(e.localMainAudioTrack.stat=i[t]),e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=i[t])):t===tk.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=i[t]):t===tk.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=i[t])}))}catch(wb){this._log.warn("failed to getStats on sender connection ".concat(wb))}return 0===i.rtt&&(i.rtt=(null==(t=this.room.networkQuality)?void 0:t.uplinkRTT)||0),i}))}getReceiverStats(e){return nb(this,null,(function*(){var t;let i={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}},r=e.getPeerConnection();if(r)try{let{ssrc:t}=e,{muteState:n,subscribeState:o}=e;(this._spcStats||(yield r.getStats())).forEach((r=>{if("inbound-rtp"===r.type){let s=(r.mediaType||r.kind)===tk.AUDIO;if(s){if(r.ssrc!==t.audio||!n.hasAudio)return;i.audio.packetsReceived=r.packetsReceived,i.audio.bytesReceived=r.bytesReceived,i.audio.packetsLost=r.packetsLost,r.insertedSamplesForDeceleration&&(i.audio.insertedSamplesForDeceleration=r.insertedSamplesForDeceleration),r.removedSamplesForAcceleration&&(i.audio.removedSamplesForAcceleration=r.removedSamplesForAcceleration),r.totalSamplesDuration&&(i.audio.totalSamplesDuration=r.totalSamplesDuration),r.totalSamplesReceived&&(i.audio.totalSamplesReceived=r.totalSamplesReceived),r.concealedSamples&&(i.audio.concealedSamples=r.concealedSamples);let{remoteAudioTrack:o}=e;o.stat.packetsReceived=r.packetsReceived,o.stat.bytesReceived=r.bytesReceived,o.stat.packetsLost=r.packetsLost,i.audio.p2pDelay=o.stat.end2EndDelay,i.hasAudio=!0}else{if(nD&&0===r.bytesReceived)return;let s;r.ssrc===t.video&&n.hasVideo&&(i.video.packetsReceived=r.packetsReceived,i.video.bytesReceived=r.bytesReceived,i.video.packetsLost=r.packetsLost,i.video.framesReceived=r.framesReceived,i.video.framesDecoded=r.framesDecoded,i.video.fpsDecoded=r.framesPerSecond,i.hasVideo=!0,s=e.remoteVideoTrack,n.hasSmall&&o.smallVideo&&(i.isSmallSubscribed=!0),r.decoderImplementation&&(!this._prevDecoderImplementationMap.has(i.userId)||this._prevDecoderImplementationMap.get(i.userId)!==r.decoderImplementation)&&(this._log.info("".concat(i.userId," decoderImplementation change to ").concat(r.decoderImplementation," HWDecoder: ").concat(r.powerEfficientDecoder)),VN.emit("262",{userId:this.room.userId,remoteUserId:i.userId,prevImplementation:this._prevDecoderImplementationMap.get(i.userId),implementation:r.decoderImplementation,codec:e.videoCodec,isHWCodec:r.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(i.userId,r.decoderImplementation))),r.ssrc===t.auxiliary&&n.hasAuxiliary&&(i.auxiliary.packetsReceived=r.packetsReceived,i.auxiliary.bytesReceived=r.bytesReceived,i.auxiliary.packetsLost=r.packetsLost,i.auxiliary.framesReceived=r.framesReceived,i.auxiliary.framesDecoded=r.framesDecoded,i.auxiliary.fpsDecoded=r.framesPerSecond,s=e.remoteAuxiliaryTrack,i.hasAuxiliary=!0),s&&(s.stat.packetsReceived=r.packetsReceived,s.stat.bytesReceived=r.bytesReceived,s.stat.packetsLost=r.packetsLost,s.stat.framesReceived=r.framesReceived,s.stat.framesDecoded=r.framesDecoded,r.jitterBufferDelay&&(s.stat.jitterBufferDelay=Math.floor(r.jitterBufferDelay/r.jitterBufferEmittedCount*1e3)))}r.jitterBufferDelay&&(s?(i.audio.totalJitter=r.jitterBufferDelay,i.audio.totalJitterCount=r.jitterBufferEmittedCount):r.ssrc===t.video&&n.hasVideo?(i.video.totalJitter=r.jitterBufferDelay,i.video.totalJitterCount=r.jitterBufferEmittedCount):r.ssrc===t.auxiliary&&n.hasAuxiliary&&(i.auxiliary.totalJitter=r.jitterBufferDelay,i.auxiliary.totalJitterCount=r.jitterBufferEmittedCount))}else"candidate-pair"===r.type&&MP(r)&&(this.totalBytesReceived=r.bytesReceived,yO(r.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*r.currentRoundTripTime)));gO(r.frameWidth)||((r.trackIdentifier===e.getMainStreamVideoTrackId()||r.ssrc===t.video)&&(i.video.frameWidth=r.frameWidth,i.video.frameHeight=r.frameHeight,e.remoteVideoTrack.stat.frameWidth=r.frameWidth,e.remoteVideoTrack.stat.frameHeight=r.frameHeight),(r.trackIdentifier===e.getAuxStreamVideoTrackId()||r.ssrc===t.auxiliary)&&(i.auxiliary.frameWidth=r.frameWidth,i.auxiliary.frameHeight=r.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=r.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=r.frameHeight)),!gO(r.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&r.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(i.audio.audioLevel=r.audioLevel||0,i.audio.totalAudioEnergy=r.totalAudioEnergy||0)})),0===i.audio.audioLevel&&e.muteState.audioAvailable&&(i.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=i.audio.bytesReceived+i.video.bytesReceived+i.auxiliary.bytesReceived)}catch(n){this._log.warn("failed to getStats on receiver connection ".concat(n))}return 0===i.rtt&&(i.rtt=(null==(t=this.room.networkQuality)?void 0:t.uplinkRTT)||0),i}))}getStats(e,t){return nb(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=DO(),n=yield e.getStats(),o=DO();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(FL(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(!FL(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*lw,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*lw),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(_k)),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(fk)),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),MD&&115===$D()&&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),gO(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),gO(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),gO(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),gO(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),gO(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/o)),gO(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(FL(e.msg_audio_status)||FL(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 nb(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}},XF=eb(ob());function $F(e){return new Promise((t=>nb(this,null,(function*(){let i=setTimeout((()=>{t({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})}),1e4),r=Date.now(),n="https://".concat(e,"/?t=").concat(r);try{yield fetch(n)}catch(wb){}clearTimeout(i);let o=function(e){let t={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let i=performance.getEntriesByType("resource").reverse();for(let r of i)if(r.name===e){let e=Math.round(r.duration),i=Math.max(Math.round(r.domainLookupStart-r.startTime),0),n=r.redirectStart>0?Math.max(Math.round(r.redirectEnd-r.redirectStart),0):0,o=r.fetchStart>0?Math.max(Math.round(r.domainLookupStart-r.fetchStart),0):0,s=Math.round(r.domainLookupEnd-r.domainLookupStart),a=Math.round(r.requestStart-r.secureConnectionStart),c=Math.round(r.secureConnectionStart-r.connectStart),l=Math.round(r.responseStart-r.requestStart),d=Math.round(r.responseEnd-(r.responseStart||r.startTime));t=XA(QA({},t),{totalCost:e,local:i,redirect:n,httpCache:o,dns:s,tcp:c,tls:a,request:l,response:d});break}}catch(i){}return t}(n);0===o.totalCost&&(o.totalCost=Date.now()-r),t(o)}))))}var ZF=class extends XF.default{constructor(e){let{signalChannel:t,room:i}=e;super(),ib(this,"_room"),ib(this,"_signalChannel"),ib(this,"_log"),ib(this,"uplinkRTT",0),ib(this,"uplinkLoss",0),ib(this,"downlinkRTT",0),ib(this,"downlinkLoss",0),ib(this,"pingResults",{}),ib(this,"_downlinkPrevStatMap",new Map),ib(this,"_downlinkLossAndRTTMap",new Map),ib(this,"_interval",-1),ib(this,"_uplinkNetworkQuality",0),ib(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=tP.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:i}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(t,", loss: ").concat(i," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(eF.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(qU,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,i;if(0!==e.data.code)return;let r=e.data.data;if(r.delay&&this.updateDelay(r.delay),this._room.signalChannel&&r.wsRtt&&(this._room.signalChannel.rtt=r.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);let n=null==(i=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:i.getPeerConnection();if(n&&this.isPeerConnectionDisconnected(n))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);let o=r.expectAudPkg+r.expectVidPkg,s=r.recvAudPkg+r.recvVidPkg,a=o-s;0===o&&0===s||(this.uplinkLoss=a<=0?0:Math.round(a/o*100),this.uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return nb(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)===Ck.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let n=0;n<t.length;n++){let e=t[n].getPeerConnection();if(!e)return;let{rtt:i,totalPacketsLost:r,totalPacketsReceived:o}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o});continue}let s=0,a=this._downlinkPrevStatMap.get(e),c=r-a.totalPacketsLost,l=o-a.totalPacketsReceived;s=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:s,userId:t[n].getUserId(),audioDelay:t[n].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[n].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach((e=>{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:i,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=i,this.downlinkLoss=r,this.downlinkNetworkQuality=this.getNetworkQuality(r,i)}))}getStat(e){return nb(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!HP())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&&yO(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===tk.AUDIO||e.mediaType===tk.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return 0===t.rtt&&(t.rtt=this.uplinkRTT),t}catch(r){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){"DISCONNECTED"===e.state?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):"CONNECTED"===e.state&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(e){let{state:t}=e;"DISCONNECTED"===t?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):"CONNECTED"===t&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==Ck.DISCONNECTED&&e.connectionState!==Ck.FAILED&&e.connectionState!==Ck.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=RM.run(tw,(()=>{var e;this.handleDownlinkNetworkQuality();let t=[...this._downlinkLossAndRTTMap.values()];VN.emit(ZO.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:t});let i=null==(e=this._room.scheduleResult.config)?void 0:e.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};i&&(r=XA(QA({},r),{pingResults:this.uplinkRTT>i.rttThreshold||this.downlinkRTT>i.rttThreshold?this.pingResults:{}})),this.emit(ZF.EVENT_NETWORK_QUALITY,r);let n=Date.now();if(i&&(this.uplinkRTT>i.rttThreshold||this.downlinkRTT>i.rttThreshold)&&n-ZF.lastPingTime>1e3*i.interval){ZF.lastPingTime=Date.now();let e=i.domain.map((e=>$F(e).then((t=>({domain:e,cost:t.totalCost})))));Promise.all(e).then((e=>{this.pingResults.isPoorNetwork=e.some((e=>e.cost>700)),this.pingResults.timestamp=n,this.pingResults.data=e,e.forEach((e=>{kvStatManager.addSuccessEvent({key:KV_REPORT_KEY_NETWORK.PING,cost:e.cost})})),this._log.warn("All ping results: ".concat(JSON.stringify(e)))})).catch((e=>{this._log.warn("Error during pinging domains: ".concat(e))}))}}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.debug("stopped"),-1!==this._interval&&(RM.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})}}))}},eB=ZF;ib(eB,"EVENT_NETWORK_QUALITY","0"),ib(eB,"lastPingTime",0);var tB=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.isDestroyed=!1,this._frameWorkType=e.frameWorkType||30,this._component=e.component||0,this.connectionType=e.connectionType||1,this._language=e.language||0,this._room=e.room,this._keyPrefix="key_point",this._log=tP.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&fO(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 CO(o)?o.catch((e=>tP.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(wk){tP.error("".concat(t.name,"() error observed ").concat(wk))}}}({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:Cb,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,yN().then((e=>{this._basicInfo.string_os_version=AN(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),VN.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(ZO.JOIN_START,this.handleJoinStart).addEvent(ZO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(ZO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(ZO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(ZO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(ZO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(ZO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(ZO.JOIN_FAILED,this.handleJoinFailed).addEvent(ZO.LEAVE_START,this.handleLeaveStart).addEvent(ZO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(ZO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(ZO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(ZO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(ZO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(ZO.PUBLISH_START,this.handlePublishStart).addEvent(ZO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(ZO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(ZO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(ZO.PLAY_TRACK_START,this.handlePlayStart).addEvent(ZO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(ZO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!RO(t)||!this.hitTest(t.room)||"PLAYING"===i&&(r===tk.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(ZO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(ZO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(ZO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(ZO.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(ZO.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)=>VN.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),RM.clearTask(this._intervalId),0===this._pathJoinRoom.uint64_start_time&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(e){this.hitTest(e.room)&&(0===this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_start_time=Date.now()),e.params&&(gO(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),gO(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),gO(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 vb?Number(i.getExtraCode()||i.getCode()):fb.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:XA(QA({},rB),{msg_user_info:new nB({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 nB({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(!RO(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(!RO(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/lw*100)>0&&(this._localStreamStat.totalAudioLevel+=e/lw,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*KA(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/lw*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/lw,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 vb?i.getExtraCode()||i.getCode():fb.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&ok))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&ck))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&ak))>=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,tk.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,tk.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,iB);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>iB&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+iB):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>iB&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+iB):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>iB&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+iB)}getReportData(){this._basicInfo.uint32_networkType=nO();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new nB({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:VO(this._signalInfo.relayIp),uint32_client_ip:VO(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*KA(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:VO(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return YO(e),e}report(){return nb(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(sP){this._log.warn(sP)}finally{this.isDestroyed&&(this._room=null)}}))}upload(e){return nb(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=yield cw(e),r=i instanceof ArrayBuffer,n="".concat(ZN(t,Gb.KEY_POINT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i));let s=[this.uploadKVStat(gP),this.uploadKVStat(fP)];o||s.push(aw({url:n,body:i})),yield Promise.all(s)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return nb(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=XA(QA({},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 cw(t),r="".concat(ZN(+this._room.sdkAppId,Gb.KV_STAT),"&gzip=").concat(+(i instanceof ArrayBuffer)),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(r,i)),n||aw({url:r,body:i})}))}};tb([NM({settings:{timeout:500,retries:3}})],tB.prototype,"upload",1);var iB=5e3,rB={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},nB=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},oB=tB,sB=class{constructor(){ib(this,"_startTime"),ib(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=DO())}stop(){0===this._endTime&&(this._endTime=DO())}getDuration(){return 0===this._endTime?DO()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},aB=class{constructor(e){ib(this,"_room",null),ib(this,"_durationMap"),ib(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(ZO.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(ZO.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(ZO.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"),tk.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_","main"),tk.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_","auxiliary"),tk.VIDEO);let s=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);!s||(!i.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,tk.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,tk.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,tk.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>VN.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>VN.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 sB,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,tk.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let e=new sB,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,tk.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,tk.AUDIO),this.stopDurationItem(o,tk.VIDEO)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new sB,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===tk.AUDIO?[n]:[],video:t===tk.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()}},cB=class{constructor(e){ib(this,"_room"),ib(this,"_renderFreezeMap",new Map),ib(this,"_isVideoPlayingEventFiredMap",new Map),ib(this,"_dataFreezeMap",new Map),ib(this,"_monitorFreezeData",new Map),ib(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(ZO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(ZO.PLAY_TRACK_START,this.onPlayTrackStart).set(ZO.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(ZO.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(ZO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(RO(t)&&this.hitTest(t.room)&&n===tk.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===tk.MUTE?this.onVideoTrackMuted(t):r===tk.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(ZO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>VN.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>VN.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 sB;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>Fk?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 nb(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=DO();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=DO();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!RO(t)||!this.hitTest(t.room)||t.kind!==tk.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()<Fk&&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=DO()-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()}},lB=eb(ob(),1),dB=[1,0,0,0,1,1,0,1],uB=class extends Ix{constructor(e,t){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:t}),e instanceof hV)try{this.setTexBuffer(dB)}catch(wk){e.destroy(new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(wk.message||wk)}))}}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)}},hB=class{constructor(e,t){this.node=e,this.layout=t,ib(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}},pB=class extends Ix{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),ib(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new hB(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 hV&&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},QA({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 hV))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(r){}}))}},mB=class extends lV{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log}),ib(this,"_bgTexture"),ib(this,"_waterMarkTexture"),ib(this,"_lastMaskTexture"),ib(this,"_lastMaskFbo"),ib(this,"_textureValid",!1),ib(this,"_selfieTextureValid",!1),ib(this,"_selfieSegmentation"),ib(this,"wasm"),ib(this,"_prePrograme"),ib(this,"_segmentationMask"),ib(this,"_weixin",!1),t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(t)}catch(kb){e.log.error(kb),e.destroy(new vb({code:fb.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(kb.message||kb)}))}}init(e){var t,i;let r=e.Wasm,n=this.context.ctx;if(this.wasm=new r.AllIn1(n),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:i,width:r,height:n}=e.waterMark;this.wasm.setWaterMark(t,i,r,n)}if(e.beautyParams){let{beauty:r,brightness:n,ruddy:o}=e.beautyParams;this.wasm.setBeauty(r,n,o,null==(t=this.context._canvas)?void 0:t.width,null==(i=this.context._canvas)?void 0:i.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.uniform1i(n.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(n.uniform1i(n.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(n.uniform1i(n.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),n.uniform1i(n.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(n.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\nuniform sampler2D u_texture;\nuniform sampler2D mask;\n\nin vec2 v_texCoord;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);\n}"),t=this.context.createShader(n.VERTEX_SHADER,"#version 300 es\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_texCoord;\nvoid main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n v_texCoord = a_texCoord;\n}");this._prePrograme=this.context.createProgram(t,e),n.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.uniform1i(n.getUniformLocation(this._prePrograme,"mask"),1)}}onPredict(e){var t;let i=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():null==this||this._selfieSegmentation.bindTexture(),i.activeTexture(i.TEXTURE1),null==(t=this._selfieSegmentation)||t.bindTexture2d(e),i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,this._bgTexture||null),i.activeTexture(i.TEXTURE3),i.bindTexture(i.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),i.drawArrays(i.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){var t,i,r,n;let o=this.context.ctx,{image:s}=this;this.tryVideoFrameCallback(s);let{videoWidth:a,videoHeight:c}=s;s.width=a,s.height=c;let l=!1;if(this.totalFrames)this._weixin?this.useTexture():null==(t=this._selfieSegmentation)||t.bindTexture(),l=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),l=this._textureValid,this._textureValid=!0}return this.width===a&&this.height===c&&l?o.texSubImage2D(o.TEXTURE_2D,0,0,0,o.RGBA,o.UNSIGNED_BYTE,s):(this.resize(a,c),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,s)),this._weixin&&(o.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(o.activeTexture(o.TEXTURE1),null==(i=this._selfieSegmentation)||i.bindTexture2d(this._segmentationMask),o.bindFramebuffer(o.FRAMEBUFFER,this._lastMaskFbo||null)),o.drawArrays(o.TRIANGLE_STRIP,0,4),null==(r=this._selfieSegmentation)||r.bindTexture(),this._segmentationMask?o.copyTexSubImage2D(o.TEXTURE_2D,0,0,0,0,0,a,c):o.copyTexImage2D(o.TEXTURE_2D,0,o.RGBA,0,0,a,c,0)),null==(n=this._selfieSegmentation)||n.send(a,c),this.totalFrames||(o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this._bgTexture||null),o.activeTexture(o.TEXTURE3),o.bindTexture(o.TEXTURE_2D,this._waterMarkTexture||null),o.drawArrays(o.TRIANGLE_STRIP,0,4)),!1}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&t.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&t.deleteProgram(this._prePrograme),null==(e=this.wasm)||e.close()}},_B=class extends lB.EventEmitter{constructor(e){super(),this.room=e,ib(this,"videoContext"),ib(this,"_glVideoContext"),ib(this,"_2dVideoContext"),ib(this,"destination"),ib(this,"smallVideoContext"),ib(this,"smallDestination"),ib(this,"smallTrackSource"),ib(this,"smallImageSource"),ib(this,"_isMirror",!1),ib(this,"cameraTrack"),ib(this,"cameraNode"),ib(this,"mirrorNode"),ib(this,"mixNode"),ib(this,"screenTrack"),ib(this,"screenNode"),ib(this,"selfModel",!1),ib(this,"blurRadius",3),ib(this,"arTrack"),ib(this,"Wasm"),ib(this,"waterMarkNode"),ib(this,"_waterMarkOption"),ib(this,"watermarkImageList",[]),ib(this,"_beautyParams"),ib(this,"isUsingArTrack",!1),ib(this,"_isMixScreen",!1),ib(this,"_virtualBackground"),ib(this,"_virtualBackgroundAbortCallback"),ib(this,"virtualBackgroundInstance"),ib(this,"_bgAssetPath"),ib(this,"log",tP.createLogger({id:"vm"})),ib(this,"_checkId",0),ib(this,"_use2d",!1),ib(this,"_autoSwitchRenderMode",!0),ib(this,"_selfieSegmentation"),ib(this,"encodePipeline",[]),ib(this,"decodePipeline",[]),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new pV({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 pV({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new hV({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on("unavailable",(e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),null==(t=this._virtualBackgroundAbortCallback)||t.call(this,e),this.update()}))}catch(bb){this.emit("error",bb)}}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=RM.run(rw,(()=>{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(),RM.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(oN||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?gP.addFailedEvent({key:t,error:e}):gP.addSuccessEvent({key:t})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else{if(!t)return!0;if(!this._use2d)return!0;this.clear()}}else{if(this._glVideoContext=new hV({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return null==(e=this.smallDestination)?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return null==(e=this.cameraTrack)?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var t;try{let i=this.cameraTrack,{small:r,settings:n,player:o}=i;r?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new sV(this.smallVideoContext,r,this.log)),this.smallVideoContext.frameRate=r.frameRate,this.smallDestination.resolution=r,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),oN&&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(kb){this.log.error("set main output failed",kb)}}update(){return nb(this,null,(function*(){var e,t;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:i,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),16===lN?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof lV?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof lV?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(i.width,i.height)):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new oV(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new mB(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=r.frameRate,this._use2d){let i=this.cameraNode;i.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new uB(this.videoContext,this.log)),i=i.connect(this.mirrorNode),i.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new pB(this.videoContext,this.log),i.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),null==(e=this.waterMarkNode)||e.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),null==(t=this.screenNode)||t.connect(this.mixNode,{zIndex:0}),i=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))),i.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext._canvas)}))}changeInput(e){var t,i,r,n;if(e instanceof px)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof lx)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof mV){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);let t=e.mediaTrack;return e.setOutputMediaStreamTrack(t)}this.log.warn("change unknown input",null==(n=e.mediaTrack)?void 0:n.label)}configPipeline(e){}removeInput(e){var t;e instanceof px?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof lx?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof mV&&e.source&&e.source.context.destroy()}setCameraTrack(e){return nb(this,null,(function*(){this.cameraTrack=e,this.update()}))}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return nb(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 vb({code:fb.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)})),qO(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 nb(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return nb(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return nb(this,null,(function*(){let t;try{t=yield qO((null==e?void 0:e.imageElement)||e.imageUrl)}catch(c){throw new vb({code:fb.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 nb(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 nb(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 nb(this,null,(function*(){if(e){if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,"image"===e.type?this._virtualBackground=yield qO(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}else delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;if(this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat((null==e?void 0:e.type)||"",", ").concat(this.blurRadius||"")),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new vb({code:fb.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})}))}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return nb(this,null,(function*(){var e;null==(e=this.cameraTrack)||!e.mediaTrack||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))}))}disableAr(){var e;this.isUsingArTrack=!1,null==(e=this.arTrack)||e.stop(),this.arTrack=void 0,this.update()}clear(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(e){let{processor:t,type:i}=e;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t)}addDecodeProcessor(e){let{processor:t,type:i}=e;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t)}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}},fB=0,gB=class extends yM{constructor(e){super("room"),this.seq=++fB,this.role="anchor",this.joinParams=null,this.localTracks=new Set,this.enableAutoPlayDialog=!0,this.autoReceiveAudio=!0,this.autoReceiveVideo=!0,this.checkSystemResult={result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0}},this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this._isUsingCachedSchedule=!1,this._log=tP.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this.isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,TO(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),TO(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),TO(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new oB({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new aB({room:this}),this.badCaseDetector=new cB({room:this}),this.audioManager=new fx(this),this.videoManager=new _B(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(4&e.mediaType)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(2&e.mediaType)return e;return null}getLogger(){return this._log}get isJoining(){return"joining"===this.state.toString()}get isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return nb(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return nb(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return nb(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(vO(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(hO(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?(JN([o,o]),Mb("https://".concat(o))):(r&&Mb(r),n&&JN(n))}VN.once(ZO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:GN.main,sched_back_domain:GN.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return nb(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return nb(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 nb(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 vb({code:fb.INVALID_OPERATION,message:DN({key:kw,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Hw.INVALID_DESTROY),new vb({code:fb.INVALID_OPERATION,message:DN({key:Iw})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,VN.emit(ZO.ROOM_DESTROY,{room:this})}schedule(e,t){return nb(this,null,(function*(){var i,r;let n=DO();try{let{isCached:o,result:s,detailCost:a}=yield WN({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Cb,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(WO(s,{keysToExclude:["username","credential"]}))),o&&VN.once(ZO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=QA(QA({},this.scheduleResult),s),yO(null==(i=s.config)?void 0:i.retryCount)&&bk(s.config.retryCount),vO(null==(r=s.config)?void 0:r.loggerDomain)&&Mb(s.config.loggerDomain),VN.emit(ZO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:a}),gP.addSuccessEvent({key:521700,cost:DO()-n,split:50})}catch(o){throw gP.addFailedEvent({key:521700,error:o}),o}}))}},vB=eb(ob(),1),yB=Symbol("instance"),TB=Symbol("cacheResult"),SB=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,AB.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},EB=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var IB=new Map;function RB(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=IB.get(r)||[];IB.has(r)||IB.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=bB.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return r[TB];r.state instanceof SB&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;if(Array.isArray(e)?0==e.length?r.state instanceof SB&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new EB(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 EB(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 SB(d,t,s);AB.call(r,u);let h=e=>{var n;return r[TB]=e,u.aborted||(AB.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[TB])),e},p=e=>{let t=e instanceof Error?e.message:String(e);if(AB.call(r,d,e),!i.fail){if(i.ignoreError)return e;throw e}i.fail.call(this,new EB(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 CB="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 AB(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(bB.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var bB=class extends vB.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=bB.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[yB];r?this.name=r.name+"-"+r.count++:i[yB]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=IB.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);IB.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=bB.instances.get(e),t||bB.instances.set(e,t=new bB(e,void 0,Object.create(bB.prototype)))):(t=bB.instances2.get(e),t||bB.instances2.set(e,t=new bB(e.constructor.name,void 0,Object.create(bB.prototype)))),t}static getState(e){var t;return null===(t=bB.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};CB(bB.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){AB.call(this,e)}};bB.STATECHANGED="stateChanged",bB.UPDATEAFSM="updateAFSM",bB.INIT="[*]",bB.ON="on",bB.OFF="off",bB.instances=new Map,bB.instances2=new WeakMap;var kB=eb(ob()),wB=eb(pb());function DB(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 NB=(e,t)=>nb(void 0,null,(function*(){var i;let r=BF(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=[...DB(s)].filter((e=>c.includes(e.codec.toLocaleLowerCase()))),n.video.decoders=(yield function(){return nb(this,null,(function*(){let e=new RTCPeerConnection;e.addTransceiver(tk.VIDEO,{direction:tk.TRANSCEIVER_DIRECTION_RECVONLY});let t=yield e.createOffer();if(!t.sdp)return[];let i=DB(BF(t.sdp).media[0]);return e.close(),i}))}()).filter((e=>["h264","vp8"].includes(e.codec.toLocaleLowerCase()))),n})),OB=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,o=BF(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:tk.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:tk.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(PB({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),n&&s.media.push(o.media.find((e=>"dc"===e.mid))),HF(s)},PB=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:tk.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:tk.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(o)(i.video.decoders||i.video.codecs).forEach((e=>{MB(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];MB(s,t)}return s},MB=(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 LB=(e,t,i)=>{let r=wB.default.parse(e);return r.media.forEach(((e,n)=>{var o;(e.type===tk.AUDIO||e.type===tk.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===tk.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===tk.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===tk.VIDEO&&(n<4?(e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach((t=>MB(e,t)))):i&&(e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],(i.video.decoders||i.video.codecs).forEach((t=>MB(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")})),wB.default.write(r)},xB=eb(ob()),VB=class extends xB.EventEmitter{constructor(e){super(),this.room=e,ib(this,"mainFpsHealth",1),ib(this,"mainBitrateHealth",1),ib(this,"badMainBitrateHealthCount",0),ib(this,"lastEmitBadHealthTime",0),ib(this,"log"),!eD&&ZD&&VN.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(){VN.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};ib(VB,"EVENT_BAD_HEALTH","bad_health");var UB=VB;function FB(e){let{seiMessageList:t,isAudio:i}=e;return new TransformStream({transform(e,r){let n=e;i?audioEncodePipeline.forEach((e=>{n=e({frame:n})})):videoEncodePipeline.forEach((e=>{n=e({frame:n,seiMessageList:t})})),r.enqueue(n)}})}function BB(e,t){return new TransformStream({transform(i,r){let n=i;videoDecodePipeline.forEach((i=>{n=i({frame:n,onSEI:i=>{i.forEach((i=>{self.postMessage({type:"sei",seiPayloadType:i.seiPayloadType,data:i.seiPayload.buffer,userId:e,streamType:t})}))}})})),r.enqueue(n)}})}var HB,jB=((HB=jB||{}).TRACK="track",HB.DATA_CHANNEL_MESSAGE="data_channel_msg",HB[HB.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",HB[HB.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",HB.RECONNECTED="spc-reconnected",HB.RECONNECT_FAILED="spc-reconnect-failed",HB.ERROR="error",HB.SEI_MESSAGE="sei-message",HB),WB=0,GB=!1,JB=new Set,zB=1,qB=class extends kB.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),ib(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),ib(this,"currentState","DISCONNECTED"),ib(this,"_room"),ib(this,"_signalChannel"),ib(this,"_peerConnection",null),ib(this,"_datachannel",null),ib(this,"_enableCustomMessage"),ib(this,"_log"),ib(this,"_downlinkMIDMap",new Map),ib(this,"_downlinkMIDUserIDMap",new Map),ib(this,"_reconnectionTimer",-1),ib(this,"reconnectionCount",0),ib(this,"clientAbility"),ib(this,"_serverAbility",null),ib(this,"addDownlinkQueue",new Set),ib(this,"removeDownlinkQueue",new Set),ib(this,"_parsedAnswer",null),ib(this,"_updateSDPPromise",null),ib(this,"_waitForPCConnectedPromise"),ib(this,"clearConnectTimeout"),ib(this,"_isSDPLogged",!1),ib(this,"enableInsertableStreams",!1),ib(this,"insertableStreamsAbortMap",new Map),ib(this,"scriptTransformWorker"),ib(this,"_isRelayTried",!1),ib(this,"_rttOverCount",0),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=tP.createLogger({id:"spc".concat(zB++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(ZP?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((e=>"h264"===e.codec.toLowerCase()))),e}addAbortController(e,t){var i;null==(i=this.insertableStreamsAbortMap.get(e))||i.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find((e=>"vp8"===e.codec.toLowerCase()))),e}get videoCodec(){var e,t;let i=null==(e=this._parsedAnswer)?void 0:e.media[1].rtp.find((e=>["h264","vp8"].includes(e.codec.toLowerCase())));return i?i.codec.toLowerCase():null!=(t=this._serverAbility)&&t.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return null!=(e=this._serverAbility)&&e.video.decoders.find((e=>"h264"===e.codec.toLowerCase()))?"h264":"vp8"}get isUsingH264(){return"h264"===this.videoCodec}get is42001fSupported(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f")))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=BF(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&&!gO(e.ssrcs[0].id)){let n=Number(e.ssrcs[0].id),o=Number(null==(r=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:r.id);switch(t){case 0:i.audioSsrc=n;break;case 1:i.bigVideoSsrc=n,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=n,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=n,i.auxVideoRtxSsrc=o}}})),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(e){let{isAux:t}=e;this.useHWEncoder(!1,t?7:2)}initScriptTransformWorker(){eM&&(this.scriptTransformWorker=function(e){let t=[ax],i=[AU,RU,CU,IU,FB,BB],r="const videoEncodePipeline=[".concat(e.videoEncodePipeline.toString(),"];\n const videoDecodePipeline=[").concat(e.videoDecodePipeline.toString(),"];\n const audioEncodePipeline = [").concat(e.audioEncodePipeline.toString(),"];\n const audioDecodePipeline = [").concat(e.audioDecodePipeline.toString(),"];"),n="(()=>{".concat(t.map((e=>"const ".concat(e.name,"=(()=>").concat(e.toString(),")()"))).join("\n"),"\n").concat(i.map((e=>e.toString())).join("\n"),";(").concat((()=>{let e=[],t=[],i=[];self.onmessage=r=>{"sei"===r.data.type&&(r.data.isMain?(e.push(r.data.data),r.data.small&&i.push(r.data.data)):t.push(r.data.data))},self.onrtctransform=r=>{let{options:n}=r.transformer,o=n.isReceiver?BB(n.userId,n.streamType):FB({seiMessageList:n.isMain?n.small?i:e:t});r.transformer.readable.pipeThrough(o).pipeTo(r.transformer.writable)}}),")();").concat(r,"})()"),o=new Blob([n],{type:"text/javascript"}),s=URL.createObjectURL(o),a=new Worker(s);return URL.revokeObjectURL(s),a}({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{"sei"===e.data.type&&this.emit("sei-message",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e)})}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}initialize(){return nb(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(),gP.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):"failed"===e&&gP.addFailedEvent({key:521711})},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=e=>this.emit("track",e),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=e=>{let t=new YB(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(tk.AUDIO,{direction:tk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(tk.VIDEO,{direction:tk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(tk.VIDEO,{direction:tk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(tk.VIDEO,{direction:tk.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield NB(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()))}),gP.addSuccessEvent({key:521707}),this.clientAbility}catch(kb){throw gP.addFailedEvent({key:521707,error:kb}),this._log.error("initialize failed ".concat(kb," \noffer: ").concat(null==t?void 0:t.sdp)),kb}}))}setPriority(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"high";if(this._peerConnection)try{this._peerConnection.getSenders().forEach((t=>{let i=t.getParameters();i.encodings[0]&&(i.encodings[0].priority=e,i.encodings[0].networkPriority=e,t.setParameters(i).catch((e=>{this._log.warn("setPriority error ",e)})))}))}catch(wk){this._log.warn("setPriority error ",wk)}}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return nb(this,null,(function*(){var i,r;try{if("CONNECTED"===this.currentState)return;let n=DO(),o={type:"answer",sdp:OB({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(o),yield this.waitForPeerConnectionConnected();let s=(null==(i=this._room.scheduleResult.config)?void 0:i.priority)||(null==(r=this._room.joinParams)?void 0:r.priority)||new URLSearchParams(location.search).get("priority");s&&this.setPriority(s),t||gP.addSuccessEvent({key:521703,cost:DO()-n})}catch(wb){let i=wb instanceof vb&&wb.code===fb.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(wb),e),this.reset(),!i&&!this.isReconnecting&&(gP.addFailedEvent({key:521703,error:wb}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),wb}}))}reconnect(){return nb(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(KU,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:RF,responseCommand:eF.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(0!==t.data.code)throw new vb({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),gP.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),VN.emit(ZO.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(bb){if(!this.isReconnecting)return;if(null!=bb&&bb.message.includes("timeout")){let e=mO(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield QO(e,(e=>{this._reconnectionTimer=e})),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(null==bb?void 0:bb.code," ").concat(bb)),gP.addFailedEvent({key:521704,error:bb}),this.reconnectionCount>=kk()&&this._log.warn("SDK has tried reconnect for ".concat(kk()," 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 nb(this,null,(function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())}))}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),null==(e=this.clearConnectTimeout)||e.call(this),this._signalChannel.off(KU,this.reconnect,this),"RECONNECTING"===this.currentState&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===Ck.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===Ck.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===Ck.FAILED||e.target.connectionState===Ck.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===Ck.CONNECTED||e.target.connectionState===Ck.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),VN.emit(ZO.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 Rk;let e=null;return jP()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,HP()&&0!==this._peerConnection.getReceivers().length&&e?e.state:Rk):Rk}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(jB.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return nb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(MP(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&&rO(t.networkType)),r&&this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port));break}}))}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this.currentState)return e();let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new vb({code:fb.API_CALL_ABORTED,message:DN({key:Fw,data:"leave room"})})))},n=()=>{VN.off(ZO.LEAVE_SUCCESS,r,this),this.off(jB.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{n();let e=new vb({code:fb.API_CALL_TIMEOUT,message:"connection timeout"});WB+=1,(e=>WB>2&&!GB&&0===JB.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),GB=!0,this.emit(jB.FIREWALL_RESTRICTION)),t(e)}),Wk);this.clearConnectTimeout=()=>{n(),clearTimeout(o),delete this.clearConnectTimeout},VN.on(ZO.LEAVE_SUCCESS,r,this),this.on(jB.CONNECTION_STATE_CHANGED,i,this)})),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally((()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}))),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise(((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)})):Promise.resolve()}addDownlink(e){return nb(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(wk){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(wk)),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=tk.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=BF(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(tk.AUDIO,{direction:tk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(tk.VIDEO,{direction:tk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(tk.VIDEO,{direction:tk.TRANSCEIVER_DIRECTION_RECVONLY}),o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=PB({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:BF(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=tk.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(tk.MAIN," ").concat(l,"-audio")}],s.direction=tk.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(tk.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(tk.MAIN," ").concat(l,"-bigvideo")}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=tk.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(tk.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(tk.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(tk.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 nb(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=BF(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 nb(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(YP()){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=BF(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=BF(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=BF(this._peerConnection.remoteDescription.sdp));let s=nD?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:nD?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:nD?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:nD?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:nD?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:s,limit:nD?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:nD?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:s,limit:nD?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:nD?1e3*n:n}]);let a={type:"offer",sdp:HF(o)};return this.updateSDP({localDescription:a})}setScaleResolutionDownBy(e,t,i){let r=e.getParameters();(!r.encodings||0===r.encodings.length)&&(r.encodings=[{}]);let n=r.encodings[0].scaleResolutionDownBy;if(gO(n)?1===t:t===n)return;let o="setScaleResolutionDownBy ".concat(i," ").concat(t);return n&&(o+=" prevScale: ".concat(n)),this._log.warn(o),r.encodings[0].scaleResolutionDownBy=t,e.setParameters(r)}updateSDP(){let{localDescription:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=HF(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,r)=>nb(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(HB){this._log.error(HB),!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(HB)}})))),this._updateSDPPromise}setTransceiverDirection(e,t){return nb(this,null,(function*(){if(!nD||!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===ik.INACTIVE&&t===ik.RECVONLY&&(this._parsedAnswer.media[r].direction=e),e===ik.SENDONLY&&t===ik.INACTIVE&&(this._parsedAnswer.media[r].direction=ik.RECVONLY)}yield this.updateSDP()}))}filterSDPDirection(){return BF(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:LB(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 nb(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach((i=>{var r;if(i.type===tk.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=[],MB(i,n),t=!0)}})),t&&(this._log.warn("switch video encoder to ".concat(e)),yield this.updateSDP())}))}useHWEncoder(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;return nb(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];gO(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===tk.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=[],MB(t,n),i=!0)}})),i&&(this._log.warn("use ".concat(e?"hw":"sw"," encoder")),yield this.updateSDP())}))}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;null==(e=this._peerConnection)||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach((e=>ON(e.abort)&&e.abort("destroy"))),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map((e=>t[e]))}get isUsingRelay(){return"relay"===this._room.getIceTransportPolicy()}detectTCPAndUDP(e){let{uplinkRTT:t,downlinkRTT:i}=e;var r;if("CONNECTED"!==this.currentState||this._isRelayTried&&!this._room.forceRelay||0===this._room.getIceServers().length)return;let n=this._signalChannel.rtt,o=Math.max(t,i),{rttRatioThreshold:s,rttThreshold:a}=(null==(r=this._room.scheduleResult.config)?void 0:r.useTurnTcpInfo)||{};if(!(s&&a&&n&&o))return;let c=Math.floor(o/n),l=(this._isRelayTried||c>s)&&o>a;l?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(n," upRTT: ").concat(t," downRTT: ").concat(i," ratio: ").concat(c," over-count: ").concat(this._rttOverCount," isOver: ").concat(l," isRelayTried: ").concat(this._isRelayTried," force-relay: ").concat(this._room.forceRelay)),this.isUsingRelay||this._isRelayTried?this._room.forceRelay&&this.switchRelay(!1):(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0))):this._rttOverCount=0}switchRelay(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return nb(this,null,(function*(){if(this.isUsingRelay===e)return;let i=e?"relay":"udp",r=e?521709:521710;try{this._room.forceRelay=e,this._log.warn("switchRelay ".concat(i));let t=Date.now();yield this.doSwitchRelay(i),this._log.warn("switchRelay ".concat(i," success")),gP.addSuccessEvent({key:r,cost:Date.now()-t})}catch(wb){this._log.warn("switchRelay ".concat(i," failed"),wb),gP.addFailedEvent({key:r,error:wb}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}}))}doSwitchRelay(e){return new Promise(((t,i)=>{let r=setTimeout((()=>{this.stopReconnection(),i(new Error("switch ".concat(e," timeout")))}),1e4);this.startReconnection().then(t,i).finally((()=>clearTimeout(r)))}))}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}setProfileLevelId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"42e01f",t=arguments.length>1?arguments[1]:void 0;return nb(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];gO(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===tk.VIDEO){let n;e&&(n=this.clientAbility.video.codecs.find((t=>t.fmtp.includes(e)))),n&&(null==(r=t.payloads)||!r.includes(String(n.payload)))&&(t.fmtp=[],t.payloads="",t.rtp=[],t.rtcpFb=[],MB(t,n),i=!0)}})),i&&(this._log.warn("use ".concat(e)),yield this.updateSDP())}))}};tb([ex("reconnect")],qB.prototype,"startReconnection",1),tb([tx((e=>e.userId))],qB.prototype,"addDownlink",1),tb([tx((e=>e))],qB.prototype,"removeDownlink",1),tb([ZL(!0)],qB.prototype,"updateSDP",1),tb([ix(521712,!1)],qB.prototype,"setOffer",1),tb([ix(521713,!1)],qB.prototype,"setAnswer",1);var KB=class{constructor(e){ib(this,"tag"),ib(this,"len"),ib(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}},YB=class{constructor(e){ib(this,"tinyId"),ib(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new KB(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)}))}},QB=new Set;function XB(){let e=Math.floor(4294967296*Math.random());return QB.has(e)?XB():(QB.add(e),e)}var $B=eb(ob()),ZB=class extends $B.default{constructor(e){super(),ib(this,"userId"),ib(this,"tinyId"),ib(this,"_sdpSemantics"),ib(this,"_isUplink"),ib(this,"_room"),ib(this,"_log"),ib(this,"_currentState","DISCONNECTED"),ib(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=tP.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&&(VN.emit(ZO.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"))}},eH=class extends ZB{constructor(e){super(XA(QA({},e),{isUplink:!0})),ib(this,"localMainAudioTrack",null),ib(this,"localMainVideoTrack",null),ib(this,"localAuxAudioTrack",null),ib(this,"localAuxVideoTrack",null),ib(this,"_isPublishingAux",!1),ib(this,"_publishingLocalAudioTrack"),ib(this,"_publishingLocalVideoTrack"),ib(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}),ib(this,"_flag",0),ib(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=RM.run(nw,(()=>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(AN()," ").concat(SN())),gP.addCount({key:521e3})}RM.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&&(WP()?(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===tk.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}get serverPublishState(){return{audio:!!(this.flag&ck),bigVideo:!!(this.flag&ok),smallVideo:!!(this.flag&sk),auxVideo:!!(this.flag&ak)}}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)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}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 nb(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,u;if(!t.singlePC)return;yield t.singlePC.waitForPeerConnectionConnected();let h,{publishState:p,muteState:m}=t;if(i&&(t._publishingLocalAudioTrack=i,p.audio=!0,m.audio=i.muted),r){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new vb({code:fb.NOT_SUPPORTED_H264,message:DN({key:Nw})});eD&&115===$D()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to 480p"),r.setProfile(Zb["480p_2"]),yield r.applyProfile()),t._publishingLocalVideoTrack=r,n?(p.auxVideo=!0,m.auxVideo=r.muted):(p.bigVideo=!0,m.bigVideo=r.muted)}if(t._isPublishingAux=n,r&&!n&&r.small&&(h=t._room.videoManager.smallTrack,p.smallVideo=!0),yield t._signalChannel.sendWaitForResponseWithRetry({command:AF,responseCommand:eF.SPC_PUBLISH_RESULT,data:XA(QA({},t.singlePC.uplinkSSRC),{state:p,muteState:m}),retries:3}),yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:h,isAuxiliary:n}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r){t[n?"localAuxVideoTrack":"localMainVideoTrack"]=r;let{scaleResolutionDownBy:e}=r;yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[n?3:1],e,r.streamType)}i&&(t[n?"localAuxAudioTrack":"localMainAudioTrack"]=i),yield t.singlePC.setBandwidth({audio:(null==(e=t.localMainAudioTrack)?void 0:e.profile.bitrate)||(null==(o=t.localAuxAudioTrack)?void 0:o.profile.bitrate),bigVideo:null==(s=t.localMainVideoTrack)?void 0:s.profile.bitrate,smallVideo:null==(c=null==(a=t.localMainVideoTrack)?void 0:a.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),t.sendMediaSettings(),t.installTrackMuteEvents(i,r),!n&&(t._room.preferHW||(null==(d=t._room.scheduleResult.config)?void 0:d.preferHW))&&r&&r.profile.width*r.profile.height>=921600&&t.singlePC.useHWEncoder(!0,2);let _=new URLSearchParams(location.search).get("profileLevelId"),f=SN();if("SM-A032F"===f||(null==(u=t._room.options.profileLevelIdModelList)?void 0:u.includes(f))){let e=new Set;t.singlePC.clientAbility.video.codecs.forEach((t=>{if("H264"===t.codec){let i=t.fmtp.match(/profile-level-id=([0-9a-fA-F]+)/);i&&i[1]&&e.add(i[1])}})),_=[...e.values()].find((e=>"42e01f"!==e)),_&&t._log.warn("set profileLevelId to ".concat(_," on ").concat(f))}_&&t.singlePC.setProfileLevelId(_)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!GP())return;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[],d=(e,t,i)=>{var r,n;let o=a[t].sender.replaceTrack(i);l.push(t),null!=(r=this.singlePC)&&r.enableInsertableStreams&&o.then((()=>this.createEncodedStreams(a[t].sender,e))),null!=(n=this.singlePC)&&n.scriptTransformWorker&&this.initSenderTransfrom(a[t].sender,e),c.push(o)};s&&d(t.mediaType,0,s),o&&d(i.mediaType,n?3:1,o),r&&d(8,2,r);let u=this.singlePC.setTransceiverDirection(ik.SENDONLY,l);return c.push(u),Promise.all(c)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var i,r;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let n=e.createEncodedStreams(),o=new AbortController;null==(i=this.singlePC)||i.addAbortController(e,o),(null!=(r=this.getTrackByMediaType(t))&&r.enableEncodeFrame?n.readable.pipeThrough(new TransformStream({transform:(e,i)=>{var r;let n=this.getTrackByMediaType(t);i.enqueue((null==(r=this.singlePC)?void 0:r.isUsingH264)&&n?n.encodeFrame(e,8===t):e)}}),o):n.readable).pipeTo(n.writable,o).catch((e=>{this._log.debug("encoded stream error",e),"destory"!==e&&this._log.warn(e)}))}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)return;let i=2!==t,r=8===t;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:1===t,isMain:i,isSmall:r}))}enableSmall(e){return nb(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(ik.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(ik.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 nb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){let e=r&&r===t.localAuxVideoTrack,n=null==r?void 0:r.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localMainAudioTrack&&!t.localAuxAudioTrack&&(yield o[0].replaceTrack(null),s.push(0))),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=XA(QA({},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=XA(QA({},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(ik.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 nb(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:aF,data:t,responseCommand:eF.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:cF,commandDesc:"unpublish",responseCommand:eF.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===fb.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),XP){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:IF,data:this._mediaSettings,responseCommand:eF.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return nb(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?tk.AUXILIARY:tk.MAIN," stream")),WP()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return nb(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===tk.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===ik.INACTIVE&&(yield this.singlePC.setTransceiverDirection(ik.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return nb(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?tk.AUXILIARY:tk.MAIN," stream")),WP()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return nb(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===tk.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(ik.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}replaceTrack(e){return nb(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?tk.AUXILIARY:tk.MAIN," stream")),r.kind===tk.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===tk.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0}))}setBandwidth(e){return nb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===tk.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:oF,responseCommand:eF.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&VN.emit(ZO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===tk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===tk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===tk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===tk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Vk?(this._log.error(Hw.NOT_SUPPORTED_H264ENCODE),new vb({code:fb.NOT_SUPPORTED_H264,message:DN({key:Nw})})):new vb({code:fb.UNKNOWN,message:DN({key:Lw,data:{signalResponse:eF.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return nb(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}))}))}};tb([zL((function(e){let{localVideoTrack:t}=e;null==t||t.once("6",this.onVideoEncodeFailed,this)}))],eH.prototype,"publish",1),tb([zL((function(e){let{localVideoTrack:t}=e;null==t||t.off("6",this.onVideoEncodeFailed,this)}))],eH.prototype,"unpublish",1);var tH=eH;function iH(e){return Object.keys(e).filter((t=>e[t]))}var rH=class extends ZB{constructor(e){super(XA(QA({},e),{isUplink:!1})),ib(this,"_flag",0),ib(this,"isRobot",!1),ib(this,"role","anchor"),ib(this,"remoteAudioTrack"),ib(this,"remoteVideoTrack"),ib(this,"remoteAuxiliaryTrack"),ib(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),ib(this,"jitterBufferTimeoutId",-1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Tx(this._room,this),this.remoteVideoTrack=new mV(this._room,this),this.remoteAuxiliaryTrack=new _V(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 LO(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===tk.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){var t;let i=e.streams[0],{track:r,receiver:n}=e;if(!i.id.includes(this.tinyId))return;let o=i.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(o," ").concat(r.kind));let s=tk.AUDIO;r.kind===tk.VIDEO&&(s=o===tk.MAIN?tk.VIDEO:tk.AUXILIARY);let a=this.remoteAudioTrack;s===tk.VIDEO?a=this.remoteVideoTrack:s===tk.AUXILIARY&&(a=this.remoteAuxiliaryTrack),null!=(t=this.singlePC)&&t.scriptTransformWorker&&this.initReceiverTransform(n,o,r.kind===tk.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(a,n),a.setInputMediaStreamTrack(r)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let i=t.createEncodedStreams(),r=new AbortController,n={abortController:r,enqueue:t=>{var i;return null!=(i=this.singlePC)&&i.isUsingH264?e.decodeFrame(t):t}};(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)}}initReceiverTransform(e,t,i){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:i,userId:this.userId,streamType:t}))}subscribe(e,t){return nb(this,null,(function*(){try{if(this._log.info("subscribe ".concat(t," ").concat(iH(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(kb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(kb.message," ").concat(JSON.stringify(this.muteState))),new vb({code:fb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):kb}}))}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"),ZD&&iN<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return nb(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=QA({},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(iH(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=dF,n=eF.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=uF,n=eF.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 vb({code:i.code,message:DN({key:hw,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 nb(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:XB(),bigVideoSsrc:XB(),bigVideoRtxSsrc:XB(),auxVideoSsrc:XB(),auxVideoRtxSsrc:XB()},{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:bF,responseCommand:eF.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 vb({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 nb(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||PN(t)&&PN(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return yO(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),yO(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,PN(t)&&(this.remoteAudioTrack.jitterBufferDelay=i)),new Promise((e=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:e})}))}doSetJitterBufferDelay(e){let{mainDelay:t,auxDelay:i,receivers:r,resolve:n}=e;try{if(0===t&&0===i)return r.forEach((e=>e.jitterBufferTarget=0)),n();if(r.forEach((e=>{var r;let n=e.track===this.remoteAuxiliaryTrack.outMediaTrack||PN(t)&&e.track===this.remoteAudioTrack.outMediaTrack;if(n&&PN(i)||!n&&PN(t))return;let o=n?i||0:t,s=(e.jitterBufferTarget||0)+100;s>o||(e.jitterBufferTarget=s,this._log.debug("set ".concat(n?"aux ":"").concat(null==(r=null==e?void 0:e.track)?void 0:r.kind," jitterBuffer delay ").concat(s," -> ").concat(o)))})),!r.find((e=>{let r=e.track===this.remoteAuxiliaryTrack.outMediaTrack?i||0:t;return e.jitterBufferTarget<r})))return this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i," done")),n();this.jitterBufferTimeoutId=setTimeout((()=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:n})}),1e3)}catch(wb){this._log.warn("set jitterBuffer delay error: ".concat(wb)),clearTimeout(this.jitterBufferTimeoutId),n()}}get audioReceiver(){var e;return(null==(e=this.singlePC)?void 0:e.getReceiversByUserId(this.userId)[0])||null}};tb([ZL(),qL((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 vb({code:fb.API_CALL_ABORTED,message:DN({key:Fw,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],rH.prototype,"subscribe",1),tb([ZL()],rH.prototype,"unsubscribe",1),tb([tx((()=>"jitter"))],rH.prototype,"setJitterBufferDelay",1);var nH=rH;var oH=eb(ob());var sH=class extends oH.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,ib(this,"log"),ib(this,"cmdIdSeqMap",new Map),ib(this,"messageMap",new Map),this.log=tP.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(eF.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",(e=>{[...this.messageMap.keys()].forEach((t=>{t.split("_").slice(0,-1).join("_")===e&&this.messageMap.delete(t)}))}))}send(e){let{cmdId:t,data:i}=e,r=this.cmdIdSeqMap.get(t)||Math.floor(16383*Math.random()),n={cmdId:t,msg:btoa(String.fromCharCode(...new Uint8Array(i))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(t,r+1),this.signalChannel.send(DF,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)>sH.SEQ_INTERVAL)this.messageMap.set(t,{lastSeq:e.seq,cachedMessageMap:new Map}),this.emitMessage(e);else if(e.seq>r.lastSeq){if(e.seq===r.lastSeq+1)this.emitMessage(e);else if(!r.cachedMessageMap.has(e.seq)){let t=setTimeout((()=>this.emitMessage(e,!0)),5e3);r.cachedMessageMap.set(e.seq,{message:e,timeoutId:t})}}else this.log.debug("drop message ".concat(e.userId,"-").concat(e.cmdId,"-").concat(e.seq));else r||(r={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(t,r),setTimeout((()=>this.emitMessage(e,!0)),100)),r.cachedMessageMap.set(e.seq,{message:e})}else this.emit("message",e)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(t.srcTinyId));let i=r=>{r.tinyId===t.srcTinyId&&(this.room.off("peer-join",i),this.onReceiveMsg(e))};this.room.on("peer-join",i),QO(2e3).then((()=>this.room.off("peer-join",i)))}}emitMessage(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i;let r=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),n=e;if(r){if(t){let e=[...r.cachedMessageMap.values()].sort(((e,t)=>e.message.seq-t.message.seq));e[0]&&(n=e[0].message)}0!==r.lastSeq&&n.seq-r.lastSeq>1&&this.log.debug("msg lost userId: ".concat(n.userId," seq: ").concat(r.lastSeq," -> ").concat(n.seq)),r.lastSeq=n.seq,clearTimeout(null==(i=r.cachedMessageMap.get(n.seq))?void 0:i.timeoutId),r.cachedMessageMap.delete(n.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(n))),this.emit("message",n);let o=null==r?void 0:r.cachedMessageMap.get(n.seq+1);o&&this.emitMessage(o.message)}},aH=sH;ib(aH,"SEQ_INTERVAL",300);var{isString:cH,isUndefined:lH,getNetworkType:dH,isEmpty:uH}=Eb,hH=class extends gB{constructor(e){super(e),this.options=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=JP,this._changeBigSmallRecords=new Map,this.forceRelay=!1,this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=0,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this.preferHW=!1,this._updateAudioLevelTaskId=-1,this._stats=new QF(this,this._log),this.userManager=new yV(this.userId,this._log),this._version=Cb,this.sdpSemantics=xk,lH(e.sdpSemantics)?nP.isUnifiedPlanDefault()&&(this.sdpSemantics=Lk):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(dH())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!lH(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&JP,!lH(e.enableSPC)&&JP&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new UB(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 nb(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)JA.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&WA)for(var r of WA(e))t.indexOf(r)<0&&zA.call(e,r)&&(i[r]=e[r]);return i})(e,[]);VN.emit(ZO.REMOTE_PUBLISH_STATE_CHANGED,QA({room:this},t)),this.emit("remote-publish-state-changed",QA({},t))})),this.joinParams=e,new Promise(((t,i)=>nb(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 vb&&o.code===fb.SPC_INITIALIZED_FAILED))return i(o);null==(r=this.signalChannel)||r.destroy(),yield this.initialize()}let s=DO();yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),gP.addSuccessEvent({key:521708,cost:DO()-s}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(oP){gP.addFailedEvent({key:521708,error:oP}),i(oP)}this._joinReject=null}))))}))}initSinglePC(){return nb(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new qB({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(bb){throw this.fallbackToMPC(),new vb({code:fb.SPC_INITIALIZED_FAILED,message:null==bb?void 0:bb.message})}}}))}doJoin(e,t){return new Promise(((i,r)=>nb(this,null,(function*(){var n,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(QU,(e=>{this.clearJoinTimeout(),VN.emit(ZO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)})),TO(null==(o=null==(n=this.scheduleResult)?void 0:n.config)?void 0:o.singlePC)&&JP&&(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:bN(),netType:nO(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;(null==(s=this.scheduleResult.config)?void 0:s.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{r(new vb({code:fb.JOIN_ROOM_FAILED,message:DN({key:Tw})}))}),c),VN.emit(ZO.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?CF:iF,a),this.signalChannel.once(eF.JOIN_ROOM_RESULT,(t=>{this.clearJoinTimeout();let{code:n,message:o,data:s,tinyId:a}=t.data;VN.emit(ZO.JOIN_RECEIVED_CMD_RES,{room:this,code:n}),0===n?(this._log.info("Join room success, start heartbeat"),a&&(this.tinyId=a),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=s.publishers,this.singlePC&&this.singlePC.connect(XA(QA({},s.ability),{useVp8:s.ability.useVp8||!!e.useVp8})).catch((()=>{})),i()):(this._log.error("Join room failed result: ".concat(n," error: ").concat(o)),r(new vb({code:fb.JOIN_ROOM_FAILED,extraCode:n,message:DN({key:Sw,data:{error:o,code:n}})})))}))}))))}reJoin(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return nb(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(XA(QA({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),FN.logSuccessEvent({userId:this.userId,eventType:Nk.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(jB.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof tH&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(jB.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof YF&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(wk){this._log.warn("reJoin fail ".concat(wk)),this.reset(),FN.logFailedEvent({userId:this.userId,eventType:Nk.REJOIN,error:wk}),this.emit("error",new vb({code:fb.JOIN_ROOM_FAILED,message:DN({key:Ew,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return nb(this,null,(function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this.signalChannel||function(e){let t=[...NF.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 OF({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 aH(this,this.signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this.networkQuality||(this.networkQuality=new eB({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(eB.EVENT_NETWORK_QUALITY,(e=>{var t;this.emit("network-quality",e),null==(t=this.singlePC)||t.detectTCPAndUDP(e)}))),kM(this,this.signalChannel).add(qU,(e=>{VN.emit(ZO.SIGNAL_CONNECTION_STATE_CHANGED,QA({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(YU,(e=>{this.reset(),this.emit("error",e)})).add(eF.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})).add(eF.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(eF.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(eF.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(FN.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(zU,(e=>{this.tinyId=e.signalInfo.tinyId,VN.emit(ZO.JOIN_SIGNAL_CONNECTION_END,{room:this})})),VN.emit(ZO.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&VN.emit(ZO.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this.signalChannel=e,e||wM(this)}leave(){return nb(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(wk){}this._log.info("leave() => leaving room"),VN.emit(ZO.LEAVE_SEND_CMD,{room:this}),null==(e=this.signalChannel)||e.send(rF)}))}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach((e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")}))}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){-1===this._heartbeat&&(this._heartbeat=RM.run(tw,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),RM.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return nb(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(fV.has(e)){let t=fV.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 fV.delete(e),t}return[]}(this.userId):[],n=XA(QA({str_sdk_version:Rb,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:QA({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:nO()},i.msg_device_info)});if(this.heartbeatReport=n,VN.emit(ZO.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(nF,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",XA(QA({},n),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter((e=>e.flag!==hk)).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})})),VN.emit(ZO.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 YF&&(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?nH:JF)({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!==fb.ICE_TRANSPORT_ERROR&&(i===fb.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",XA(QA({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=RM.run(tw,this.syncUserList.bind(this)))}stopSyncUserListInterval(){RM.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:SF,responseCommand:eF.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 DN({key:Lw,data:{signalResponse:eF.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||!VF)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)===Ck.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof UF&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===Ck.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return nb(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),FN.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 YF({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0})),e.close()}for(let t of[...this.remotePublishedUserMap.values()]){let e=new JF({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(e,t.userId),this.remotePublishedUserMap.set(t.userId,e),t.isMainStreamSubscribed&&(yield e.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield e.subscribe(t.subscribeState,"auxiliary"))}}))}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new vb({code:fb.INVALID_OPERATION,message:DN({key:kw,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),RM.clearTask(this._audioVolumeIntervalId))}switchRole(e){return nb(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:EF,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:eF.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 vb({code:fb.SWITCH_ROLE_FAILED,message:DN({key:Aw,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof vb&&e.getCode()===fb.API_CALL_TIMEOUT&&(e=new vb({code:fb.SWITCH_ROLE_FAILED,message:DN({key:Cw})})),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 nb(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof sx&&(t instanceof mx?i.audio=t:e.audio=t),t instanceof lx&&(t instanceof px&&2===t.mediaType?i.video=t:e.video=t)}));let r=uH(e),n=uH(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new tH({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new YF({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",(e=>{this.emit("media-connection-state-changed",XA(QA({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==fb.ICE_TRANSPORT_ERROR&&(t===fb.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 nb(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 sx&&(t instanceof mx?i.audio=t:e.audio=t),t instanceof lx&&(t instanceof px&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");uH(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),uH(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&&KP()?this.uplinkConnection.replaceTrack(e).then((t=>{t&&VN.emit(ZO.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return nb(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return nb(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:tk.VIDEO,videoType:tk.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 nb(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=QA({},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),VN.emit(ZO.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(jF(n),"] prev: [").concat(jF(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());VN.emit(ZO.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(wb){let i=wb instanceof vb?wb.getCode():fb.UNKNOWN,n=wb;throw wb instanceof vb?i===fb.REMOTE_STREAM_NOT_EXIST&&(n=new vb({code:fb.API_CALL_ABORTED,message:DN({key:Bw,data:{message:wb.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new vb({code:i,message:DN({key:Rw,data:{message:wb.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 nb(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(wb){this._log.warn("unsubscribe() => failed ".concat(wb))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),VN.emit(ZO.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 RM.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),VN.emit(ZO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&RM.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=RM.run(iw,(()=>{var i;vL.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];null==(i=this.remotePublishedUserMap)||i.forEach((e=>{if(e.muteState.hasAudio){vL.isRunning?e.remoteAudioTrack.volume=0:this.updateDownlinkAudioLevelFromReceiver(e);let t=Math.floor(100*e.remoteAudioTrack.getAudioLevel());r.push({userId:e.userId,volume:t})}})),this.emit("audio-volume",r)}),{fps:1e3/e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return nb(this,null,(function*(){var i;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||-1!==this._updateAudioLevelTaskId)return;let r=null==(i=this.uplinkConnection.getPeerConnection())?void 0:i.getSenders()[0];if(!r)return;let n=Math.max(e,500);this._log.warn("updateAudioLevelFromSenderStat ".concat(n)),this._updateAudioLevelTaskId=RM.run(iw,(()=>nb(this,null,(function*(){let e=yield r.getStats();this._updateAudioLevelTaskId<0||e.forEach((e=>{"media-source"===e.type&&e.audioLevel&&(this.uplinkConnection.localMainAudioTrack.volume=e.audioLevel)}))}))),{delay:n,backgroundTask:t})}))}stopUpdateAudioLevelFromSenderStat(){var e;-1!==this._updateAudioLevelTaskId&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),RM.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,null!=(e=this.uplinkConnection)&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var t;let{audioReceiver:i}=e;if(!QP||!i)return;let r=null==(t=i.getSynchronizationSources()[0])?void 0:t.audioLevel;this._log.debug("updateDownlinkAudioLevelFromReceiver"),r&&(e.remoteAudioTrack.volume=Math.min(2*r,1))}getLocalAudioStats(){return nb(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 nb(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 nb(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 nb(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 nb(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(Eb.getTurnServer(e)))):Eb.isPlainObject(e)&&i.push(Eb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:fF,data:e,timeout:5e3,responseCommand:eF.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:gF,data:e,timeout:5e3,responseCommand:eF.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?hF:mF,data:e,timeout:5e3,responseCommand:t?eF.START_PUBLISH_TENCENT_CDN_RES:eF.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?pF:_F,data:e,timeout:5e3,responseCommand:t?eF.STOP_PUBLISH_TENCENT_CDN_RES:eF.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:vF,data:e,timeout:5e3,responseCommand:eF.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:yF,data:e,timeout:5e3,responseCommand:eF.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:TF,data:e,timeout:5e3,responseCommand:eF.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:kF,data:e,timeout:5e3,responseCommand:eF.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch((e=>{}))}getIceServers(){return 0===this._turnServers.length&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=Eb.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 nb(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(Zk-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=Zk}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(Zk-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:Zk};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(cH(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!lH(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new vb({code:fb.INVALID_PARAMETER,message:DN({key:fw})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!lH(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new vb({code:fb.INVALID_PARAMETER,message:DN({key:gw})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!lH(e.userDefinePushArgs)){if(!(cH(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new vb({code:fb.INVALID_PARAMETER,message:DN({key:vw})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}uH(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&ZP)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 vb({code:fb.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return null==(e=this.singlePC)?void 0:e.scriptTransformWorker}};return tb([RB(["left",bB.INIT],"joined"),NM({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn("join retry ".concat(e))},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),jN(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),qL((e=>{let t=new WU;return function(i,r,n){return nb(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 vb({code:fb.INVALID_OPERATION,message:DN({key:yw})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new vb({code:fb.INVALID_OPERATION,message:DN({key:bw,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)),VN.emit(ZO.JOIN_START,{room:this,roomId:o,params:i});let s=Eb.getEnv();s||(s=Jb.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(rk.OLD_CLOUD_LADDER)?s=Jb.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(rk.WEBRTC)&&(s=Jb.WEBRTC))),FN.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),nP.checkSystemRequirementsInternal().then((e=>{this.checkSystemResult=e,GU.call(this)}));try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Eb.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=Eb.performanceNow(),VN.emit(ZO.JOIN_SUCCESS,{room:this}),30===n&&!i.component&&FN.uploadEvent({log:"stat-conv-".concat(Number(pN),"-").concat(location.hostname),userId:this.userId}),t}catch(a){throw t.delete({room:this,roomId:o}),VN.emit(ZO.JOIN_FAILED,{room:this,error:a}),a}}))}}))],hH.prototype,"join",1),tb([RB("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),qL((e=>function(){return nb(this,null,(function*(){VN.emit(ZO.LEAVE_START,{room:this}),yield e.call(this),VN.emit(ZO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),ex("leave room"),OM({fnName:"publish",validateArgs:!1}),OM({fnName:"unsubscribe",validateArgs:!1})],hH.prototype,"leave",1),tb([ZL(),qL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return nb(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"capture"===e.state)),!i.length))return;VN.emit("61",{room:this});let t=e.apply(this,i);return i.forEach((e=>e.publish(this,t))),t}))})),NM({settings:{retries:kk,timeout:e=>mO(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),VN.emit(ZO.PUBLISH_FAILED,{room:this}))}})],hH.prototype,"publish",1),tb([OM({fnName:"publish"}),function(e){return function(t,i,r){let n=r.value;return r.value=function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let o=XL.get(this);if(o){let t=o.queue.filter(((t,r)=>{if(0===r)return!0;let n=!0;return t.args.forEach((e=>{i.find((t=>t===e))||(n=!1)})),!n||(t.reject(new vb({code:fb.API_CALL_ABORTED,message:e})),!1)}));o.queue=t}return n.apply(this,i)},r}}("api-call"),ZL(),qL((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})),zL((function(){var e,t;0===this.localTracks.size&&jP()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((e=>e.track&&e.replaceTrack(null))))}))],hH.prototype,"unpublish",1),tb([tx((e=>e.userId))],hH.prototype,"replaceTrack",1),tb([tx((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),gx(),qL((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})),NM({settings:{retries:kk,timeout:e=>mO(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),VN.emit(ZO.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],hH.prototype,"subscribe",1),tb([OM({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")}))}}),tx((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],hH.prototype,"unsubscribe",1),jU.create=jU._create.bind(jU,hH),jU}));
|