trtc-sdk-v5 5.9.2-beta.5 → 5.10.0-wasm.0
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/assets/av_processing.wasm +0 -0
- package/assets/videodec.wasm +0 -0
- package/assets/videodec_simd.wasm +0 -0
- package/assets/worker.js +17 -0
- package/package.json +4 -6
- package/plugins/ai-denoiser/denoiser-wasm.js +17 -0
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/package.json +1 -1
- package/plugins/video-decoder/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/virtual-background/virtual-background.esm.js +1 -1
- package/plugins/video-effect/virtual-background/virtual-background.umd.js +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +63 -40
- package/trtc.js +1 -1
package/trtc.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TRTC=t()}(this,(function(){function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},i=function(e){return e&&e.Math===Math&&e},r=i("object"==typeof globalThis&&globalThis)||i("object"==typeof window&&window)||i("object"==typeof self&&self)||i("object"==typeof t&&t)||i("object"==typeof t&&t)||function(){return this}()||Function("return this")(),n={},s=function(e){try{return!!e()}catch(t){return!0}},o=!s((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})),a=!s((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),c=a,l=Function.prototype.call,d=c?l.bind(l):function(){return l.apply(l,arguments)},u={},h={}.propertyIsEnumerable,p=Object.getOwnPropertyDescriptor,m=p&&!h.call({1:2},1);u.f=m?function(e){var t=p(this,e);return!!t&&t.enumerable}:h;var _,f,g=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},E=a,T=Function.prototype,v=T.call,y=E&&T.bind.bind(v,v),S=E?y:function(e){return function(){return v.apply(e,arguments)}},I=S,R=I({}.toString),A=I("".slice),C=function(e){return A(R(e),8,-1)},b=s,k=C,D=Object,N=S("".split),w=b((function(){return!D("z").propertyIsEnumerable(0)}))?function(e){return"String"===k(e)?N(e,""):D(e)}:D,O=function(e){return null==e},P=O,M=TypeError,L=function(e){if(P(e))throw new M("Can't call method on "+e);return e},x=w,V=L,U=function(e){return x(V(e))},F="object"==typeof document&&document.all,B=void 0===F&&void 0!==F?function(e){return"function"==typeof e||e===F}:function(e){return"function"==typeof e},H=B,G=function(e){return"object"==typeof e?null!==e:H(e)},W=r,j=B,J=function(e,t){return arguments.length<2?(i=W[e],j(i)?i:void 0):W[e]&&W[e][t];var i},K=S({}.isPrototypeOf),q=r.navigator,z=q&&q.userAgent,Y=z?String(z):"",X=r,Q=Y,Z=X.process,$=X.Deno,ee=Z&&Z.versions||$&&$.version,te=ee&&ee.v8;te&&(f=(_=te.split("."))[0]>0&&_[0]<4?1:+(_[0]+_[1])),!f&&Q&&(!(_=Q.match(/Edge\/(\d+)/))||_[1]>=74)&&(_=Q.match(/Chrome\/(\d+)/))&&(f=+_[1]);var ie=f,re=ie,ne=s,se=r.String,oe=!!Object.getOwnPropertySymbols&&!ne((function(){var e=Symbol("symbol detection");return!se(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&re&&re<41})),ae=oe&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ce=J,le=B,de=K,ue=Object,he=ae?function(e){return"symbol"==typeof e}:function(e){var t=ce("Symbol");return le(t)&&de(t.prototype,ue(e))},pe=String,me=function(e){try{return pe(e)}catch(t){return"Object"}},_e=B,fe=me,ge=TypeError,Ee=function(e){if(_e(e))return e;throw new ge(fe(e)+" is not a function")},Te=Ee,ve=O,ye=function(e,t){var i=e[t];return ve(i)?void 0:Te(i)},Se=d,Ie=B,Re=G,Ae=TypeError,Ce={},be={get exports(){return Ce},set exports(e){Ce=e}},ke=r,De=Object.defineProperty,Ne=function(e,t){try{De(ke,e,{value:t,configurable:!0,writable:!0})}catch(i){ke[e]=t}return t},we=r,Oe=Ne,Pe="__core-js_shared__",Me=be.exports=we[Pe]||Oe(Pe,{});(Me.versions||(Me.versions=[])).push({version:"3.38.1",mode:"global",copyright:"© 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.1/LICENSE",source:"https://github.com/zloirock/core-js"});var Le=Ce,xe=function(e,t){return Le[e]||(Le[e]=t||{})},Ve=L,Ue=Object,Fe=function(e){return Ue(Ve(e))},Be=Fe,He=S({}.hasOwnProperty),Ge=Object.hasOwn||function(e,t){return He(Be(e),t)},We=S,je=0,Je=Math.random(),Ke=We(1..toString),qe=function(e){return"Symbol("+(void 0===e?"":e)+")_"+Ke(++je+Je,36)},ze=xe,Ye=Ge,Xe=qe,Qe=oe,Ze=ae,$e=r.Symbol,et=ze("wks"),tt=Ze?$e.for||$e:$e&&$e.withoutSetter||Xe,it=function(e){return Ye(et,e)||(et[e]=Qe&&Ye($e,e)?$e[e]:tt("Symbol."+e)),et[e]},rt=d,nt=G,st=he,ot=ye,at=function(e,t){var i,r;if("string"===t&&Ie(i=e.toString)&&!Re(r=Se(i,e)))return r;if(Ie(i=e.valueOf)&&!Re(r=Se(i,e)))return r;if("string"!==t&&Ie(i=e.toString)&&!Re(r=Se(i,e)))return r;throw new Ae("Can't convert object to primitive value")},ct=TypeError,lt=it("toPrimitive"),dt=function(e,t){if(!nt(e)||st(e))return e;var i,r=ot(e,lt);if(r){if(void 0===t&&(t="default"),i=rt(r,e,t),!nt(i)||st(i))return i;throw new ct("Can't convert object to primitive value")}return void 0===t&&(t="number"),at(e,t)},ut=dt,ht=he,pt=function(e){var t=ut(e,"string");return ht(t)?t:t+""},mt=G,_t=r.document,ft=mt(_t)&&mt(_t.createElement),gt=function(e){return ft?_t.createElement(e):{}},Et=gt,Tt=!o&&!s((function(){return 7!==Object.defineProperty(Et("div"),"a",{get:function(){return 7}}).a})),vt=o,yt=d,St=u,It=g,Rt=U,At=pt,Ct=Ge,bt=Tt,kt=Object.getOwnPropertyDescriptor;n.f=vt?kt:function(e,t){if(e=Rt(e),t=At(t),bt)try{return kt(e,t)}catch(i){}if(Ct(e,t))return It(!yt(St.f,e,t),e[t])};var Dt={},Nt=o&&s((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),wt=G,Ot=String,Pt=TypeError,Mt=function(e){if(wt(e))return e;throw new Pt(Ot(e)+" is not an object")},Lt=o,xt=Tt,Vt=Nt,Ut=Mt,Ft=pt,Bt=TypeError,Ht=Object.defineProperty,Gt=Object.getOwnPropertyDescriptor,Wt="enumerable",jt="configurable",Jt="writable";Dt.f=Lt?Vt?function(e,t,i){if(Ut(e),t=Ft(t),Ut(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Jt in i&&!i[Jt]){var r=Gt(e,t);r&&r[Jt]&&(e[t]=i.value,i={configurable:jt in i?i[jt]:r[jt],enumerable:Wt in i?i[Wt]:r[Wt],writable:!1})}return Ht(e,t,i)}:Ht:function(e,t,i){if(Ut(e),t=Ft(t),Ut(i),xt)try{return Ht(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Bt("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Kt=Dt,qt=g,zt=o?function(e,t,i){return Kt.f(e,t,qt(1,i))}:function(e,t,i){return e[t]=i,e},Yt={},Xt={get exports(){return Yt},set exports(e){Yt=e}},Qt=o,Zt=Ge,$t=Function.prototype,ei=Qt&&Object.getOwnPropertyDescriptor,ti=Zt($t,"name"),ii={EXISTS:ti,PROPER:ti&&"something"===function(){}.name,CONFIGURABLE:ti&&(!Qt||Qt&&ei($t,"name").configurable)},ri=B,ni=Ce,si=S(Function.toString);ri(ni.inspectSource)||(ni.inspectSource=function(e){return si(e)});var oi,ai,ci,li=ni.inspectSource,di=B,ui=r.WeakMap,hi=di(ui)&&/native code/.test(String(ui)),pi=qe,mi=xe("keys"),_i=function(e){return mi[e]||(mi[e]=pi(e))},fi={},gi=hi,Ei=r,Ti=G,vi=zt,yi=Ge,Si=Ce,Ii=_i,Ri=fi,Ai="Object already initialized",Ci=Ei.TypeError,bi=Ei.WeakMap;if(gi||Si.state){var ki=Si.state||(Si.state=new bi);ki.get=ki.get,ki.has=ki.has,ki.set=ki.set,oi=function(e,t){if(ki.has(e))throw new Ci(Ai);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 Di=Ii("state");Ri[Di]=!0,oi=function(e,t){if(yi(e,Di))throw new Ci(Ai);return t.facade=e,vi(e,Di,t),t},ai=function(e){return yi(e,Di)?e[Di]:{}},ci=function(e){return yi(e,Di)}}var Ni={set:oi,get:ai,has:ci,enforce:function(e){return ci(e)?ai(e):oi(e,{})},getterFor:function(e){return function(t){var i;if(!Ti(t)||(i=ai(t)).type!==e)throw new Ci("Incompatible receiver, "+e+" required");return i}}},wi=S,Oi=s,Pi=B,Mi=Ge,Li=o,xi=ii.CONFIGURABLE,Vi=li,Ui=Ni.enforce,Fi=Ni.get,Bi=String,Hi=Object.defineProperty,Gi=wi("".slice),Wi=wi("".replace),ji=wi([].join),Ji=Li&&!Oi((function(){return 8!==Hi((function(){}),"length",{value:8}).length})),Ki=String(String).split("String"),qi=Xt.exports=function(e,t,i){"Symbol("===Gi(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=ji(Ki,"string"==typeof t?t:"")),e};Function.prototype.toString=qi((function(){return Pi(this)&&Fi(this).source||Vi(this)}),"toString");var zi=B,Yi=Dt,Xi=Yt,Qi=Ne,Zi=function(e,t,i,r){r||(r={});var n=r.enumerable,s=void 0!==r.name?r.name:t;if(zi(i)&&Xi(i,s,r),r.global)n?e[t]=i:Qi(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch(o){}n?e[t]=i:Yi.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},$i={},er=Math.ceil,tr=Math.floor,ir=Math.trunc||function(e){var t=+e;return(t>0?tr:er)(t)},rr=ir,nr=function(e){var t=+e;return t!=t||0===t?0:rr(t)},sr=nr,or=Math.max,ar=Math.min,cr=function(e,t){var i=sr(e);return i<0?or(i+t,0):ar(i,t)},lr=nr,dr=Math.min,ur=function(e){var t=lr(e);return t>0?dr(t,9007199254740991):0},hr=ur,pr=function(e){return hr(e.length)},mr=U,_r=cr,fr=pr,gr=function(e){return function(t,i,r){var n=mr(t),s=fr(n);if(0===s)return!e&&-1;var o,a=_r(r,s);if(e&&i!=i){for(;s>a;)if((o=n[a++])!=o)return!0}else for(;s>a;a++)if((e||a in n)&&n[a]===i)return e||a||0;return!e&&-1}},Er={includes:gr(!0),indexOf:gr(!1)},Tr=Ge,vr=U,yr=Er.indexOf,Sr=fi,Ir=S([].push),Rr=function(e,t){var i,r=vr(e),n=0,s=[];for(i in r)!Tr(Sr,i)&&Tr(r,i)&&Ir(s,i);for(;t.length>n;)Tr(r,i=t[n++])&&(~yr(s,i)||Ir(s,i));return s},Ar=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Cr=Rr,br=Ar.concat("length","prototype");$i.f=Object.getOwnPropertyNames||function(e){return Cr(e,br)};var kr={};kr.f=Object.getOwnPropertySymbols;var Dr=J,Nr=$i,wr=kr,Or=Mt,Pr=S([].concat),Mr=Dr("Reflect","ownKeys")||function(e){var t=Nr.f(Or(e)),i=wr.f;return i?Pr(t,i(e)):t},Lr=Ge,xr=Mr,Vr=n,Ur=Dt,Fr=function(e,t,i){for(var r=xr(t),n=Ur.f,s=Vr.f,o=0;o<r.length;o++){var a=r[o];Lr(e,a)||i&&Lr(i,a)||n(e,a,s(t,a))}},Br=s,Hr=B,Gr=/#|\.prototype\./,Wr=function(e,t){var i=Jr[jr(e)];return i===qr||i!==Kr&&(Hr(t)?Br(t):!!t)},jr=Wr.normalize=function(e){return String(e).replace(Gr,".").toLowerCase()},Jr=Wr.data={},Kr=Wr.NATIVE="N",qr=Wr.POLYFILL="P",zr=Wr,Yr=r,Xr=n.f,Qr=zt,Zr=Zi,$r=Ne,en=Fr,tn=zr,rn=function(e,t){var i,r,n,s,o,a=e.target,c=e.global,l=e.stat;if(i=c?Yr:l?Yr[a]||$r(a,{}):Yr[a]&&Yr[a].prototype)for(r in t){if(s=t[r],n=e.dontCallGetSet?(o=Xr(i,r))&&o.value:i[r],!tn(c?r:a+(l?".":"#")+r,e.forced)&&void 0!==n){if(typeof s==typeof n)continue;en(s,n)}(e.sham||n&&n.sham)&&Qr(s,"sham",!0),Zr(i,r,s,e)}},nn={};nn[it("toStringTag")]="z";var sn="[object z]"===String(nn),on=B,an=C,cn=it("toStringTag"),ln=Object,dn="Arguments"===an(function(){return arguments}()),un=sn?an: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=ln(e),cn))?i:dn?an(t):"Object"===(r=an(t))&&on(t.callee)?"Arguments":r},hn=un,pn=String,mn=function(e){if("Symbol"===hn(e))throw new TypeError("Cannot convert a Symbol value to a string");return pn(e)},_n=Yt,fn=Dt,gn=function(e,t,i){return i.get&&_n(i.get,t,{getter:!0}),i.set&&_n(i.set,t,{setter:!0}),fn.f(e,t,i)},En=rn,Tn=o,vn=S,yn=Ge,Sn=B,In=K,Rn=mn,An=gn,Cn=Fr,bn=r.Symbol,kn=bn&&bn.prototype;if(Tn&&Sn(bn)&&(!("description"in kn)||void 0!==bn().description)){var Dn={},Nn=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:Rn(arguments[0]),t=In(kn,this)?new bn(e):void 0===e?bn():bn(e);return""===e&&(Dn[t]=!0),t};Cn(Nn,bn),Nn.prototype=kn,kn.constructor=Nn;var wn="Symbol(description detection)"===String(bn("description detection")),On=vn(kn.valueOf),Pn=vn(kn.toString),Mn=/^Symbol\((.*)\)[^)]+$/,Ln=vn("".replace),xn=vn("".slice);An(kn,"description",{configurable:!0,get:function(){var e=On(this);if(yn(Dn,e))return"";var t=Pn(e),i=wn?xn(t,7,-1):Ln(t,Mn,"$1");return""===i?void 0:i}}),En({global:!0,constructor:!0,forced:!0},{Symbol:Nn})}var Vn={},Un=Rr,Fn=Ar,Bn=Object.keys||function(e){return Un(e,Fn)},Hn=o,Gn=Nt,Wn=Dt,jn=Mt,Jn=U,Kn=Bn;Vn.f=Hn&&!Gn?Object.defineProperties:function(e,t){jn(e);for(var i,r=Jn(t),n=Kn(t),s=n.length,o=0;s>o;)Wn.f(e,i=n[o++],r[i]);return e};var qn,zn=J("document","documentElement"),Yn=Mt,Xn=Vn,Qn=Ar,Zn=fi,$n=zn,es=gt,ts="prototype",is="script",rs=_i("IE_PROTO"),ns=function(){},ss=function(e){return"<"+is+">"+e+"</"+is+">"},os=function(e){e.write(ss("")),e.close();var t=e.parentWindow.Object;return e=null,t},as=function(){try{qn=new ActiveXObject("htmlfile")}catch(n){}var e,t,i;as="undefined"!=typeof document?document.domain&&qn?os(qn):(t=es("iframe"),i="java"+is+":",t.style.display="none",$n.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(ss("document.F=Object")),e.close(),e.F):os(qn);for(var r=Qn.length;r--;)delete as[ts][Qn[r]];return as()};Zn[rs]=!0;var cs=Object.create||function(e,t){var i;return null!==e?(ns[ts]=Yn(e),i=new ns,ns[ts]=null,i[rs]=e):i=as(),void 0===t?i:Xn.f(i,t)},ls=it,ds=cs,us=Dt.f,hs=ls("unscopables"),ps=Array.prototype;void 0===ps[hs]&&us(ps,hs,{configurable:!0,value:ds(null)});var ms=function(e){ps[hs][e]=!0},_s=Er.includes,fs=ms;rn({target:"Array",proto:!0,forced:s((function(){return!Array(1).includes()}))},{includes:function(e){return _s(this,e,arguments.length>1?arguments[1]:void 0)}}),fs("includes");var gs,Es,Ts,vs={},ys=!s((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Ss=Ge,Is=B,Rs=Fe,As=ys,Cs=_i("IE_PROTO"),bs=Object,ks=bs.prototype,Ds=As?bs.getPrototypeOf:function(e){var t=Rs(e);if(Ss(t,Cs))return t[Cs];var i=t.constructor;return Is(i)&&t instanceof i?i.prototype:t instanceof bs?ks:null},Ns=s,ws=B,Os=G,Ps=Ds,Ms=Zi,Ls=it("iterator"),xs=!1;[].keys&&("next"in(Ts=[].keys())?(Es=Ps(Ps(Ts)))!==Object.prototype&&(gs=Es):xs=!0);var Vs=!Os(gs)||Ns((function(){var e={};return gs[Ls].call(e)!==e}));Vs&&(gs={}),ws(gs[Ls])||Ms(gs,Ls,(function(){return this}));var Us={IteratorPrototype:gs,BUGGY_SAFARI_ITERATORS:xs},Fs=Dt.f,Bs=Ge,Hs=it("toStringTag"),Gs=function(e,t,i){e&&!i&&(e=e.prototype),e&&!Bs(e,Hs)&&Fs(e,Hs,{configurable:!0,value:t})},Ws=Us.IteratorPrototype,js=cs,Js=g,Ks=Gs,qs=vs,zs=function(){return this},Ys=function(e,t,i,r){var n=t+" Iterator";return e.prototype=js(Ws,{next:Js(+!r,i)}),Ks(e,n,!1),qs[n]=zs,e},Xs=S,Qs=Ee,Zs=G,$s=function(e){return Zs(e)||null===e},eo=String,to=TypeError,io=function(e,t,i){try{return Xs(Qs(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},ro=G,no=L,so=function(e){if($s(e))return e;throw new to("Can't set "+eo(e)+" as a prototype")},oo=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=io(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return no(i),so(r),ro(i)?(t?e(i,r):i.__proto__=r,i):i}}():void 0),ao=rn,co=d,lo=B,uo=Ys,ho=Ds,po=oo,mo=Gs,_o=zt,fo=Zi,go=vs,Eo=ii.PROPER,To=ii.CONFIGURABLE,vo=Us.IteratorPrototype,yo=Us.BUGGY_SAFARI_ITERATORS,So=it("iterator"),Io="keys",Ro="values",Ao="entries",Co=function(){return this},bo=function(e,t,i,r,n,s,o){uo(i,t,r);var a,c,l,d=function(e){if(e===n&&_)return _;if(!yo&&e&&e in p)return p[e];switch(e){case Io:case Ro:case Ao:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[So]||p["@@iterator"]||n&&p[n],_=!yo&&m||d(n),f="Array"===t&&p.entries||m;if(f&&(a=ho(f.call(new e)))!==Object.prototype&&a.next&&(ho(a)!==vo&&(po?po(a,vo):lo(a[So])||fo(a,So,Co)),mo(a,u,!0)),Eo&&n===Ro&&m&&m.name!==Ro&&(To?_o(p,"name",Ro):(h=!0,_=function(){return co(m,this)})),n)if(c={values:d(Ro),keys:s?_:d(Io),entries:d(Ao)},o)for(l in c)(yo||h||!(l in p))&&fo(p,l,c[l]);else ao({target:t,proto:!0,forced:yo||h},c);return p[So]!==_&&fo(p,So,_,{name:n}),go[t]=_,c},ko=function(e,t){return{value:e,done:t}},Do=U,No=ms,wo=vs,Oo=Ni,Po=Dt.f,Mo=bo,Lo=ko,xo=o,Vo="Array Iterator",Uo=Oo.set,Fo=Oo.getterFor(Vo),Bo=Mo(Array,"Array",(function(e,t){Uo(this,{type:Vo,target:Do(e),index:0,kind:t})}),(function(){var e=Fo(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,Lo(void 0,!0);switch(e.kind){case"keys":return Lo(i,!1);case"values":return Lo(t[i],!1)}return Lo([i,t[i]],!1)}),"values"),Ho=wo.Arguments=wo.Array;if(No("keys"),No("values"),No("entries"),xo&&"values"!==Ho.name)try{Po(Ho,"name",{value:"values"})}catch(IW){}var Go=Ee,Wo=Fe,jo=w,Jo=pr,Ko=TypeError,qo="Reduce of empty array with no initial value",zo=function(e){return function(t,i,r,n){var s=Wo(t),o=jo(s),a=Jo(s);if(Go(i),0===a&&r<2)throw new Ko(qo);var c=e?a-1:0,l=e?-1:1;if(r<2)for(;;){if(c in o){n=o[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw new Ko(qo)}for(;e?c>=0:a>c;c+=l)c in o&&(n=i(n,o[c],c,s));return n}},Yo={left:zo(!1),right:zo(!0)},Xo=s,Qo=function(e,t){var i=[][e];return!!i&&Xo((function(){i.call(null,t||function(){return 1},1)}))},Zo=r,$o=Y,ea=C,ta=function(e){return $o.slice(0,e.length)===e},ia=ta("Bun/")?"BUN":ta("Cloudflare-Workers")?"CLOUDFLARE":ta("Deno/")?"DENO":ta("Node.js/")?"NODE":Zo.Bun&&"string"==typeof Bun.version?"BUN":Zo.Deno&&"object"==typeof Deno.version?"DENO":"process"===ea(Zo.process)?"NODE":Zo.window&&Zo.document?"BROWSER":"REST",ra="NODE"===ia,na=Yo.left;rn({target:"Array",proto:!0,forced:!ra&&ie>79&&ie<83||!Qo("reduce")},{reduce:function(e){var t=arguments.length;return na(this,e,t,t>1?arguments[1]:void 0)}});var sa=Yo.right;rn({target:"Array",proto:!0,forced:!ra&&ie>79&&ie<83||!Qo("reduceRight")},{reduceRight:function(e){return sa(this,e,arguments.length,arguments.length>1?arguments[1]:void 0)}});var oa=C,aa=Array.isArray||function(e){return"Array"===oa(e)},ca=rn,la=aa,da=S([].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=me,pa=TypeError,ma=S([].slice),_a=ma,fa=Math.floor,ga=function(e,t){var i=e.length;if(i<8)for(var r,n,s=1;s<i;){for(n=s,r=e[s];n&&t(e[n-1],r)>0;)e[n]=e[--n];n!==s++&&(e[n]=r)}else for(var o=fa(i/2),a=ga(_a(e,0,o),t),c=ga(_a(e,o),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},Ea=ga,Ta=Y.match(/firefox\/(\d+)/i),va=!!Ta&&+Ta[1],ya=/MSIE|Trident/.test(Y),Sa=Y.match(/AppleWebKit\/(\d+)\./),Ia=!!Sa&&+Sa[1],Ra=rn,Aa=S,Ca=Ee,ba=Fe,ka=pr,Da=function(e,t){if(!delete e[t])throw new pa("Cannot delete property "+ha(t)+" of "+ha(e))},Na=mn,wa=s,Oa=Ea,Pa=Qo,Ma=va,La=ya,xa=ie,Va=Ia,Ua=[],Fa=Aa(Ua.sort),Ba=Aa(Ua.push),Ha=wa((function(){Ua.sort(void 0)})),Ga=wa((function(){Ua.sort(null)})),Wa=Pa("sort"),ja=!wa((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||!Ga||!Wa||!ja},{sort:function(e){void 0!==e&&Ca(e);var t=ba(this);if(ja)return void 0===e?Fa(t):Fa(t,e);var i,r,n=[],s=ka(t);for(r=0;r<s;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:Na(t)>Na(i)?1:-1}}(e)),i=ka(n),r=0;r<i;)t[r]=n[r++];for(;r<s;)Da(t,r++);return t}});var Ja="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,Ka=Zi,qa=function(e,t,i){for(var r in t)Ka(e,r,t[r],i);return e},za=K,Ya=TypeError,Xa=function(e,t){if(za(t,e))return e;throw new Ya("Incorrect invocation")},Qa=nr,Za=ur,$a=RangeError,ec=function(e){if(void 0===e)return 0;var t=Qa(e),i=Za(t);if(t!==i)throw new $a("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=tc,rc=Math.abs,nc=2220446049250313e-31,sc=1/nc,oc=function(e,t,i,r){var n=+e,s=rc(n),o=ic(n);if(s<r)return o*function(e){return e+sc-sc}(s/r/t)*r*t;var a=(1+t/nc)*s,c=a-(a-s);return c>i||c!=c?Infinity*o:o*c},ac=Math.fround||function(e){return oc(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,s,o=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*(s=dc(2,-r))<1&&(r--,s*=2),(e+=r+l>=1?d/s:d*dc(2,1-l))*s>=2&&(r++,s/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*s-1)*dc(2,t),r+=l):(n=e*dc(2,l-1)*dc(2,t),r=0));t>=8;)o[h++]=255&n,n/=256,t-=8;for(r=r<<t|n,a+=t;a>0;)o[h++]=255&r,r/=256,a-=8;return o[h-1]|=128*u,o},unpack:function(e,t){var i,r=e.length,n=8*r-t-1,s=(1<<n)-1,o=s>>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-o;else{if(d===s)return i?NaN:l?-Infinity:Infinity;i+=dc(2,t),d-=o}return(l?-1:1)*i*dc(2,d-t)}},_c=Fe,fc=cr,gc=pr,Ec=function(e){for(var t=_c(this),i=gc(t),r=arguments.length,n=fc(r>1?arguments[1]:void 0,i),s=r>2?arguments[2]:void 0,o=void 0===s?i:fc(s,i);o>n;)t[n++]=e;return t},Tc=B,vc=G,yc=oo,Sc=function(e,t,i){var r,n;return yc&&Tc(r=t.constructor)&&r!==i&&vc(n=r.prototype)&&n!==i.prototype&&yc(e,n),e},Ic=r,Rc=S,Ac=o,Cc=Ja,bc=zt,kc=gn,Dc=qa,Nc=s,wc=Xa,Oc=nr,Pc=ur,Mc=ec,Lc=ac,xc=mc,Vc=Ds,Uc=oo,Fc=Ec,Bc=ma,Hc=Sc,Gc=Fr,Wc=Gs,jc=Ni,Jc=ii.PROPER,Kc=ii.CONFIGURABLE,qc="ArrayBuffer",zc="DataView",Yc="prototype",Xc="Wrong index",Qc=jc.getterFor(qc),Zc=jc.getterFor(zc),$c=jc.set,el=Ic[qc],tl=el,il=tl&&tl[Yc],rl=Ic[zc],nl=rl&&rl[Yc],sl=Object.prototype,ol=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)},El=function(e,t,i){kc(e[Yc],t,{configurable:!0,get:function(){return i(this)[t]}})},Tl=function(e,t,i,r){var n=Zc(e),s=Mc(i),o=!!r;if(s+t>n.byteLength)throw new al(Xc);var a=n.bytes,c=s+n.byteOffset,l=Bc(a,c,c+t);return o?l:ll(l)},vl=function(e,t,i,r,n,s){var o=Zc(e),a=Mc(i),c=r(+n),l=!!s;if(a+t>o.byteLength)throw new al(Xc);for(var d=o.bytes,u=a+o.byteOffset,h=0;h<t;h++)d[u+h]=c[l?h:t-h-1]};if(Cc){var yl=Jc&&el.name!==qc;Nc((function(){el(1)}))&&Nc((function(){new el(-1)}))&&!Nc((function(){return new el,new el(1.5),new el(NaN),1!==el.length||yl&&!Kc}))?yl&&Kc&&bc(el,"name",qc):((tl=function(e){return wc(this,il),Hc(new el(Mc(e)),this,tl)})[Yc]=il,il.constructor=tl,Gc(tl,el)),Uc&&Vc(nl)!==sl&&Uc(nl,sl);var Sl=new rl(new tl(2)),Il=Rc(nl.setInt8);Sl.setInt8(0,2147483648),Sl.setInt8(1,2147483649),!Sl.getInt8(0)&&Sl.getInt8(1)||Dc(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){wc(this,il);var t=Mc(e);$c(this,{type:qc,bytes:cl(ol(t),0),byteLength:t}),Ac||(this.byteLength=t,this.detached=!1)})[Yc],nl=(rl=function(e,t,i){wc(this,nl),wc(e,il);var r=Qc(e),n=r.byteLength,s=Oc(t);if(s<0||s>n)throw new al("Wrong offset");if(s+(i=void 0===i?n-s:Pc(i))>n)throw new al("Wrong length");$c(this,{type:zc,buffer:e,byteLength:i,byteOffset:s,bytes:r.bytes}),Ac||(this.buffer=e,this.byteLength=i,this.byteOffset=s)})[Yc],Ac&&(El(tl,"byteLength",Qc),El(rl,"buffer",Zc),El(rl,"byteLength",Zc),El(rl,"byteOffset",Zc)),Dc(nl,{getInt8:function(e){return Tl(this,1,e)[0]<<24>>24},getUint8:function(e){return Tl(this,1,e)[0]},getInt16:function(e){var t=Tl(this,2,e,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=Tl(this,2,e,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return _l(Tl(this,4,e,arguments.length>1&&arguments[1]))},getUint32:function(e){return _l(Tl(this,4,e,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(e){return ul(Tl(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return ul(Tl(this,8,e,arguments.length>1&&arguments[1]),52)},setInt8:function(e,t){vl(this,1,e,hl,t)},setUint8:function(e,t){vl(this,1,e,hl,t)},setInt16:function(e,t){vl(this,2,e,pl,t,arguments.length>2&&arguments[2])},setUint16:function(e,t){vl(this,2,e,pl,t,arguments.length>2&&arguments[2])},setInt32:function(e,t){vl(this,4,e,ml,t,arguments.length>2&&arguments[2])},setUint32:function(e,t){vl(this,4,e,ml,t,arguments.length>2&&arguments[2])},setFloat32:function(e,t){vl(this,4,e,fl,t,arguments.length>2&&arguments[2])},setFloat64:function(e,t){vl(this,8,e,gl,t,arguments.length>2&&arguments[2])}});Wc(tl,qc),Wc(rl,zc);var Rl={ArrayBuffer:tl,DataView:rl},Al=J,Cl=gn,bl=o,kl=it("species"),Dl=function(e){var t=Al(e);bl&&t&&!t[kl]&&Cl(t,kl,{configurable:!0,get:function(){return this}})},Nl=Dl,wl="ArrayBuffer",Ol=Rl[wl];rn({global:!0,constructor:!0,forced:r[wl]!==Ol},{ArrayBuffer:Ol}),Nl(wl);var Pl=C,Ml=S,Ll=function(e){if("Function"===Pl(e))return Ml(e)},xl=S,Vl=s,Ul=B,Fl=un,Bl=li,Hl=function(){},Gl=J("Reflect","construct"),Wl=/^\s*(?:class|function)\b/,jl=xl(Wl.exec),Jl=!Wl.test(Hl),Kl=function(e){if(!Ul(e))return!1;try{return Gl(Hl,[],e),!0}catch(IW){return!1}},ql=function(e){if(!Ul(e))return!1;switch(Fl(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Jl||!!jl(Wl,Bl(e))}catch(IW){return!0}};ql.sham=!0;var zl=!Gl||Vl((function(){var e;return Kl(Kl.call)||!Kl(Object)||!Kl((function(){e=!0}))||e}))?ql:Kl,Yl=zl,Xl=me,Ql=TypeError,Zl=function(e){if(Yl(e))return e;throw new Ql(Xl(e)+" is not a constructor")},$l=Mt,ed=Zl,td=O,id=it("species"),rd=function(e,t){var i,r=$l(e).constructor;return void 0===r||td(i=$l(r)[id])?t:ed(i)},nd=rn,sd=Ll,od=s,ad=Mt,cd=cr,ld=ur,dd=rd,ud=Rl.ArrayBuffer,hd=Rl.DataView,pd=hd.prototype,md=sd(ud.prototype.slice),_d=sd(pd.getUint8),fd=sd(pd.setUint8);nd({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:od((function(){return!new ud(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(md&&void 0===t)return md(ad(this),e);for(var i=ad(this).byteLength,r=cd(e,i),n=cd(void 0===t?i:t,i),s=new(dd(this,ud))(ld(n-r)),o=new hd(this),a=new hd(s),c=0;r<n;)fd(a,c++,_d(o,r++));return s}});var gd,Ed,Td,vd,yd=a,Sd=Function.prototype,Id=Sd.apply,Rd=Sd.call,Ad="object"==typeof Reflect&&Reflect.apply||(yd?Rd.bind(Id):function(){return Rd.apply(Id,arguments)}),Cd=Ee,bd=a,kd=Ll(Ll.bind),Dd=function(e,t){return Cd(e),void 0===t?e:bd?kd(e,t):function(){return e.apply(t,arguments)}},Nd=TypeError,wd=function(e,t){if(e<t)throw new Nd("Not enough arguments");return e},Od=/(?:ipad|iphone|ipod).*applewebkit/i.test(Y),Pd=r,Md=Ad,Ld=Dd,xd=B,Vd=Ge,Ud=s,Fd=zn,Bd=ma,Hd=gt,Gd=wd,Wd=Od,jd=ra,Jd=Pd.setImmediate,Kd=Pd.clearImmediate,qd=Pd.process,zd=Pd.Dispatch,Yd=Pd.Function,Xd=Pd.MessageChannel,Qd=Pd.String,Zd=0,$d={},eu="onreadystatechange";Ud((function(){gd=Pd.location}));var tu=function(e){if(Vd($d,e)){var t=$d[e];delete $d[e],t()}},iu=function(e){return function(){tu(e)}},ru=function(e){tu(e.data)},nu=function(e){Pd.postMessage(Qd(e),gd.protocol+"//"+gd.host)};Jd&&Kd||(Jd=function(e){Gd(arguments.length,1);var t=xd(e)?e:Yd(e),i=Bd(arguments,1);return $d[++Zd]=function(){Md(t,void 0,i)},Ed(Zd),Zd},Kd=function(e){delete $d[e]},jd?Ed=function(e){qd.nextTick(iu(e))}:zd&&zd.now?Ed=function(e){zd.now(iu(e))}:Xd&&!Wd?(vd=(Td=new Xd).port2,Td.port1.onmessage=ru,Ed=Ld(vd.postMessage,vd)):Pd.addEventListener&&xd(Pd.postMessage)&&!Pd.importScripts&&gd&&"file:"!==gd.protocol&&!Ud(nu)?(Ed=nu,Pd.addEventListener("message",ru,!1)):Ed=eu in Hd("script")?function(e){Fd.appendChild(Hd("script"))[eu]=function(){Fd.removeChild(this),tu(e)}}:function(e){setTimeout(iu(e),0)});var su={set:Jd,clear:Kd},ou=r,au=o,cu=Object.getOwnPropertyDescriptor,lu=function(e){if(!au)return ou[e];var t=cu(ou,e);return t&&t.value},du=function(){this.head=null,this.tail=null};du.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 uu,hu,pu,mu,_u,fu=du,gu=/ipad|iphone|ipod/i.test(Y)&&"undefined"!=typeof Pebble,Eu=/web0s(?!.*chrome)/i.test(Y),Tu=r,vu=lu,yu=Dd,Su=su.set,Iu=fu,Ru=Od,Au=gu,Cu=Eu,bu=ra,ku=Tu.MutationObserver||Tu.WebKitMutationObserver,Du=Tu.document,Nu=Tu.process,wu=Tu.Promise,Ou=vu("queueMicrotask");if(!Ou){var Pu=new Iu,Mu=function(){var e,t;for(bu&&(e=Nu.domain)&&e.exit();t=Pu.get();)try{t()}catch(IW){throw Pu.head&&uu(),IW}e&&e.enter()};Ru||bu||Cu||!ku||!Du?!Au&&wu&&wu.resolve?((mu=wu.resolve(void 0)).constructor=wu,_u=yu(mu.then,mu),uu=function(){_u(Mu)}):bu?uu=function(){Nu.nextTick(Mu)}:(Su=yu(Su,Tu),uu=function(){Su(Mu)}):(hu=!0,pu=Du.createTextNode(""),new ku(Mu).observe(pu,{characterData:!0}),uu=function(){pu.data=hu=!hu}),Ou=function(e){Pu.head||uu(),Pu.add(e)}}var Lu=Ou,xu=function(e){try{return{error:!1,value:e()}}catch(IW){return{error:!0,value:IW}}},Vu=r.Promise,Uu=r,Fu=Vu,Bu=B,Hu=zr,Gu=li,Wu=it,ju=ia,Ju=ie;Fu&&Fu.prototype;var Ku=Wu("species"),qu=!1,zu=Bu(Uu.PromiseRejectionEvent),Yu=Hu("Promise",(function(){var e=Gu(Fu),t=e!==String(Fu);if(!t&&66===Ju)return!0;if(!Ju||Ju<51||!/native code/.test(e)){var i=new Fu((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((i.constructor={})[Ku]=r,!(qu=i.then((function(){}))instanceof r))return!0}return!(t||"BROWSER"!==ju&&"DENO"!==ju||zu)})),Xu={CONSTRUCTOR:Yu,REJECTION_EVENT:zu,SUBCLASSING:qu},Qu={},Zu=Ee,$u=TypeError,eh=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=Zu(t),this.reject=Zu(i)};Qu.f=function(e){return new eh(e)};var th,ih,rh,nh=rn,sh=ra,oh=r,ah=d,ch=Zi,lh=oo,dh=Gs,uh=Dl,hh=Ee,ph=B,mh=G,_h=Xa,fh=rd,gh=su.set,Eh=Lu,Th=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(IW){}},vh=xu,yh=fu,Sh=Ni,Ih=Vu,Rh=Qu,Ah="Promise",Ch=Xu.CONSTRUCTOR,bh=Xu.REJECTION_EVENT,kh=Xu.SUBCLASSING,Dh=Sh.getterFor(Ah),Nh=Sh.set,wh=Ih&&Ih.prototype,Oh=Ih,Ph=wh,Mh=oh.TypeError,Lh=oh.document,xh=oh.process,Vh=Rh.f,Uh=Vh,Fh=!!(Lh&&Lh.createEvent&&oh.dispatchEvent),Bh="unhandledrejection",Hh=function(e){var t;return!(!mh(e)||!ph(t=e.then))&&t},Gh=function(e,t){var i,r,n,s=t.value,o=1===t.state,a=o?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{a?(o||(2===t.rejection&&qh(t),t.rejection=1),!0===a?i=s:(d&&d.enter(),i=a(s),d&&(d.exit(),n=!0)),i===e.promise?l(new Mh("Promise-chain cycle")):(r=Hh(i))?ah(r,i,c,l):c(i)):l(s)}catch(IW){d&&!n&&d.exit(),l(IW)}},Wh=function(e,t){e.notified||(e.notified=!0,Eh((function(){for(var i,r=e.reactions;i=r.get();)Gh(i,e);e.notified=!1,t&&!e.rejection&&Jh(e)})))},jh=function(e,t,i){var r,n;Fh?((r=Lh.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),oh.dispatchEvent(r)):r={promise:t,reason:i},!bh&&(n=oh["on"+e])?n(r):e===Bh&&Th("Unhandled promise rejection",i)},Jh=function(e){ah(gh,oh,(function(){var t,i=e.facade,r=e.value;if(Kh(e)&&(t=vh((function(){sh?xh.emit("unhandledRejection",r,i):jh(Bh,i,r)})),e.rejection=sh||Kh(e)?2:1,t.error))throw t.value}))},Kh=function(e){return 1!==e.rejection&&!e.parent},qh=function(e){ah(gh,oh,(function(){var t=e.facade;sh?xh.emit("rejectionHandled",t):jh("rejectionhandled",t,e.value)}))},zh=function(e,t,i){return function(r){e(t,r,i)}},Yh=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Wh(e,!0))},Xh=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new Mh("Promise can't be resolved itself");var r=Hh(t);r?Eh((function(){var i={done:!1};try{ah(r,t,zh(Xh,i,e),zh(Yh,i,e))}catch(IW){Yh(i,IW,e)}})):(e.value=t,e.state=1,Wh(e,!1))}catch(IW){Yh({done:!1},IW,e)}}};if(Ch&&(Ph=(Oh=function(e){_h(this,Ph),hh(e),ah(th,this);var t=Dh(this);try{e(zh(Xh,t),zh(Yh,t))}catch(IW){Yh(t,IW)}}).prototype,(th=function(e){Nh(this,{type:Ah,done:!1,notified:!1,parent:!1,reactions:new yh,rejection:!1,state:0,value:null})}).prototype=ch(Ph,"then",(function(e,t){var i=Dh(this),r=Vh(fh(this,Oh));return i.parent=!0,r.ok=!ph(e)||e,r.fail=ph(t)&&t,r.domain=sh?xh.domain:void 0,0===i.state?i.reactions.add(r):Eh((function(){Gh(r,i)})),r.promise})),ih=function(){var e=new th,t=Dh(e);this.promise=e,this.resolve=zh(Xh,t),this.reject=zh(Yh,t)},Rh.f=Vh=function(e){return e===Oh||undefined===e?new ih(e):Uh(e)},ph(Ih)&&wh!==Object.prototype)){rh=wh.then,kh||ch(wh,"then",(function(e,t){var i=this;return new Oh((function(e,t){ah(rh,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete wh.constructor}catch(IW){}lh&&lh(wh,Ph)}nh({global:!0,constructor:!0,wrap:!0,forced:Ch},{Promise:Oh}),dh(Oh,Ah,!1),uh(Ah);var Qh=vs,Zh=it("iterator"),$h=Array.prototype,ep=function(e){return void 0!==e&&(Qh.Array===e||$h[Zh]===e)},tp=un,ip=ye,rp=O,np=vs,sp=it("iterator"),op=function(e){if(!rp(e))return ip(e,sp)||ip(e,"@@iterator")||np[tp(e)]},ap=d,cp=Ee,lp=Mt,dp=me,up=op,hp=TypeError,pp=function(e,t){var i=arguments.length<2?up(e):t;if(cp(i))return lp(ap(i,e));throw new hp(dp(e)+" is not iterable")},mp=d,_p=Mt,fp=ye,gp=function(e,t,i){var r,n;_p(e);try{if(!(r=fp(e,"return"))){if("throw"===t)throw i;return i}r=mp(r,e)}catch(IW){n=!0,r=IW}if("throw"===t)throw i;if(n)throw r;return _p(r),i},Ep=Dd,Tp=d,vp=Mt,yp=me,Sp=ep,Ip=pr,Rp=K,Ap=pp,Cp=op,bp=gp,kp=TypeError,Dp=function(e,t){this.stopped=e,this.result=t},Np=Dp.prototype,wp=function(e,t,i){var r,n,s,o,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),_=Ep(t,d),f=function(e){return r&&bp(r,"normal",e),new Dp(!0,e)},g=function(e){return u?(vp(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 kp(yp(e)+" is not iterable");if(Sp(n)){for(s=0,o=Ip(e);o>s;s++)if((a=g(e[s]))&&Rp(Np,a))return a;return new Dp(!1)}r=Ap(e,n)}for(c=h?e.next:r.next;!(l=Tp(c,r)).done;){try{a=g(l.value)}catch(IW){bp(r,"throw",IW)}if("object"==typeof a&&a&&Rp(Np,a))return a}return new Dp(!1)},Op=it("iterator"),Pp=!1;try{var Mp=0,Lp={next:function(){return{done:!!Mp++}},return:function(){Pp=!0}};Lp[Op]=function(){return this},Array.from(Lp,(function(){throw 2}))}catch(IW){}var xp=function(e,t){try{if(!t&&!Pp)return!1}catch(IW){return!1}var i=!1;try{var r={};r[Op]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(IW){}return i},Vp=Vu,Up=Xu.CONSTRUCTOR||!xp((function(e){Vp.all(e).then(void 0,(function(){}))})),Fp=d,Bp=Ee,Hp=Qu,Gp=xu,Wp=wp;rn({target:"Promise",stat:!0,forced:Up},{all:function(e){var t=this,i=Hp.f(t),r=i.resolve,n=i.reject,s=Gp((function(){var i=Bp(t.resolve),s=[],o=0,a=1;Wp(e,(function(e){var c=o++,l=!1;a++,Fp(i,t,e).then((function(e){l||(l=!0,s[c]=e,--a||r(s))}),n)})),--a||r(s)}));return s.error&&n(s.value),i.promise}});var jp=rn,Jp=Xu.CONSTRUCTOR,Kp=Vu,qp=J,zp=B,Yp=Zi,Xp=Kp&&Kp.prototype;if(jp({target:"Promise",proto:!0,forced:Jp,real:!0},{catch:function(e){return this.then(void 0,e)}}),zp(Kp)){var Qp=qp("Promise").prototype.catch;Xp.catch!==Qp&&Yp(Xp,"catch",Qp,{unsafe:!0})}var Zp=d,$p=Ee,em=Qu,tm=xu,im=wp;rn({target:"Promise",stat:!0,forced:Up},{race:function(e){var t=this,i=em.f(t),r=i.reject,n=tm((function(){var n=$p(t.resolve);im(e,(function(e){Zp(n,t,e).then(i.resolve,r)}))}));return n.error&&r(n.value),i.promise}});var rm=Qu;rn({target:"Promise",stat:!0,forced:Xu.CONSTRUCTOR},{reject:function(e){var t=rm.f(this);return(0,t.reject)(e),t.promise}});var nm=Mt,sm=G,om=Qu,am=function(e,t){if(nm(e),sm(t)&&t.constructor===e)return t;var i=om.f(e);return(0,i.resolve)(t),i.promise},cm=rn,lm=Xu.CONSTRUCTOR,dm=am;J("Promise"),cm({target:"Promise",stat:!0,forced:lm},{resolve:function(e){return dm(this,e)}});var um=rn,hm=Vu,pm=s,mm=J,_m=B,fm=rd,gm=am,Em=Zi,Tm=hm&&hm.prototype;if(um({target:"Promise",proto:!0,real:!0,forced:!!hm&&pm((function(){Tm.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=fm(this,mm("Promise")),i=_m(e);return this.then(i?function(i){return gm(t,e()).then((function(){return i}))}:e,i?function(i){return gm(t,e()).then((function(){throw i}))}:e)}}),_m(hm)){var vm=mm("Promise").prototype.finally;Tm.finally!==vm&&Em(Tm,"finally",vm,{unsafe:!0})}var ym=G,Sm=C,Im=it("match"),Rm=Mt,Am=function(){var e=Rm(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=d,bm=Ge,km=K,Dm=Am,Nm=RegExp.prototype,wm=s,Om=r.RegExp,Pm=wm((function(){var e=Om("a","y");return e.lastIndex=2,null!==e.exec("abcd")})),Mm=Pm||wm((function(){return!Om("a","y").sticky})),Lm=Pm||wm((function(){var e=Om("^r","gy");return e.lastIndex=2,null!==e.exec("str")})),xm={BROKEN_CARET:Lm,MISSED_STICKY:Mm,UNSUPPORTED_Y:Pm},Vm=Dt.f,Um=s,Fm=r.RegExp,Bm=Um((function(){var e=Fm(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)})),Hm=s,Gm=r.RegExp,Wm=Hm((function(){var e=Gm("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),jm=o,Jm=r,Km=S,qm=zr,zm=Sc,Ym=zt,Xm=cs,Qm=$i.f,Zm=K,$m=function(e){var t;return ym(e)&&(void 0!==(t=e[Im])?!!t:"RegExp"===Sm(e))},e_=mn,t_=function(e){var t=e.flags;return void 0!==t||"flags"in Nm||bm(e,"flags")||!km(Nm,e)?t:Cm(Dm,e)},i_=xm,r_=function(e,t,i){i in e||Vm(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},n_=Zi,s_=s,o_=Ge,a_=Ni.enforce,c_=Dl,l_=Bm,d_=Wm,u_=it("match"),h_=Jm.RegExp,p_=h_.prototype,m_=Jm.SyntaxError,__=Km(p_.exec),f_=Km("".charAt),g_=Km("".replace),E_=Km("".indexOf),T_=Km("".slice),v_=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,y_=/a/g,S_=/a/g,I_=new h_(y_)!==y_,R_=i_.MISSED_STICKY,A_=i_.UNSUPPORTED_Y,C_=jm&&(!I_||R_||l_||d_||s_((function(){return S_[u_]=!1,h_(y_)!==y_||h_(S_)===S_||"/a/i"!==String(h_(y_,"i"))})));if(qm("RegExp",C_)){for(var b_=function(e,t){var i,r,n,s,o,a,c=Zm(p_,this),l=$m(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===b_)return e;if((l||Zm(p_,e))&&(e=e.source,d&&(t=t_(h))),e=void 0===e?"":e_(e),t=void 0===t?"":e_(t),h=e,l_&&"dotAll"in y_&&(r=!!t&&E_(t,"s")>-1)&&(t=g_(t,/s/g,"")),i=t,R_&&"sticky"in y_&&(n=!!t&&E_(t,"y")>-1)&&A_&&(t=g_(t,/y/g,"")),d_&&(s=function(e){for(var t,i=e.length,r=0,n="",s=[],o=Xm(null),a=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=f_(e,r)))t+=f_(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:if(n+=t,"?:"===T_(e,r+1,r+3))continue;__(v_,T_(e,r+1))&&(r+=2,c=!0),l++;continue;case">"===t&&c:if(""===d||o_(o,d))throw new m_("Invalid capture group name");o[d]=!0,s[s.length]=[d,l],c=!1,d="";continue}c?d+=t:n+=t}return[n,s]}(e),e=s[0],u=s[1]),o=zm(h_(e,t),c?this:p_,b_),(r||n||u.length)&&(a=a_(o),r&&(a.dotAll=!0,a.raw=b_(function(e){for(var t,i=e.length,r=0,n="",s=!1;r<=i;r++)"\\"!==(t=f_(e,r))?s||"."!==t?("["===t?s=!0:"]"===t&&(s=!1),n+=t):n+="[\\s\\S]":n+=t+f_(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Ym(o,"source",""===h?"(?:)":h)}catch(IW){}return o},k_=Qm(h_),D_=0;k_.length>D_;)r_(b_,h_,k_[D_++]);p_.constructor=b_,b_.prototype=p_,n_(Jm,"RegExp",b_,{constructor:!0})}c_("RegExp");var N_=d,w_=S,O_=mn,P_=Am,M_=xm,L_=cs,x_=Ni.get,V_=Bm,U_=Wm,F_=xe("native-string-replace",String.prototype.replace),B_=RegExp.prototype.exec,H_=B_,G_=w_("".charAt),W_=w_("".indexOf),j_=w_("".replace),J_=w_("".slice),K_=function(){var e=/a/,t=/b*/g;return N_(B_,e,"a"),N_(B_,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),q_=M_.BROKEN_CARET,z_=void 0!==/()??/.exec("")[1];(K_||z_||q_||V_||U_)&&(H_=function(e){var t,i,r,n,s,o,a,c=this,l=x_(c),d=O_(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=N_(H_,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=q_&&c.sticky,m=N_(P_,c),_=c.source,f=0,g=d;if(p&&(m=j_(m,"y",""),-1===W_(m,"g")&&(m+="g"),g=J_(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==G_(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),z_&&(i=new RegExp("^"+_+"$(?!\\s)",m)),K_&&(r=c.lastIndex),n=N_(B_,p?i:c,g),p?n?(n.input=J_(n.input,f),n[0]=J_(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:K_&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),z_&&n&&n.length>1&&N_(F_,n[0],i,(function(){for(s=1;s<arguments.length-2;s++)void 0===arguments[s]&&(n[s]=void 0)})),n&&h)for(n.groups=o=L_(null),s=0;s<h.length;s++)o[(a=h[s])[0]]=n[a[1]];return n});var Y_=H_;rn({target:"RegExp",proto:!0,forced:/./.exec!==Y_},{exec:Y_});var X_=nr,Q_=mn,Z_=L,$_=RangeError,ef=S,tf=ur,rf=mn,nf=function(e){var t=Q_(Z_(this)),i="",r=X_(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},sf=L,of=ef(nf),af=ef("".slice),cf=Math.ceil,lf=function(e){return function(t,i,r){var n,s,o=rf(sf(t)),a=tf(i),c=o.length,l=void 0===r?" ":rf(r);return a<=c||""===l?o:((s=of(l,cf((n=a-c)/l.length))).length>n&&(s=af(s,0,n)),e?o+s:s+o)}},df={start:lf(!1),end:lf(!0)},uf=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Y),hf=df.start;rn({target:"String",proto:!0,forced:uf},{padStart:function(e){return hf(this,e,arguments.length>1?arguments[1]:void 0)}});var pf=d,mf=Zi,_f=Y_,ff=s,gf=it,Ef=zt,Tf=gf("species"),vf=RegExp.prototype,yf=S,Sf=nr,If=mn,Rf=L,Af=yf("".charAt),Cf=yf("".charCodeAt),bf=yf("".slice),kf=function(e){return function(t,i){var r,n,s=If(Rf(t)),o=Sf(i),a=s.length;return o<0||o>=a?e?"":void 0:(r=Cf(s,o))<55296||r>56319||o+1===a||(n=Cf(s,o+1))<56320||n>57343?e?Af(s,o):r:e?bf(s,o,o+2):n-56320+(r-55296<<10)+65536}},Df={codeAt:kf(!1),charAt:kf(!0)},Nf=Df.charAt,wf=S,Of=Fe,Pf=Math.floor,Mf=wf("".charAt),Lf=wf("".replace),xf=wf("".slice),Vf=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Uf=/\$([$&'`]|\d{1,2})/g,Ff=d,Bf=Mt,Hf=B,Gf=C,Wf=Y_,jf=TypeError,Jf=Ad,Kf=d,qf=S,zf=function(e,t,i,r){var n=gf(e),s=!ff((function(){var t={};return t[n]=function(){return 7},7!==""[e](t)})),o=s&&!ff((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[Tf]=function(){return i},i.flags="",i[n]=/./[n]),i.exec=function(){return t=!0,null},i[n](""),!t}));if(!s||!o||i){var a=/./[n],c=t(n,""[e],(function(e,t,i,r,n){var o=t.exec;return o===_f||o===vf.exec?s&&!n?{done:!0,value:pf(a,t,i,r)}:{done:!0,value:pf(e,i,t,r)}:{done:!1}}));mf(String.prototype,e,c[0]),mf(vf,n,c[1])}r&&Ef(vf[n],"sham",!0)},Yf=s,Xf=Mt,Qf=B,Zf=O,$f=nr,eg=ur,tg=mn,ig=L,rg=function(e,t,i){return t+(i?Nf(e,t).length:1)},ng=ye,sg=function(e,t,i,r,n,s){var o=i+e.length,a=r.length,c=Uf;return void 0!==n&&(n=Of(n),c=Vf),Lf(s,c,(function(s,c){var l;switch(Mf(c,0)){case"$":return"$";case"&":return e;case"`":return xf(t,0,i);case"'":return xf(t,o);case"<":l=n[xf(c,1,-1)];break;default:var d=+c;if(0===d)return s;if(d>a){var u=Pf(d/10);return 0===u?s:u<=a?void 0===r[u-1]?Mf(c,1):r[u-1]+Mf(c,1):s}l=r[d-1]}return void 0===l?"":l}))},og=function(e,t){var i=e.exec;if(Hf(i)){var r=Ff(i,e,t);return null!==r&&Bf(r),r}if("RegExp"===Gf(e))return Ff(Wf,e,t);throw new jf("RegExp#exec called on incompatible receiver")},ag=it("replace"),cg=Math.max,lg=Math.min,dg=qf([].concat),ug=qf([].push),hg=qf("".indexOf),pg=qf("".slice),mg=function(e){return void 0===e?e:String(e)},_g="$0"==="a".replace(/./,"$0"),fg=!!/./[ag]&&""===/./[ag]("a","$0"),gg=!Yf((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));zf("replace",(function(e,t,i){var r=fg?"$":"$0";return[function(e,i){var r=ig(this),n=Zf(e)?void 0:ng(e,ag);return n?Kf(n,e,r,i):Kf(t,tg(r),e,i)},function(e,n){var s=Xf(this),o=tg(e);if("string"==typeof n&&-1===hg(n,r)&&-1===hg(n,"$<")){var a=i(t,s,o,n);if(a.done)return a.value}var c=Qf(n);c||(n=tg(n));var l,d=s.global;d&&(l=s.unicode,s.lastIndex=0);for(var u,h=[];null!==(u=og(s,o))&&(ug(h,u),d);){""===tg(u[0])&&(s.lastIndex=rg(o,eg(s.lastIndex),l))}for(var p="",m=0,_=0;_<h.length;_++){for(var f,g=tg((u=h[_])[0]),E=cg(lg($f(u.index),o.length),0),T=[],v=1;v<u.length;v++)ug(T,mg(u[v]));var y=u.groups;if(c){var S=dg([g],T,E,o);void 0!==y&&ug(S,y),f=tg(Jf(n,void 0,S))}else f=sg(g,o,E,T,y,n);E>=m&&(p+=pg(o,m,E)+f,m=E+g.length)}return p+pg(o,m)}]}),!gg||!_g||fg);var Eg="\t\n\v\f\r \u2028\u2029\ufeff",Tg=L,vg=mn,yg=Eg,Sg=S("".replace),Ig=RegExp("^["+yg+"]+"),Rg=RegExp("(^|[^"+yg+"])["+yg+"]+$"),Ag=function(e){return function(t){var i=vg(Tg(t));return 1&e&&(i=Sg(i,Ig,"")),2&e&&(i=Sg(i,Rg,"$1")),i}},Cg={start:Ag(1),end:Ag(2),trim:Ag(3)},bg=ii.PROPER,kg=s,Dg=Eg,Ng=Cg.trim;rn({target:"String",proto:!0,forced:function(e){return kg((function(){return!!Dg[e]()||"
"!=="
"[e]()||bg&&Dg[e].name!==e}))}("trim")},{trim:function(){return Ng(this)}});var wg,Og,Pg,Mg={},Lg={get exports(){return Mg},set exports(e){Mg=e}},xg=Ja,Vg=o,Ug=r,Fg=B,Bg=G,Hg=Ge,Gg=un,Wg=me,jg=zt,Jg=Zi,Kg=gn,qg=K,zg=Ds,Yg=oo,Xg=it,Qg=qe,Zg=Ni.enforce,$g=Ni.get,eE=Ug.Int8Array,tE=eE&&eE.prototype,iE=Ug.Uint8ClampedArray,rE=iE&&iE.prototype,nE=eE&&zg(eE),sE=tE&&zg(tE),oE=Object.prototype,aE=Ug.TypeError,cE=Xg("toStringTag"),lE=Qg("TYPED_ARRAY_TAG"),dE="TypedArrayConstructor",uE=xg&&!!Yg&&"Opera"!==Gg(Ug.opera),hE=!1,pE={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},mE={BigInt64Array:8,BigUint64Array:8},_E=function(e){var t=zg(e);if(Bg(t)){var i=$g(t);return i&&Hg(i,dE)?i[dE]:_E(t)}},fE=function(e){if(!Bg(e))return!1;var t=Gg(e);return Hg(pE,t)||Hg(mE,t)};for(wg in pE)(Pg=(Og=Ug[wg])&&Og.prototype)?Zg(Pg)[dE]=Og:uE=!1;for(wg in mE)(Pg=(Og=Ug[wg])&&Og.prototype)&&(Zg(Pg)[dE]=Og);if((!uE||!Fg(nE)||nE===Function.prototype)&&(nE=function(){throw new aE("Incorrect invocation")},uE))for(wg in pE)Ug[wg]&&Yg(Ug[wg],nE);if((!uE||!sE||sE===oE)&&(sE=nE.prototype,uE))for(wg in pE)Ug[wg]&&Yg(Ug[wg].prototype,sE);if(uE&&zg(rE)!==sE&&Yg(rE,sE),Vg&&!Hg(sE,cE))for(wg in hE=!0,Kg(sE,cE,{configurable:!0,get:function(){return Bg(this)?this[lE]:void 0}}),pE)Ug[wg]&&jg(Ug[wg],lE,wg);var gE={NATIVE_ARRAY_BUFFER_VIEWS:uE,TYPED_ARRAY_TAG:hE&&lE,aTypedArray:function(e){if(fE(e))return e;throw new aE("Target is not a typed array")},aTypedArrayConstructor:function(e){if(Fg(e)&&(!Yg||qg(nE,e)))return e;throw new aE(Wg(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(Vg){if(i)for(var n in pE){var s=Ug[n];if(s&&Hg(s.prototype,e))try{delete s.prototype[e]}catch(IW){try{s.prototype[e]=t}catch(o){}}}sE[e]&&!i||Jg(sE,e,i?t:uE&&tE[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(Vg){if(Yg){if(i)for(r in pE)if((n=Ug[r])&&Hg(n,e))try{delete n[e]}catch(IW){}if(nE[e]&&!i)return;try{return Jg(nE,e,i?t:uE&&nE[e]||t)}catch(IW){}}for(r in pE)!(n=Ug[r])||n[e]&&!i||Jg(n,e,t)}},getTypedArrayConstructor:_E,isView:function(e){if(!Bg(e))return!1;var t=Gg(e);return"DataView"===t||Hg(pE,t)||Hg(mE,t)},isTypedArray:fE,TypedArray:nE,TypedArrayPrototype:sE},EE=r,TE=s,vE=xp,yE=gE.NATIVE_ARRAY_BUFFER_VIEWS,SE=EE.ArrayBuffer,IE=EE.Int8Array,RE=!yE||!TE((function(){IE(1)}))||!TE((function(){new IE(-1)}))||!vE((function(e){new IE,new IE(null),new IE(1.5),new IE(e)}),!0)||TE((function(){return 1!==new IE(new SE(2),1,void 0).length})),AE=G,CE=Math.floor,bE=Number.isInteger||function(e){return!AE(e)&&isFinite(e)&&CE(e)===e},kE=nr,DE=RangeError,NE=function(e){var t=kE(e);if(t<0)throw new DE("The argument can't be less than 0");return t},wE=RangeError,OE=function(e,t){var i=NE(e);if(i%t)throw new wE("Wrong offset");return i},PE=Math.round,ME=un,LE=dt,xE=TypeError,VE=function(e){var t=LE(e,"number");if("number"==typeof t)throw new xE("Can't convert number to bigint");return BigInt(t)},UE=Dd,FE=d,BE=Zl,HE=Fe,GE=pr,WE=pp,jE=op,JE=ep,KE=function(e){var t=ME(e);return"BigInt64Array"===t||"BigUint64Array"===t},qE=gE.aTypedArrayConstructor,zE=VE,YE=function(e){var t,i,r,n,s,o,a,c,l=BE(this),d=HE(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=jE(d);if(m&&!JE(m))for(c=(a=WE(d,m)).next,d=[];!(o=FE(c,a)).done;)d.push(o.value);for(p&&u>2&&(h=UE(h,arguments[2])),i=GE(d),r=new(qE(l))(i),n=KE(r),t=0;i>t;t++)s=p?h(d[t],t):d[t],r[t]=n?zE(s):+s;return r},XE=aa,QE=zl,ZE=G,$E=it("species"),eT=Array,tT=function(e){var t;return XE(e)&&(t=e.constructor,(QE(t)&&(t===eT||XE(t.prototype))||ZE(t)&&null===(t=t[$E]))&&(t=void 0)),void 0===t?eT:t},iT=Dd,rT=w,nT=Fe,sT=pr,oT=function(e,t){return new(tT(e))(0===t?0:t)},aT=S([].push),cT=function(e){var t=1===e,i=2===e,r=3===e,n=4===e,s=6===e,o=7===e,a=5===e||s;return function(c,l,d,u){for(var h,p,m=nT(c),_=rT(m),f=sT(_),g=iT(l,d),E=0,T=u||oT,v=t?T(c,f):i||o?T(c,0):void 0;f>E;E++)if((a||E in _)&&(p=g(h=_[E],E,m),e))if(t)v[E]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return E;case 2:aT(v,h)}else switch(e){case 4:return!1;case 7:aT(v,h)}return s?-1:r||n?n:v}},lT={forEach:cT(0),map:cT(1),filter:cT(2),some:cT(3),every:cT(4),find:cT(5),findIndex:cT(6),filterReject:cT(7)},dT=pr,uT=rn,hT=r,pT=d,mT=o,_T=RE,fT=gE,gT=Rl,ET=Xa,TT=g,vT=zt,yT=bE,ST=ur,IT=ec,RT=OE,AT=function(e){var t=PE(e);return t<0?0:t>255?255:255&t},CT=pt,bT=Ge,kT=un,DT=G,NT=he,wT=cs,OT=K,PT=oo,MT=$i.f,LT=YE,xT=lT.forEach,VT=Dl,UT=gn,FT=Dt,BT=n,HT=function(e,t,i){for(var r=0,n=arguments.length>2?i:dT(t),s=new e(n);n>r;)s[r]=t[r++];return s},GT=Sc,WT=Ni.get,jT=Ni.set,JT=Ni.enforce,KT=FT.f,qT=BT.f,zT=hT.RangeError,YT=gT.ArrayBuffer,XT=YT.prototype,QT=gT.DataView,ZT=fT.NATIVE_ARRAY_BUFFER_VIEWS,$T=fT.TYPED_ARRAY_TAG,ev=fT.TypedArray,tv=fT.TypedArrayPrototype,iv=fT.isTypedArray,rv="BYTES_PER_ELEMENT",nv="Wrong length",sv=function(e,t){UT(e,t,{configurable:!0,get:function(){return WT(this)[t]}})},ov=function(e){var t;return OT(XT,e)||"ArrayBuffer"===(t=kT(e))||"SharedArrayBuffer"===t},av=function(e,t){return iv(e)&&!NT(t)&&t in e&&yT(+t)&&t>=0},cv=function(e,t){return t=CT(t),av(e,t)?TT(2,e[t]):qT(e,t)},lv=function(e,t,i){return t=CT(t),!(av(e,t)&&DT(i)&&bT(i,"value"))||bT(i,"get")||bT(i,"set")||i.configurable||bT(i,"writable")&&!i.writable||bT(i,"enumerable")&&!i.enumerable?KT(e,t,i):(e[t]=i.value,e)};mT?(ZT||(BT.f=cv,FT.f=lv,sv(tv,"buffer"),sv(tv,"byteOffset"),sv(tv,"byteLength"),sv(tv,"length")),uT({target:"Object",stat:!0,forced:!ZT},{getOwnPropertyDescriptor:cv,defineProperty:lv}),Lg.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",s="get"+e,o="set"+e,a=hT[n],c=a,l=c&&c.prototype,d={},u=function(e,t){KT(e,t,{get:function(){return function(e,t){var i=WT(e);return i.view[s](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var s=WT(e);s.view[o](t*r+s.byteOffset,i?AT(n):n,!0)}(this,t,e)},enumerable:!0})};ZT?_T&&(c=t((function(e,t,i,n){return ET(e,l),GT(DT(t)?ov(t)?void 0!==n?new a(t,RT(i,r),n):void 0!==i?new a(t,RT(i,r)):new a(t):iv(t)?HT(c,t):pT(LT,c,t):new a(IT(t)),e,c)})),PT&&PT(c,ev),xT(MT(a),(function(e){e in c||vT(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,n){ET(e,l);var s,o,a,d=0,h=0;if(DT(t)){if(!ov(t))return iv(t)?HT(c,t):pT(LT,c,t);s=t,h=RT(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw new zT(nv);if((o=p-h)<0)throw new zT(nv)}else if((o=ST(n)*r)+h>p)throw new zT(nv);a=o/r}else a=IT(t),s=new YT(o=a*r);for(jT(e,{buffer:s,byteOffset:h,byteLength:o,length:a,view:new QT(s)});d<a;)u(e,d++)})),PT&&PT(c,ev),l=c.prototype=wT(tv)),l.constructor!==c&&vT(l,"constructor",c),JT(l).TypedArrayConstructor=c,$T&&vT(l,$T,n);var h=c!==a;d[n]=c,uT({global:!0,constructor:!0,forced:h,sham:!ZT},d),rv in c||vT(c,rv,r),rv in l||vT(l,rv,r),VT(n)}):Lg.exports=function(){},Mg("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}})),Mg("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var dv=Ec,uv=VE,hv=un,pv=d,mv=s,_v=gE.aTypedArray,fv=gE.exportTypedArrayMethod,gv=S("".slice);fv("fill",(function(e){var t=arguments.length;_v(this);var i="Big"===gv(hv(this),0,3)?uv(e):+e;return pv(dv,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),mv((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e}))),(0,gE.exportTypedArrayStaticMethod)("from",YE,RE);var Ev=r,Tv=d,vv=gE,yv=pr,Sv=OE,Iv=Fe,Rv=s,Av=Ev.RangeError,Cv=Ev.Int8Array,bv=Cv&&Cv.prototype,kv=bv&&bv.set,Dv=vv.aTypedArray,Nv=vv.exportTypedArrayMethod,wv=!Rv((function(){var e=new Uint8ClampedArray(2);return Tv(kv,e,{length:1,0:3},1),3!==e[1]})),Ov=wv&&vv.NATIVE_ARRAY_BUFFER_VIEWS&&Rv((function(){var e=new Cv(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));Nv("set",(function(e){Dv(this);var t=Sv(arguments.length>1?arguments[1]:void 0,1),i=Iv(e);if(wv)return Tv(kv,this,i,t);var r=this.length,n=yv(i),s=0;if(n+t>r)throw new Av("Wrong length");for(;s<n;)this[t+s]=i[s++]}),!wv||Ov);var Pv=Ll,Mv=s,Lv=Ee,xv=Ea,Vv=va,Uv=ya,Fv=ie,Bv=Ia,Hv=gE.aTypedArray,Gv=gE.exportTypedArrayMethod,Wv=r.Uint16Array,jv=Wv&&Pv(Wv.prototype.sort),Jv=!(!jv||Mv((function(){jv(new Wv(2),null)}))&&Mv((function(){jv(new Wv(2),{})}))),Kv=!!jv&&!Mv((function(){if(Fv)return Fv<74;if(Vv)return Vv<67;if(Uv)return!0;if(Bv)return Bv<602;var e,t,i=new Wv(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(jv(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));Gv("sort",(function(e){return void 0!==e&&Lv(e),Kv?jv(this,e):xv(Hv(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))}),!Kv||Jv);var qv={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},zv=gt("span").classList,Yv=zv&&zv.constructor&&zv.constructor.prototype,Xv=Yv===Object.prototype?void 0:Yv,Qv=lT.forEach,Zv=Qo("forEach")?[].forEach:function(e){return Qv(this,e,arguments.length>1?arguments[1]:void 0)},$v=r,ey=qv,ty=Xv,iy=Zv,ry=zt,ny=function(e){if(e&&e.forEach!==iy)try{ry(e,"forEach",iy)}catch(IW){e.forEach=iy}};for(var sy in ey)ey[sy]&&ny($v[sy]&&$v[sy].prototype);ny(ty);var oy=r,ay=qv,cy=Xv,ly=Bo,dy=zt,uy=Gs,hy=it("iterator"),py=ly.values,my=function(e,t){if(e){if(e[hy]!==py)try{dy(e,hy,py)}catch(IW){e[hy]=py}if(uy(e,t,!0),ay[t])for(var i in ly)if(e[i]!==ly[i])try{dy(e,i,ly[i])}catch(IW){e[i]=ly[i]}}};for(var _y in ay)my(oy[_y]&&oy[_y].prototype,_y);my(cy,"DOMTokenList");var fy=Df.charAt,gy=mn,Ey=Ni,Ty=bo,vy=ko,yy="String Iterator",Sy=Ey.set,Iy=Ey.getterFor(yy);Ty(String,"String",(function(e){Sy(this,{type:yy,string:gy(e),index:0})}),(function(){var e,t=Iy(this),i=t.string,r=t.index;return r>=i.length?vy(void 0,!0):(e=fy(i,r),t.index+=e.length,vy(e,!1))}));var Ry=s,Ay=o,Cy=it("iterator"),by=!Ry((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&&!Ay||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[Cy]||"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})),ky=o,Dy=S,Ny=d,wy=s,Oy=Bn,Py=kr,My=u,Ly=Fe,xy=w,Vy=Object.assign,Uy=Object.defineProperty,Fy=Dy([].concat),By=!Vy||wy((function(){if(ky&&1!==Vy({b:1},Vy(Uy({},"a",{enumerable:!0,get:function(){Uy(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!==Vy({},e)[i]||Oy(Vy({},t)).join("")!==r}))?function(e,t){for(var i=Ly(e),r=arguments.length,n=1,s=Py.f,o=My.f;r>n;)for(var a,c=xy(arguments[n++]),l=s?Fy(Oy(c),s(c)):Oy(c),d=l.length,u=0;d>u;)a=l[u++],ky&&!Ny(o,c,a)||(i[a]=c[a]);return i}:Vy,Hy=Mt,Gy=gp,Wy=o,jy=Dt,Jy=g,Ky=Dd,qy=d,zy=Fe,Yy=function(e,t,i,r){try{return r?t(Hy(i)[0],i[1]):t(i)}catch(IW){Gy(e,"throw",IW)}},Xy=ep,Qy=zl,Zy=pr,$y=function(e,t,i){Wy?jy.f(e,t,Jy(0,i)):e[t]=i},eS=pp,tS=op,iS=Array,rS=S,nS=2147483647,sS=/[^\0-\u007E]/,oS=/[.\u3002\uFF0E\uFF61]/g,aS="Overflow: input needs wider integers to process",cS=RangeError,lS=rS(oS.exec),dS=Math.floor,uS=String.fromCharCode,hS=rS("".charCodeAt),pS=rS([].join),mS=rS([].push),_S=rS("".replace),fS=rS("".split),gS=rS("".toLowerCase),ES=function(e){return e+22+75*(e<26)},TS=function(e,t,i){var r=0;for(e=i?dS(e/700):e>>1,e+=dS(e/t);e>455;)e=dS(e/35),r+=36;return dS(r+36*e/(e+38))},vS=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=hS(e,i++);if(n>=55296&&n<=56319&&i<r){var s=hS(e,i++);56320==(64512&s)?mS(t,((1023&n)<<10)+(1023&s)+65536):(mS(t,n),i--)}else mS(t,n)}return t}(e);var i,r,n=e.length,s=128,o=0,a=72;for(i=0;i<e.length;i++)(r=e[i])<128&&mS(t,uS(r));var c=t.length,l=c;for(c&&mS(t,"-");l<n;){var d=nS;for(i=0;i<e.length;i++)(r=e[i])>=s&&r<d&&(d=r);var u=l+1;if(d-s>dS((nS-o)/u))throw new cS(aS);for(o+=(d-s)*u,s=d,i=0;i<e.length;i++){if((r=e[i])<s&&++o>nS)throw new cS(aS);if(r===s){for(var h=o,p=36;;){var m=p<=a?1:p>=a+26?26:p-a;if(h<m)break;var _=h-m,f=36-m;mS(t,uS(ES(m+_%f))),h=dS(_/f),p+=36}mS(t,uS(ES(h))),a=TS(o,u,l===c),o=0,l++}}o++,s++}return pS(t,"")},yS=rn,SS=S,IS=cr,RS=RangeError,AS=String.fromCharCode,CS=String.fromCodePoint,bS=SS([].join);yS({target:"String",stat:!0,arity:1,forced:!!CS&&1!==CS.length},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,n=0;r>n;){if(t=+arguments[n++],IS(t,1114111)!==t)throw new RS(t+" is not a valid code point");i[n]=t<65536?AS(t):AS(55296+((t-=65536)>>10),t%1024+56320)}return bS(i,"")}});var kS=rn,DS=r,NS=lu,wS=J,OS=d,PS=S,MS=o,LS=by,xS=Zi,VS=gn,US=qa,FS=Gs,BS=Ys,HS=Ni,GS=Xa,WS=B,jS=Ge,JS=Dd,KS=un,qS=Mt,zS=G,YS=mn,XS=cs,QS=g,ZS=pp,$S=op,eI=ko,tI=wd,iI=Ea,rI=it("iterator"),nI="URLSearchParams",sI=nI+"Iterator",oI=HS.set,aI=HS.getterFor(nI),cI=HS.getterFor(sI),lI=NS("fetch"),dI=NS("Request"),uI=NS("Headers"),hI=dI&&dI.prototype,pI=uI&&uI.prototype,mI=DS.TypeError,_I=DS.encodeURIComponent,fI=String.fromCharCode,gI=wS("String","fromCodePoint"),EI=parseInt,TI=PS("".charAt),vI=PS([].join),yI=PS([].push),SI=PS("".replace),II=PS([].shift),RI=PS([].splice),AI=PS("".split),CI=PS("".slice),bI=PS(/./.exec),kI=/\+/g,DI=/^[0-9a-f]+$/i,NI=function(e,t){var i=CI(e,t,t+2);return bI(DI,i)?EI(i,16):NaN},wI=function(e){for(var t=0,i=128;i>0&&e&i;i>>=1)t++;return t},OI=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},PI=function(e){for(var t=(e=SI(e,kI," ")).length,i="",r=0;r<t;){var n=TI(e,r);if("%"===n){if("%"===TI(e,r+1)||r+3>t){i+="%",r++;continue}var s=NI(e,r+1);if(s!=s){i+=n,r++;continue}r+=2;var o=wI(s);if(0===o)n=fI(s);else{if(1===o||o>4){i+="�",r++;continue}for(var a=[s],c=1;c<o&&!(++r+3>t||"%"!==TI(e,r));){var l=NI(e,r+1);if(l!=l){r+=3;break}if(l>191||l<128)break;yI(a,l),r+=2,c++}if(a.length!==o){i+="�";continue}var d=OI(a);null===d?i+="�":n=gI(d)}}i+=n,r++}return i},MI=/[!'()~]|%20/g,LI={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},xI=function(e){return LI[e]},VI=function(e){return SI(_I(e),MI,xI)},UI=BS((function(e,t){oI(this,{type:sI,target:aI(e).entries,index:0,kind:t})}),nI,(function(){var e=cI(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,eI(void 0,!0);var r=t[i];switch(e.kind){case"keys":return eI(r.key,!1);case"values":return eI(r.value,!1)}return eI([r.key,r.value],!1)}),!0),FI=function(e){this.entries=[],this.url=null,void 0!==e&&(zS(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===TI(e,0)?CI(e,1):e:YS(e)))};FI.prototype={type:nI,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,s,o,a,c=this.entries,l=$S(e);if(l)for(i=(t=ZS(e,l)).next;!(r=OS(i,t)).done;){if(s=(n=ZS(qS(r.value))).next,(o=OS(s,n)).done||(a=OS(s,n)).done||!OS(s,n).done)throw new mI("Expected sequence with length 2");yI(c,{key:YS(o.value),value:YS(a.value)})}else for(var d in e)jS(e,d)&&yI(c,{key:d,value:YS(e[d])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,n=AI(e,"&"),s=0;s<n.length;)(t=n[s++]).length&&(i=AI(t,"="),yI(r,{key:PI(II(i)),value:PI(vI(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],yI(i,VI(e.key)+"="+VI(e.value));return vI(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var BI=function(){GS(this,HI);var e=oI(this,new FI(arguments.length>0?arguments[0]:void 0));MS||(this.size=e.entries.length)},HI=BI.prototype;if(US(HI,{append:function(e,t){var i=aI(this);tI(arguments.length,2),yI(i.entries,{key:YS(e),value:YS(t)}),MS||this.length++,i.updateURL()},delete:function(e){for(var t=aI(this),i=tI(arguments.length,1),r=t.entries,n=YS(e),s=i<2?void 0:arguments[1],o=void 0===s?s:YS(s),a=0;a<r.length;){var c=r[a];if(c.key!==n||void 0!==o&&c.value!==o)a++;else if(RI(r,a,1),void 0!==o)break}MS||(this.size=r.length),t.updateURL()},get:function(e){var t=aI(this).entries;tI(arguments.length,1);for(var i=YS(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=aI(this).entries;tI(arguments.length,1);for(var i=YS(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=aI(this).entries,i=tI(arguments.length,1),r=YS(e),n=i<2?void 0:arguments[1],s=void 0===n?n:YS(n),o=0;o<t.length;){var a=t[o++];if(a.key===r&&(void 0===s||a.value===s))return!0}return!1},set:function(e,t){var i=aI(this);tI(arguments.length,1);for(var r,n=i.entries,s=!1,o=YS(e),a=YS(t),c=0;c<n.length;c++)(r=n[c]).key===o&&(s?RI(n,c--,1):(s=!0,r.value=a));s||yI(n,{key:o,value:a}),MS||(this.size=n.length),i.updateURL()},sort:function(){var e=aI(this);iI(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=aI(this).entries,r=JS(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 UI(this,"keys")},values:function(){return new UI(this,"values")},entries:function(){return new UI(this,"entries")}},{enumerable:!0}),xS(HI,rI,HI.entries,{name:"entries"}),xS(HI,"toString",(function(){return aI(this).serialize()}),{enumerable:!0}),MS&&VS(HI,"size",{get:function(){return aI(this).entries.length},configurable:!0,enumerable:!0}),FS(BI,nI),kS({global:!0,constructor:!0,forced:!LS},{URLSearchParams:BI}),!LS&&WS(uI)){var GI=PS(pI.has),WI=PS(pI.set),jI=function(e){if(zS(e)){var t,i=e.body;if(KS(i)===nI)return t=e.headers?new uI(e.headers):new uI,GI(t,"content-type")||WI(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),XS(e,{body:QS(0,YS(i)),headers:QS(0,t)})}return e};if(WS(lI)&&kS({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return lI(e,arguments.length>1?jI(arguments[1]):{})}}),WS(dI)){var JI=function(e){return GS(this,hI),new dI(e,arguments.length>1?jI(arguments[1]):{})};hI.constructor=JI,JI.prototype=hI,kS({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:JI})}}var KI,qI=rn,zI=o,YI=by,XI=r,QI=Dd,ZI=S,$I=Zi,eR=gn,tR=Xa,iR=Ge,rR=By,nR=function(e){var t=zy(e),i=Qy(this),r=arguments.length,n=r>1?arguments[1]:void 0,s=void 0!==n;s&&(n=Ky(n,r>2?arguments[2]:void 0));var o,a,c,l,d,u,h=tS(t),p=0;if(!h||this===iS&&Xy(h))for(o=Zy(t),a=i?new this(o):iS(o);o>p;p++)u=s?n(t[p],p):t[p],$y(a,p,u);else for(a=i?new this:[],d=(l=eS(t,h)).next;!(c=qy(d,l)).done;p++)u=s?Yy(l,n,[c.value,p],!0):c.value,$y(a,p,u);return a.length=p,a},sR=ma,oR=Df.codeAt,aR=function(e){var t,i,r=[],n=fS(_S(gS(e),oS,"."),".");for(t=0;t<n.length;t++)i=n[t],mS(r,lS(sS,i)?"xn--"+vS(i):i);return pS(r,".")},cR=mn,lR=Gs,dR=wd,uR={URLSearchParams:BI,getState:aI},hR=Ni,pR=hR.set,mR=hR.getterFor("URL"),_R=uR.URLSearchParams,fR=uR.getState,gR=XI.URL,ER=XI.TypeError,TR=XI.parseInt,vR=Math.floor,yR=Math.pow,SR=ZI("".charAt),IR=ZI(/./.exec),RR=ZI([].join),AR=ZI(1..toString),CR=ZI([].pop),bR=ZI([].push),kR=ZI("".replace),DR=ZI([].shift),NR=ZI("".split),wR=ZI("".slice),OR=ZI("".toLowerCase),PR=ZI([].unshift),MR="Invalid scheme",LR="Invalid host",xR="Invalid port",VR=/[a-z]/i,UR=/[\d+-.a-z]/i,FR=/\d/,BR=/^0x/i,HR=/^[0-7]+$/,GR=/^\d+$/,WR=/^[\da-f]+$/i,jR=/[\0\t\n\r #%/:<>?@[\\\]^|]/,JR=/[\0\t\n\r #/:<>?@[\\\]^|]/,KR=/^[\u0000-\u0020]+/,qR=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,zR=/[\t\n\r]/g,YR=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)PR(t,e%256),e=vR(e/256);return RR(t,".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,i=1,r=null,n=0,s=0;s<8;s++)0!==e[s]?(n>i&&(t=r,i=n),r=null,n=0):(null===r&&(r=s),++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+=AR(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},XR={},QR=rR({},XR,{" ":1,'"':1,"<":1,">":1,"`":1}),ZR=rR({},QR,{"#":1,"?":1,"{":1,"}":1}),$R=rR({},ZR,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),eA=function(e,t){var i=oR(e,0);return i>32&&i<127&&!iR(t,e)?e:encodeURIComponent(e)},tA={ftp:21,file:null,http:80,https:443,ws:80,wss:443},iA=function(e,t){var i;return 2===e.length&&IR(VR,SR(e,0))&&(":"===(i=SR(e,1))||!t&&"|"===i)},rA=function(e){var t;return e.length>1&&iA(wR(e,0,2))&&(2===e.length||"/"===(t=SR(e,2))||"\\"===t||"?"===t||"#"===t)},nA=function(e){return"."===e||"%2e"===OR(e)},sA={},oA={},aA={},cA={},lA={},dA={},uA={},hA={},pA={},mA={},_A={},fA={},gA={},EA={},TA={},vA={},yA={},SA={},IA={},RA={},AA={},CA=function(e,t,i){var r,n,s,o=cR(e);if(t){if(n=this.parse(o))throw new ER(n);this.searchParams=null}else{if(void 0!==i&&(r=new CA(i,!0)),n=this.parse(o,null,r))throw new ER(n);(s=fR(new _R)).bindURL(this),this.searchParams=s}};CA.prototype={type:"URL",parse:function(e,t,i){var r,n,s,o,a,c=this,l=t||sA,d=0,u="",h=!1,p=!1,m=!1;for(e=cR(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=kR(e,KR,""),e=kR(e,qR,"$1")),e=kR(e,zR,""),r=nR(e);d<=r.length;){switch(n=r[d],l){case sA:if(!n||!IR(VR,n)){if(t)return MR;l=aA;continue}u+=OR(n),l=oA;break;case oA:if(n&&(IR(UR,n)||"+"===n||"-"===n||"."===n))u+=OR(n);else{if(":"!==n){if(t)return MR;u="",l=aA,d=0;continue}if(t&&(c.isSpecial()!==iR(tA,u)||"file"===u&&(c.includesCredentials()||null!==c.port)||"file"===c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&tA[c.scheme]===c.port&&(c.port=null));u="","file"===c.scheme?l=EA:c.isSpecial()&&i&&i.scheme===c.scheme?l=cA:c.isSpecial()?l=hA:"/"===r[d+1]?(l=lA,d++):(c.cannotBeABaseURL=!0,bR(c.path,""),l=IA)}break;case aA:if(!i||i.cannotBeABaseURL&&"#"!==n)return MR;if(i.cannotBeABaseURL&&"#"===n){c.scheme=i.scheme,c.path=sR(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=AA;break}l="file"===i.scheme?EA:dA;continue;case cA:if("/"!==n||"/"!==r[d+1]){l=dA;continue}l=pA,d++;break;case lA:if("/"===n){l=mA;break}l=SA;continue;case dA:if(c.scheme=i.scheme,n===KI)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=sR(i.path),c.query=i.query;else if("/"===n||"\\"===n&&c.isSpecial())l=uA;else if("?"===n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=sR(i.path),c.query="",l=RA;else{if("#"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=sR(i.path),c.path.length--,l=SA;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=sR(i.path),c.query=i.query,c.fragment="",l=AA}break;case uA:if(!c.isSpecial()||"/"!==n&&"\\"!==n){if("/"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=SA;continue}l=mA}else l=pA;break;case hA:if(l=pA,"/"!==n||"/"!==SR(u,d+1))continue;d++;break;case pA:if("/"!==n&&"\\"!==n){l=mA;continue}break;case mA:if("@"===n){h&&(u="%40"+u),h=!0,s=nR(u);for(var _=0;_<s.length;_++){var f=s[_];if(":"!==f||m){var g=eA(f,$R);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n===KI||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(h&&""===u)return"Invalid authority";d-=nR(u).length+1,u="",l=_A}else u+=n;break;case _A:case fA:if(t&&"file"===c.scheme){l=vA;continue}if(":"!==n||p){if(n===KI||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(c.isSpecial()&&""===u)return LR;if(t&&""===u&&(c.includesCredentials()||null!==c.port))return;if(o=c.parseHost(u))return o;if(u="",l=yA,t)return;continue}"["===n?p=!0:"]"===n&&(p=!1),u+=n}else{if(""===u)return LR;if(o=c.parseHost(u))return o;if(u="",l=gA,t===fA)return}break;case gA:if(!IR(FR,n)){if(n===KI||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()||t){if(""!==u){var E=TR(u,10);if(E>65535)return xR;c.port=c.isSpecial()&&E===tA[c.scheme]?null:E,u=""}if(t)return;l=yA;continue}return xR}u+=n;break;case EA:if(c.scheme="file","/"===n||"\\"===n)l=TA;else{if(!i||"file"!==i.scheme){l=SA;continue}switch(n){case KI:c.host=i.host,c.path=sR(i.path),c.query=i.query;break;case"?":c.host=i.host,c.path=sR(i.path),c.query="",l=RA;break;case"#":c.host=i.host,c.path=sR(i.path),c.query=i.query,c.fragment="",l=AA;break;default:rA(RR(sR(r,d),""))||(c.host=i.host,c.path=sR(i.path),c.shortenPath()),l=SA;continue}}break;case TA:if("/"===n||"\\"===n){l=vA;break}i&&"file"===i.scheme&&!rA(RR(sR(r,d),""))&&(iA(i.path[0],!0)?bR(c.path,i.path[0]):c.host=i.host),l=SA;continue;case vA:if(n===KI||"/"===n||"\\"===n||"?"===n||"#"===n){if(!t&&iA(u))l=SA;else if(""===u){if(c.host="",t)return;l=yA}else{if(o=c.parseHost(u))return o;if("localhost"===c.host&&(c.host=""),t)return;u="",l=yA}continue}u+=n;break;case yA:if(c.isSpecial()){if(l=SA,"/"!==n&&"\\"!==n)continue}else if(t||"?"!==n)if(t||"#"!==n){if(n!==KI&&(l=SA,"/"!==n))continue}else c.fragment="",l=AA;else c.query="",l=RA;break;case SA:if(n===KI||"/"===n||"\\"===n&&c.isSpecial()||!t&&("?"===n||"#"===n)){if(".."===(a=OR(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"===n||"\\"===n&&c.isSpecial()||bR(c.path,"")):nA(u)?"/"===n||"\\"===n&&c.isSpecial()||bR(c.path,""):("file"===c.scheme&&!c.path.length&&iA(u)&&(c.host&&(c.host=""),u=SR(u,0)+":"),bR(c.path,u)),u="","file"===c.scheme&&(n===KI||"?"===n||"#"===n))for(;c.path.length>1&&""===c.path[0];)DR(c.path);"?"===n?(c.query="",l=RA):"#"===n&&(c.fragment="",l=AA)}else u+=eA(n,ZR);break;case IA:"?"===n?(c.query="",l=RA):"#"===n?(c.fragment="",l=AA):n!==KI&&(c.path[0]+=eA(n,XR));break;case RA:t||"#"!==n?n!==KI&&("'"===n&&c.isSpecial()?c.query+="%27":c.query+="#"===n?"%23":eA(n,XR)):(c.fragment="",l=AA);break;case AA:n!==KI&&(c.fragment+=eA(n,QR))}d++}},parseHost:function(e){var t,i,r;if("["===SR(e,0)){if("]"!==SR(e,e.length-1))return LR;if(t=function(e){var t,i,r,n,s,o,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return SR(e,u)};if(":"===h()){if(":"!==SR(e,1))return;u+=2,d=++l}for(;h();){if(8===l)return;if(":"!==h()){for(t=i=0;i<4&&IR(WR,h());)t=16*t+TR(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(!IR(FR,h()))return;for(;IR(FR,h());){if(s=TR(h(),10),null===n)n=s;else{if(0===n)return;n=10*n+s}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(o=l-d,l=7;0!==l&&o>0;)a=c[l],c[l--]=c[d+o-1],c[d+--o]=a;else if(8!==l)return;return c}(wR(e,1,-1)),!t)return LR;this.host=t}else if(this.isSpecial()){if(e=aR(e),IR(jR,e))return LR;if(t=function(e){var t,i,r,n,s,o,a,c=NR(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(s=10,n.length>1&&"0"===SR(n,0)&&(s=IR(BR,n)?16:8,n=wR(n,8===s?1:2)),""===n)o=0;else{if(!IR(10===s?GR:8===s?HR:WR,n))return e;o=TR(n,s)}bR(i,o)}for(r=0;r<t;r++)if(o=i[r],r===t-1){if(o>=yR(256,5-t))return null}else if(o>255)return null;for(a=CR(i),r=0;r<i.length;r++)a+=i[r]*yR(256,3-r);return a}(e),null===t)return LR;this.host=t}else{if(IR(JR,e))return LR;for(t="",i=nR(e),r=0;r<i.length;r++)t+=eA(i[r],XR);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return iR(tA,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&iA(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,r=e.password,n=e.host,s=e.port,o=e.path,a=e.query,c=e.fragment,l=t+":";return null!==n?(l+="//",e.includesCredentials()&&(l+=i+(r?":"+r:"")+"@"),l+=YR(n),null!==s&&(l+=":"+s)):"file"===t&&(l+="//"),l+=e.cannotBeABaseURL?o[0]:o.length?"/"+RR(o,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw new ER(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new bA(e.path[0]).origin}catch(IW){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+YR(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(cR(e)+":",sA)},getUsername:function(){return this.username},setUsername:function(e){var t=nR(cR(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=eA(t[i],$R)}},getPassword:function(){return this.password},setPassword:function(e){var t=nR(cR(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=eA(t[i],$R)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?YR(e):YR(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,_A)},getHostname:function(){var e=this.host;return null===e?"":YR(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,fA)},getPort:function(){var e=this.port;return null===e?"":cR(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=cR(e))?this.port=null:this.parse(e,gA))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+RR(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,yA))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=cR(e))?this.query=null:("?"===SR(e,0)&&(e=wR(e,1)),this.query="",this.parse(e,RA)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=cR(e))?("#"===SR(e,0)&&(e=wR(e,1)),this.fragment="",this.parse(e,AA)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var bA=function(e){var t=tR(this,kA),i=dR(arguments.length,1)>1?arguments[1]:void 0,r=pR(t,new CA(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())},kA=bA.prototype,DA=function(e,t){return{get:function(){return mR(this)[e]()},set:t&&function(e){return mR(this)[t](e)},configurable:!0,enumerable:!0}};if(zI&&(eR(kA,"href",DA("serialize","setHref")),eR(kA,"origin",DA("getOrigin")),eR(kA,"protocol",DA("getProtocol","setProtocol")),eR(kA,"username",DA("getUsername","setUsername")),eR(kA,"password",DA("getPassword","setPassword")),eR(kA,"host",DA("getHost","setHost")),eR(kA,"hostname",DA("getHostname","setHostname")),eR(kA,"port",DA("getPort","setPort")),eR(kA,"pathname",DA("getPathname","setPathname")),eR(kA,"search",DA("getSearch","setSearch")),eR(kA,"searchParams",DA("getSearchParams")),eR(kA,"hash",DA("getHash","setHash"))),$I(kA,"toJSON",(function(){return mR(this).serialize()}),{enumerable:!0}),$I(kA,"toString",(function(){return mR(this).serialize()}),{enumerable:!0}),gR){var NA=gR.createObjectURL,wA=gR.revokeObjectURL;NA&&$I(bA,"createObjectURL",QI(NA,gR)),wA&&$I(bA,"revokeObjectURL",QI(wA,gR))}lR(bA,"URL"),qI({global:!0,constructor:!0,forced:!YI,sham:!zI},{URL:bA});var OA=d;rn({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return OA(URL.prototype.toString,this)}});let PA=!0,MA=!0;function LA(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function xA(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 s=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,s),n.apply(this,[e,s])};const s=r.removeEventListener;r.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.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,s.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 VA(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(PA=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function UA(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(MA=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function FA(){if("object"==typeof window){if(PA)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function BA(e,t){MA&&console.warn(e+" is deprecated, please use "+t+" instead.")}function HA(e){return"[object Object]"===Object.prototype.toString.call(e)}function GA(e){return HA(e)?Object.keys(e).reduce((function(t,i){const r=HA(e[i]),n=r?GA(e[i]):e[i],s=r&&!Object.keys(n).length;return void 0===n||s?t:Object.assign(t,{[i]:n})}),{}):e}function WA(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?WA(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{WA(e,e.get(t),i)}))})))}function jA(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===r&&i.trackId===t.id&&WA(e,i,n)}))})),n}const JA=FA;function KA(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 s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=r(e.video),JA("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return JA("chrome: "+JSON.stringify(e)),n(e)},s=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(s(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(s(e))))))}}}function qA(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function zA(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 xA(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function YA(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 XA(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},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const r=function(e){i(s(n(e)))};return t.apply(this,[r,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(n(t)))},i])})).then(i,r)}}function QA(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=>jA(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}),xA(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>jA(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 ZA(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 $A(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ZA(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 s(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=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=r[t]}));const o=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]),o.apply(this,arguments)):o.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:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function eC(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],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 tC(e,t){xA(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var iC=Object.freeze({__proto__:null,shimMediaStream:qA,shimOnTrack:zA,shimGetSendersWithDtmf:YA,shimGetStats:XA,shimSenderReceiverGetStats:QA,shimAddTrackRemoveTrackWithNative:ZA,shimAddTrackRemoveTrack:$A,shimPeerConnection:eC,fixNegotiationNeeded:tC,shimGetUserMedia:KA,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,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||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 rC(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){BA("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 nC(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function sC(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],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,s]=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(Db){if("TypeError"!==Db.name)throw Db;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,s)}}function oC(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function aC(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),xA(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function cC(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){BA("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function lC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function dC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const 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 uC(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function hC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function pC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var mC=Object.freeze({__proto__:null,shimOnTrack:nC,shimPeerConnection:sC,shimSenderGetStats:oC,shimReceiverGetStats:aC,shimRemoveStream:cC,shimRTCDataChannel:lC,shimAddTransceiver:dC,shimGetParameters:uC,shimCreateOffer:hC,shimCreateAnswer:pC,shimGetUserMedia:rC,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function _C(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function fC(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function gC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=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=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.setRemoteDescription=a,a=function(e,t,i){const r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.addIceCandidate=a}function EC(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(TC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function TC(e){return e&&void 0!==e.video?Object.assign({},e,{video:GA(e.video)}):e}function vC(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?(BA("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 yC(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function SC(e){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 IC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var RC=Object.freeze({__proto__:null,shimLocalStreamsAPI:_C,shimRemoteStreamsAPI:fC,shimCallbacksAPI:gC,shimGetUserMedia:EC,shimConstraints:TC,shimRTCIceServerUrls:vC,shimTrackEventTransceiver:yC,shimCreateOfferLegacy:SC,shimAudioContext:IC}),AC={},CC={get exports(){return AC},set exports(e){AC=e}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let r=8;r<t.length;r+=2)switch(t[r]){case"raddr":i.relatedAddress=t[r+1];break;case"rport":i.relatedPort=parseInt(t[r+1],10);break;case"tcptype":i.tcpType=t[r+1];break;case"ufrag":i.ufrag=t[r+1],i.usernameFragment=t[r+1];break;default:void 0===i[t[r]]&&(i[t[r]]=t[r+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const r=e.substring(e.indexOf(" ")+1).split(";");for(let n=0;n<r.length;n++)i=r[n].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const r=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+i+" "+r.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substring(t+1,r),i.value=e.substring(r+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const r=t.matchPrefix(e+i,"a=ice-ufrag:")[0],n=t.matchPrefix(e+i,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substring(12),password:n.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(" ");i.profile=r[2];for(let s=3;s<r.length;s++){const n=r[s],o=t.matchPrefix(e,"a=rtpmap:"+n+" ")[0];if(o){const r=t.parseRtpMap(o),s=t.matchPrefix(e,"a=fmtp:"+n+" ");switch(r.parameters=s.length?t.parseFmtp(s[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"),s=-1!==r.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[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:s?"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 s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.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 s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:n};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[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 s=void 0!==i?i:2;n=e||t.generateSessionId();return"v=0\r\no="+(r||"thisisadapterortc")+" "+n+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const r=t.splitLines(e);for(let t=0;t<r.length;t++)switch(r[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(CC);var bC=AC,kC=e({__proto__:null,default:bC},[AC]);function DC(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),r=bC.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,xA(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function NC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||xA(e,"icecandidate",(e=>{if(e.candidate){const t=bC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function wC(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=bC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=bC.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),r=function(e,i){let r=65536;"firefox"===t.browser&&57===t.version&&(r=65535);const n=bC.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 s={};Object.defineProperty(s,"maxMessageSize",{get:()=>n}),this._sctp=s}return i.apply(this,arguments)}}function OC(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},xA(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function PC(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function MC(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function LC(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function xC(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var VC=Object.freeze({__proto__:null,shimRTCIceCandidate:DC,shimRTCIceCandidateRelayProtocol:NC,shimMaxMessageSize:wC,shimSendThrowTypeError:OC,shimConnectionState:PC,removeExtmapAllowMixed:MC,shimAddIceCandidateNullOrEmpty:LC,shimParameterlessSetLocalDescription:xC});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=FA,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=LA(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=LA(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=LA(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:VC,extractVersion:LA,disableLog:VA,disableWarnings:UA,sdp:kC};switch(r.browser){case"chrome":if(!iC||!eC||!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=iC,LC(e,r),xC(e),KA(e,r),qA(e),eC(e,r),zA(e),$A(e,r),YA(e),XA(e),QA(e),tC(e,r),DC(e),NC(e),PC(e),wC(e,r),OC(e),MC(e,r);break;case"firefox":if(!mC||!sC||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=mC,LC(e,r),xC(e),rC(e,r),sC(e,r),nC(e),cC(e),oC(e),aC(e),lC(e),dC(e),uC(e),hC(e),pC(e),DC(e),PC(e),wC(e,r),OC(e);break;case"safari":if(!RC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=RC,LC(e,r),xC(e),vC(e),SC(e),gC(e),_C(e),fC(e),yC(e),EC(e),IC(e),DC(e),NC(e),wC(e,r),OC(e),MC(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var UC,FC=Object.create,BC=Object.defineProperty,HC=Object.defineProperties,GC=Object.getOwnPropertyDescriptor,WC=Object.getOwnPropertyDescriptors,jC=Object.getOwnPropertyNames,JC=Object.getOwnPropertySymbols,KC=Object.getPrototypeOf,qC=Object.prototype.hasOwnProperty,zC=Object.prototype.propertyIsEnumerable,YC=Reflect.get,XC=Math.pow,QC=(e,t,i)=>t in e?BC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,ZC=(e,t)=>{for(var i in t||(t={}))qC.call(t,i)&&QC(e,i,t[i]);if(JC)for(var i of JC(t))zC.call(t,i)&&QC(e,i,t[i]);return e},$C=(e,t)=>HC(e,WC(t)),eb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tb=(e,t)=>{for(var i in t)BC(e,i,{get:t[i],enumerable:!0})},ib=(e,t,i)=>(i=null!=e?FC(KC(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of jC(t))!qC.call(e,n)&&n!==i&&BC(e,n,{get:()=>t[n],enumerable:!(r=GC(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:BC(i,"default",{value:e,enumerable:!0}),e)),rb=(e,t,i,r)=>{for(var n,s=r>1?void 0:r?GC(t,i):t,o=e.length-1;o>=0;o--)(n=e[o])&&(s=(r?n(t,i,s):n(s))||s);return r&&s&&BC(t,i,s),s},nb=(e,t,i)=>QC(e,"symbol"!=typeof t?t+"":t,i),sb=(e,t,i)=>YC(KC(e),i,t),ob=(e,t,i)=>new Promise(((r,n)=>{var s=e=>{try{a(i.next(e))}catch(uO){n(uO)}},o=e=>{try{a(i.throw(e))}catch(uO){n(uO)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(s,o);a((i=i.apply(e,t)).next())})),ab=eb(((e,t)=>{var i=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function o(e,t,i,n,o){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new s(i,n||e,o),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,s=i.length,o=new Array(s);n<s;n++)o[n]=i[n].fn;return o},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,s,o){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,s),!0;case 6:return d.fn.call(d.context,t,i,n,s,o),!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 o(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return o(this,e,t,i,!0)},c.prototype.removeListener=function(e,t,i,n){var s=r?r+e:e;if(!this._events[s])return this;if(!t)return a(this,s),this;var o=this._events[s];if(o.fn)o.fn===t&&(!n||o.once)&&(!i||o.context===i)&&a(this,s);else{for(var c=0,l=[],d=o.length;c<d;c++)(o[c].fn!==t||n&&!o[c].once||i&&o[c].context!==i)&&l.push(o[c]);l.length?this._events[s]=1===l.length?l[0]:l:a(this,s)}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)})),cb=eb(((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),lb=eb((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 s=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var s=0;s<r.length;s+=1)null!=e[s+1]&&(i[r[s]]=t(e[s+1]))})(r.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},r=cb(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.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,o,n)}})),t.media=s,t};var s=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(s,{})},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(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),db=eb(((e,t)=>{var i=cb(),r=/%[sdv%]/g,n=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},s=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 s=0;s<t.names.length;s+=1){var o=t.names[s];t.name?r.push(i[t.name][o]):r.push(i[t.names[s]])}else r.push(i[t.name]);return n.apply(null,r)},o=["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||o,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(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(s(t,i,e))}))}))})),e.media.forEach((function(e){c.push(s("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(s(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),ub=eb((e=>{var t=lb(),i=db();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),hb=eb(((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%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")}))}))})),pb=eb((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 s=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var s=0;s<r.length;s+=1)null!=e[s+1]&&(i[r[s]]=t(e[s+1]))})(r.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},r=hb(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.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,o,n)}})),t.media=s,t};var s=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(s,{})},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(s,{})}))},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}}))}))}})),mb=eb(((e,t)=>{var i=hb(),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""}}))},s=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 s=0;s<t.names.length;s+=1){var o=t.names[s];t.name?r.push(i[t.name][o]):r.push(i[t.names[s]])}else r.push(i[t.name]);return n.apply(null,r)},o=["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||o,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(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(s(t,i,e))}))}))})),e.media.forEach((function(e){c.push(s("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(s(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),_b=eb((e=>{var t=pb(),i=mb();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})),fb=ib(ab()),gb=((UC=gb||{})[UC.INVALID_PARAMETER=4096]="INVALID_PARAMETER",UC[UC.INVALID_OPERATION=4097]="INVALID_OPERATION",UC[UC.NOT_SUPPORTED=4098]="NOT_SUPPORTED",UC[UC.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",UC[UC.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",UC[UC.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",UC[UC.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",UC[UC.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",UC[UC.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",UC[UC.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",UC[UC.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",UC[UC.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",UC[UC.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",UC[UC.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",UC[UC.CLIENT_BANNED=16448]="CLIENT_BANNED",UC[UC.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",UC[UC.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",UC[UC.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",UC[UC.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",UC[UC.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",UC[UC.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",UC[UC.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",UC[UC.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",UC[UC.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",UC[UC.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",UC[UC.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",UC[UC.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",UC[UC.API_CALL_ABORTED=16461]="API_CALL_ABORTED",UC[UC.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",UC[UC.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",UC[UC.UNKNOWN=65535]="UNKNOWN",UC),Eb=gb,Tb=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=Eb.UNKNOWN,extraCode:n=0,constraint:s}=e,o="<".concat(function(e){for(let t in Eb)if(Eb[t]===e)return t;return"UNKNOWN"}(r)," 0x").concat(r.toString(16),">"),a="".concat(i).concat(s?" constraint: ".concat(s):"").concat(null!=i&&i.includes(o)?"":" ".concat(o));super(a),nb(this,"code"),nb(this,"extraCode"),nb(this,"message"),nb(this,"originMessage"),nb(this,"name"),nb(this,"constraint"),this.code=r,this.extraCode=n,this.name=t,this.message=a,this.constraint=s,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},vb=Tb,yb=((new Date).getTime(),0),Sb=function(){return(new Date).getTime()+yb},Ib=function(){let e=new Date;return e.setTime(Sb()),e.toLocaleString()},Rb={};tb(Rb,{bytes2ms:()=>pD,convertObjectNumberToInt:()=>iN,copyProperties:()=>hD,deepClone:()=>KD,deepMerge:()=>JD,delay:()=>rN,fibonacci:()=>vD,formatedTime:()=>YD,getConstructorName:()=>MD,getContainerFromElement:()=>zD,getEnv:()=>nD,getInternalVersion:()=>FD,getLoggerUrl:()=>oD,getMuteStateFromFlag:()=>GD,getNetworkType:()=>cD,getNumNetworkType:()=>uD,getReconnectionTimeout:()=>yD,getStringByteLength:()=>ZD,getTurnServer:()=>WD,getUint32Version:()=>tN,getValueType:()=>SD,getViewListFromView:()=>qD,glog:()=>gD,ipv4ToUint32:()=>jD,isArray:()=>DD,isAudioWorkletSupported:()=>LD,isBoolean:()=>bD,isConstructor:()=>PD,isEmpty:()=>HD,isFunction:()=>ID,isLangChinese:()=>ED,isMediaStreamTrack:()=>ND,isNumber:()=>CD,isObject:()=>kD,isOverseaSdkAppId:()=>sD,isPlainObject:()=>TD,isPortrait:()=>$D,isPromise:()=>OD,isRemoteTrack:()=>wD,isString:()=>AD,isUndefined:()=>RD,loadImage:()=>eN,ms2bytes:()=>_D,ms2samples:()=>fD,performanceNow:()=>VD,promiseAny:()=>xD,samples2ms:()=>mD,setNetworkType:()=>dD,stringify:()=>XD,stringifyIncludeValue:()=>QD,throttlePromise:()=>nN});var Ab={};tb(Ab,{AUDIO_MUTE_BIT:()=>dk,AUDIO_STAT_BIT:()=>lk,AUX_STAT_BIT:()=>ck,AUX_STREAM_MSID:()=>_k,BACKEND_ENV:()=>nk,BASE_DOC_URL:()=>Bb,BASE_HOST:()=>xb,CAPABILITIES_KEYS:()=>iD,CLASS_NAME:()=>qk,CLOUD_CONSOLE_URL:()=>Fb,CROSS_ROOM_BIT:()=>pk,DATA_FREEZE_TIMING:()=>Bk,DEFAULT_ASSETS_URL:()=>Hb,DOC_URL:()=>Gb,DTLS_STATE_UNKNOWN:()=>Ak,ENV_NAME:()=>qb,EXCHANGE_SDP_TIMEOUT:()=>Lk,IS_WORKER:()=>wb,IS_WORKLET:()=>Ob,KIBANA_EVENT:()=>Ok,LOCAL_STREAM_PUBLISH_STATE:()=>Fk,LOGGER_CMD_TYPE:()=>Kb,LOGGER_DOMAIN:()=>Wb,LOGGER_DOMAIN_OVERSEA:()=>jb,LOG_LEVEL:()=>zb,LOG_LEVEL_NAME:()=>Zk,MAIN_STREAM_MSID:()=>mk,MAX_RTT:()=>rD,MICROPHONE_COMMUNICATIONS:()=>Qk,MICROPHONE_DEFAULT:()=>Yk,MUTE_ALL_BIT:()=>hk,NAME:()=>ik,NETWORK_TYPE:()=>Qb,NOT_SUPPORTED_H264:()=>Uk,PAUSED_RETRY_COUNT:()=>zk,PEERCONNECTION_CONNECTING_TIMEOUT:()=>jk,PEER_CONNECTION_STATE:()=>Ck,PEER_LEAVE_REASON:()=>$k,RECOVER_CAPTURE_INTERVAL:()=>tD,REMOTE_STREAM_TYPE_AUX:()=>gk,REMOTE_STREAM_TYPE_MAIN:()=>fk,RENDER_FREEZE_TIMING:()=>Hk,SCHEDULE_DOMAIN:()=>Jk,SCHEDULE_TIMEOUT:()=>Kk,SDP_SEMANTICS_PLAN_B:()=>Vk,SDP_SEMANTICS_UNIFIED_PLAN:()=>xk,SECOND_HOST:()=>Vb,SIGNAL_PING_PONG_INTERVAL:()=>Xb,SIGNAL_PING_TIMEOUT:()=>Yb,SIGNAL_RECONNECTION_COUNT:()=>wk,SMALL_STAT_BIT:()=>ak,SPEAKER_DEFAULT:()=>Xk,STORAGE_EXPIRES_TIME:()=>Zb,STREAM_TYPE_BIG:()=>Gk,STREAM_TYPE_SMALL:()=>Wk,SUBSCRIBE_SMALL_RETRY_COUNT:()=>eD,SYNC_USER_LIST_INTERVAL:()=>Pk,Scene:()=>sk,THIRD_HOST:()=>Ub,TRANSPORT_DIRECTION:()=>rk,TRTC_ERROR_ASSISTANCE:()=>Jb,TRTC_QUALITY_BAD:()=>Sk,TRTC_QUALITY_DISCONNECTED:()=>Rk,TRTC_QUALITY_EXCELLENT:()=>Tk,TRTC_QUALITY_GOOD:()=>vk,TRTC_QUALITY_POOR:()=>yk,TRTC_QUALITY_UNKNOWN:()=>Ek,TRTC_QUALITY_VERY_BAD:()=>Ik,UPDATE_OFFER_TIMEOUT:()=>Mk,VIDEO_MUTE_BIT:()=>uk,VIDEO_STAT_BIT:()=>ok,audioProfileMap:()=>$b,getRetryCount:()=>Dk,getScriptDir:()=>Pb,innerVersion:()=>Cb,loggerProxy:()=>Mb,screenProfileMap:()=>tk,setLoggerProxy:()=>Lb,setRetryCount:()=>kk,setVersion:()=>kb,version:()=>bb,videoProfileMap:()=>ek});var Cb="4.15.00.1600",bb="5.0.0";function kb(e){bb=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));Cb="".concat(t,".").concat(Math.min(15,i),".").concat(Math.min(15,r),".").concat(i.toString().padStart(2,"0")).concat(r.toString().padStart(2,"0"))}var Db,Nb,wb="undefined"!=typeof importScripts,Ob="undefined"!=typeof registerProcessor,Pb=()=>{let e=wb?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Mb="",Lb=e=>Mb=e,xb="web.sdk.qcloud.com",Vb="web.sdk.tencent.cn",Ub="web.sdk.cloud.tencent.cn",Fb="https://console.cloud.tencent.com/trtc",Bb="https://".concat(xb,"/trtc/webrtc/v5/doc"),Hb="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",Gb="".concat(Bb,"/zh-cn/"),Wb="https://yun.tim.qq.com",jb="https://apisgp.my-imcloud.com",Jb="trtc_error_assistance",Kb={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},qb={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},zb=((Nb=zb||{})[Nb.TRACE=0]="TRACE",Nb[Nb.DEBUG=1]="DEBUG",Nb[Nb.INFO=2]="INFO",Nb[Nb.WARN=3]="WARN",Nb[Nb.ERROR=4]="ERROR",Nb[Nb.NONE=5]="NONE",Nb),Yb=18e3,Xb=2e3,Qb={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Zb=6048e5,$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}},ek={"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}},tk={"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}},ik={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",LOADEDMETADATA:"loadedmetadata",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"},rk={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},nk={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},sk=((Db=sk||{}).LIVE="live",Db.RTC="rtc",Db),ok=1,ak=2,ck=4,lk=8,dk=64,uk=16,hk=112,pk=128,mk="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",_k="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",fk=ik.MAIN,gk=ik.AUXILIARY,Ek=0,Tk=1,vk=2,yk=3,Sk=4,Ik=5,Rk=6,Ak="unknown",Ck={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},bk=1/0;function kk(e){bk=e}function Dk(){return bk}var Nk,wk=30,Ok={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"},Pk=1e4,Mk=1e4,Lk=1e4,xk="unified-plan",Vk="plan-b",Uk=1028,Fk=((Nk=Fk||{})[Nk.UNPUBLISH=-1]="UNPUBLISH",Nk[Nk.PUBLISHING=0]="PUBLISHING",Nk[Nk.PUBLISHED=1]="PUBLISHED",Nk),Bk=500,Hk=1e3,Gk=ik.BIG,Wk=ik.SMALL,jk=1e4,Jk={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},Kk=2e3,qk={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},zk=5,Yk="default",Xk=Yk,Qk="communications",Zk=Object.keys(zb),$k=["normal leave","timeout leave","kick","role change"],eD=10,tD=2e3,iD=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],rD=1e4,nD=function(){return new URLSearchParams(location.search).get("trtc_env")||""},sD=e=>Number(e)<14e8,oD=function(e,t){let i;i=Mb||(sD(e)?jb:Wb);let r=Math.floor(Math.random()*XC(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},aD="unknown";function cD(){if("unknown"!==aD)return aD;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&&(aD=lD(r,n)),aD}function lD(e,t){if(Qb[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function dD(e){aD=lD(e)}function uD(){return Qb[cD()]}function hD(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 pD(e){return mD(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function mD(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function _D(e){return 4*fD(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function fD(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var gD="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},ED=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},TD=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 vD(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:vD(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function yD(e){return e>8?3e4:1e3*vD(e)}function SD(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ID=e=>"function"==typeof e,RD=e=>void 0===e,AD=e=>"string"==typeof e,CD=e=>"number"==typeof e,bD=e=>"boolean"==typeof e,kD=e=>"object"===SD(e),DD=e=>"array"===SD(e),ND=e=>SD(e)==="MediaStreamTrack".toLowerCase(),wD=e=>e.isRemote,OD=e=>"promise"===SD(e),PD=e=>ID(e)&&e.prototype.constructor===e,MD=e=>PD(e)?e.prototype.constructor.name:"",LD="undefined"!=typeof AudioWorkletNode;function xD(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 VD(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var UD=e=>+e<10?"0".concat(e):e,FD=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=UD(i[1])+UD(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},BD=Object.prototype.hasOwnProperty;function HD(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(TD(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(BD.call(e,t))return!1;return!0}return!1}function GD(e,t){return{userId:t,hasAudio:!!(e&lk),hasVideo:!!(e&ok),hasAuxiliary:!!(e&ck),hasSmall:!!(e&ak),audioMuted:!!(e&dk),videoMuted:!!(e&uk),audioAvailable:!(!(e&lk)||e&dk),videoAvailable:!(!(e&ok)||e&uk)}}function WD(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!RD(e.username)&&!RD(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",RD(e.credentialType)||(t.credentialType=e.credentialType)),t}function jD(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!AD(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 JD=function(e,t,i,r){if(!kD(e)||!kD(t))return 0;let n,s=0,o=Object.keys(t);for(let a=0,c=o.length;a<c;a++)if(n=o[a],!(RD(t[n])||i&&i.includes(n)))if(kD(e[n])&&kD(t[n]))s+=JD(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=KD(t[n]),s+=1)}return s};function KD(e){if(DD(e)){let t=[];return e.forEach(((e,i)=>{t[i]=KD(e)})),t}if(kD(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=KD(e[i])})),t}return e}var qD=e=>{let t=[];if(DD(e))t=[...e];else if(AD(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},zD=e=>AD(e)?document.getElementById(e):e,YD=()=>(e=>{let t=e=>e<10?"0".concat(e):"".concat(e),i=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),s=t(e.getHours()),o=t(e.getMinutes()),a=t(e.getSeconds());return"".concat(i,"/").concat(r,"/").concat(n," ").concat(s,":").concat(o,":").concat(a)})(new Date);function XD(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(DD(e))return"[".concat(e.map((e=>XD(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!TD(e)||!DD(i)&&!DD(r))return JSON.stringify(e);let t={},n=new Set(i),s=new Set(r);return Object.keys(e).forEach((o=>{(0===s.size&&n.has(o)||0===n.size&&!s.has(o))&&(t[o]=TD(e[o])||DD(e[o])?JSON.parse(XD(e[o],{keysToExclude:r,keysToInclude:i})):e[o])})),JSON.stringify(t)}catch(Nk){return"{}"}}function QD(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)})),XD(e,{keysToInclude:i})}function ZD(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var $D=()=>{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},eN=e=>ob(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(AD(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:Eb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}}))})),tN=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},iN=e=>(Object.keys(e).forEach((t=>{CD(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(TD(e[t])||DD(e[t]))&&iN(e[t])})),e);function rN(e,t){return new Promise((i=>{let r=setTimeout(i,e);t&&t(r)}))}function nN(e,t){let i=null;return function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return i||(i=e.apply(t||this,n),i.finally((()=>i=null)),i)}}function sN(e){let{url:t,body:i,method:r="POST",timeout:n,priority:s}=e;return new Promise(((e,o)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:s}).then((e=>e.text())).then((t=>{try{e({data:JSON.parse(t)})}catch(uO){e({data:t})}}),o);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(4===a.readyState)if(a.status>=200&&a.status<300)try{let t=JSON.parse(a.response);e({data:t})}catch(t){e({data:a.response})}else o({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=n||5e3,a.open(r,t,!0),a.send(i)}))}function oN(e){return ob(this,null,(function*(){let t=VD(),i=JSON.stringify(e);try{if(!CompressionStream||i.length<=2800)return i;let e=new Blob([i],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),r=yield(yield(yield new Response(e)).blob()).arrayBuffer();return sO.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(VD()-t,"ms")),r}catch(Nk){return i}}))}var aN=Object.prototype.hasOwnProperty,cN=e=>"function"==typeof e,lN=e=>void 0===e,dN=e=>e.isRemote;function uN(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(aN.call(e,t))return!1;return!0}return!1}var hN=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:n,onRetryFailed:s,onRetrySuccess:o,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)=>ob(this,null,(function*(){let l=a||this;try{let i=yield t.apply(l,c);h>0&&o&&o.call(this,h),h=0,e(i)}catch(f){let t=()=>{clearTimeout(p),h=0,m=2,i(f)},o=()=>{2!==m&&h<(cN(d)?d():d)?(h++,m=1,cN(n)&&n.call(this,h,t),p=window.setTimeout((()=>{p=-1,_(e,i)}),cN(u)?u(h):u)):(t(),cN(s)&&s.call(this,f))};cN(r)?r.call(this,{error:f,retry:o,reject:i,retryFuncArgs:c,retriedCount:h}):o()}}));return new Promise(_)}},pN=class{constructor(e){nb(this,"userId"),nb(this,"remoteUserId"),nb(this,"id"),nb(this,"sdkAppId"),nb(this,"type"),nb(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal="boolean"!=typeof e.isLocal||e.isLocal,this.type=this.isLocal?"":e.type}createChild(e){return Object.setPrototypeOf(e,this)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId;t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(this.id).concat(i?"|".concat(i):"","]")),sO.log(e,t,lN(this.userId)||uN(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)}},mN={};tb(mN,{ANDROID_VERSION:()=>bN,CHROME_MAJOR_VERSION:()=>Dw,CHROME_VERSION:()=>Nw,EDGE_VERSION:()=>MN,EDG_MAJOR_VERSION:()=>VN,EDG_VERSION:()=>xN,FIREFOX_MAJOR_VERSION:()=>ON,FIREFOX_VERSION:()=>wN,HUAWEI_VERSION:()=>Ew,IE_VERSION:()=>zN,IOS_MAIN_VERSION:()=>xw,IOS_VERSION:()=>Lw,IPADQQB_VERSION:()=>sw,IS_ANDROID:()=>CN,IS_ANDROID_WEBVIEW:()=>Mw,IS_ANY_SAFARI:()=>Ow,IS_CHROME:()=>bw,IS_CHROME_OS:()=>lw,IS_CHROMIUM_BASE:()=>Cw,IS_EDG:()=>LN,IS_EDGE:()=>PN,IS_ELECTRON:()=>hw,IS_FIREFOX:()=>NN,IS_HEADLESS_CHROME:()=>kw,IS_HONOR:()=>gw,IS_HUAWEI:()=>fw,IS_HUAWEIBROWSER:()=>_w,IS_IE:()=>qN,IS_IE8:()=>KN,IS_IOS:()=>AN,IS_IOS_13_OR_14:()=>Fw,IS_IOS_15_1:()=>Uw,IS_IPAD:()=>yN,IS_IPADQQB:()=>nw,IS_IPAD_PRO:()=>SN,IS_IPHONE:()=>IN,IS_IPOD:()=>RN,IS_LINUX:()=>cw,IS_LOCAL:()=>Bw,IS_MAC:()=>aw,IS_MACQQB:()=>iw,IS_MIBROWSER:()=>pw,IS_MQQB:()=>ZN,IS_NATIVE_ANDROID:()=>DN,IS_OLD_ANDROID:()=>kN,IS_OPPOBROWSER:()=>yw,IS_SAFARI:()=>ww,IS_SAFARI_15_1:()=>Vw,IS_SAMSUNGBROWSER:()=>Tw,IS_SOGOU:()=>BN,IS_SOGOUM:()=>UN,IS_TBS:()=>GN,IS_UCBROWSER:()=>uw,IS_VIVOBROWSER:()=>Iw,IS_WECHAT:()=>YN,IS_WIN:()=>ow,IS_WQQB:()=>ew,IS_WX:()=>dw,IS_X5MQQB:()=>QN,IS_XWEB:()=>jN,MACQQB_VERSION:()=>rw,MI_VERSION:()=>mw,MQQB_VERSION:()=>$N,OPPO_VERSION:()=>Sw,SAFARI_VERSION:()=>Pw,SAMSUNG_VERSION:()=>vw,SOGOUM_VERSION:()=>FN,SOGOU_VERSION:()=>HN,TBS_VERSION:()=>WN,UA_DATA_STRING:()=>Jw,USER_AGENT:()=>_N,VIVO_VERSION:()=>Rw,WECHAT_VERSION:()=>XN,WQQB_VERSION:()=>tw,XWEB_VERSION:()=>JN,browserInfo:()=>Gw,getBrowserInfo:()=>Ww,getChromeMajorVersion:()=>Aw,getDeviceModel:()=>qw,getOSName:()=>Yw,getOSNumber:()=>Xw,getOSString:()=>Qw,getOSType:()=>$w,getTerminalType:()=>Zw,getUserAgentData:()=>Kw,isLocalStorageEnabled:()=>Hw});var _N="undefined"==typeof navigator?"":navigator.userAgent,fN=e=>new RegExp(e,"i").test(_N),gN=e=>{if(fN(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=_N.match(t);if(i&&i[1])return i[1]}return""},EN=e=>{if(fN(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=_N.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},TN=/AppleWebKit\/([\d.]+)/i.exec(_N),vN=TN?parseFloat(TN[1]):NaN,yN=fN("iPad"),SN="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&fN("Macintosh"),IN=fN("iPhone")&&!yN,RN=fN("iPod"),AN=IN||yN||RN||SN,CN=fN("Android"),bN=function(){if(CN){let e=_N.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(e){let t=e[1]&&parseFloat(e[1]),i=e[2]&&parseFloat(e[2]);if(t&&i)return parseFloat("".concat(e[1],".").concat(e[2]));if(t)return t}}return NaN}(),kN=CN&&fN("webkit")&&bN<2.3,DN=CN&&bN<5&&vN<537,NN=fN("Firefox"),wN=gN("Firefox"),ON=EN("Firefox"),PN=fN("Edge"),MN=gN("Edge"),LN=fN("Edg"),xN=gN("Edg"),VN=EN("Edg"),UN=fN("SogouMobileBrowser"),FN=gN("SogouMobileBrowser"),BN=fN("MetaSr\\s"),HN=gN("MetaSr\\s"),GN=fN("TBS"),WN=gN("TBS"),jN=fN("XWEB"),JN=gN("XWEB"),KN=fN("MSIE\\s8\\.0"),qN=fN("MSIE\\/\\d+"),zN=function(){if(qN){let e=/MSIE\s(\d+)\.\d/.exec(_N),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(_N)&&/rv:11.0/.test(_N)&&(t=11),t}return NaN}(),YN=fN("(micromessenger|webbrowser)"),XN=gN("MicroMessenger"),QN=!GN&&fN("MQQBrowser")&&fN("COVC"),ZN=!GN&&fN("MQQBrowser")&&!fN("COVC"),$N=ZN||QN?gN("MQQBrowser"):"",ew=!GN&&fN(" QQBrowser"),tw=gN(" QQBrowser"),iw=!GN&&fN("QQBrowserLite"),rw=gN("QQBrowserLite"),nw=!GN&&fN("MQBHD"),sw=gN("MQBHD"),ow=fN("Windows"),aw=!AN&&fN("MAC OS X"),cw=!CN&&fN("Linux"),lw=fN("CrOS"),dw=fN("MicroMessenger"),uw=fN("UCBrowser"),hw=fN("Electron"),pw=fN("MiuiBrowser"),mw=gN("MiuiBrowser"),_w=fN("HuaweiBrowser"),fw=fN("Huawei")||fN("HUAWEI"),gw=fN("Honor")||fN("HONOR"),Ew=gN("HuaweiBrowser"),Tw=fN("SamsungBrowser"),vw=gN("SamsungBrowser"),yw=fN("HeyTapBrowser"),Sw=gN("HeyTapBrowser"),Iw=fN("VivoBrowser"),Rw=gN("VivoBrowser"),Aw=()=>EN("Chrome"),Cw=fN("Chrome"),bw=!PN&&!BN&&!UN&&!GN&&!jN&&!LN&&!ew&&!pw&&!_w&&!Tw&&!yw&&!Iw&&Cw,kw=fN("HeadlessChrome"),Dw=Aw(),Nw=gN("Chrome"),ww=!Cw&&!ZN&&!QN&&!iw&&!nw&&fN("Safari"),Ow=ww||AN,Pw=gN("Version"),Mw=/Android.*(wv|.0.0.0)/.test(_N),Lw=(()=>{if(SN)return Pw;if(AN){let e=_N.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),xw=Number(Lw.split(".")[0]),Vw="15.1"===Pw,Uw="15.1"===Lw,Fw=(()=>{let e=Number(Lw.split(".")[0]);return 14===e||13===e})(),Bw="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),Hw=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(pO){e=!1}return e}})(),Gw=Ww();function Ww(){let e=new Map([[NN,["Firefox",wN]],[LN,["Edg",xN]],[bw,["Chrome",Nw]],[ww,["Safari",Pw]],[GN,["TBS",WN]],[jN,["XWEB",JN]],[YN&&IN,["WeChat",XN]],[ew,["QQ(Win)",tw]],[ZN,["QQ(Mobile)",$N]],[QN,["QQ(Mobile X5)",$N]],[iw,["QQ(Mac)",rw]],[nw,["QQ(iPad)",sw]],[pw,["MI",mw]],[_w,["HW",Ew]],[Tw,["Samsung",vw]],[yw,["OPPO",Sw]],[Iw,["VIVO",Rw]],[PN,["EDGE",MN]],[UN,["SogouMobile",FN]],[BN,["Sogou",HN]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var jw=null,Jw="";function Kw(){return ob(this,null,(function*(){if(jw)return jw;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(jw=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!Jw&&(Jw="UAData: ".concat(jw.platform,"/").concat(jw.platformVersion),jw.architecture&&jw.bitness&&(Jw+=" ".concat(jw.architecture,"/").concat(jw.bitness)),jw.mobile&&(Jw+=" mobile"),jw.model&&(Jw+=" model: ".concat(jw.model)),jw.fullVersionList&&(Jw+=" ".concat(jw.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),jw}catch(fW){return null}}))}function qw(){return(null==jw?void 0:jw.model)||""}var zw=new Map([[CN,"Android"],[AN,"iOS"],[ow,"Windows"],[aw,"MacOS"],[cw,"Linux"],[lw,"ChromeOS"]]),Yw=function(){return zw.get(!0)?zw.get(!0):jw?jw.platform:"unknown"};function Xw(){return ow?1:CN?2:aw?3:AN?4:cw?5:lw?6:0}var Qw=()=>{let e=Yw();return e+="/".concat(Gw.name,"/").concat(ww?Gw.version:Gw.version.split(".")[0]),null!=jw&&jw.platformVersion&&(e+="/".concat(jw.platformVersion)),null!=jw&&jw.architecture&&(e+="/".concat(jw.architecture)),e};function Zw(){return CN?4:IN?2:yN?3:aw?12:ow?5:cw?13:1}function $w(){return CN?"Android":IN?"iPhone":yN?"iPad":aw?"Mac":ow?"Windows":cw?"Linux":"unknown"}var eO,tO=new(ib(ab(),1).default),iO=((eO=iO||{}).ROOM_DESTROY="1",eO.JOIN_START="21",eO.JOIN_SCHEDULE_SUCCESS="22",eO.JOIN_SIGNAL_CONNECTION_START="23",eO.JOIN_SIGNAL_CONNECTION_END="24",eO.JOIN_SEND_CMD="25",eO.JOIN_RECEIVED_CMD_RES="26",eO.JOIN_SUCCESS="27",eO.JOIN_FAILED="28",eO.LEAVE_START="51",eO.LEAVE_SEND_CMD="52",eO.LEAVE_SUCCESS="53",eO.PUBLISH_START="61",eO.SEND_FIRST_VIDEO_FRAME="62",eO.PUBLISH_FAILED="63",eO.SUBSCRIBE_START="81",eO.SUBSCRIBE_SUCCESS="82",eO.SUBSCRIBE_FAILED="84",eO.UNSUBSCRIBE_SUCCESS="83",eO.LOCAL_TRACK_CAPTURE_START="101",eO.LOCAL_TRACK_CAPTURE_SUCCESS="102",eO.LOCAL_TRACK_CAPTURE_FAILED="103",eO.LOCAL_TRACK_PUBLISHED="104",eO.LOCAL_TRACK_UNPUBLISHED="105",eO.LOCAL_TRACK_REPLACED="106",eO.SWITCH_DEVICE_SUCCESS="107",eO.TRACK_MUTED="108",eO.TRACK_UNMUTED="109",eO.REMOTE_TRACK_SUBSCRIBED="110",eO.REMOTE_TRACK_UNSUBSCRIBED="111",eO.LOCAL_TRACK_RECAPTURE="112",eO.PLAY_TRACK_START="151",eO.PLAYER_STATE_CHANGED="152",eO.VIDEO_LOADED_DATA="153",eO.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",eO.SIGNAL_CONNECTION_STATE_CHANGED="201",eO.PEER_CONNECTION_STATE_CHANGED="202",eO.SINGLE_CONNECTION_STAT="203",eO.SPC_RECONNECTED="204",eO.HEARTBEAT_REPORT="251",eO.RECEIVED_PUBLISHED_USER_LIST="252",eO.REMOTE_PUBLISH_STATE_CHANGED="253",eO.AUDIO_LEVEL_INTERVAL="260",eO.NETWORK_QUALITY="261",eO.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",eO.QUALITY_LIMITATION_CHANGED="263",eO.LOG="264",eO),rO=iO,nO=class e{constructor(){nb(this,"_isEnableUploadLog",!0),nb(this,"_localJoinedUser",new Map),nb(this,"_queue",[]),nb(this,"_timeoutId",-1),nb(this,"_logLevel",1),nb(this,"_logLevelToUpload",2),!wb&&!Ob&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){tO.on(rO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.logLevelToUpload&&zb[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),tO.on(rO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),tO.once(rO.JOIN_FAILED,(()=>{this.startUpload()})),tO.on(rO.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()),5e3)}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(AD(i.userId)&&CD(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 ob(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:Ib(),sdkAppId:String(r),userId:i,version:bb,log:n.map((e=>e.log)).join("\n")}),r),n.forEach((e=>e.uploaded=!0))}}catch(mO){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return hN({retryFunction:()=>sN({url:oD(t,Kb.LOG),body:e,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;t.setTime(Sb());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){RD(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(AD(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(Db){return""}}log(t,i){let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;var o;i.unshift(this.getPrefix(t));let a={log:i.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:t,userId:n,sdkAppId:s,forAllJoinedClients:r};if(tO.emit(rO.LOG,{log:a}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(a),t<this._logLevel)return;let c=(null==(o=zb[t])?void 0:o.toLowerCase())||"info";e.PRINT_LOG_TAG?console[c]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...i):console[c](...i)}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 pN(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;zb[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};nb(nO,"PRINT_LOG_TAG",!(AN||CN||kw));var sO=new nO,oO=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)}))},aO=new class{constructor(){nb(this,"_prefix","TRTC"),nb(this,"_queue",new Map)}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){Hw()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix))try{let t=localStorage.getItem(e);if(!t)return!1;let i=JSON.parse(t);if(i&&i.expiresIn<Date.now())return!0}catch(mO){return!1}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(Hw())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(pO){sO.warn(pO)}}getItem(e){if(!Hw())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(Db){sO.warn(Db)}}setItem(e,t){if(Hw())try{let i={expiresIn:Date.now()+Zb,value:t};this._queue.set(this.getRealKey(e),i)}catch(Nk){sO.warn(Nk)}}deleteItem(e){if(!Hw())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(Db){return sO.warn(Db),!1}}clear(){if(Hw())try{localStorage.clear()}catch(pO){sO.warn(pO)}}},cO={};tb(cO,{HTTPS_API:()=>FP,IS_GET_CAPABILITIES_SUPPORTED:()=>nM,IS_GET_SETTINGS_SUPPORTED:()=>rM,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>iM,IS_INSERTABLE_STREAM_SUPPORTED:()=>sM,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>gM,IS_RTC_RTP_SENDER_SUPPORTED:()=>$P,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>oM,IS_SEI_SUPPORTED:()=>aM,IS_SPC_SUPPORTED:()=>QP,basis:()=>pM,capabilityCheck:()=>_M,checkSystemRequirementsInternal:()=>LP,decodeSupportStatus:()=>MP,encodeSupportStatus:()=>PP,getBrowserInfo:()=>CP,getDisplayResolution:()=>HP,isAddTransceiverSupported:()=>XP,isBrowserSupported:()=>bP,isGetReceiversSupported:()=>qP,isGetSendersSupported:()=>zP,isGetTransceiversSupported:()=>YP,isGetUserMediaSupported:()=>GP,isMediaDevicesSupported:()=>DP,isMediaSessionSupported:()=>dM,isMediaStreamTrackProcessorSupported:()=>OP,isReplaceTrackSupported:()=>eM,isRequestVideoFrameCallbackSupported:()=>fM,isSIMDSupported:()=>hM,isScreenCaptureApiAvailable:()=>VP,isSelectedCandidatePair:()=>BP,isSetParametersSupported:()=>tM,isSmallStreamAPISupported:()=>jP,isSmallStreamSupported:()=>JP,isStopTransceiverSupported:()=>ZP,isTRTCSupported:()=>xP,isUnifiedPlanDefault:()=>KP,isUsedInHttpProtocol:()=>wP,isWebAudioSupported:()=>WP,isWebCodecSupported:()=>lM,isWebCodecsSupported:()=>kP,isWebRTCSupported:()=>cM,isWebTransportSupported:()=>uM});var lO={};tb(lO,{AUDIO_LEVEL_SCALE:()=>$O,AudioCodecPipelineType:()=>nP,AudioDecoderDowngradeState:()=>MO,AudioPlayerMode:()=>XO,AudioType:()=>BO,BASIC_TYPE:()=>tP,BannedReason:()=>QO,CONNECTION_CLOSED_REASON:()=>yO,ClientEvent:()=>SO,CodecType:()=>sP,ConnectionEvent:()=>vO,ConnectionState:()=>PO,DECODE_FAILED_ERROR_CODE:()=>oP,FacingMode:()=>zO,LeaveReason:()=>ZO,LocalTrackEvent:()=>RO,MULTI_VIDEO_DATA_TYPE:()=>jO,MediaType:()=>UO,MediaTypeLabel:()=>FO,MonitorEventId:()=>JO,MutedFlag:()=>DO,NetworkQualityValue:()=>KO,PlayerState:()=>AO,ReceiveMode:()=>qO,RemoteStreamType:()=>WO,RemoteTrackEvent:()=>kO,RoomEvent:()=>CO,SceneNumber:()=>NO,StreamEvent:()=>IO,StreamType:()=>GO,SubscribeMediaType:()=>eP,TIMER_TYPE:()=>cP,TRACK_ACTION:()=>VO,TRACK_KIND:()=>xO,TrackEvent:()=>bO,UserRole:()=>OO,UserRoleNumber:()=>wO,VideoCodec:()=>iP,VideoCodecPipelineType:()=>rP,VideoContentHint:()=>aP,VideoDecoderDowngradeState:()=>LO,VideoPlayerMode:()=>YO,VideoType:()=>HO});var dO,uO,hO,pO,mO,_O,fO,gO,EO,TO,vO=((TO=vO||{}).TRACK_ADDED="track-added",TO.TRACK_UPDATED="track-updated",TO.TRACK_SUBSCRIBED="track-subscribed",TO.STREAM_ADDED="stream-added",TO.STREAM_REMOVED="stream-removed",TO.STREAM_UPDATED="stream-updated",TO.STREAM_PUBLISHED="stream-published",TO.STREAM_SUBSCRIBED="stream-subscribed",TO.STREAM_UNSUBSCRIBED="stream-unsubscribed",TO.STATE_CHANGED="state-changed",TO.ERROR="error",TO.CONNECTION_STATE_CHANGED="connection-state-changed",TO.FIREWALL_RESTRICTION="firewall-restriction",TO.SEI_MESSAGE="sei-message",TO.CLOSED="closed",TO),yO=(e=>(e.REMOTE_LEAVE="remote user exitRoom",e.REMOTE_UNPUBLISH="remote user unpublished",e.LOCAL_LEAVE="you exitRoom",e.LOCAL_UNPUBLISH="you unpublished",e.LOCAL_UNSUBSCRIBE="you unsubscribed",e.SWITCH_ROLE="you switch role to audience",e))(yO||{}),SO=((EO=SO||{}).STREAM_ADDED="stream-added",EO.STREAM_REMOVED="stream-removed",EO.STREAM_UPDATED="stream-updated",EO.STREAM_SUBSCRIBED="stream-subscribed",EO.CONNECTION_STATE_CHANGED="connection-state-changed",EO.PEER_JOIN="peer-join",EO.PEER_LEAVE="peer-leave",EO.MUTE_AUDIO="mute-audio",EO.MUTE_VIDEO="mute-video",EO.UNMUTE_AUDIO="unmute-audio",EO.UNMUTE_VIDEO="unmute-video",EO.CLIENT_BANNED="client-banned",EO.NETWORK_QUALITY="network-quality",EO.AUDIO_VOLUME="audio-volume",EO.SEI_MESSAGE="sei-message",EO.ERROR="error",EO),IO=((gO=IO||{}).PLAYER_STATE_CHANGED="player-state-changed",gO.SCREEN_SHARING_STOPPED="screen-sharing-stopped",gO.CONNECTION_STATE_CHANGED="connection-state-changed",gO.DEVICE_AUTO_RECOVERED="device-auto-recovered",gO.ERROR="error",gO),RO=(e=>(e.DEVICE_AUTO_RECOVERED="1",e.DEVICE_RECOVER_FAILED="5",e.DEVICE_CHANGED="2",e.ERROR="3",e.PUBLISH_STATE_CHANGED="4",e.ENCODE_FAILED="6",e))(RO||{}),AO=(e=>(e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e))(AO||{}),CO=((fO=CO||{}).PEER_JOIN="peer-join",fO.PEER_LEAVE="peer-leave",fO.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",fO.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",fO.BANNED="banned",fO.NETWORK_QUALITY="network-quality",fO.AUDIO_VOLUME="audio-volume",fO.SEI_MESSAGE="sei-message",fO.ERROR="error",fO.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",fO.REMOTE_PUBLISHED="remote-published",fO.REMOTE_UNPUBLISHED="remote-unpublished",fO.FIREWALL_RESTRICTION="firewall-restriction",fO.HEARTBEAT_REPORT="heartbeat-report",fO.CUSTOM_MESSAGE="custom-message",fO.LAYER_DATA="layerData",fO.FIRST_VIDEO_FRAME="first-video-frame",fO.DUMP="dump",fO),bO=((_O=bO||{}).PLAYER_STATE_CHANGED="player-state-changed",_O.MUTE="mute",_O.UNMUTE="unmute",_O.ERROR="error",_O.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",_O.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",_O.FIRST_VIDEO_FRAME="first-video-frame",_O),kO=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(kO||{}),DO=(e=>(e[e.VIDEO=1]="VIDEO",e[e.SMALL=2]="SMALL",e[e.AUX=4]="AUX",e[e.AUDIO=8]="AUDIO",e[e.VIDEO_MUTE=16]="VIDEO_MUTE",e[e.AUX_MUTE=32]="AUX_MUTE",e[e.AUDIO_MUTE=64]="AUDIO_MUTE",e))(DO||{}),NO=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(NO||{}),wO=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(wO||{}),OO=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(OO||{}),PO=(e=>(e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e))(PO||{}),MO=((mO=MO||{}).INITIALIZED="INITIALIZED",mO.STARTING="STARTING",mO.STARTED="STARTED",mO.FAILED="FAILED",mO),LO=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(LO||{}),xO=(e=>(e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e))(xO||{}),VO=(e=>(e.ADD="add",e.REMOVE="remove",e))(VO||{}),UO=(e=>(e[e.NULL=0]="NULL",e[e.AUDIO=1]="AUDIO",e[e.AUX_VIDEO=2]="AUX_VIDEO",e[e.BIG_VIDEO=4]="BIG_VIDEO",e[e.SMALL_VIDEO=8]="SMALL_VIDEO",e))(UO||{}),FO={1:"audio",2:"auxVideo",4:"video"},BO=((pO=BO||{})[pO.opus=111]="opus",pO),HO=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(HO||{}),GO=(e=>(e.Big="big",e.Small="small",e))(GO||{}),WO=(e=>(e.Main="main",e.Aux="auxiliary",e))(WO||{}),jO=(e=>(e[e.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",e[e.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",e[e.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",e[e.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",e[e.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",e))(jO||{}),JO=((hO=JO||{})[hO.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",hO[hO.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",hO[hO.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",hO[hO.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",hO[hO.MUTE_AUDIO=32772]="MUTE_AUDIO",hO[hO.MUTE_VIDEO=32773]="MUTE_VIDEO",hO[hO.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",hO[hO.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",hO[hO.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",hO[hO.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",hO[hO.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",hO[hO.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",hO[hO.SWITCH_CAMERA=32780]="SWITCH_CAMERA",hO[hO.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",hO[hO.REPLACE_VIDEO=32782]="REPLACE_VIDEO",hO[hO.REPLACE_AUDIO=32783]="REPLACE_AUDIO",hO[hO.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",hO[hO.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",hO[hO.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",hO[hO.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",hO[hO.JOIN=32788]="JOIN",hO[hO.LEAVE=32789]="LEAVE",hO[hO.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",hO[hO.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",hO[hO.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",hO[hO.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",hO[hO.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",hO[hO.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",hO[hO.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",hO[hO.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",hO[hO.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",hO[hO.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",hO[hO.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",hO[hO.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",hO[hO.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",hO[hO.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",hO[hO.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",hO[hO.PUBLISH_AUX=32805]="PUBLISH_AUX",hO[hO.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",hO[hO.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",hO[hO.VIDEO_ENCODER=4004]="VIDEO_ENCODER",hO[hO.VIDEO_DECODER=4005]="VIDEO_DECODER",hO),KO=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.EXCELLENT=1]="EXCELLENT",e[e.GOOD=2]="GOOD",e[e.POOR=3]="POOR",e[e.BAD=4]="BAD",e[e.VERY_BAD=5]="VERY_BAD",e[e.DISCONNECTED=6]="DISCONNECTED",e))(KO||{}),qO=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTO_AUDIO=1]="AUTO_AUDIO",e[e.AUTO_VIDEO=2]="AUTO_VIDEO",e[e.AUTO_ALL=3]="AUTO_ALL",e))(qO||{}),zO=(e=>(e.user="user",e.environment="environment",e))(zO||{}),YO=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",e[e.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",e))(YO||{}),XO=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(XO||{}),QO=(e=>(e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e))(QO||{}),ZO=((uO=ZO||{})[uO.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",uO[uO.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",uO[uO.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",uO[uO.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",uO[uO.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",uO[uO.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",uO[uO.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",uO[uO.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",uO[uO.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",uO),$O=1e8,eP=class{constructor(){nb(this,"mediaType",0)}set audio(e){e?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(1&this.mediaType)}set video(e){e?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(4&this.mediaType)}set auxiliary(e){e?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(2&this.mediaType)}set smallVideo(e){e?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(8&this.mediaType)}},tP=(e=>(e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e))(tP||{}),iP=(e=>(e.H264="h264",e.H265="h265",e.VP8="vp8",e))(iP||{}),rP=(e=>(e[e.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",e[e.DUMP=1]="DUMP",e[e.SEI=2]="SEI",e[e.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",e))(rP||{}),nP=(e=>(e[e.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",e[e.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",e[e.DUMP=2]="DUMP",e[e.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",e))(nP||{}),sP=(e=>(e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e))(sP||{}),oP=((dO=oP||{})[dO.SUCCESS=0]="SUCCESS",dO[dO.FAILED=1]="FAILED",dO[dO.WEBCODEC_INIT=2]="WEBCODEC_INIT",dO[dO.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",dO[dO.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",dO[dO.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",dO[dO.WASM_INIT=6]="WASM_INIT",dO[dO.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",dO[dO.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",dO[dO.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",dO[dO.TEST=10]="TEST",dO),aP=(e=>(e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e))(aP||{}),cP=(e=>(e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e))(cP||{}),lP={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},dP={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,s="".concat(t||i.name),o="";return o=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(s,"' must be type of ").concat(o," when calling ").concat(r,"(), received type: ").concat(SD(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,s="".concat(t||i.name),o="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(s,"' must be instanceof ").concat(o," when calling ").concat(r,"(), received type: ").concat(SD(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/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 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,"()")},uP=(e,t)=>t?"".concat(Bb,"/").concat(e,"/").concat(t):"".concat(Bb,"/").concat(e,"/index.html"),hP=()=>{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(Jb);if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let i=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:r}}return{}};function pP(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,s="",o="",a="";ID(dP[t])?s=dP[t](i):AD(dP[t])&&(s=dP[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=hP();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(ID(l[t])?a=l[t](i):AD(l[t])&&(a=l[t]));let d=s;return ED()&&(c&&c[t]&&(ID(c[t])?o=c[t](i):AD(c[t])&&(o=c[t])),o&&(d=n?"".concat(o,"\n请查看文档: ").concat(uP("zh-cn",a),"\n\n"):"".concat(o,"\n\n"),d+=s)),n&&(d+=" \nRefer to: ".concat(uP("en",a),"\n")),d}var mP,_P=ib(ub(),1),fP=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];nb(this,"countMap",new Map),nb(this,"distributionMap",new Map),nb(this,"version"),nb(this,"log",sO.createLogger({id:"kv"})),e&&(tO.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===ik.AUDIO?501700:511700,cost:i})})),tO.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===ik.AUDIO?501700:511700,error:i})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:tN(this.version||bb),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 s=(null==(n=this.distributionMap)?void 0:n.get(t))||new Map;s.set(i,(s.get(i)||0)+1),this.distributionMap.set(t,s)}addNumber(e){let{key:t,value:i,split:r=100,useUV:n=!1}=e;var s;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 o=(null==(s=this.distributionMap)?void 0:s.get(t))||new Map,a=0;if(CD(r))a=Math.floor(i/r);else for(let c=r.length-1;c>0;c--)if(i>r[c]){a=c;break}o.set(a,(o.get(a)||0)+1),this.distributionMap.set(t,o)}addSuccessEvent(e){let{key:t,cost:i,timeKey:r,split:n}=e;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),i)){let e=+String(t).slice(-3);e<800&&e>=700?this.addNumber({key:r||t+100,value:i,split:n}):r||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:i}=e;if(!t)return;let r=Eb.UNKNOWN;i&&(CD(i)?r=i:(!RD(i.extraCode)||!RD(i.code))&&(r=i.extraCode||i.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:r,useUV:!1})}},gP=((mP=gP||{})[mP.enterRoom=500700]="enterRoom",mP[mP.exitRoom=500701]="exitRoom",mP[mP.switchRole=500702]="switchRole",mP[mP.destroy=500703]="destroy",mP[mP.startLocalAudio=500704]="startLocalAudio",mP[mP.updateLocalAudio=500705]="updateLocalAudio",mP[mP.stopLocalAudio=500706]="stopLocalAudio",mP[mP.startLocalVideo=500707]="startLocalVideo",mP[mP.updateLocalVideo=500708]="updateLocalVideo",mP[mP.stopLocalVideo=500709]="stopLocalVideo",mP[mP.startScreenShare=500710]="startScreenShare",mP[mP.updateScreenShare=500711]="updateScreenShare",mP[mP.stopScreenShare=500712]="stopScreenShare",mP[mP.startRemoteVideo=500713]="startRemoteVideo",mP[mP.updateRemoteVideo=500714]="updateRemoteVideo",mP[mP.stopRemoteVideo=500715]="stopRemoteVideo",mP[mP.muteRemoteAudio=500716]="muteRemoteAudio",mP[mP.setRemoteAudioVolume=500717]="setRemoteAudioVolume",mP[mP.use=500718]="use",mP[mP.sendSEIMessage=5e5]="sendSEIMessage",mP[mP.sendCustomMessage=500001]="sendCustomMessage",mP),EP=(e=>(e[e.AudioMixer=550700]="AudioMixer",e[e.AIDenoiser=551700]="AIDenoiser",e[e.VirtualBackground=570700]="VirtualBackground",e[e.Beauty=571700]="Beauty",e[e.Watermark=572700]="Watermark",e[e.BasicBeauty=574700]="BasicBeauty",e[e.CDNStreaming=590700]="CDNStreaming",e[e.DeviceDetector=591700]="DeviceDetector",e[e.Debug=592700]="Debug",e))(EP||{}),TP=(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))(TP||{}),vP=(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))(vP||{}),yP=new fP(!0),SP=new fP(!1),IP=yP,RP={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},AP=new Map([[NN,["Firefox",wN]],[LN,["Edg",xN]],[bw,["Chrome",Nw]],[ww,["Safari",Pw]],[GN,["TBS",WN]],[jN,["XWEB",JN]],[YN&&IN,["WeChat",XN]],[ew,["QQ(Win)",tw]],[ZN,["QQ(Mobile)",$N]],[QN,["QQ(Mobile X5)",$N]],[iw,["QQ(Mac)",rw]],[nw,["QQ(iPad)",sw]],[pw,["MI",mw]],[_w,["HW",Ew]],[Tw,["Samsung",vw]],[yw,["OPPO",Sw]],[Iw,["VIVO",Rw]],[PN,["EDGE",MN]],[UN,["SogouMobile",FN]],[BN,["Sogou",HN]]]);function CP(){let e=AP.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var bP=function(){return!(uw||PN||LN&&VN<80||NN&&ON<56)},kP=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},DP=function(){if(!navigator.mediaDevices)return wP()||sO.error(dP.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},NP=!1;function wP(){return"http:"===location.protocol&&!Bw&&(NP||sO.error(pP({key:lP.NOT_SUPPORTED_HTTP})),NP=!0,!0)}var OP=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},PP=function(){return ob(this,null,(function*(){if(RP.detail.isH264EncodeSupported&&RP.detail.isVp8EncodeSupported)return{isH264EncodeSupported:RP.detail.isH264EncodeSupported,isVp8EncodeSupported:RP.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection,n=document.createElement(ik.CANVAS);n.getContext("2d");let s=n.captureStream(0);return r.addTrack(s.getVideoTracks()[0],s),e=yield r.createOffer(),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),RP.detail.isH264EncodeSupported=t,RP.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:RP.detail.isH264EncodeSupported,isVp8EncodeSupported:RP.detail.isVp8EncodeSupported}}catch(Nk){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},MP=function(){return ob(this,null,(function*(){if(RP.detail.isH264DecodeSupported&&RP.detail.isVp8DecodeSupported)return{isH264DecodeSupported:RP.detail.isH264DecodeSupported,isVp8DecodeSupported:RP.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(Nk){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},LP=nN((()=>ob(void 0,null,(function*(){if(RP.result&&RP.detail.isH264EncodeSupported&&RP.detail.isVp8EncodeSupported&&RP.detail.isH264DecodeSupported&&RP.detail.isVp8DecodeSupported)return RP;let e=Date.now(),t=bP(),i=cM(),r=kP(),n=DP(),{isH264EncodeSupported:s,isVp8EncodeSupported:o}=yield PP(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield MP();if(!s||!o){let e=yield PP();sO.warn("detect encode again h264:".concat(s," vp8:").concat(o," result: ").concat(JSON.stringify(e))),s=e.isH264EncodeSupported,o=e.isVp8EncodeSupported}if(s&&a&&(yw||Iw||Mw)&&!GN&&Aw()<79){let{encode:e,decode:t}=yield function(){return ob(this,null,(function*(){return UP||(UP=new Promise((e=>ob(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{sO.warn("detectH264Supported start");let r=document.createElement("canvas"),n=r.getContext("2d");r.width=320,r.height=240;let s=setInterval((()=>{n.fillText("test",Math.floor(320*Math.random()),Math.floor(240*Math.random()))}),66),o=-1,a=-1;i=()=>{clearInterval(o),clearInterval(s),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=_P.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=_P.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),o=setInterval((()=>ob(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===ik.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===ik.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(r){i(),sO.warn(r),e(t)}})))).then((e=>((!e.encode||!e.decode)&&sO.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(Jw)),e))),UP)}))}();s=e,a=t}return RP.result=t&&i&&n&&(s||o)&&(a||c),RP.detail.isBrowserSupported=t,RP.detail.isWebRTCSupported=i,RP.detail.isWebCodecsSupported=r,RP.detail.isMediaDevicesSupported=n,RP.detail.isScreenShareSupported=VP(),RP.detail.isSmallStreamSupported=JP(),RP.detail.isH264EncodeSupported=s,RP.detail.isVp8EncodeSupported=o,RP.detail.isH264DecodeSupported=a,RP.detail.isVp8DecodeSupported=c,RP.result||sO.error("".concat(navigator.userAgent," ").concat(QD(RP.detail,!1))),aO.setItem(mM,{ua:navigator.userAgent,checkResult:RP}),IP.addNumber({key:523800,value:Date.now()-e}),RP})))),xP=function(){return RP.result},VP=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},UP=null;var FP=(e,t,i)=>{"http:"===location.protocol&&!Bw&&(e[t]=()=>{throw new vb({code:Eb.INVALID_OPERATION,message:dP.NOT_SUPPORTED_HTTP})})},BP=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(bD(e.selected)&&!e.selected)};function HP(){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 GP(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function WP(){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 jP(){return"captureStream"in HTMLCanvasElement.prototype}function JP(){return!(YN||AN||Dw&&Dw<63)&&!(!bP()||!jP())}var KP=function(){if(RD(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:xk}),e.addTransceiver(ik.AUDIO),t=!0}catch(Db){}return null==e||e.close(),t};function qP(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function zP(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function YP(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function XP(){return 11!==xw&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var QP=!(!XP()||Cw&&Dw<86);function ZP(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var $P="RTCRtpSender"in window;function eM(){return $P&&"replaceTrack"in window.RTCRtpSender.prototype}function tM(){return $P&&"setParameters"in window.RTCRtpSender.prototype&&zP()}var iM="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,rM=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,nM=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,sM=$P&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Aw()>=86,oM="RTCRtpScriptTransform"in window,aM=$P&&(sM||oM),cM=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function lM(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return RD(window.AudioDecoder)||(e.AudioDecoder=!0),RD(window.AudioEncoder)||(e.AudioEncoder=!0),RD(window.VideoDecoder)||(e.VideoDecoder=!0),RD(window.VideoEncoder)||(e.VideoEncoder=!0),RD(window.ImageDecoder)||(e.ImageDecoder=!0),e}function dM(){return"mediaSession"in navigator&&!RD(navigator.mediaSession.setActionHandler)}function uM(){return!RD(window.WebTransport)}function hM(){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 pM(){let e={browser:"".concat(Gw.name,"/").concat(Gw.version),os:Yw(),displayResolution:HP(),isScreenShareSupported:VP(),isWebRTCSupported:cM(),isGetUserMediaSupported:GP(),isWebAudioSupported:WP(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:lM(),isMediaSessionSupported:dM(),isWebTransportSupported:uM()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var mM="checkResult";function _M(){wP();let e=aO.getItem(mM);e&&e.ua===navigator.userAgent&&(RP=e.checkResult),LP()}function fM(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var gM="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype,EM=ib(ab(),1),TM=Symbol("instance"),vM=Symbol("cacheResult"),yM=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,CM.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},SM=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var IM=new Map;function RM(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,n,s)=>{let o=i.action||n;if(!i.context){let i=IM.get(r)||[];IM.has(r)||IM.set(r,i),i.push({from:e,to:t,action:o})}let a=s.value;s.value=function(){let r=this;for(var n=arguments.length,s=new Array(n),c=0;c<n;c++)s[c]=arguments[c];if(i.context&&(r=bM.get("function"==typeof i.context?i.context.call(this,...s):i.context)),r.state===t)return i.sync?r[vM]:Promise.resolve(r[vM]);r.state instanceof yM&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof yM&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new SM(r._state,"".concat(r.name," ").concat(o," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e.join("|")))):e!==r.state&&(l=new SM(r._state,"".concat(r.name," ").concat(o," 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 yM(u,t,o);CM.call(r,h);let p=e=>{var n;return r[vM]=e,h.aborted||(CM.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[vM])),e},m=e=>(CM.call(r,u,e),d(e));try{let e=a.apply(this,s);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(EO){return m(new SM(r._state,"".concat(r.name," ").concat(o," from ").concat(e," to ").concat(t," failed: ").concat(EO),EO instanceof Error?EO:new Error(String(EO))))}}}}var AM="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 CM(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(bM.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var bM=class e extends EM.default{constructor(t,i,r){super(),this.name=t,this.groupName=i,this._state=e.INIT,t||(t=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),i||(this.groupName=this.constructor.name);let n=r[TM];n?this.name=n.name+"-"+n.count++:r[TM]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=IM.get(e)||[],i=new Set,r=[],n=[],s=new Set,o=Object.getPrototypeOf(e);IM.has(o)&&(o.stateDiagram.forEach((e=>i.add(e))),o.allStates.forEach((e=>s.add(e)))),t.forEach((e=>{let{from:t,to:i,action:s}=e;"string"==typeof t?r.push({from:t,to:i,action:s}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:s})})):n.push({to:i,action:s})})),r.forEach((e=>{let{from:t,to:r,action:n}=e;s.add(t),s.add(r),s.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," 🟢")),s.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:s}}),a}static get(t){let i;return"string"==typeof t?(i=e.instances.get(t),i||e.instances.set(t,i=new e(t,void 0,Object.create(e.prototype)))):(i=e.instances2.get(t),i||e.instances2.set(t,i=new e(t.constructor.name,void 0,Object.create(e.prototype)))),i}static getState(t){var i;return null===(i=e.get(t))||void 0===i?void 0:i.state}updateDevTools(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};AM(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){CM.call(this,e)}};bM.STATECHANGED="stateChanged",bM.UPDATEAFSM="updateAFSM",bM.INIT="[*]",bM.ON="on",bM.OFF="off",bM.instances=new Map,bM.instances2=new WeakMap;var kM="undefined"!=typeof window,DM=kM&&window.requestIdleCallback||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},NM=kM&&window.cancelIdleCallback||function(e){clearTimeout(e)},wM=kM&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),OM=class e{static generateTaskID(){return this.currentTaskID++}static run(e,t,i){null!=i&&i.fps&&(i.delay=i.delay||Number((1e3/i.fps).toFixed(2))),i=ZC("interval"===e?{delay:2e3,count:0,backgroundTask:!0}:"ric"===e?{delay:1e4,count:0}:"raf"===e?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i);let r=$C(ZC({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i),{delay:i.delay});return this.taskMap.set(r.taskID,r),this[e](r),r.taskID}static interval(t){return t.intervalID=setInterval((()=>{t.callback(),t.loopCount+=1,e.isBreakLoop(t)}),t.delay)}static intervalInWorker(t){e.sharedWorker||(e.sharedWorker=new Worker(URL.createObjectURL(new Blob(["\n const timers = new Map();\n self.onmessage = function(e) {\n const { taskId, delay, type } = e.data;\n if (type === 'start') {\n timers.set(taskId, setInterval(() => {\n self.postMessage({ type: 'tick', taskId });\n }, delay));\n } else if (type === 'stop') {\n clearInterval(timers.get(taskId));\n timers.delete(taskId);\n }\n };\n "],{type:"application/javascript"}))),e.sharedWorker.onmessage=t=>{var i;if("tick"===t.data.type){let r=e.workerTasks.get(t.data.taskId);r&&(r.callback(),r.loopCount+=1,e.isBreakLoop(r)&&(null==(i=e.sharedWorker)||i.postMessage({type:"stop",taskId:r.taskID}),e.workerTasks.delete(r.taskID)))}}),e.workerTasks.set(t.taskID,t),e.sharedWorker.postMessage({taskId:t.taskID,delay:t.delay,type:"start"})}static timeout(t){let i=()=>{if(t.callback(),t.loopCount+=1,!e.isBreakLoop(t))return t.timeoutID=setTimeout(i,t.delay)};return t.timeoutID=setTimeout(i,t.delay)}static ric(t){let i,r=VD(),n=()=>{if(i=VD()-r,i>=t.delay&&(r=VD()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!e.isBreakLoop(t))return t.ricID=DM(n,{timeout:t.delay})};return t.ricID=DM(n,{timeout:t.delay})}static raf(t){let i,r=VD(),n=()=>document.hidden&&t.backgroundTask?(i=VD()-r,r=VD(),t.callback(),t.loopCount+=1,e.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(n,t.delay-Math.floor(i%t.delay))):(i=VD()-r,i>=t.delay&&(r=VD()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),e.isBreakLoop(t)?void 0:t.rafID=requestAnimationFrame(n));if(t.rafID=requestAnimationFrame(n),t.backgroundTask){let e=()=>{if(document.hidden){let e=VD()-r;e>=t.delay?n():t.timeoutID=setTimeout(n,t.delay-e)}};document.addEventListener("visibilitychange",e),t.onVisibilitychange=e,document.hidden&&e()}return t.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:s,worker:o}=this.taskMap.get(e);return o&&o.terminate(),t&&clearInterval(t),i&&clearTimeout(i),r&&wM&&wM(r),n&&NM(n),s&&document.removeEventListener("visibilitychange",s),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)}};nb(OM,"taskMap",new Map),nb(OM,"currentTaskID",1),nb(OM,"sharedWorker",null),nb(OM,"workerTasks",new Map);var PM=OM;ik.SEI_MESSAGE;var MM={LOADED_DATA:ik.LOADEDDATA,LOADED_META_DATA:ik.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},LM={};tb(LM,{create:()=>VM,remove:()=>UM});var xM=new WeakMap;function VM(e,t){xM.has(e)||xM.set(e,[]);let i=xM.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 UM(e){let t=xM.get(e);t&&(t.forEach((e=>e())),xM.delete(e))}var FM=new class{constructor(){nb(this,"_roomIdMap",new Map),nb(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:bb,env:qb.QCLOUD,browserVersion:Gw.name+Gw.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){Bw||!sO.isAbleToUpload||this._configs.env===qb.QCLOUD&&this.uploadEventToKibana($C(ZC({},e),{result:"success"}))}logFailedEvent(e){if(Bw||!sO.isAbleToUpload)return;let{eventType:t,code:i,error:r,userId:n}=e,s={roomId:this._roomIdMap.get(n||this._configs.userId),userId:n,eventType:t,result:"failed",code:i||(null==r?void 0:r.extraCode)||(null==r?void 0:r.code)||Eb.UNKNOWN};this._configs.env===qb.QCLOUD&&this.uploadEventToKibana($C(ZC({},s),{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:Ib(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:bb,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+="\n".concat(r.stack))),this.sendRequest(oD(this._configs.sdkAppId,Kb.LOG),n)}sendRequest(e,t){setTimeout((()=>sN({url:e,body:JSON.stringify(t),priority:"low"}).catch((()=>{}))),2e3)}},BM=new WeakMap;function HM(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,s,o){let a=hN({retryFunction:o.value,settings:t,onError(t){let{error:r,retry:n,reject:o,retryFuncArgs:a}=t;var c;i?i.call(this,r,(()=>{var t;null!=(t=BM.get(e))&&t.has(s)?n():o(r)}),o,a):null!=(c=BM.get(e))&&c.has(s)?n():o(r)},onRetrying(t,i){var n;cN(r)&&r.call(this,t,i),null!=(n=BM.get(e))&&n.has(s)&&(BM.get(e).get(s).stopRetry=i)},onRetryFailed:n});return o.value=function(){let t=BM.get(e);for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return t?t.set(s,{args:r}):BM.set(e,new Map([[s,{args:r}]])),a.apply(this,r).finally((()=>{var t;return null==(t=BM.get(e))?void 0:t.delete(s)}))},o}}function GM(e){let{fnName:t,callback:i,validateArgs:r=!0}=e;return function(e,n,s){let o=s.value;return s.value=function(){for(var n,s,a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(null!=(n=BM.get(e))&&n.has(t)){let{stopRetry:n,args:o}=BM.get(e).get(t),a=!0;if(r)for(let e of o)if(!c.find((t=>t===e))){a=!1;break}a&&(i&&i.apply(this,c),n&&n(),null==(s=BM.get(e))||s.delete(t))}return o.apply(this,c)},s}}var WM=class extends bM{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,nb(this,"id"),nb(this,"element",null),nb(this,"track"),nb(this,"url"),nb(this,"attr"),nb(this,"mode"),nb(this,"muted"),nb(this,"_log"),nb(this,"_pausedRetryCount"),nb(this,"_isElementPlayingFired",!1),nb(this,"_interval"),nb(this,"_delayDestroyTimeoutId",0),nb(this,"_playSuccessResolve"),nb(this,"_isReplayByRecreateMediaStreamCalled",!1),nb(this,"isInAutoPlayFailedState",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=zk,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){var e;return"PLAYING"===this._state&&(!1===(null==(e=this.element)?void 0:e.paused)||this.track&&"live"===this.track.readyState&&!this.track.muted)}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,null!==e&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return ob(this,null,(function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise(((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)}))}catch(Db){let t=pP({key:lP.PLAY_FAILED,data:{media:this.kind,error:Db}});if(this.track&&!this.track.muted&&this._log.warn(Db),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new vb({code:Eb.PLAY_NOT_ALLOWED,message:t})}}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Ow?this._delayDestroyTimeoutId||(this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout((()=>this.destroyElement()),3*e)):this.destroyElement(),this.handleStopped(ik.ENDED),this._interval>0&&PM.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():Uw?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 VM(this.element,this.element).add(ik.PLAYING,e).add(ik.ENDED,e).add(ik.PAUSE,e).add(ik.ERROR,e).add(ik.LOADEDDATA,e).add(ik.LOADEDMETADATA,e)}}bindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;if(e){let t=this.handleTrackEvent.bind(this);null==LM||LM.create(e,e).add(ik.ENDED,t).add(ik.MUTE,t).add(ik.UNMUTE,t),e.readyState===ik.ENDED&&this.handleTrackEvent({type:ik.ENDED}),e.muted&&this.handleTrackEvent({type:ik.MUTE})}}bindAutoPlayEvent(){tO.on(rO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;e&&UM(e)}unbindEvents(){this.element&&UM(this.element),this.unbindTrackEvents(),tO.off(rO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case ik.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(ik.PLAYING),this._interval&&(PM.clearTask(this._interval),this._interval=-1);break;case ik.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(ik.ENDED);break;case ik.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(ik.PAUSE),AN&&(this._interval=PM.run("timeout",(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case ik.ERROR:if(this.element&&this.element.error){this.handlePaused(ik.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)),FM.uploadEvent({log:"stat-".concat(this.kind,"-").concat(Ok.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),gw||fw?this.emit(MM.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case ik.LOADEDDATA:this.kind===ik.VIDEO&&this.emit(MM.LOADED_DATA);break;case ik.LOADEDMETADATA:this.kind===ik.VIDEO&&this.emit(MM.LOADED_META_DATA)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),FM.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),IP.addSuccessEvent({key:this.kind===ik.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),FM.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),IP.addFailedEvent({key:this.kind===ik.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(MM.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,i)=>{rN(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)}),rN(5e3).then((()=>{var e,r;(!this.isPlaying||null!=(e=this.element)&&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 ik.ENDED:this.handleStopped(ik.ENDED);break;case ik.MUTE:this.handlePaused(ik.MUTE);break;case ik.UNMUTE:this._isElementPlayingFired?this.handlePlaying(ik.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString())}}handlePlaying(e){var t;null==(t=this._playSuccessResolve)||t.call(this,e),this.emit(MM.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(MM.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(MM.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};rb([HM({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],WM.prototype,"doReplayByRecreateMediaStream",1),rb([RM([],"PLAYING",{sync:!0})],WM.prototype,"handlePlaying",1),rb([RM("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],WM.prototype,"handlePaused",1),rb([RM([],"STOPPED",{sync:!0})],WM.prototype,"handleStopped",1);var jM,JM="trtc_autoplay",KM="".concat(JM,"_mask"),qM="".concat(JM,"_wrapper"),zM="".concat(JM,"_header"),YM="".concat(JM,"_content"),XM="".concat(JM,"_action_wrapper"),QM="".concat(JM,"_question"),ZM="".concat(JM,"_collapse"),$M="".concat(JM,"_action_confirm"),eL="".concat(JM,"_detail"),tL="#2473E8",iL="dialog",rL="".concat(iL,"-show"),nL="".concat(iL,"-1"),sL="".concat(iL,"-2"),oL=!1,aL=()=>!!document.querySelector(".".concat(qM)),cL="".concat(Bb,"/").concat(ED()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),lL="<br><a href='".concat(cL,"' target='_blank'>").concat(ED()?"其他方案?":"Any other solution?","</a>"),dL="".concat(ED()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(lL):"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(lL)),uL=class{constructor(){if(nb(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),nb(this,"_dialogNode",null),nb(this,"_bodyPosition",""),nb(this,"_showDetail",!1),nb(this,"_isCollapseClicked",!1),nb(this,"_isQuestionClicked",!1),ED()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!oL){let e=document.createElement("style");e.innerHTML=".".concat(KM,"{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(KM," div:not(.").concat(XM,"){display:block !important;}.").concat(qM,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(qM," a{color:").concat(tL,";}.").concat(zM,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(YM,"{margin:8px 0;}.").concat(XM,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(ZM,"{margin-right:auto;cursor:pointer}.").concat(QM,"{height:100%;line-height:16px;cursor:pointer;}.").concat($M,"{margin-left:8px;color:#fff;background:").concat(tL,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat($M,":hover{opacity:0.9;}.").concat(ZM,",.").concat($M,",.").concat(YM,",.").concat(QM,"{font-size:14px;}@media screen and (max-width:750px){.").concat(qM,"{width:80vw;}}"),document.head.appendChild(e),oL=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(KM,"\"><div class='").concat(qM,"'><div class='").concat(zM,"'>").concat(location.host,"</div><div class='").concat(YM,"'>").concat(this.content,"</div><div class='").concat(eL,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(dL,"</div><div class='").concat(XM,"'></div></div></div>").trim();let t=document.createElement("button");t.className=$M,t.innerText=ED()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=QM,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=ZM,r.innerText="".concat(ED()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,s=n.querySelector(".".concat(XM));return s.appendChild(r),s.appendChild(i),s.appendChild(t),n}addDiaLog(){aL()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(qM)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",sO.info("show autoplay dialog"),FM.uploadEvent({log:rL}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){sO.warn("confirm clicked, try resume stream"),tO.emit(rO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(eL));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||FM.uploadEvent({log:nL}),this._isCollapseClicked=!0}onQuestionClick(){window.open(cL,"_blank"),this._isQuestionClicked||FM.uploadEvent({log:sL}),this._isQuestionClicked=!0}},hL=class extends WM{constructor(e){super(e,ik.VIDEO),nb(this,"stat",{}),nb(this,"_calculateTimeout",-1),nb(this,"viewMirror",!1),nb(this,"objectFit"),nb(this,"container"),nb(this,"canvas"),nb(this,"canvasTrack"),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,RD(e.viewMirror)||(this.viewMirror=e.viewMirror),RD(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var e;let t=document.createElement(ik.VIDEO);this.track&&2!==this.mode&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,(this.track||this.canvasTrack)&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(ik.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(ik.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;super.handleTrackEvent(e),e.type===ik.MUTE&&null!=(t=this.stat)&&t.fps&&(this.stat.fps=0)}handleElementEvent(e){var t;if(2===this.mode)return;super.handleElementEvent(e);let i=e.type;if(i===ik.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&&!aL()&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let e=this.element.style.transform;i===ik.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):i===ik.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}}setCanvas(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;var i,r,n,s;this.canvas!==e&&(null==(i=this.canvas)||i.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,2===this.mode&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?(null==(r=this.element)||r.remove(),null==(n=this.container)||n.appendChild(e)):this.element&&(null==(s=this.container)||s.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(t,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}setPoster(e){this.element&&(this.element.poster=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(),2===this.mode?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(MM.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element&&2!==this.mode&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(fM()&&this.element&&this._calculateTimeout<0){let e=0,t=null,i=(r,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(r-e)*1e3)),e=r,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout((()=>{var e;return null==(e=this.element)?void 0:e.requestVideoFrameCallback(i)}),2e3))};this.element.requestVideoFrameCallback(i)}}catch(Db){this._log.warn("init stat failed",Db)}}};function pL(e,t){return ob(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),sO.info("worklet addModule success")}catch(Db){throw sO.info("worklet addModule catch error. ".concat(Db.message)),Db}}))}"undefined"!=typeof AudioContext?jM=AudioContext:"undefined"!=typeof webkitAudioContext?jM=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(jM=mozAudioContext);var mL,_L=-1;!function e(){try{if(mL)return;(mL=new jM({sampleRate:48e3})).onstatechange=()=>{sO.info("context state: ".concat(mL.state).concat("running"!==mL.state?" visibilityState: ".concat(document.visibilityState):"")),fL()},clearTimeout(_L)}catch(fW){sO.error("initAudioContext failed: ".concat(fW," typeof AudioContextClass: ").concat(typeof jM)),_L=setTimeout(e,1e3)}}();var fL=()=>{"suspended"===mL.state?(TL(),document.addEventListener("click",fL)):"interrupted"===mL.state?TL():(document.removeEventListener("visibilitychange",fL),document.removeEventListener("click",fL))},gL=0,EL=-1;function TL(){return new Promise(((e,t)=>{if("running"===mL.state)return e();Date.now()-gL<1e3?(clearTimeout(EL),EL=setTimeout((()=>{gL=Date.now(),mL.resume().then(e,t)}),1e3)):(clearTimeout(EL),gL=Date.now(),mL.resume().then(e,t))})).catch((e=>{sO.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",fL)}))}document.addEventListener("click",fL);var vL=e=>mL,yL=class{constructor(){nb(this,"node"),nb(this,"node2"),nb(this,"pre",new Set),nb(this,"next",new Set),nb(this,"context"),nb(this,"connectedNodes",new Set)}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&(null==(e=this.context)||e.reduceMixWeight()),delete this.context}replaceNode(e){var t;if(e!==this.node)try{this.node?this._disconnect():null==(t=this.context)||t.addMixWeight(),this.node=e,this.preNodeReconnect(),this.reconnect()}catch(Nk){sO.error(Nk)}}setNode(e,t){var i;if(!this.node)try{null==(i=this.context)||i.addMixWeight(),this.node=e,t&&(this.node2=t),this.preNodeReconnect(),this.reconnect(),IP.addSuccessEvent({key:502701})}catch(mO){sO.error(mO),IP.addFailedEvent({key:502701,error:mO})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),IP.addSuccessEvent({key:502702})}catch(Db){sO.error(Db),IP.addFailedEvent({key:502702,error:Db})}}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.node2||this.node).connect(e),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach((e=>{var t;return null==(t=this.node2||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}},SL=class extends yL{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,nb(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}},IL=class{constructor(){nb(this,"source",new yL),nb(this,"gain",new yL),nb(this,"destination",new yL)}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(vL().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.replaceNode(bL(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}},RL=class extends IL{constructor(e){super(),this.context=e,nb(this,"denoiser",new yL),nb(this,"voiceChanger",new yL),this.source.pipeTo(this.denoiser.pipeTo(this.voiceChanger.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.voiceChanger.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.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.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()}},AL=class{constructor(){nb(this,"audioContext",vL()),nb(this,"destination",this.audioContext.createMediaStreamDestination()),nb(this,"inputs",new Set),nb(this,"mixWeight",0),this.destination.channelCount=1}addMixWeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.mixWeight+=e,this.mixWeight-1==e+1>>1&&this.mixOnChange()}reduceMixWeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.addMixWeight(-e)}close(){this.inputs.forEach((e=>e.remove()))}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},CL=new WeakMap;function bL(e){let t=CL.get(e);if(t)return t;let i=vL();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return CL.set(e,t),t}var kL=class e{constructor(e){nb(this,"_volume",0),nb(this,"_volumeDb",0),nb(this,"_log"),nb(this,"_scriptProcessorNode",null),nb(this,"_audioWorkletNode",null),nb(this,"_interval",200),nb(this,"ready",this.preload());let{log:t}=e;this._log=t,tO.on(rO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-e.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!e.workletReady){let t='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';e.workletReady=pL(e.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return e.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(e.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=i=>{e.lastMessageTime=Date.now(),this._volume=i.data.volume||0,this._volumeDb=i.data.volumeDb||0,!t&&i.data.cacheLen&&i.data.outputLen&&(this._log.warn("worklet play success"),t=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(pO){this._log.error("volumeMeter init audio worklet error: ".concat(pO)),FM.logFailedEvent({userId:this._log.userId,eventType:Ok.LOAD_WORKLET,error:pO}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=vL().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{e.lastMessageTime=Date.now();let i=t.inputBuffer.getChannelData(0),r=0;for(let e=0;e<i.length;++e)r+=i[e]*i[e];this._volume=Math.sqrt(r/i.length)||0}}catch(pO){this._log.error("volumeMeter init script processor error: ".concat(pO))}}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,tO.off(rO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(100*this._volumeDb)}handleAudioLevelInterval(e){var t;let{interval:i}=e;this._interval=i,null==(t=this._audioWorkletNode)||t.port.postMessage({name:"setIntervalTime",intervalTime:i})}};nb(kL,"lastMessageTime",0),nb(kL,"audioContext",vL()),nb(kL,"workletReady");var DL=kL,NL=class extends yL{constructor(e){super(),nb(this,"_volumeMeter"),this._volumeMeter=new DL(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return ob(this,null,(function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)}))}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}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()}}},wL=DL,OL=ib(ab(),1),PL=e=>t=>t.deviceId===e,ML=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";nb(this,"kind"),nb(this,"type"),nb(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&&VL(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(PL(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");sO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(PL(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");sO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},LL=class extends OL.EventEmitter{constructor(){super(),nb(this,"audioInputs",new ML(ik.AUDIO)),nb(this,"videoInputs",new ML(ik.VIDEO)),nb(this,"audioOutputs",new ML(ik.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||PM.run("interval",(()=>{this.update()}),{delay:1e4}))}init(){UL().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return ob(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield UL(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},xL=Ob||wb?null:new LL;function VL(e){return e.deviceId===e.groupId&&""===e.groupId}function UL(){return ob(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(wP()||!DP())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{VL(e)&&(e.kind===ik.AUDIO_INPUT?i.audio=!0:e.kind===ik.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),i.audio&&TL()}catch(mO){sO.debug("capture before getDevices failed: ",mO)}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&&WL.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function FL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return xL.update(e?1:0).then((e=>e.audioInputs.devices))}function BL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return xL.update(e?2:0).then((e=>e.videoInputs.devices))}var HL=!1;function GL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return ob(this,null,(function*(){return(AN||ww)&&(e=!1),xL.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var WL=new Set;function jL(e,t){return ob(this,null,(function*(){let i=(yield FL()).find((e=>e.deviceId===Yk));return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t}))}var JL,KL=class extends IL{constructor(e){super(),this.log=e,nb(this,"volumeMeter"),nb(this,"volumeDestination"),nb(this,"analyser",new SL),this.volumeMeter=new NL({log:this.log}),this.volumeDestination=new yL,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},qL=class e extends WM{constructor(e){super(e,ik.AUDIO),nb(this,"_outputDeviceId"),nb(this,"_volume",1),nb(this,"_destination",vL().createMediaStreamDestination()),nb(this,"pipeline"),nb(this,"volumeMeterMode","worklet"),this.mode=0,this.pipeline=new KL(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(("15.2"===Lw||"15.3"===Lw||"15.4"===Lw)&&this.muted)return void this._log.info("audioElement is muted.");let t=JL||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,CD(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),t===JL&&(JL=void 0),this.bindElementEvents()}play(t){return ob(this,null,(function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(null==t?void 0:t.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(vL().createAnalyser()),function(){ob(this,null,(function*(){try{HL||(HL=!0,sO.info("speakers:".concat((yield GL()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(e){}}))}(),sb(e.prototype,this,"play").call(this)}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy(),super.stop(e)}setSinkId(e){return ob(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()}},zL=class extends qL{setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(MM.MEDIA_TRACK_CHANGED,e),e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]))))}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}},YL=class extends qL{constructor(e){super(e),nb(this,"_sourceElement"),nb(this,"_output",new yL),this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(vL().destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,i;(null==(i=null==(t=this.element)?void 0:t.error)?void 0:i.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(MM.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?this.element?(this._log.info("set element volume: ".concat(e)),this.element.volume=e):this._log.info("set element volume: no element"):AN||(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),UM(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Ow&&(JL=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},XL=class extends bM{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:s=(1===r?YL:hL)}=e;var o;super(),nb(this,"id",oO()),nb(this,"userId",""),nb(this,"isRemote"),nb(this,"mediaType"),nb(this,"room"),nb(this,"user"),nb(this,"_log"),nb(this,"_inputTrack"),nb(this,"_outputTrack"),nb(this,"isPlayCalled"),nb(this,"container",null),nb(this,"player"),nb(this,"subVideoPlayerMap"),nb(this,"muted",!1),nb(this,"abortCtrl"),nb(this,"objectFit","cover"),nb(this,"mirror"),nb(this,"isScreen",!1),nb(this,"manager"),nb(this,"trackSettings"),nb(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=sO.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(o=n||this.room)?void 0:o.userId,remoteUserId:this instanceof Ex?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof Ex}),this.player=new s({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(MM.PLAYER_STATE_CHANGED,(e=>{tO.emit(rO.PLAYER_STATE_CHANGED,ZC({track:this},e)),this.emit("player-state-changed",e)})),this.kind===ik.VIDEO&&(this.player.on(MM.LOADED_DATA,(()=>{this.emitFirstVideoFrameEvent(MM.LOADED_DATA),tO.emit(rO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(MM.LOADED_META_DATA,(()=>{this.emitFirstVideoFrameEvent(MM.LOADED_META_DATA)})),this.player.on(MM.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(MM.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||sO}get kind(){return 1===this.mediaType?ik.AUDIO:ik.VIDEO}get strMediaType(){return 4===this.mediaType?ik.VIDEO:2===this.mediaType?ik.SCREEN:ik.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 ob(this,null,(function*(){let i=DD(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!RD(t.muted)&&this.setPlayerMute(t.muted),t&&!RD(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof hL&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),DD(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!RD(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===ik.VIDEO)&&this.setPlayerMute(!0),t&&!RD(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof hL&&(this.player.setObjectFit(this.objectFit),t&&!RD(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof hL&&this.player.setContainer(i)),tO.emit(rO.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),DD(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(gO){throw this.handleAutoPlayFailed(gO),gO}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==ik.VIDEO||RD(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(bD(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 ob(this,null,(function*(){if(!this._outputTrack||this.kind===ik.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&&(RD(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new hL({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(dN(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return ob(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),tO.emit(e?rO.TRACK_MUTED:rO.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){VM(e,e).add(ik.MUTE,this.onTrackMuted).add(ik.UNMUTE,this.onTrackUnmuted).add(ik.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===ik.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){UM(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((e=>this.handleAutoPlayFailed(e))),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(dN(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(e){if(this.room&&this.room.enableAutoPlayDialog)new uL;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof hL?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var t,i,r;if(this.isFirstVideoFrameEmitted)return;let n=null==(t=this.mediaTrack)?void 0:t.getSettings(),s=(null==n?void 0:n.width)||(null==(i=this.player.element)?void 0:i.videoWidth)||0,o=(null==n?void 0:n.height)||(null==(r=this.player.element)?void 0:r.videoHeight)||0;e===MM.LOADED_META_DATA&&!s&&!o||(e===MM.LOADED_DATA&&!s&&!o&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,this.emit("first-video-frame",{width:s,height:o,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}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"))}};rb([RM([],bM.INIT,{sync:!0})],XL.prototype,"close",1);var QL=Object.prototype.hasOwnProperty;var ZL=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(TD(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(QL.call(e,t))return!1;return!0}return!1},$L=hN({retryFunction:function(e){return ob(this,null,(function*(){let t=function(e){return{audio:tx(e),video:ix(e)}}(e);sO.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId","groupId"];t.audio&&(i=yield FL(),sO.info("microphones: ".concat(XD(i.map((e=>$C(ZC({},e),{groupId:e.groupId.substring(0,8)}))),{keysToInclude:n})))),t.video&&(r=yield BL(),sO.info("cameras: ".concat(XD(r,{keysToInclude:n}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return nM&&e.getTracks().forEach((e=>{sO.info("".concat(e.kind," capabilities: ").concat(XD(e.getCapabilities(),{keysToInclude:iD})))})),t.audio&&TL(),e}catch(gO){let{message:n}=gO;throw"NotFoundError"===gO.name&&(e.video&&r&&0===r.length&&(n=pP({key:lP.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(n=pP({key:lP.MICROPHONE_NOT_FOUND}))),new vb({code:Eb.INITIALIZE_FAILED,name:gO.name,message:n,constraint:gO.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,retryFuncArgs:n,retriedCount:s}=e,o=s+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===o?(n[0].video&&(n[0].maxResolution=!1,(!ww||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===o?n[0].useDeviceIdOnly=!0:3===o&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&ex(n[0].microphoneId,!1),n[0].cameraId&&ex(n[0].cameraId,!0)},onRetrying:e=>{sO.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{FM.logFailedEvent({eventType:Ok.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{FM.logSuccessEvent({eventType:Ok.GET_USER_MEDIA_RETRY}),FM.uploadEvent({log:"stat-".concat(Ok.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function ex(e,t){return ob(this,null,(function*(){let i=(t?yield BL():yield FL()).find((t=>t.deviceId===e));i&&ID(i.getCapabilities)&&sO.warn(XD(i.getCapabilities(),{keysToInclude:iD}))}))}function tx(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!ZL(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(CD(e.channelCount)&&(t.channelCount=e.channelCount),bD(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),bD(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),bD(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!ZL(t)||t)}function ix(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&&!ZL(i)?i:(e.width&&(i.width={ideal:e.width},t&&!NN&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!NN&&(i.height.max=e.height)),NN&&aw&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!ZL(i)||i)}var rx=$L;function nx(e){return ax(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return ob(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function sx(e){return ax(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return ob(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function ox(e){return ax(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return ob(this,null,(function*(){try{return yield t.apply(this,r)}catch(mO){e.call(this,mO)}}))}))}function ax(e){return function(t,i,r){return r.value=e(r.value,i),r}}var cx=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&sO.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{sO.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),lx=0,dx=class{constructor(){nb(this,"log",sO.createLogger({id:"fq".concat(++lx)})),nb(this,"isRunning",!1),nb(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=ZC({},e),s=new Promise(((e,t)=>{n.resolve=e,n.reject=t}));return n.promise=s,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(),s}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()}))}},ux=new WeakMap,hx=new WeakMap;function px(){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=ux.get(this)||new dx;for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];return ux.set(this,t),t.push({fn:n,args:r,context:this},e)},r}}function mx(e){return function(t,i,r){let n=r.value;return r.value=function(){var t,i,r;let s=[];for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];return null==(i=null==(t=ux.get(this))?void 0:t.queue)||i.forEach((e=>s.push(e))),null==(r=hx.get(this))||r.forEach((e=>null==e?void 0:e.queue.forEach((e=>s.push(e))))),s.forEach((t=>{t.reject(new vb({code:Eb.API_CALL_ABORTED,message:e}))})),ux.delete(this),hx.delete(this),n.apply(this,a)},r}}function _x(e){return function(t,i,r){let n=r.value,s=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=hx.get(this)||new Map,o=r.get(s(t))||new dx;return r.set(s(t),o),hx.set(this,r),o.push({fn:n,args:t,context:this})},r}}function fx(e,t){return ax(((i,r)=>function(){let r=e;try{for(var n=arguments.length,s=new Array(n),o=0;o<n;o++)s[o]=arguments[o];let e=i.apply(this,s),a=VD();return OD(e)?e.then((e=>(t?IP.addSuccessEvent({key:r,cost:VD()-a}):IP.addSuccessEvent({key:r}),e))).catch((e=>{throw IP.addFailedEvent({key:r,error:e}),e})):(IP.addSuccessEvent({key:r}),e)}catch(Nb){throw IP.addFailedEvent({key:r,error:Nb}),Nb}}))}var gx=class e extends XL{constructor(e,t){super({mediaType:e,PlayerClass:t}),nb(this,"isRemote",!1),nb(this,"deviceId"),nb(this,"groupId",""),nb(this,"label",""),nb(this,"_isRecapturing",!1),nb(this,"_lastRecaptureTime",0),nb(this,"_onMuteTimeoutId",-1),nb(this,"_encodeCheckTimeoutId",-1),nb(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){VM(e,e).add(ik.MUTE,this.onTrackMuted).add(ik.UNMUTE,this.onTrackUnmuted).add(ik.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===ik.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){UM(e)}setStateToCapture(){}capture(e){return ob(this,null,(function*(){var t;try{let i,r=VD();tO.emit(rO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield rx(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),tO.emit(rO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:VD()-r}),i}catch(mO){throw tO.emit(rO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:mO}),this.log.error("getUserMedia error observed ".concat(mO)),mO}}))}setInputMediaStreamTrack(e){return this.state===bM.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),tO.emit(rO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return ob(this,null,(function*(){if(this.mediaTrack&&rM){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return ob(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:s}=e;return function*(){return t===i&&(s!==ik.AUDIO||t!==Yk||(yield jL(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),UL().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===ik.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(ik.AUDIO_INPUT);return!!WL.has(i)}(this.mediaTrack)||this.kind===ik.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(ik.VIDEO_INPUT);return!!WL.has(i)}(this.mediaTrack)||this._isRecapturing||e&&aw&&ww)}onTrackMuted(){if(super.onTrackMuted(),cx(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<tD)return void setTimeout((()=>this.onTrackMuted()),tD);this._onMuteTimeoutId=setTimeout((()=>ob(this,null,(function*(){var e;if(null!=(e=this.mediaTrack)&&e.muted){if((AN||CN)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return ob(this,null,(function*(){if(sb(e.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<tD)return void setTimeout((()=>this.onTrackEnded()),tD);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return ob(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 FL():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}),tO.emit(rO.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),tO.emit(rO.LOCAL_TRACK_RECAPTURE,{track:this,error:e})}))}))}getRecoverCaptureDeviceId(){return ob(this,null,(function*(){let e=this instanceof Rx;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(Tx.get(t)||0)+1;if(Tx.set(t,i),i>=3){let r=e?(yield BL()).find((e=>!Tx.has(e.deviceId))):(yield FL()).find((e=>!Tx.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)}};rb([RM(bM.INIT,"capture",{ignoreError:!0,sync:!0})],gx.prototype,"setStateToCapture",1),rb([px()],gx.prototype,"capture",1),rb([RM("capture","publish",{ignoreError:!0,success(){var e,t;this.room.localTracks.add(this),tO.emit(rO.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===ik.AUDIO,t=this.stat.bytesSent>0;IP[t?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),t||(IP.addEnum({key:e?503701:513703,value:Xw()}),FM.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(qw()||Qw()),userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}}),5e3))},fail(e){let t="error";if(e.cause instanceof RTCError){let i=e.cause;i.message.includes("timeout")?t="timeout":i.code===Eb.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),fx(521714,!1)],gx.prototype,"publish",1),rb([ax((e=>function(){return ob(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)}))})),RM([],"capture",{sync:!0})],gx.prototype,"unpublish",1);var Ex=gx,Tx=new Map;tO.on(rO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&Tx.delete(e.track.deviceId)}));var vx=class e extends Ex{constructor(e){super(1,zL),nb(this,"mediaType",1),nb(this,"volume",0),nb(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),nb(this,"playerMuted",!0),nb(this,"pipeline"),nb(this,"earMonitorGainNode",new yL),nb(this,"_output",new yL),nb(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),this.manager=e,this.pipeline=new RL(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode.pipeTo(this._output),this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return wL.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(t){return ob(this,null,(function*(){let i=this.trackSettings||{};IP.addEnum({key:501701,value:i.channelCount||0,useUV:!1}),IP.addEnum({key:501702,value:i.sampleRate||0,useUV:!1}),IP.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:n}=i;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:r,channelCount:n}))),this.pipeline.replaceSource(t),yield sb(e.prototype,this,"setInputMediaStreamTrack").call(this,t),this.updatePlayingState(!!t)}))}capture(e){let{deviceId:t,customSource:i,useExactDeviceId:r=!0,retryWhenExactFailed:n=!0}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:n,customSource:i})}switchDevice(e){return ob(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==Yk)return;if(yield jL(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}),tO.emit(rO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(Nk){throw this.log.error("switch microphone failed ".concat(Nk)),this.deviceId&&this.recapture(this.deviceId),Nk}}}))}listenDeviceChange(){xL&&!xL.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&xL.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return ob(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e))),_F(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield FL();t[0]?this.recapture(t[0].deviceId):xL.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return ob(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:n}=e;return function*(){let e=!1;!RD(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!RD(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,e=!0),!RD(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&&IP.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(vL().createGain()),this._output.setNode(vL().destination)),this.earMonitorGainNode.node.gain.value=e}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;Dw<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(IP.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1))}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}close(){this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),xL.off("audioInputAdded",this.handleMicrophoneAdded,this),xL.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(t){return ob(this,null,(function*(){try{yield sb(e.prototype,this,"recapture").call(this,t)}catch(Nk){let r=(yield FL()).find((e=>e.deviceId!==t));if(!r)throw Nk;yield sb(e.prototype,this,"recapture").call(this,r.deviceId)}}))}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight(((e,t)=>t?t({frame:e}):e),e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}},yx=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 s=e;s<=t;s++){let e=this.dataView.getInt8(s);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 s=e;s<=t;s++)switch(this.dataView.getInt8(s)){case 0:r++,i.push(this.dataView.getInt8(s));break;case 3:2!==r&&i.push(this.dataView.getInt8(s)),r=0;break;default:i.push(this.dataView.getInt8(s)),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}},Sx=class{constructor(){nb(this,"_seiMessageList",[]),nb(this,"_smallSeiMessageList",[]),nb(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 o=0;o<i;o++)n.push(255);n.push(r);let s=new DataView(e);return n.push(...new Uint8Array(s.buffer)),n.push(128),new yx(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)}isEmpty(){return!this._seiMessageList.length}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),s=new ArrayBuffer(n+e.data.byteLength),o=new DataView(s),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++)o.setInt8(c++,r[e].dataView.getInt8(t));for(let i=0;i<e.data.byteLength;i++)o.setInt8(c++,a.getInt8(i));return e.data=s,r.length}return 0}},Ix=class e extends Ex{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,hL),nb(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),nb(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0}),nb(this,"small"),nb(this,"isNeedToSetBandwidth"),nb(this,"muteImage"),nb(this,"manager"),nb(this,"_seiCodec",new Sx),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($C(ZC({},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(rM&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}setMute(t){return ob(this,null,(function*(){var i,r,n;if(AD(t)){if(this.muteImage===t)return;yield null==(i=this.manager)?void 0:i.deleteWatermark("mute"),yield null==(r=this.manager)?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:t}),this.muteImage=t,sb(e.prototype,this,"setMute").call(this,!1)}else yield null==(n=this.manager)?void 0:n.deleteWatermark("mute"),this.muteImage=void 0,sb(e.prototype,this,"setMute").call(this,t)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:r=!0,customSource:n,retryWhenExactFailed:s=!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:s,customSource:n})}setProfile(e){let t=ZC({},e),i=t.width>t.height;t.width*t.height<=19200&&CN&&Cw&&(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&&Fw&&(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($C(ZC({},this.profile),{width:1920,height:1080})))}applyProfile(){return ob(this,null,(function*(){var e;if(!this.mediaTrack)return;let t=this.settings;return(t.height!==this.profile.height||t.width!==this.profile.width||t.frameRate!==this.profile.frameRate)&&this.deviceId&&(16===xw?yield this.recapture(this.deviceId):(yield null==(e=this.mediaTrack)?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)?(this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:ik.VIDEO,videoType:ik.BIG})):void 0}))}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return rM&&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:$D()&&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 ob(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),tO.emit(rO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(Nk){throw this.log.error("switch camera failed ".concat(Nk)),this.deviceId&&this.recapture(this.deviceId),Nk}}))}listenDeviceChange(){xL&&!xL.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&xL.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return ob(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e))),_F(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield BL();t[0]?this.recapture(t[0].deviceId):xL.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return ob(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.reduceRight(((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 RD(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){xL.off("videoInputAdded",this.handleCameraAdded,this),xL.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return ob(this,null,(function*(){try{yield sb(e.prototype,this,"recapture").call(this,t)}catch(Nk){let r=(yield BL()).find((e=>e.deviceId!==t));if(!r)throw Nk;yield sb(e.prototype,this,"recapture").call(this,r.deviceId)}}))}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info("setContentHint ".concat(e)),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}};rb([sx((function(e){this.setContentHint(e.contentHint||"motion")}))],Ix.prototype,"capture",1);var Rx=Ix,Ax=oO();if("undefined"!=typeof navigator&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Ax,exposeOrigin:!0,permittedOrigins:["*"]})}catch(fW){}var Cx=function(e){return ob(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:ww?{max:e.width}:{ideal:e.width,max:e.width},height:ww?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:e.preferDisplaySurface||"monitor"};if(t.video=i,e.systemAudio){let{echoCancellation:i=!0,noiseSuppression:r=!1,autoGainControl:n=!1}=e;t.audio={echoCancellation:i,noiseSuppression:r,autoGainControl:n,sampleRate:48e3}}return t}(e);sO.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(bw&&Dw<74||ww||NN)&&sO.warn("Your browser not support capture system audio");let n=r.getVideoTracks()[0];if(n){if(e.frameRate)try{yield n.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height})}catch(gO){sO.warn("screen applyConstraints failed: ".concat(gO))}e.captureElement&&(yield function(e,t){return ob(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&ID(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==Ax)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){sO.warn("cropTo target failed ".concat(r))}}))}(n,e.captureElement))}if(e.audio){let i=function(e){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return RD(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);sO.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},bx=class extends Rx{constructor(e){super(e,2),nb(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),nb(this,"objectFit","contain"),nb(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return ob(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:r,echoCancellation:n,noiseSuppression:s,audioTrack:o,videoTrack:a,captureElement:c,preferDisplaySurface:l}=e;return function*(){try{let e;return a||o?(e=new MediaStream,a&&e.addTrack(a),o&&e.addTrack(o)):e=yield Cx({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:r,echoCancellation:n,noiseSuppression:s,captureElement:c,preferDisplaySurface:l}),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(dO){throw t.log.error("getDisplayMedia error observed ".concat(dO)),dO instanceof vb?dO:new vb({code:Eb.INITIALIZE_FAILED,name:dO.name,message:dO.message})}}()}))}switchDevice(e){return ob(this,null,(function*(){throw new Error("Method not implemented.")}))}};rb([sx((function(e){this.setContentHint(e.contentHint||"detail")}))],bx.prototype,"capture",1);var kx,Dx=class extends vx{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}};function Nx(e){return ob(this,null,(function*(){let t=vL();kx||(kx=pL(t,URL.createObjectURL(new Blob(["registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});"],{type:"application/javascript"})))),yield kx;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 wx=class extends AL{constructor(e){super(),this.room=e,nb(this,"_localAudioTrack"),nb(this,"_localScreenAudioTrack"),nb(this,"log",sO.createLogger({id:"am"})),nb(this,"denoiser"),nb(this,"voiceChanger"),nb(this,"mixChangedDebounce"),nb(this,"encodePipeline",[]),nb(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 s=new AbortController,o=[],a=setTimeout((()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")}),1e3*e),c=()=>{for(let e=0;e<n.length;e++){let t=URL.createObjectURL(new Blob(o[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),s.abort("download")},l=Nx(r).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>o[t]=o[t]?o[t].concat(e[0]):[e[0]]))}}),s).catch((e=>c))));return{then:l.then.bind(l),download:c}}getPCM(e){var t;if(RD(WritableStream))return void this.log.warn("getPCM failed: browser not support WritableStream");if(null==(t=this._localAudioPipline)||!t.source.node)return void this.log.warn("getPCM failed: no local audio track");this.log.warn("getPCM");let i=new Float32Array(1920),r=0,n=new AbortController;return Nx([this._localAudioPipline.source.node]).then((t=>t.pipeTo(new WritableStream({write(t){t[0][0]&&(i.set(t[0][0],r),r+=t[0][0].length,r>=1920&&(r=0,e(i),i=new Float32Array(1920)))}}),n).catch((e=>this.log.warn("stop getPCM reason:".concat(e)))))),n}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return!RD(this._localAudioTrack)}changeInput(e){return e instanceof Dx?(this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange()):e instanceof vx?(this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange()):e instanceof zU?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 Dx?delete this._localScreenAudioTrack:e instanceof vx&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,null==(t=this._localAudioTrack)||t.removeDenoiser(e)}addVoiceChanger(e,t){var i;this.voiceChanger=[e,t],null==(i=this._localAudioTrack)||i.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,null==(e=this._localAudioTrack)||e.pipeline.voiceChanger.deleteNode()}destroy(){this.close()}addEncodeProcessor(e){let{processor:t,type:i}=e;var r;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:i}=e;var r;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}};function Ox(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return ax(((i,r)=>function(){for(var n=arguments.length,s=new Array(n),o=0;o<n;o++)s[o]=arguments[o];return new Promise(((n,o)=>{let a=setTimeout((()=>{let i=new vb({code:Eb.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});sO.warn(i),2===t?o(i):1===t&&n()}),1e3*e);i.apply(this,s).then(n,o).finally((()=>{clearTimeout(a)}))}))}))}var Px={};function Mx(){}tb(Px,{Events:()=>Yx,Inspect:()=>Bx,LastSink:()=>Hx,Sink:()=>Gx,Subscribe:()=>Wx,TimeoutError:()=>Xx,audit:()=>eU,bindCallback:()=>DV,bindNodeCallback:()=>NV,buffer:()=>lV,bufferCount:()=>cV,bufferTime:()=>VU,call:()=>Lx,catchError:()=>FU,combineLatest:()=>nV,concat:()=>tV,concatMap:()=>AU,concatMapTo:()=>CU,count:()=>xV,create:()=>Jx,debounce:()=>rU,debounceTime:()=>nU,defer:()=>hV,delay:()=>UU,deliver:()=>Kx,dispose:()=>Vx,elementAt:()=>sU,empty:()=>PV,every:()=>dU,exhaustMap:()=>PU,exhaustMapTo:()=>MU,filter:()=>BV,find:()=>oU,findIndex:()=>aU,first:()=>cU,fromAnimationFrame:()=>bV,fromArray:()=>fV,fromEvent:()=>yV,fromEventPattern:()=>vV,fromFetch:()=>IV,fromIterable:()=>RV,fromPromise:()=>SV,fromReadableStream:()=>CV,fromReader:()=>AV,groupBy:()=>LU,identity:()=>xx,ignoreElements:()=>HV,iif:()=>rV,inspect:()=>Ux,interval:()=>gV,last:()=>lU,map:()=>mU,mapTo:()=>_U,max:()=>VV,merge:()=>$x,mergeMap:()=>DU,mergeMapTo:()=>NU,min:()=>UV,never:()=>wV,nothing:()=>Mx,of:()=>_V,pairwise:()=>hU,pipe:()=>jx,race:()=>eV,range:()=>kV,reduce:()=>LV,retry:()=>JU,scan:()=>uU,share:()=>Zx,shareReplay:()=>iV,skip:()=>KV,skipUntil:()=>qV,skipWhile:()=>zV,startWith:()=>oV,subject:()=>uV,subscribe:()=>GU,sum:()=>FV,switchMap:()=>vU,switchMapTo:()=>SU,take:()=>GV,takeLast:()=>JV,takeUntil:()=>WV,takeWhile:()=>jV,tap:()=>WU,throttle:()=>ZV,throwError:()=>OV,timeInterval:()=>xU,timeout:()=>jU,timer:()=>EV,toPromise:()=>BU,toReadableStream:()=>HU,withLatestFrom:()=>aV,zip:()=>sV});var Lx=e=>e(),xx=e=>e;function Vx(){this.dispose()}var Ux=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,Fx=1,Bx=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new zx(e,this,this.streamId++);return Yx.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},Hx=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=Mx,this.error=Mx,this.next=Mx,this.dispose=Mx,this.subscribe=Mx,this.doDefer()}subscribe(e){return e instanceof Bx?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(Lx),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}},Gx=class extends Hx{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)}},Wx=class extends Hx{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Mx,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Mx,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Mx;if(super(),this._next=t,this._error=i,this._complete=r,this.then=Mx,e instanceof Bx){let n={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{Yx.defer(n,0)})),Yx.create(n),Yx.pipe(n),this.sourceId=n.id,this.subscribe(e),Yx.subscribe({id:n.id,end:!0}),t==Mx?this._next=e=>Yx.next(n,0,e):this.next=e=>{Yx.next(n,0,e),t(e)},r==Mx?this._complete=()=>Yx.complete(n,0):this.complete=()=>{this.dispose(),Yx.complete(n,0),r()},i==Mx?this._error=e=>Yx.complete(n,0,e):this.error=e=>{this.dispose(),Yx.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 jx(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 Jx(e,t,i){if(Ux()){let r=Object.defineProperties(Object.setPrototypeOf(e,Bx.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}});Yx.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof Bx&&Yx.addSource(r,t)}return r}return e}function Kx(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 Bx){let n=Jx((t=>{let s=new e(t,...r);s.sourceId=n.id,s.subscribe(i)}),t,arguments);return n.source=i,Yx.pipe(n),n}return t=>i(new e(t,...r))}}}function qx(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var zx=class extends Gx{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{Yx.defer(this.source,this.id)}))}next(e){Yx.next(this.source,this.id,e),this.sink.next(e)}complete(){Yx.complete(this.source,this.id),this.sink.complete()}error(e){Yx.complete(this.source,this.id,e),this.sink.error(e)}},Yx={addSource(e,t){qx("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){qx("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;qx("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){qx("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){qx("defer",{id:e.id,streamId:t})},pipe(e){qx("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){qx("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=Fx++),qx("create",{name:e.toString(),id:e.id})}},Xx=class extends Error{constructor(e){super("timeout after ".concat(e,"ms")),this.timeout=e}},Qx=class extends Hx{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 Zx(){return e=>{let t=new Qx(e);if(e instanceof Bx){let i=Jx((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,Yx.pipe(i),i}return Jx(t.add.bind(t),"share",arguments)}}function $x(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Jx((e=>{let i=new Gx(e),r=t.length;i.complete=()=>{0==--r&&e.complete()},t.forEach(i.bindSubscribe)}),"merge",arguments)}function eV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Jx((e=>{let i=new Map;t.forEach((t=>{let r=new Gx(e);i.set(t,r),r.complete=()=>{i.delete(t),0===i.size?e.complete():r.dispose()},r.next=e=>{i.delete(t),i.forEach((e=>e.dispose())),r.resetNext(),r.resetComplete(),r.next(e)}})),t.forEach((e=>i.get(e).subscribe(e)))}),"race",arguments)}function tV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Jx((e=>{let i=0,r=t.length,n=new Gx(e);n.complete=()=>{i<r&&!n.disposed?(n.doDefer(),n.subscribe(t[i++])):e.complete()},n.complete()}),"concat",arguments)}function iV(e){return t=>{let i=new Qx(t),r=[];return i.next=function(t){r.push(t),r.length>e&&r.shift(),this.sinks.forEach((e=>e.next(t)))},Jx((e=>{e.defer((()=>i.remove(e))),r.forEach((t=>e.next(t))),i.add(e)}),"shareReplay",arguments)}}function rV(e,t,i){return Jx((r=>e()?t(r):i(r)),"iif",arguments)}function nV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Jx((e=>{let i=t.length,r=i,n=i,s=new Array(i),o=()=>{0==--n&&e.complete()};t.forEach(((t,i)=>{let n=new Gx(e);n.next=t=>{0==--r?(n.next=t=>{s[i]=t,e.next(s)},n.next(t)):s[i]=t},n.complete=o,n.subscribe(t)}))}),"combineLatest",arguments)}function sV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Jx((e=>{let i=t.length,r=i,n=new Array(i),s=()=>{0==--r&&e.complete()};t.forEach(((t,i)=>{let r=new Gx(e),o=[];n[i]=o,r.next=t=>{o.push(t),n.every((e=>e.length))&&e.next(n.map((e=>e.shift())))},r.complete=s,r.subscribe(t)}))}),"zip",arguments)}function oV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>Jx((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)}var aV=Kx(class extends Gx{constructor(e){super(e);let t=new Gx(this.sink);for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];t.next=e=>this.buffer=e,t.complete=Mx,t.subscribe(nV(...r))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},"withLatestFrom"),cV=Kx(class extends Gx{constructor(e,t,i){super(e),this.bufferSize=t,this.startBufferEvery=i,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(e){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach((t=>{t.push(e)})),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(e),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach((e=>this.sink.next(e))),super.complete()}},"bufferCount"),lV=Kx(class extends Gx{constructor(e,t){super(e),this.buffer=[];let i=new Gx(e);i.next=t=>{e.next(this.buffer),this.buffer=[]},i.complete=Mx,i.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),dV=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(dO){s(dO)}}function a(e){try{c(r.throw(e))}catch(dO){s(dO)}}function c(e){e.done?n(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(o,a)}c((r=r.apply(e,t||[])).next())}))};function uV(e){let t=arguments,i=Zx()(Jx((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=Mx,i.complete=Mx,i.error=Mx,i}function hV(e){return Jx((t=>t.subscribe(e())),"defer",arguments)}var pV=e=>t=>{setTimeout((()=>e(t)))},mV=e=>pV((t=>{for(let i=0;!t.disposed&&i<e.length;i++)t.next(e[i]);t.complete()}));function _V(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Jx(mV(t),"of",arguments)}function fV(e){return Jx(mV(e),"fromArray",arguments)}function gV(e){return Jx((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}function EV(e,t){return Jx((i=>{let r=0,n=setTimeout((()=>{if(i.removeDefer(s),i.next(r++),t){let e=setInterval((()=>i.next(r++)),t);i.defer((()=>{clearInterval(e)}))}else i.complete()}),e),s=()=>{clearTimeout(n)};i.defer(s)}),"timer",arguments)}function TV(e,t){return i=>{let r=e=>i.next(e);i.defer((()=>t(r))),e(r)}}function vV(e,t){return Jx(TV(e,t),"fromEventPattern",arguments)}function yV(e,t){if("on"in e&&"off"in e)return Jx(TV((i=>e.on(t,i)),(i=>e.off(t,i))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return Jx(TV((i=>e.addListener(t,i)),(i=>e.removeListener(t,i))),"fromEvent",arguments);if("addEventListener"in e)return Jx(TV((i=>e.addEventListener(t,i)),(i=>e.removeEventListener(t,i))),"fromEvent",arguments);throw"target is not a EventDispachter"}function SV(e){return Jx((t=>{e.then(t.next.bind(t),t.error.bind(t))}),"fromPromise",arguments)}function IV(e,t){return Jx(hV((()=>SV(fetch(e,t)))),"fromFetch",arguments)}function RV(e){return Jx(pV((t=>{try{for(let i of e){if(t.disposed)return;t.next(i)}t.complete()}catch(Db){t.error(Db)}})),"fromIterable",arguments)}function AV(e){let t=i=>dV(this,void 0,void 0,(function*(){if(i.disposed)return;let{done:r,value:n}=yield e.read();r?i.complete():(i.next(n),t(i))}));return Jx((e=>{t(e)}),"fromReader",arguments)}function CV(e){return Jx((t=>{let i=new AbortController,r=i.signal;t.defer((()=>i.abort("cancelled"))),e.pipeTo(new WritableStream({write(e){t.next(e)},close(){t.complete()},abort(e){t.error(e)}}),{signal:r}).then((()=>t.complete()),(e=>t.error(e)))}),"fromReadableStream",arguments)}function bV(){return Jx((e=>{let t=requestAnimationFrame((function i(r){e.disposed||(e.next(r),t=requestAnimationFrame(i))}));e.defer((()=>cancelAnimationFrame(t)))}),"fromAnimationFrame",arguments)}function kV(e,t){return Jx((function(i){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t+e;for(;r<n&&!i.disposed;)i.next(r++);return i.complete(),"range"}),"range",arguments)}function DV(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return Jx((i=>{let n=r.concat((e=>(i.next(e),i.complete())));e.apply(t,n)}),"bindCallback",arguments)}function NV(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return Jx((i=>{let n=r.concat(((e,t)=>e?i.error(e):(i.next(t),i.complete())));e.apply(t,n)}),"bindNodeCallback",arguments)}function wV(){return Jx((()=>{}),"never",arguments)}function OV(e){return Jx((t=>t.error(e)),"throwError",arguments)}function PV(){return Jx((e=>e.complete()),"empty",arguments)}var MV=class extends Gx{constructor(e,t,i){super(e),this.f=t;let r=()=>{this.sink.next(this.acc),this.sink.complete()};void 0===i?this.next=e=>{this.acc=e,this.complete=r,this.resetNext()}:(this.acc=i,this.complete=r)}next(e){this.acc=this.f(this.acc,e)}},LV=Kx(MV,"reduce"),xV=e=>Kx(MV,"count")(((t,i)=>e(i)?t+1:t),0),VV=()=>Kx(MV,"max")(Math.max),UV=()=>Kx(MV,"min")(Math.min),FV=()=>Kx(MV,"sum")(((e,t)=>e+t),0),BV=Kx(class extends Gx{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"),HV=Kx(class extends Gx{next(e){}},"ignoreElements"),GV=Kx(class extends Gx{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&this.complete()}},"take"),WV=Kx(class extends Gx{constructor(e,t){super(e);let i=new Gx(e);i.next=()=>e.complete(),i.complete=Vx,i.subscribe(t)}},"takeUntil"),jV=Kx(class extends Gx{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):this.complete()}},"takeWhile"),JV=e=>LV(((t,i)=>(t.push(i),t.length>e&&t.shift(),t)),[]),KV=Kx(class extends Gx{constructor(e,t){super(e),this.count=t}next(e){0==--this.count&&(this.next=super.next)}},"skip"),qV=Kx(class extends Gx{constructor(e,t){super(e),e.next=Mx;let i=new Gx(e);i.next=()=>{i.dispose(),e.resetNext()},i.complete=Vx,i.subscribe(t)}},"skipUntil"),zV=Kx(class extends Gx{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),YV={leading:!0,trailing:!1},XV=class extends Gx{constructor(e,t,i){super(e),this.durationSelector=t,this.trailing=i}cacheValue(e){this.last=e,this.disposed&&this.throttle(e)}send(e){this.sink.next(e),this.throttle(e)}throttle(e){this.reset(),this.subscribe(this.durationSelector(e))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},QV=class extends Gx{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:YV;super(e),this.durationSelector=t,this.config=i,this._throttle=new XV(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(e){this._throttle.disposed&&this.config.leading?this._throttle.send(e):this._throttle.cacheValue(e)}complete(){this._throttle.throttle=Mx,this._throttle.complete(),super.complete()}},ZV=Kx(QV,"throttle"),$V={leading:!1,trailing:!0},eU=e=>Kx(QV,"audit")(e,$V),tU=class extends Gx{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},iU=class extends Gx{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new tU(this.sink),this._debounce.dispose()}next(e){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=e,this._debounce.subscribe(this.durationSelector(e))}complete(){this._debounce.complete(),super.complete()}},rU=Kx(iU,"debounce"),nU=e=>Kx(iU,"debounceTime")((t=>EV(e))),sU=Kx(class extends Gx{constructor(e,t,i){super(e),this.count=t,this.defaultValue=i}next(e){0==this.count--&&(this.defaultValue=e,this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("not enough elements in sequence"))}},"elementAt"),oU=e=>t=>GV(1)(zV((t=>!e(t)))(t)),aU=Kx(class extends Gx{constructor(e,t){super(e),this.f=t,this.i=0}next(e){this.f(e)?(this.sink.next(this.i++),this.complete()):++this.i}},"findIndex"),cU=Kx(class extends Gx{constructor(e,t,i){super(e),this.f=t,this.defaultValue=i,this.index=0}next(e){(!this.f||this.f(e,this.index++))&&(this.defaultValue=e,this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"first"),lU=Kx(class extends Gx{constructor(e,t,i){super(e),this.f=t,this.defaultValue=i,this.index=0}next(e){(!this.f||this.f(e,this.index++))&&(this.defaultValue=e)}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"last"),dU=Kx(class extends Gx{constructor(e,t){super(e),this.predicate=t,this.index=0}next(e){this.predicate(e,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){void 0!==this.result?(this.sink.next(this.result),super.complete()):this.error(new Error("no elements in sequence"))}},"every"),uU=Kx(class extends Gx{constructor(e,t,i){super(e),this.f=t,void 0===i?this.next=e=>{this.acc=e,this.resetNext(),this.sink.next(this.acc)}:this.acc=i}next(e){this.sink.next(this.acc=this.f(this.acc,e))}},"scan"),hU=Kx(class extends Gx{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},"pairwise"),pU=class extends Gx{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},mU=Kx(pU,"map"),_U=e=>Kx(pU,"mapTo")((t=>e)),fU=class extends Gx{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()}},gU=class extends Gx{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()}},EU=class extends fU{},TU=class extends gU{next(e){this.subInner(e,EU),this.next=e=>{this.currentSink.dispose(),this.subInner(e,EU)}}},vU=Kx(TU,"switchMap");function yU(e){return(t,i)=>e((()=>t),i)}var SU=yU(Kx(TU,"switchMapTo")),IU=class extends fU{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},RU=class extends gU{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(e){this.next2(e),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),IU),this.disposed&&0===this.sources.length&&this.currentSink.resetComplete()}tryComplete(){0===this.sources.length&&this.currentSink.resetComplete(),this.dispose()}},AU=Kx(RU,"concatMap"),CU=yU(Kx(RU,"concatMapTo")),bU=class extends fU{tryComplete(){this.context.inners.delete(this),super.dispose(),0===this.context.inners.size&&this.context.resetComplete()}},kU=class extends gU{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,bU),this.inners.add(this.currentSink)}tryComplete(){1===this.inners.size?this.inners.forEach((e=>e.resetComplete())):this.dispose()}},DU=Kx(kU,"mergeMap"),NU=yU(Kx(kU,"mergeMapTo")),wU=class extends fU{dispose(){this.context.resetNext(),super.dispose()}},OU=class extends gU{next(e){this.next=Mx,this.subInner(e,wU)}},PU=Kx(OU,"exhaustMap"),MU=yU(Kx(OU,"exhaustMapTo")),LU=Kx(class extends Gx{constructor(e,t){super(e),this.f=t,this.groups=new Map}next(e){let t=this.f(e),i=this.groups.get(t);void 0===i&&(i=uV(),i.key=t,this.groups.set(t,i),super.next(i)),i.next(e)}complete(){this.groups.forEach((e=>e.complete())),super.complete()}error(e){this.groups.forEach((t=>t.error(e))),super.error(e)}},"groupBy"),xU=Kx(class extends Gx{constructor(){super(...arguments),this.start=new Date}next(e){this.sink.next({value:e,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},"timeInterval"),VU=Kx(class extends Gx{constructor(e,t){super(e),this.miniseconds=t,this.buffer=[],this.id=setInterval((()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0}),this.miniseconds)}next(e){this.buffer.push(e)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},"bufferTime"),UU=Kx(class extends Gx{constructor(e,t){super(e),this.buffer=[],this.delayTime=t}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(e){this.timeoutId=setTimeout((()=>{let e=this.buffer.shift();if(e){let{time:t,data:i}=e;super.next(i),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}}),e)}next(e){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:e})}complete(){this.timeoutId=setTimeout((()=>super.complete()),this.delayTime)}},"delay"),FU=Kx(class extends Gx{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),BU=()=>e=>new Promise(((t,i)=>{let r;new Wx(e,(e=>r=e),i,(()=>t(r)))})),HU=()=>e=>{let t;return new ReadableStream({start(i){t=new Wx(e,i.enqueue.bind(i),i.error.bind(i),i.close.bind(i))},cancel(){t.dispose()}})},GU=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Mx,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Mx,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Mx;return r=>new Wx(r,e,t,i)},WU=Kx(class extends Gx{constructor(e,t){super(e),t instanceof Function?this.next=i=>{t(i),e.next(i)}:(t.next&&(this.next=i=>{t.next(i),e.next(i)}),t.complete&&(this.complete=()=>{t.complete(),e.complete()}),t.error&&(this.error=i=>{t.error(i),e.error(i)}))}},"tap"),jU=Kx(class extends Gx{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout((()=>this.error(new Xx(this.timeout))),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),JU=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0;return t=>{if(t instanceof Bx){let i=Jx((r=>{let n=e,s=new Gx(r);s.error=e=>{n-- >0?s.subscribe(t):r.error(e)},s.sourceId=i.id,s.subscribe(t)}),"retry",[e]);return i.source=t,Yx.pipe(i),i}return i=>{let r=e,n=new Gx(i);n.error=e=>{r-- >0?t(n):i.error(e)},t(n)}}},KU=class e extends XL{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,nb(this,"tinyId"),nb(this,"isRemote",!0),nb(this,"jitterBufferDelay",0),nb(this,"availableState"),nb(this,"remotePublishState"),nb(this,"_decodeCheckTimeoutId",-1),this.tinyId=t.tinyId,this.availableState=new bM("".concat(t.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new bM("".concat(t.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),jx($x(yV(this,bM.STATECHANGED),yV(this.remotePublishState,bM.STATECHANGED)),mU((()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing))),GU((e=>{this.availableState.state!==(e?bM.ON:bM.OFF)&&(this.availableState.state=e?bM.ON:bM.OFF),this.updatePlayingState(e)})))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&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===e.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===bM.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){let i=this.kind===ik.AUDIO;IP[e?"addSuccessEvent":"addFailedEvent"]({key:i?504700:514702}),e||(IP.addEnum({key:i?504701:514703,value:Xw()}),FM.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(qw()||Qw()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===ik.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," isAvailable: ").concat(this.isRemotePublished," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?bM.ON:bM.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};nb(KU,"STATE_SUBSCRIBE","subscribe"),rb([Ox(5,1)],KU.prototype,"waitHasMediaTrack",1),rb([RM(bM.INIT,KU.STATE_SUBSCRIBE,{success(){var e,t;this.log.info("subscribed"),tO.emit(rO.REMOTE_TRACK_SUBSCRIBED,{track:this}),!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&(this._decodeCheckTimeoutId=setTimeout((()=>{var e,t;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let e=this.kind===ik.AUDIO,t=this.player.isPlaying||(e?this.getAudioLevel()>0:this.stat.framesDecoded>0);this.reportDecodeResult(t)}}),5e3),this.player.once(MM.ERROR,(e=>{e.code===MediaError.MEDIA_ERR_DECODE&&(clearTimeout(this._decodeCheckTimeoutId),this.reportDecodeResult(!1,3))})))},ignoreError:!0}),fx(521716,!1)],KU.prototype,"subscribe",1),rb([RM(KU.STATE_SUBSCRIBE,bM.INIT,{sync:!0,success(){this.log.info("unsubscribed"),tO.emit(rO.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],KU.prototype,"unsubscribe",1);var qU=KU,zU=class extends qU{constructor(e,t){super(e,t,1),nb(this,"volume",0),nb(this,"mediaType",1),nb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}get dbVolume(){return wL.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let t=e;for(let i of this.manager.decodePipeline)if(i&&(t=i({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}},YU=[-1,-1,1,-1,-1,1,1,1],XU=[0,0,1,0,0,1,1,1],QU=class extends bM{constructor(e,t){if(super(),this.context=e,nb(this,"name"),nb(this,"input"),nb(this,"output"),nb(this,"texture"),nb(this,"ctx2d",null),nb(this,"fbo"),nb(this,"width",0),nb(this,"height",0),nb(this,"x",0),nb(this,"y",0),nb(this,"program"),nb(this,"vertexShader"),nb(this,"fragmentShader"),nb(this,"totalFrames",0),nb(this,"dropFrames",0),nb(this,"matchInputSize",!0),nb(this,"texCoordBuffer"),nb(this,"positionBuffer"),nb(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),nb(this,"cost",0),nb(this,"_canvas",null),nb(this,"_image"),nb(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 uF)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==xw?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);else try{let i=e.ctx;this.texCoordBuffer=this.createBuffer(XU),this.positionBuffer=this.createBuffer(YU),!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(mO){this.context.destroy(new vb({code:Eb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(mO.message||mO)}))}}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 dF&&this.render(e)||this.context instanceof uF&&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(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;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 dF){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),"undefined"!=typeof VideoFrame&&e instanceof VideoFrame&&e.close()),!0)}getInfo(){var e;let{totalFrames:t,x:i,y:r,width:n,height:s,name:o,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:s,timestamp:c,fps:l,name:o,cost:a},ZC({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,i=t.createTexture();return this.useTextures(i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};rb([RM(bM.INIT,"connected",{sync:!0})],QU.prototype,"connect",1),rb([RM("connected",bM.INIT,{ignoreError:!0,sync:!0})],QU.prototype,"disconnect",1),rb([RM([],"closed",{sync:!0})],QU.prototype,"close",1);var ZU=jx(gV(250),mU((()=>performance.now())),Zx()),$U=[0,1,1,1,0,0,1,0],eF=class extends QU{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),nb(this,"_intervalId",0),nb(this,"_sequence",0),nb(this,"checkGLError",!1),nb(this,"checkVisibilityChange"),e instanceof uF?this.ctx2d=e.ctx||null:e.available&&null!=t&&t.mirrorUpAndDown&&this.setTexBuffer($U)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),PM.clearTask(this._intervalId),this._intervalId=PM.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(PM.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof dF){let e=this.context.ctx.getError();e&&this.context.destroy(new vb({code:Eb.VIDEO_MANAGER_ERROR,extraCode:5,message:"".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)}))}}),{fps:this.context.frameRate})}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];super.addInput(e,...i),this.start(this.context.frameRate)}update(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(this._intervalId&&(PM.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),PM.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),PM.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},tF=class extends eF{constructor(e,t){super(e,t),nb(this,"_videoTrack"),nb(this,"_muteOb"),nb(this,"_closedOb",yV(this,"closed")),nb(this,"_subscription"),nb(this,"_canvasContainer"),Number(Pw)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=yV(this._videoTrack,"mute"),jx(yV(this._videoTrack,"ended"),WV(this._closedOb),GU((()=>{this.context.destroy(new vb({code:Eb.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){var e;this._subscription=jx(this._muteOb,WV(this._closedOb),SU((e=5e3,t=>{let i=performance.now();jx(ZU,zV((t=>t-i<e)),GV(1))(t)})),GU((()=>{var e;null!=(e=this._videoTrack)&&e.muted&&this.context.destroy(new vb({code:Eb.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))})))}disableCheckMute(){var e;null==(e=this._subscription)||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info("".concat(this.name," put canvas to body")),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack,null==(t=this._canvasContainer)||t.remove()}},iF=class extends tF{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},rF=class extends tF{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))}},nF=class extends QU{constructor(e,t){super(e,ZC({name:"imageSource"},t)),nb(this,"_lastImage"),nb(this,"_totalFrames",0),nb(this,"_autoResize",!1),nb(this,"_canvasRendered"),nb(this,"_videoCallbackId",0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===xw&&(this._canvasRendered=uV(),jx(this._canvasRendered,oV(this._image),vU((e=>e instanceof HTMLCanvasElement?yV(e,"rendered"):PV())),WV(yV(this,"closed")),GU((()=>{this.update()}))))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),fM()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback(((e,t)=>{document.hidden||(this._totalFrames=t.presentedFrames,this.update(1))})))}_render(e,t){var i;let{width:r,height:n}=this,{image:s}=this;if(s instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(s),({videoWidth:r,videoHeight:n}=s),!r||!n)return!1;s.width=r,s.height=n}else if(s instanceof HTMLImageElement||s instanceof ImageData||s instanceof ImageBitmap){if(({width:r,height:n}=s),s!==this._lastImage)this._lastImage=s;else if(r===this.width&&n===this.height)return!1}else s instanceof HTMLCanvasElement||s instanceof OffscreenCanvas?(({width:r,height:n}=s),this._lastImage=s):"undefined"!=typeof VideoFrame&&s instanceof VideoFrame&&(({displayWidth:r,displayHeight:n}=s),null==(i=this._lastImage)||i.close(),this._lastImage=s);if(!this._autoResize)return!0;if(this.width===r&&this.height===n&&this.totalFrames){if(t){this.useTexture();let e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,s)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,s)}this.resize(r,n)}return!0}get image(){return this._image}set image(e){var t;null==(t=this._canvasRendered)||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},sF=class extends nF{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",jx(yV(this._player,MM.PLAYER_STATE_CHANGED),WV(yV(this,"closed")),BV((e=>{let{state:t}=e;return"PLAYING"===t})),GU((()=>{this.tryVideoFrameCallback(this._player.element)})))}get image(){return this._player.element}},oF=class extends sF{constructor(e,t,i){super(e,new hL({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()}},aF=class extends bM{constructor(e){super(),nb(this,"frameRate"),nb(this,"_canvas"),nb(this,"log"),nb(this,"hasAlpha",!1),nb(this,"name"),nb(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 oF(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new tF(this,e)}createVideoImageSource(e,t){return new nF(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new sF(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};nb(aF,"_ids",0);var cF={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},lF=class extends aF{constructor(){super(...arguments),nb(this,"defaultProgam"),nb(this,"defaultVShader"),nb(this,"defaultFShader"),nb(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(aF._ids++)),this.ctx=this._canvas.getContext("webgl2",cF),!this.ctx)throw new vb({code:Eb.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,"\n// 顶点着色器\nattribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main() {\n gl_Position = a_position;\n v_texCoord = a_texCoord;\n}\n"),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,"\n// 片元着色器\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\n\nvoid main() {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n} "),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",(()=>{this.destroy(new vb({code:Eb.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})),this.log.info("video context created use webgl")}destroy(e){let t="";return e&&(t=e.message,this.error=e,IP.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}};nb(lF,"UNAVAILABLE","unavailable"),rb([RM(bM.INIT,"created",{sync:!0,fail(e){IP.addFailedEvent({key:512700,error:e.cause||e})},success(){IP.addSuccessEvent({key:512700})}})],lF.prototype,"create",1),rb([RM("created",bM.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(lF.UNAVAILABLE,e),this.removeAllListeners()}})],lF.prototype,"destroy",1);var dF=lF,uF=class extends aF{constructor(){super(...arguments),nb(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(aF._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new vb({code:Eb.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this.log.info("video context created use 2d")}destroy(e){let t="";e&&(t=e.message,this.error=e,IP.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(),IP.addSuccessEvent({key:512703})}};rb([RM(bM.INIT,"created",{sync:!0,fail(e){IP.addFailedEvent({key:512701,error:e.cause||e})},success(){IP.addSuccessEvent({key:512701})}})],uF.prototype,"create",1),rb([RM("created",bM.INIT,{ignoreError:!0,sync:!0})],uF.prototype,"destroy",1);var hF=class extends qU{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),nb(this,"mediaType",4),nb(this,"source"),nb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager,this.once("first-video-frame",(e=>{this.room.emit("first-video-frame",e)}))}play(e,t){return(bD(null==t?void 0:t.canvasRender)?t.canvasRender:17===xw)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then((()=>{this.player.calculateStat()}))}useCanvasPlayer(){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let e=new uF({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new eF(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),fM()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,i=(r=t,[15,30,45,60].reduce(((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)));var r;!CD(t)||t<=0?this.log.debug("updateCanvasPlayerFPS() ignore decoder: ".concat(t," ")):i!==e.frameRate?(this.log.info("updateCanvasPlayerFPS() decoder: ".concat(t,", closest: ").concat(i,", current: ").concat(e.frameRate)),e.frameRate=i):this.log.debug("updateCanvasPlayerFPS() ignore ClosestFPS ".concat(i," == ").concat(e.frameRate))}get decodeFPS(){var e;let{msg_video_status:t}=(null==(e=this.room.heartbeatReport)?void 0:e.msg_down_stream_info.find((e=>e.msg_user_info.str_identifier===this.userId)))||{},i=2===this.mediaType?7:this.isSmall?3:2;if(!t||0===t.length)return 0;let r=t.find((e=>e.uint32_video_stream_type===i));return(null==r?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&!(e=t({frame:e,track:this})))return;return e}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},pF=class extends hF{constructor(e,t){super(e,t,2),nb(this,"mediaType",2),nb(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},mF=new Map;function _F(e,t){let i=$C(ZC({},t),{timestamp:Sb()});mF.has(e)?mF.get(e).push(i):mF.set(e,[i])}tO.on(rO.JOIN_SUCCESS,(e=>{let{room:t}=e;_F(t.userId,{eventId:32788})})),tO.on(rO.LEAVE_START,(e=>{let{room:t}=e;_F(t.userId,{eventId:32789})})),tO.on(rO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),_F(t.room.userId,{eventId:e})}})),tO.on(rO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),_F(t.room.userId,{eventId:e})}})),tO.on(rO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===ik.AUDIO?_F(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):_F(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),tO.on(rO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===ik.AUDIO?_F(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):_F(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),tO.on(rO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&_F(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&_F(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&_F(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),tO.on(rO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&_F(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&_F(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&_F(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),tO.on(rO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&_F(t.room.userId,{eventId:t.kind===ik.VIDEO?32780:32781})})),tO.on(rO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&_F(t.room.userId,{eventId:t.kind===ik.VIDEO?32782:32783})})),tO.on(rO.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&&_F(i.userId,{eventId:t})})),tO.on(rO.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:n,remoteUserId:s}=e,o=!!s;switch(n){case"CONNECTED":t="RECONNECTING"===r?o?32801:32798:o?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===r&&(t=o?32802:32799);break;case"RECONNECTING":t=o?32800:32797}t&&_F(i.userId,{eventId:t,remoteUserId:s})})),tO.on(rO.VIDEO_CODEC_IMPLEMENTATION_CHANGED,(e=>{let{implementation:t,userId:i,remoteUserId:r,codec:n,isHWCodec:s,prevImplementation:o,streamType:a}=e,c=s?1:0;o||(c=s?3:2);let l="h264"===n?0:2,d={eventId:4004,param1:c,param2:l,streamType:a||2};r&&(d.remoteUserId=r,d.eventId=4005),_F(i,d),IP.addEnum({key:r?514701:513701,value:c}),IP.addEnum({key:r?514700:513700,value:l})})),tO.on(rO.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===ik.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),_F(t.userId,e)}}));var fF=ib(ab(),1),gF=class extends fF.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,nb(this,"userMap",new Map),nb(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 s={userId:i,tinyId:r,role:20===n?"anchor":"audience"};this.userMap.set(t,s),this.emit("1",s)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let r="peer leave [".concat(e,"]");RD(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:s}=e,o=GD(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:o,flag:r}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(o))),this.addUser({userId:n,tinyId:s,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:GD(0,n),muteState:o,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function EF(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return ax(((e,n)=>{let s=new WeakMap;return tO.on(rO.ROOM_DESTROY,(e=>{let{room:t}=e;return s.delete(t)})),function(){let o=s.get(this);for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(o||(o={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,o)),0===o.timestamp?o.timestamp=Date.now():Date.now()-o.timestamp>1e3&&(o.timestamp=Date.now(),o.callCountInSecond=0,o.totalSizeInSecond=0),r&&(o.totalSizeInSecond+=r(...c)),0!==o.timestamp&&Date.now()-o.timestamp<1e3&&(o.callCountInSecond>=t||o.totalSizeInSecond>i))throw new vb({code:Eb.INVALID_OPERATION,message:pP({key:lP.CALL_FREQUENCY_LIMIT,data:{isTimes:o.callCountInSecond>=t,isSize:o.totalSizeInSecond>i,name:n,timesInSecond:t,maxSizeInSecond:i}})});o.callCountInSecond++,e.call(this,...c)}}))}var TF,vF=!0,yF={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",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"},SF={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},IF=((TF=IF||{})[TF.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",TF[TF.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",TF[TF.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",TF[TF.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",TF[TF.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",TF[TF.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",TF[TF.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",TF[TF.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",TF[TF.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",TF[TF.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",TF[TF.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",TF[TF.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",TF[TF.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",TF[TF.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",TF[TF.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",TF[TF.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",TF[TF.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",TF[TF.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",TF[TF.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",TF[TF.INVALID_OPERATION=5100]="INVALID_OPERATION",TF[TF.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",TF[TF.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",TF[TF.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",TF[TF.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",TF[TF.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",TF[TF.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",TF[TF.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",TF[TF.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",TF[TF.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",TF[TF.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",TF[TF.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",TF[TF.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",TF[TF.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",TF[TF.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",TF[TF.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",TF[TF.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",TF[TF.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",TF[TF.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",TF[TF.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",TF[TF.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",TF[TF.DEVICE_ERROR=5300]="DEVICE_ERROR",TF[TF.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",TF[TF.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",TF[TF.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",TF[TF.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",TF[TF.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",TF[TF.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",TF[TF.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",TF[TF.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",TF[TF.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",TF[TF.SERVER_ERROR=5400]="SERVER_ERROR",TF[TF.NEED_TO_BUY=5401]="NEED_TO_BUY",TF[TF.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",TF[TF.OPERATION_FAILED=5500]="OPERATION_FAILED",TF[TF.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",TF[TF.REJOIN_FAILED=5502]="REJOIN_FAILED",TF[TF.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",TF[TF.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",TF[TF.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",TF[TF.OPERATION_ABORT=5998]="OPERATION_ABORT",TF[TF.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",TF);var RF=$C(ZC({},dP),{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,s="".concat(t||i.name),o="";return o=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(s,"' must be type of ").concat(o," when calling ").concat(r,"(), received type: ").concat(SD(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,s="".concat(t||i.name),o="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(s,"' must be instanceof ").concat(o," when calling ").concat(r,"(), received type: ").concat(SD(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: '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=AF(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=AF(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=AF(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=AF(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=AF(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=AF(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=AF(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 AF(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var CF=class e extends Error{constructor(e){let{code:t,extraCode:i,message:r="",messageParams:n,fnName:s="",originError:o}=e;var a;let c;c=r||function(e){let t,{code:i,params:r,enableDocLink:n=!1}=e,o="",a=IF[i];try{t=RF[a]}catch(s){t=RF.UNKNOWN_ERROR}return ID(t)?o=t(r):AD(t)&&(o=t),r.fnName&&!o.includes(r.fnName)&&("."!==o[o.length-1]&&(o+="."),o+=" thrown from ".concat(r.fnName,"()")),n&&(o+=" doc:"),o}({code:t===SF.SERVER_ERROR?t:i||t,params:ZC({fnName:s,error:o},n)}),super(c),nb(this,"name","RtcError"),nb(this,"code"),nb(this,"extraCode"),nb(this,"functionName"),nb(this,"message"),nb(this,"handler"),nb(this,"originError"),this.name=IF[t],this.code=t,this.extraCode=i,this.functionName=s,this.originError=o,this.message=c,5302===this.extraCode&&null!=(a=this.originError)&&a.message.includes("system")&&(this.handler=()=>{let e=document.createElement("a");ow?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):aw&&(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(t,i,r){let n=t;if(t instanceof vb){let{stack:s}=t,o={code:SF.UNKNOWN_ERROR,fnName:i,originError:t};switch(t.getCode()){case Eb.INVALID_PARAMETER:o.code=SF.INVALID_PARAMETER,o.message=t.message;break;case Eb.INVALID_OPERATION:o.code=SF.INVALID_OPERATION;break;case Eb.NOT_SUPPORTED:case Eb.NOT_SUPPORTED_H264:o.code=SF.ENV_NOT_SUPPORTED,t.getCode()===Eb.NOT_SUPPORTED_H264&&(o.extraCode=t.message.includes(dP.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Eb.JOIN_ROOM_FAILED:o.messageParams={fnParams:r};case Eb.SERVER_TIMEOUT:case Eb.SWITCH_ROLE_FAILED:o.code=SF.SERVER_ERROR,o.extraCode=t.getExtraCode();break;case Eb.API_CALL_ABORTED:o.code=SF.OPERATION_ABORT;break;case Eb.DEVICE_NOT_FOUND:case Eb.DEVICE_AUTO_RECOVER_FAILED:case Eb.INITIALIZE_FAILED:o.code=5300,t.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}(t.name));break;case Eb.UNKNOWN:break;default:o.code=SF.OPERATION_FAILED}n=new e(o),s&&(n.stack+=s.substr(s.indexOf("\n")))}else{if(t instanceof e)return t;n=new e({code:SF.UNKNOWN_ERROR,fnName:i,originError:t})}return n}};var bF=CF,kF={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}}},DF={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}}},NF={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(AD(e)&&!document.getElementById(e))throw new bF({code:SF.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},wF={name:"userId",required:!0,type:"string"},OF={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[yF.AUDIO_PROFILE_STANDARD,yF.AUDIO_PROFILE_STANDARD_STEREO,yF.AUDIO_PROFILE_HIGH,yF.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function PF(e,t){if(!e)throw new bF({code:SF.INVALID_OPERATION,extraCode:5101,fnName:t})}function MF(e,t,i){if(!e)throw new bF({code:SF.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var LF={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 bF({code:SF.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(AD(e.roomId))throw new bF({code:SF.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new bF({code:SF.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new bF({code:SF.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new bF({code:SF.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:NF,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:kF},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&wP())throw new bF({code:SF.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:$C(ZC({},NF),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:kF}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:OF},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&wP())throw new bF({code:SF.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:OF}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:NF,publish:{type:"boolean"},option:DF},validate(e,t,i,r,n){var s;if((null==(s=null==e?void 0:e.option)||!s.videoTrack)&&wP())throw new bF({code:SF.ENV_NOT_SUPPORTED,extraCode:5201});if(!VP())throw new bF({code:SF.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:NF,publish:{type:"boolean"},option:DF}},muteRemoteAudio:[wF,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[wF,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:NF,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){PF(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(MF(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new bF({code:SF.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:$C(ZC({},NF),{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){PF(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(MF(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new bF({code:SF.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&&RD(e.streamType))throw new bF({code:SF.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){PF(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(!aM)throw new bF({code:SF.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new bF({code:SF.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new bF({code:SF.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new bF({code:SF.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});PF(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 bF({code:SF.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 bF({code:SF.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new bF({code:SF.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(PF(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new bF({code:SF.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}}},xF={TRTC:LF},VF=class extends Error{};function UF(e,t){let i=KD(e);for(let r=0;r<t.length;r++)JD(i[r],t[r]);return i}function FF(e){this._resolve=Promise.resolve(e)}function BF(e){this._reject=Promise.reject(e)}var HF=class e{constructor(t,i){this.instance=t,this.group=i,nb(this,"started",!1),nb(this,"ops",[]),nb(this,"startSame",(()=>!0)),nb(this,"mergeUpdate",UF);let r=e.instances.get(t);r?r.set(i,this):e.instances.set(t,new Map([[i,this]]))}static get(t,i){if(!i)return;let r=e.instances.get(t);return r&&r.get(i)||new e(t,i)}static gets(t,i){let r=e.instances.get(t),n=[];return r&&r.forEach(((e,t)=>{i.test(t)&&n.push(e)})),n}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 VF("start failed")),null==(r=this.currentOp)||r.action(),t},s={type:e,action:()=>t(...s.args).then(r,n),args:i,resolve:FF,reject:BF};try{switch(this.state){case 1:if(0===e)throw new VF("already started");break;case 4:if(2===e)throw new VF("not started");break;default:return this.cacheOp(s)}}catch(_O){return Promise.reject(_O)}return this.ops.push(s),s.promise=t(...s.args).then(r,n)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new VF("already start");break;case 3:switch(e.type){case 2:throw new VF("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new VF("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new VF("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 VF("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new VF("start not allowed after update");case 0:throw new VF("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new VF("keep start")),new VF("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}};nb(HF,"instances",new WeakMap);var GF=HF,WF=new WeakMap,jF=(e,t)=>{if(t instanceof VF){let{stack:i}=t;t=new bF({code:SF.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function JF(e,t){return ax(((i,r)=>function(){for(var n=arguments.length,s=new Array(n),o=0;o<n;o++)s[o]=arguments[o];let a=GF.get(this,"string"==typeof e?e:e.call(this,...s));return a?(t&&(a.startSame=t.bind(this)),a.action(0,i.bind(this),s).catch(jF.bind(null,r))):i.apply(this,s)}))}function KF(e,t){let{merge:i,debounce:r}=t||{};return ax(((t,n)=>function(){for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];let c=GF.get(this,"string"==typeof e?e:e.call(this,...o));if(!c)return t.apply(this,o);if(i&&(c.mergeUpdate=i.bind(this)),r&&r.isNeedToDebounce.apply(this,o)){let{delay:e,getKey:i}=r;return new Promise(((r,s)=>{var a,l;let d=null==(a=WF.get(this))?void 0:a.get(i(...o));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),o).catch(jF.bind(null,n)).then(r,s)}),e);WF.has(this)?null==(l=WF.get(this))||l.set(i(...o),{timeoutId:u,resolve:r}):WF.set(this,new Map([[i(...o),{timeoutId:u,resolve:r}]]))}))}return c.action(2,t.bind(this),o).catch(jF.bind(null,n))}))}function qF(e){return ax(((t,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];let o="function"==typeof e?e.call(this,...n):e;if(o instanceof RegExp)return Promise.all(GF.gets(this,o).map((e=>e.action(3,(()=>Promise.resolve()),n)))).then((()=>t.call(this,...n)));let a=GF.get(this,o);return a?a.action(3,t.bind(this),n).catch(jF.bind(null,i)):t.apply(this,n)}))}var zF={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame"},YF=new Set([zF.ERROR,zF.AUTOPLAY_FAILED,zF.KICKED_OUT,zF.REMOTE_USER_ENTER,zF.REMOTE_USER_EXIT,zF.REMOTE_AUDIO_AVAILABLE,zF.REMOTE_AUDIO_UNAVAILABLE,zF.REMOTE_VIDEO_AVAILABLE,zF.REMOTE_VIDEO_UNAVAILABLE,zF.CONNECTION_STATE_CHANGED,zF.PUBLISH_STATE_CHANGED,zF.SCREEN_SHARE_STOPPED,zF.DEVICE_CHANGED,zF.FIRST_VIDEO_FRAME]);function XF(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function QF(e){return e===yF.QOS_PREFERENCE_CLEAR?"detail":e===yF.QOS_PREFERENCE_SMOOTH?"motion":""}var ZF={};tb(ZF,{bytes2ms:()=>pD,convertObjectNumberToInt:()=>iN,copyProperties:()=>hD,deepClone:()=>KD,deepMerge:()=>JD,delay:()=>rN,fibonacci:()=>vD,formatedTime:()=>YD,getConstructorName:()=>MD,getContainerFromElement:()=>zD,getEnv:()=>nD,getInternalVersion:()=>FD,getLoggerUrl:()=>oD,getMuteStateFromFlag:()=>GD,getNetworkType:()=>cD,getNumNetworkType:()=>uD,getReconnectionTimeout:()=>yD,getStringByteLength:()=>ZD,getTurnServer:()=>WD,getUint32Version:()=>tN,getValueType:()=>SD,getViewListFromView:()=>qD,glog:()=>gD,ipv4ToUint32:()=>jD,isArray:()=>DD,isAudioWorkletSupported:()=>LD,isBoolean:()=>bD,isConstructor:()=>PD,isEmpty:()=>HD,isFunction:()=>ID,isLangChinese:()=>ED,isMediaStreamTrack:()=>ND,isNumber:()=>CD,isObject:()=>kD,isOverseaSdkAppId:()=>sD,isPlainObject:()=>TD,isPortrait:()=>$D,isPromise:()=>OD,isRemoteTrack:()=>wD,isString:()=>AD,isUndefined:()=>RD,loadImage:()=>eN,ms2bytes:()=>_D,ms2samples:()=>fD,performanceNow:()=>VD,promiseAny:()=>xD,samples2ms:()=>mD,setNetworkType:()=>dD,stringify:()=>XD,stringifyIncludeValue:()=>QD,throttlePromise:()=>nN});var $F={};tb($F,{getAbilityConfigUrl:()=>aB,getScheduleDomain:()=>cB,isNeedToSchedule:()=>tB,scheduleProxy:()=>nB,sendScheduleRequest:()=>rB,setIsNeedToSchedule:()=>iB,setScheduleProxy:()=>sB});var eB=null,tB=!0;function iB(e){bD(e)&&e!==tB&&(tB=e,sO.info("setIsNeedToSchedule ".concat(e)))}function rB(e){return ob(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:n,userSig:s,version:o,frameWorkType:a,role:c,latencyLevel:l}=e;return function*(){if(!tB&&eB)return{isCached:!0,result:eB};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",o),d.append("userSig",String(s)),c&&d.append("role",String(c)),l&&d.append("latencyLevel",String(l)),a&&d.append("frameWorkType",String(a));let u=VD(),h=yield function(e,t,i){return new Promise(((r,n)=>{let s=null;xD([dB((e=>t.count[0]=e+1),(e=>{let{error:r,retry:n,retriedCount:o,retryFuncArgs:a}=e;t.msg[0]=r.message,s||(o>=1&&(a[0]=oB(i,ik.MAIN,!0)),n())}))(oB(i,ik.MAIN),e,{get timeout(){return 1e3*vD(2+t.count[0])}}),dB((e=>t.count[1]=e+1),(e=>{let{error:r,retry:n,retriedCount:o,retryFuncArgs:a}=e;t.msg[1]=r.message,s||(o>=2&&(a[0]=oB(i,ik.BACKUP,!0)),n())}))(oB(i,ik.BACKUP),e,{get timeout(){return 1e3*vD(2+t.count[1])}})]).then((e=>{s=e,r(s)})).catch(n)}))}(d,e,i);h.config&&(h.config.loggerDomain&&Lb(h.config.loggerDomain),bD(h.config.scheduleCache)&&iB(!h.config.scheduleCache)),e.delta=VD()-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"),s=oB(e,ik.MAIN),o=oB(e,ik.BACKUP);for(let e of n)if(e.startTime>=i&&(e.name===s||e.name===o)&&e.transferSize>0){let i=e.name===s?ik.MAIN:ik.BACKUP,n=Math.round(e.duration),o=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];FM.uploadEvent({log:"stat-schedule-net:".concat(n,"(").concat(o,"(").concat(a,"->").concat(c,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=$C(ZC({},r),{totalCost:n,local:o,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(s){sO.error("getScheduleDetailCost error",s)}return r}(Number(i),t,u);return eB=h,{isCached:!1,result:h,detailCost:p}}catch(dO){let t=DD(dO)?dO[0]:dO,i=CD(t.code)?t.code:0,r="schedule failed".concat(t.message?": ".concat(t.message):""),n=new vb({code:Eb.SCHEDULE_FAILED,extraCode:i,message:pP({key:lP.JOIN_ROOM_FAILED,data:{error:r,code:i}})});throw sO.error(r,i),n}}()}))}"undefined"!=typeof document&&document.head.insertAdjacentHTML("beforeend",Object.values(Jk).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),tO.on("28",(()=>iB(!0))),tO.on("63",(()=>iB(!0))),tO.on("84",(()=>iB(!0))),tO.on("201",(e=>{"RECONNECTING"===e.state&&iB(!0)})),tO.on("202",(e=>{"RECONNECTING"===e.state&&iB(!0)}));var nB={main:"",backup:""};function sB(e){DD(e)?(nB.main=e[0],nB.backup=e[1]):nB.main=e}function oB(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ik.MAIN,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return"https://".concat(nB[t]||cB(e,t,i),"/api/v1/config")}function aB(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ik.MAIN;return"https://".concat(nB[t]||cB(e,t),"/api/v1/trtcAutoConf")}function cB(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ik.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=sD(e)?r?i===ik.MAIN?Jk.MAIN_OVERSEA_BACKUP:Jk.BACKUP_OVERSEA:i===ik.MAIN?Jk.MAIN_OVERSEA:Jk.BACKUP_OVERSEA:i===ik.MAIN?Jk.MAIN:Jk.BACKUP,t}function lB(e,t,i){return new Promise(((r,n)=>{sN({url:e,body:t,timeout:i.timeout,priority:"high"}).then((e=>{0===e.data.code?r(e.data.data):n({code:e.data.code,message:e.data.msg})})).catch(n)}))}var dB=(e,t)=>hN({retryFunction:lB,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var uB=class{constructor(){nb(this,"_log"),this._log=sO.createLogger({id:"fd"})}download(e,t){return ob(this,null,(function*(){let{type:i="blob"}=t||{};try{let t,r=VD();if(t=ID(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let n=VD()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(n,"ms")),IP.addSuccessEvent({key:522700,cost:VD()-r}),t.data}catch(mO){throw this._log.error("failed to download: ".concat(e,", error: ").concat(mO)),IP.addFailedEvent({key:522700,error:mO}),mO}}))}downloadWithFetch(e,t){return ob(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(Nk){throw Nk}}))}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 ob(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=VD(),r=null,n=null;if(ID(WebAssembly.instantiateStreaming)&&!e.startsWith("data:application/octet-stream;base64,")&&!(e=>e.startsWith("file://"))(e)&&ID(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(Nb){n=Nb}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(Nb){n=Nb}if(r){let t=VD()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),IP.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),IP.addFailedEvent({key:522701,error:n}),n}))}};rb([HM({settings:{timeout:0,retries:3},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],uB.prototype,"download",1);var hB=new uB;function pB(e){let{TRTC:t,room:i,errorModule:r,assetsPath:n}=e;return{TRTC:t,room:i,assetsPath:n,fileDownloader:hB,innerEmitter:tO,constants:Ab,environment:mN,utils:ZF,eventLogger:FM,log:this.room.getLogger(),loggerManager:sO,errorModule:r,kvStatManager:IP,rtcDectection:cO,trtc:this,rx:Px,enums:lO,schedule:$F,clearStarted:(e,t)=>{let i=e.getAlias(),r=GF.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:Nx,createAudioNode:bL}}var mB=new WeakMap;function _B(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ax(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];try{gB.call(this,t,n,i,this._name)}catch(mO){return Promise.reject(mO)}return e.apply(this,n)}))}function fB(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ax(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];try{gB.call(this,t,n,i,this._name)}catch(mO){throw mO}return e.apply(this,n)}))}function gB(e,t,i,r){if(DD(e))for(let n=0;n<e.length;n++)EB.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else EB.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function EB(e){let{rule:t,value:i,key:r,fnName:n,className:s}=e;function o(e){return{code:SF.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(RD(i)){if(t.required)throw new bF(o(5001));if(RD(t.defaultValue))return void(ID(t.validate)&&t.validate.call(this,i,r,n,s,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),ID(t.type[r])&&i instanceof t.type[r]&&(e=!0),AD(t.type[r])&&SD(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new bF({code:SF.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>PD(e)?MD(e):AD(e)?e:SD(e)))},value:i}})}else if(!RD(t.type)&&SD(i)!==t.type)throw new bF(o(5002));if(!1===t.allowEmpty){let e=CD(i)&&(0===i||Number.isNaN(i)),t=AD(i)&&""===i.trim();if(e||t)throw new bF(o(5003))}if(t.notLessThanZero&&CD(i)&&i<0)throw new bF(o(5006));if(!RD(t.min)&&CD(i)&&i<t.min)throw new bF(o(5007));if(!RD(t.max)&&CD(i)&&i>t.max)throw new bF(o(5008));if(AD(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new bF(o(5004))}else if(ID(t.instanceOf)&&!(i instanceof t.instanceOf))throw new bF(o(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new bF(o(5005));let{properties:a}=t;TD(a)&&kD(i)&&Object.keys(a).forEach((e=>{EB.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:s})}));let{arrayItem:c}=t;TD(c)&&DD(i)&&i.forEach(((e,t)=>{EB.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:s})})),ID(t.validate)&&t.validate.call(this,i,r,n,s,this)}function TB(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r,ignoreLog:n}=e;return ax(((e,s)=>function(){for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];var l;function d(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...a);if(a[e.argIndex]===t)return e.value}if(t===a||e in a)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(SD(t)):(JSON.stringify(t),t)}catch(TO){return"type:".concat(SD(t))}}let u=this._log||sO;if(null!=n&&n(...a))return e.apply(this,a);a.length>0?u.info("".concat(s,"() ").concat(JSON.stringify(a,((e,t)=>d(e,t,["userSig","privateMapKey"]))))):u.info("".concat(s,"()"));let h=r?r(...a):gP[s];try{let i=e.apply(this,a),r=VD();return OD(i)?i.then((e=>(u.info("".concat(s,"() success ").concat(t.call(this,...a))),IP.addSuccessEvent({key:h,cost:VD()-r}),e))).catch((e=>{var i;let r=(e=bF.convertFrom.call(this,e,s,1===a.length?a[0]:a)).extraCode||e.code,n=null!=(i=e.message)&&i.includes(r)?"":" code:".concat(r);throw u.error("".concat(s,"() failed ").concat(t.call(this,...a)," ").concat(e).concat(n," params: ").concat(JSON.stringify(a,d))),IP.addFailedEvent({key:h,error:e}),e})):(IP.addSuccessEvent({key:h}),i)}catch(p){let e=(p=bF.convertFrom.call(this,p,s)).extraCode||p.code,t=null!=(l=p.message)&&l.includes(e)?"":" code:".concat(e);throw u.error("".concat(s,"() failed ").concat(p).concat(t," params: ").concat(JSON.stringify(a,d))),IP.addFailedEvent({key:h,error:p}),p}}))}var vB=e=>ax(((t,i)=>function(r,n){return ob(this,null,(function*(){let s=this._plugins.get(r);if(!s)throw this._log.error("plugin ".concat(String(r)," is not found")),new bF({code:SF.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(ID(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new bF({code:SF.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return gB.call(this,s.getValidateRule(e),[n],i,"TRTC"),t.call(this,s,n)}))})),yB=0,SB=class{constructor(e,t){nb(this,"player"),nb(this,"publisher"),nb(this,"mixInput"),this.mixInput=new RL(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&&(RD(e.volume)||(this.volume=e.volume),RD(e.loop)||(this.loop=e.loop),RD(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 IB(e,t){if(t&&"function"!=typeof t)throw new bF({code:SF.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var RB=class e{constructor(e){this.core=e,nb(this,"log"),nb(this,"mixedMusicMap",new Map),nb(this,"cacheMusicMap",new Map),yB+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(yB)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat(yB)),this.core=e}getName(){return e.Name}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(t){switch(t){case"start":return e.startValidateRule;case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return ob(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 SB(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.")),IP.addEnum({key:502700,value:3}),this.kvUpload(e)}))}update(e){return ob(this,null,(function*(){let{id:t,operation:i,seekFrom:r,playbackRate:n}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let s=this.mixedMusicMap.get(t);s?(s.updateSettings(e),s.updateListener(e),RD(i)||s.setOperation(i),RD(r)||s.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return ob(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:s,seekFrom:o,onTimeUpdate:a,onDurationChange:c,onEnded:l}=e;t&&IP.addCount({key:502711}),i&&IP.addCount({key:502703}),r&&IP.addCount({key:502704}),n&&IP.addCount({key:502705}),s&&IP.addCount({key:502706}),o&&IP.addCount({key:502707}),"function"!=typeof a&&IP.addCount({key:502709}),"function"!=typeof l&&IP.addCount({key:502710}),"function"!=typeof c&&IP.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()}};nb(RB,"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(),s=r.indexOf(n)>=0,o=t.startsWith("blob"),a=t.startsWith("data");if(!(s||o||a))throw new bF({code:SF.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new bF({code:SF.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});IB("onTimeUpdate",e.onTimeUpdate),IB("onEnded",e.onEnded),IB("onDurationChange",e.onDurationChange)}}),nb(RB,"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){IB("onTimeUpdate",e.onTimeUpdate),IB("onEnded",e.onEnded),IB("onDurationChange",e.onDurationChange)}}),nb(RB,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),nb(RB,"Name","AudioMixer");var AB,CB=RB,bB=0,kB=class e{constructor(e){this.core=e,nb(this,"log"),nb(this,"audioContext",vL()),nb(this,"workletNode"),bB+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(bB)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(bB)),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 bF({code:SF.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return AB||(AB=this.doPreload(e)),AB}doPreload(e){return ob(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield pL(this.audioContext,i)}finally{URL.revokeObjectURL(i)}}))}getName(){return e.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(t){switch(t){case"start":return e.startValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return ob(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:s}=yield function(e){return ob(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:r,timestamp:n}=e;return function*(){let e="".concat(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ik.MAIN;return"https://".concat(nB[t]||cB(e,t),"/api/v1/audioAiAuth")}(t),"?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(r,"×tamp=").concat(n),s=yield fetch(e),{data:{errCode:o,errMsg:a,sign:c,status:l}}=yield s.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d="Init RTCAIDenoiser failed.",u="";switch(o){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)}}()}))}($C(ZC({},e),{timestamp:t}));if(!i)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(i,". Message: ").concat(s)),new bF({code:SF.INVALID_PARAMETER,message:s});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 ob(this,null,(function*(){}))}stop(){return ob(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)}};nb(kB,"updateValidateRule",{type:"object"}),nb(kB,"stopValidateRule",{type:"object"}),nb(kB,"Name","AIDenoiser");var DB=kB;var NB=ib(ab(),1),wB=class extends NB.EventEmitter{constructor(){super(),nb(this,"observer"),nb(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 ob(this,null,(function*(){if(!this.observer)try{"PressureObserver"in window&&!CN&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(Db){FM.uploadEvent({log:"stat-pressure-detector-start-failed",error:Db})}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&sO.info("".concat(i.source,": ").concat(i.state)),this.emit("state-changed",{type:i.source,state:this.state})}destroy(){var e;try{null==(e=this.observer)||e.disconnect(),this.observer=null}catch(Nk){FM.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:Nk})}}},OB=new wB;function PB(e){let[t,i]=e,r=i.byteLength,n=parseInt(String(r/255),10),s=r%255,o=[];o.push(0,0,0,1,6,t);for(let c=0;c<n;c++)o.push(255);o.push(s);let a=new DataView(i);return o.push(...new Uint8Array(a.buffer)),o.push(128),new yx(new DataView(new Uint8Array(o).buffer),!0)}function MB(e){return"empty"===e.type||0===e.data.byteLength}function LB(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}function xB(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 VB(e){let{frame:t,seiMessageList:i}=e;if(!i||0===i.length||0===t.data.byteLength)return t;let r=9-xB(t.data);if(r<=0)return t;let n=i.splice(0,r).reverse().map(PB),s=n.reduce(((e,t)=>e+t.dataView.byteLength),0),o=new ArrayBuffer(s+t.data.byteLength),a=new DataView(o),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=o,t}function UB(e){let{frame:t,onSEI:i}=e;try{let e=new DataView(t.data);if(MB(t)||!LB(e))return t;let r=[],n=0,s=-1,o=-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===s?s=a:-1===o&&(o=a,r.push(new yx(new DataView(e.buffer.slice(s,o)))),s=a,o=-1),6!==e.getUint8(i+1)){t.data=e.buffer.slice(a);break}}n=0}else n=0}null==i||i(r.reverse())}catch(Db){}return t}var FB=0,BB=class e{constructor(e){this.core=e,nb(this,"log"),nb(this,"_seiMessageList",[]),nb(this,"_smallSeiMessageList",[]),nb(this,"_subStreamSeiMessageList",[]),FB++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(FB)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(FB)),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 VB({frame:t,seiMessageList:8===i?this._smallSeiMessageList:2===i?this._subStreamSeiMessageList:this._seiMessageList})}catch(Nk){this.log.warn(Nk)}return t}decode(e){let{frame:t,track:i}=e;return UB({frame:t,onSEI:e=>{e.forEach((e=>{this.core.trtc.emit(zF.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:sM?this.encode:VB,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:sM?this.decode:UB,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update(e){let{buffer:t,options:i}=e;var r;let n=[i.seiPayloadType,t],s=!!i.small;i.toSubStream?this._subStreamSeiMessageList.push(n):(this._seiMessageList.push(n),s&&this._smallSeiMessageList.push(n)),null==(r=this.core.room.scriptTransformWorker)||r.postMessage({type:"sei",data:n,isMain:!i.toSubStream,small:s})}getName(){return e.Name}getAlias(){return"sei"}getGroup(){return"sei"}};nb(BB,"autoStart",!0),nb(BB,"Name","SEI");var HB=BB;function GB(e){let{frame:t,onDump:i}=e;return null==i||i(),t}function WB(e){let{frame:t,onDump:i}=e;return null==i||i(),t}var jB={"play() error: NotAllowedError:":{tips:e=>e.includes("main <video>")||e.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:e=>e.includes("↓")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:e=>e.includes("↓")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:"The remote stream audio playback is paused, which usually has two possibilities:\n 1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.\n 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.",color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:"The remote stream video playback is paused, which usually has two possibilities:\n 1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.\n 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.",color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach((e=>{jB["".concat(e,"()")]={tips:"Call trtc.".concat(e),color:"blue",class:"blue",textColor:"#fff"}}));var JB,KB=0,qB=class e{constructor(e){this.core=e,nb(this,"_core"),nb(this,"log"),nb(this,"dumpLocalVideoMap",{}),nb(this,"dumpRemoteVideoMap",{}),nb(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++KB)}),this.log.info("created")}getName(){return e.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 ob(this,null,(function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&"true"!==(null==(e=window.sessionStorage)?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))||(yield this.openDebugDiaLog(),this.addVideoProcessor())}))}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return ob(this,null,(function*(){try{if(JB)yield JB;else{let e=Date.now(),t=new URLSearchParams(location.search).get("trtcDebugDialogVersion")||bb;JB=this.loadScript("https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@".concat(t,".js")),yield JB,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(pO){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(pO))}}))}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):GB,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):WB,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo(e){let{frame:t,mediaType:i}=e;return GB({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 WB({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())}})}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)}))}};nb(qB,"Name","Debug"),nb(qB,"autoStart",!0),rb([HM({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)}})],qB.prototype,"loadScript",1);var zB=qB,YB=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},XB=class{constructor(e,t,i){nb(this,"trackDoneOB"),nb(this,"startOB"),nb(this,"stopOB"),nb(this,"inputFrameCount",0),nb(this,"decodedFrameCount",0),nb(this,"type","auto"),nb(this,"config"),nb(this,"decoder"),nb(this,"_decodeSink");let{kvStatManager:r,trtc:n}=e;this.config=i.config,this.trackDoneOB=yV(t,bM.INIT),this.stopOB=uV(this.trackDoneOB),this.startOB=uV(),"auto"===i.type?this.type="webCodecs":this.type=i.type;let s=uV();jx(this.startOB,oV(0),vU((e=>{let i=this.pipe(t);return s.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),jx(i,WV(this.stopOB),GU((()=>{}),(i=>{t.log.error(i),r.addFailedEvent({key:YB(this.type),error:i}),e>4?this.startOB.error(i):this.startOB.next(e+1)}))),jx(i,GV(1),FU(PV))})),WV(this.stopOB),GU((()=>{t.player.setOutput(),s.next("STARTED")}),(e=>{s.next("FAILED")}),(()=>{r.addSuccessEvent({key:YB(this.type)}),r.addSuccessEvent({key:504702})})))}mock(e){this._decodeSink?this._decodeSink.error(e):this.startOB.next(0)}close(e){this.stopOB.next(e)}pipe(e){return Zx()((t=>ob(this,null,(function*(){this._decodeSink=t,t.defer((()=>{var e;null==(e=this.decoder)||e.close()}));let{type:i}=this;try{if("webCodecs"===i)this.decoder=new AudioDecoder({error:i=>{e.log.error(i),t.error(4)},output:i=>{this.decodedFrameCount++,t.next(i),e.player.write(i)}});this.decoder.configure(this.config)}catch(mO){e.log.error(mO),t.error("webCodecs"===i?2:6)}}))))}decodeFrame(e){var t;this.inputFrameCount++,"configured"===(null==(t=this.decoder)?void 0:t.state)&&this.decoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"}))}},QB={type:"object"},ZB=class e{constructor(e){this.core=e,nb(this,"log"),nb(this,"contextMap",new Map),nb(this,"decodeProcessorMap",new WeakMap),this.log=e.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return e.Name}getGroup(e){return e.track.userId+e.track.streamType}getName(){return e.Name}getValidateRule(e){return QB}start(e){let{track:t}=e;this.decodeProcessorMap.set(t,this.decode(e)),this.core.room.audioManager.addDecodeProcessor({processor:e=>{let{frame:t,track:i}=e;return this.decodeProcessorMap.has(i)?this.decodeProcessorMap.get(i)({frame:t,track:i}):t},type:3})}decode(e){return t=>{let{frame:i,track:r}=t;if(r!==e.track)return i;if(this.contextMap.has(r))return this.contextMap.get(r).decodeFrame(i);let n=new XB(this.core,r,e);return jx(n.trackDoneOB,GV(1),GU((()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:r})}))),this.contextMap.set(r,n),n.decodeFrame(i)}}stop(e){let{track:t}=e,i=this.contextMap.get(t);i&&(i.close("stop"),this.contextMap.delete(t),0===this.contextMap.size&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(e){let t=this.contextMap.get(e.track);if(t){if("mock"===e.type)return void t.mock(10);t.close("update"),this.contextMap.set(e.track,new XB(this.core,e.track,e))}}};nb(ZB,"Name","TRTCAudioDecoder");var $B=ZB,eH=0,tH=new Set,iH=null;kb("5.9.2-beta.5"),aO.checkStorage(),_M();var rH={RtcError:bF,ErrorCode:SF,ErrorCodeDictionary:IF},nH=class e extends fb.EventEmitter{constructor(t,i){super(),nb(this,"_room"),nb(this,"_eventListened",new Set),nb(this,"_localVideoTrack",null),nb(this,"_localAudioTrack",null),nb(this,"_localScreenTrack",null),nb(this,"_localScreenAudioTrack",null),nb(this,"_localVideoConfig",null),nb(this,"_localScreenConfig",null),nb(this,"_localAudioConfig",null),nb(this,"_remoteVideoConfigMap",new Map),nb(this,"_remoteAudioConfigMap",new Map),nb(this,"_remoteAudioVolumeMap",new Map),nb(this,"_remoteAudioMuteMap",new Map),nb(this,"_mediaTrackMap",new WeakMap),nb(this,"_log",sO.createLogger({id:"t".concat(++eH)})),nb(this,"_plugins",new Map),nb(this,"_networkQuality",null),nb(this,"_speakerId"),nb(this,"_getPCMAbortCtrl"),this._room=new t(ZC({logger:this._log,frameWorkType:e.frameWorkType},i)),this._room.videoDecodeFallbackType=i.videoDecodeFallback,this._log.debug("TRTC.create() ".concat(JSON.stringify(i,((e,t)=>"plugins"===e?t.map((e=>e.Name)):t)))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(e){return this._room.audioManager.dump(e)}}}),i.plugins&&i.plugins.forEach((e=>{this._use(e,i.assetsPath)})),this._use(CB,i.assetsPath),this._use(DB,i.assetsPath),this._use($B,i.assetsPath||Hb),this._use(zB),i.enableSEI&&aM&&this._use(HB),this._room.on("audio-volume",(e=>{!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*this._localAudioTrack.getAudioLevel())}),1===i.volumeType&&e.forEach((e=>{var t;let i=""===e.userId?this._localAudioTrack:null==(t=this.room.remotePublishedUserMap.get(e.userId))?void 0:t.remoteAudioTrack;i&&(e.volume=i.dbVolume)})),this.emit(zF.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{this._log.error(new bF({code:SF.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),s=0;s<r;s++)n[s]=arguments[s];try{return i.apply(e,n)}catch(mO){let i=pP({key:lP.CATCH_HANDLER_ERROR,data:{name:t,event:n[0]},addDocLink:!1});return sO.warn("".concat(i,"\n\n").concat(mO.stack)),!1}}})(this,"trtc")}static create(e){}static _create(t,i){var r;vF&&(vF=!1,5!==sO.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Bb,"/en/index.html")),console.info("* Changelog: ".concat(Bb,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),sO.info("TRTC Web SDK Version:",bb),Bw||sO.debug("Build Time:","2025-03-27 20:39:38"),sO.info("UA:",navigator.userAgent),sO.info("URL: ".concat(location.href).concat("IFRAME"===(null==(r=self.frameElement)?void 0:r.tagName)?" in iframe":"")),Kw().then((e=>{e&&sO.info(Jw)})));let n=new e(t,i||{});return tH.add(n),n}get room(){return this._room}_listenEvents(){VM(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(zF.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(zF.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)})).add("banned",(e=>{this._exitRoom().finally((()=>{this.emit(zF.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().finally((()=>{this.emit(zF.ERROR,bF.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(zF.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e;let t=$C(ZC({},e),{uplinkRTT:Math.min(e.uplinkRTT,rD),downlinkRTT:Math.min(e.downlinkRTT,rD)});this.emit(zF.NETWORK_QUALITY,t)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{VM(t,t).add("player-state-changed",(i=>{let r=$C(ZC({},i),{userId:e.userId});t.kind===ik.VIDEO&&(r.streamType=XF(t.streamType)),this.emit(t.kind===ik.AUDIO?zF.AUDIO_PLAY_STATE_CHANGED:zF.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===Eb.PLAY_NOT_ALLOWED&&this.emit(zF.AUTOPLAY_FAILED,{userId:t.userId,resume:()=>t.player.resume()})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{UM(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:r}=i,n=t.audioAvailable,s=t.videoAvailable,{audioAvailable:o,videoAvailable:a}=i;o||this._remoteAudioConfigMap.delete(r),a||this._remoteVideoConfigMap.delete("".concat(r,"_main")),i.hasAuxiliary||this._remoteVideoConfigMap.delete("".concat(r,"_sub")),s!==a&&(a?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(a?zF.REMOTE_VIDEO_AVAILABLE:zF.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),n!==o&&(o?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i}),this.emit(o?zF.REMOTE_AUDIO_AVAILABLE:zF.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),t.hasAuxiliary!==i.hasAuxiliary&&(i.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(i.hasAuxiliary?zF.REMOTE_VIDEO_AVAILABLE:zF.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))})).add("sei-message",(e=>{this.emit(zF.SEI_MESSAGE,$C(ZC({},e),{streamType:XF(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(zF.ERROR,new bF({code:SF.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,i,r,n,s,o,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,rD),upLoss:(null==(n=this._networkQuality)?void 0:n.uplinkLoss)||0,downLoss:(null==(s=this._networkQuality)?void 0:s.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(o=e.msg_up_stream_info.msg_audio_status)?void 0:o.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/$O},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)/$O},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(zF.STATISTICS,l)})).add("custom-message",(e=>{this.emit(zF.CUSTOM_MESSAGE,e)})).add("layerData",(e=>this.emit(zF.LAYER_DATA,e))).add("first-video-frame",(e=>{this.emit(zF.FIRST_VIDEO_FRAME,$C(ZC({},e),{streamType:XF(e.streamType)}))})),VM(this,xL).add("audioInputAdded",(e=>{this.emit(zF.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(zF.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(zF.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(zF.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>ob(this,null,(function*(){if(this.emit(zF.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),iH&&iH.deviceId===Xk){let e=(yield GL()).find((e=>e.deviceId===Xk));e&&iH.groupId!==e.groupId&&(iH=e,this.emit(zF.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>ob(this,null,(function*(){this.emit(zF.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield GL())[0];if(!t||!iH||iH.groupId===t.groupId)return;let i=iH.deviceId===e.deviceId,r=iH.deviceId===Xk&&iH.deviceId===t.deviceId;(i||r)&&(iH=t,this.emit(zF.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||Hb)}_use(t,i){if(this._plugins.get(t.Name))return void this._log.warn("duplicate install plugin",t.Name);let r=new t(pB.call(this,{TRTC:e,room:this._room,errorModule:rH,assetsPath:i}));this._plugins.set(t.Name,r),t.autoStart&&this.startPlugin(t.Name)}enterRoom(t){return ob(this,null,(function*(){var i,r;let{scene:n="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:o=!0,autoReceiveVideo:a=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!AD(t.proxy)&&t.proxy.turnServer&&(null==(r=(i=this._room).setTurnServer)||r.call(i,t.proxy.turnServer,t.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=a,bD(t.preferHW)&&(this._room.preferHW=t.preferHW);let c={sdkAppId:t.sdkAppId,userId:t.userId,userSig:t.userSig,privateMapKey:t.privateMapKey||null,latencyLevel:t.latencyLevel,role:"audience"===t.role?21:20,roomId:t.roomId||0,strRoomId:t.strRoomId||"",businessInfo:t.businessInfo||null,streamId:null,userDefineRecordId:t.userDefineRecordId||null,frameWorkType:t.frameWorkType,component:t.component,language:t.language,priority:t.priority,useVp8:t.useVp8};t.strRoomId&&!t.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(c,n,e.frameWorkType),this._checkTrackToPublish(),OB.start()}))}exitRoom(){return ob(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return ob(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(){UM(this),this.removeAllListeners(),this._room.destroy(),tH.delete(this),0===tH.size&&OB.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)})),this._plugins.clear(),tO.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return ob(this,arguments,(function(){var t=this;let i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(t._localAudioTrack)return void t._log.warn("local audio is already started");let{publish:r=!0,mute:n,option:s}=i,o=new vx(t._room.audioManager),a={},c={muted:!0};s&&(RD(s.microphoneId)?RD(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&CD(s.captureVolume)&&o.setCaptureVolume(s.captureVolume),RD(s.profile)||(AD(s.profile)?$b[s.profile]&&o.setProfile($b[s.profile]):o.setProfile(s.profile)),CD(s.earMonitorVolume)&&(c.muted=!(s.earMonitorVolume>0),c.volume=s.earMonitorVolume),RD(s.echoCancellation)||(o.profile.echoCancellation=s.echoCancellation),RD(s.noiseSuppression)||(o.profile.noiseSuppression=s.noiseSuppression),RD(s.autoGainControl)||(o.profile.autoGainControl=s.autoGainControl)),o.on("5",(e=>{t.emit(zF.ERROR,new bF({code:SF.DEVICE_ERROR,extraCode:5309,messageParams:{error:e}}))})),o.on("2",(e=>{t.emit(zF.DEVICE_CHANGED,{type:"microphone",action:"active",device:e})})),o.on("4",(e=>{let i;e.error&&(i=bF.convertFrom(e.error)),t.emit(zF.PUBLISH_STATE_CHANGED,$C(ZC({},e),{error:i}))})),t._listenOutputTrackChanged(o),t._speakerId&&o.setAudioOutput(t._speakerId),yield o.capture(a),RD(n)||o.setMute(n),VM(o,o).add("player-state-changed",(e=>{t.emit(zF.AUDIO_PLAY_STATE_CHANGED,$C(ZC({},e),{userId:""}))})),t.listeners(zF.AUDIO_FRAME).length>0&&(t._getPCMAbortCtrl=t._room.audioManager.getPCM((i=>{t.emit(e.EVENT.AUDIO_FRAME,{data:i})}))),t._getPCMAbortCtrl&&o.on("input-media-track-changed",(()=>{t._getPCMAbortCtrl&&(t._getPCMAbortCtrl.abort("inputMediaTrackChanged"),t._getPCMAbortCtrl=t._room.audioManager.getPCM((i=>{t.emit(e.EVENT.AUDIO_FRAME,{data:i})})))})),r&&t._room.isJoined&&t._room.publish(o).catch((()=>{})),t._localAudioTrack=o,t._localAudioConfig=$C(ZC({},i),{publish:r}),yield t._updateAudioPlayOption({playOption:c,track:o})}()}))}updateLocalAudio(e){return ob(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):RD(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),RD(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),RD(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!RD(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),RD(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),JD(this._localAudioConfig,e)}))}stopLocalAudio(){return ob(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),UM(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))}))}startLocalVideo(){return ob(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:s}=t,o=new Rx(e._room.videoManager),a={},c={};s&&(s.cameraId?a.deviceId=s.cameraId:RD(s.useFrontCamera)?RD(s.videoTrack)||(a.customSource=s.videoTrack):a.facingMode=s.useFrontCamera?ik.FACING_MODE_USER:ik.FACING_MODE_ENVIRONMENT,s.qosPreference&&(a.contentHint=QF(s.qosPreference)),RD(s.profile)||(AD(s.profile)?ek[s.profile]&&o.setProfile(ek[s.profile]):o.setProfile(s.profile)),RD(s.fillMode)||(c.objectFit=s.fillMode),RD(s.mirror)||(c.mirror=s.mirror),RD(s.small)||(JP()?AD(s.small)?o.small=ek[s.small]:!0===s.small?o.small=ek["120p"]:o.small=s.small:e._log.warn("small stream is not supported"))),o.once("first-video-frame",(t=>{e.emit(zF.FIRST_VIDEO_FRAME,$C(ZC({},t),{streamType:XF(t.streamType)}))})),o.on("5",(t=>{e.emit(zF.ERROR,new bF({code:SF.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(zF.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=bF.convertFrom(t.error)),e.emit(zF.PUBLISH_STATE_CHANGED,$C(ZC({},t),{error:i}))})),e._listenOutputTrackChanged(o),yield o.capture(a),RD(n)||(yield o.setMute(n)),VM(o,o).add("player-state-changed",(t=>{e.emit(zF.VIDEO_PLAY_STATE_CHANGED,$C(ZC({},t),{userId:"",streamType:"main"}))})),r&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localVideoTrack=o,e._localVideoConfig=$C(ZC({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:o})}()}))}updateLocalVideo(e){return ob(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:r,option:n}=e,s={};if(n)if(RD(n.profile)||(AD(n.profile)?ek[n.profile]&&this._localVideoTrack.setProfile(ek[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&RD(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):RD(n.useFrontCamera)?RD(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?ik.FACING_MODE_USER:ik.FACING_MODE_ENVIRONMENT),RD(n.fillMode)||(s.objectFit=n.fillMode),RD(n.mirror)||(s.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(QF(n.qosPreference)),n.small){let e=!this._localVideoTrack.small;JP()?(!0===n.small?this._localVideoTrack.small=ek["120p"]:AD(n.small)?this._localVideoTrack.small=ek[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&&!RD(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),RD(r)||(yield this._localVideoTrack.setMute(r)),yield this._updateVideoPlayOption({view:t,playOption:s,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),JD(this._localVideoConfig,e)}))}stopLocalVideo(){return ob(this,null,(function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),UM(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return ob(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,s=new bx(e._room.videoManager);s.on("4",(t=>{let i;t.error&&(i=bF.convertFrom(t.error)),e.emit(zF.PUBLISH_STATE_CHANGED,$C(ZC({},t),{error:i}))})),s.once("first-video-frame",(t=>{e.emit(zF.FIRST_VIDEO_FRAME,$C(ZC({},t),{streamType:XF(t.streamType)}))})),e._listenOutputTrackChanged(s),"main"===t.streamType&&(s.mediaType=4);let o=null,a={},c={};n&&(RD(n.profile)||(AD(n.profile)?tk[n.profile]&&s.setProfile(tk[n.profile]):s.setProfile(n.profile)),n.systemAudio&&(a.systemAudio=!0,a.echoCancellation=n.echoCancellation,a.noiseSuppression=n.noiseSuppression,a.autoGainControl=n.autoGainControl),RD(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),n.qosPreference&&(a.contentHint=QF(n.qosPreference)));let l=yield s.capture(a);if(s.mediaTrack.addEventListener(ik.ENDED,(()=>{e._stopScreenShare(),e.emit(zF.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(o=new Dx(e._room.audioManager),yield o.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&o.setAudioOutput(e._speakerId)),VM(s,s).add("player-state-changed",(t=>{e.emit(zF.VIDEO_PLAY_STATE_CHANGED,$C(ZC({},t),{userId:"",streamType:"sub"}))})),r&&e._room.isJoined){let t=[s];o&&t.push(o),e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=s,e._localScreenAudioTrack=o,e._localScreenConfig=$C(ZC({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:s})}()}))}updateScreenShare(e){return ob(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(RD(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let e=QF(r.qosPreference);this._localScreenTrack.setContentHint(e)}this._room.isJoined&&!RD(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}),JD(this._localScreenConfig,e)}))}stopScreenShare(){return ob(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return ob(this,null,(function*(){let{view:t,userId:i,streamType:r,option:n}=e,s="".concat(i,"_").concat(r);if(this._remoteVideoConfigMap.has(s))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(r));let o=this._room.remotePublishedUserMap.get(i);if(!o)return;let a={},c="main"===r?o.remoteVideoTrack:o.remoteAuxiliaryTrack;this._listenOutputTrackChanged(c),n&&(RD(n.fillMode)||(a.objectFit=n.fillMode),RD(n.mirror)||(a.mirror=n.mirror),RD(n.poster)||(a.poster=n.poster),a.canvasRender=n.canvasRender,"main"===r&&!RD(n.small)&&(!o.remoteVideoTrack.isSubscribing&&!o.remoteVideoTrack.isSubscribed&&o.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,c.user))),yield this._room.subscribe(c),yield this._enableVideoDecodeFallback(c,r),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._emitTrackEvent(c),this._remoteVideoConfigMap.set(s,{config:e}),n&&!RD(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return ob(this,null,(function*(){var t,i;let{view:r,userId:n,streamType:s,option:o}=e,a="".concat(n,"_").concat(s),c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(n))return;let l={};o&&(RD(o.fillMode)||(l.objectFit=o.fillMode),RD(o.mirror)||(l.mirror=o.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);if("main"===s&&null!=u&&u.muteState.hasVideo&&(d=u.remoteVideoTrack),"sub"===s&&null!=u&&u.muteState.hasAuxiliary&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:h}=c;"main"===s&&o&&!RD(o.small)&&this._room.changeType(o.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:h}),JD(h,e);let p=RD(null==o?void 0:o.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:o.receiveWhenViewVisible,m=RD(r)?h.view:r,_=RD(null==o?void 0:o.viewRoot)?null==(i=h.option)?void 0:i.viewRoot:o.viewRoot;this._observeView({remoteTrack:d,view:m,receiveWhenViewVisible:p,viewRoot:_})}))}stopRemoteVideo(e){return ob(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return ob(this,null,(function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:n,remoteAuxiliaryTrack:s}=r;"main"===e.streamType&&(n.stop(),t.hasVideo&&i.push(n)),"sub"===e.streamType&&(s.stop(),t.hasAuxiliary&&i.push(s))}for(let e of i)t&&(yield this._room.unsubscribe(e),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 ob(this,null,(function*(){this._remoteAudioMuteMap.set(e,t);try{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}))}catch(mO){throw this._remoteAudioMuteMap.delete(e),mO}}))}setRemoteAudioVolume(e,t){if("*"===e){let e=[...this._room.remotePublishedUserMap.values()];for(let i of e)this._remoteAudioVolumeMap.set(i.userId,t),i.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),i&&i.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}startPlugin(e,t){return ob(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return ob(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return ob(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(t,i,r){return this.listeners(t).includes(i)||(this._log.debug("on",t),super.on(t,i,r),this._eventListened.add(t),t===e.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM((t=>{this.emit(e.EVENT.AUDIO_FRAME,{data:t})})),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",(()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM((t=>{this.emit(e.EVENT.AUDIO_FRAME,{data:t})})))})))),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{YF.has(e)&&this._log.debug("emit ".concat(e," ").concat(JSON.stringify(i)))}catch(mO){}return super.emit(e,...i)}off(t,i,r){var n,s;return this._log.debug("off",t),"*"===t?(this._eventListened.clear(),this.removeAllListeners(),null==(n=this._getPCMAbortCtrl)||n.abort("off"),delete this._getPCMAbortCtrl):(super.off(t,i,r),t===e.EVENT.AUDIO_FRAME&&(null==(s=this._getPCMAbortCtrl)||s.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(AD(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&&e.muteState.hasVideo)return e.remoteVideoTrack.getVideoFrame();if("sub"===i&&null!=e&&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 ob(this,null,(function*(){(yield GL()).forEach((t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(zF.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),iH=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 ob(this,null,(function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let i=this._room.remotePublishedUserMap.get(t);if(!i)return;let r={},n=i.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let i=this._remoteAudioVolumeMap.get(t),s=CD(i)?i:100;r.volume=s,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),jx(yV(n,"decode-failed"),WV(yV(n,bM.INIT)),GU((()=>{this.startPlugin($B.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})}))),yield this._updateAudioPlayOption({playOption:r,track:n})}catch(_O){throw this._remoteAudioConfigMap.delete(t),_O}this._emitTrackEvent(n)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return ob(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.delete(i.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId))}))}_enableVideoDecodeFallback(e,t){let i=this._room.videoDecodeFallbackType;!i||!this._plugins.has("VideoDecoderPlugin")||(this._log.debug("remote video will fall back when decode failed"),jx(yV(e,"decode-failed"),WV(yV(e,bM.INIT)),WU((()=>{this.startPlugin("VideoDecoderPlugin",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:i})})),SU(yV(e,"decode-downgrade-state-changed")),GU((i=>{this.emit(zF.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,$C(ZC({},i),{streamType:t,userId:e.userId}))}),(e=>{this._log.error("fallback",e)}),(()=>this._log.info("fallback complete")))))}_updateVideoPlayOption(e){return ob(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),RD(t)&&n&&n.view&&!HD(i)){let e=qD(n.view);e.length>0&&(yield r.play(e,i))}if(!RD(t)){let e=qD(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return ob(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:r}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t)}catch(Nb){}RD(t.muted)||i.setPlayerMute(t.muted),RD(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(zF.TRACK,{userId:i,streamType:XF(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var e,t,i;let r=[];if(null!=(e=this._localAudioConfig)&&e.publish&&this._localAudioTrack&&r.push(this._localAudioTrack),null!=(t=this._localVideoConfig)&&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(RD(i))return;let s=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(XF(t.streamType)));if(!s)return;let o=s.observer||void 0;if(null===i||DD(i)&&0===i.length||!r)return null==o||o.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch((()=>{})));let a=s.visibleViewMap||new Map,c=-1;(!o||o.root!==n)&&(null==o||o.disconnect(),a.clear(),o=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(qD(i));a.forEach(((e,t)=>{l.has(t)||(o.unobserve(t),a.delete(t))})),l.forEach((e=>{a.set(e,!0),o.observe(e)})),o.takeRecords().forEach((e=>{a.set(e.target,e.isIntersecting)})),s.visibleViewMap=a,s.observer=o}_exitRoom(){return ob(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach((e=>{this._stopRemoteAudio({userId:e}).catch()})),[...this._remoteVideoConfigMap.keys()].forEach((e=>{let t=e.includes("main")?"main":"sub",i=e.split("_".concat(t))[0];i&&this._stopRemoteVideo({userId:i,streamType:t}).catch()})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),function(e){let t=mB.get(e);t&&(t.forEach((e=>clearTimeout(e))),mB.delete(e))}(this),this._room.remotePublishedUserMap.forEach((e=>{UM(e.remoteAudioTrack),UM(e.remoteVideoTrack),UM(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return ob(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),UM(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_onLocalTrackCaptured(e){let{track:t}=e;"audio"===t.kind&&(!iH||VL(iH))&&(this._initActiveSpeaker(),tO.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return ob(this,null,(function*(){if(iH&&!VL(iH))this.emit(zF.DEVICE_CHANGED,{type:"speaker",action:"active",device:iH});else{let e=yield GL();e[0]&&!VL(e[0])?(iH=e[0],this.emit(zF.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):tO.on("102",this._onLocalTrackCaptured,this)}}))}_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,t=[e];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&t.push(r.remoteAudioTrack),this._room.subscribe(...t).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:$C(ZC({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),IP.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),IP.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){sO.setLogLevel(e),RD(t)||(t?sO.enableUploadLog():sO.disableUploadLog())}static isSupported(){return LP()}static getCameraList(){return BL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return FL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return GL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(t){return ob(this,null,(function*(){if(!CN||t!==yF.SPEAKER&&t!==yF.HEADSET)(yield GL()).forEach((e=>{e.deviceId===t&&(tH.forEach((i=>{i._setCurrentSpeaker(t),i.emit(zF.DEVICE_CHANGED,{type:"speaker",action:"active",device:e})})),iH=e)}));else{let i=yield e.getMicrophoneList(),r="";if(i.forEach((e=>{e.label===t&&(r=e.deviceId)})),!r)return;tH.forEach((e=>ob(this,null,(function*(){e._localAudioTrack&&(yield e.updateLocalAudio({option:{microphoneId:r}}))}))))}}))}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:s,version:o}=e;switch(o&&(SP.version=o),t){case"count":SP.addCount({key:i,useUV:s});break;case"enum":SP.addEnum({key:i,value:r,useUV:s});break;case"number":SP.addNumber({key:i,value:r,split:n})}}};nb(nH,"_loggerManager",sO),nb(nH,"EVENT",zF),nb(nH,"ERROR_CODE",SF),nb(nH,"TYPE",yF),nb(nH,"frameWorkType",30),rb([TB({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"}})})],nH.prototype,"use",1),rb([_B(xF.TRTC.enterRoom),JF("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})),ax((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),TB()],nH.prototype,"enterRoom",1),rb([TB()],nH.prototype,"exitRoom",1),rb([_B(xF.TRTC.switchRole),KF("room",{merge:(e,t)=>t}),TB()],nH.prototype,"switchRole",1),rb([TB()],nH.prototype,"destroy",1),rb([_B(xF.TRTC.startLocalAudio),JF("audio",((e,t)=>{let[i]=e,[r]=t;var n,s;return(null==(n=null==i?void 0:i.option)?void 0:n.microphoneId)===(null==(s=null==r?void 0:r.option)?void 0:s.microphoneId)})),TB()],nH.prototype,"startLocalAudio",1),rb([_B(xF.TRTC.updateLocalAudio),KF("audio",{debounce:{delay:200,getKey:()=>"".concat(eH,"-localAudio"),isNeedToDebounce:e=>{var t;return!RD(null==(t=e.option)?void 0:t.captureVolume)}}}),TB()],nH.prototype,"updateLocalAudio",1),rb([qF("audio"),TB()],nH.prototype,"stopLocalAudio",1),rb([_B(xF.TRTC.startLocalVideo),JF("video",((e,t)=>{let[i]=e,[r]=t;var n,s;return(null==(n=null==i?void 0:i.option)?void 0:n.cameraId)===(null==(s=null==r?void 0:r.option)?void 0:s.cameraId)})),TB()],nH.prototype,"startLocalVideo",1),rb([_B(xF.TRTC.updateLocalVideo),KF("video"),TB()],nH.prototype,"updateLocalVideo",1),rb([qF("video"),TB()],nH.prototype,"stopLocalVideo",1),rb([_B(xF.TRTC.startScreenShare),JF("screen",(()=>!0)),TB()],nH.prototype,"startScreenShare",1),rb([_B(xF.TRTC.updateScreenShare),KF("screen"),TB()],nH.prototype,"updateScreenShare",1),rb([TB()],nH.prototype,"stopScreenShare",1),rb([_B(xF.TRTC.startRemoteVideo),JF((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),TB({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],nH.prototype,"startRemoteVideo",1),rb([_B(xF.TRTC.updateRemoteVideo),KF((e=>"v".concat(e.userId).concat(e.streamType))),TB({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],nH.prototype,"updateRemoteVideo",1),rb([_B(xF.TRTC.stopRemoteVideo),ax((e=>function(t){return ob(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)}))})),TB({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],nH.prototype,"stopRemoteVideo",1),rb([qF((e=>"v".concat(e.userId).concat(e.streamType)))],nH.prototype,"_stopRemoteVideo",1),rb([_B(...xF.TRTC.muteRemoteAudio),TB({getRemoteId:e=>e})],nH.prototype,"muteRemoteAudio",1),rb([fB(...xF.TRTC.setRemoteAudioVolume),function(e,t){return ax(((i,r)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];let o=mB.get(this);o||(o=new Map,mB.set(this,o));let a=t(...n),c=o.get(a);if(!c||c<=0){i.apply(this,n);let t=setTimeout((()=>{var e;null==(e=mB.get(this))||e.delete(a)}),e);o.set(a,t)}else{clearTimeout(c);let t=window.setTimeout((()=>{var e;i.apply(this,n),null==(e=mB.get(this))||e.delete(a)}),e);o.set(a,t)}}))}(200,(e=>e)),TB({getRemoteId:e=>e})],nH.prototype,"setRemoteAudioVolume",1),rb([vB("start"),sx((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),JF(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),TB({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>EP[e.getName()],ignoreLog:e=>"Debug"===e.getName()})],nH.prototype,"startPlugin",1),rb([vB("update"),KF(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),TB({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>TP[e.getName()]})],nH.prototype,"updatePlugin",1),rb([vB("stop"),qF(((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i})),TB({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>vP[e.getName()]})],nH.prototype,"stopPlugin",1),rb([fB(...xF.TRTC.enableAudioVolumeEvaluation)],nH.prototype,"enableAudioVolumeEvaluation",1),rb([TB()],nH.prototype,"getVideoSnapshot",1),rb([TB()],nH.prototype,"_setCurrentSpeaker",1),rb([JF((e=>"a".concat(e.userId)),(()=>!0))],nH.prototype,"_startRemoteAudio",1),rb([ax((e=>function(t){return ob(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio($C(ZC({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),qF((e=>"a".concat(e.userId)))],nH.prototype,"_stopRemoteAudio",1),rb([qF("room")],nH.prototype,"_exitRoom",1),rb([qF("screen")],nH.prototype,"_stopScreenShare",1),rb([_B(...xF.TRTC.sendSEIMessage),EF({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}})],nH.prototype,"sendSEIMessage",1),rb([_B(xF.TRTC.sendCustomMessage),EF({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],nH.prototype,"sendCustomMessage",1),rb([_B(xF.TRTC.create)],nH,"_create",1);var sH=nH,oH=class{constructor(){nb(this,"_set",new Set),tO.on(rO.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 aH(){return ob(this,null,(function*(){let e,t;try{let t=yield FL();e=t&&t.length}catch(dO){}try{let e=yield BL();t=e&&e.length}catch(dO){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:s,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=cO.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:n,vp8Decode:o},l={browser:a.browser,os:a.os,trtc:c,devices:i},d={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};FM.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),FM.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var cH=ib(ab()),lH="1",dH="2",uH="3",hH="4",pH="5",mH="6",_H={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},fH=[_H.UPDATE_REMOTE_MUTE_STAT,_H.UPLINK_NETWORK_STATS,_H.USER_LIST_RES,_H.MUTE_RESULT,_H.SERVER_FIRST_PACKAGE_RECEIVED,_H.RECEIVE_CUSTOM_MSG],gH={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"},EH="publish_change",TH="join",vH="leave",yH="quality_report",SH="mute_uplink",IH="publish",RH="publish_state_change",AH="unpublish",CH="subscribe",bH="unsubscribe",kH="subscribe_change",DH="start_publishing",NH="stop_publishing",wH="start_push_user_cdn",OH="stop_push_user_cdn",PH="start_mcu_mix",MH="stop_mcu_mix",LH="start_publish_cdn_stream",xH="update_publish_cdn_stream",VH="stop_publish_cdn_stream",UH="get_user_list",FH="change_role",BH="update_constraint_config",HH="rebuild_pc",GH="join/v2",WH="publish/v2",jH="subscribe/v3",JH="ability_status_report",KH="reconnect",qH="channel_msg",zH=new Set;var YH=class extends cH.default{constructor(e){var t,i;super(),nb(this,"room"),nb(this,"url"),nb(this,"backupUrl"),nb(this,"race"),nb(this,"destroyed",!1),nb(this,"_socketInUse"),nb(this,"_socket"),nb(this,"_backupSocket"),nb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[]}),nb(this,"_currentState","DISCONNECTED"),nb(this,"_isReconnecting",!1),nb(this,"_seq",0),nb(this,"_log"),nb(this,"_lastMessageTime",-1),nb(this,"_connectStartTime",-1),nb(this,"_stopConnectRetry"),nb(this,"bytesSent",0),nb(this,"bytesReceived",0),nb(this,"keepAlive",!1),nb(this,"signalDomainWhenUnifiedProxy"),nb(this,"stopKeepAliveTimeout"),nb(this,"rtt",0),this.room=e.room,this.race=!!RD(e.race)||e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,((null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0)-zH.size>0&&this.room.enableSPC&&(this.keepAlive=!0,zH.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=sO.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));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 ob(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._connectStartTime=VD();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 xD(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?ik.BACKUP:ik.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 s=-1;return new Promise(((e,t)=>{n.onclose=t,n.onerror=t,n.onopen=()=>e(n),i&&(s=setTimeout((()=>{this.unbindAndCloseSocket(r?ik.MAIN:ik.BACKUP),t(new vb({code:Eb.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),i))})).finally((()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(s)}))}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===ik.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(Nk){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(Nk){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn("".concat(e.target===this._socket?"main":"backup"," is closed code:").concat(e.code," ").concat(e.reason)),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||1e3!==e.code)&&this.startReconnection(),this.room.isJoining&&this.emit(pH,new vb({code:Eb.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(ik.MAIN),this.unbindAndCloseSocket(ik.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(pH,new vb({code:Eb.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=ZD(e.data);let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values(_H),s=Object.keys(_H)[n.indexOf(i)],o=gH[s]||i;switch(fH.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),o&&this._log.info("Received event: [ ".concat(o," ]"))),i){case _H.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),sO.info("baseTime from server: ".concat(t," offset: ").concat(yb))}(r.svrTime),this._log.info("ChannelSetup Success ".concat(VD()-this._connectStartTime)),IP.addSuccessEvent({key:521701,cost:VD()-this._connectStartTime}),this._connectStartTime=-1,this.emit(lH,{signalInfo:this._signalInfo});else{let e=new vb({code:Eb.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:pP({key:lP.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),IP.addFailedEvent({key:521701,error:e}),this.emit(pH,e)}break;case _H.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=r.relayOuterIp,this._signalInfo.relayInnerIp=r.relayInnerIp,this._signalInfo.bakRelayIps=r.bakRelayIps,this._signalInfo.relayPort=r.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=r.endReportExtend,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(o,{data:t});break;default:this.emit(String(o),{data:t})}}reGetSignalChannelUrl(){return ob(this,null,(function*(){try{if(!this.room.joinParams)return;iB(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(Db){}}))}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?ik.MAIN:ik.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return ob(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:s}=yield this.sendWaitForResponse({command:KH,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:gH.CHANNEL_RECONNECT_RESULT});0===s.code?(this._log.warn("reconnect success"),this.stopReconnection(),IP.addSuccessEvent({key:521702,cost:VD()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(IP.addFailedEvent({key:521702,error:s.code}),this._log.warn("reconnect failed, ".concat(s.code," ").concat(s.message)),this.room.reJoin())}catch(Db){this._log.error(Db),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+=ZD(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:s,enableLog:o=!0,addReceiveTime:a=!1}=e;return new Promise(((e,c)=>{let l=setTimeout((()=>{this.off(n,d);let e=new vb({code:Eb.API_CALL_TIMEOUT,message:pP({key:lP.API_CALL_TIMEOUT,data:{commandDesc:s,command:t}})});o&&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 hN({retryFunction:this.sendWaitForResponse,onError:e=>{let{retry:t}=e;this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(uH,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),zH.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(ik.MAIN),this.unbindAndCloseSocket(ik.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var e;let t=null==(e=this._signalInfo.bakRelayIps)?void 0:e.shift();return t&&(t.relayPort=t.relayPort||this._signalInfo.relayPort),t}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}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(gH.JOIN_ROOM_RESULT,t)}),1e3*e);let t=e=>{0===e.data.code&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(gH.JOIN_ROOM_RESULT,t))};this.on(gH.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(dH,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(uH):"DISCONNECTED"===e&&this.emit(mH))}};rb([HM({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())}})],YH.prototype,"connect",1);var XH=ib(ab()),QH=0,ZH=!1,$H=new Set,eG=!1,tG=class{constructor(e){nb(this,"userId"),nb(this,"tinyId"),nb(this,"_sdpSemantics"),nb(this,"_isUplink"),nb(this,"_room"),nb(this,"_log"),nb(this,"_signalChannel"),nb(this,"_isErrorObserved",!1),nb(this,"_waitForPeerConnectionConnectedPromise"),nb(this,"_waitForPeerConnectionConnectedPromiseReject",null),nb(this,"_peerConnection",null),nb(this,"_emitter",new XH.default),nb(this,"_currentState","DISCONNECTED"),nb(this,"_isReconnecting",!1),nb(this,"_reconnectionCount",0),nb(this,"_reconnectionTimer",-1),nb(this,"_isFirstConnection",!0),nb(this,"_prevTime",-1),nb(this,"_localAddress"),nb(this,"_remoteAddress"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=sO.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=VD())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,IP.addSuccessEvent({key:521705,cost:Math.min(VD()-this._prevTime,3e4)})):this._isReconnecting&&IP.addSuccessEvent({key:521706,cost:VD()-this._prevTime}),this._prevTime=-1}catch(pO){throw this._isFirstConnection?(this._isFirstConnection=!1,IP.addFailedEvent({key:521705,error:pO})):this._isReconnecting&&this._reconnectionCount>=3&&IP.addFailedEvent({key:521706,error:pO}),pO}}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(),$H.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:Eb.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Ak;let e=null;if(this._isUplink){if(!zP()||0===this._peerConnection.getSenders().length)return Ak;e=this._peerConnection.getSenders()[0].transport}else{if(!qP()||0===this._peerConnection.getReceivers().length)return Ak;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:Ak}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:Eb.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(),FM.logSuccessEvent({userId:this._room.userId,eventType:Ok.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(QH=0,ZH=!1,eG=!0,$H.add(this)):$H.delete(this),tO.emit(rO.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 ob(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(BP(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(s),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(s),n(),t(new vb({code:Eb.API_CALL_ABORTED,message:pP({key:lP.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{tO.off(rO.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},s=setTimeout((()=>{n();let e=new vb({code:Eb.API_CALL_TIMEOUT,message:"connection timeout"});var i;QH+=1,i=this._signalChannel.isConnected,QH>2&&!ZH&&0===$H.size&&i&&(this._log.warn("firewall restriction"),ZH=!0,this._emitter.emit("firewall-restriction")),t(e)}),jk);tO.on(rO.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(uH,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Dk()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new vb({code:this._isUplink?Eb.UPLINK_RECONNECTION_FAILED:Eb.DOWNLINK_RECONNECTION_FAILED,message:pP({key:this._isUplink?lP.UPLINK_RECONNECTION_FAILED:lP.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",e),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this._reconnectionCount,"]")),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(uH,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)}};rb([fx(521712,!1)],tG.prototype,"setOffer",1),rb([fx(521713,!1)],tG.prototype,"setAnswer",1);var iG=ib(_b()),rG=function(e){return iG.default.parse(e)},nG=function(e){return iG.default.write(e)};function sG(e){return Object.keys(e).filter((t=>e[t]))}var oG=class e extends tG{constructor(e){super($C(ZC({},e),{isUplink:!1})),nb(this,"_flag",0),nb(this,"isRobot",!1),nb(this,"role","anchor"),nb(this,"remoteAudioTrack"),nb(this,"remoteVideoTrack"),nb(this,"remoteAuxiliaryTrack"),nb(this,"ssrc",{audio:0,video:0,auxiliary:0}),nb(this,"_isSDPExchanging",!1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new zU(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new hF(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new pF(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 GD(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===ik.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===mk?ik.MAIN:ik.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=ik.AUDIO;i.kind===ik.VIDEO&&(n=r===ik.MAIN?ik.VIDEO:ik.AUXILIARY);let s=this.remoteAudioTrack;n===ik.VIDEO?s=this.remoteVideoTrack:n===ik.AUXILIARY&&(s=this.remoteAuxiliaryTrack),s.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=rG(e);return t.media.forEach((e=>{e.type===ik.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),nG(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=rG(e);return i.media.forEach((e=>{e.ext&&(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),nG(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return ob(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(Nb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Nb.message," ").concat(JSON.stringify(this.muteState))),new vb({code:Eb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Nb}}))}unsubscribe(e){return ob(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=ZC({},t.subscribeState);i.forEach((t=>{switch(t.mediaType){case 1:e.audio=!1;break;case 4:e.video=!1;break;case 8:e.smallVideo=!1;break;case 2:e.auxiliary=!1}}));let n="subscribe_change";Object.values(e).find((e=>!0===e))||(n="unsubscribe"),t._log.info("".concat("unsubscribe"===n?n:"subscribe"," ").concat(r," [").concat(sG(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=bH,n=gH.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=kH,n=gH.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:pP({key:lP.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return ob(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(Nk){throw e.closePeerConnection(!0),Nk}}()}))}exchangeSDP(e){return ob(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:CH,commandDesc:"exchange sdp",data:r,responseCommand:gH.SUBSCRIBE_RESULT,timeout:Lk});if(!this._peerConnection){let e=new vb({code:Eb.INVALID_OPERATION,message:pP({key:lP.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(Nk){throw this._isSDPExchanging=!1,Nk}}))}createOffer(){return ob(this,null,(function*(){let e={voiceActivityDetection:!1};XP()&&this._sdpSemantics===xk?(this._peerConnection.addTransceiver(ik.AUDIO,{direction:rk.RECVONLY}),this._peerConnection.addTransceiver(ik.VIDEO,{direction:rk.RECVONLY}),this._peerConnection.addTransceiver(ik.VIDEO,{direction:rk.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield MP();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=rG(e);return t.media.forEach((e=>{var t,i;if(e.type===ik.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(" ")}})),nG(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=rG(e);return t.media.forEach((e=>{e.type===ik.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),nG(t)}(t.sdp),this._sdpSemantics===xk&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)}))}onSubscribeResult(e){return ob(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===Uk)throw new vb({code:Eb.NOT_SUPPORTED_H264,message:pP({key:lP.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new vb({code:t,message:pP({key:lP.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(n)),yield this.setAnswer({type:r,sdp:n}),this.updateSSRC(n)}catch(_O){throw this._log.error(_O),_O}}))}updateSSRC(e){try{rG(e).media.forEach((e=>{if(e.ssrcs)if(e.type===ik.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(mk)}));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(mk)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(_k)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(Nk){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return ob(this,null,(function*(){if(!(sb(e.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(Nk){let t=yD(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}};rb([ax((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:Eb.API_CALL_ABORTED,message:pP({key:lP.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],oG.prototype,"subscribe",1),rb([fx(521717,!1)],oG.prototype,"unsubscribe",1),rb([sx(tG.prototype.afterConnect),nx(tG.prototype.beforeConnect)],oG.prototype,"connect",1);var aG=oG,cG={voiceActivityDetection:!1},lG=class e extends tG{constructor(e){super($C(ZC({},e),{isUplink:!0})),nb(this,"localMainAudioTrack",null),nb(this,"localMainVideoTrack",null),nb(this,"localAuxAudioTrack",null),nb(this,"localAuxVideoTrack",null),nb(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),nb(this,"_isPublishingAux",!1),nb(this,"_publishingLocalAudioTrack"),nb(this,"_publishingLocalVideoTrack"),nb(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}),nb(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 s=this._peerConnection.getSenders();s&&(YP()?(n.audio=!(null==(e=s[0])||!e.track),n.bigVideo=!(null==(t=s[1])||!t.track),n.smallVideo=!(null==(i=s[2])||!i.track),n.auxVideo=!(null==(r=s[3])||!r.track)):s.forEach((e=>{e.track&&(e.track.kind===ik.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 s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:s,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:s,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:s,state:e}))),o}publish(e){return ob(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(),XP()?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 ob(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n,isAuxiliary:s}=e;return function*(){t._log.info("publish by transceiver");let e=new MediaStream,o=null==r?void 0:r.outMediaTrack,a=null==i?void 0:i.outMediaTrack;a&&e.addTrack(a),o&&e.addTrack(o);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||ik.AUDIO,{direction:rk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(s?ik.VIDEO:o||ik.VIDEO,{direction:rk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||ik.VIDEO,{direction:rk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(s&&o||ik.VIDEO,{direction:rk.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:ik.AUDIO})),o){let i=s?3:1;yield c[i].sender.replaceTrack(o),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:ik.VIDEO,videoType:s?ik.AUXILIARY:ik.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:ik.VIDEO,videoType:ik.SMALL}),e.push(2))}yield t.setTransceiverDirection(rk.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 ob(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,s=null==i?void 0:i.outMediaTrack;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return i&&s&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(r)));let o=new MediaStream;if(s&&o.addTrack(s),e&&o.addTrack(e),s&&t._peerConnection.addTrack(s,o),e&&(t._peerConnection.addTrack(e,o),n)){let e=new MediaStream;e.addTrack(n),t._peerConnection.addTrack(n,e)}yield t.connect()}()}))}enableSmall(e){return ob(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(rk.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(rk.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 ob(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!YP())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,s=t._peerConnection.getSenders(),o=[];i&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localAuxAudioTrack&&!t.localMainAudioTrack&&(yield s[0].replaceTrack(null),o.push(0))),n&&(e?(yield s[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=$C(ZC({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),o.push(3)):(yield s[1].replaceTrack(null),yield s[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=$C(ZC({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),o.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.setTransceiverDirection(rk.INACTIVE,o),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 ob(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:RH,data:t,responseCommand:gH.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:AH,commandDesc:"unpublish",responseCommand:gH.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===Eb.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),rM){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:BH,data:this._mediaSettings,responseCommand:gH.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return ob(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?ik.AUXILIARY:ik.MAIN," stream")),XP()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return ob(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===ik.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)&&i.small&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===rk.INACTIVE&&(yield this.setTransceiverDirection(rk.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return ob(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;YP()&&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===ik.VIDEO&&e instanceof Rx&&e.small){let e=new MediaStream,{smallTrack:t}=this._room.videoManager;e.addTrack(t),this._peerConnection.addTrack(t,e)}yield this.updateOffer("add",t)}))}isNeedToResetOfferOrder(){if(this._sdpSemantics===Vk||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=rG(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===ik.VIDEO)return!0;return!1}removeSender(e){let t=null;YP()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&ID(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return ob(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?ik.AUXILIARY:ik.MAIN," stream")),XP()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return ob(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===ik.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(rk.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return ob(this,null,(function*(){if(!NN)return;let i=!1,r=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let n=this._peerConnection.getTransceivers();if(t.forEach((t=>{n[t].direction!==e&&(n[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this.setOffer(e)}let s=-1,o=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(rk.INACTIVE,"|").concat(rk.RECVONLY,"|").concat(rk.SENDONLY,")")))&&s++,t.includes(s)){if(e===rk.INACTIVE&&i.includes("a=".concat(rk.RECVONLY)))return r=!0,"a=".concat(e);if(e===rk.SENDONLY&&i.includes("a=".concat(rk.INACTIVE)))return r=!0,"a=".concat(rk.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:o}))}))}removeTrackBySender(e){return ob(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===ik.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===ik.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===ik.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return ob(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=XP()?e.kind===ik.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?ik.AUXILIARY:ik.MAIN," stream")),e.kind===ik.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===ik.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack)),!0}))}updateOffer(e,t){return ob(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(cG);NN&&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===ik.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 s=yield this._signalChannel.sendWaitForResponse({command:EH,data:n,responseCommand:gH.UPDATE_OFFER_RESULT,timeout:Mk,commandDesc:"update offer"}),{code:o,message:a}=s.data;0!==o&&this.checkPublishResultCode(o,a),yield this.acceptAnswer(s.data.data),i.sdp&&this.updateSSRC(i.sdp)}catch(mO){throw this._log.error(mO),mO}}))}setBandwidth(e){return ob(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:s}=e;return function*(){if(!tM())return s?r===ik.VIDEO?t.updateVideoBandwidthRestriction(s,i,n):t.updateAudioBandwidthRestriction(s,i):void 0;let e,o=t._peerConnection.getSenders();if(XP()){let t=0;r===ik.VIDEO&&(t=n===ik.SMALL?2:n===ik.AUXILIARY?3:1),e=o[t]}else e=o.find((e=>e.track&&e.track.kind===r));if(e){let o=e.getParameters();(!o.encodings||0===o.encodings.length)&&(o.encodings=[{}]),o.encodings[0].maxBitrate=1e3*i;try{return yield e.setParameters(o),t._log.info("".concat(n||"").concat(r," bandwidth ").concat(i," kbps")),s}catch(a){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(a)),s)return r===ik.VIDEO?t.updateVideoBandwidthRestriction(s,i,n):t.updateAudioBandwidthRestriction(s,i)}}return s}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";NN&&(r="TIAS",t*=1e3);let n=0,s=-1;return i===ik.SMALL?n=1:i===ik.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(s+=1,s===n?"".concat(e,"b=").concat(r,":").concat(t,"\r\n"):e)))}updateAudioBandwidthRestriction(e,t){let i="AS";return NN&&(i="TIAS",t*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,"m=audio $1\r\nc=IN $2\r\nb=".concat(i,":").concat(t,"\r\n"))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return ob(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(Db){throw this.closePeerConnection(!0),this.uninstallEvents(),Db}}))}exchangeSDP(){return ob(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(Db){throw Db}}))}createOffer(){return ob(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(cG);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(Db){throw Db}}))}doExchangeSDP(){let e={command:IH,responseCommand:gH.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof bx||this.localAuxVideoTrack instanceof bx,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=rG(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),nG(r)}acceptAnswer(e){return ob(this,null,(function*(){var t,i,r,n,s;try{let o;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),s=(null==(r=this._publishingLocalAudioTrack)?void 0:r.profile.bitrate)||(null==(n=this.localMainAudioTrack)?void 0:n.profile.bitrate);if(e){let t=this._isPublishingAux?ik.AUXILIARY:ik.BIG;o=yield this.setBandwidth({bandwidth:e,type:ik.VIDEO,sdp:o,videoType:t})}s&&(o=yield this.setBandwidth({bandwidth:s,type:ik.AUDIO,sdp:o}))}if(o=this.removeVideoOrientation(e.sdp),null!=(s=this._publishingLocalVideoTrack)&&s.small){let{smallStreamConfig:e}=this._room;o=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:ik.VIDEO,videoType:ik.SMALL,sdp:o})}let a={type:e.type,sdp:o};yield this.setAnswer(a),this._log.debug("accepted answer: ".concat(o))}catch(o){throw this._log.error("failed to accept remote answer ".concat(o)),o}}))}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(SH,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return ob(this,null,(function*(){if(!(sb(e.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:AH,responseCommand:gH.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(Nk){let t=yD(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)&&tO.emit(rO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{rG(e).media.forEach(((e,t)=>{if(e.type===ik.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===Vk&&e.ssrcGroups)return void e.ssrcGroups.forEach(((e,t)=>{let i=Number(e.ssrcs.split(" ")[0]);0===t?this.ssrc.video=i:1===t&&(this.ssrc.small=i)}));let i=e.ssrcs&&e.ssrcs[0];if(!i)return;switch(t){case 1:this.ssrc.video=Number(i.id);break;case 2:this.ssrc.small=Number(i.id);break;case 3:this.ssrc.auxiliary=Number(i.id)}}}))}catch(Nk){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ik.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===ik.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===ik.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===ik.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===ik.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Uk?(this._log.error(dP.NOT_SUPPORTED_H264ENCODE),new vb({code:Eb.NOT_SUPPORTED_H264,message:pP({key:lP.NOT_SUPPORTED_H264ENCODE})})):new vb({code:Eb.UNKNOWN,message:pP({key:lP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:gH.PUBLISH_RESULT,code:e,message:t}})})}};rb([ax((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:Eb.API_CALL_ABORTED,message:pP({key:lP.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],lG.prototype,"publish",1),rb([fx(521715,!1)],lG.prototype,"unpublish",1),rb([sx(tG.prototype.afterConnect),nx(tG.prototype.beforeConnect)],lG.prototype,"connect",1);var dG=lG,uG=class{constructor(e,t){this.room=e,nb(this,"_log"),nb(this,"_prevReportTime",0),nb(this,"_prevReport",{}),nb(this,"_prevStats",null),nb(this,"_prevEncoderImplementation",""),nb(this,"_prevAuxEncoderImpl",""),nb(this,"_prevQualityLimitationReason",""),nb(this,"_prevAuxQualityLimitationReason",""),nb(this,"_prevDecoderImplementationMap",new Map),nb(this,"totalBytesSent",0),nb(this,"totalBytesReceived",0),nb(this,"_spcStats",null),this._log=t}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return ob(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,s,o;let a,c;if("outbound-rtp"===t.type)if((t.mediaType||t.kind)===ik.VIDEO){if(t.ssrc===n.video?(a=ik.VIDEO,c=e.localMainVideoTrack):t.ssrc===n.small?a=ik.SMALL:t.ssrc===n.auxiliary&&(c=e.localAuxVideoTrack,a=ik.AUXILIARY),!a)return;if(i[a].bytesSent=t.bytesSent,i[a].packetsSent=t.packetsSent,i[a].framesEncoded=t.framesEncoded,RD(t.keyFramesEncoded)||(i[a].keyFramesEncoded=t.keyFramesEncoded),RD(t.nackCount)||(i[a].nackCount=t.nackCount),RD(t.pliCount)||(i[a].pliCount=t.pliCount),RD(t.retransmittedPacketsSent)||(i[a].retransmittedPacketsSent=t.retransmittedPacketsSent),RD(t.totalEncodeTime)||(i[a].totalEncodeTime=t.totalEncodeTime),RD(t.totalPacketSendDelay)||(i[a].totalPacketSendDelay=t.totalPacketSendDelay),!RD(t.encoderImplementation)&&(a===ik.VIDEO&&this._prevEncoderImplementation!==t.encoderImplementation||a===ik.AUXILIARY&&this._prevAuxEncoderImpl!==t.encoderImplementation)){let i=2,r=this._prevEncoderImplementation;a===ik.AUXILIARY&&(i=7,r=this._prevAuxEncoderImpl),tO.emit("262",{userId:e.userId,streamType:i,prevImplementation:r,implementation:t.encoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientEncoder}),this[a===ik.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=t.encoderImplementation,this._log.info("".concat(a===ik.AUXILIARY?"aux ":"","encoderImplementation change to ").concat(t.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(t.powerEfficientEncoder))}t.ssrc===n.video?!RD(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),tO.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&&!RD(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),tO.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(s=e.localAuxVideoTrack)?void 0:s.isQosClearFirst}),this._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else i.audio.bytesSent=t.bytesSent,i.audio.packetsSent=t.packetsSent;else"candidate-pair"===t.type?BP(t)&&(this.totalBytesSent=t.bytesSent,CD(t.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*t.currentRoundTripTime))):"media-source"===t.type&&(t.kind===ik.AUDIO?(i.audio.audioLevel=t.audioLevel||0,i.audio.totalAudioEnergy=t.totalAudioEnergy||0,t.echoReturnLoss,t.totalSamplesDuration&&(i.audio.totalSamplesDuration=t.totalSamplesDuration)):t.kind===ik.VIDEO&&(t.trackIdentifier===e.getVideoTrackId(ik.VIDEO)?i.video.fpsCapture=t.framesPerSecond:t.trackIdentifier===e.getVideoTrackId(ik.AUXILIARY)?i.auxiliary.fpsCapture=t.framesPerSecond:i.small.fpsCapture=t.framesPerSecond));if(!RD(t.audioLevel)&&null!=(o=e.localMainAudioTrack)&&o.mediaTrack&&t.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(i.audio.audioLevel=t.audioLevel||0),!RD(t.frameWidth)){let r=ik.SMALL;t.trackIdentifier===e.getVideoTrackId(ik.VIDEO)||t.ssrc===n.video?r=ik.VIDEO:(t.trackIdentifier===e.getVideoTrackId(ik.AUXILIARY)||t.ssrc===n.auxiliary)&&(r=ik.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===ik.AUDIO?(e.localMainAudioTrack&&(e.localMainAudioTrack.stat=i[t]),e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=i[t])):t===ik.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=i[t]):t===ik.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=i[t])}))}catch(Nb){this._log.warn("failed to getStats on sender connection ".concat(Nb))}return 0===i.rtt&&(i.rtt=(null==(t=this.room.networkQuality)?void 0:t.uplinkRTT)||0),i}))}getReceiverStats(e){return ob(this,null,(function*(){var t,i,r;let n={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},s=e.getPeerConnection();if(s)try{let{ssrc:r}=e,{muteState:o,subscribeState:a}=e;(this._spcStats||(yield s.getStats())).forEach((t=>{if("inbound-rtp"===t.type){let i=(t.mediaType||t.kind)===ik.AUDIO;if(i){if(t.ssrc!==r.audio||!o.hasAudio)return;n.audio.packetsReceived=t.packetsReceived,n.audio.bytesReceived=t.bytesReceived,n.audio.packetsLost=t.packetsLost,t.insertedSamplesForDeceleration&&(n.audio.insertedSamplesForDeceleration=t.insertedSamplesForDeceleration),t.removedSamplesForAcceleration&&(n.audio.removedSamplesForAcceleration=t.removedSamplesForAcceleration),t.totalSamplesDuration&&(n.audio.totalSamplesDuration=t.totalSamplesDuration),t.totalSamplesReceived&&(n.audio.totalSamplesReceived=t.totalSamplesReceived),t.concealedSamples&&(n.audio.concealedSamples=t.concealedSamples);let{remoteAudioTrack:i}=e;i.stat.packetsReceived=t.packetsReceived,i.stat.bytesReceived=t.bytesReceived,i.stat.packetsLost=t.packetsLost,n.audio.p2pDelay=i.stat.end2EndDelay,n.hasAudio=!0}else{if(NN&&0===t.bytesReceived)return;let i;t.ssrc===r.video&&o.hasVideo&&(n.video.packetsReceived=t.packetsReceived,n.video.bytesReceived=t.bytesReceived,n.video.packetsLost=t.packetsLost,n.video.framesReceived=t.framesReceived,n.video.framesDecoded=t.framesDecoded,n.video.fpsDecoded=t.framesPerSecond,n.hasVideo=!0,i=e.remoteVideoTrack,o.hasSmall&&a.smallVideo&&(n.isSmallSubscribed=!0),t.decoderImplementation&&(!this._prevDecoderImplementationMap.has(n.userId)||this._prevDecoderImplementationMap.get(n.userId)!==t.decoderImplementation)&&(this._log.info("".concat(n.userId," decoderImplementation change to ").concat(t.decoderImplementation," HWDecoder: ").concat(t.powerEfficientDecoder)),tO.emit("262",{userId:this.room.userId,remoteUserId:n.userId,prevImplementation:this._prevDecoderImplementationMap.get(n.userId),implementation:t.decoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(n.userId,t.decoderImplementation))),t.ssrc===r.auxiliary&&o.hasAuxiliary&&(n.auxiliary.packetsReceived=t.packetsReceived,n.auxiliary.bytesReceived=t.bytesReceived,n.auxiliary.packetsLost=t.packetsLost,n.auxiliary.framesReceived=t.framesReceived,n.auxiliary.framesDecoded=t.framesDecoded,n.auxiliary.fpsDecoded=t.framesPerSecond,i=e.remoteAuxiliaryTrack,n.hasAuxiliary=!0),i&&(i.stat.packetsReceived=t.packetsReceived,i.stat.bytesReceived=t.bytesReceived,i.stat.packetsLost=t.packetsLost,i.stat.framesReceived=t.framesReceived,i.stat.framesDecoded=t.framesDecoded,t.jitterBufferDelay&&(i.stat.jitterBufferDelay=Math.floor(t.jitterBufferDelay/t.jitterBufferEmittedCount*1e3)))}t.jitterBufferDelay&&(i?(n.audio.totalJitter=t.jitterBufferDelay,n.audio.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.video&&o.hasVideo?(n.video.totalJitter=t.jitterBufferDelay,n.video.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.auxiliary&&o.hasAuxiliary&&(n.auxiliary.totalJitter=t.jitterBufferDelay,n.auxiliary.totalJitterCount=t.jitterBufferEmittedCount))}else"candidate-pair"===t.type&&BP(t)&&(this.totalBytesReceived=t.bytesReceived,CD(t.currentRoundTripTime)&&(n.rtt=Math.floor(1e3*t.currentRoundTripTime)));RD(t.frameWidth)||((t.trackIdentifier===e.getMainStreamVideoTrackId()||t.ssrc===r.video)&&(n.video.frameWidth=t.frameWidth,n.video.frameHeight=t.frameHeight,e.remoteVideoTrack.stat.frameWidth=t.frameWidth,e.remoteVideoTrack.stat.frameHeight=t.frameHeight),(t.trackIdentifier===e.getAuxStreamVideoTrackId()||t.ssrc===r.auxiliary)&&(n.auxiliary.frameWidth=t.frameWidth,n.auxiliary.frameHeight=t.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=t.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=t.frameHeight)),!RD(t.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&t.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(n.audio.audioLevel=t.audioLevel||0,n.audio.totalAudioEnergy=t.totalAudioEnergy||0)})),0===n.audio.audioLevel&&e.muteState.audioAvailable&&(n.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=n.audio.bytesReceived+n.video.bytesReceived+n.auxiliary.bytesReceived),RD(null==(t=e.remoteVideoTrack.player.stat)?void 0:t.fps)||(n.video.fpsRender=e.remoteVideoTrack.player.stat.fps),RD(null==(i=e.remoteAuxiliaryTrack.player.stat)?void 0:i.fps)||(n.auxiliary.fpsRender=e.remoteAuxiliaryTrack.player.stat.fps)}catch(_O){this._log.warn("failed to getStats on receiver connection ".concat(_O))}return 0===n.rtt&&(n.rtt=(null==(r=this.room.networkQuality)?void 0:r.uplinkRTT)||0),n}))}getStats(e,t){return ob(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=VD(),n=yield e.getStats(),s=VD();s-t>2e3&&this._log.warn("getStats cost ".concat(s-t,"ms"));let o=[],a=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);n.forEach((e=>a.has(e.type)&&o.push(e))),this._spcStats=o}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(ZL(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(!ZL(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*$O,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*$O),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:s}=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(fk)),n=i?i.duration:0,s={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.video.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.video.totalJitter,uint32_video_cache_ms_count:e.video.totalJitterCount};t.msg_video_status.push(s)}if(e.hasAuxiliary){let i=r.get("".concat(e.userId,"_").concat(gk)),n=i?i.duration:0,s={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.auxiliary.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.auxiliary.totalJitter,uint32_video_cache_ms_count:e.auxiliary.totalJitterCount};t.msg_video_status.push(s)}i.msg_down_stream_info.push(t)}));let o=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&&o.msg_up_stream_info.msg_audio_status){let e=o.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let r=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*r/s),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}null!=(n=o.msg_device_info)&&n.uint32_audio_capture_cost?i.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(o.msg_device_info.uint32_audio_capture_cost,i.msg_device_info.uint32_audio_capture_cost)/s):delete i.msg_device_info.uint32_audio_capture_cost}let c=o.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,o=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(r=t.uint32_video_codec_bitrate,n=t.uint32_video_enc_fps,o=t.uint32_video_codec_fps);let a=this.getDifferenceValue(r,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*a/s),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)/s),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_codec_fps)/s),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),RD(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),RD(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),RD(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),RD(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),RD(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/s)),RD(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/s))}));let l=o.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(ZL(e.msg_audio_status)||ZL(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 o=this.room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);o&&(o.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/s),i.uint32_audio_total_bitrate=Math.round(8*a/s)}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,o=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(o,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/s);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/s),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/s);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*s);if(n>1e3*s/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 ob(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}}]},s=yield t.getStats(i,r);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:s,report:e,freezeMap:n}),t._prevReportTime=Date.now(),e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},hG=ib(ab());function pG(e){return new Promise((t=>ob(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(Nb){}clearTimeout(i);let s=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,s=r.fetchStart>0?Math.max(Math.round(r.domainLookupStart-r.fetchStart),0):0,o=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=$C(ZC({},t),{totalCost:e,local:i,redirect:n,httpCache:s,dns:o,tcp:c,tls:a,request:l,response:d});break}}catch(i){}return t}(n);0===s.totalCost&&(s.totalCost=Date.now()-r),t(s)}))))}var mG=class e extends hG.default{constructor(e){let{signalChannel:t,room:i}=e;super(),nb(this,"_room"),nb(this,"_signalChannel"),nb(this,"_log"),nb(this,"uplinkRTT",0),nb(this,"uplinkLoss",0),nb(this,"downlinkRTT",0),nb(this,"downlinkLoss",0),nb(this,"pingResults",{}),nb(this,"_downlinkPrevStatMap",new Map),nb(this,"_downlinkLossAndRTTMap",new Map),nb(this,"_interval",-1),nb(this,"_uplinkNetworkQuality",0),nb(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=sO.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," 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(gH.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(dH,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 s=r.expectAudPkg+r.expectVidPkg,o=r.recvAudPkg+r.recvVidPkg,a=s-o;0===s&&0===o||(this.uplinkLoss=a<=0?0:Math.round(a/s*100),this.uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return ob(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:s}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:s});continue}let o=0,a=this._downlinkPrevStatMap.get(e),c=r-a.totalPacketsLost,l=s-a.totalPacketsReceived;o=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:s}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:o,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 ob(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!qP())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&&CD(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===ik.AUDIO||e.mediaType===ik.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return 0===t.rtt&&(t.rtt=this.uplinkRTT),t}catch(gO){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=PM.run("ric",(()=>{var t;this.handleDownlinkNetworkQuality();let i=[...this._downlinkLossAndRTTMap.values()];tO.emit(rO.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:i});let r=null==(t=this._room.scheduleResult.config)?void 0:t.pingDomainInfo,n={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};r&&(n=$C(ZC({},n),{pingResults:this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold?this.pingResults:{}})),this.emit(e.EVENT_NETWORK_QUALITY,n);let s=Date.now();if(r&&(this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold)&&s-e.lastPingTime>1e3*r.interval){e.lastPingTime=Date.now();let t=r.domain.map((e=>pG(e).then((t=>({domain:e,cost:t.totalCost})))));Promise.all(t).then((e=>{this.pingResults.isPoorNetwork=e.some((e=>e.cost>700)),this.pingResults.timestamp=s,this.pingResults.data=e,e.forEach((e=>{IP.addSuccessEvent({key:521718,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&&(PM.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,s=t.get(i);if(s){let e=this._room.remotePublishedUserMap.get(s);null==e||e.setDelay({videoDelay:r,audioDelay:n})}}))}};nb(mG,"EVENT_NETWORK_QUALITY","0"),nb(mG,"lastPingTime",0);var _G=mG;var fG=class{constructor(e){nb(this,"_frameWorkType"),nb(this,"_component"),nb(this,"_language"),nb(this,"connectionType"),nb(this,"_room"),nb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0}),nb(this,"_keyPrefix"),nb(this,"_log"),nb(this,"_intervalId"),nb(this,"_firstPublishedUserList"),nb(this,"_networkQuality"),nb(this,"_basicInfo"),nb(this,"_pathJoinRoom"),nb(this,"_pathLeaveRoom"),nb(this,"_pathMainVideoMap"),nb(this,"_pathMainAudioMap"),nb(this,"_pathAuxiliaryMap"),nb(this,"_remoteStreamStatMap"),nb(this,"_localStreamStat"),nb(this,"_eventMap",new Map),nb(this,"_captureCostSum",0),nb(this,"_captureCostCount",0),nb(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=sO.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&ID(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 s=t.apply(i,r);return OD(s)?s.catch((e=>sO.error("".concat(t.name,"() error observed ").concat(e)))):s}catch(Nk){sO.error("".concat(t.name,"() error observed ").concat(Nk))}}}({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:bb,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,Kw().then((e=>{this._basicInfo.string_os_version=Qw(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),tO.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(rO.JOIN_START,this.handleJoinStart).addEvent(rO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(rO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(rO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(rO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(rO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(rO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(rO.JOIN_FAILED,this.handleJoinFailed).addEvent(rO.LEAVE_START,this.handleLeaveStart).addEvent(rO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(rO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(rO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(rO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(rO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(rO.PUBLISH_START,this.handlePublishStart).addEvent(rO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(rO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(rO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(rO.PLAY_TRACK_START,this.handlePlayStart).addEvent(rO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(rO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!t.isRemote||!this.hitTest(t.room)||"PLAYING"===i&&(r===ik.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(rO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(rO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(rO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(rO.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,s=i.hasAuxiliary,o=r.hasAudio||r.hasVideo||r.hasSmall,a=r.hasAuxiliary;!n&&o&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")})).addEvent(rO.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("pagehide",this.handleUnload),this._eventMap.forEach(((e,t)=>tO.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),PM.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&&(RD(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),RD(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),RD(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:s,request:o,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=s,this._pathJoinRoom.int32_schedule_request=o,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()):Eb.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}handleJoinFailed(e){let{room:t,error:i}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=i.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout((()=>{this.report()})))}handleReceivedPublishUserList(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(e,t){var i;let r="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(r)){let n={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:$C(ZC({},EG),{msg_user_info:new TG({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:s,tinyId:o,role:a}=i,c=new TG({userId:s,tinyId:o,role:"anchor"===a?20:21}),l=Date.now(),d="".concat(s,"_").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:s,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:s,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(!t.isRemote||!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(!t.isRemote||!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(n){let{statsToReport:t}=n;if(t.uint32_video_render_first||"main"!==e.streamType?this.hasAuxFlag(e.userId):this.hasVideoFlag(e.userId)){let e=i-this._pathJoinRoom.uint64_start_time;t.uint32_video_render_first=e,IP.addNumber({key:516820,value:e})}}0===(null==r?void 0:r.statsToReport.uint64_render_first_frame_time)&&(r.statsToReport.uint64_render_first_frame_time=i)}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:s}=e,o=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(o)o.totalRTT+=t,o.totalLoss+=i,n&&(o.totalVideoDelay=(o.totalVideoDelay||0)+n,o.videoDelayCount=(o.videoDelayCount||0)+1),s&&(o.totalAudioDelay=(o.totalAudioDelay||0)+s,o.audioDelayCount=(o.audioDelayCount||0)+1),o.count++;else{let e,o,a,c;n&&(o=n,a=1),s&&(e=s,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:o,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/$O*100)>0&&(this._localStreamStat.totalAudioLevel+=e/$O,this._localStreamStat.audioLevelCount++)}r.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:r}=e,n=t.str_identifier,s=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"),o=this._remoteStreamStatMap.get(r);if(o&&(t&&null!=s&&s.remoteVideoTrack.isSubscribed||i&&null!=s&&s.remoteAuxiliaryTrack)){o.totalVideoFPS+=e.uint32_video_receive_fps,o.totalVideoBitrate+=e.uint32_video_codec_bitrate,o.videoCount++,0===o.statsToReport.uint32_video_width&&(o.statsToReport.uint32_video_width=e.uint32_video_width),0===o.statsToReport.uint32_video_height&&(o.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?s.remoteVideoTrack:s.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(o.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(o.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*XC(10,6)))}})),!HD(i)){let e="".concat(n,"_main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&null!=s&&s.remoteAudioTrack.isSubscribed&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,s.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=s.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/$O*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/$O,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():Eb.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&ok))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&lk))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&ck))>=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:s,totalAudioDelay:o,totalVideoDelay:a}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),n&&o&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(o/n),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),s&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/s))}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,ik.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,ik.VIDEO)),e.statsToReport.uint32_video_render_first&&(e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,gG));let{badCaseDetector:s}=this._room,{dataFreeze:o,count:a}=s.getDataFreezeDuration(t),{renderFreeze:c}=s.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=a,e.statsToReport.uint32_video_block_time=Math.min(o,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),s.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})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>gG&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+gG):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>gG&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+gG):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>gG&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+gG)}getReportData(){this._basicInfo.uint32_networkType=uD();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new TG({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:jD(this._signalInfo.relayIp),uint32_client_ip:jD(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*XC(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:jD(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return iN(e),e}report(){return ob(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(pO){this._log.warn(pO)}finally{this.isDestroyed&&(this._room=null)}}))}upload(e){return ob(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=yield oN(e),r=i instanceof ArrayBuffer,n="".concat(oD(t,Kb.KEY_POINT),"&gzip=").concat(+r),s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(n,i));let o=[this.uploadKVStat(IP),this.uploadKVStat(SP)];s||o.push(sN({url:n,body:i,priority:"low"})),yield Promise.all(o)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return ob(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=$C(ZC({},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 oN(t),r="".concat(oD(+this._room.sdkAppId,Kb.KV_STAT),"&gzip=").concat(+(i instanceof ArrayBuffer)),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(r,i)),n||sN({url:r,body:i})}))}};rb([HM({settings:{timeout:500,retries:3}})],fG.prototype,"upload",1);var gG=5e3,EG={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_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},TG=class{constructor(e){nb(this,"str_identifier"),nb(this,"str_tinyid"),nb(this,"uint32_role"),this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},vG=fG,yG=class{constructor(){nb(this,"_startTime"),nb(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=VD())}stop(){0===this._endTime&&(this._endTime=VD())}getDuration(){return 0===this._endTime?VD()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},SG=class{constructor(e){nb(this,"_room",null),nb(this,"_durationMap"),nb(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(rO.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(rO.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(rO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;var n;let{userId:s}=r;if(!this.hitTest(t))return;i.hasAudio&&!r.hasAudio&&this.stopDurationItem("".concat(s,"_main"),ik.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(s,"_main"),ik.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(s,"_auxiliary"),ik.VIDEO);let o=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(s);o&&(!i.hasAudio&&r.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,ik.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,ik.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,ik.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>tO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>tO.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{track:t}=e;if(!this.hitTest(t.room))return;let{userId:i,streamType:r,kind:n}=t;t.isSubscribed?this.addDuractionItem(i,n,r):this.stopDurationItem("".concat(i,"_").concat(r),n)}handleUnsubscribed(e){let{track:t}=e;this.hitTest(t.room)&&this.stopDurationItem("".concat(t.userId,"_").concat(t.streamType),t.kind)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new yG,s=this._durationMap.get(r);s?this.isRecording(s[t])||s[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===ik.AUDIO?[n]:[],video:t===ik.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()}},IG=class{constructor(e){nb(this,"_room"),nb(this,"_renderFreezeMap",new Map),nb(this,"_isVideoPlayingEventFiredMap",new Map),nb(this,"_dataFreezeMap",new Map),nb(this,"_monitorFreezeData",new Map),nb(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(rO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(rO.PLAY_TRACK_START,this.onPlayTrackStart).set(rO.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,s="".concat(n,"_").concat(i);this.stopDataFreeze({key:s,userId:n,type:i})})).set(rO.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(rO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(t.isRemote&&t.room&&this.hitTest(t.room)&&n===ik.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===ik.MUTE?this.onVideoTrackMuted(t):r===ik.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(rO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>tO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>tO.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),s=new yG;n?n.durationItemList.push(s):this._dataFreezeMap.set(r,{userId:t,type:i,durationItemList:[s],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 s=n.durationItemList[n.durationItemList.length-1];s.stop();let o=s.getDuration();o>Bk?this._monitorFreezeData.set(t,{userId:i,type:r,duration:o}):n.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return ob(this,arguments,(function(e){var t=this;let{userId:i,fps:r,type:n}=e;return function*(){let e="".concat(i,"_").concat(n),s=t._renderFreezeMap.get(e);if(r<=2){let r=VD();s&&!s.isFreeze&&(s.freezeTimeline.push({startTime:r,endTime:0}),s.isFreeze=!0),s||t._renderFreezeMap.set(e,{userId:i,type:n,isFreeze:!0,freezeTimeline:[{startTime:r,endTime:0}],renderFreezeTotal:0})}else if(s&&s.isFreeze){s.isFreeze=!1;let e=s.freezeTimeline.pop();if(e){e.endTime=VD();let t=e.endTime-e.startTime;s.freezeTimeline.push(e),s.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room)||t.kind!==ik.VIDEO||!t.isRemotePublished)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()<Bk&&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=VD()-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()}},RG=ib(ab(),1),AG=[1,0,0,0,1,1,0,1],CG=class extends QU{constructor(e,t){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:t}),e instanceof dF)try{this.setTexBuffer(AG)}catch(Nk){e.destroy(new vb({code:Eb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(Nk.message||Nk)}))}}draw2d(e,t,i,r,n){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let s=super.draw2d(e,t,i,r,n);return this.ctx2d.restore(),s}return!1}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}},bG=class{constructor(e,t){this.node=e,this.layout=t,nb(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}},kG=class extends QU{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),nb(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new bG(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 dF&&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:s}=this,o=Date.now(),a=(e-this.lastInfo.totalFrames)/((o-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:i,width:r,height:n,timestamp:o,fps:a,name:s},ZC({parent:this.inputs.filter((e=>e)).map((e=>e.node.getInfo()))},this.lastInfo)}close(){super.close(),this.inputs.forEach((e=>{var t,i;if(e&&(null==(t=e.node)||t.disconnect(),e.positionBuffer&&this.context instanceof dF))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(gO){}}))}},DG=class extends oF{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log}),nb(this,"_bgTexture"),nb(this,"_waterMarkTexture"),nb(this,"_lastMaskTexture"),nb(this,"_lastMaskFbo"),nb(this,"_textureValid",!1),nb(this,"_selfieTextureValid",!1),nb(this,"_selfieSegmentation"),nb(this,"wasm"),nb(this,"_prePrograme"),nb(this,"_segmentationMask"),nb(this,"_weixin",!1),t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(t)}catch(mO){e.log.error(mO),e.destroy(new vb({code:Eb.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(mO.message||mO)}))}}init(e){let t=e.Wasm,i=this.context.ctx;if(this.wasm=new t.AllIn1(i),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:i,width:r,height:n}=e.waterMark;this.wasm.setWaterMark(t,i,r,n)}if(e.beautyParams){let{beauty:t,brightness:i,ruddy:r}=e.beautyParams;this.wasm.setBeauty(t,i,r,null==e?void 0:e.width,null==e?void 0:e.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),i.uniform1i(i.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(i.uniform1i(i.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(i.uniform1i(i.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),i.uniform1i(i.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(i.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\nuniform sampler2D u_texture;\nuniform sampler2D mask;\n\nin vec2 v_texCoord;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);\n}"),t=this.context.createShader(i.VERTEX_SHADER,"#version 300 es\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_texCoord;\nvoid main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n v_texCoord = a_texCoord;\n}");this._prePrograme=this.context.createProgram(t,e),i.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),i.uniform1i(i.getUniformLocation(this._prePrograme,"mask"),1)}}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 s=this.context.ctx,{image:o}=this;this.tryVideoFrameCallback(o);let{videoWidth:a,videoHeight:c}=o;if(0===a||0===c)return!1;o.width=a,o.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?s.texSubImage2D(s.TEXTURE_2D,0,0,0,s.RGBA,s.UNSIGNED_BYTE,o):(this.resize(a,c),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,o)),this._weixin&&(s.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(s.activeTexture(s.TEXTURE1),null==(i=this._selfieSegmentation)||i.bindTexture2d(this._segmentationMask),s.bindFramebuffer(s.FRAMEBUFFER,this._lastMaskFbo||null)),s.drawArrays(s.TRIANGLE_STRIP,0,4),null==(r=this._selfieSegmentation)||r.bindTexture(),this._segmentationMask?s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,0,0,a,c):s.copyTexImage2D(s.TEXTURE_2D,0,s.RGBA,0,0,a,c,0)),null==(n=this._selfieSegmentation)||n.send(a,c),this.totalFrames||(s.activeTexture(s.TEXTURE2),s.bindTexture(s.TEXTURE_2D,this._bgTexture||null),s.activeTexture(s.TEXTURE3),s.bindTexture(s.TEXTURE_2D,this._waterMarkTexture||null),s.drawArrays(s.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()}},NG=class extends QU{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:"\n precision highp float;\n uniform sampler2D ySampler;\n uniform sampler2D uSampler;\n uniform sampler2D vSampler;\n varying highp vec2 textureCoord;\n const mat4 YUV2RGB = mat4(\n 1.1643828125, 0, 1.59602734375, -.87078515625,\n 1.1643828125, -.39176171875, -.81296875, .52959375,\n 1.1643828125, 2.017234375, 0, -1.081390625,\n 0, 0, 0, 1);\n void main() {\n vec3 yuv;\n yuv.r = texture2D(ySampler, textureCoord).r;\n yuv.g = texture2D(uSampler, textureCoord).r;\n yuv.b = texture2D(vSampler, textureCoord).r;\n gl_FragColor = vec4(yuv,1) * YUV2RGB;\n }\n ",vertexShaderSource:"\n attribute vec4 vertexPos;\n attribute vec2 texturePos;\n varying vec2 textureCoord;\n void main() {\n gl_Position = vertexPos;\n textureCoord = texturePos;\n }"}),nb(this,"yTextureRef"),nb(this,"uTextureRef"),nb(this,"vTextureRef"),nb(this,"Y"),nb(this,"U"),nb(this,"V"),this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let i=this.context.ctx,r=i.createTexture();return i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_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.bindTexture(i.TEXTURE_2D,null),i.uniform1i(i.getUniformLocation(this.program,e),t),r}render(e){let t=this.context.ctx,i=this.width,r=this.height;return this.useProgram(),t.viewport(0,0,i,r),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,i,r,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,i/2,r/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,i/2,r/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let i=this.context.ctx;i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,this.yTextureRef),i.texImage2D(i.TEXTURE_2D,0,i.LUMINANCE,e,t,0,i.LUMINANCE,i.UNSIGNED_BYTE,null),i.activeTexture(i.TEXTURE1),i.bindTexture(i.TEXTURE_2D,this.uTextureRef),i.texImage2D(i.TEXTURE_2D,0,i.LUMINANCE,e/2,t/2,0,i.LUMINANCE,i.UNSIGNED_BYTE,null),i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,this.vTextureRef),i.texImage2D(i.TEXTURE_2D,0,i.LUMINANCE,e/2,t/2,0,i.LUMINANCE,i.UNSIGNED_BYTE,null)}},wG=[e=>{e.codec="avc1.420028"},e=>{delete e.hardwareAcceleration}],OG=(e,t)=>{switch(e){case"webCodecs":return"videoFrame"===t?514705:514706;case"wasm":return"webgl"===t?514707:"videoFrame"===t?514708:514709}throw new Error("decoder type not supported")},PG=0,MG=class{constructor(e){nb(this,"id",PG++),nb(this,"trackDoneOB"),nb(this,"startOB"),nb(this,"stopOB"),nb(this,"decoder"),nb(this,"videoContext"),nb(this,"gop",0),nb(this,"gop_helper",0),nb(this,"waitFirstKeyFrame",!0),nb(this,"startTimestamp",0),nb(this,"startTime",0),nb(this,"startPerformanceTime",0),nb(this,"inputFrameCount",0),nb(this,"decodedFrameCount",0),nb(this,"downgradeLevel",0),nb(this,"config"),nb(this,"gop_before_configure",[]),nb(this,"videoElement"),nb(this,"type","wasm"),nb(this,"goodType","webCodecs"),nb(this,"renderer","2d"),nb(this,"wasmOption"),nb(this,"createDecoder"),nb(this,"_decodeSink"),nb(this,"isReported",!1),nb(this,"track"),nb(this,"stateChangeOB"),nb(this,"failedReason");let{track:t,createDecoder:i}=e;if(this.stateChangeOB=uV(),this.track=t,this.createDecoder=i,this.wasmOption={yuvMode:"webgl"===e.renderer,wasmPath:e.wasmPath,workerMode:e.workerMode,canvas:e.canvas},this.config=e.config,this.videoElement=e.videoElement,this.renderer=e.renderer,this.trackDoneOB=yV(t.availableState,bM.OFF),this.stopOB=uV(this.trackDoneOB),"auto"===e.type){switch(e.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode="webgl"===this.renderer}else this.type=e.type;this.changeRenderer(this.renderer),jx(this.stateChangeOB,uU(((e,i)=>(e!==i&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:e,state:i}),i)),"INITIALIZED"),WV(this.stopOB),GU()),this.start()}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=jx(this.pipe(this.track),WV(this.stopOB),Zx());jx(t,GU((()=>{this.track.stat.framesDecoded++}),(t=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(t," retryCount: ").concat(e)),IP.addFailedEvent({key:OG(this.type,this.renderer),error:t}),e>4)this.failedReason=t,this.stateChangeOB.next("FAILED");else{if(this.goodType)return void this.start(e);switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":if("webgl"===this.renderer)this.changeRenderer("videoFrame")}this.start(e+1)}}),(()=>{this.track.log.warn("".concat(this.id," decoderOB completed")),IP.addSuccessEvent({key:OG(this.type,this.renderer)}),IP.addSuccessEvent({key:514704})}))),jx(t,GV(1),GU((()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")})))}mock(e){this._decodeSink?this._decodeSink.error(e):this.start()}close(e){this.stopOB.next(e)}changeRenderer(e){this.renderer=e,"videoFrame"===this.renderer&&!OP()&&(this.renderer="2d"),this.wasmOption.yuvMode="webgl"===this.renderer}decode(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i;if(this.failedReason)return;let r=!1;switch(31&new Uint8Array(e.data)[4]){case 5:case 7:r=!0}if(this.inputFrameCount++,"configured"!==(null==(i=this.decoder)?void 0:i.state))return this.track.log.debug("not configured ".concat(this.inputFrameCount)),r&&(this.gop_before_configure=[]),this.gop_before_configure.push(ZC({},e)),e;this.gop_before_configure.length>0&&!t&&(this.gop_before_configure.forEach((e=>{this.decode(e,!0)})),this.gop_before_configure=[]);let{timestamp:n}=e;if(r?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!r)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount));this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=VD()}let t=(n-this.startTimestamp)/90,i=Date.now()-this.startTime-t;switch(r&&((i<500?0:i/1e3|0)>0?this.downgradeLevel++:this.downgradeLevel>3&&this.downgradeLevel--),this.downgradeLevel){case 0:case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}return this.inputFrameCount<10&&this.track.log.debug("decode ".concat(this.inputFrameCount," ").concat(this.downgradeLevel," ").concat(this.gop_helper," ").concat(this.gop)),void this.decoder.decode(e)}return e}pipe(e){return t=>ob(this,null,(function*(){this._decodeSink=t,t.defer((()=>{var e,t;null==(e=this.decoder)||e.close(),null==(t=this.videoContext)||t.destroy(),delete this._decodeSink}));let{renderer:i,type:r}=this;e.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(r){case"wasm":this.decoder=this.createDecoder(r,this.wasmOption);break;case"webCodecs":for(let e=0;e<=wG.length;e++){let{supported:i}=yield VideoDecoder.isConfigSupported(this.config);if(i)break;if(e===wG.length)return void t.error(3);wG[e](this.config)}this.decoder=this.createDecoder(r);break;case"mse":throw new Error("not supported yet")}if(this.decoder.on("videoFrame",(e=>{this.decodedFrameCount++,t.next(e)})),this.decoder.on("error",(i=>{e.log.error(i),t.error("webCodecs"===r?4:8)})),yield this.decoder.initialize(this.videoElement),this.decoder.configure(this.config),"wasm"===r&&"webgl"===i){this.videoContext=new dF({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(dF.UNAVAILABLE,(i=>{e.log.error(i),t.error(7)}));let i=new NG(this.videoContext);this.decoder.on("videoCodecInfo",(e=>i.resize(e.width,e.height))),this.decoder.on("videoFrame",(e=>{[i.Y,i.U,i.V]=e,1===this.downgradeLevel?this.decodedFrameCount%2==0&&i.render(this.decodedFrameCount):i.render(this.decodedFrameCount)})),e.source=i,e.player.setCanvas(this.videoContext._canvas,2)}else if("videoFrame"===i){e.player.setCanvas();let i=new MediaStreamTrackGenerator({kind:"video"}),r=i.writable.getWriter();e.setInputMediaStreamTrack(i);let n=0;this.decoder.on("videoFrame",(t=>{n++,n<=10&&e.log.info("Frame ".concat(n," decoded width: ").concat(t.displayWidth," height: ").concat(t.displayHeight)),r.write(t)})),t.defer((()=>i.onmute=null))}else{this.videoContext=new uF({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create({alpha:!1});let t=this.videoContext.createVideoImageSource();this.decoder.on("videoFrame",(e=>{t.image=e,t.update()}));let i=new eF(this.videoContext,{name:"remotePlayer",logger:e.log});t.connect(i),e.source=t,e.player.setCanvas(this.videoContext._canvas,2)}}catch(gO){e.log.error(gO),t.error("webCodecs"===r?2:6)}}))}},LG=class extends RG.EventEmitter{constructor(e){super(),this.room=e,nb(this,"videoContext"),nb(this,"_glVideoContext"),nb(this,"_2dVideoContext"),nb(this,"destination"),nb(this,"smallVideoContext"),nb(this,"smallDestination"),nb(this,"smallTrackSource"),nb(this,"smallImageSource"),nb(this,"_isMirror",!1),nb(this,"cameraTrack"),nb(this,"cameraNode"),nb(this,"mirrorNode"),nb(this,"mixNode"),nb(this,"screenTrack"),nb(this,"screenNode"),nb(this,"selfModel",!1),nb(this,"blurRadius",3),nb(this,"arTrack"),nb(this,"Wasm"),nb(this,"waterMarkNode"),nb(this,"_waterMarkOption"),nb(this,"watermarkImageList",[]),nb(this,"_beautyParams"),nb(this,"isUsingArTrack",!1),nb(this,"_isMixScreen",!1),nb(this,"_virtualBackground"),nb(this,"_virtualBackgroundAbortCallback"),nb(this,"virtualBackgroundInstance"),nb(this,"_bgAssetPath"),nb(this,"log",sO.createLogger({id:"vm"})),nb(this,"_checkId",0),nb(this,"_use2d",!1),nb(this,"_autoSwitchRenderMode",!0),nb(this,"_selfieSegmentation"),nb(this,"encodePipeline",[]),nb(this,"decodePipeline",[]),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new uF({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 uF({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 dF({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((e=>{this.log.error(e)}))}))}catch(Db){this.emit("error",Db)}}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=PM.run("interval",(()=>{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(),PM.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Ow||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?IP.addFailedEvent({key:t,error:e}):IP.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 dF({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:s}=i;r?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new rF(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),Ow&&s.setCanvas(e);let o=e&&(null==(t=this.destination)?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),o=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info("set main output ".concat(o?o.label:"no output track")),i.setOutputMediaStreamTrack(o)}catch(mO){this.log.error("set main output failed",mO)}}update(){return ob(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===xw?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof oF?(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 oF?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 iF(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new DG(this.videoContext,{input:this.cameraTrack.mediaTrack,width:i.width,height:i.height,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 CG(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 kG(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 bx)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof Rx)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof hF){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);let t=e.mediaTrack;return e.setOutputMediaStreamTrack(t)}this.log.warn("change unknown input",null==(n=e.mediaTrack)?void 0:n.label)}removeInput(e){var t;e instanceof bx?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Rx?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof hF&&e.source&&e.source.context.destroy()}setCameraTrack(e){return ob(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 ob(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:Eb.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort(((e,t)=>e.zIndex-t.zIndex)),this.watermarkImageList.forEach((e=>{let{image:t,x:i,y:n,width:s,height:o}=e;r.drawImage(t,i,n,s,o)})),eN(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 ob(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return ob(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return ob(this,null,(function*(){var t,i;let r;try{r=yield eN((null==e?void 0:e.imageElement)||e.imageUrl)}catch(d){throw new vb({code:Eb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:n=0,y:s=0,width:o=r.width,height:a=r.height,type:c="watermark",zIndex:l=2}=e;this.watermarkImageList.some((e=>e.type===c))?(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==c)),this.pushWaterMarkImageList({x:n,y:s,width:o,height:a,image:r,zIndex:l,type:c,imageUrl:e.imageUrl}),r=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(i=this.cameraTrack)?void 0:i.settings.height),this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(r.width,r.height),this.waterMarkNode.image=r):this.update()):(this.pushWaterMarkImageList({x:n,y:s,width:o,height:a,image:r,zIndex:l,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,((e,t)=>"imageUrl"===e?void 0:t)))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return ob(this,null,(function*(){this.watermarkImageList=this.watermarkImageList.filter((t=>t.type!==e)),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,((e,t)=>"imageUrl"===e?void 0:t))),yield this.freshWatermark()}))}freshWatermark(){return ob(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 ob(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 eN(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:Eb.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})}))}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return ob(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()}createDecodeContext(e){return new MG(e)}clear(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(e){let{processor:t,type:i}=e;var r;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:i}=e;var r;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}};rb([ox((function(e){this.log.error("update failed",e)}))],LG.prototype,"update",1);var xG=0,VG=class extends bM{constructor(e){super("room"),nb(this,"seq",++xG),nb(this,"sdkAppId"),nb(this,"userId"),nb(this,"userSig"),nb(this,"privateMapKey"),nb(this,"latencyLevel"),nb(this,"tinyId"),nb(this,"scene"),nb(this,"roomId"),nb(this,"useStringRoomId"),nb(this,"role","anchor"),nb(this,"joinParams",null),nb(this,"localTracks",new Set),nb(this,"enableAutoPlayDialog",!0),nb(this,"autoReceiveAudio",!0),nb(this,"autoReceiveVideo",!0),nb(this,"proxy_ws"),nb(this,"proxy_wt"),nb(this,"proxy_unified"),nb(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}}),nb(this,"keyPointManager"),nb(this,"audioManager"),nb(this,"videoManager"),nb(this,"callDurationCalculator"),nb(this,"badCaseDetector"),nb(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),nb(this,"videoDecodeFallbackType"),nb(this,"_isUsingCachedSchedule",!1),nb(this,"_log",sO.createLogger({id:"r".concat(this.seq)})),nb(this,"_joinedTimestamp",0),nb(this,"_sdkType"),nb(this,"heartbeatReport"),nb(this,"quality"),nb(this,"enableSEI"),nb(this,"isDestroyed",!1),this.useStringRoomId=!!e.useStringRoomId,bD(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),bD(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),bD(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new vG({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new SG({room:this}),this.badCaseDetector=new IG({room:this}),this.audioManager=new wx(this),this.videoManager=new LG(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 ob(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return ob(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return ob(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(AD(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(TD(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:r,scheduleProxy:n,unifiedProxy:s}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=s,s?(sB([s,s]),Lb("https://".concat(s))):(r&&Lb(r),n&&sB(n))}tO.once(rO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:nB.main,sched_back_domain:nB.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return ob(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return ob(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 ob(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:Eb.INVALID_OPERATION,message:pP({key:lP.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(dP.INVALID_DESTROY),new vb({code:Eb.INVALID_OPERATION,message:pP({key:lP.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,tO.emit(rO.ROOM_DESTROY,{room:this})}schedule(e,t){return ob(this,null,(function*(){var i,r,n;let s=VD();try{let{isCached:o,result:a,detailCost:c}=yield rB({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:bb,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(XD(a,{keysToExclude:["username","credential"]}))),o&&tO.once(rO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=ZC(ZC({},this.scheduleResult),a),CD(null==(i=a.config)?void 0:i.retryCount)&&kk(a.config.retryCount),AD(null==(r=a.config)?void 0:r.loggerDomain)&&Lb(a.config.loggerDomain),this.videoDecodeFallbackType=(null==(n=a.config)?void 0:n.videoDecodeFallback)||this.videoDecodeFallbackType,tO.emit(rO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:c}),IP.addSuccessEvent({key:521700,cost:VD()-s,split:50})}catch(o){throw IP.addFailedEvent({key:521700,error:o}),o}}))}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}},UG=ib(ab()),FG=ib(_b());function BG(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 HG=(e,t)=>ob(void 0,null,(function*(){var i;let r=rG(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 s=r.media[0],o=r.media[1];s.ext&&(n.audio.extensions=s.ext.map((e=>({id:e.value,uri:e.uri})))),o.ext&&(n.video.extensions=o.ext.map((e=>({id:e.value,uri:e.uri}))));let a={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channels:s.rtp[0].encoding,rtcpfb:[],rtx:0};null==(i=s.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=[...BG(o)].filter((e=>c.includes(e.codec.toLocaleLowerCase()))),n.video.decoders=(yield function(){return ob(this,null,(function*(){let e=new RTCPeerConnection;e.addTransceiver(ik.VIDEO,{direction:ik.TRANSCEIVER_DIRECTION_RECVONLY});let t=yield e.createOffer();if(!t.sdp)return[];let i=BG(rG(t.sdp).media[0]);return e.close(),i}))}()).filter((e=>["h264","vp8"].includes(e.codec.toLocaleLowerCase()))),n})),GG=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,s=rG(r),o={extmapAllowMixed:"extmap-allow-mixed",groups:s.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:ik.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:s.media[0].port,protocol:s.media[0].protocol,type:ik.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 o.media.push(a),[1,2,3].forEach((e=>{o.media.push(WG({mid:e,serverAbility:t,clientAbility:i,parsedOffer:s}))})),n&&o.media.push(s.media.find((e=>"dc"===e.mid))),nG(o)},WG=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,isDownlink:s=!1}=e,o={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:ik.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:ik.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(s){let e=i.video.decoders;(!e||0===e.length)&&(e=i.video.codecs),(!e||0===e.length)&&(e=r.video.decoders),e.forEach((e=>{jG(o,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];jG(o,t)}return o},jG=(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.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 JG=(e,t,i)=>{let r=FG.default.parse(e);return r.media.forEach(((e,n)=>{var s;if((e.type===ik.AUDIO||e.type===ik.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===ik.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===ik.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===ik.VIDEO))if(n<4)e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach((t=>jG(e,t)));else if(i){e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[];let r=i.video.decoders;(!r||0===r.length)&&(r=i.video.codecs),(!r||0===r.length)&&(r=t.video.decoders),r.forEach((t=>jG(e,t)))}null!=(s=e.payloads)&&s.includes("datachannel")&&r.groups&&e.mid&&(r.groups[0].mids=r.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),FG.default.write(r)},KG=ib(ab()),qG=class extends KG.EventEmitter{constructor(e){super(),this.room=e,nb(this,"mainFpsHealth",1),nb(this,"mainBitrateHealth",1),nb(this,"badMainBitrateHealthCount",0),nb(this,"lastEmitBadHealthTime",0),nb(this,"log"),!CN&&Cw&&tO.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(){tO.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};nb(qG,"EVENT_BAD_HEALTH","bad_health");var zG=qG;function YG(e){let{seiMessageList:t,isAudio:i,isMain:r}=e;return new TransformStream({transform(e,n){let s=e;i?audioEncodePipeline.forEach((e=>{s=e({frame:s})})):videoEncodePipeline.forEach((e=>{s=e({frame:s,seiMessageList:t,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:s.data,userId:"",streamType:r?"main":"auxiliary"})}})})),n.enqueue(s)}})}function XG(e,t,i){return new TransformStream({transform(r,n){let s=r;videoDecodePipeline.forEach((r=>{s=r({frame:s,onSEI:i=>{i.forEach((i=>{self.postMessage({type:"sei",seiPayloadType:i.seiPayloadType,data:i.seiPayload.buffer,userId:e,streamType:t})}))},onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:s.data,userId:e,streamType:t})}})})),n.enqueue(s)}})}var QG=(e=>(e.TRACK="track",e.DATA_CHANNEL_MESSAGE="data_channel_msg",e[e.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",e[e.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",e.RECONNECTED="spc-reconnected",e.RECONNECT_FAILED="spc-reconnect-failed",e.ERROR="error",e.SEI_MESSAGE="sei-message",e.DUMP="dump",e))(QG||{}),ZG=0,$G=!1,eW=new Set,tW=1,iW=class extends UG.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),nb(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),nb(this,"currentState","DISCONNECTED"),nb(this,"_room"),nb(this,"_signalChannel"),nb(this,"_peerConnection",null),nb(this,"_datachannel",null),nb(this,"_enableCustomMessage"),nb(this,"_log"),nb(this,"_downlinkMIDMap",new Map),nb(this,"_downlinkMIDUserIDMap",new Map),nb(this,"_reconnectionTimer",-1),nb(this,"reconnectionCount",0),nb(this,"clientAbility"),nb(this,"_serverAbility",null),nb(this,"addDownlinkQueue",new Set),nb(this,"removeDownlinkQueue",new Set),nb(this,"_parsedAnswer",null),nb(this,"_updateSDPPromise",null),nb(this,"_waitForPCConnectedPromise"),nb(this,"clearConnectTimeout"),nb(this,"_isSDPLogged",!1),nb(this,"enableInsertableStreams",!1),nb(this,"insertableStreamsAbortMap",new Map),nb(this,"receiverRemoteTrackMap",new WeakMap),nb(this,"scriptTransformWorker"),nb(this,"_isRelayTried",!1),nb(this,"_rttOverCount",0),nb(this,"originOffer",null),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=sO.createLogger({id:"spc".concat(tW++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(sM?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=rG(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&&!RD(e.ssrcs[0].id)){let n=Number(e.ssrcs[0].id),s=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=s;break;case 2:i.smallVideoSsrc=n,i.smallVideoRtxSsrc=s;break;case 3:i.auxVideoSsrc=n,i.auxVideoRtxSsrc=s}}})),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(){oM&&(this.scriptTransformWorker=function(e){let t=[yx],i=[xB,MB,LB,PB,YG,XG],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,s=n.isReceiver?XG(n.userId,n.streamType,n.isAudio):YG({isAudio:n.isAudio,seiMessageList:n.isMain?n.small?i:e:t,isMain:n.isMain});r.transformer.readable.pipeThrough(s).pipeTo(r.transformer.writable)}}),")();").concat(r,"})()"),s=new Blob([n],{type:"text/javascript"}),o=URL.createObjectURL(s),a=new Worker(o);return URL.revokeObjectURL(o),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),"dump"===e.data.type&&this.emit("dump",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}getPeerConnectionConfig(e){let t={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};return this._log.debug("getPeerConnectionConfig",JSON.stringify(t)),t}initialize(e){return ob(this,null,(function*(){var t;let i;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let e=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(e)),"checking"===e&&0===this.stat.iceStartTime?this.stat.iceStartTime=Date.now():"connected"===e&&0===this.stat.iceEndTime?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),IP.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):"failed"===e&&IP.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var e;let t=(null==(e=this._peerConnection)?void 0:e.signalingState)||"";this._log["closed"===t?"debug":"info"]("signaling state: ".concat(t))},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 nW(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(ik.AUDIO,{direction:ik.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(ik.VIDEO,{direction:ik.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(ik.VIDEO,{direction:ik.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(ik.VIDEO,{direction:ik.TRANSCEIVER_DIRECTION_SENDONLY}),i=yield this._peerConnection.createOffer(),this.clientAbility=yield HG(i.sdp,(null==(t=this._room.scheduleResult.config)?void 0:t.remove264FromSDP)||!1),this.originOffer=i,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()))}),IP.addSuccessEvent({key:521707}),this.clientAbility}catch(gO){throw IP.addFailedEvent({key:521707,error:gO}),this._log.error("initialize failed ".concat(gO," \noffer: ").concat(null==i?void 0:i.sdp)),gO}}))}setIceServers(e){return ob(this,null,(function*(){var t;if(this._peerConnection){if(this._log.info("setIceServers",JSON.stringify(e)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),null!=(t=this._peerConnection)&&t.localDescription||!this.originOffer)return void this._log.warn("setIceServers warning, already has localDescription or no origin Offer");yield this.setOffer(this.originOffer)}}))}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(Nk){this._log.warn("setPriority error ",Nk)}}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return ob(this,null,(function*(){var i,r,n;try{if("CONNECTED"===this.currentState)return;(null==(i=this._peerConnection)||!i.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let s=VD(),o={type:"answer",sdp:GG({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(o),yield this.waitForPeerConnectionConnected();let a=(null==(r=this._room.scheduleResult.config)?void 0:r.priority)||(null==(n=this._room.joinParams)?void 0:n.priority)||new URLSearchParams(location.search).get("priority");a&&this.setPriority(a),t||IP.addSuccessEvent({key:521703,cost:VD()-s})}catch(_O){let i=_O instanceof vb&&_O.code===Eb.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(_O),e),this.reset(),!i&&!this.isReconnecting&&(IP.addFailedEvent({key:521703,error:_O}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),_O}}))}reconnect(){return ob(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(uH,this.reconnect,this);try{this.reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let e=this._signalChannel.getBackupRelayIpPair(),t=yield this.initialize(this._room.getIceServers(null!=e&&e.iceServer?[e.iceServer]:[])),i=ZC({ability:t},e),r=yield this._signalChannel.sendWaitForResponse({command:HH,responseCommand:gH.REBUILD_PEER_CONNECTION_RES,data:i,enableLog:!1});if(0!==r.data.code)throw new vb({code:r.data.code,message:r.data.message});yield this.connect(r.data.data.ability,!0),IP.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),tO.emit(rO.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(Db){if(!this.isReconnecting)return;if(null!=Db&&Db.message.includes("timeout")){let e=yD(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield rN(e,(e=>{this._reconnectionTimer=e})),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(null==Db?void 0:Db.code," ").concat(Db)),IP.addFailedEvent({key:521704,error:Db}),this.reconnectionCount>=Dk()&&this._log.warn("SDK has tried reconnect for ".concat(Dk()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")}))}getPeerConnection(){return this._peerConnection}startReconnection(){return ob(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(uH,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){var t;let i=(null==(t=this._peerConnection)?void 0:t.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info("connectionState: ".concat(e.target.connectionState," ICE: ").concat(i," DTLS: ").concat(r)),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()),tO.emit(rO.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 Ak;let e=null;return zP()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,qP()&&0!==this._peerConnection.getReceivers().length&&e?e.state:Ak):Ak}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(QG.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return ob(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(BP(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&&dD(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(s),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(s),n(),t(new vb({code:Eb.API_CALL_ABORTED,message:pP({key:lP.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{tO.off(rO.LEAVE_SUCCESS,r,this),this.off(QG.CONNECTION_STATE_CHANGED,i,this)},s=setTimeout((()=>{n();let e=new vb({code:Eb.API_CALL_TIMEOUT,message:"connection timeout"});var i;ZG+=1,i=this._signalChannel.isConnected,ZG>2&&!$G&&0===eW.size&&i&&(this._log.warn("firewall restriction"),$G=!0,this.emit(QG.FIREWALL_RESTRICTION)),t(e)}),jk);this.clearConnectTimeout=()=>{n(),clearTimeout(s),delete this.clearConnectTimeout},tO.on(rO.LEAVE_SUCCESS,r,this),this.on(QG.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 ob(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(Nk){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(Nk)),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=ik.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=rG(this._peerConnection.remoteDescription.sdp));let s,o,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)s=c[0],o=c[1],a=c[2];else if(3===n.length)s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[0]))),o=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(ik.AUDIO,{direction:ik.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(ik.VIDEO,{direction:ik.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(ik.VIDEO,{direction:ik.TRANSCEIVER_DIRECTION_RECVONLY}),s=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=WG({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:rG(this._peerConnection.localDescription.sdp),isDownlink:!0});o=JSON.parse(JSON.stringify(e)),a=JSON.parse(JSON.stringify(e)),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a)}s.direction=ik.TRANSCEIVER_DIRECTION_SENDONLY;let l="".concat(r,"-").concat(t.audio);s.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(l)},{id:t.audio,attribute:"msid",value:"".concat(l,"-").concat(ik.MAIN," ").concat(l,"-audio")}],o.direction=ik.TRANSCEIVER_DIRECTION_SENDONLY,o.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(ik.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(ik.MAIN," ").concat(l,"-bigvideo")}],o.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=ik.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(ik.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(ik.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(ik.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,[s.mid,o.mid,a.mid]),this._downlinkMIDUserIDMap.set(s.mid,i),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(a.mid,i)}removeDownlink(e){return ob(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=rG(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 ob(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(tM()){let e=this._peerConnection.getSenders().slice(0,4);for(let o=0;o<e.length;o++){let s,a=e[o];0===o&&t?s=t:1===o&&i?s=i:2===o&&r?s=r:3===o&&n&&(s=n),s&&(yield this.setSenderMaxBitrate(a,s))}let s=!1;i&&e[1].track&&(s=this.setStartBitrate(1,i)),n&&e[3].track&&(s=this.setStartBitrate(3,n)||s),s&&(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=rG(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 s=rG(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=rG(this._peerConnection.remoteDescription.sdp));let o=NN?"TIAS":"AS";t&&(s.media[0].bandwidth=[{type:o,limit:NN?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:o,limit:NN?1e3*t:t}]),i&&(s.media[1].bandwidth=[{type:o,limit:NN?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:o,limit:NN?1e3*i:i}]),r&&(s.media[2].bandwidth=[{type:o,limit:NN?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:o,limit:NN?1e3*r:r}]),n&&(s.media[3].bandwidth=[{type:o,limit:NN?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:o,limit:NN?1e3*n:n}]);let a={type:"offer",sdp:nG(s)};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(RD(n)?1===t:t===n)return;let s="setScaleResolutionDownBy ".concat(i," ").concat(t);return n&&(s+=" prevScale: ".concat(n)),this._log.warn(s),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=nG(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,r)=>ob(this,null,(function*(){var n,s;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(o){this._log.error(o),!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==(s=this._peerConnection.remoteDescription)?void 0:s.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(o)}})))),this._updateSDPPromise}setTransceiverDirection(e,t){return ob(this,null,(function*(){if(!NN||!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===rk.INACTIVE&&t===rk.RECVONLY&&(this._parsedAnswer.media[r].direction=e),e===rk.SENDONLY&&t===rk.INACTIVE&&(this._parsedAnswer.media[r].direction=rk.RECVONLY)}yield this.updateSDP()}))}filterSDPDirection(){return rG(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((e=>e.direction))}setOffer(e){this._log.info("setting offer");let t=JG(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return ob(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach((i=>{var r;if(i.type===ik.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=[],jG(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 ob(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];RD(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===ik.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=[],jG(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(){this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),this._waitForPCConnectedPromise=null,this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach((e=>cN(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,s=Math.max(t,i),{rttRatioThreshold:o,rttThreshold:a}=(null==(r=this._room.scheduleResult.config)?void 0:r.useTurnTcpInfo)||{};if(!(o&&a&&n&&s))return;let c=Math.floor(s/n),l=(this._isRelayTried||c>o)&&s>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 ob(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")),IP.addSuccessEvent({key:r,cost:Date.now()-t})}catch(Nb){this._log.warn("switchRelay ".concat(i," failed"),Nb),IP.addFailedEvent({key:r,error:Nb}),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.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};rb([mx("reconnect")],iW.prototype,"startReconnection",1),rb([_x((e=>e.userId))],iW.prototype,"addDownlink",1),rb([_x((e=>e))],iW.prototype,"removeDownlink",1),rb([px(!0)],iW.prototype,"updateSDP",1),rb([fx(521712,!1)],iW.prototype,"setOffer",1),rb([fx(521713,!1)],iW.prototype,"setAnswer",1);var rW=class{constructor(e){nb(this,"tag"),nb(this,"len"),nb(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}},nW=class{constructor(e){nb(this,"tinyId"),nb(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),s=new rW(new Uint8Array(e).slice(i,i+2+2+n).buffer);r.push(s),i+=4+n}r.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},sW=new Set;function oW(){let e=Math.floor(4294967296*Math.random());return sW.has(e)?oW():(sW.add(e),e)}var aW=ib(ab()),cW=class extends aW.default{constructor(e){super(),nb(this,"userId"),nb(this,"tinyId"),nb(this,"_sdpSemantics"),nb(this,"_isUplink"),nb(this,"_room"),nb(this,"_log"),nb(this,"_currentState","DISCONNECTED"),nb(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=sO.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&&(tO.emit(rO.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"))}},lW=class extends cW{constructor(e){super($C(ZC({},e),{isUplink:!0})),nb(this,"localMainAudioTrack",null),nb(this,"localMainVideoTrack",null),nb(this,"localAuxAudioTrack",null),nb(this,"localAuxVideoTrack",null),nb(this,"_isPublishingAux",!1),nb(this,"_publishingLocalAudioTrack"),nb(this,"_publishingLocalVideoTrack"),nb(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}),nb(this,"_flag",0),nb(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:s,auxVideoRtxSsrc:o}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:s||0,auxiliaryRtx:o||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=PM.run("timeout",(()=>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(Qw()," ").concat(qw())),IP.addCount({key:521e3})}PM.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 s=this._peerConnection.getSenders();s&&(YP()?(n.audio=!(null==(e=s[0])||!e.track),n.bigVideo=!(null==(t=s[1])||!t.track),n.smallVideo=!(null==(i=s[2])||!i.track),n.auxVideo=!(null==(r=s[3])||!r.track)):s.forEach((e=>{e.track&&(e.track.kind===ik.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}get publishingState(){let{publishState:e}=this,t=ZC({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}get serverPublishState(){return{audio:!!(this.flag&lk),bigVideo:!!(this.flag&ok),smallVideo:!!(this.flag&ak),auxVideo:!!(this.flag&ck)}}get muteState(){var e,t,i;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(i=this.localAuxVideoTrack)||!i.muted)}}initialize(){this.installEvents()}close(e){var t;let i=(null==(t=this._peerConnection)?void 0:t.getSenders())||[];for(let r of i)r.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;null!=(e=this.singlePC)&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(t=this.singlePC)||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var i,r,n;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:s,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:s,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:s,state:e}))),o}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 ob(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e,s,o,a,c,l,d;if(!t.singlePC)return;t.installEvents(),yield t.singlePC.waitForPeerConnectionConnected();let u,{publishState:h,muteState:p}=t;if(i&&(t._publishingLocalAudioTrack=i,h.audio=!0,p.audio=i.muted),r){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new vb({code:Eb.NOT_SUPPORTED_H264,message:pP({key:lP.NOT_SUPPORTED_H264ENCODE})});CN&&115===Aw()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to 480p"),r.setProfile(ek["480p_2"]),yield r.applyProfile()),t._publishingLocalVideoTrack=r,n?(h.auxVideo=!0,p.auxVideo=r.muted):(h.bigVideo=!0,p.bigVideo=r.muted)}if(t._isPublishingAux=n,r&&!n&&r.small&&(u=t._room.videoManager.smallTrack,h.smallVideo=!0),yield t._signalChannel.sendWaitForResponseWithRetry({command:WH,responseCommand:gH.SPC_PUBLISH_RESULT,data:$C(ZC({},t.singlePC.uplinkSSRC),{state:h,muteState:p}),retries:3}),yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:u,isAuxiliary:n}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r){t[n?"localAuxVideoTrack":"localMainVideoTrack"]=r;let{scaleResolutionDownBy:e}=r;yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[n?3:1],e,r.streamType)}i&&(t[n?"localAuxAudioTrack":"localMainAudioTrack"]=i),yield t.singlePC.setBandwidth({audio:(null==(e=t.localMainAudioTrack)?void 0:e.profile.bitrate)||(null==(s=t.localAuxAudioTrack)?void 0:s.profile.bitrate),bigVideo:null==(o=t.localMainVideoTrack)?void 0:o.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),(t._room.preferHW||null!=(d=t._room.scheduleResult.config)&&d.preferHW)&&r&&r.profile.width*r.profile.height>=921600&&t.singlePC.useHWEncoder(!0,n?7:2)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!XP())return;this._log.info("publish by transceiver");let s=null==i?void 0:i.outMediaTrack,o=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[],d=(e,t,i)=>{var r,n;let s=a[t].sender.replaceTrack(i);l.push(t),null!=(r=this.singlePC)&&r.enableInsertableStreams&&s.then((()=>this.createEncodedStreams(a[t].sender,e))),null!=(n=this.singlePC)&&n.scriptTransformWorker&&this.initSenderTransfrom(a[t].sender,e),c.push(s)};o&&d(t.mediaType,0,o),s&&d(i.mediaType,n?3:1,s),r&&d(8,2,r);let u=this.singlePC.setTransceiverDirection(rk.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(),s=new AbortController;null==(i=this.singlePC)||i.addAbortController(e,s),(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)&&r.isUsingH264&&n?n.encodeFrame(e,8===t):e)}}),s):n.readable).pipeTo(n.writable,s).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 ob(this,null,(function*(){var t;if(!this.singlePC)return;let i=this._peerConnection.getTransceivers();if(e){if(this._room.videoManager.smallTrack){let{sender:e}=i[2];null!=(t=this.singlePC)&&t.enableInsertableStreams&&this.createEncodedStreams(e,8),yield e.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(rk.SENDONLY,[2])}}else yield i[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(rk.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 ob(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,s=t._peerConnection.getSenders(),o=[];i&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localMainAudioTrack&&!t.localAuxAudioTrack&&(yield s[0].replaceTrack(null),o.push(0))),n&&(e?(yield s[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=$C(ZC({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),o.push(3)):(yield s[1].replaceTrack(null),yield s[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=$C(ZC({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),o.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.singlePC.setTransceiverDirection(rk.INACTIVE,o),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 ob(this,null,(function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:RH,data:t,responseCommand:gH.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:AH,commandDesc:"unpublish",responseCommand:gH.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===Eb.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),rM){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:BH,data:this._mediaSettings,responseCommand:gH.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return ob(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?ik.AUXILIARY:ik.MAIN," stream")),YP()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return ob(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===ik.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)&&i.small&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===rk.INACTIVE&&(yield this.singlePC.setTransceiverDirection(rk.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return ob(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?ik.AUXILIARY:ik.MAIN," stream")),YP()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return ob(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===ik.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(rk.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}replaceTrack(e){return ob(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!i||0===i.length||!r||i.find((e=>e.track===r)))return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(r.kind," track ").concat(r.id," ").concat(r.label," on ").concat(n?ik.AUXILIARY:ik.MAIN," stream")),r.kind===ik.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===ik.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0}))}setBandwidth(e){return ob(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===ik.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:SH,responseCommand:gH.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&tO.emit(rO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ik.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===ik.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===ik.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===ik.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===ik.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Uk?(this._log.error(dP.NOT_SUPPORTED_H264ENCODE),new vb({code:Eb.NOT_SUPPORTED_H264,message:pP({key:lP.NOT_SUPPORTED_H264ENCODE})})):new vb({code:Eb.UNKNOWN,message:pP({key:lP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:gH.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return ob(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}))}))}};rb([sx((function(e){let{localVideoTrack:t}=e;null==t||t.once("6",this.onVideoEncodeFailed,this)}))],lW.prototype,"publish",1),rb([sx((function(e){let{localVideoTrack:t}=e;null==t||t.off("6",this.onVideoEncodeFailed,this)}))],lW.prototype,"unpublish",1);var dW=lW;function uW(e){return Object.keys(e).filter((t=>e[t]))}var hW=class extends cW{constructor(e){super($C(ZC({},e),{isUplink:!1})),nb(this,"_flag",0),nb(this,"isRobot",!1),nb(this,"role","anchor"),nb(this,"remoteAudioTrack"),nb(this,"remoteVideoTrack"),nb(this,"remoteAuxiliaryTrack"),nb(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),nb(this,"jitterBufferTimeoutId",-1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new zU(this._room,this),this.remoteVideoTrack=new hF(this._room,this),this.remoteAuxiliaryTrack=new pF(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 GD(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===ik.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,i;let r=e.streams[0],{track:n,receiver:s}=e;if(!r.id.includes(this.tinyId))return;let o=r.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(o," ").concat(n.kind));let a=ik.AUDIO;n.kind===ik.VIDEO&&(a=o===ik.MAIN?ik.VIDEO:ik.AUXILIARY);let c=this.remoteAudioTrack;a===ik.VIDEO?c=this.remoteVideoTrack:a===ik.AUXILIARY&&(c=this.remoteAuxiliaryTrack),null==(t=this.singlePC)||t.receiverRemoteTrackMap.set(s,c),null!=(i=this.singlePC)&&i.scriptTransformWorker&&this.initReceiverTransform(s,o,n.kind===ik.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s),c.setInputMediaStreamTrack(n)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),i=new AbortController,r={abortController:i,enqueue:t=>{var i,r;let n=null==(i=this.singlePC)?void 0:i.receiverRemoteTrackMap.get(e);return n&&("video"!==n.kind||null!=(r=this.singlePC)&&r.isUsingH264)?n.decodeFrame(t):t}};t.readable.pipeThrough(new TransformStream({transform:(e,t)=>{let i=r.enqueue(e);i&&t.enqueue(i)}})).pipeTo(t.writable,i).catch((e=>{"destory"!==e&&this._log.warn(e)})),this.singlePC.addAbortController(e,i)}}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 ob(this,null,(function*(){try{if(this._log.info("subscribe ".concat(t," ").concat(uW(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(mO){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(mO.message," ").concat(JSON.stringify(this.muteState))),new vb({code:Eb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):mO}}))}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"),Cw&&Dw<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return ob(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=ZC({},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 s="subscribe_change";Object.values(n).find((e=>!0===e))||(s="unsubscribe"),t._log.info("".concat("unsubscribe"===s?s:"subscribe"," ").concat(r," [").concat(uW(n),"]")),"unsubscribe"===s&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(s,n),"unsubscribe"===s&&(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=bH,n=gH.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=kH,n=gH.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:pP({key:lP.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return ob(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:oW(),bigVideoSsrc:oW(),bigVideoRtxSsrc:oW(),auxVideoSsrc:oW(),auxVideoRtxSsrc:oW()},{audioSsrc:n,bigVideoSsrc:s,bigVideoRtxSsrc:o,auxVideoSsrc:a,auxVideoRtxSsrc:c}=i;e.ssrc={audio:n,video:s,videoRtx:o,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:jH,responseCommand:gH.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;gM&&(null!=t&&t.jitterDelay||null!=t&&t.jitterDelayAux)&&e.setJitterBufferDelay({mainDelay:t.jitterDelay,auxDelay:t.jitterDelayAux})}}}()}))}removeDownlink(){return ob(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&&e.jitterDelay||null!=e&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)}))}setJitterBufferDelay(e){let{mainDelay:t,auxDelay:i}=e;if(!gM||!this.singlePC||!this._peerConnection||lN(t)&&lN(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return CD(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),CD(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,lN(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||lN(t)&&e.track===this.remoteAudioTrack.outMediaTrack;if(n&&lN(i)||!n&&lN(t))return;let s=n?i||0:t,o=(e.jitterBufferTarget||0)+100;o>s||(e.jitterBufferTarget=o,this._log.debug("set ".concat(n?"aux ":"").concat(null==(r=null==e?void 0:e.track)?void 0:r.kind," jitterBuffer delay ").concat(o," -> ").concat(s)))})),!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(Nb){this._log.warn("set jitterBuffer delay error: ".concat(Nb)),clearTimeout(this.jitterBufferTimeoutId),n()}}get audioReceiver(){var e;return(null==(e=this.singlePC)?void 0:e.getReceiversByUserId(this.userId)[0])||null}};rb([px(),ax((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:Eb.API_CALL_ABORTED,message:pP({key:lP.CONNECTION_ABORTED,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],hW.prototype,"subscribe",1),rb([px()],hW.prototype,"unsubscribe",1),rb([_x((()=>"jitter"))],hW.prototype,"setJitterBufferDelay",1);var pW=hW;var mW=ib(ab());var _W=class e extends mW.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,nb(this,"log"),nb(this,"cmdIdSeqMap",new Map),nb(this,"messageMap",new Map),this.log=sO.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(gH.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(qH,n),this.log.debug("send custom msg: ".concat(JSON.stringify(n)))}onReceiveMsg(t){let{data:i}=t.data,r=this.room.tinyIdToUserIdMap.get(i.srcTinyId);if(r){let t={userId:r,cmdId:i.cmdId,seq:i.streamSeq,data:Uint8Array.from(atob(i.msg),(e=>e.charCodeAt(0))).buffer};if(i.ordered){let i="".concat(r,"_").concat(t.cmdId),n=this.messageMap.get(i);if(n&&0!==n.lastSeq)if(Math.abs(n.lastSeq-t.seq)>e.SEQ_INTERVAL)this.messageMap.set(i,{lastSeq:t.seq,cachedMessageMap:new Map}),this.emitMessage(t);else if(t.seq>n.lastSeq){if(t.seq===n.lastSeq+1)this.emitMessage(t);else if(!n.cachedMessageMap.has(t.seq)){let e=setTimeout((()=>this.emitMessage(t,!0)),5e3);n.cachedMessageMap.set(t.seq,{message:t,timeoutId:e})}}else this.log.debug("drop message ".concat(t.userId,"-").concat(t.cmdId,"-").concat(t.seq));else n||(n={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(i,n),setTimeout((()=>this.emitMessage(t,!0)),100)),n.cachedMessageMap.set(t.seq,{message:t})}else this.emit("message",t)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(i.srcTinyId));let e=r=>{r.tinyId===i.srcTinyId&&(this.room.off("peer-join",e),this.onReceiveMsg(t))};this.room.on("peer-join",e),rN(2e3).then((()=>this.room.off("peer-join",e)))}}emitMessage(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i;let r=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),n=e;if(r){if(t){let e=[...r.cachedMessageMap.values()].sort(((e,t)=>e.message.seq-t.message.seq));e[0]&&(n=e[0].message)}0!==r.lastSeq&&n.seq-r.lastSeq>1&&this.log.debug("msg lost userId: ".concat(n.userId," seq: ").concat(r.lastSeq," -> ").concat(n.seq)),r.lastSeq=n.seq,clearTimeout(null==(i=r.cachedMessageMap.get(n.seq))?void 0:i.timeoutId),r.cachedMessageMap.delete(n.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(n))),this.emit("message",n);let s=null==r?void 0:r.cachedMessageMap.get(n.seq+1);s&&this.emitMessage(s.message)}};nb(_W,"SEQ_INTERVAL",300);var fW,gW=_W,{isString:EW,isUndefined:TW,getNetworkType:vW,isEmpty:yW}=Rb,SW=class extends VG{constructor(e){super(e),nb(this,"_businessInfo"),nb(this,"userManager"),nb(this,"_version"),nb(this,"_heartbeat",-1),nb(this,"_lastHeartBeatTime",-1),nb(this,"_stats"),nb(this,"_joinTimeout",-1),nb(this,"_firstPublishedList",null),nb(this,"_joinReject",null),nb(this,"_isRelayChanged",!1),nb(this,"sdpSemantics"),nb(this,"signalChannel",null),nb(this,"uplinkConnection",null),nb(this,"singlePC",null),nb(this,"enableSPC",QP),nb(this,"_changeBigSmallRecords",new Map),nb(this,"networkQuality"),nb(this,"_iceTransportPolicy"),nb(this,"forceRelay",!1),nb(this,"_turnServers",[]),nb(this,"_iceServersFromJoin"),nb(this,"_syncUserListInterval",-1),nb(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),nb(this,"enableSEI",!1),nb(this,"_enableAudioVolumeEvaluation",!1),nb(this,"_audioVolumeIntervalId",0),nb(this,"_enableMultiAuxStream",!1),nb(this,"_pureAudioPushMode",!1),nb(this,"_customMessageManager"),nb(this,"preferHW",!1),nb(this,"healthDetector"),nb(this,"_updateAudioLevelTaskId",-1),this._stats=new uG(this,this._log),this.userManager=new gF(this.userId,this._log),this._version=bb,this.sdpSemantics=Vk,TW(e.sdpSemantics)?cO.isUnifiedPlanDefault()&&(this.sdpSemantics=xk):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(vW())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!TW(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&QP,!TW(e.enableSPC)&&QP&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new zG(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 ob(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",(e=>{this.emit("peer-join",e)})),this.userManager.on("2",(e=>{this.closeDownLinkConnection(e,"remote user exitRoom"),this.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(e=>{var t=((e,t)=>{var i={};for(var r in e)qC.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&JC)for(var r of JC(e))t.indexOf(r)<0&&zC.call(e,r)&&(i[r]=e[r]);return i})(e,[]);tO.emit(rO.REMOTE_PUBLISH_STATE_CHANGED,ZC({room:this},t)),this.emit("remote-publish-state-changed",ZC({},t))})),this.joinParams=e,new Promise(((t,i)=>ob(this,null,(function*(){var r,n;this._joinReject=i;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(s){if(!(s instanceof vb&&s.code===Eb.SPC_INITIALIZED_FAILED))return i(s);null==(r=this.signalChannel)||r.destroy(),yield this.initialize()}let o=VD();yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),IP.addSuccessEvent({key:521708,cost:VD()-o}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(uO){IP.addFailedEvent({key:521708,error:uO}),i(uO)}this._joinReject=null}))))}))}initSinglePC(){return ob(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new iW({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",(e=>this.emit("sei-message",e))),this.singlePC.on("dump",(e=>this.emit("dump",e))),this.singlePC.once("error",(()=>this.fallbackToMPC()));try{return yield this.singlePC.initialize()}catch(Db){throw this.fallbackToMPC(),new vb({code:Eb.SPC_INITIALIZED_FAILED,message:null==Db?void 0:Db.message})}}}))}doJoin(e,t){return new Promise(((i,r)=>ob(this,null,(function*(){var n,s,o;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(pH,(e=>{this.clearJoinTimeout(),tO.emit(rO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)})),bD(null==(s=null==(n=this.scheduleResult)?void 0:n.config)?void 0:s.singlePC)&&QP&&(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:Zw(),netType:uD(),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!=(o=this.scheduleResult.config)&&o.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{r(new vb({code:Eb.JOIN_ROOM_FAILED,message:pP({key:lP.JOIN_ROOM_TIMEOUT})}))}),c),tO.emit(rO.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?GH:TH,a),this.signalChannel.once(gH.JOIN_ROOM_RESULT,(t=>ob(this,null,(function*(){this.clearJoinTimeout();let{code:n,message:s,data:o,tinyId:a}=t.data;tO.emit(rO.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=o.publishers,this._iceServersFromJoin=o.iceServer?[o.iceServer]:[],this.singlePC&&(yield this.singlePC.setIceServers(this.getIceServers()),this.singlePC.connect($C(ZC({},o.ability),{useVp8:o.ability.useVp8||!!e.useVp8})).catch((()=>{}))),i()):(this._log.error("Join room failed result: ".concat(n," error: ").concat(s)),r(new vb({code:Eb.JOIN_ROOM_FAILED,extraCode:n,message:pP({key:lP.JOIN_ROOM_FAILED,data:{error:s,code:n}})})))}))))}))))}reJoin(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return ob(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($C(ZC({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),FM.logSuccessEvent({userId:this.userId,eventType:Ok.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(QG.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof dW&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(QG.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof dG&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(Nk){this._log.warn("reJoin fail ".concat(Nk)),this.reset(),FM.logFailedEvent({userId:this.userId,eventType:Ok.REJOIN,error:Nk}),this.emit("error",new vb({code:Eb.JOIN_ROOM_FAILED,message:pP({key:lP.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return ob(this,null,(function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this.signalChannel||function(e){let t=[...zH.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 YH({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 gW(this,this.signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this.networkQuality||(this.networkQuality=new _G({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(_G.EVENT_NETWORK_QUALITY,(e=>{var t;this.emit("network-quality",e),null==(t=this.singlePC)||t.detectTCPAndUDP(e)}))),VM(this,this.signalChannel).add(dH,(e=>{tO.emit(rO.SIGNAL_CONNECTION_STATE_CHANGED,ZC({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(hH,(e=>{this.reset(),this.emit("error",e)})).add(gH.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})).add(gH.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(gH.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(gH.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(FM.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(lH,(e=>{this.tinyId=e.signalInfo.tinyId,tO.emit(rO.JOIN_SIGNAL_CONNECTION_END,{room:this})})),tO.emit(rO.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&tO.emit(rO.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this.signalChannel=e,e||UM(this)}leave(){return ob(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(Nk){}this._log.info("leave() => leaving room"),tO.emit(rO.LEAVE_SEND_CMD,{room:this}),null==(e=this.signalChannel)||e.send(vH)}))}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=PM.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),PM.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return ob(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(mF.has(e)){let t=mF.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 mF.delete(e),t}return[]}(this.userId):[],n=$C(ZC({str_sdk_version:Cb,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i),{msg_device_info:ZC({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:uD()},i.msg_device_info)});if(this.heartbeatReport=n,tO.emit(rO.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(yH,n);let e=Date.now();this._lastHeartBeatTime>0&&e-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(e-this._lastHeartBeatTime)),this._lastHeartBeatTime=e,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",$C(ZC({},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!==pk)).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:s}=e;t.unshift({userId:i,tinyId:r,flag:n,isRobot:!0,mixUserList:s})})),tO.emit(rO.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 dG&&(this.uplinkConnection=null)),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r,isRobot:n}=e,s=new(this.singlePC?pW:aG)({userId:t,tinyId:i,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:n});this.userManager.addRemotePublishedUser(s),this.installDownlinkEvents(s,t),this.emit("remote-published",s)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",(e=>{let i=e.getCode();i!==Eb.ICE_TRANSPORT_ERROR&&(i===Eb.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",$C(ZC({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=PM.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){PM.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:UH,responseCommand:gH.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 pP({key:lP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:gH.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||!eG)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 tG&&!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 ob(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),FM.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 dG({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 aG({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:Eb.INVALID_OPERATION,message:pP({key:lP.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),PM.clearTask(this._audioVolumeIntervalId))}switchRole(e){return ob(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:FH,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:gH.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:Eb.SWITCH_ROLE_FAILED,message:pP({key:lP.SWITCH_ROLE_FAILED,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof vb&&e.getCode()===Eb.API_CALL_TIMEOUT&&(e=new vb({code:Eb.SWITCH_ROLE_FAILED,message:pP({key:lP.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e}))}publish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ob(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof vx&&(t instanceof Dx?i.audio=t:e.audio=t),t instanceof Rx&&(t instanceof bx&&2===t.mediaType?i.video=t:e.video=t)}));let r=yW(e),n=yW(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new dW({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new dG({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",$C(ZC({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==Eb.ICE_TRANSPORT_ERROR&&(t===Eb.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})));let s=t.map((e=>e.kind)).join(",");r||(this._log.info("publish() => main ".concat(s)),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(s)),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 ob(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 vx&&(t instanceof Dx?i.audio=t:e.audio=t),t instanceof Rx&&(t instanceof bx&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");yW(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),yW(i)||(this._log.info("unpublish() => aux ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(gO){}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&&eM()?this.uplinkConnection.replaceTrack(e).then((t=>{t&&tO.emit(rO.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return ob(this,null,(function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return ob(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:ik.VIDEO,videoType:ik.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 ob(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=ZC({},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 s=this._changeBigSmallRecords.get(e);s&&s.options.smallVideo&&i.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),tO.emit(rO.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(sG(n),"] prev: [").concat(sG(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());tO.emit(rO.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(Nb){let i=Nb instanceof vb?Nb.getCode():Eb.UNKNOWN,n=Nb;throw Nb instanceof vb?i===Eb.REMOTE_STREAM_NOT_EXIST&&(n=new vb({code:Eb.API_CALL_ABORTED,message:pP({key:lP.API_CALL_ABORTED,data:{message:Nb.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new vb({code:i,message:pP({key:lP.SUBSCRIBE_FAILED,data:{message:Nb.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 ob(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(Nb){this._log.warn("unsubscribe() => failed ".concat(Nb))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),tO.emit(rO.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 PM.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),tO.emit(rO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&PM.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=PM.run("intervalInWorker",(()=>{var i;wL.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];null==(i=this.remotePublishedUserMap)||i.forEach((e=>{if(e.muteState.hasAudio){!wL.isRunning&&e.muteState.audioAvailable&&e.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(e):e.remoteAudioTrack.volume=0;let t=Math.floor(100*e.remoteAudioTrack.getAudioLevel());r.push({userId:e.userId,volume:t})}})),this.emit("audio-volume",r)}),{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return ob(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=PM.run("intervalInWorker",(()=>ob(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack)return void this.stopUpdateAudioLevelFromSenderStat();let e=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let t=this.uplinkConnection.localMainAudioTrack;e.forEach((e=>{"media-source"===e.type&&e.audioLevel&&(t.volume=e.audioLevel)}))}))),{delay:n,backgroundTask:t})}))}stopUpdateAudioLevelFromSenderStat(){var e;-1!==this._updateAudioLevelTaskId&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),PM.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(!iM||!i)return;let r=null==(t=i.getSynchronizationSources()[0])?void 0:t.audioLevel;CD(r)?e.remoteAudioTrack.volume=Math.min(2*r,1):i.getStats().then((t=>{t.forEach((t=>{"inbound-rtp"===t.type&&CD(t.audioLevel)&&(e.remoteAudioTrack.volume=t.audioLevel)}))}))}getLocalAudioStats(){return ob(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 ob(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 ob(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 ob(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 ob(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(Rb.getTurnServer(e)))):Rb.isPlainObject(e)&&i.push(Rb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:PH,data:e,timeout:5e3,responseCommand:gH.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:MH,data:e,timeout:5e3,responseCommand:gH.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?DH:wH,data:e,timeout:5e3,responseCommand:t?gH.START_PUBLISH_TENCENT_CDN_RES:gH.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?NH:OH,data:e,timeout:5e3,responseCommand:t?gH.STOP_PUBLISH_TENCENT_CDN_RES:gH.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:LH,data:e,timeout:5e3,responseCommand:gH.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:xH,data:e,timeout:5e3,responseCommand:gH.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:VH,data:e,timeout:5e3,responseCommand:gH.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:JH,data:e,timeout:5e3,responseCommand:gH.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch((e=>{}))}getIceServers(e){return this._turnServers.length>0?this._turnServers:this.scheduleResult.iceServers&&this.scheduleResult.iceServers.length>0?this.scheduleResult.iceServers:e||(this._iceServersFromJoin&&this._iceServersFromJoin.length>0?this._iceServersFromJoin:[])}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=Rb.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 ob(this,null,(function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:r,hasVideo:n}}=e;if(!r&&!n||!t.video&&!t.smallVideo)return;let s=this._changeBigSmallRecords.get(i);if(!s||s.isSubscribing||s.reSubscribeCount<=0)return;let{options:o,reSubscribeCount:a}=s;if(o.video&&t.video||o.smallVideo&&t.smallVideo&&r)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:o.video,smallVideo:o.smallVideo};try{if(!r&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;s.isSubscribing=!0,s.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(eD-s.reSubscribeCount,".")),s.isSubscribing=!1,s.reSubscribeCount=eD}catch(dO){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(eD-s.reSubscribeCount,".")),s.isSubscribing=!1,0===s.reSubscribeCount&&this._changeBigSmallRecords.delete(i)}}))}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:eD};this._changeBigSmallRecords.set(t.userId,i),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big"));let r=this.remotePublishedUserMap.get(t.userId);r&&this.checkSubscribeBigSmallVideo(r)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(EW(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!TW(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new vb({code:Eb.INVALID_PARAMETER,message:pP({key:lP.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!TW(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new vb({code:Eb.INVALID_PARAMETER,message:pP({key:lP.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!TW(e.userDefinePushArgs)){if(!(EW(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new vb({code:Eb.INVALID_PARAMETER,message:pP({key:lP.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}yW(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){return ob(this,null,(function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&sM)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()}))}sendSignalMessage(e){var t;return this.signalChannel?null==(t=this.signalChannel)?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new vb({code:Eb.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return null==(e=this.singlePC)?void 0:e.scriptTransformWorker}};return rb([RM(["left",bM.INIT],"joined"),HM({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"),iB(!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())}}),ax((e=>{let t=new oH;return function(i,r,n){return ob(this,null,(function*(){let s=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:Eb.INVALID_OPERATION,message:pP({key:lP.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new vb({code:Eb.INVALID_OPERATION,message:pP({key:lP.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this.role=21===i.role?"audience":"anchor",this._log.info("Join() => joining room: ".concat(s," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),tO.emit(rO.JOIN_START,{room:this,roomId:s,params:i});let o=Rb.getEnv();o||(o=qb.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(nk.OLD_CLOUD_LADDER)?o=qb.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(nk.WEBRTC)&&(o=qb.WEBRTC))),FM.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),cO.checkSystemRequirementsInternal().then((e=>{this.checkSystemResult=e,aH.call(this)}));try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Rb.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=s,this._joinedTimestamp=Rb.performanceNow(),tO.emit(rO.JOIN_SUCCESS,{room:this}),30===n&&!i.component&&FM.uploadEvent({log:"stat-conv-".concat(Number(Bw),"-").concat(location.hostname),userId:this.userId}),t}catch(_O){throw t.delete({room:this,roomId:s}),tO.emit(rO.JOIN_FAILED,{room:this,error:_O}),_O}}))}}))],SW.prototype,"join",1),rb([RM("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),ax((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return ob(this,null,(function*(){tO.emit(rO.LEAVE_START,{room:this}),yield e.call(this,...i),tO.emit(rO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),mx("leave room"),GM({fnName:"publish",validateArgs:!1}),GM({fnName:"unsubscribe",validateArgs:!1})],SW.prototype,"leave",1),rb([px(),ax((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return ob(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"capture"===e.state)),!i.length))return;tO.emit("61",{room:this});let t=e.apply(this,i);return i.forEach((e=>e.publish(this,t))),t}))})),HM({settings:{retries:Dk,timeout:e=>yD(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),tO.emit(rO.PUBLISH_FAILED,{room:this}))}})],SW.prototype,"publish",1),rb([GM({fnName:"publish"}),(fW="api-call",function(e,t,i){let r=i.value;return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let n=ux.get(this);if(n){let e=n.queue.filter(((e,i)=>{if(0===i)return!0;let r=!0;return e.args.forEach((e=>{t.find((t=>t===e))||(r=!1)})),!r||(e.reject(new vb({code:Eb.API_CALL_ABORTED,message:fW})),!1)}));n.queue=e}return r.apply(this,t)},i}),px(),ax((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})),sx((function(){var e,t;0===this.localTracks.size&&zP()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((e=>e.track&&e.replaceTrack(null))))}))],SW.prototype,"unpublish",1),rb([ox((e=>{if(e.code!==Eb.API_CALL_ABORTED)throw e})),_x((e=>e.userId))],SW.prototype,"replaceTrack",1),rb([_x((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),Ox(),ax((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})),HM({settings:{retries:Dk,timeout:e=>yD(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),tO.emit(rO.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],SW.prototype,"subscribe",1),rb([GM({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")}))}}),_x((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],SW.prototype,"unsubscribe",1),sH.create=sH._create.bind(sH,SW),sH}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TRTC=t()}(this,(function(){function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},i=function(e){try{return!!e()}catch(t){return!0}},r=!i((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),n=r,s=Function.prototype,o=s.call,a=n&&s.bind.bind(o,o),c=n?a:function(e){return function(){return o.apply(e,arguments)}},l=c,d=l({}.toString),u=l("".slice),h=function(e){return u(d(e),8,-1)},p=i,m=h,_=Object,f=c("".split),g=p((function(){return!_("z").propertyIsEnumerable(0)}))?function(e){return"String"==m(e)?f(e,""):_(e)}:_,T=function(e){return null==e},E=T,v=TypeError,y=function(e){if(E(e))throw v("Can't call method on "+e);return e},S=g,I=y,A=function(e){return S(I(e))},R=function(e){return e&&e.Math==Math&&e},C=R("object"==typeof globalThis&&globalThis)||R("object"==typeof window&&window)||R("object"==typeof self&&self)||R("object"==typeof t&&t)||function(){return this}()||Function("return this")(),b={},k={get exports(){return b},set exports(e){b=e}},D=C,N=Object.defineProperty,w=function(e,t){try{N(D,e,{value:t,configurable:!0,writable:!0})}catch(i){D[e]=t}return t},O=w,P="__core-js_shared__",M=C[P]||O(P,{}),L=M;(k.exports=function(e,t){return L[e]||(L[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.30.0",mode:"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.30.0/LICENSE",source:"https://github.com/zloirock/core-js"});var x,V,U=y,F=Object,B=function(e){return F(U(e))},H=B,G=c({}.hasOwnProperty),W=Object.hasOwn||function(e,t){return G(H(e),t)},j=c,K=0,J=Math.random(),q=j(1..toString),z=function(e){return"Symbol("+(void 0===e?"":e)+")_"+q(++K+J,36)},Y="undefined"!=typeof navigator&&String(navigator.userAgent)||"",X=C,Q=Y,Z=X.process,$=X.Deno,ee=Z&&Z.versions||$&&$.version,te=ee&&ee.v8;te&&(V=(x=te.split("."))[0]>0&&x[0]<4?1:+(x[0]+x[1])),!V&&Q&&(!(x=Q.match(/Edge\/(\d+)/))||x[1]>=74)&&(x=Q.match(/Chrome\/(\d+)/))&&(V=+x[1]);var ie=V,re=ie,ne=i,se=!!Object.getOwnPropertySymbols&&!ne((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&re&&re<41})),oe=se&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ae=b,ce=W,le=z,de=se,ue=oe,he=C.Symbol,pe=ae("wks"),me=ue?he.for||he:he&&he.withoutSetter||le,_e=function(e){return ce(pe,e)||(pe[e]=de&&ce(he,e)?he[e]:me("Symbol."+e)),pe[e]},fe="object"==typeof document&&document.all,ge={all:fe,IS_HTMLDDA:void 0===fe&&void 0!==fe},Te=ge.all,Ee=ge.IS_HTMLDDA?function(e){return"function"==typeof e||e===Te}:function(e){return"function"==typeof e},ve=Ee,ye=ge.all,Se=ge.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:ve(e)||e===ye}:function(e){return"object"==typeof e?null!==e:ve(e)},Ie=Se,Ae=String,Re=TypeError,Ce=function(e){if(Ie(e))return e;throw Re(Ae(e)+" is not an object")},be={},ke=!i((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),De=ke&&i((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Ne={},we=Se,Oe=C.document,Pe=we(Oe)&&we(Oe.createElement),Me=function(e){return Pe?Oe.createElement(e):{}},Le=Me,xe=!ke&&!i((function(){return 7!=Object.defineProperty(Le("div"),"a",{get:function(){return 7}}).a})),Ve=r,Ue=Function.prototype.call,Fe=Ve?Ue.bind(Ue):function(){return Ue.apply(Ue,arguments)},Be=C,He=Ee,Ge=function(e,t){return arguments.length<2?(i=Be[e],He(i)?i:void 0):Be[e]&&Be[e][t];var i},We=c({}.isPrototypeOf),je=Ge,Ke=Ee,Je=We,qe=Object,ze=oe?function(e){return"symbol"==typeof e}:function(e){var t=je("Symbol");return Ke(t)&&Je(t.prototype,qe(e))},Ye=String,Xe=function(e){try{return Ye(e)}catch(t){return"Object"}},Qe=Ee,Ze=Xe,$e=TypeError,et=function(e){if(Qe(e))return e;throw $e(Ze(e)+" is not a function")},tt=et,it=T,rt=function(e,t){var i=e[t];return it(i)?void 0:tt(i)},nt=Fe,st=Ee,ot=Se,at=TypeError,ct=Fe,lt=Se,dt=ze,ut=rt,ht=function(e,t){var i,r;if("string"===t&&st(i=e.toString)&&!ot(r=nt(i,e)))return r;if(st(i=e.valueOf)&&!ot(r=nt(i,e)))return r;if("string"!==t&&st(i=e.toString)&&!ot(r=nt(i,e)))return r;throw at("Can't convert object to primitive value")},pt=TypeError,mt=_e("toPrimitive"),_t=function(e,t){if(!lt(e)||dt(e))return e;var i,r=ut(e,mt);if(r){if(void 0===t&&(t="default"),i=ct(r,e,t),!lt(i)||dt(i))return i;throw pt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ht(e,t)},ft=_t,gt=ze,Tt=function(e){var t=ft(e,"string");return gt(t)?t:t+""},Et=ke,vt=xe,yt=De,St=Ce,It=Tt,At=TypeError,Rt=Object.defineProperty,Ct=Object.getOwnPropertyDescriptor,bt="enumerable",kt="configurable",Dt="writable";Ne.f=Et?yt?function(e,t,i){if(St(e),t=It(t),St(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Dt in i&&!i[Dt]){var r=Ct(e,t);r&&r[Dt]&&(e[t]=i.value,i={configurable:kt in i?i[kt]:r[kt],enumerable:bt in i?i[bt]:r[bt],writable:!1})}return Rt(e,t,i)}:Rt:function(e,t,i){if(St(e),t=It(t),St(i),vt)try{return Rt(e,t,i)}catch(r){}if("get"in i||"set"in i)throw At("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Nt=Math.ceil,wt=Math.floor,Ot=Math.trunc||function(e){var t=+e;return(t>0?wt:Nt)(t)},Pt=Ot,Mt=function(e){var t=+e;return t!=t||0===t?0:Pt(t)},Lt=Mt,xt=Math.max,Vt=Math.min,Ut=function(e,t){var i=Lt(e);return i<0?xt(i+t,0):Vt(i,t)},Ft=Mt,Bt=Math.min,Ht=function(e){return e>0?Bt(Ft(e),9007199254740991):0},Gt=Ht,Wt=function(e){return Gt(e.length)},jt=A,Kt=Ut,Jt=Wt,qt=function(e){return function(t,i,r){var n,s=jt(t),o=Jt(s),a=Kt(r,o);if(e&&i!=i){for(;o>a;)if((n=s[a++])!=n)return!0}else for(;o>a;a++)if((e||a in s)&&s[a]===i)return e||a||0;return!e&&-1}},zt={includes:qt(!0),indexOf:qt(!1)},Yt={},Xt=W,Qt=A,Zt=zt.indexOf,$t=Yt,ei=c([].push),ti=function(e,t){var i,r=Qt(e),n=0,s=[];for(i in r)!Xt($t,i)&&Xt(r,i)&&ei(s,i);for(;t.length>n;)Xt(r,i=t[n++])&&(~Zt(s,i)||ei(s,i));return s},ii=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ri=ti,ni=ii,si=Object.keys||function(e){return ri(e,ni)},oi=ke,ai=De,ci=Ne,li=Ce,di=A,ui=si;be.f=oi&&!ai?Object.defineProperties:function(e,t){li(e);for(var i,r=di(t),n=ui(t),s=n.length,o=0;s>o;)ci.f(e,i=n[o++],r[i]);return e};var hi,pi=Ge("document","documentElement"),mi=z,_i=b("keys"),fi=function(e){return _i[e]||(_i[e]=mi(e))},gi=Ce,Ti=be,Ei=ii,vi=Yt,yi=pi,Si=Me,Ii="prototype",Ai="script",Ri=fi("IE_PROTO"),Ci=function(){},bi=function(e){return"<"+Ai+">"+e+"</"+Ai+">"},ki=function(e){e.write(bi("")),e.close();var t=e.parentWindow.Object;return e=null,t},Di=function(){try{hi=new ActiveXObject("htmlfile")}catch(n){}var e,t,i;Di="undefined"!=typeof document?document.domain&&hi?ki(hi):(t=Si("iframe"),i="java"+Ai+":",t.style.display="none",yi.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(bi("document.F=Object")),e.close(),e.F):ki(hi);for(var r=Ei.length;r--;)delete Di[Ii][Ei[r]];return Di()};vi[Ri]=!0;var Ni=Object.create||function(e,t){var i;return null!==e?(Ci[Ii]=gi(e),i=new Ci,Ci[Ii]=null,i[Ri]=e):i=Di(),void 0===t?i:Ti.f(i,t)},wi=_e,Oi=Ni,Pi=Ne.f,Mi=wi("unscopables"),Li=Array.prototype;null==Li[Mi]&&Pi(Li,Mi,{configurable:!0,value:Oi(null)});var xi,Vi,Ui,Fi=function(e){Li[Mi][e]=!0},Bi={},Hi=Ee,Gi=C.WeakMap,Wi=Hi(Gi)&&/native code/.test(String(Gi)),ji=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},Ki=Ne,Ji=ji,qi=ke?function(e,t,i){return Ki.f(e,t,Ji(1,i))}:function(e,t,i){return e[t]=i,e},zi=Wi,Yi=C,Xi=Se,Qi=qi,Zi=W,$i=M,er=fi,tr=Yt,ir="Object already initialized",rr=Yi.TypeError,nr=Yi.WeakMap;if(zi||$i.state){var sr=$i.state||($i.state=new nr);sr.get=sr.get,sr.has=sr.has,sr.set=sr.set,xi=function(e,t){if(sr.has(e))throw rr(ir);return t.facade=e,sr.set(e,t),t},Vi=function(e){return sr.get(e)||{}},Ui=function(e){return sr.has(e)}}else{var or=er("state");tr[or]=!0,xi=function(e,t){if(Zi(e,or))throw rr(ir);return t.facade=e,Qi(e,or,t),t},Vi=function(e){return Zi(e,or)?e[or]:{}},Ui=function(e){return Zi(e,or)}}var ar={set:xi,get:Vi,has:Ui,enforce:function(e){return Ui(e)?Vi(e):xi(e,{})},getterFor:function(e){return function(t){var i;if(!Xi(t)||(i=Vi(t)).type!==e)throw rr("Incompatible receiver, "+e+" required");return i}}},cr={},lr={},dr={}.propertyIsEnumerable,ur=Object.getOwnPropertyDescriptor,hr=ur&&!dr.call({1:2},1);lr.f=hr?function(e){var t=ur(this,e);return!!t&&t.enumerable}:dr;var pr=ke,mr=Fe,_r=lr,fr=ji,gr=A,Tr=Tt,Er=W,vr=xe,yr=Object.getOwnPropertyDescriptor;cr.f=pr?yr:function(e,t){if(e=gr(e),t=Tr(t),vr)try{return yr(e,t)}catch(i){}if(Er(e,t))return fr(!mr(_r.f,e,t),e[t])};var Sr={},Ir={get exports(){return Sr},set exports(e){Sr=e}},Ar=ke,Rr=W,Cr=Function.prototype,br=Ar&&Object.getOwnPropertyDescriptor,kr=Rr(Cr,"name"),Dr={EXISTS:kr,PROPER:kr&&"something"===function(){}.name,CONFIGURABLE:kr&&(!Ar||Ar&&br(Cr,"name").configurable)},Nr=Ee,wr=M,Or=c(Function.toString);Nr(wr.inspectSource)||(wr.inspectSource=function(e){return Or(e)});var Pr=wr.inspectSource,Mr=c,Lr=i,xr=Ee,Vr=W,Ur=ke,Fr=Dr.CONFIGURABLE,Br=Pr,Hr=ar.enforce,Gr=ar.get,Wr=String,jr=Object.defineProperty,Kr=Mr("".slice),Jr=Mr("".replace),qr=Mr([].join),zr=Ur&&!Lr((function(){return 8!==jr((function(){}),"length",{value:8}).length})),Yr=String(String).split("String"),Xr=Ir.exports=function(e,t,i){"Symbol("===Kr(Wr(t),0,7)&&(t="["+Jr(Wr(t),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Vr(e,"name")||Fr&&e.name!==t)&&(Ur?jr(e,"name",{value:t,configurable:!0}):e.name=t),zr&&i&&Vr(i,"arity")&&e.length!==i.arity&&jr(e,"length",{value:i.arity});try{i&&Vr(i,"constructor")&&i.constructor?Ur&&jr(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var r=Hr(e);return Vr(r,"source")||(r.source=qr(Yr,"string"==typeof t?t:"")),e};Function.prototype.toString=Xr((function(){return xr(this)&&Gr(this).source||Br(this)}),"toString");var Qr=Ee,Zr=Ne,$r=Sr,en=w,tn=function(e,t,i,r){r||(r={});var n=r.enumerable,s=void 0!==r.name?r.name:t;if(Qr(i)&&$r(i,s,r),r.global)n?e[t]=i:en(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch(o){}n?e[t]=i:Zr.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},rn={},nn=ti,sn=ii.concat("length","prototype");rn.f=Object.getOwnPropertyNames||function(e){return nn(e,sn)};var on={};on.f=Object.getOwnPropertySymbols;var an,cn,ln,dn=Ge,un=rn,hn=on,pn=Ce,mn=c([].concat),_n=dn("Reflect","ownKeys")||function(e){var t=un.f(pn(e)),i=hn.f;return i?mn(t,i(e)):t},fn=W,gn=_n,Tn=cr,En=Ne,vn=function(e,t,i){for(var r=gn(t),n=En.f,s=Tn.f,o=0;o<r.length;o++){var a=r[o];fn(e,a)||i&&fn(i,a)||n(e,a,s(t,a))}},yn=i,Sn=Ee,In=/#|\.prototype\./,An=function(e,t){var i=Cn[Rn(e)];return i==kn||i!=bn&&(Sn(t)?yn(t):!!t)},Rn=An.normalize=function(e){return String(e).replace(In,".").toLowerCase()},Cn=An.data={},bn=An.NATIVE="N",kn=An.POLYFILL="P",Dn=An,Nn=C,wn=cr.f,On=qi,Pn=tn,Mn=w,Ln=vn,xn=Dn,Vn=function(e,t){var i,r,n,s,o,a=e.target,c=e.global,l=e.stat;if(i=c?Nn:l?Nn[a]||Mn(a,{}):(Nn[a]||{}).prototype)for(r in t){if(s=t[r],n=e.dontCallGetSet?(o=wn(i,r))&&o.value:i[r],!xn(c?r:a+(l?".":"#")+r,e.forced)&&void 0!==n){if(typeof s==typeof n)continue;Ln(s,n)}(e.sham||n&&n.sham)&&On(s,"sham",!0),Pn(i,r,s,e)}},Un=!i((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Fn=W,Bn=Ee,Hn=B,Gn=Un,Wn=fi("IE_PROTO"),jn=Object,Kn=jn.prototype,Jn=Gn?jn.getPrototypeOf:function(e){var t=Hn(e);if(Fn(t,Wn))return t[Wn];var i=t.constructor;return Bn(i)&&t instanceof i?i.prototype:t instanceof jn?Kn:null},qn=i,zn=Ee,Yn=Se,Xn=Jn,Qn=tn,Zn=_e("iterator"),$n=!1;[].keys&&("next"in(ln=[].keys())?(cn=Xn(Xn(ln)))!==Object.prototype&&(an=cn):$n=!0);var es=!Yn(an)||qn((function(){var e={};return an[Zn].call(e)!==e}));es&&(an={}),zn(an[Zn])||Qn(an,Zn,(function(){return this}));var ts={IteratorPrototype:an,BUGGY_SAFARI_ITERATORS:$n},is=Ne.f,rs=W,ns=_e("toStringTag"),ss=function(e,t,i){e&&!i&&(e=e.prototype),e&&!rs(e,ns)&&is(e,ns,{configurable:!0,value:t})},os=ts.IteratorPrototype,as=Ni,cs=ji,ls=ss,ds=Bi,us=function(){return this},hs=function(e,t,i,r){var n=t+" Iterator";return e.prototype=as(os,{next:cs(+!r,i)}),ls(e,n,!1),ds[n]=us,e},ps=c,ms=et,_s=Ee,fs=String,gs=TypeError,Ts=function(e,t,i){try{return ps(ms(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},Es=Ce,vs=function(e){if("object"==typeof e||_s(e))return e;throw gs("Can't set "+fs(e)+" as a prototype")},ys=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Ts(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return Es(i),vs(r),t?e(i,r):i.__proto__=r,i}}():void 0),Ss=Vn,Is=Fe,As=Ee,Rs=hs,Cs=Jn,bs=ys,ks=ss,Ds=qi,Ns=tn,ws=Bi,Os=Dr.PROPER,Ps=Dr.CONFIGURABLE,Ms=ts.IteratorPrototype,Ls=ts.BUGGY_SAFARI_ITERATORS,xs=_e("iterator"),Vs="keys",Us="values",Fs="entries",Bs=function(){return this},Hs=function(e,t,i,r,n,s,o){Rs(i,t,r);var a,c,l,d=function(e){if(e===n&&_)return _;if(!Ls&&e in p)return p[e];switch(e){case Vs:case Us:case Fs:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[xs]||p["@@iterator"]||n&&p[n],_=!Ls&&m||d(n),f="Array"==t&&p.entries||m;if(f&&(a=Cs(f.call(new e)))!==Object.prototype&&a.next&&(Cs(a)!==Ms&&(bs?bs(a,Ms):As(a[xs])||Ns(a,xs,Bs)),ks(a,u,!0)),Os&&n==Us&&m&&m.name!==Us&&(Ps?Ds(p,"name",Us):(h=!0,_=function(){return Is(m,this)})),n)if(c={values:d(Us),keys:s?_:d(Vs),entries:d(Fs)},o)for(l in c)(Ls||h||!(l in p))&&Ns(p,l,c[l]);else Ss({target:t,proto:!0,forced:Ls||h},c);return p[xs]!==_&&Ns(p,xs,_,{name:n}),ws[t]=_,c},Gs=function(e,t){return{value:e,done:t}},Ws=A,js=Fi,Ks=Bi,Js=ar,qs=Ne.f,zs=Hs,Ys=Gs,Xs=ke,Qs="Array Iterator",Zs=Js.set,$s=Js.getterFor(Qs),eo=zs(Array,"Array",(function(e,t){Zs(this,{type:Qs,target:Ws(e),index:0,kind:t})}),(function(){var e=$s(this),t=e.target,i=e.kind,r=e.index++;return!t||r>=t.length?(e.target=void 0,Ys(void 0,!0)):Ys("keys"==i?r:"values"==i?t[r]:[r,t[r]],!1)}),"values"),to=Ks.Arguments=Ks.Array;if(js("keys"),js("values"),js("entries"),Xs&&"values"!==to.name)try{qs(to,"name",{value:"values"})}catch(cW){}var io={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},ro=Me("span").classList,no=ro&&ro.constructor&&ro.constructor.prototype,so=no===Object.prototype?void 0:no,oo=C,ao=io,co=so,lo=eo,uo=qi,ho=_e,po=ho("iterator"),mo=ho("toStringTag"),_o=lo.values,fo=function(e,t){if(e){if(e[po]!==_o)try{uo(e,po,_o)}catch(cW){e[po]=_o}if(e[mo]||uo(e,mo,t),ao[t])for(var i in lo)if(e[i]!==lo[i])try{uo(e,i,lo[i])}catch(cW){e[i]=lo[i]}}};for(var go in ao)fo(oo[go]&&oo[go].prototype,go);fo(co,"DOMTokenList");var To="undefined"!=typeof process&&"process"==h(process),Eo=Sr,vo=Ne,yo=function(e,t,i){return i.get&&Eo(i.get,t,{getter:!0}),i.set&&Eo(i.set,t,{setter:!0}),vo.f(e,t,i)},So=Ge,Io=yo,Ao=ke,Ro=_e("species"),Co=function(e){var t=So(e);Ao&&t&&!t[Ro]&&Io(t,Ro,{configurable:!0,get:function(){return this}})},bo=We,ko=TypeError,Do=function(e,t){if(bo(t,e))return e;throw ko("Incorrect invocation")},No={};No[_e("toStringTag")]="z";var wo="[object z]"===String(No),Oo=Ee,Po=h,Mo=_e("toStringTag"),Lo=Object,xo="Arguments"==Po(function(){return arguments}()),Vo=wo?Po: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(cW){}}(t=Lo(e),Mo))?i:xo?Po(t):"Object"==(r=Po(t))&&Oo(t.callee)?"Arguments":r},Uo=c,Fo=i,Bo=Ee,Ho=Vo,Go=Pr,Wo=function(){},jo=[],Ko=Ge("Reflect","construct"),Jo=/^\s*(?:class|function)\b/,qo=Uo(Jo.exec),zo=!Jo.exec(Wo),Yo=function(e){if(!Bo(e))return!1;try{return Ko(Wo,jo,e),!0}catch(cW){return!1}},Xo=function(e){if(!Bo(e))return!1;switch(Ho(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return zo||!!qo(Jo,Go(e))}catch(cW){return!0}};Xo.sham=!0;var Qo,Zo,$o,ea,ta=!Ko||Fo((function(){var e;return Yo(Yo.call)||!Yo(Object)||!Yo((function(){e=!0}))||e}))?Xo:Yo,ia=ta,ra=Xe,na=TypeError,sa=function(e){if(ia(e))return e;throw na(ra(e)+" is not a constructor")},oa=Ce,aa=sa,ca=T,la=_e("species"),da=function(e,t){var i,r=oa(e).constructor;return void 0===r||ca(i=oa(r)[la])?t:aa(i)},ua=r,ha=Function.prototype,pa=ha.apply,ma=ha.call,_a="object"==typeof Reflect&&Reflect.apply||(ua?ma.bind(pa):function(){return ma.apply(pa,arguments)}),fa=h,ga=c,Ta=function(e){if("Function"===fa(e))return ga(e)},Ea=et,va=r,ya=Ta(Ta.bind),Sa=function(e,t){return Ea(e),void 0===t?e:va?ya(e,t):function(){return e.apply(t,arguments)}},Ia=c([].slice),Aa=TypeError,Ra=function(e,t){if(e<t)throw Aa("Not enough arguments");return e},Ca=/(?:ipad|iphone|ipod).*applewebkit/i.test(Y),ba=C,ka=_a,Da=Sa,Na=Ee,wa=W,Oa=i,Pa=pi,Ma=Ia,La=Me,xa=Ra,Va=Ca,Ua=To,Fa=ba.setImmediate,Ba=ba.clearImmediate,Ha=ba.process,Ga=ba.Dispatch,Wa=ba.Function,ja=ba.MessageChannel,Ka=ba.String,Ja=0,qa={},za="onreadystatechange";Oa((function(){Qo=ba.location}));var Ya=function(e){if(wa(qa,e)){var t=qa[e];delete qa[e],t()}},Xa=function(e){return function(){Ya(e)}},Qa=function(e){Ya(e.data)},Za=function(e){ba.postMessage(Ka(e),Qo.protocol+"//"+Qo.host)};Fa&&Ba||(Fa=function(e){xa(arguments.length,1);var t=Na(e)?e:Wa(e),i=Ma(arguments,1);return qa[++Ja]=function(){ka(t,void 0,i)},Zo(Ja),Ja},Ba=function(e){delete qa[e]},Ua?Zo=function(e){Ha.nextTick(Xa(e))}:Ga&&Ga.now?Zo=function(e){Ga.now(Xa(e))}:ja&&!Va?(ea=($o=new ja).port2,$o.port1.onmessage=Qa,Zo=Da(ea.postMessage,ea)):ba.addEventListener&&Na(ba.postMessage)&&!ba.importScripts&&Qo&&"file:"!==Qo.protocol&&!Oa(Za)?(Zo=Za,ba.addEventListener("message",Qa,!1)):Zo=za in La("script")?function(e){Pa.appendChild(La("script"))[za]=function(){Pa.removeChild(this),Ya(e)}}:function(e){setTimeout(Xa(e),0)});var $a={set:Fa,clear:Ba},ec=function(){this.head=null,this.tail=null};ec.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var tc,ic,rc,nc,sc,oc=ec,ac=/ipad|iphone|ipod/i.test(Y)&&"undefined"!=typeof Pebble,cc=/web0s(?!.*chrome)/i.test(Y),lc=C,dc=Sa,uc=cr.f,hc=$a.set,pc=oc,mc=Ca,_c=ac,fc=cc,gc=To,Tc=lc.MutationObserver||lc.WebKitMutationObserver,Ec=lc.document,vc=lc.process,yc=lc.Promise,Sc=uc(lc,"queueMicrotask"),Ic=Sc&&Sc.value;if(!Ic){var Ac=new pc,Rc=function(){var e,t;for(gc&&(e=vc.domain)&&e.exit();t=Ac.get();)try{t()}catch(cW){throw Ac.head&&tc(),cW}e&&e.enter()};mc||gc||fc||!Tc||!Ec?!_c&&yc&&yc.resolve?((nc=yc.resolve(void 0)).constructor=yc,sc=dc(nc.then,nc),tc=function(){sc(Rc)}):gc?tc=function(){vc.nextTick(Rc)}:(hc=dc(hc,lc),tc=function(){hc(Rc)}):(ic=!0,rc=Ec.createTextNode(""),new Tc(Rc).observe(rc,{characterData:!0}),tc=function(){rc.data=ic=!ic}),Ic=function(e){Ac.head||tc(),Ac.add(e)}}var Cc=Ic,bc=function(e){try{return{error:!1,value:e()}}catch(cW){return{error:!0,value:cW}}},kc=C.Promise,Dc="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,Nc=!Dc&&!To&&"object"==typeof window&&"object"==typeof document,wc=C,Oc=kc,Pc=Ee,Mc=Dn,Lc=Pr,xc=_e,Vc=Nc,Uc=Dc,Fc=ie;Oc&&Oc.prototype;var Bc=xc("species"),Hc=!1,Gc=Pc(wc.PromiseRejectionEvent),Wc=Mc("Promise",(function(){var e=Lc(Oc),t=e!==String(Oc);if(!t&&66===Fc)return!0;if(!Fc||Fc<51||!/native code/.test(e)){var i=new Oc((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((i.constructor={})[Bc]=r,!(Hc=i.then((function(){}))instanceof r))return!0}return!t&&(Vc||Uc)&&!Gc})),jc={CONSTRUCTOR:Wc,REJECTION_EVENT:Gc,SUBCLASSING:Hc},Kc={},Jc=et,qc=TypeError,zc=function(e){var t,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw qc("Bad Promise constructor");t=e,i=r})),this.resolve=Jc(t),this.reject=Jc(i)};Kc.f=function(e){return new zc(e)};var Yc,Xc,Qc,Zc=Vn,$c=To,el=C,tl=Fe,il=tn,rl=ys,nl=ss,sl=Co,ol=et,al=Ee,cl=Se,ll=Do,dl=da,ul=$a.set,hl=Cc,pl=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(cW){}},ml=bc,_l=oc,fl=ar,gl=kc,Tl=Kc,El="Promise",vl=jc.CONSTRUCTOR,yl=jc.REJECTION_EVENT,Sl=jc.SUBCLASSING,Il=fl.getterFor(El),Al=fl.set,Rl=gl&&gl.prototype,Cl=gl,bl=Rl,kl=el.TypeError,Dl=el.document,Nl=el.process,wl=Tl.f,Ol=wl,Pl=!!(Dl&&Dl.createEvent&&el.dispatchEvent),Ml="unhandledrejection",Ll=function(e){var t;return!(!cl(e)||!al(t=e.then))&&t},xl=function(e,t){var i,r,n,s=t.value,o=1==t.state,a=o?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{a?(o||(2===t.rejection&&Hl(t),t.rejection=1),!0===a?i=s:(d&&d.enter(),i=a(s),d&&(d.exit(),n=!0)),i===e.promise?l(kl("Promise-chain cycle")):(r=Ll(i))?tl(r,i,c,l):c(i)):l(s)}catch(cW){d&&!n&&d.exit(),l(cW)}},Vl=function(e,t){e.notified||(e.notified=!0,hl((function(){for(var i,r=e.reactions;i=r.get();)xl(i,e);e.notified=!1,t&&!e.rejection&&Fl(e)})))},Ul=function(e,t,i){var r,n;Pl?((r=Dl.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),el.dispatchEvent(r)):r={promise:t,reason:i},!yl&&(n=el["on"+e])?n(r):e===Ml&&pl("Unhandled promise rejection",i)},Fl=function(e){tl(ul,el,(function(){var t,i=e.facade,r=e.value;if(Bl(e)&&(t=ml((function(){$c?Nl.emit("unhandledRejection",r,i):Ul(Ml,i,r)})),e.rejection=$c||Bl(e)?2:1,t.error))throw t.value}))},Bl=function(e){return 1!==e.rejection&&!e.parent},Hl=function(e){tl(ul,el,(function(){var t=e.facade;$c?Nl.emit("rejectionHandled",t):Ul("rejectionhandled",t,e.value)}))},Gl=function(e,t,i){return function(r){e(t,r,i)}},Wl=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Vl(e,!0))},jl=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw kl("Promise can't be resolved itself");var r=Ll(t);r?hl((function(){var i={done:!1};try{tl(r,t,Gl(jl,i,e),Gl(Wl,i,e))}catch(cW){Wl(i,cW,e)}})):(e.value=t,e.state=1,Vl(e,!1))}catch(cW){Wl({done:!1},cW,e)}}};if(vl&&(bl=(Cl=function(e){ll(this,bl),ol(e),tl(Yc,this);var t=Il(this);try{e(Gl(jl,t),Gl(Wl,t))}catch(cW){Wl(t,cW)}}).prototype,(Yc=function(e){Al(this,{type:El,done:!1,notified:!1,parent:!1,reactions:new _l,rejection:!1,state:0,value:void 0})}).prototype=il(bl,"then",(function(e,t){var i=Il(this),r=wl(dl(this,Cl));return i.parent=!0,r.ok=!al(e)||e,r.fail=al(t)&&t,r.domain=$c?Nl.domain:void 0,0==i.state?i.reactions.add(r):hl((function(){xl(r,i)})),r.promise})),Xc=function(){var e=new Yc,t=Il(e);this.promise=e,this.resolve=Gl(jl,t),this.reject=Gl(Wl,t)},Tl.f=wl=function(e){return e===Cl||undefined===e?new Xc(e):Ol(e)},al(gl)&&Rl!==Object.prototype)){Qc=Rl.then,Sl||il(Rl,"then",(function(e,t){var i=this;return new Cl((function(e,t){tl(Qc,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete Rl.constructor}catch(cW){}rl&&rl(Rl,bl)}Zc({global:!0,constructor:!0,wrap:!0,forced:vl},{Promise:Cl}),nl(Cl,El,!1),sl(El);var Kl=Bi,Jl=_e("iterator"),ql=Array.prototype,zl=function(e){return void 0!==e&&(Kl.Array===e||ql[Jl]===e)},Yl=Vo,Xl=rt,Ql=T,Zl=Bi,$l=_e("iterator"),ed=function(e){if(!Ql(e))return Xl(e,$l)||Xl(e,"@@iterator")||Zl[Yl(e)]},td=Fe,id=et,rd=Ce,nd=Xe,sd=ed,od=TypeError,ad=function(e,t){var i=arguments.length<2?sd(e):t;if(id(i))return rd(td(i,e));throw od(nd(e)+" is not iterable")},cd=Fe,ld=Ce,dd=rt,ud=function(e,t,i){var r,n;ld(e);try{if(!(r=dd(e,"return"))){if("throw"===t)throw i;return i}r=cd(r,e)}catch(cW){n=!0,r=cW}if("throw"===t)throw i;if(n)throw r;return ld(r),i},hd=Sa,pd=Fe,md=Ce,_d=Xe,fd=zl,gd=Wt,Td=We,Ed=ad,vd=ed,yd=ud,Sd=TypeError,Id=function(e,t){this.stopped=e,this.result=t},Ad=Id.prototype,Rd=function(e,t,i){var r,n,s,o,a,c,l,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),_=hd(t,d),f=function(e){return r&&yd(r,"normal",e),new Id(!0,e)},g=function(e){return u?(md(e),m?_(e[0],e[1],f):_(e[0],e[1])):m?_(e,f):_(e)};if(h)r=e.iterator;else if(p)r=e;else{if(!(n=vd(e)))throw Sd(_d(e)+" is not iterable");if(fd(n)){for(s=0,o=gd(e);o>s;s++)if((a=g(e[s]))&&Td(Ad,a))return a;return new Id(!1)}r=Ed(e,n)}for(c=h?e.next:r.next;!(l=pd(c,r)).done;){try{a=g(l.value)}catch(cW){yd(r,"throw",cW)}if("object"==typeof a&&a&&Td(Ad,a))return a}return new Id(!1)},Cd=_e("iterator"),bd=!1;try{var kd=0,Dd={next:function(){return{done:!!kd++}},return:function(){bd=!0}};Dd[Cd]=function(){return this},Array.from(Dd,(function(){throw 2}))}catch(cW){}var Nd=function(e,t){if(!t&&!bd)return!1;var i=!1;try{var r={};r[Cd]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(cW){}return i},wd=kc,Od=jc.CONSTRUCTOR||!Nd((function(e){wd.all(e).then(void 0,(function(){}))})),Pd=Fe,Md=et,Ld=Kc,xd=bc,Vd=Rd;Vn({target:"Promise",stat:!0,forced:Od},{all:function(e){var t=this,i=Ld.f(t),r=i.resolve,n=i.reject,s=xd((function(){var i=Md(t.resolve),s=[],o=0,a=1;Vd(e,(function(e){var c=o++,l=!1;a++,Pd(i,t,e).then((function(e){l||(l=!0,s[c]=e,--a||r(s))}),n)})),--a||r(s)}));return s.error&&n(s.value),i.promise}});var Ud=Vn,Fd=jc.CONSTRUCTOR,Bd=kc,Hd=Ge,Gd=Ee,Wd=tn,jd=Bd&&Bd.prototype;if(Ud({target:"Promise",proto:!0,forced:Fd,real:!0},{catch:function(e){return this.then(void 0,e)}}),Gd(Bd)){var Kd=Hd("Promise").prototype.catch;jd.catch!==Kd&&Wd(jd,"catch",Kd,{unsafe:!0})}var Jd=Fe,qd=et,zd=Kc,Yd=bc,Xd=Rd;Vn({target:"Promise",stat:!0,forced:Od},{race:function(e){var t=this,i=zd.f(t),r=i.reject,n=Yd((function(){var n=qd(t.resolve);Xd(e,(function(e){Jd(n,t,e).then(i.resolve,r)}))}));return n.error&&r(n.value),i.promise}});var Qd=Fe,Zd=Kc;Vn({target:"Promise",stat:!0,forced:jc.CONSTRUCTOR},{reject:function(e){var t=Zd.f(this);return Qd(t.reject,void 0,e),t.promise}});var $d=Ce,eu=Se,tu=Kc,iu=function(e,t){if($d(e),eu(t)&&t.constructor===e)return t;var i=tu.f(e);return(0,i.resolve)(t),i.promise},ru=Vn,nu=jc.CONSTRUCTOR,su=iu;Ge("Promise"),ru({target:"Promise",stat:!0,forced:nu},{resolve:function(e){return su(this,e)}});var ou=Ee,au=Se,cu=ys,lu=function(e,t,i){var r,n;return cu&&ou(r=t.constructor)&&r!==i&&au(n=r.prototype)&&n!==i.prototype&&cu(e,n),e},du=Se,uu=h,hu=_e("match"),pu=Vo,mu=String,_u=function(e){if("Symbol"===pu(e))throw TypeError("Cannot convert a Symbol value to a string");return mu(e)},fu=Ce,gu=function(){var e=fu(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},Tu=Fe,Eu=W,vu=We,yu=gu,Su=RegExp.prototype,Iu=i,Au=C.RegExp,Ru=Iu((function(){var e=Au("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),Cu=Ru||Iu((function(){return!Au("a","y").sticky})),bu=Ru||Iu((function(){var e=Au("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),ku={BROKEN_CARET:bu,MISSED_STICKY:Cu,UNSUPPORTED_Y:Ru},Du=Ne.f,Nu=i,wu=C.RegExp,Ou=Nu((function(){var e=wu(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),Pu=i,Mu=C.RegExp,Lu=Pu((function(){var e=Mu("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),xu=ke,Vu=C,Uu=c,Fu=Dn,Bu=lu,Hu=qi,Gu=rn.f,Wu=We,ju=function(e){var t;return du(e)&&(void 0!==(t=e[hu])?!!t:"RegExp"==uu(e))},Ku=_u,Ju=function(e){var t=e.flags;return void 0!==t||"flags"in Su||Eu(e,"flags")||!vu(Su,e)?t:Tu(yu,e)},qu=ku,zu=function(e,t,i){i in e||Du(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Yu=tn,Xu=i,Qu=W,Zu=ar.enforce,$u=Co,eh=Ou,th=Lu,ih=_e("match"),rh=Vu.RegExp,nh=rh.prototype,sh=Vu.SyntaxError,oh=Uu(nh.exec),ah=Uu("".charAt),ch=Uu("".replace),lh=Uu("".indexOf),dh=Uu("".slice),uh=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,hh=/a/g,ph=/a/g,mh=new rh(hh)!==hh,_h=qu.MISSED_STICKY,fh=qu.UNSUPPORTED_Y,gh=xu&&(!mh||_h||eh||th||Xu((function(){return ph[ih]=!1,rh(hh)!=hh||rh(ph)==ph||"/a/i"!=rh(hh,"i")})));if(Fu("RegExp",gh)){for(var Th=function(e,t){var i,r,n,s,o,a,c=Wu(nh,this),l=ju(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Th)return e;if((l||Wu(nh,e))&&(e=e.source,d&&(t=Ju(h))),e=void 0===e?"":Ku(e),t=void 0===t?"":Ku(t),h=e,eh&&"dotAll"in hh&&(r=!!t&&lh(t,"s")>-1)&&(t=ch(t,/s/g,"")),i=t,_h&&"sticky"in hh&&(n=!!t&&lh(t,"y")>-1)&&fh&&(t=ch(t,/y/g,"")),th&&(s=function(e){for(var t,i=e.length,r=0,n="",s=[],o={},a=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=ah(e,r)))t+=ah(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:oh(uh,dh(e,r+1))&&(r+=2,c=!0),n+=t,l++;continue;case">"===t&&c:if(""===d||Qu(o,d))throw new sh("Invalid capture group name");o[d]=!0,s[s.length]=[d,l],c=!1,d="";continue}c?d+=t:n+=t}return[n,s]}(e),e=s[0],u=s[1]),o=Bu(rh(e,t),c?this:nh,Th),(r||n||u.length)&&(a=Zu(o),r&&(a.dotAll=!0,a.raw=Th(function(e){for(var t,i=e.length,r=0,n="",s=!1;r<=i;r++)"\\"!==(t=ah(e,r))?s||"."!==t?("["===t?s=!0:"]"===t&&(s=!1),n+=t):n+="[\\s\\S]":n+=t+ah(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Hu(o,"source",""===h?"(?:)":h)}catch(cW){}return o},Eh=Gu(rh),vh=0;Eh.length>vh;)zu(Th,rh,Eh[vh++]);nh.constructor=Th,Th.prototype=nh,Yu(Vu,"RegExp",Th,{constructor:!0})}$u("RegExp");var yh=Fe,Sh=c,Ih=_u,Ah=gu,Rh=ku,Ch=Ni,bh=ar.get,kh=Ou,Dh=Lu,Nh=b("native-string-replace",String.prototype.replace),wh=RegExp.prototype.exec,Oh=wh,Ph=Sh("".charAt),Mh=Sh("".indexOf),Lh=Sh("".replace),xh=Sh("".slice),Vh=function(){var e=/a/,t=/b*/g;return yh(wh,e,"a"),yh(wh,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Uh=Rh.BROKEN_CARET,Fh=void 0!==/()??/.exec("")[1];(Vh||Fh||Uh||kh||Dh)&&(Oh=function(e){var t,i,r,n,s,o,a,c=this,l=bh(c),d=Ih(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=yh(Oh,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Uh&&c.sticky,m=yh(Ah,c),_=c.source,f=0,g=d;if(p&&(m=Lh(m,"y",""),-1===Mh(m,"g")&&(m+="g"),g=xh(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Ph(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),Fh&&(i=new RegExp("^"+_+"$(?!\\s)",m)),Vh&&(r=c.lastIndex),n=yh(wh,p?i:c,g),p?n?(n.input=xh(n.input,f),n[0]=xh(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:Vh&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),Fh&&n&&n.length>1&&yh(Nh,n[0],i,(function(){for(s=1;s<arguments.length-2;s++)void 0===arguments[s]&&(n[s]=void 0)})),n&&h)for(n.groups=o=Ch(null),s=0;s<h.length;s++)o[(a=h[s])[0]]=n[a[1]];return n});var Bh=Oh;Vn({target:"RegExp",proto:!0,forced:/./.exec!==Bh},{exec:Bh});var Hh=h,Gh=Array.isArray||function(e){return"Array"==Hh(e)},Wh=Gh,jh=ta,Kh=Se,Jh=_e("species"),qh=Array,zh=function(e){var t;return Wh(e)&&(t=e.constructor,(jh(t)&&(t===qh||Wh(t.prototype))||Kh(t)&&null===(t=t[Jh]))&&(t=void 0)),void 0===t?qh:t},Yh=Sa,Xh=g,Qh=B,Zh=Wt,$h=function(e,t){return new(zh(e))(0===t?0:t)},ep=c([].push),tp=function(e){var t=1==e,i=2==e,r=3==e,n=4==e,s=6==e,o=7==e,a=5==e||s;return function(c,l,d,u){for(var h,p,m=Qh(c),_=Xh(m),f=Yh(l,d),g=Zh(_),T=0,E=u||$h,v=t?E(c,g):i||o?E(c,0):void 0;g>T;T++)if((a||T in _)&&(p=f(h=_[T],T,m),e))if(t)v[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:ep(v,h)}else switch(e){case 4:return!1;case 7:ep(v,h)}return s?-1:r||n?n:v}},ip={forEach:tp(0),map:tp(1),filter:tp(2),some:tp(3),every:tp(4),find:tp(5),findIndex:tp(6),filterReject:tp(7)},rp=i,np=function(e,t){var i=[][e];return!!i&&rp((function(){i.call(null,t||function(){return 1},1)}))},sp=ip.forEach,op=np("forEach")?[].forEach:function(e){return sp(this,e,arguments.length>1?arguments[1]:void 0)},ap=C,cp=io,lp=so,dp=op,up=qi,hp=function(e){if(e&&e.forEach!==dp)try{up(e,"forEach",dp)}catch(cW){e.forEach=dp}};for(var pp in cp)cp[pp]&&hp(ap[pp]&&ap[pp].prototype);hp(lp);var mp=et,_p=B,fp=g,gp=Wt,Tp=TypeError,Ep=function(e){return function(t,i,r,n){mp(i);var s=_p(t),o=fp(s),a=gp(s),c=e?a-1:0,l=e?-1:1;if(r<2)for(;;){if(c in o){n=o[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw Tp("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=l)c in o&&(n=i(n,o[c],c,s));return n}},vp={left:Ep(!1),right:Ep(!0)},yp=vp.left;Vn({target:"Array",proto:!0,forced:!To&&ie>79&&ie<83||!np("reduce")},{reduce:function(e){var t=arguments.length;return yp(this,e,t,t>1?arguments[1]:void 0)}});var Sp=Ta,Ip=tn,Ap=Bh,Rp=i,Cp=_e,bp=qi,kp=Cp("species"),Dp=RegExp.prototype,Np=c,wp=Mt,Op=_u,Pp=y,Mp=Np("".charAt),Lp=Np("".charCodeAt),xp=Np("".slice),Vp=function(e){return function(t,i){var r,n,s=Op(Pp(t)),o=wp(i),a=s.length;return o<0||o>=a?e?"":void 0:(r=Lp(s,o))<55296||r>56319||o+1===a||(n=Lp(s,o+1))<56320||n>57343?e?Mp(s,o):r:e?xp(s,o,o+2):n-56320+(r-55296<<10)+65536}},Up={codeAt:Vp(!1),charAt:Vp(!0)},Fp=Up.charAt,Bp=c,Hp=B,Gp=Math.floor,Wp=Bp("".charAt),jp=Bp("".replace),Kp=Bp("".slice),Jp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,qp=/\$([$&'`]|\d{1,2})/g,zp=Fe,Yp=Ce,Xp=Ee,Qp=h,Zp=Bh,$p=TypeError,em=_a,tm=Fe,im=c,rm=function(e,t,i,r){var n=Cp(e),s=!Rp((function(){var t={};return t[n]=function(){return 7},7!=""[e](t)})),o=s&&!Rp((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[kp]=function(){return i},i.flags="",i[n]=/./[n]),i.exec=function(){return t=!0,null},i[n](""),!t}));if(!s||!o||i){var a=Sp(/./[n]),c=t(n,""[e],(function(e,t,i,r,n){var o=Sp(e),c=t.exec;return c===Ap||c===Dp.exec?s&&!n?{done:!0,value:a(t,i,r)}:{done:!0,value:o(i,t,r)}:{done:!1}}));Ip(String.prototype,e,c[0]),Ip(Dp,n,c[1])}r&&bp(Dp[n],"sham",!0)},nm=i,sm=Ce,om=Ee,am=T,cm=Mt,lm=Ht,dm=_u,um=y,hm=function(e,t,i){return t+(i?Fp(e,t).length:1)},pm=rt,mm=function(e,t,i,r,n,s){var o=i+e.length,a=r.length,c=qp;return void 0!==n&&(n=Hp(n),c=Jp),jp(s,c,(function(s,c){var l;switch(Wp(c,0)){case"$":return"$";case"&":return e;case"`":return Kp(t,0,i);case"'":return Kp(t,o);case"<":l=n[Kp(c,1,-1)];break;default:var d=+c;if(0===d)return s;if(d>a){var u=Gp(d/10);return 0===u?s:u<=a?void 0===r[u-1]?Wp(c,1):r[u-1]+Wp(c,1):s}l=r[d-1]}return void 0===l?"":l}))},_m=function(e,t){var i=e.exec;if(Xp(i)){var r=zp(i,e,t);return null!==r&&Yp(r),r}if("RegExp"===Qp(e))return zp(Zp,e,t);throw $p("RegExp#exec called on incompatible receiver")},fm=_e("replace"),gm=Math.max,Tm=Math.min,Em=im([].concat),vm=im([].push),ym=im("".indexOf),Sm=im("".slice),Im=function(e){return void 0===e?e:String(e)},Am="$0"==="a".replace(/./,"$0"),Rm=!!/./[fm]&&""===/./[fm]("a","$0"),Cm=!nm((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));rm("replace",(function(e,t,i){var r=Rm?"$":"$0";return[function(e,i){var r=um(this),n=am(e)?void 0:pm(e,fm);return n?tm(n,e,r,i):tm(t,dm(r),e,i)},function(e,n){var s=sm(this),o=dm(e);if("string"==typeof n&&-1===ym(n,r)&&-1===ym(n,"$<")){var a=i(t,s,o,n);if(a.done)return a.value}var c=om(n);c||(n=dm(n));var l=s.global;if(l){var d=s.unicode;s.lastIndex=0}for(var u=[];;){var h=_m(s,o);if(null===h)break;if(vm(u,h),!l)break;""===dm(h[0])&&(s.lastIndex=hm(o,lm(s.lastIndex),d))}for(var p="",m=0,_=0;_<u.length;_++){for(var f=dm((h=u[_])[0]),g=gm(Tm(cm(h.index),o.length),0),T=[],E=1;E<h.length;E++)vm(T,Im(h[E]));var v=h.groups;if(c){var y=Em([f],T,g,o);void 0!==v&&vm(y,v);var S=dm(em(n,void 0,y))}else S=mm(f,o,g,T,v,n);g>=m&&(p+=Sm(o,m,g)+S,m=g+f.length)}return p+Sm(o,m)}]}),!Cm||!Am||Rm);var bm=zt.includes,km=Fi;Vn({target:"Array",proto:!0,forced:i((function(){return!Array(1).includes()}))},{includes:function(e){return bm(this,e,arguments.length>1?arguments[1]:void 0)}}),km("includes");var Dm=Mt,Nm=_u,wm=y,Om=RangeError,Pm=c,Mm=Ht,Lm=_u,xm=function(e){var t=Nm(wm(this)),i="",r=Dm(e);if(r<0||Infinity==r)throw Om("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},Vm=y,Um=Pm(xm),Fm=Pm("".slice),Bm=Math.ceil,Hm=function(e){return function(t,i,r){var n,s,o=Lm(Vm(t)),a=Mm(i),c=o.length,l=void 0===r?" ":Lm(r);return a<=c||""==l?o:((s=Um(l,Bm((n=a-c)/l.length))).length>n&&(s=Fm(s,0,n)),e?o+s:s+o)}},Gm={start:Hm(!1),end:Hm(!0)},Wm=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Y),jm=Gm.start;Vn({target:"String",proto:!0,forced:Wm},{padStart:function(e){return jm(this,e,arguments.length>1?arguments[1]:void 0)}});var Km=i,Jm=ke,qm=_e("iterator"),zm=!Km((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i="";return e.pathname="c%20d",t.forEach((function(e,r){t.delete("b"),i+=r+e})),!t.size&&!Jm||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[qm]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==i||"x"!==new URL("http://x",void 0).host})),Ym=tn,Xm=function(e,t,i){for(var r in t)Ym(e,r,t[r],i);return e},Qm=Tt,Zm=Ne,$m=ji,e_=function(e,t,i){var r=Qm(t);r in e?Zm.f(e,r,$m(0,i)):e[r]=i},t_=Ut,i_=Wt,r_=e_,n_=Array,s_=Math.max,o_=function(e,t,i){for(var r=i_(e),n=t_(t,r),s=t_(void 0===i?r:i,r),o=n_(s_(s-n,0)),a=0;n<s;n++,a++)r_(o,a,e[n]);return o.length=a,o},a_=o_,c_=Math.floor,l_=function(e,t){var i=e.length,r=c_(i/2);return i<8?d_(e,t):u_(e,l_(a_(e,0,r),t),l_(a_(e,r),t),t)},d_=function(e,t){for(var i,r,n=e.length,s=1;s<n;){for(r=s,i=e[s];r&&t(e[r-1],i)>0;)e[r]=e[--r];r!==s++&&(e[r]=i)}return e},u_=function(e,t,i,r){for(var n=t.length,s=i.length,o=0,a=0;o<n||a<s;)e[o+a]=o<n&&a<s?r(t[o],i[a])<=0?t[o++]:i[a++]:o<n?t[o++]:i[a++];return e},h_=l_,p_=Vn,m_=C,__=Fe,f_=c,g_=ke,T_=zm,E_=tn,v_=yo,y_=Xm,S_=ss,I_=hs,A_=ar,R_=Do,C_=Ee,b_=W,k_=Sa,D_=Vo,N_=Ce,w_=Se,O_=_u,P_=Ni,M_=ji,L_=ad,x_=ed,V_=Ra,U_=h_,F_=_e("iterator"),B_="URLSearchParams",H_=B_+"Iterator",G_=A_.set,W_=A_.getterFor(B_),j_=A_.getterFor(H_),K_=Object.getOwnPropertyDescriptor,J_=function(e){if(!g_)return m_[e];var t=K_(m_,e);return t&&t.value},q_=J_("fetch"),z_=J_("Request"),Y_=J_("Headers"),X_=z_&&z_.prototype,Q_=Y_&&Y_.prototype,Z_=m_.RegExp,$_=m_.TypeError,ef=m_.decodeURIComponent,tf=m_.encodeURIComponent,rf=f_("".charAt),nf=f_([].join),sf=f_([].push),of=f_("".replace),af=f_([].shift),cf=f_([].splice),lf=f_("".split),df=f_("".slice),uf=/\+/g,hf=Array(4),pf=function(e){return hf[e-1]||(hf[e-1]=Z_("((?:%[\\da-f]{2}){"+e+"})","gi"))},mf=function(e){try{return ef(e)}catch(cW){return e}},_f=function(e){var t=of(e,uf," "),i=4;try{return ef(t)}catch(cW){for(;i;)t=of(t,pf(i--),mf);return t}},ff=/[!'()~]|%20/g,gf={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},Tf=function(e){return gf[e]},Ef=function(e){return of(tf(e),ff,Tf)},vf=I_((function(e,t){G_(this,{type:H_,iterator:L_(W_(e).entries),kind:t})}),"Iterator",(function(){var e=j_(this),t=e.kind,i=e.iterator.next(),r=i.value;return i.done||(i.value="keys"===t?r.key:"values"===t?r.value:[r.key,r.value]),i}),!0),yf=function(e){this.entries=[],this.url=null,void 0!==e&&(w_(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===rf(e,0)?df(e,1):e:O_(e)))};yf.prototype={type:B_,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,s,o,a,c=x_(e);if(c)for(i=(t=L_(e,c)).next;!(r=__(i,t)).done;){if(s=(n=L_(N_(r.value))).next,(o=__(s,n)).done||(a=__(s,n)).done||!__(s,n).done)throw $_("Expected sequence with length 2");sf(this.entries,{key:O_(o.value),value:O_(a.value)})}else for(var l in e)b_(e,l)&&sf(this.entries,{key:l,value:O_(e[l])})},parseQuery:function(e){if(e)for(var t,i,r=lf(e,"&"),n=0;n<r.length;)(t=r[n++]).length&&(i=lf(t,"="),sf(this.entries,{key:_f(af(i)),value:_f(nf(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],sf(i,Ef(e.key)+"="+Ef(e.value));return nf(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var Sf=function(){R_(this,If);var e=G_(this,new yf(arguments.length>0?arguments[0]:void 0));g_||(this.length=e.entries.length)},If=Sf.prototype;if(y_(If,{append:function(e,t){V_(arguments.length,2);var i=W_(this);sf(i.entries,{key:O_(e),value:O_(t)}),g_||this.length++,i.updateURL()},delete:function(e){V_(arguments.length,1);for(var t=W_(this),i=t.entries,r=O_(e),n=0;n<i.length;)i[n].key===r?cf(i,n,1):n++;g_||(this.length=i.length),t.updateURL()},get:function(e){V_(arguments.length,1);for(var t=W_(this).entries,i=O_(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){V_(arguments.length,1);for(var t=W_(this).entries,i=O_(e),r=[],n=0;n<t.length;n++)t[n].key===i&&sf(r,t[n].value);return r},has:function(e){V_(arguments.length,1);for(var t=W_(this).entries,i=O_(e),r=0;r<t.length;)if(t[r++].key===i)return!0;return!1},set:function(e,t){V_(arguments.length,1);for(var i,r=W_(this),n=r.entries,s=!1,o=O_(e),a=O_(t),c=0;c<n.length;c++)(i=n[c]).key===o&&(s?cf(n,c--,1):(s=!0,i.value=a));s||sf(n,{key:o,value:a}),g_||(this.length=n.length),r.updateURL()},sort:function(){var e=W_(this);U_(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=W_(this).entries,r=k_(e,arguments.length>1?arguments[1]:void 0),n=0;n<i.length;)r((t=i[n++]).value,t.key,this)},keys:function(){return new vf(this,"keys")},values:function(){return new vf(this,"values")},entries:function(){return new vf(this,"entries")}},{enumerable:!0}),E_(If,F_,If.entries,{name:"entries"}),E_(If,"toString",(function(){return W_(this).serialize()}),{enumerable:!0}),g_&&v_(If,"size",{get:function(){return W_(this).entries.length},configurable:!0,enumerable:!0}),S_(Sf,B_),p_({global:!0,constructor:!0,forced:!T_},{URLSearchParams:Sf}),!T_&&C_(Y_)){var Af=f_(Q_.has),Rf=f_(Q_.set),Cf=function(e){if(w_(e)){var t,i=e.body;if(D_(i)===B_)return t=e.headers?new Y_(e.headers):new Y_,Af(t,"content-type")||Rf(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),P_(e,{body:M_(0,O_(i)),headers:M_(0,t)})}return e};if(C_(q_)&&p_({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return q_(e,arguments.length>1?Cf(arguments[1]):{})}}),C_(z_)){var bf=function(e){return R_(this,X_),new z_(e,arguments.length>1?Cf(arguments[1]):{})};X_.constructor=bf,bf.prototype=X_,p_({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:bf})}}var kf={URLSearchParams:Sf,getState:W_},Df=Vn,Nf=kc,wf=i,Of=Ge,Pf=Ee,Mf=da,Lf=iu,xf=tn,Vf=Nf&&Nf.prototype;if(Df({target:"Promise",proto:!0,real:!0,forced:!!Nf&&wf((function(){Vf.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Mf(this,Of("Promise")),i=Pf(e);return this.then(i?function(i){return Lf(t,e()).then((function(){return i}))}:e,i?function(i){return Lf(t,e()).then((function(){throw i}))}:e)}}),Pf(Nf)){var Uf=Of("Promise").prototype.finally;Vf.finally!==Uf&&xf(Vf,"finally",Uf,{unsafe:!0})}var Ff="\t\n\v\f\r \u2028\u2029\ufeff",Bf=y,Hf=_u,Gf=Ff,Wf=c("".replace),jf=RegExp("^["+Gf+"]+"),Kf=RegExp("(^|[^"+Gf+"])["+Gf+"]+$"),Jf=function(e){return function(t){var i=Hf(Bf(t));return 1&e&&(i=Wf(i,jf,"")),2&e&&(i=Wf(i,Kf,"$1")),i}},qf={start:Jf(1),end:Jf(2),trim:Jf(3)},zf=Dr.PROPER,Yf=i,Xf=Ff,Qf=qf.trim;Vn({target:"String",proto:!0,forced:function(e){return Yf((function(){return!!Xf[e]()||"
"!=="
"[e]()||zf&&Xf[e].name!==e}))}("trim")},{trim:function(){return Qf(this)}});var Zf="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,$f=Mt,eg=Ht,tg=RangeError,ig=function(e){if(void 0===e)return 0;var t=$f(e),i=eg(t);if(t!==i)throw tg("Wrong length or index");return i},rg=Array,ng=Math.abs,sg=Math.pow,og=Math.floor,ag=Math.log,cg=Math.LN2,lg={pack:function(e,t,i){var r,n,s,o=rg(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?sg(2,-24)-sg(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=ng(e))!=e||Infinity===e?(n=e!=e?1:0,r=c):(r=og(ag(e)/cg),e*(s=sg(2,-r))<1&&(r--,s*=2),(e+=r+l>=1?d/s:d*sg(2,1-l))*s>=2&&(r++,s/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*s-1)*sg(2,t),r+=l):(n=e*sg(2,l-1)*sg(2,t),r=0));t>=8;)o[h++]=255&n,n/=256,t-=8;for(r=r<<t|n,a+=t;a>0;)o[h++]=255&r,r/=256,a-=8;return o[--h]|=128*u,o},unpack:function(e,t){var i,r=e.length,n=8*r-t-1,s=(1<<n)-1,o=s>>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-o;else{if(d===s)return i?NaN:l?-Infinity:Infinity;i+=sg(2,t),d-=o}return(l?-1:1)*i*sg(2,d-t)}},dg=B,ug=Ut,hg=Wt,pg=function(e){for(var t=dg(this),i=hg(t),r=arguments.length,n=ug(r>1?arguments[1]:void 0,i),s=r>2?arguments[2]:void 0,o=void 0===s?i:ug(s,i);o>n;)t[n++]=e;return t},mg=C,_g=c,fg=ke,gg=Zf,Tg=Dr,Eg=qi,vg=yo,yg=Xm,Sg=i,Ig=Do,Ag=Mt,Rg=Ht,Cg=ig,bg=lg,kg=Jn,Dg=ys,Ng=rn.f,wg=pg,Og=o_,Pg=ss,Mg=ar,Lg=Tg.PROPER,xg=Tg.CONFIGURABLE,Vg="ArrayBuffer",Ug="DataView",Fg="prototype",Bg="Wrong index",Hg=Mg.getterFor(Vg),Gg=Mg.getterFor(Ug),Wg=Mg.set,jg=mg[Vg],Kg=jg,Jg=Kg&&Kg[Fg],qg=mg[Ug],zg=qg&&qg[Fg],Yg=Object.prototype,Xg=mg.Array,Qg=mg.RangeError,Zg=_g(wg),$g=_g([].reverse),eT=bg.pack,tT=bg.unpack,iT=function(e){return[255&e]},rT=function(e){return[255&e,e>>8&255]},nT=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},sT=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},oT=function(e){return eT(e,23,4)},aT=function(e){return eT(e,52,8)},cT=function(e,t,i){vg(e[Fg],t,{configurable:!0,get:function(){return i(this)[t]}})},lT=function(e,t,i,r){var n=Cg(i),s=Gg(e);if(n+t>s.byteLength)throw Qg(Bg);var o=s.bytes,a=n+s.byteOffset,c=Og(o,a,a+t);return r?c:$g(c)},dT=function(e,t,i,r,n,s){var o=Cg(i),a=Gg(e);if(o+t>a.byteLength)throw Qg(Bg);for(var c=a.bytes,l=o+a.byteOffset,d=r(+n),u=0;u<t;u++)c[l+u]=d[s?u:t-u-1]};if(gg){var uT=Lg&&jg.name!==Vg;if(Sg((function(){jg(1)}))&&Sg((function(){new jg(-1)}))&&!Sg((function(){return new jg,new jg(1.5),new jg(NaN),1!=jg.length||uT&&!xg})))uT&&xg&&Eg(jg,"name",Vg);else{(Kg=function(e){return Ig(this,Jg),new jg(Cg(e))})[Fg]=Jg;for(var hT,pT=Ng(jg),mT=0;pT.length>mT;)(hT=pT[mT++])in Kg||Eg(Kg,hT,jg[hT]);Jg.constructor=Kg}Dg&&kg(zg)!==Yg&&Dg(zg,Yg);var _T=new qg(new Kg(2)),fT=_g(zg.setInt8);_T.setInt8(0,2147483648),_T.setInt8(1,2147483649),!_T.getInt8(0)&&_T.getInt8(1)||yg(zg,{setInt8:function(e,t){fT(this,e,t<<24>>24)},setUint8:function(e,t){fT(this,e,t<<24>>24)}},{unsafe:!0})}else Jg=(Kg=function(e){Ig(this,Jg);var t=Cg(e);Wg(this,{type:Vg,bytes:Zg(Xg(t),0),byteLength:t}),fg||(this.byteLength=t,this.detached=!1)})[Fg],zg=(qg=function(e,t,i){Ig(this,zg),Ig(e,Jg);var r=Hg(e),n=r.byteLength,s=Ag(t);if(s<0||s>n)throw Qg("Wrong offset");if(s+(i=void 0===i?n-s:Rg(i))>n)throw Qg("Wrong length");Wg(this,{type:Ug,buffer:e,byteLength:i,byteOffset:s,bytes:r.bytes}),fg||(this.buffer=e,this.byteLength=i,this.byteOffset=s)})[Fg],fg&&(cT(Kg,"byteLength",Hg),cT(qg,"buffer",Gg),cT(qg,"byteLength",Gg),cT(qg,"byteOffset",Gg)),yg(zg,{getInt8:function(e){return lT(this,1,e)[0]<<24>>24},getUint8:function(e){return lT(this,1,e)[0]},getInt16:function(e){var t=lT(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=lT(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return sT(lT(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return sT(lT(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return tT(lT(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return tT(lT(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){dT(this,1,e,iT,t)},setUint8:function(e,t){dT(this,1,e,iT,t)},setInt16:function(e,t){dT(this,2,e,rT,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){dT(this,2,e,rT,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){dT(this,4,e,nT,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){dT(this,4,e,nT,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){dT(this,4,e,oT,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){dT(this,8,e,aT,t,arguments.length>2?arguments[2]:void 0)}});Pg(Kg,Vg),Pg(qg,Ug);var gT={ArrayBuffer:Kg,DataView:qg},TT=Vn,ET=Ta,vT=i,yT=Ce,ST=Ut,IT=Ht,AT=da,RT=gT.ArrayBuffer,CT=gT.DataView,bT=CT.prototype,kT=ET(RT.prototype.slice),DT=ET(bT.getUint8),NT=ET(bT.setUint8);TT({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:vT((function(){return!new RT(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(kT&&void 0===t)return kT(yT(this),e);for(var i=yT(this).byteLength,r=ST(e,i),n=ST(void 0===t?i:t,i),s=new(AT(this,RT))(IT(n-r)),o=new CT(this),a=new CT(s),c=0;r<n;)NT(a,c++,DT(o,r++));return s}});var wT,OT,PT,MT={},LT={get exports(){return MT},set exports(e){MT=e}},xT=Zf,VT=ke,UT=C,FT=Ee,BT=Se,HT=W,GT=Vo,WT=Xe,jT=qi,KT=tn,JT=yo,qT=We,zT=Jn,YT=ys,XT=_e,QT=z,ZT=ar.enforce,$T=ar.get,eE=UT.Int8Array,tE=eE&&eE.prototype,iE=UT.Uint8ClampedArray,rE=iE&&iE.prototype,nE=eE&&zT(eE),sE=tE&&zT(tE),oE=Object.prototype,aE=UT.TypeError,cE=XT("toStringTag"),lE=QT("TYPED_ARRAY_TAG"),dE="TypedArrayConstructor",uE=xT&&!!YT&&"Opera"!==GT(UT.opera),hE=!1,pE={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},mE={BigInt64Array:8,BigUint64Array:8},_E=function(e){var t=zT(e);if(BT(t)){var i=$T(t);return i&&HT(i,dE)?i[dE]:_E(t)}},fE=function(e){if(!BT(e))return!1;var t=GT(e);return HT(pE,t)||HT(mE,t)};for(wT in pE)(PT=(OT=UT[wT])&&OT.prototype)?ZT(PT)[dE]=OT:uE=!1;for(wT in mE)(PT=(OT=UT[wT])&&OT.prototype)&&(ZT(PT)[dE]=OT);if((!uE||!FT(nE)||nE===Function.prototype)&&(nE=function(){throw aE("Incorrect invocation")},uE))for(wT in pE)UT[wT]&&YT(UT[wT],nE);if((!uE||!sE||sE===oE)&&(sE=nE.prototype,uE))for(wT in pE)UT[wT]&&YT(UT[wT].prototype,sE);if(uE&&zT(rE)!==sE&&YT(rE,sE),VT&&!HT(sE,cE))for(wT in hE=!0,JT(sE,cE,{configurable:!0,get:function(){return BT(this)?this[lE]:void 0}}),pE)UT[wT]&&jT(UT[wT],lE,wT);var gE={NATIVE_ARRAY_BUFFER_VIEWS:uE,TYPED_ARRAY_TAG:hE&&lE,aTypedArray:function(e){if(fE(e))return e;throw aE("Target is not a typed array")},aTypedArrayConstructor:function(e){if(FT(e)&&(!YT||qT(nE,e)))return e;throw aE(WT(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(VT){if(i)for(var n in pE){var s=UT[n];if(s&&HT(s.prototype,e))try{delete s.prototype[e]}catch(cW){try{s.prototype[e]=t}catch(o){}}}sE[e]&&!i||KT(sE,e,i?t:uE&&tE[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(VT){if(YT){if(i)for(r in pE)if((n=UT[r])&&HT(n,e))try{delete n[e]}catch(cW){}if(nE[e]&&!i)return;try{return KT(nE,e,i?t:uE&&nE[e]||t)}catch(cW){}}for(r in pE)!(n=UT[r])||n[e]&&!i||KT(n,e,t)}},getTypedArrayConstructor:_E,isView:function(e){if(!BT(e))return!1;var t=GT(e);return"DataView"===t||HT(pE,t)||HT(mE,t)},isTypedArray:fE,TypedArray:nE,TypedArrayPrototype:sE},TE=C,EE=i,vE=Nd,yE=gE.NATIVE_ARRAY_BUFFER_VIEWS,SE=TE.ArrayBuffer,IE=TE.Int8Array,AE=!yE||!EE((function(){IE(1)}))||!EE((function(){new IE(-1)}))||!vE((function(e){new IE,new IE(null),new IE(1.5),new IE(e)}),!0)||EE((function(){return 1!==new IE(new SE(2),1,void 0).length})),RE=Se,CE=Math.floor,bE=Number.isInteger||function(e){return!RE(e)&&isFinite(e)&&CE(e)===e},kE=Mt,DE=RangeError,NE=function(e){var t=kE(e);if(t<0)throw DE("The argument can't be less than 0");return t},wE=RangeError,OE=function(e,t){var i=NE(e);if(i%t)throw wE("Wrong offset");return i},PE=Vo,ME=_t,LE=TypeError,xE=function(e){var t=ME(e,"number");if("number"==typeof t)throw LE("Can't convert number to bigint");return BigInt(t)},VE=Sa,UE=Fe,FE=sa,BE=B,HE=Wt,GE=ad,WE=ed,jE=zl,KE=function(e){var t=PE(e);return"BigInt64Array"==t||"BigUint64Array"==t},JE=gE.aTypedArrayConstructor,qE=xE,zE=function(e){var t,i,r,n,s,o,a,c,l=FE(this),d=BE(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=WE(d);if(m&&!jE(m))for(c=(a=GE(d,m)).next,d=[];!(o=UE(c,a)).done;)d.push(o.value);for(p&&u>2&&(h=VE(h,arguments[2])),i=HE(d),r=new(JE(l))(i),n=KE(r),t=0;i>t;t++)s=p?h(d[t],t):d[t],r[t]=n?qE(s):+s;return r},YE=Vn,XE=C,QE=Fe,ZE=ke,$E=AE,ev=gE,tv=gT,iv=Do,rv=ji,nv=qi,sv=bE,ov=Ht,av=ig,cv=OE,lv=Tt,dv=W,uv=Vo,hv=Se,pv=ze,mv=Ni,_v=We,fv=ys,gv=rn.f,Tv=zE,Ev=ip.forEach,vv=Co,yv=yo,Sv=Ne,Iv=cr,Av=lu,Rv=ar.get,Cv=ar.set,bv=ar.enforce,kv=Sv.f,Dv=Iv.f,Nv=Math.round,wv=XE.RangeError,Ov=tv.ArrayBuffer,Pv=Ov.prototype,Mv=tv.DataView,Lv=ev.NATIVE_ARRAY_BUFFER_VIEWS,xv=ev.TYPED_ARRAY_TAG,Vv=ev.TypedArray,Uv=ev.TypedArrayPrototype,Fv=ev.aTypedArrayConstructor,Bv=ev.isTypedArray,Hv="BYTES_PER_ELEMENT",Gv="Wrong length",Wv=function(e,t){Fv(e);for(var i=0,r=t.length,n=new e(r);r>i;)n[i]=t[i++];return n},jv=function(e,t){yv(e,t,{configurable:!0,get:function(){return Rv(this)[t]}})},Kv=function(e){var t;return _v(Pv,e)||"ArrayBuffer"==(t=uv(e))||"SharedArrayBuffer"==t},Jv=function(e,t){return Bv(e)&&!pv(t)&&t in e&&sv(+t)&&t>=0},qv=function(e,t){return t=lv(t),Jv(e,t)?rv(2,e[t]):Dv(e,t)},zv=function(e,t,i){return t=lv(t),!(Jv(e,t)&&hv(i)&&dv(i,"value"))||dv(i,"get")||dv(i,"set")||i.configurable||dv(i,"writable")&&!i.writable||dv(i,"enumerable")&&!i.enumerable?kv(e,t,i):(e[t]=i.value,e)};ZE?(Lv||(Iv.f=qv,Sv.f=zv,jv(Uv,"buffer"),jv(Uv,"byteOffset"),jv(Uv,"byteLength"),jv(Uv,"length")),YE({target:"Object",stat:!0,forced:!Lv},{getOwnPropertyDescriptor:qv,defineProperty:zv}),LT.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",s="get"+e,o="set"+e,a=XE[n],c=a,l=c&&c.prototype,d={},u=function(e,t){kv(e,t,{get:function(){return function(e,t){var i=Rv(e);return i.view[s](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var s=Rv(e);i&&(n=(n=Nv(n))<0?0:n>255?255:255&n),s.view[o](t*r+s.byteOffset,n,!0)}(this,t,e)},enumerable:!0})};Lv?$E&&(c=t((function(e,t,i,n){return iv(e,l),Av(hv(t)?Kv(t)?void 0!==n?new a(t,cv(i,r),n):void 0!==i?new a(t,cv(i,r)):new a(t):Bv(t)?Wv(c,t):QE(Tv,c,t):new a(av(t)),e,c)})),fv&&fv(c,Vv),Ev(gv(a),(function(e){e in c||nv(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,n){iv(e,l);var s,o,a,d=0,h=0;if(hv(t)){if(!Kv(t))return Bv(t)?Wv(c,t):QE(Tv,c,t);s=t,h=cv(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw wv(Gv);if((o=p-h)<0)throw wv(Gv)}else if((o=ov(n)*r)+h>p)throw wv(Gv);a=o/r}else a=av(t),s=new Ov(o=a*r);for(Cv(e,{buffer:s,byteOffset:h,byteLength:o,length:a,view:new Mv(s)});d<a;)u(e,d++)})),fv&&fv(c,Vv),l=c.prototype=mv(Uv)),l.constructor!==c&&nv(l,"constructor",c),bv(l).TypedArrayConstructor=c,xv&&nv(l,xv,n);var h=c!=a;d[n]=c,YE({global:!0,constructor:!0,forced:h,sham:!Lv},d),Hv in c||nv(c,Hv,r),Hv in l||nv(l,Hv,r),vv(n)}):LT.exports=function(){},MT("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var Yv=pg,Xv=xE,Qv=Vo,Zv=Fe,$v=i,ey=gE.aTypedArray,ty=gE.exportTypedArrayMethod,iy=c("".slice);ty("fill",(function(e){var t=arguments.length;ey(this);var i="Big"===iy(Qv(this),0,3)?Xv(e):+e;return Zv(Yv,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),$v((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var ry=C,ny=Fe,sy=gE,oy=Wt,ay=OE,cy=B,ly=i,dy=ry.RangeError,uy=ry.Int8Array,hy=uy&&uy.prototype,py=hy&&hy.set,my=sy.aTypedArray,_y=sy.exportTypedArrayMethod,fy=!ly((function(){var e=new Uint8ClampedArray(2);return ny(py,e,{length:1,0:3},1),3!==e[1]})),gy=fy&&sy.NATIVE_ARRAY_BUFFER_VIEWS&&ly((function(){var e=new uy(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));_y("set",(function(e){my(this);var t=ay(arguments.length>1?arguments[1]:void 0,1),i=cy(e);if(fy)return ny(py,this,i,t);var r=this.length,n=oy(i),s=0;if(n+t>r)throw dy("Wrong length");for(;s<n;)this[t+s]=i[s++]}),!fy||gy);var Ty=Y.match(/firefox\/(\d+)/i),Ey=!!Ty&&+Ty[1],vy=/MSIE|Trident/.test(Y),yy=Y.match(/AppleWebKit\/(\d+)\./),Sy=!!yy&&+yy[1],Iy=Ta,Ay=i,Ry=et,Cy=h_,by=Ey,ky=vy,Dy=ie,Ny=Sy,wy=gE.aTypedArray,Oy=gE.exportTypedArrayMethod,Py=C.Uint16Array,My=Py&&Iy(Py.prototype.sort),Ly=!(!My||Ay((function(){My(new Py(2),null)}))&&Ay((function(){My(new Py(2),{})}))),xy=!!My&&!Ay((function(){if(Dy)return Dy<74;if(by)return by<67;if(ky)return!0;if(Ny)return Ny<602;var e,t,i=new Py(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(My(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));Oy("sort",(function(e){return void 0!==e&&Ry(e),xy?My(this,e):Cy(wy(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))}),!xy||Ly);var Vy=Vn,Uy=ke,Fy=c,By=W,Hy=Ee,Gy=We,Wy=_u,jy=yo,Ky=vn,Jy=C.Symbol,qy=Jy&&Jy.prototype;if(Uy&&Hy(Jy)&&(!("description"in qy)||void 0!==Jy().description)){var zy={},Yy=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:Wy(arguments[0]),t=Gy(qy,this)?new Jy(e):void 0===e?Jy():Jy(e);return""===e&&(zy[t]=!0),t};Ky(Yy,Jy),Yy.prototype=qy,qy.constructor=Yy;var Xy="Symbol(test)"==String(Jy("test")),Qy=Fy(qy.valueOf),Zy=Fy(qy.toString),$y=/^Symbol\((.*)\)[^)]+$/,eS=Fy("".replace),tS=Fy("".slice);jy(qy,"description",{configurable:!0,get:function(){var e=Qy(this);if(By(zy,e))return"";var t=Zy(e),i=Xy?tS(t,7,-1):eS(t,$y,"$1");return""===i?void 0:i}}),Vy({global:!0,constructor:!0,forced:!0},{Symbol:Yy})}var iS=Up.charAt,rS=_u,nS=ar,sS=Hs,oS=Gs,aS="String Iterator",cS=nS.set,lS=nS.getterFor(aS);sS(String,"String",(function(e){cS(this,{type:aS,string:rS(e),index:0})}),(function(){var e,t=lS(this),i=t.string,r=t.index;return r>=i.length?oS(void 0,!0):(e=iS(i,r),t.index+=e.length,oS(e,!1))}));var dS,uS=ke,hS=c,pS=Fe,mS=i,_S=si,fS=on,gS=lr,TS=B,ES=g,vS=Object.assign,yS=Object.defineProperty,SS=hS([].concat),IS=!vS||mS((function(){if(uS&&1!==vS({b:1},vS(yS({},"a",{enumerable:!0,get:function(){yS(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol(),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach((function(e){t[e]=e})),7!=vS({},e)[i]||_S(vS({},t)).join("")!=r}))?function(e,t){for(var i=TS(e),r=arguments.length,n=1,s=fS.f,o=gS.f;r>n;)for(var a,c=ES(arguments[n++]),l=s?SS(_S(c),s(c)):_S(c),d=l.length,u=0;d>u;)a=l[u++],uS&&!pS(o,c,a)||(i[a]=c[a]);return i}:vS,AS=Ce,RS=ud,CS=Sa,bS=Fe,kS=B,DS=function(e,t,i,r){try{return r?t(AS(i)[0],i[1]):t(i)}catch(cW){RS(e,"throw",cW)}},NS=zl,wS=ta,OS=Wt,PS=e_,MS=ad,LS=ed,xS=Array,VS=c,US=2147483647,FS=/[^\0-\u007E]/,BS=/[.\u3002\uFF0E\uFF61]/g,HS="Overflow: input needs wider integers to process",GS=RangeError,WS=VS(BS.exec),jS=Math.floor,KS=String.fromCharCode,JS=VS("".charCodeAt),qS=VS([].join),zS=VS([].push),YS=VS("".replace),XS=VS("".split),QS=VS("".toLowerCase),ZS=function(e){return e+22+75*(e<26)},$S=function(e,t,i){var r=0;for(e=i?jS(e/700):e>>1,e+=jS(e/t);e>455;)e=jS(e/35),r+=36;return jS(r+36*e/(e+38))},eI=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=JS(e,i++);if(n>=55296&&n<=56319&&i<r){var s=JS(e,i++);56320==(64512&s)?zS(t,((1023&n)<<10)+(1023&s)+65536):(zS(t,n),i--)}else zS(t,n)}return t}(e);var i,r,n=e.length,s=128,o=0,a=72;for(i=0;i<e.length;i++)(r=e[i])<128&&zS(t,KS(r));var c=t.length,l=c;for(c&&zS(t,"-");l<n;){var d=US;for(i=0;i<e.length;i++)(r=e[i])>=s&&r<d&&(d=r);var u=l+1;if(d-s>jS((US-o)/u))throw GS(HS);for(o+=(d-s)*u,s=d,i=0;i<e.length;i++){if((r=e[i])<s&&++o>US)throw GS(HS);if(r==s){for(var h=o,p=36;;){var m=p<=a?1:p>=a+26?26:p-a;if(h<m)break;var _=h-m,f=36-m;zS(t,KS(ZS(m+_%f))),h=jS(_/f),p+=36}zS(t,KS(ZS(h))),a=$S(o,u,l==c),o=0,l++}}o++,s++}return qS(t,"")},tI=Vn,iI=ke,rI=zm,nI=C,sI=Sa,oI=c,aI=tn,cI=yo,lI=Do,dI=W,uI=IS,hI=function(e){var t=kS(e),i=wS(this),r=arguments.length,n=r>1?arguments[1]:void 0,s=void 0!==n;s&&(n=CS(n,r>2?arguments[2]:void 0));var o,a,c,l,d,u,h=LS(t),p=0;if(!h||this===xS&&NS(h))for(o=OS(t),a=i?new this(o):xS(o);o>p;p++)u=s?n(t[p],p):t[p],PS(a,p,u);else for(d=(l=MS(t,h)).next,a=i?new this:[];!(c=bS(d,l)).done;p++)u=s?DS(l,n,[c.value,p],!0):c.value,PS(a,p,u);return a.length=p,a},pI=o_,mI=Up.codeAt,_I=function(e){var t,i,r=[],n=XS(YS(QS(e),BS,"."),".");for(t=0;t<n.length;t++)i=n[t],zS(r,WS(FS,i)?"xn--"+eI(i):i);return qS(r,".")},fI=_u,gI=ss,TI=Ra,EI=kf,vI=ar,yI=vI.set,SI=vI.getterFor("URL"),II=EI.URLSearchParams,AI=EI.getState,RI=nI.URL,CI=nI.TypeError,bI=nI.parseInt,kI=Math.floor,DI=Math.pow,NI=oI("".charAt),wI=oI(/./.exec),OI=oI([].join),PI=oI(1..toString),MI=oI([].pop),LI=oI([].push),xI=oI("".replace),VI=oI([].shift),UI=oI("".split),FI=oI("".slice),BI=oI("".toLowerCase),HI=oI([].unshift),GI="Invalid scheme",WI="Invalid host",jI="Invalid port",KI=/[a-z]/i,JI=/[\d+-.a-z]/i,qI=/\d/,zI=/^0x/i,YI=/^[0-7]+$/,XI=/^\d+$/,QI=/^[\da-f]+$/i,ZI=/[\0\t\n\r #%/:<>?@[\\\]^|]/,$I=/[\0\t\n\r #/:<>?@[\\\]^|]/,eA=/^[\u0000-\u0020]+/,tA=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,iA=/[\t\n\r]/g,rA=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)HI(t,e%256),e=kI(e/256);return OI(t,".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,i=1,r=null,n=0,s=0;s<8;s++)0!==e[s]?(n>i&&(t=r,i=n),r=null,n=0):(null===r&&(r=s),++n);return n>i&&(t=r,i=n),t}(e),i=0;i<8;i++)n&&0===e[i]||(n&&(n=!1),r===i?(t+=i?":":"::",n=!0):(t+=PI(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},nA={},sA=uI({},nA,{" ":1,'"':1,"<":1,">":1,"`":1}),oA=uI({},sA,{"#":1,"?":1,"{":1,"}":1}),aA=uI({},oA,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),cA=function(e,t){var i=mI(e,0);return i>32&&i<127&&!dI(t,e)?e:encodeURIComponent(e)},lA={ftp:21,file:null,http:80,https:443,ws:80,wss:443},dA=function(e,t){var i;return 2==e.length&&wI(KI,NI(e,0))&&(":"==(i=NI(e,1))||!t&&"|"==i)},uA=function(e){var t;return e.length>1&&dA(FI(e,0,2))&&(2==e.length||"/"===(t=NI(e,2))||"\\"===t||"?"===t||"#"===t)},hA=function(e){return"."===e||"%2e"===BI(e)},pA={},mA={},_A={},fA={},gA={},TA={},EA={},vA={},yA={},SA={},IA={},AA={},RA={},CA={},bA={},kA={},DA={},NA={},wA={},OA={},PA={},MA=function(e,t,i){var r,n,s,o=fI(e);if(t){if(n=this.parse(o))throw CI(n);this.searchParams=null}else{if(void 0!==i&&(r=new MA(i,!0)),n=this.parse(o,null,r))throw CI(n);(s=AI(new II)).bindURL(this),this.searchParams=s}};MA.prototype={type:"URL",parse:function(e,t,i){var r,n,s,o,a,c=this,l=t||pA,d=0,u="",h=!1,p=!1,m=!1;for(e=fI(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=xI(e,eA,""),e=xI(e,tA,"$1")),e=xI(e,iA,""),r=hI(e);d<=r.length;){switch(n=r[d],l){case pA:if(!n||!wI(KI,n)){if(t)return GI;l=_A;continue}u+=BI(n),l=mA;break;case mA:if(n&&(wI(JI,n)||"+"==n||"-"==n||"."==n))u+=BI(n);else{if(":"!=n){if(t)return GI;u="",l=_A,d=0;continue}if(t&&(c.isSpecial()!=dI(lA,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&lA[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?l=CA:c.isSpecial()&&i&&i.scheme==c.scheme?l=fA:c.isSpecial()?l=vA:"/"==r[d+1]?(l=gA,d++):(c.cannotBeABaseURL=!0,LI(c.path,""),l=wA)}break;case _A:if(!i||i.cannotBeABaseURL&&"#"!=n)return GI;if(i.cannotBeABaseURL&&"#"==n){c.scheme=i.scheme,c.path=pI(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=PA;break}l="file"==i.scheme?CA:TA;continue;case fA:if("/"!=n||"/"!=r[d+1]){l=TA;continue}l=yA,d++;break;case gA:if("/"==n){l=SA;break}l=NA;continue;case TA:if(c.scheme=i.scheme,n==dS)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=pI(i.path),c.query=i.query;else if("/"==n||"\\"==n&&c.isSpecial())l=EA;else if("?"==n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=pI(i.path),c.query="",l=OA;else{if("#"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=pI(i.path),c.path.length--,l=NA;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=pI(i.path),c.query=i.query,c.fragment="",l=PA}break;case EA:if(!c.isSpecial()||"/"!=n&&"\\"!=n){if("/"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=NA;continue}l=SA}else l=yA;break;case vA:if(l=yA,"/"!=n||"/"!=NI(u,d+1))continue;d++;break;case yA:if("/"!=n&&"\\"!=n){l=SA;continue}break;case SA:if("@"==n){h&&(u="%40"+u),h=!0,s=hI(u);for(var _=0;_<s.length;_++){var f=s[_];if(":"!=f||m){var g=cA(f,aA);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n==dS||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(h&&""==u)return"Invalid authority";d-=hI(u).length+1,u="",l=IA}else u+=n;break;case IA:case AA:if(t&&"file"==c.scheme){l=kA;continue}if(":"!=n||p){if(n==dS||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(c.isSpecial()&&""==u)return WI;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(o=c.parseHost(u))return o;if(u="",l=DA,t)return;continue}"["==n?p=!0:"]"==n&&(p=!1),u+=n}else{if(""==u)return WI;if(o=c.parseHost(u))return o;if(u="",l=RA,t==AA)return}break;case RA:if(!wI(qI,n)){if(n==dS||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()||t){if(""!=u){var T=bI(u,10);if(T>65535)return jI;c.port=c.isSpecial()&&T===lA[c.scheme]?null:T,u=""}if(t)return;l=DA;continue}return jI}u+=n;break;case CA:if(c.scheme="file","/"==n||"\\"==n)l=bA;else{if(!i||"file"!=i.scheme){l=NA;continue}if(n==dS)c.host=i.host,c.path=pI(i.path),c.query=i.query;else if("?"==n)c.host=i.host,c.path=pI(i.path),c.query="",l=OA;else{if("#"!=n){uA(OI(pI(r,d),""))||(c.host=i.host,c.path=pI(i.path),c.shortenPath()),l=NA;continue}c.host=i.host,c.path=pI(i.path),c.query=i.query,c.fragment="",l=PA}}break;case bA:if("/"==n||"\\"==n){l=kA;break}i&&"file"==i.scheme&&!uA(OI(pI(r,d),""))&&(dA(i.path[0],!0)?LI(c.path,i.path[0]):c.host=i.host),l=NA;continue;case kA:if(n==dS||"/"==n||"\\"==n||"?"==n||"#"==n){if(!t&&dA(u))l=NA;else if(""==u){if(c.host="",t)return;l=DA}else{if(o=c.parseHost(u))return o;if("localhost"==c.host&&(c.host=""),t)return;u="",l=DA}continue}u+=n;break;case DA:if(c.isSpecial()){if(l=NA,"/"!=n&&"\\"!=n)continue}else if(t||"?"!=n)if(t||"#"!=n){if(n!=dS&&(l=NA,"/"!=n))continue}else c.fragment="",l=PA;else c.query="",l=OA;break;case NA:if(n==dS||"/"==n||"\\"==n&&c.isSpecial()||!t&&("?"==n||"#"==n)){if(".."===(a=BI(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==n||"\\"==n&&c.isSpecial()||LI(c.path,"")):hA(u)?"/"==n||"\\"==n&&c.isSpecial()||LI(c.path,""):("file"==c.scheme&&!c.path.length&&dA(u)&&(c.host&&(c.host=""),u=NI(u,0)+":"),LI(c.path,u)),u="","file"==c.scheme&&(n==dS||"?"==n||"#"==n))for(;c.path.length>1&&""===c.path[0];)VI(c.path);"?"==n?(c.query="",l=OA):"#"==n&&(c.fragment="",l=PA)}else u+=cA(n,oA);break;case wA:"?"==n?(c.query="",l=OA):"#"==n?(c.fragment="",l=PA):n!=dS&&(c.path[0]+=cA(n,nA));break;case OA:t||"#"!=n?n!=dS&&("'"==n&&c.isSpecial()?c.query+="%27":c.query+="#"==n?"%23":cA(n,nA)):(c.fragment="",l=PA);break;case PA:n!=dS&&(c.fragment+=cA(n,sA))}d++}},parseHost:function(e){var t,i,r;if("["==NI(e,0)){if("]"!=NI(e,e.length-1))return WI;if(t=function(e){var t,i,r,n,s,o,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return NI(e,u)};if(":"==h()){if(":"!=NI(e,1))return;u+=2,d=++l}for(;h();){if(8==l)return;if(":"!=h()){for(t=i=0;i<4&&wI(QI,h());)t=16*t+bI(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(!wI(qI,h()))return;for(;wI(qI,h());){if(s=bI(h(),10),null===n)n=s;else{if(0==n)return;n=10*n+s}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(o=l-d,l=7;0!=l&&o>0;)a=c[l],c[l--]=c[d+o-1],c[d+--o]=a;else if(8!=l)return;return c}(FI(e,1,-1)),!t)return WI;this.host=t}else if(this.isSpecial()){if(e=_I(e),wI(ZI,e))return WI;if(t=function(e){var t,i,r,n,s,o,a,c=UI(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(s=10,n.length>1&&"0"==NI(n,0)&&(s=wI(zI,n)?16:8,n=FI(n,8==s?1:2)),""===n)o=0;else{if(!wI(10==s?XI:8==s?YI:QI,n))return e;o=bI(n,s)}LI(i,o)}for(r=0;r<t;r++)if(o=i[r],r==t-1){if(o>=DI(256,5-t))return null}else if(o>255)return null;for(a=MI(i),r=0;r<i.length;r++)a+=i[r]*DI(256,3-r);return a}(e),null===t)return WI;this.host=t}else{if(wI($I,e))return WI;for(t="",i=hI(e),r=0;r<i.length;r++)t+=cA(i[r],nA);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return dI(lA,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&dA(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,r=e.password,n=e.host,s=e.port,o=e.path,a=e.query,c=e.fragment,l=t+":";return null!==n?(l+="//",e.includesCredentials()&&(l+=i+(r?":"+r:"")+"@"),l+=rA(n),null!==s&&(l+=":"+s)):"file"==t&&(l+="//"),l+=e.cannotBeABaseURL?o[0]:o.length?"/"+OI(o,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw CI(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new LA(e.path[0]).origin}catch(cW){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+rA(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(fI(e)+":",pA)},getUsername:function(){return this.username},setUsername:function(e){var t=hI(fI(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=cA(t[i],aA)}},getPassword:function(){return this.password},setPassword:function(e){var t=hI(fI(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=cA(t[i],aA)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?rA(e):rA(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,IA)},getHostname:function(){var e=this.host;return null===e?"":rA(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,AA)},getPort:function(){var e=this.port;return null===e?"":fI(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=fI(e))?this.port=null:this.parse(e,RA))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+OI(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,DA))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=fI(e))?this.query=null:("?"==NI(e,0)&&(e=FI(e,1)),this.query="",this.parse(e,OA)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=fI(e))?("#"==NI(e,0)&&(e=FI(e,1)),this.fragment="",this.parse(e,PA)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var LA=function(e){var t=lI(this,xA),i=TI(arguments.length,1)>1?arguments[1]:void 0,r=yI(t,new MA(e,!1,i));iI||(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())},xA=LA.prototype,VA=function(e,t){return{get:function(){return SI(this)[e]()},set:t&&function(e){return SI(this)[t](e)},configurable:!0,enumerable:!0}};if(iI&&(cI(xA,"href",VA("serialize","setHref")),cI(xA,"origin",VA("getOrigin")),cI(xA,"protocol",VA("getProtocol","setProtocol")),cI(xA,"username",VA("getUsername","setUsername")),cI(xA,"password",VA("getPassword","setPassword")),cI(xA,"host",VA("getHost","setHost")),cI(xA,"hostname",VA("getHostname","setHostname")),cI(xA,"port",VA("getPort","setPort")),cI(xA,"pathname",VA("getPathname","setPathname")),cI(xA,"search",VA("getSearch","setSearch")),cI(xA,"searchParams",VA("getSearchParams")),cI(xA,"hash",VA("getHash","setHash"))),aI(xA,"toJSON",(function(){return SI(this).serialize()}),{enumerable:!0}),aI(xA,"toString",(function(){return SI(this).serialize()}),{enumerable:!0}),RI){var UA=RI.createObjectURL,FA=RI.revokeObjectURL;UA&&aI(LA,"createObjectURL",sI(UA,RI)),FA&&aI(LA,"revokeObjectURL",sI(FA,RI))}gI(LA,"URL"),tI({global:!0,constructor:!0,forced:!rI,sham:!iI},{URL:LA}),MT("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var BA=vp.right;Vn({target:"Array",proto:!0,forced:!To&&ie>79&&ie<83||!np("reduceRight")},{reduceRight:function(e){return BA(this,e,arguments.length,arguments.length>1?arguments[1]:void 0)}});var HA=Co,GA="ArrayBuffer",WA=gT[GA];Vn({global:!0,constructor:!0,forced:C[GA]!==WA},{ArrayBuffer:WA}),HA(GA);var jA=Vn,KA=Gh,JA=c([].reverse),qA=[1,2];jA({target:"Array",proto:!0,forced:String(qA)===String(qA.reverse())},{reverse:function(){return KA(this)&&(this.length=this.length),JA(this)}});var zA=Xe,YA=TypeError,XA=Vn,QA=c,ZA=et,$A=B,eR=Wt,tR=function(e,t){if(!delete e[t])throw YA("Cannot delete property "+zA(t)+" of "+zA(e))},iR=_u,rR=i,nR=h_,sR=np,oR=Ey,aR=vy,cR=ie,lR=Sy,dR=[],uR=QA(dR.sort),hR=QA(dR.push),pR=rR((function(){dR.sort(void 0)})),mR=rR((function(){dR.sort(null)})),_R=sR("sort"),fR=!rR((function(){if(cR)return cR<70;if(!(oR&&oR>3)){if(aR)return!0;if(lR)return lR<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++)dR.push({k:t+r,v:i})}for(dR.sort((function(e,t){return t.v-e.v})),r=0;r<dR.length;r++)t=dR[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));XA({target:"Array",proto:!0,forced:pR||!mR||!_R||!fR},{sort:function(e){void 0!==e&&ZA(e);var t=$A(this);if(fR)return void 0===e?uR(t):uR(t,e);var i,r,n=[],s=eR(t);for(r=0;r<s;r++)r in t&&hR(n,t[r]);for(nR(n,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:iR(t)>iR(i)?1:-1}}(e)),i=eR(n),r=0;r<i;)t[r]=n[r++];for(;r<s;)tR(t,r++);return t}}),(0,gE.exportTypedArrayStaticMethod)("from",zE,AE);let gR=!0,TR=!0;function ER(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function vR(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 s=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,s),n.apply(this,[e,s])};const s=r.removeEventListener;r.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.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,s.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 yR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(gR=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function SR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(TR=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function IR(){if("object"==typeof window){if(gR)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function AR(e,t){TR&&console.warn(e+" is deprecated, please use "+t+" instead.")}function RR(e){return"[object Object]"===Object.prototype.toString.call(e)}function CR(e){return RR(e)?Object.keys(e).reduce((function(t,i){const r=RR(e[i]),n=r?CR(e[i]):e[i],s=r&&!Object.keys(n).length;return void 0===n||s?t:Object.assign(t,{[i]:n})}),{}):e}function bR(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?bR(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{bR(e,e.get(t),i)}))})))}function kR(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===r&&i.trackId===t.id&&bR(e,i,n)}))})),n}const DR=IR;function NR(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 s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{i=i.filter((e=>"videoinput"===e.kind));let o=i.find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=r(e.video),DR("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return DR("chrome: "+JSON.stringify(e)),n(e)},s=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(s(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(s(e))))))}}}function wR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function OR(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 vR(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function PR(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 MR(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},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const r=function(e){i(s(n(e)))};return t.apply(this,[r,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(n(t)))},i])})).then(i,r)}}function LR(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>kR(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),vR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>kR(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,r;return this.getSenders().forEach((i=>{i.track===e&&(t?r=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?r=!0:i=t),t.track===e))),r||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function xR(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 VR(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return xR(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 s(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=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=r[t]}));const o=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]),o.apply(this,arguments)):o.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:s(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 UR(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 FR(e,t){vR(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var BR=Object.freeze({__proto__:null,shimMediaStream:wR,shimOnTrack:OR,shimGetSendersWithDtmf:PR,shimGetStats:MR,shimSenderReceiverGetStats:LR,shimAddTrackRemoveTrackWithNative:xR,shimAddTrackRemoveTrack:VR,shimPeerConnection:UR,fixNegotiationNeeded:FR,shimGetUserMedia:NR,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,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||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 HR(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){AR("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 GR(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 WR(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,s]=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(pb){if("TypeError"!==pb.name)throw pb;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,s)}}function jR(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function KR(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),vR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function JR(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){AR("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function qR(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function zR(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const r=t.apply(this,arguments);if(i){const{sender:t}=r,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return r})}function YR(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 XR(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 QR(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 ZR=Object.freeze({__proto__:null,shimOnTrack:GR,shimPeerConnection:WR,shimSenderGetStats:jR,shimReceiverGetStats:KR,shimRemoveStream:JR,shimRTCDataChannel:qR,shimAddTransceiver:zR,shimGetParameters:YR,shimCreateOffer:XR,shimCreateAnswer:QR,shimGetUserMedia:HR,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 $R(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function eC(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function tC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=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=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.setRemoteDescription=a,a=function(e,t,i){const r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.addIceCandidate=a}function iC(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(rC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function rC(e){return e&&void 0!==e.video?Object.assign({},e,{video:CR(e.video)}):e}function nC(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?(AR("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 sC(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function oC(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function aC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var cC=Object.freeze({__proto__:null,shimLocalStreamsAPI:$R,shimRemoteStreamsAPI:eC,shimCallbacksAPI:tC,shimGetUserMedia:iC,shimConstraints:rC,shimRTCIceServerUrls:nC,shimTrackEventTransceiver:sC,shimCreateOfferLegacy:oC,shimAudioContext:aC}),lC={},dC={get exports(){return lC},set exports(e){lC=e}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let r=8;r<t.length;r+=2)switch(t[r]){case"raddr":i.relatedAddress=t[r+1];break;case"rport":i.relatedPort=parseInt(t[r+1],10);break;case"tcptype":i.tcpType=t[r+1];break;case"ufrag":i.ufrag=t[r+1],i.usernameFragment=t[r+1];break;default:void 0===i[t[r]]&&(i[t[r]]=t[r+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const r=e.substring(e.indexOf(" ")+1).split(";");for(let n=0;n<r.length;n++)i=r[n].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const r=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+i+" "+r.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substring(t+1,r),i.value=e.substring(r+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const r=t.matchPrefix(e+i,"a=ice-ufrag:")[0],n=t.matchPrefix(e+i,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substring(12),password:n.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(" ");i.profile=r[2];for(let s=3;s<r.length;s++){const n=r[s],o=t.matchPrefix(e,"a=rtpmap:"+n+" ")[0];if(o){const r=t.parseRtpMap(o),s=t.matchPrefix(e,"a=fmtp:"+n+" ");switch(r.parameters=s.length?t.parseFmtp(s[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"),s=-1!==r.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[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:s?"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 s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.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 s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:n};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[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 s=void 0!==i?i:2;n=e||t.generateSessionId();return"v=0\r\no="+(r||"thisisadapterortc")+" "+n+" "+s+" 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}(dC);var uC=lC,hC=e({__proto__:null,default:uC},[lC]);function pC(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=uC.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,vR(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function mC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||vR(e,"icecandidate",(e=>{if(e.candidate){const t=uC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function _C(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=uC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=uC.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=uC.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 s={};Object.defineProperty(s,"maxMessageSize",{get:()=>n}),this._sctp=s}return i.apply(this,arguments)}}function fC(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},vR(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function gC(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 TC(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 EC(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function vC(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var yC=Object.freeze({__proto__:null,shimRTCIceCandidate:pC,shimRTCIceCandidateRelayProtocol:mC,shimMaxMessageSize:_C,shimSendThrowTypeError:fC,shimConnectionState:gC,removeExtmapAllowMixed:TC,shimAddIceCandidateNullOrEmpty:EC,shimParameterlessSetLocalDescription:vC});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=IR,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=ER(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=ER(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=ER(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:yC,extractVersion:ER,disableLog:yR,disableWarnings:SR,sdp:hC};switch(r.browser){case"chrome":if(!BR||!UR||!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=BR,EC(e,r),vC(e),NR(e,r),wR(e),UR(e,r),OR(e),VR(e,r),PR(e),MR(e),LR(e),FR(e,r),pC(e),mC(e),gC(e),_C(e,r),fC(e),TC(e,r);break;case"firefox":if(!ZR||!WR||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=ZR,EC(e,r),vC(e),HR(e,r),WR(e,r),GR(e),JR(e),jR(e),KR(e),qR(e),zR(e),YR(e),XR(e),QR(e),pC(e),gC(e),_C(e,r),fC(e);break;case"safari":if(!cC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=cC,EC(e,r),vC(e),nC(e),oC(e),tC(e),$R(e),eC(e),sC(e),iC(e),aC(e),pC(e),mC(e),_C(e,r),fC(e),TC(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var SC,IC=Object.create,AC=Object.defineProperty,RC=Object.defineProperties,CC=Object.getOwnPropertyDescriptor,bC=Object.getOwnPropertyDescriptors,kC=Object.getOwnPropertyNames,DC=Object.getOwnPropertySymbols,NC=Object.getPrototypeOf,wC=Object.prototype.hasOwnProperty,OC=Object.prototype.propertyIsEnumerable,PC=Reflect.get,MC=Math.pow,LC=(e,t,i)=>t in e?AC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,xC=(e,t)=>{for(var i in t||(t={}))wC.call(t,i)&&LC(e,i,t[i]);if(DC)for(var i of DC(t))OC.call(t,i)&&LC(e,i,t[i]);return e},VC=(e,t)=>RC(e,bC(t)),UC=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),FC=(e,t)=>{for(var i in t)AC(e,i,{get:t[i],enumerable:!0})},BC=(e,t,i)=>(i=null!=e?IC(NC(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of kC(t))!wC.call(e,n)&&n!==i&&AC(e,n,{get:()=>t[n],enumerable:!(r=CC(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:AC(i,"default",{value:e,enumerable:!0}),e)),HC=(e,t,i,r)=>{for(var n,s=r>1?void 0:r?CC(t,i):t,o=e.length-1;o>=0;o--)(n=e[o])&&(s=(r?n(t,i,s):n(s))||s);return r&&s&&AC(t,i,s),s},GC=(e,t,i)=>LC(e,"symbol"!=typeof t?t+"":t,i),WC=(e,t,i)=>PC(NC(e),i,t),jC=(e,t,i)=>new Promise(((r,n)=>{var s=e=>{try{a(i.next(e))}catch(Yw){n(Yw)}},o=e=>{try{a(i.throw(e))}catch(Yw){n(Yw)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(s,o);a((i=i.apply(e,t)).next())})),KC=UC(((e,t)=>{var i=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function o(e,t,i,n,o){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new s(i,n||e,o),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,s=i.length,o=new Array(s);n<s;n++)o[n]=i[n].fn;return o},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,s,o){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,s),!0;case 6:return d.fn.call(d.context,t,i,n,s,o),!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 o(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return o(this,e,t,i,!0)},c.prototype.removeListener=function(e,t,i,n){var s=r?r+e:e;if(!this._events[s])return this;if(!t)return a(this,s),this;var o=this._events[s];if(o.fn)o.fn===t&&(!n||o.once)&&(!i||o.context===i)&&a(this,s);else{for(var c=0,l=[],d=o.length;c<d;c++)(o[c].fn!==t||n&&!o[c].once||i&&o[c].context!==i)&&l.push(o[c]);l.length?this._events[s]=1===l.length?l[0]:l:a(this,s)}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)})),JC=UC(((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),qC=UC((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 s=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var s=0;s<r.length;s+=1)null!=e[s+1]&&(i[r[s]]=t(e[s+1]))})(r.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},r=JC(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.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,o,n)}})),t.media=s,t};var s=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(s,{})},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(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),zC=UC(((e,t)=>{var i=JC(),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""}}))},s=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 s=0;s<t.names.length;s+=1){var o=t.names[s];t.name?r.push(i[t.name][o]):r.push(i[t.names[s]])}else r.push(i[t.name]);return n.apply(null,r)},o=["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||o,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(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(s(t,i,e))}))}))})),e.media.forEach((function(e){c.push(s("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(s(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),YC=UC((e=>{var t=qC(),i=zC();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),XC=UC(((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),QC=UC((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 s=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var s=0;s<r.length;s+=1)null!=e[s+1]&&(i[r[s]]=t(e[s+1]))})(r.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},r=XC(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.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,o,n)}})),t.media=s,t};var s=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(s,{})},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(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),ZC=UC(((e,t)=>{var i=XC(),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""}}))},s=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 s=0;s<t.names.length;s+=1){var o=t.names[s];t.name?r.push(i[t.name][o]):r.push(i[t.names[s]])}else r.push(i[t.name]);return n.apply(null,r)},o=["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||o,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(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(s(t,i,e))}))}))})),e.media.forEach((function(e){c.push(s("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(s(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),$C=UC((e=>{var t=QC(),i=ZC();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),eb=BC(KC()),tb=((SC=tb||{})[SC.INVALID_PARAMETER=4096]="INVALID_PARAMETER",SC[SC.INVALID_OPERATION=4097]="INVALID_OPERATION",SC[SC.NOT_SUPPORTED=4098]="NOT_SUPPORTED",SC[SC.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",SC[SC.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",SC[SC.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",SC[SC.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",SC[SC.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",SC[SC.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",SC[SC.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",SC[SC.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",SC[SC.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",SC[SC.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",SC[SC.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",SC[SC.CLIENT_BANNED=16448]="CLIENT_BANNED",SC[SC.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",SC[SC.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",SC[SC.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",SC[SC.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",SC[SC.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",SC[SC.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",SC[SC.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",SC[SC.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",SC[SC.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",SC[SC.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",SC[SC.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",SC[SC.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",SC[SC.API_CALL_ABORTED=16461]="API_CALL_ABORTED",SC[SC.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",SC[SC.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",SC[SC.UNKNOWN=65535]="UNKNOWN",SC),ib=tb,rb=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=ib.UNKNOWN,extraCode:n=0,constraint:s}=e,o="<".concat(function(e){for(let t in ib)if(ib[t]===e)return t;return"UNKNOWN"}(r)," 0x").concat(r.toString(16),">"),a="".concat(i).concat(s?" constraint: ".concat(s):"").concat(null!=i&&i.includes(o)?"":" ".concat(o));super(a),GC(this,"code"),GC(this,"extraCode"),GC(this,"message"),GC(this,"originMessage"),GC(this,"name"),GC(this,"constraint"),this.code=r,this.extraCode=n,this.name=t,this.message=a,this.constraint=s,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},nb=rb,sb=((new Date).getTime(),0),ob=function(){return(new Date).getTime()+sb},ab=function(){let e=new Date;return e.setTime(ob()),e.toLocaleString()},cb={};FC(cb,{bytes2ms:()=>Qk,convertObjectNumberToInt:()=>BD,copyProperties:()=>Xk,deepClone:()=>ND,deepMerge:()=>DD,delay:()=>HD,fibonacci:()=>nD,formatedTime:()=>PD,getConstructorName:()=>TD,getContainerFromElement:()=>OD,getEnv:()=>Gk,getInternalVersion:()=>ID,getLoggerUrl:()=>jk,getMuteStateFromFlag:()=>CD,getNetworkType:()=>Jk,getNumNetworkType:()=>Yk,getReconnectionTimeout:()=>sD,getStringByteLength:()=>xD,getTurnServer:()=>bD,getUint32Version:()=>FD,getValueType:()=>oD,getViewListFromView:()=>wD,glog:()=>tD,ipv4ToUint32:()=>kD,isArray:()=>pD,isAudioWorkletSupported:()=>ED,isBoolean:()=>uD,isConstructor:()=>gD,isEmpty:()=>RD,isFunction:()=>aD,isLangChinese:()=>iD,isMediaStreamTrack:()=>mD,isNumber:()=>dD,isObject:()=>hD,isOverseaSdkAppId:()=>Wk,isPlainObject:()=>rD,isPortrait:()=>VD,isPromise:()=>fD,isRemoteTrack:()=>_D,isString:()=>lD,isUndefined:()=>cD,loadImage:()=>UD,ms2bytes:()=>$k,ms2samples:()=>eD,performanceNow:()=>yD,promiseAny:()=>vD,samples2ms:()=>Zk,setNetworkType:()=>zk,stringify:()=>MD,stringifyIncludeValue:()=>LD,throttlePromise:()=>GD});var lb={};FC(lb,{AUDIO_MUTE_BIT:()=>zb,AUDIO_STAT_BIT:()=>qb,AUX_STAT_BIT:()=>Jb,AUX_STREAM_MSID:()=>$b,BACKEND_ENV:()=>Gb,BASE_DOC_URL:()=>Ab,BASE_HOST:()=>vb,CAPABILITIES_KEYS:()=>Bk,CLASS_NAME:()=>wk,CLOUD_CONSOLE_URL:()=>Ib,CROSS_ROOM_BIT:()=>Qb,DATA_FREEZE_TIMING:()=>Ak,DEFAULT_ASSETS_URL:()=>Rb,DOC_URL:()=>Cb,DTLS_STATE_UNKNOWN:()=>lk,ENV_NAME:()=>wb,EXCHANGE_SDP_TIMEOUT:()=>Ek,IS_WORKER:()=>_b,IS_WORKLET:()=>fb,KIBANA_EVENT:()=>fk,LOCAL_STREAM_PUBLISH_STATE:()=>Ik,LOGGER_CMD_TYPE:()=>Nb,LOGGER_DOMAIN:()=>bb,LOGGER_DOMAIN_OVERSEA:()=>kb,LOG_LEVEL:()=>Ob,LOG_LEVEL_NAME:()=>xk,MAIN_STREAM_MSID:()=>Zb,MAX_RTT:()=>Hk,MICROPHONE_COMMUNICATIONS:()=>Lk,MICROPHONE_DEFAULT:()=>Pk,MUTE_ALL_BIT:()=>Xb,NAME:()=>Bb,NETWORK_TYPE:()=>Lb,NOT_SUPPORTED_H264:()=>Sk,PAUSED_RETRY_COUNT:()=>Ok,PEERCONNECTION_CONNECTING_TIMEOUT:()=>kk,PEER_CONNECTION_STATE:()=>dk,PEER_LEAVE_REASON:()=>Vk,RECOVER_CAPTURE_INTERVAL:()=>Fk,REMOTE_STREAM_TYPE_AUX:()=>tk,REMOTE_STREAM_TYPE_MAIN:()=>ek,RENDER_FREEZE_TIMING:()=>Rk,SCHEDULE_DOMAIN:()=>Dk,SCHEDULE_TIMEOUT:()=>Nk,SDP_SEMANTICS_PLAN_B:()=>yk,SDP_SEMANTICS_UNIFIED_PLAN:()=>vk,SECOND_HOST:()=>yb,SIGNAL_PING_PONG_INTERVAL:()=>Mb,SIGNAL_PING_TIMEOUT:()=>Pb,SIGNAL_RECONNECTION_COUNT:()=>_k,SMALL_STAT_BIT:()=>Kb,SPEAKER_DEFAULT:()=>Mk,STORAGE_EXPIRES_TIME:()=>xb,STREAM_TYPE_BIG:()=>Ck,STREAM_TYPE_SMALL:()=>bk,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Uk,SYNC_USER_LIST_INTERVAL:()=>gk,Scene:()=>Wb,THIRD_HOST:()=>Sb,TRANSPORT_DIRECTION:()=>Hb,TRTC_ERROR_ASSISTANCE:()=>Db,TRTC_QUALITY_BAD:()=>ok,TRTC_QUALITY_DISCONNECTED:()=>ck,TRTC_QUALITY_EXCELLENT:()=>rk,TRTC_QUALITY_GOOD:()=>nk,TRTC_QUALITY_POOR:()=>sk,TRTC_QUALITY_UNKNOWN:()=>ik,TRTC_QUALITY_VERY_BAD:()=>ak,UPDATE_OFFER_TIMEOUT:()=>Tk,VIDEO_MUTE_BIT:()=>Yb,VIDEO_STAT_BIT:()=>jb,audioProfileMap:()=>Vb,getRetryCount:()=>pk,getScriptDir:()=>gb,innerVersion:()=>db,loggerProxy:()=>Tb,screenProfileMap:()=>Fb,setLoggerProxy:()=>Eb,setRetryCount:()=>hk,setVersion:()=>hb,version:()=>ub,videoProfileMap:()=>Ub});var db="4.15.00.1600",ub="5.0.0";function hb(e){ub=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));db="".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 pb,mb,_b="undefined"!=typeof importScripts,fb="undefined"!=typeof registerProcessor,gb=()=>{let e=_b?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Tb="",Eb=e=>Tb=e,vb="web.sdk.qcloud.com",yb="web.sdk.tencent.cn",Sb="web.sdk.cloud.tencent.cn",Ib="https://console.cloud.tencent.com/trtc",Ab="https://".concat(vb,"/trtc/webrtc/v5/doc"),Rb="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",Cb="".concat(Ab,"/zh-cn/"),bb="https://yun.tim.qq.com",kb="https://apisgp.my-imcloud.com",Db="trtc_error_assistance",Nb={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},wb={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Ob=((mb=Ob||{})[mb.TRACE=0]="TRACE",mb[mb.DEBUG=1]="DEBUG",mb[mb.INFO=2]="INFO",mb[mb.WARN=3]="WARN",mb[mb.ERROR=4]="ERROR",mb[mb.NONE=5]="NONE",mb),Pb=18e3,Mb=2e3,Lb={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},xb=6048e5,Vb={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}},Ub={"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}},Fb={"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}},Bb={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",LOADEDMETADATA:"loadedmetadata",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"},Hb={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Gb={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Wb=((pb=Wb||{}).LIVE="live",pb.RTC="rtc",pb),jb=1,Kb=2,Jb=4,qb=8,zb=64,Yb=16,Xb=112,Qb=128,Zb="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",$b="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",ek=Bb.MAIN,tk=Bb.AUXILIARY,ik=0,rk=1,nk=2,sk=3,ok=4,ak=5,ck=6,lk="unknown",dk={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},uk=1/0;function hk(e){uk=e}function pk(){return uk}var mk,_k=30,fk={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"},gk=1e4,Tk=1e4,Ek=1e4,vk="unified-plan",yk="plan-b",Sk=1028,Ik=((mk=Ik||{})[mk.UNPUBLISH=-1]="UNPUBLISH",mk[mk.PUBLISHING=0]="PUBLISHING",mk[mk.PUBLISHED=1]="PUBLISHED",mk),Ak=500,Rk=1e3,Ck=Bb.BIG,bk=Bb.SMALL,kk=1e4,Dk={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},Nk=2e3,wk={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Ok=5,Pk="default",Mk=Pk,Lk="communications",xk=Object.keys(Ob),Vk=["normal leave","timeout leave","kick","role change"],Uk=10,Fk=2e3,Bk=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Hk=1e4,Gk=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Wk=e=>Number(e)<14e8,jk=function(e,t){let i;i=Tb||(Wk(e)?kb:bb);let r=Math.floor(Math.random()*MC(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},Kk="unknown";function Jk(){if("unknown"!==Kk)return Kk;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&&(Kk=qk(r,n)),Kk}function qk(e,t){if(Lb[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function zk(e){Kk=qk(e)}function Yk(){return Lb[Jk()]}function Xk(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 Qk(e){return Zk(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function Zk(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function $k(e){return 4*eD(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function eD(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var tD="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},iD=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},rD=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 nD(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:nD(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function sD(e){return e>8?3e4:1e3*nD(e)}function oD(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var aD=e=>"function"==typeof e,cD=e=>void 0===e,lD=e=>"string"==typeof e,dD=e=>"number"==typeof e,uD=e=>"boolean"==typeof e,hD=e=>"object"===oD(e),pD=e=>"array"===oD(e),mD=e=>oD(e)==="MediaStreamTrack".toLowerCase(),_D=e=>e.isRemote,fD=e=>"promise"===oD(e),gD=e=>aD(e)&&e.prototype.constructor===e,TD=e=>gD(e)?e.prototype.constructor.name:"",ED="undefined"!=typeof AudioWorkletNode;function vD(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 yD(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var SD=e=>+e<10?"0".concat(e):e,ID=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=SD(i[1])+SD(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},AD=Object.prototype.hasOwnProperty;function RD(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(rD(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(AD.call(e,t))return!1;return!0}return!1}function CD(e,t){return{userId:t,hasAudio:!!(e&qb),hasVideo:!!(e&jb),hasAuxiliary:!!(e&Jb),hasSmall:!!(e&Kb),audioMuted:!!(e&zb),videoMuted:!!(e&Yb),audioAvailable:!(!(e&qb)||e&zb),videoAvailable:!(!(e&jb)||e&Yb)}}function bD(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!cD(e.username)&&!cD(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",cD(e.credentialType)||(t.credentialType=e.credentialType)),t}function kD(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!lD(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 DD=function(e,t,i,r){if(!hD(e)||!hD(t))return 0;let n,s=0,o=Object.keys(t);for(let a=0,c=o.length;a<c;a++)if(n=o[a],!(cD(t[n])||i&&i.includes(n)))if(hD(e[n])&&hD(t[n]))s+=DD(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=ND(t[n]),s+=1)}return s};function ND(e){if(pD(e)){let t=[];return e.forEach(((e,i)=>{t[i]=ND(e)})),t}if(hD(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=ND(e[i])})),t}return e}var wD=e=>{let t=[];if(pD(e))t=[...e];else if(lD(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},OD=e=>lD(e)?document.getElementById(e):e,PD=()=>(e=>{let t=e=>e<10?"0".concat(e):"".concat(e),i=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),s=t(e.getHours()),o=t(e.getMinutes()),a=t(e.getSeconds());return"".concat(i,"/").concat(r,"/").concat(n," ").concat(s,":").concat(o,":").concat(a)})(new Date);function MD(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(pD(e))return"[".concat(e.map((e=>MD(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!rD(e)||!pD(i)&&!pD(r))return JSON.stringify(e);let t={},n=new Set(i),s=new Set(r);return Object.keys(e).forEach((o=>{(0===s.size&&n.has(o)||0===n.size&&!s.has(o))&&(t[o]=rD(e[o])||pD(e[o])?JSON.parse(MD(e[o],{keysToExclude:r,keysToInclude:i})):e[o])})),JSON.stringify(t)}catch(mk){return"{}"}}function LD(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)})),MD(e,{keysToInclude:i})}function xD(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var VD=()=>{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},UD=e=>jC(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(lD(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 nb({code:ib.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}}))})),FD=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},BD=e=>(Object.keys(e).forEach((t=>{dD(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(rD(e[t])||pD(e[t]))&&BD(e[t])})),e);function HD(e,t){return new Promise((i=>{let r=setTimeout(i,e);t&&t(r)}))}function GD(e,t){let i=null;return function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return i||(i=e.apply(t||this,n),i.finally((()=>i=null)),i)}}function WD(e){let{url:t,body:i,method:r="POST",timeout:n,priority:s}=e;return new Promise(((e,o)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:s}).then((e=>e.text())).then((t=>{try{e({data:JSON.parse(t)})}catch(Yw){e({data:t})}}),o);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(4===a.readyState)if(a.status>=200&&a.status<300)try{let t=JSON.parse(a.response);e({data:t})}catch(t){e({data:a.response})}else o({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=n||5e3,a.open(r,t,!0),a.send(i)}))}function jD(e){return jC(this,null,(function*(){let t=yD(),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 Ww.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(yD()-t,"ms")),r}catch(mk){return i}}))}var KD=Object.prototype.hasOwnProperty,JD=e=>"function"==typeof e,qD=e=>void 0===e,zD=e=>e.isRemote;function YD(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(KD.call(e,t))return!1;return!0}return!1}var XD=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:n,onRetryFailed:s,onRetrySuccess:o,context:a}=e;return function(){for(var e=arguments.length,c=new Array(e),l=0;l<e;l++)c[l]=arguments[l];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,_=(e,i)=>jC(this,null,(function*(){let l=a||this;try{let i=yield t.apply(l,c);h>0&&o&&o.call(this,h),h=0,e(i)}catch(f){let t=()=>{clearTimeout(p),h=0,m=2,i(f)},o=()=>{2!==m&&h<(JD(d)?d():d)?(h++,m=1,JD(n)&&n.call(this,h,t),p=window.setTimeout((()=>{p=-1,_(e,i)}),JD(u)?u(h):u)):(t(),JD(s)&&s.call(this,f))};JD(r)?r.call(this,{error:f,retry:o,reject:i,retryFuncArgs:c,retriedCount:h}):o()}}));return new Promise(_)}},QD=class{constructor(e){GC(this,"userId"),GC(this,"remoteUserId"),GC(this,"id"),GC(this,"sdkAppId"),GC(this,"type"),GC(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):"","]")),Ww.log(e,t,qD(this.userId)||YD(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)}},ZD={};FC(ZD,{ANDROID_VERSION:()=>uN,CHROME_MAJOR_VERSION:()=>pw,CHROME_VERSION:()=>mw,EDGE_VERSION:()=>TN,EDG_MAJOR_VERSION:()=>yN,EDG_VERSION:()=>vN,FIREFOX_MAJOR_VERSION:()=>fN,FIREFOX_VERSION:()=>_N,HUAWEI_VERSION:()=>iw,IE_VERSION:()=>ON,IOS_MAIN_VERSION:()=>vw,IOS_VERSION:()=>Ew,IPADQQB_VERSION:()=>WN,IS_ANDROID:()=>dN,IS_ANDROID_WEBVIEW:()=>Tw,IS_ANY_SAFARI:()=>fw,IS_CHROME:()=>uw,IS_CHROME_OS:()=>qN,IS_CHROMIUM_BASE:()=>dw,IS_EDG:()=>EN,IS_EDGE:()=>gN,IS_ELECTRON:()=>XN,IS_FIREFOX:()=>mN,IS_HEADLESS_CHROME:()=>hw,IS_HONOR:()=>tw,IS_HUAWEI:()=>ew,IS_HUAWEIBROWSER:()=>$N,IS_IE:()=>wN,IS_IE8:()=>NN,IS_IOS:()=>lN,IS_IOS_13_OR_14:()=>Iw,IS_IOS_15_1:()=>Sw,IS_IPAD:()=>sN,IS_IPADQQB:()=>GN,IS_IPAD_PRO:()=>oN,IS_IPHONE:()=>aN,IS_IPOD:()=>cN,IS_LINUX:()=>JN,IS_LOCAL:()=>Aw,IS_MAC:()=>KN,IS_MACQQB:()=>BN,IS_MIBROWSER:()=>QN,IS_MQQB:()=>xN,IS_NATIVE_ANDROID:()=>pN,IS_OLD_ANDROID:()=>hN,IS_OPPOBROWSER:()=>sw,IS_SAFARI:()=>_w,IS_SAFARI_15_1:()=>yw,IS_SAMSUNGBROWSER:()=>rw,IS_SOGOU:()=>AN,IS_SOGOUM:()=>SN,IS_TBS:()=>CN,IS_UCBROWSER:()=>YN,IS_VIVOBROWSER:()=>aw,IS_WECHAT:()=>PN,IS_WIN:()=>jN,IS_WQQB:()=>UN,IS_WX:()=>zN,IS_X5MQQB:()=>LN,IS_XWEB:()=>kN,MACQQB_VERSION:()=>HN,MI_VERSION:()=>ZN,MQQB_VERSION:()=>VN,OPPO_VERSION:()=>ow,SAFARI_VERSION:()=>gw,SAMSUNG_VERSION:()=>nw,SOGOUM_VERSION:()=>IN,SOGOU_VERSION:()=>RN,TBS_VERSION:()=>bN,UA_DATA_STRING:()=>Dw,USER_AGENT:()=>$D,VIVO_VERSION:()=>cw,WECHAT_VERSION:()=>MN,WQQB_VERSION:()=>FN,XWEB_VERSION:()=>DN,browserInfo:()=>Cw,getBrowserInfo:()=>bw,getChromeMajorVersion:()=>lw,getDeviceModel:()=>ww,getOSName:()=>Pw,getOSNumber:()=>Mw,getOSString:()=>Lw,getOSType:()=>Vw,getTerminalType:()=>xw,getUserAgentData:()=>Nw,isLocalStorageEnabled:()=>Rw});var $D="undefined"==typeof navigator?"":navigator.userAgent,eN=e=>new RegExp(e,"i").test($D),tN=e=>{if(eN(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=$D.match(t);if(i&&i[1])return i[1]}return""},iN=e=>{if(eN(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=$D.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},rN=/AppleWebKit\/([\d.]+)/i.exec($D),nN=rN?parseFloat(rN[1]):NaN,sN=eN("iPad"),oN="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&eN("Macintosh"),aN=eN("iPhone")&&!sN,cN=eN("iPod"),lN=aN||sN||cN||oN,dN=eN("Android"),uN=function(){if(dN){let e=$D.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}(),hN=dN&&eN("webkit")&&uN<2.3,pN=dN&&uN<5&&nN<537,mN=eN("Firefox"),_N=tN("Firefox"),fN=iN("Firefox"),gN=eN("Edge"),TN=tN("Edge"),EN=eN("Edg"),vN=tN("Edg"),yN=iN("Edg"),SN=eN("SogouMobileBrowser"),IN=tN("SogouMobileBrowser"),AN=eN("MetaSr\\s"),RN=tN("MetaSr\\s"),CN=eN("TBS"),bN=tN("TBS"),kN=eN("XWEB"),DN=tN("XWEB"),NN=eN("MSIE\\s8\\.0"),wN=eN("MSIE\\/\\d+"),ON=function(){if(wN){let e=/MSIE\s(\d+)\.\d/.exec($D),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test($D)&&/rv:11.0/.test($D)&&(t=11),t}return NaN}(),PN=eN("(micromessenger|webbrowser)"),MN=tN("MicroMessenger"),LN=!CN&&eN("MQQBrowser")&&eN("COVC"),xN=!CN&&eN("MQQBrowser")&&!eN("COVC"),VN=xN||LN?tN("MQQBrowser"):"",UN=!CN&&eN(" QQBrowser"),FN=tN(" QQBrowser"),BN=!CN&&eN("QQBrowserLite"),HN=tN("QQBrowserLite"),GN=!CN&&eN("MQBHD"),WN=tN("MQBHD"),jN=eN("Windows"),KN=!lN&&eN("MAC OS X"),JN=!dN&&eN("Linux"),qN=eN("CrOS"),zN=eN("MicroMessenger"),YN=eN("UCBrowser"),XN=eN("Electron"),QN=eN("MiuiBrowser"),ZN=tN("MiuiBrowser"),$N=eN("HuaweiBrowser"),ew=eN("Huawei")||eN("HUAWEI"),tw=eN("Honor")||eN("HONOR"),iw=tN("HuaweiBrowser"),rw=eN("SamsungBrowser"),nw=tN("SamsungBrowser"),sw=eN("HeyTapBrowser"),ow=tN("HeyTapBrowser"),aw=eN("VivoBrowser"),cw=tN("VivoBrowser"),lw=()=>iN("Chrome"),dw=eN("Chrome"),uw=!gN&&!AN&&!SN&&!CN&&!kN&&!EN&&!UN&&!QN&&!$N&&!rw&&!sw&&!aw&&dw,hw=eN("HeadlessChrome"),pw=lw(),mw=tN("Chrome"),_w=!dw&&!xN&&!LN&&!BN&&!GN&&eN("Safari"),fw=_w||lN,gw=tN("Version"),Tw=/Android.*(wv|.0.0.0)/.test($D),Ew=(()=>{if(oN)return gw;if(lN){let e=$D.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),vw=Number(Ew.split(".")[0]),yw="15.1"===gw,Sw="15.1"===Ew,Iw=(()=>{let e=Number(Ew.split(".")[0]);return 14===e||13===e})(),Aw="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),Rw=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(Qw){e=!1}return e}})(),Cw=bw();function bw(){let e=new Map([[mN,["Firefox",_N]],[EN,["Edg",vN]],[uw,["Chrome",mw]],[_w,["Safari",gw]],[CN,["TBS",bN]],[kN,["XWEB",DN]],[PN&&aN,["WeChat",MN]],[UN,["QQ(Win)",FN]],[xN,["QQ(Mobile)",VN]],[LN,["QQ(Mobile X5)",VN]],[BN,["QQ(Mac)",HN]],[GN,["QQ(iPad)",WN]],[QN,["MI",ZN]],[$N,["HW",iw]],[rw,["Samsung",nw]],[sw,["OPPO",ow]],[aw,["VIVO",cw]],[gN,["EDGE",TN]],[SN,["SogouMobile",IN]],[AN,["Sogou",RN]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var kw=null,Dw="";function Nw(){return jC(this,null,(function*(){if(kw)return kw;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(kw=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!Dw&&(Dw="UAData: ".concat(kw.platform,"/").concat(kw.platformVersion),kw.architecture&&kw.bitness&&(Dw+=" ".concat(kw.architecture,"/").concat(kw.bitness)),kw.mobile&&(Dw+=" mobile"),kw.model&&(Dw+=" model: ".concat(kw.model)),kw.fullVersionList&&(Dw+=" ".concat(kw.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),kw}catch(tW){return null}}))}function ww(){return(null==kw?void 0:kw.model)||""}var Ow=new Map([[dN,"Android"],[lN,"iOS"],[jN,"Windows"],[KN,"MacOS"],[JN,"Linux"],[qN,"ChromeOS"]]),Pw=function(){return Ow.get(!0)?Ow.get(!0):kw?kw.platform:"unknown"};function Mw(){return jN?1:dN?2:KN?3:lN?4:JN?5:qN?6:0}var Lw=()=>{let e=Pw();return e+="/".concat(Cw.name,"/").concat(_w?Cw.version:Cw.version.split(".")[0]),null!=kw&&kw.platformVersion&&(e+="/".concat(kw.platformVersion)),null!=kw&&kw.architecture&&(e+="/".concat(kw.architecture)),e};function xw(){return dN?4:aN?2:sN?3:KN?12:jN?5:JN?13:1}function Vw(){return dN?"Android":aN?"iPhone":sN?"iPad":KN?"Mac":jN?"Windows":JN?"Linux":"unknown"}var Uw,Fw=new(BC(KC(),1).default),Bw=((Uw=Bw||{}).ROOM_DESTROY="1",Uw.JOIN_START="21",Uw.JOIN_SCHEDULE_SUCCESS="22",Uw.JOIN_SIGNAL_CONNECTION_START="23",Uw.JOIN_SIGNAL_CONNECTION_END="24",Uw.JOIN_SEND_CMD="25",Uw.JOIN_RECEIVED_CMD_RES="26",Uw.JOIN_SUCCESS="27",Uw.JOIN_FAILED="28",Uw.LEAVE_START="51",Uw.LEAVE_SEND_CMD="52",Uw.LEAVE_SUCCESS="53",Uw.PUBLISH_START="61",Uw.SEND_FIRST_VIDEO_FRAME="62",Uw.PUBLISH_FAILED="63",Uw.SUBSCRIBE_START="81",Uw.SUBSCRIBE_SUCCESS="82",Uw.SUBSCRIBE_FAILED="84",Uw.UNSUBSCRIBE_SUCCESS="83",Uw.LOCAL_TRACK_CAPTURE_START="101",Uw.LOCAL_TRACK_CAPTURE_SUCCESS="102",Uw.LOCAL_TRACK_CAPTURE_FAILED="103",Uw.LOCAL_TRACK_PUBLISHED="104",Uw.LOCAL_TRACK_UNPUBLISHED="105",Uw.LOCAL_TRACK_REPLACED="106",Uw.SWITCH_DEVICE_SUCCESS="107",Uw.TRACK_MUTED="108",Uw.TRACK_UNMUTED="109",Uw.REMOTE_TRACK_SUBSCRIBED="110",Uw.REMOTE_TRACK_UNSUBSCRIBED="111",Uw.LOCAL_TRACK_RECAPTURE="112",Uw.PLAY_TRACK_START="151",Uw.PLAYER_STATE_CHANGED="152",Uw.VIDEO_LOADED_DATA="153",Uw.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",Uw.SIGNAL_CONNECTION_STATE_CHANGED="201",Uw.PEER_CONNECTION_STATE_CHANGED="202",Uw.SINGLE_CONNECTION_STAT="203",Uw.SPC_RECONNECTED="204",Uw.HEARTBEAT_REPORT="251",Uw.RECEIVED_PUBLISHED_USER_LIST="252",Uw.REMOTE_PUBLISH_STATE_CHANGED="253",Uw.AUDIO_LEVEL_INTERVAL="260",Uw.NETWORK_QUALITY="261",Uw.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",Uw.QUALITY_LIMITATION_CHANGED="263",Uw.LOG="264",Uw),Hw=Bw,Gw=class e{constructor(){GC(this,"_isEnableUploadLog",!0),GC(this,"_localJoinedUser",new Map),GC(this,"_queue",[]),GC(this,"_timeoutId",-1),GC(this,"_logLevel",1),GC(this,"_logLevelToUpload",2),!_b&&!fb&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){Fw.on(Hw.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.logLevelToUpload&&Ob[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),Fw.on(Hw.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),Fw.once(Hw.JOIN_FAILED,(()=>{this.startUpload()})),Fw.on(Hw.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()),5e3)}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(lD(i.userId)&&dD(i.sdkAppId)){let{userId:t,sdkAppId:r}=i;e.map.has(t)?e.map.get(t).logs.push(i):e.map.set(t,{userId:t,sdkAppId:r,logs:[i]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e}upload(){return jC(this,null,(function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;e<t.length;e++){let{userId:i,sdkAppId:r,logs:n}=t[e];yield this.uploadLogWithRetry(JSON.stringify({timestamp:ab(),sdkAppId:String(r),userId:i,version:ub,log:n.map((e=>e.log)).join("\n")}),r),n.forEach((e=>e.uploaded=!0))}}catch(Zw){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return XD({retryFunction:()=>WD({url:jk(t,Nb.LOG),body:e,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;t.setTime(ob());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(Ob[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){cD(Ob[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(lD(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(pb){return""}}log(t,i){let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;var o;i.unshift(this.getPrefix(t));let a={log:i.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:t,userId:n,sdkAppId:s,forAllJoinedClients:r};if(Fw.emit(Hw.LOG,{log:a}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(a),t<this._logLevel)return;let c=(null==(o=Ob[t])?void 0:o.toLowerCase())||"info";e.PRINT_LOG_TAG?console[c]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...i):console[c](...i)}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 QD(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Ob[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};GC(Gw,"PRINT_LOG_TAG",!(lN||dN||hw));var Ww=new Gw,jw=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)}))},Kw=new class{constructor(){GC(this,"_prefix","TRTC"),GC(this,"_queue",new Map)}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){Rw()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix))try{let t=localStorage.getItem(e);if(!t)return!1;let i=JSON.parse(t);if(i&&i.expiresIn<Date.now())return!0}catch(Zw){return!1}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(Rw())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(Qw){Ww.warn(Qw)}}getItem(e){if(!Rw())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(pb){Ww.warn(pb)}}setItem(e,t){if(Rw())try{let i={expiresIn:Date.now()+xb,value:t};this._queue.set(this.getRealKey(e),i)}catch(mk){Ww.warn(mk)}}deleteItem(e){if(!Rw())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(pb){return Ww.warn(pb),!1}}clear(){if(Rw())try{localStorage.clear()}catch(Qw){Ww.warn(Qw)}}},Jw={};FC(Jw,{HTTPS_API:()=>IP,IS_GET_CAPABILITIES_SUPPORTED:()=>GP,IS_GET_SETTINGS_SUPPORTED:()=>HP,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>BP,IS_INSERTABLE_STREAM_SUPPORTED:()=>WP,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>tM,IS_RTC_RTP_SENDER_SUPPORTED:()=>VP,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>jP,IS_SEI_SUPPORTED:()=>KP,IS_SPC_SUPPORTED:()=>LP,basis:()=>QP,capabilityCheck:()=>$P,checkSystemRequirementsInternal:()=>EP,decodeSupportStatus:()=>TP,encodeSupportStatus:()=>gP,getBrowserInfo:()=>dP,getDisplayResolution:()=>RP,isAddTransceiverSupported:()=>MP,isBrowserSupported:()=>uP,isGetReceiversSupported:()=>wP,isGetSendersSupported:()=>OP,isGetTransceiversSupported:()=>PP,isGetUserMediaSupported:()=>CP,isMediaDevicesSupported:()=>pP,isMediaSessionSupported:()=>zP,isMediaStreamTrackProcessorSupported:()=>fP,isReplaceTrackSupported:()=>UP,isRequestVideoFrameCallbackSupported:()=>eM,isSIMDSupported:()=>XP,isScreenCaptureApiAvailable:()=>yP,isSelectedCandidatePair:()=>AP,isSetParametersSupported:()=>FP,isSmallStreamAPISupported:()=>kP,isSmallStreamSupported:()=>DP,isStopTransceiverSupported:()=>xP,isTRTCSupported:()=>vP,isUnifiedPlanDefault:()=>NP,isUsedInHttpProtocol:()=>_P,isWebAudioSupported:()=>bP,isWebCodecSupported:()=>qP,isWebCodecsSupported:()=>hP,isWebRTCSupported:()=>JP,isWebTransportSupported:()=>YP});var qw={};FC(qw,{AUDIO_LEVEL_SCALE:()=>VO,AudioCodecPipelineType:()=>GO,AudioDecoderDowngradeState:()=>TO,AudioPlayerMode:()=>MO,AudioType:()=>AO,BASIC_TYPE:()=>FO,BannedReason:()=>LO,CONNECTION_CLOSED_REASON:()=>sO,ClientEvent:()=>oO,CodecType:()=>WO,ConnectionEvent:()=>nO,ConnectionState:()=>gO,DECODE_FAILED_ERROR_CODE:()=>jO,FacingMode:()=>OO,LeaveReason:()=>xO,LocalTrackEvent:()=>cO,MULTI_VIDEO_DATA_TYPE:()=>kO,MediaType:()=>SO,MediaTypeLabel:()=>IO,MonitorEventId:()=>DO,MutedFlag:()=>pO,NetworkQualityValue:()=>NO,PlayerState:()=>lO,ReceiveMode:()=>wO,RemoteStreamType:()=>bO,RemoteTrackEvent:()=>hO,RoomEvent:()=>dO,SceneNumber:()=>mO,StreamEvent:()=>aO,StreamType:()=>CO,SubscribeMediaType:()=>UO,TIMER_TYPE:()=>JO,TRACK_ACTION:()=>yO,TRACK_KIND:()=>vO,TrackEvent:()=>uO,UserRole:()=>fO,UserRoleNumber:()=>_O,VideoCodec:()=>BO,VideoCodecPipelineType:()=>HO,VideoContentHint:()=>KO,VideoDecoderDowngradeState:()=>EO,VideoPlayerMode:()=>PO,VideoType:()=>RO});var zw,Yw,Xw,Qw,Zw,$w,eO,tO,iO,rO,nO=((rO=nO||{}).TRACK_ADDED="track-added",rO.TRACK_UPDATED="track-updated",rO.TRACK_SUBSCRIBED="track-subscribed",rO.STREAM_ADDED="stream-added",rO.STREAM_REMOVED="stream-removed",rO.STREAM_UPDATED="stream-updated",rO.STREAM_PUBLISHED="stream-published",rO.STREAM_SUBSCRIBED="stream-subscribed",rO.STREAM_UNSUBSCRIBED="stream-unsubscribed",rO.STATE_CHANGED="state-changed",rO.ERROR="error",rO.CONNECTION_STATE_CHANGED="connection-state-changed",rO.FIREWALL_RESTRICTION="firewall-restriction",rO.SEI_MESSAGE="sei-message",rO.CLOSED="closed",rO),sO=(e=>(e.REMOTE_LEAVE="remote user exitRoom",e.REMOTE_UNPUBLISH="remote user unpublished",e.LOCAL_LEAVE="you exitRoom",e.LOCAL_UNPUBLISH="you unpublished",e.LOCAL_UNSUBSCRIBE="you unsubscribed",e.SWITCH_ROLE="you switch role to audience",e))(sO||{}),oO=((iO=oO||{}).STREAM_ADDED="stream-added",iO.STREAM_REMOVED="stream-removed",iO.STREAM_UPDATED="stream-updated",iO.STREAM_SUBSCRIBED="stream-subscribed",iO.CONNECTION_STATE_CHANGED="connection-state-changed",iO.PEER_JOIN="peer-join",iO.PEER_LEAVE="peer-leave",iO.MUTE_AUDIO="mute-audio",iO.MUTE_VIDEO="mute-video",iO.UNMUTE_AUDIO="unmute-audio",iO.UNMUTE_VIDEO="unmute-video",iO.CLIENT_BANNED="client-banned",iO.NETWORK_QUALITY="network-quality",iO.AUDIO_VOLUME="audio-volume",iO.SEI_MESSAGE="sei-message",iO.ERROR="error",iO),aO=((tO=aO||{}).PLAYER_STATE_CHANGED="player-state-changed",tO.SCREEN_SHARING_STOPPED="screen-sharing-stopped",tO.CONNECTION_STATE_CHANGED="connection-state-changed",tO.DEVICE_AUTO_RECOVERED="device-auto-recovered",tO.ERROR="error",tO),cO=(e=>(e.DEVICE_AUTO_RECOVERED="1",e.DEVICE_RECOVER_FAILED="5",e.DEVICE_CHANGED="2",e.ERROR="3",e.PUBLISH_STATE_CHANGED="4",e.ENCODE_FAILED="6",e))(cO||{}),lO=(e=>(e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e))(lO||{}),dO=((eO=dO||{}).PEER_JOIN="peer-join",eO.PEER_LEAVE="peer-leave",eO.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",eO.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",eO.BANNED="banned",eO.NETWORK_QUALITY="network-quality",eO.AUDIO_VOLUME="audio-volume",eO.SEI_MESSAGE="sei-message",eO.ERROR="error",eO.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",eO.REMOTE_PUBLISHED="remote-published",eO.REMOTE_UNPUBLISHED="remote-unpublished",eO.FIREWALL_RESTRICTION="firewall-restriction",eO.HEARTBEAT_REPORT="heartbeat-report",eO.CUSTOM_MESSAGE="custom-message",eO.LAYER_DATA="layerData",eO.FIRST_VIDEO_FRAME="first-video-frame",eO.DUMP="dump",eO),uO=(($w=uO||{}).PLAYER_STATE_CHANGED="player-state-changed",$w.MUTE="mute",$w.UNMUTE="unmute",$w.ERROR="error",$w.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",$w.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",$w.FIRST_VIDEO_FRAME="first-video-frame",$w),hO=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(hO||{}),pO=(e=>(e[e.VIDEO=1]="VIDEO",e[e.SMALL=2]="SMALL",e[e.AUX=4]="AUX",e[e.AUDIO=8]="AUDIO",e[e.VIDEO_MUTE=16]="VIDEO_MUTE",e[e.AUX_MUTE=32]="AUX_MUTE",e[e.AUDIO_MUTE=64]="AUDIO_MUTE",e))(pO||{}),mO=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(mO||{}),_O=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(_O||{}),fO=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(fO||{}),gO=(e=>(e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e))(gO||{}),TO=((Zw=TO||{}).INITIALIZED="INITIALIZED",Zw.STARTING="STARTING",Zw.STARTED="STARTED",Zw.FAILED="FAILED",Zw),EO=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(EO||{}),vO=(e=>(e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e))(vO||{}),yO=(e=>(e.ADD="add",e.REMOVE="remove",e))(yO||{}),SO=(e=>(e[e.NULL=0]="NULL",e[e.AUDIO=1]="AUDIO",e[e.AUX_VIDEO=2]="AUX_VIDEO",e[e.BIG_VIDEO=4]="BIG_VIDEO",e[e.SMALL_VIDEO=8]="SMALL_VIDEO",e))(SO||{}),IO={1:"audio",2:"auxVideo",4:"video"},AO=((Qw=AO||{})[Qw.opus=111]="opus",Qw),RO=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(RO||{}),CO=(e=>(e.Big="big",e.Small="small",e))(CO||{}),bO=(e=>(e.Main="main",e.Aux="auxiliary",e))(bO||{}),kO=(e=>(e[e.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",e[e.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",e[e.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",e[e.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",e[e.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",e))(kO||{}),DO=((Xw=DO||{})[Xw.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",Xw[Xw.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",Xw[Xw.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",Xw[Xw.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",Xw[Xw.MUTE_AUDIO=32772]="MUTE_AUDIO",Xw[Xw.MUTE_VIDEO=32773]="MUTE_VIDEO",Xw[Xw.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",Xw[Xw.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",Xw[Xw.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",Xw[Xw.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",Xw[Xw.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",Xw[Xw.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",Xw[Xw.SWITCH_CAMERA=32780]="SWITCH_CAMERA",Xw[Xw.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",Xw[Xw.REPLACE_VIDEO=32782]="REPLACE_VIDEO",Xw[Xw.REPLACE_AUDIO=32783]="REPLACE_AUDIO",Xw[Xw.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",Xw[Xw.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",Xw[Xw.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",Xw[Xw.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",Xw[Xw.JOIN=32788]="JOIN",Xw[Xw.LEAVE=32789]="LEAVE",Xw[Xw.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",Xw[Xw.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",Xw[Xw.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",Xw[Xw.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",Xw[Xw.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",Xw[Xw.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",Xw[Xw.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",Xw[Xw.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",Xw[Xw.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",Xw[Xw.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",Xw[Xw.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",Xw[Xw.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",Xw[Xw.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",Xw[Xw.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",Xw[Xw.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",Xw[Xw.PUBLISH_AUX=32805]="PUBLISH_AUX",Xw[Xw.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",Xw[Xw.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",Xw[Xw.VIDEO_ENCODER=4004]="VIDEO_ENCODER",Xw[Xw.VIDEO_DECODER=4005]="VIDEO_DECODER",Xw),NO=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.EXCELLENT=1]="EXCELLENT",e[e.GOOD=2]="GOOD",e[e.POOR=3]="POOR",e[e.BAD=4]="BAD",e[e.VERY_BAD=5]="VERY_BAD",e[e.DISCONNECTED=6]="DISCONNECTED",e))(NO||{}),wO=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTO_AUDIO=1]="AUTO_AUDIO",e[e.AUTO_VIDEO=2]="AUTO_VIDEO",e[e.AUTO_ALL=3]="AUTO_ALL",e))(wO||{}),OO=(e=>(e.user="user",e.environment="environment",e))(OO||{}),PO=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",e[e.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",e))(PO||{}),MO=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(MO||{}),LO=(e=>(e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e))(LO||{}),xO=((Yw=xO||{})[Yw.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",Yw[Yw.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",Yw[Yw.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",Yw[Yw.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",Yw[Yw.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",Yw[Yw.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",Yw[Yw.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",Yw[Yw.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",Yw[Yw.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",Yw),VO=1e8,UO=class{constructor(){GC(this,"mediaType",0)}set audio(e){e?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(1&this.mediaType)}set video(e){e?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(4&this.mediaType)}set auxiliary(e){e?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(2&this.mediaType)}set smallVideo(e){e?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(8&this.mediaType)}},FO=(e=>(e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e))(FO||{}),BO=(e=>(e.H264="h264",e.H265="h265",e.VP8="vp8",e))(BO||{}),HO=(e=>(e[e.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",e[e.DUMP=1]="DUMP",e[e.SEI=2]="SEI",e[e.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",e))(HO||{}),GO=(e=>(e[e.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",e[e.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",e[e.DUMP=2]="DUMP",e[e.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",e))(GO||{}),WO=(e=>(e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e))(WO||{}),jO=((zw=jO||{})[zw.SUCCESS=0]="SUCCESS",zw[zw.FAILED=1]="FAILED",zw[zw.WEBCODEC_INIT=2]="WEBCODEC_INIT",zw[zw.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",zw[zw.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",zw[zw.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",zw[zw.WASM_INIT=6]="WASM_INIT",zw[zw.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",zw[zw.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",zw[zw.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",zw[zw.TEST=10]="TEST",zw),KO=(e=>(e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e))(KO||{}),JO=(e=>(e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e))(JO||{}),qO={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},zO={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName: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,s="".concat(t||i.name),o="";return o=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(s,"' must be type of ").concat(o," when calling ").concat(r,"(), received type: ").concat(oD(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,s="".concat(t||i.name),o="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(s,"' must be instanceof ").concat(o," when calling ").concat(r,"(), received type: ").concat(oD(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/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 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,"()")},YO=(e,t)=>t?"".concat(Ab,"/").concat(e,"/").concat(t):"".concat(Ab,"/").concat(e,"/index.html"),XO=()=>{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(Db);if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let i=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:r}}return{}};function QO(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,s="",o="",a="";aD(zO[t])?s=zO[t](i):lD(zO[t])&&(s=zO[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=XO();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(aD(l[t])?a=l[t](i):lD(l[t])&&(a=l[t]));let d=s;return iD()&&(c&&c[t]&&(aD(c[t])?o=c[t](i):lD(c[t])&&(o=c[t])),o&&(d=n?"".concat(o,"\n请查看文档: ").concat(YO("zh-cn",a),"\n\n"):"".concat(o,"\n\n"),d+=s)),n&&(d+=" \nRefer to: ".concat(YO("en",a),"\n")),d}var ZO,$O=BC(YC(),1),eP=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];GC(this,"countMap",new Map),GC(this,"distributionMap",new Map),GC(this,"version"),GC(this,"log",Ww.createLogger({id:"kv"})),e&&(Fw.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===Bb.AUDIO?501700:511700,cost:i})})),Fw.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===Bb.AUDIO?501700:511700,error:i})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:FD(this.version||ub),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 s=(null==(n=this.distributionMap)?void 0:n.get(t))||new Map;s.set(i,(s.get(i)||0)+1),this.distributionMap.set(t,s)}addNumber(e){let{key:t,value:i,split:r=100,useUV:n=!1}=e;var s;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 o=(null==(s=this.distributionMap)?void 0:s.get(t))||new Map,a=0;if(dD(r))a=Math.floor(i/r);else for(let c=r.length-1;c>0;c--)if(i>r[c]){a=c;break}o.set(a,(o.get(a)||0)+1),this.distributionMap.set(t,o)}addSuccessEvent(e){let{key:t,cost:i,timeKey:r,split:n}=e;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),i)){let e=+String(t).slice(-3);e<800&&e>=700?this.addNumber({key:r||t+100,value:i,split:n}):r||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:i}=e;if(!t)return;let r=ib.UNKNOWN;i&&(dD(i)?r=i:(!cD(i.extraCode)||!cD(i.code))&&(r=i.extraCode||i.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:r,useUV:!1})}},tP=((ZO=tP||{})[ZO.enterRoom=500700]="enterRoom",ZO[ZO.exitRoom=500701]="exitRoom",ZO[ZO.switchRole=500702]="switchRole",ZO[ZO.destroy=500703]="destroy",ZO[ZO.startLocalAudio=500704]="startLocalAudio",ZO[ZO.updateLocalAudio=500705]="updateLocalAudio",ZO[ZO.stopLocalAudio=500706]="stopLocalAudio",ZO[ZO.startLocalVideo=500707]="startLocalVideo",ZO[ZO.updateLocalVideo=500708]="updateLocalVideo",ZO[ZO.stopLocalVideo=500709]="stopLocalVideo",ZO[ZO.startScreenShare=500710]="startScreenShare",ZO[ZO.updateScreenShare=500711]="updateScreenShare",ZO[ZO.stopScreenShare=500712]="stopScreenShare",ZO[ZO.startRemoteVideo=500713]="startRemoteVideo",ZO[ZO.updateRemoteVideo=500714]="updateRemoteVideo",ZO[ZO.stopRemoteVideo=500715]="stopRemoteVideo",ZO[ZO.muteRemoteAudio=500716]="muteRemoteAudio",ZO[ZO.setRemoteAudioVolume=500717]="setRemoteAudioVolume",ZO[ZO.use=500718]="use",ZO[ZO.sendSEIMessage=5e5]="sendSEIMessage",ZO[ZO.sendCustomMessage=500001]="sendCustomMessage",ZO),iP=(e=>(e[e.AudioMixer=550700]="AudioMixer",e[e.AIDenoiser=551700]="AIDenoiser",e[e.VirtualBackground=570700]="VirtualBackground",e[e.Beauty=571700]="Beauty",e[e.Watermark=572700]="Watermark",e[e.BasicBeauty=574700]="BasicBeauty",e[e.CDNStreaming=590700]="CDNStreaming",e[e.DeviceDetector=591700]="DeviceDetector",e[e.Debug=592700]="Debug",e))(iP||{}),rP=(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))(rP||{}),nP=(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))(nP||{}),sP=new eP(!0),oP=new eP(!1),aP=sP,cP={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},lP=new Map([[mN,["Firefox",_N]],[EN,["Edg",vN]],[uw,["Chrome",mw]],[_w,["Safari",gw]],[CN,["TBS",bN]],[kN,["XWEB",DN]],[PN&&aN,["WeChat",MN]],[UN,["QQ(Win)",FN]],[xN,["QQ(Mobile)",VN]],[LN,["QQ(Mobile X5)",VN]],[BN,["QQ(Mac)",HN]],[GN,["QQ(iPad)",WN]],[QN,["MI",ZN]],[$N,["HW",iw]],[rw,["Samsung",nw]],[sw,["OPPO",ow]],[aw,["VIVO",cw]],[gN,["EDGE",TN]],[SN,["SogouMobile",IN]],[AN,["Sogou",RN]]]);function dP(){let e=lP.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var uP=function(){return!(YN||gN||EN&&yN<80||mN&&fN<56)},hP=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},pP=function(){if(!navigator.mediaDevices)return _P()||Ww.error(zO.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},mP=!1;function _P(){return"http:"===location.protocol&&!Aw&&(mP||Ww.error(QO({key:qO.NOT_SUPPORTED_HTTP})),mP=!0,!0)}var fP=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},gP=function(){return jC(this,null,(function*(){if(cP.detail.isH264EncodeSupported&&cP.detail.isVp8EncodeSupported)return{isH264EncodeSupported:cP.detail.isH264EncodeSupported,isVp8EncodeSupported:cP.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection,n=document.createElement(Bb.CANVAS);n.getContext("2d");let s=n.captureStream(0);return r.addTrack(s.getVideoTracks()[0],s),e=yield r.createOffer(),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),cP.detail.isH264EncodeSupported=t,cP.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:cP.detail.isH264EncodeSupported,isVp8EncodeSupported:cP.detail.isVp8EncodeSupported}}catch(mk){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},TP=function(){return jC(this,null,(function*(){if(cP.detail.isH264DecodeSupported&&cP.detail.isVp8DecodeSupported)return{isH264DecodeSupported:cP.detail.isH264DecodeSupported,isVp8DecodeSupported:cP.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(mk){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},EP=GD((()=>jC(void 0,null,(function*(){if(cP.result&&cP.detail.isH264EncodeSupported&&cP.detail.isVp8EncodeSupported&&cP.detail.isH264DecodeSupported&&cP.detail.isVp8DecodeSupported)return cP;let e=Date.now(),t=uP(),i=JP(),r=hP(),n=pP(),{isH264EncodeSupported:s,isVp8EncodeSupported:o}=yield gP(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield TP();if(!s||!o){let e=yield gP();Ww.warn("detect encode again h264:".concat(s," vp8:").concat(o," result: ").concat(JSON.stringify(e))),s=e.isH264EncodeSupported,o=e.isVp8EncodeSupported}if(s&&a&&(sw||aw||Tw)&&!CN&&lw()<79){let{encode:e,decode:t}=yield function(){return jC(this,null,(function*(){return SP||(SP=new Promise((e=>jC(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{Ww.warn("detectH264Supported start");let r=document.createElement("canvas"),n=r.getContext("2d");r.width=320,r.height=240;let s=setInterval((()=>{n.fillText("test",Math.floor(320*Math.random()),Math.floor(240*Math.random()))}),66),o=-1,a=-1;i=()=>{clearInterval(o),clearInterval(s),clearTimeout(a),l.close(),d.close(),c.getTracks().forEach((e=>e.stop()))},a=setTimeout((()=>{i(),e(t)}),2e3);let c=r.captureStream(),l=new RTCPeerConnection({}),d=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",(e=>d.addIceCandidate(e.candidate))),d.addEventListener("icecandidate",(e=>l.addIceCandidate(e.candidate))),l.addTrack(c.getVideoTracks()[0],c);let u=yield l.createOffer();yield l.setLocalDescription(u),yield d.setRemoteDescription(u);let h=yield d.createAnswer(),p=$O.default.parse(h.sdp),m=p.media[0].rtp.findIndex((e=>"H264"===e.codec));p.media[0].rtp=[p.media[0].rtp[m]],p.media[0].fmtp=p.media[0].fmtp.filter((e=>e.payload===p.media[0].rtp[0].payload)),p.media[0].rtcpFb&&(p.media[0].rtcpFb=p.media[0].rtcpFb.filter((e=>e.payload===p.media[0].rtp[0].payload))),h.sdp=$O.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),o=setInterval((()=>jC(this,null,(function*(){t.encode&&t.decode&&(i(),e(t));let r=yield l.getSenders()[0].getStats(),n=yield d.getReceivers()[0].getStats();t.encode||r.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===Bb.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===Bb.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(r){i(),Ww.warn(r),e(t)}})))).then((e=>((!e.encode||!e.decode)&&Ww.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(Dw)),e))),SP)}))}();s=e,a=t}return cP.result=t&&i&&n&&(s||o)&&(a||c),cP.detail.isBrowserSupported=t,cP.detail.isWebRTCSupported=i,cP.detail.isWebCodecsSupported=r,cP.detail.isMediaDevicesSupported=n,cP.detail.isScreenShareSupported=yP(),cP.detail.isSmallStreamSupported=DP(),cP.detail.isH264EncodeSupported=s,cP.detail.isVp8EncodeSupported=o,cP.detail.isH264DecodeSupported=a,cP.detail.isVp8DecodeSupported=c,cP.result||Ww.error("".concat(navigator.userAgent," ").concat(LD(cP.detail,!1))),Kw.setItem(ZP,{ua:navigator.userAgent,checkResult:cP}),aP.addNumber({key:523800,value:Date.now()-e}),cP})))),vP=function(){return cP.result},yP=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},SP=null;var IP=(e,t,i)=>{"http:"===location.protocol&&!Aw&&(e[t]=()=>{throw new nb({code:ib.INVALID_OPERATION,message:zO.NOT_SUPPORTED_HTTP})})},AP=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(uD(e.selected)&&!e.selected)};function RP(){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 CP(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function bP(){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 kP(){return"captureStream"in HTMLCanvasElement.prototype}function DP(){return!(PN||lN||pw&&pw<63)&&!(!uP()||!kP())}var NP=function(){if(cD(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:vk}),e.addTransceiver(Bb.AUDIO),t=!0}catch(pb){}return null==e||e.close(),t};function wP(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function OP(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function PP(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function MP(){return 11!==vw&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var LP=!(!MP()||dw&&pw<86);function xP(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var VP="RTCRtpSender"in window;function UP(){return VP&&"replaceTrack"in window.RTCRtpSender.prototype}function FP(){return VP&&"setParameters"in window.RTCRtpSender.prototype&&OP()}var BP="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,HP=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,GP=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,WP=VP&&"createEncodedStreams"in window.RTCRtpSender.prototype&&lw()>=86,jP="RTCRtpScriptTransform"in window,KP=VP&&(WP||jP),JP=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function qP(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return cD(window.AudioDecoder)||(e.AudioDecoder=!0),cD(window.AudioEncoder)||(e.AudioEncoder=!0),cD(window.VideoDecoder)||(e.VideoDecoder=!0),cD(window.VideoEncoder)||(e.VideoEncoder=!0),cD(window.ImageDecoder)||(e.ImageDecoder=!0),e}function zP(){return"mediaSession"in navigator&&!cD(navigator.mediaSession.setActionHandler)}function YP(){return!cD(window.WebTransport)}function XP(){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 QP(){let e={browser:"".concat(Cw.name,"/").concat(Cw.version),os:Pw(),displayResolution:RP(),isScreenShareSupported:yP(),isWebRTCSupported:JP(),isGetUserMediaSupported:CP(),isWebAudioSupported:bP(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:qP(),isMediaSessionSupported:zP(),isWebTransportSupported:YP()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var ZP="checkResult";function $P(){_P();let e=Kw.getItem(ZP);e&&e.ua===navigator.userAgent&&(cP=e.checkResult),EP()}function eM(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var tM="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype,iM=BC(KC(),1),rM=Symbol("instance"),nM=Symbol("cacheResult"),sM=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,dM.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},oM=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var aM=new Map;function cM(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,n,s)=>{let o=i.action||n;if(!i.context){let i=aM.get(r)||[];aM.has(r)||aM.set(r,i),i.push({from:e,to:t,action:o})}let a=s.value;s.value=function(){let r=this;for(var n=arguments.length,s=new Array(n),c=0;c<n;c++)s[c]=arguments[c];if(i.context&&(r=uM.get("function"==typeof i.context?i.context.call(this,...s):i.context)),r.state===t)return i.sync?r[nM]:Promise.resolve(r[nM]);r.state instanceof sM&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof sM&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new oM(r._state,"".concat(r.name," ").concat(o," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e.join("|")))):e!==r.state&&(l=new oM(r._state,"".concat(r.name," ").concat(o," 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 sM(u,t,o);dM.call(r,h);let p=e=>{var n;return r[nM]=e,h.aborted||(dM.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[nM])),e},m=e=>(dM.call(r,u,e),d(e));try{let e=a.apply(this,s);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(iO){return m(new oM(r._state,"".concat(r.name," ").concat(o," from ").concat(e," to ").concat(t," failed: ").concat(iO),iO instanceof Error?iO:new Error(String(iO))))}}}}var lM="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 dM(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(uM.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var uM=class e extends iM.default{constructor(t,i,r){super(),this.name=t,this.groupName=i,this._state=e.INIT,t||(t=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),i||(this.groupName=this.constructor.name);let n=r[rM];n?this.name=n.name+"-"+n.count++:r[rM]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=aM.get(e)||[],i=new Set,r=[],n=[],s=new Set,o=Object.getPrototypeOf(e);aM.has(o)&&(o.stateDiagram.forEach((e=>i.add(e))),o.allStates.forEach((e=>s.add(e)))),t.forEach((e=>{let{from:t,to:i,action:s}=e;"string"==typeof t?r.push({from:t,to:i,action:s}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:s})})):n.push({to:i,action:s})})),r.forEach((e=>{let{from:t,to:r,action:n}=e;s.add(t),s.add(r),s.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," 🟢")),s.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:s}}),a}static get(t){let i;return"string"==typeof t?(i=e.instances.get(t),i||e.instances.set(t,i=new e(t,void 0,Object.create(e.prototype)))):(i=e.instances2.get(t),i||e.instances2.set(t,i=new e(t.constructor.name,void 0,Object.create(e.prototype)))),i}static getState(t){var i;return null===(i=e.get(t))||void 0===i?void 0:i.state}updateDevTools(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};lM(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){dM.call(this,e)}};uM.STATECHANGED="stateChanged",uM.UPDATEAFSM="updateAFSM",uM.INIT="[*]",uM.ON="on",uM.OFF="off",uM.instances=new Map,uM.instances2=new WeakMap;var hM="undefined"!=typeof window,pM=hM&&window.requestIdleCallback||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},mM=hM&&window.cancelIdleCallback||function(e){clearTimeout(e)},_M=hM&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),fM=class e{static generateTaskID(){return this.currentTaskID++}static run(e,t,i){null!=i&&i.fps&&(i.delay=i.delay||Number((1e3/i.fps).toFixed(2))),i=xC("interval"===e?{delay:2e3,count:0,backgroundTask:!0}:"ric"===e?{delay:1e4,count:0}:"raf"===e?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i);let r=VC(xC({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i),{delay:i.delay});return this.taskMap.set(r.taskID,r),this[e](r),r.taskID}static interval(t){return t.intervalID=setInterval((()=>{t.callback(),t.loopCount+=1,e.isBreakLoop(t)}),t.delay)}static intervalInWorker(t){e.sharedWorker||(e.sharedWorker=new Worker(URL.createObjectURL(new Blob(["\n const timers = new Map();\n self.onmessage = function(e) {\n const { taskId, delay, type } = e.data;\n if (type === 'start') {\n timers.set(taskId, setInterval(() => {\n self.postMessage({ type: 'tick', taskId });\n }, delay));\n } else if (type === 'stop') {\n clearInterval(timers.get(taskId));\n timers.delete(taskId);\n }\n };\n "],{type:"application/javascript"}))),e.sharedWorker.onmessage=t=>{var i;if("tick"===t.data.type){let r=e.workerTasks.get(t.data.taskId);r&&(r.callback(),r.loopCount+=1,e.isBreakLoop(r)&&(null==(i=e.sharedWorker)||i.postMessage({type:"stop",taskId:r.taskID}),e.workerTasks.delete(r.taskID)))}}),e.workerTasks.set(t.taskID,t),e.sharedWorker.postMessage({taskId:t.taskID,delay:t.delay,type:"start"})}static timeout(t){let i=()=>{if(t.callback(),t.loopCount+=1,!e.isBreakLoop(t))return t.timeoutID=setTimeout(i,t.delay)};return t.timeoutID=setTimeout(i,t.delay)}static ric(t){let i,r=yD(),n=()=>{if(i=yD()-r,i>=t.delay&&(r=yD()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!e.isBreakLoop(t))return t.ricID=pM(n,{timeout:t.delay})};return t.ricID=pM(n,{timeout:t.delay})}static raf(t){let i,r=yD(),n=()=>document.hidden&&t.backgroundTask?(i=yD()-r,r=yD(),t.callback(),t.loopCount+=1,e.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(n,t.delay-Math.floor(i%t.delay))):(i=yD()-r,i>=t.delay&&(r=yD()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),e.isBreakLoop(t)?void 0:t.rafID=requestAnimationFrame(n));if(t.rafID=requestAnimationFrame(n),t.backgroundTask){let e=()=>{if(document.hidden){let e=yD()-r;e>=t.delay?n():t.timeoutID=setTimeout(n,t.delay-e)}};document.addEventListener("visibilitychange",e),t.onVisibilitychange=e,document.hidden&&e()}return t.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:s,worker:o}=this.taskMap.get(e);return o&&o.terminate(),t&&clearInterval(t),i&&clearTimeout(i),r&&_M&&_M(r),n&&mM(n),s&&document.removeEventListener("visibilitychange",s),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)}};GC(fM,"taskMap",new Map),GC(fM,"currentTaskID",1),GC(fM,"sharedWorker",null),GC(fM,"workerTasks",new Map);var gM=fM;Bb.SEI_MESSAGE;var TM={LOADED_DATA:Bb.LOADEDDATA,LOADED_META_DATA:Bb.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},EM={};FC(EM,{create:()=>yM,remove:()=>SM});var vM=new WeakMap;function yM(e,t){vM.has(e)||vM.set(e,[]);let i=vM.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 SM(e){let t=vM.get(e);t&&(t.forEach((e=>e())),vM.delete(e))}var IM=new class{constructor(){GC(this,"_roomIdMap",new Map),GC(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:ub,env:wb.QCLOUD,browserVersion:Cw.name+Cw.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){Aw||!Ww.isAbleToUpload||this._configs.env===wb.QCLOUD&&this.uploadEventToKibana(VC(xC({},e),{result:"success"}))}logFailedEvent(e){if(Aw||!Ww.isAbleToUpload)return;let{eventType:t,code:i,error:r,userId:n}=e,s={roomId:this._roomIdMap.get(n||this._configs.userId),userId:n,eventType:t,result:"failed",code:i||(null==r?void 0:r.extraCode)||(null==r?void 0:r.code)||ib.UNKNOWN};this._configs.env===wb.QCLOUD&&this.uploadEventToKibana(VC(xC({},s),{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:ab(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:ub,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+="\n".concat(r.stack))),this.sendRequest(jk(this._configs.sdkAppId,Nb.LOG),n)}sendRequest(e,t){setTimeout((()=>WD({url:e,body:JSON.stringify(t),priority:"low"}).catch((()=>{}))),2e3)}},AM=new WeakMap;function RM(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,s,o){let a=XD({retryFunction:o.value,settings:t,onError(t){let{error:r,retry:n,reject:o,retryFuncArgs:a}=t;var c;i?i.call(this,r,(()=>{var t;null!=(t=AM.get(e))&&t.has(s)?n():o(r)}),o,a):null!=(c=AM.get(e))&&c.has(s)?n():o(r)},onRetrying(t,i){var n;JD(r)&&r.call(this,t,i),null!=(n=AM.get(e))&&n.has(s)&&(AM.get(e).get(s).stopRetry=i)},onRetryFailed:n});return o.value=function(){let t=AM.get(e);for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return t?t.set(s,{args:r}):AM.set(e,new Map([[s,{args:r}]])),a.apply(this,r).finally((()=>{var t;return null==(t=AM.get(e))?void 0:t.delete(s)}))},o}}function CM(e){let{fnName:t,callback:i,validateArgs:r=!0}=e;return function(e,n,s){let o=s.value;return s.value=function(){for(var n,s,a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(null!=(n=AM.get(e))&&n.has(t)){let{stopRetry:n,args:o}=AM.get(e).get(t),a=!0;if(r)for(let e of o)if(!c.find((t=>t===e))){a=!1;break}a&&(i&&i.apply(this,c),n&&n(),null==(s=AM.get(e))||s.delete(t))}return o.apply(this,c)},s}}var bM=class extends uM{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,GC(this,"id"),GC(this,"element",null),GC(this,"track"),GC(this,"url"),GC(this,"attr"),GC(this,"mode"),GC(this,"muted"),GC(this,"_log"),GC(this,"_pausedRetryCount"),GC(this,"_isElementPlayingFired",!1),GC(this,"_interval"),GC(this,"_delayDestroyTimeoutId",0),GC(this,"_playSuccessResolve"),GC(this,"_isReplayByRecreateMediaStreamCalled",!1),GC(this,"isInAutoPlayFailedState",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Ok,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){var e;return"PLAYING"===this._state&&(!1===(null==(e=this.element)?void 0:e.paused)||this.track&&"live"===this.track.readyState&&!this.track.muted)}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,null!==e&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return jC(this,null,(function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise(((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)}))}catch(pb){let t=QO({key:qO.PLAY_FAILED,data:{media:this.kind,error:pb}});if(this.track&&!this.track.muted&&this._log.warn(pb),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new nb({code:ib.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&&!fw?this._delayDestroyTimeoutId||(this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout((()=>this.destroyElement()),3*e)):this.destroyElement(),this.handleStopped(Bb.ENDED),this._interval>0&&gM.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():Sw?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 yM(this.element,this.element).add(Bb.PLAYING,e).add(Bb.ENDED,e).add(Bb.PAUSE,e).add(Bb.ERROR,e).add(Bb.LOADEDDATA,e).add(Bb.LOADEDMETADATA,e)}}bindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;if(e){let t=this.handleTrackEvent.bind(this);null==EM||EM.create(e,e).add(Bb.ENDED,t).add(Bb.MUTE,t).add(Bb.UNMUTE,t),e.readyState===Bb.ENDED&&this.handleTrackEvent({type:Bb.ENDED}),e.muted&&this.handleTrackEvent({type:Bb.MUTE})}}bindAutoPlayEvent(){Fw.on(Hw.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;e&&SM(e)}unbindEvents(){this.element&&SM(this.element),this.unbindTrackEvents(),Fw.off(Hw.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case Bb.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(Bb.PLAYING),this._interval&&(gM.clearTask(this._interval),this._interval=-1);break;case Bb.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(Bb.ENDED);break;case Bb.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(Bb.PAUSE),lN&&(this._interval=gM.run("timeout",(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case Bb.ERROR:if(this.element&&this.element.error){this.handlePaused(Bb.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)),IM.uploadEvent({log:"stat-".concat(this.kind,"-").concat(fk.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),tw||ew?this.emit(TM.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case Bb.LOADEDDATA:this.kind===Bb.VIDEO&&this.emit(TM.LOADED_DATA);break;case Bb.LOADEDMETADATA:this.kind===Bb.VIDEO&&this.emit(TM.LOADED_META_DATA)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),IM.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),aP.addSuccessEvent({key:this.kind===Bb.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),IM.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),aP.addFailedEvent({key:this.kind===Bb.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(TM.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,i)=>{HD(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)}),HD(5e3).then((()=>{var e,r;(!this.isPlaying||null!=(e=this.element)&&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 Bb.ENDED:this.handleStopped(Bb.ENDED);break;case Bb.MUTE:this.handlePaused(Bb.MUTE);break;case Bb.UNMUTE:this._isElementPlayingFired?this.handlePlaying(Bb.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString())}}handlePlaying(e){var t;null==(t=this._playSuccessResolve)||t.call(this,e),this.emit(TM.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(TM.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(TM.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};HC([RM({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],bM.prototype,"doReplayByRecreateMediaStream",1),HC([cM([],"PLAYING",{sync:!0})],bM.prototype,"handlePlaying",1),HC([cM("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],bM.prototype,"handlePaused",1),HC([cM([],"STOPPED",{sync:!0})],bM.prototype,"handleStopped",1);var kM,DM="trtc_autoplay",NM="".concat(DM,"_mask"),wM="".concat(DM,"_wrapper"),OM="".concat(DM,"_header"),PM="".concat(DM,"_content"),MM="".concat(DM,"_action_wrapper"),LM="".concat(DM,"_question"),xM="".concat(DM,"_collapse"),VM="".concat(DM,"_action_confirm"),UM="".concat(DM,"_detail"),FM="#2473E8",BM="dialog",HM="".concat(BM,"-show"),GM="".concat(BM,"-1"),WM="".concat(BM,"-2"),jM=!1,KM=()=>!!document.querySelector(".".concat(wM)),JM="".concat(Ab,"/").concat(iD()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),qM="<br><a href='".concat(JM,"' target='_blank'>").concat(iD()?"其他方案?":"Any other solution?","</a>"),zM="".concat(iD()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(qM):"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(qM)),YM=class{constructor(){if(GC(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),GC(this,"_dialogNode",null),GC(this,"_bodyPosition",""),GC(this,"_showDetail",!1),GC(this,"_isCollapseClicked",!1),GC(this,"_isQuestionClicked",!1),iD()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!jM){let e=document.createElement("style");e.innerHTML=".".concat(NM,"{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(NM," div:not(.").concat(MM,"){display:block !important;}.").concat(wM,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(wM," a{color:").concat(FM,";}.").concat(OM,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(PM,"{margin:8px 0;}.").concat(MM,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(xM,"{margin-right:auto;cursor:pointer}.").concat(LM,"{height:100%;line-height:16px;cursor:pointer;}.").concat(VM,"{margin-left:8px;color:#fff;background:").concat(FM,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(VM,":hover{opacity:0.9;}.").concat(xM,",.").concat(VM,",.").concat(PM,",.").concat(LM,"{font-size:14px;}@media screen and (max-width:750px){.").concat(wM,"{width:80vw;}}"),document.head.appendChild(e),jM=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(NM,"\"><div class='").concat(wM,"'><div class='").concat(OM,"'>").concat(location.host,"</div><div class='").concat(PM,"'>").concat(this.content,"</div><div class='").concat(UM,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(zM,"</div><div class='").concat(MM,"'></div></div></div>").trim();let t=document.createElement("button");t.className=VM,t.innerText=iD()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=LM,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=xM,r.innerText="".concat(iD()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,s=n.querySelector(".".concat(MM));return s.appendChild(r),s.appendChild(i),s.appendChild(t),n}addDiaLog(){KM()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(wM)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",Ww.info("show autoplay dialog"),IM.uploadEvent({log:HM}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){Ww.warn("confirm clicked, try resume stream"),Fw.emit(Hw.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(UM));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||IM.uploadEvent({log:GM}),this._isCollapseClicked=!0}onQuestionClick(){window.open(JM,"_blank"),this._isQuestionClicked||IM.uploadEvent({log:WM}),this._isQuestionClicked=!0}},XM=class extends bM{constructor(e){super(e,Bb.VIDEO),GC(this,"stat",{}),GC(this,"_calculateTimeout",-1),GC(this,"viewMirror",!1),GC(this,"objectFit"),GC(this,"container"),GC(this,"canvas"),GC(this,"canvasTrack"),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,cD(e.viewMirror)||(this.viewMirror=e.viewMirror),cD(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var e;let t=document.createElement(Bb.VIDEO);this.track&&2!==this.mode&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,(this.track||this.canvasTrack)&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(Bb.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(Bb.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;super.handleTrackEvent(e),e.type===Bb.MUTE&&null!=(t=this.stat)&&t.fps&&(this.stat.fps=0)}handleElementEvent(e){var t;if(2===this.mode)return;super.handleElementEvent(e);let i=e.type;if(i===Bb.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&&!KM()&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let e=this.element.style.transform;i===Bb.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):i===Bb.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}}setCanvas(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;var i,r,n,s;this.canvas!==e&&(null==(i=this.canvas)||i.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,2===this.mode&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?(null==(r=this.element)||r.remove(),null==(n=this.container)||n.appendChild(e)):this.element&&(null==(s=this.container)||s.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(t,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;super.stop(e),null==(t=this.canvas)||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),2===this.mode?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(TM.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element&&2!==this.mode&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(eM()&&this.element&&this._calculateTimeout<0){let e=0,t=null,i=(r,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(r-e)*1e3)),e=r,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout((()=>{var e;return null==(e=this.element)?void 0:e.requestVideoFrameCallback(i)}),2e3))};this.element.requestVideoFrameCallback(i)}}catch(pb){this._log.warn("init stat failed",pb)}}};function QM(e,t){return jC(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),Ww.info("worklet addModule success")}catch(pb){throw Ww.info("worklet addModule catch error. ".concat(pb.message)),pb}}))}"undefined"!=typeof AudioContext?kM=AudioContext:"undefined"!=typeof webkitAudioContext?kM=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(kM=mozAudioContext);var ZM,$M=-1;!function e(){try{if(ZM)return;(ZM=new kM({sampleRate:48e3})).onstatechange=()=>{Ww.info("context state: ".concat(ZM.state).concat("running"!==ZM.state?" visibilityState: ".concat(document.visibilityState):"")),eL()},clearTimeout($M)}catch(tW){Ww.error("initAudioContext failed: ".concat(tW," typeof AudioContextClass: ").concat(typeof kM)),$M=setTimeout(e,1e3)}}();var eL=()=>{"suspended"===ZM.state?(rL(),document.addEventListener("click",eL)):"interrupted"===ZM.state?rL():(document.removeEventListener("visibilitychange",eL),document.removeEventListener("click",eL))},tL=0,iL=-1;function rL(){return new Promise(((e,t)=>{if("running"===ZM.state)return e();Date.now()-tL<1e3?(clearTimeout(iL),iL=setTimeout((()=>{tL=Date.now(),ZM.resume().then(e,t)}),1e3)):(clearTimeout(iL),tL=Date.now(),ZM.resume().then(e,t))})).catch((e=>{Ww.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",eL)}))}document.addEventListener("click",eL);var nL=e=>ZM,sL=class{constructor(){GC(this,"node"),GC(this,"node2"),GC(this,"pre",new Set),GC(this,"next",new Set),GC(this,"context"),GC(this,"connectedNodes",new Set)}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&(null==(e=this.context)||e.reduceMixWeight()),delete this.context}replaceNode(e){var t;if(e!==this.node)try{this.node?this._disconnect():null==(t=this.context)||t.addMixWeight(),this.node=e,this.preNodeReconnect(),this.reconnect()}catch(mk){Ww.error(mk)}}setNode(e,t){var i;if(!this.node)try{null==(i=this.context)||i.addMixWeight(),this.node=e,t&&(this.node2=t),this.preNodeReconnect(),this.reconnect(),aP.addSuccessEvent({key:502701})}catch(Zw){Ww.error(Zw),aP.addFailedEvent({key:502701,error:Zw})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),aP.addSuccessEvent({key:502702})}catch(pb){Ww.error(pb),aP.addFailedEvent({key:502702,error:pb})}}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.node2||this.node).connect(e),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach((e=>{var t;return null==(t=this.node2||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}},oL=class extends sL{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,GC(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}},aL=class{constructor(){GC(this,"source",new sL),GC(this,"gain",new sL),GC(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(nL().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.replaceNode(uL(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}},cL=class extends aL{constructor(e){super(),this.context=e,GC(this,"denoiser",new sL),GC(this,"voiceChanger",new sL),this.source.pipeTo(this.denoiser.pipeTo(this.voiceChanger.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.voiceChanger.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.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.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()}},lL=class{constructor(){GC(this,"audioContext",nL()),GC(this,"destination",this.audioContext.createMediaStreamDestination()),GC(this,"inputs",new Set),GC(this,"mixWeight",0),this.destination.channelCount=1}addMixWeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.mixWeight+=e,this.mixWeight-1==e+1>>1&&this.mixOnChange()}reduceMixWeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.addMixWeight(-e)}close(){this.inputs.forEach((e=>e.remove()))}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},dL=new WeakMap;function uL(e){let t=dL.get(e);if(t)return t;let i=nL();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return dL.set(e,t),t}var hL=class e{constructor(e){GC(this,"_volume",0),GC(this,"_volumeDb",0),GC(this,"_log"),GC(this,"_scriptProcessorNode",null),GC(this,"_audioWorkletNode",null),GC(this,"_interval",200),GC(this,"ready",this.preload());let{log:t}=e;this._log=t,Fw.on(Hw.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-e.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!e.workletReady){let t='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';e.workletReady=QM(e.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return e.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(e.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=i=>{e.lastMessageTime=Date.now(),this._volume=i.data.volume||0,this._volumeDb=i.data.volumeDb||0,!t&&i.data.cacheLen&&i.data.outputLen&&(this._log.warn("worklet play success"),t=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(Qw){this._log.error("volumeMeter init audio worklet error: ".concat(Qw)),IM.logFailedEvent({userId:this._log.userId,eventType:fk.LOAD_WORKLET,error:Qw}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=nL("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{e.lastMessageTime=Date.now();let i=t.inputBuffer.getChannelData(0),r=0;for(let e=0;e<i.length;++e)r+=i[e]*i[e];this._volume=Math.sqrt(r/i.length)||0}}catch(Qw){this._log.error("volumeMeter init script processor error: ".concat(Qw))}}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,Fw.off(Hw.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(100*this._volumeDb)}handleAudioLevelInterval(e){var t;let{interval:i}=e;this._interval=i,null==(t=this._audioWorkletNode)||t.port.postMessage({name:"setIntervalTime",intervalTime:i})}};GC(hL,"lastMessageTime",0),GC(hL,"audioContext",nL()),GC(hL,"workletReady");var pL=hL,mL=class extends sL{constructor(e){super(),GC(this,"_volumeMeter"),this._volumeMeter=new pL(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return jC(this,null,(function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)}))}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}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()}}},_L=pL,fL=BC(KC(),1),gL=e=>t=>t.deviceId===e,TL=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";GC(this,"kind"),GC(this,"type"),GC(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&&yL(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(gL(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");Ww.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(gL(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");Ww.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 fL.EventEmitter{constructor(){super(),GC(this,"audioInputs",new TL(Bb.AUDIO)),GC(this,"videoInputs",new TL(Bb.VIDEO)),GC(this,"audioOutputs",new TL(Bb.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||gM.run("interval",(()=>{this.update()}),{delay:1e4}))}init(){SL().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return jC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield SL(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},vL=fb||_b?null:new EL;function yL(e){return e.deviceId===e.groupId&&""===e.groupId}function SL(){return jC(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(_P()||!pP())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{yL(e)&&(e.kind===Bb.AUDIO_INPUT?i.audio=!0:e.kind===Bb.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),i.audio&&rL()}catch(Zw){Ww.debug("capture before getDevices failed: ",Zw)}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&&bL.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function IL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return vL.update(e?1:0).then((e=>e.audioInputs.devices))}function AL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return vL.update(e?2:0).then((e=>e.videoInputs.devices))}var RL=!1;function CL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return jC(this,null,(function*(){return(lN||_w)&&(e=!1),vL.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var bL=new Set;function kL(e,t){return jC(this,null,(function*(){let i=(yield IL()).find((e=>e.deviceId===Pk));return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t}))}var DL,NL=class extends aL{constructor(e){super(),this.log=e,GC(this,"volumeMeter"),GC(this,"volumeDestination"),GC(this,"analyser",new oL),this.volumeMeter=new mL({log:this.log}),this.volumeDestination=new sL,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},wL=class e extends bM{constructor(e){super(e,Bb.AUDIO),GC(this,"_outputDeviceId"),GC(this,"_volume",1),GC(this,"_destination",nL().createMediaStreamDestination()),GC(this,"pipeline"),GC(this,"volumeMeterMode","worklet"),this.mode=0,this.pipeline=new NL(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(("15.2"===Ew||"15.3"===Ew||"15.4"===Ew)&&this.muted)return void this._log.info("audioElement is muted.");let t=DL||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,dD(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),t===DL&&(DL=void 0),this.bindElementEvents()}play(t){return jC(this,null,(function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(null==t?void 0:t.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(nL().createAnalyser()),function(){jC(this,null,(function*(){try{RL||(RL=!0,Ww.info("speakers:".concat((yield CL()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(e){}}))}(),WC(e.prototype,this,"play").call(this)}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy(),super.stop(e)}setSinkId(e){return jC(this,null,(function*(){var t,i;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield null==(i=(t=this.element).setSinkId)?void 0:i.call(t,e))}))}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},OL=class extends wL{setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(TM.MEDIA_TRACK_CHANGED,e),e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]))))}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}},PL=class extends wL{constructor(e){super(e),GC(this,"_sourceElement"),GC(this,"_output",new sL),this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(nL().destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,i;(null==(i=null==(t=this.element)?void 0:t.error)?void 0:i.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(TM.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?this.element?(this._log.info("set element volume: ".concat(e)),this.element.volume=e):this._log.info("set element volume: no element"):lN||(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),SM(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&fw&&(DL=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},ML=class extends uM{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:s=(1===r?PL:XM)}=e;var o;super(),GC(this,"id",jw()),GC(this,"userId",""),GC(this,"isRemote"),GC(this,"mediaType"),GC(this,"room"),GC(this,"user"),GC(this,"_log"),GC(this,"_inputTrack"),GC(this,"_outputTrack"),GC(this,"isPlayCalled"),GC(this,"container",null),GC(this,"player"),GC(this,"subVideoPlayerMap"),GC(this,"muted",!1),GC(this,"abortCtrl"),GC(this,"objectFit","cover"),GC(this,"mirror"),GC(this,"isScreen",!1),GC(this,"manager"),GC(this,"trackSettings"),GC(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=Ww.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(o=n||this.room)?void 0:o.userId,remoteUserId:this instanceof ix?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof ix}),this.player=new s({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(TM.PLAYER_STATE_CHANGED,(e=>{Fw.emit(Hw.PLAYER_STATE_CHANGED,xC({track:this},e)),this.emit("player-state-changed",e)})),this.kind===Bb.VIDEO&&(this.player.on(TM.LOADED_DATA,(()=>{this.emitFirstVideoFrameEvent(TM.LOADED_DATA),Fw.emit(Hw.VIDEO_LOADED_DATA,{track:this})})),this.player.on(TM.LOADED_META_DATA,(()=>{this.emitFirstVideoFrameEvent(TM.LOADED_META_DATA)})),this.player.on(TM.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(TM.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||Ww}get kind(){return 1===this.mediaType?Bb.AUDIO:Bb.VIDEO}get strMediaType(){return 4===this.mediaType?Bb.VIDEO:2===this.mediaType?Bb.SCREEN:Bb.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&(!this.mediaTrack.muted&&"live"===this.mediaTrack.readyState&&this.mediaTrack.enabled)}play(e,t){return jC(this,null,(function*(){let i=pD(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!cD(t.muted)&&this.setPlayerMute(t.muted),t&&!cD(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof XM&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),pD(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!cD(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===Bb.VIDEO)&&this.setPlayerMute(!0),t&&!cD(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof XM&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof XM&&this.player.setContainer(i)),Fw.emit(Hw.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),pD(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(tO){throw this.handleAutoPlayFailed(tO),tO}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==Bb.VIDEO||cD(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(uD(this.mirror))return i.setViewMirror(this.mirror),void(r&&(r.mirror=!1));switch(this.mirror){case"view":r&&(r.mirror=!1),i.setViewMirror(!0);break;case"publish":r&&(r.mirror=!0),i.setViewMirror(!0);break;case"both":r&&(r.mirror=!0),i.setViewMirror(!1)}}playSubContainer(e,t){return jC(this,null,(function*(){if(!this._outputTrack||this.kind===Bb.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&&(cD(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new XM({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(zD(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return jC(this,null,(function*(){var e;this.isPlayCalled&&(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),Fw.emit(e?Hw.TRACK_MUTED:Hw.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){yM(e,e).add(Bb.MUTE,this.onTrackMuted).add(Bb.UNMUTE,this.onTrackUnmuted).add(Bb.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Bb.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){SM(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((e=>this.handleAutoPlayFailed(e))),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(zD(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(e){if(this.room&&this.room.enableAutoPlayDialog)new YM;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof XM?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var t,i,r;if(this.isFirstVideoFrameEmitted)return;let n=null==(t=this.mediaTrack)?void 0:t.getSettings(),s=(null==n?void 0:n.width)||(null==(i=this.player.element)?void 0:i.videoWidth)||0,o=(null==n?void 0:n.height)||(null==(r=this.player.element)?void 0:r.videoHeight)||0;e===TM.LOADED_META_DATA&&!s&&!o||(e===TM.LOADED_DATA&&!s&&!o&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,this.emit("first-video-frame",{width:s,height:o,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}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"))}};HC([cM([],uM.INIT,{sync:!0})],ML.prototype,"close",1);var LL=Object.prototype.hasOwnProperty;var xL=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(rD(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(LL.call(e,t))return!1;return!0}return!1},VL=XD({retryFunction:function(e){return jC(this,null,(function*(){let t=function(e){return{audio:FL(e),video:BL(e)}}(e);Ww.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId","groupId"];t.audio&&(i=yield IL(),Ww.info("microphones: ".concat(MD(i.map((e=>VC(xC({},e),{groupId:e.groupId.substring(0,8)}))),{keysToInclude:n})))),t.video&&(r=yield AL(),Ww.info("cameras: ".concat(MD(r,{keysToInclude:n}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return GP&&e.getTracks().forEach((e=>{Ww.info("".concat(e.kind," capabilities: ").concat(MD(e.getCapabilities(),{keysToInclude:Bk})))})),t.audio&&rL(),e}catch(tO){let{message:n}=tO;throw"NotFoundError"===tO.name&&(e.video&&r&&0===r.length&&(n=QO({key:qO.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(n=QO({key:qO.MICROPHONE_NOT_FOUND}))),new nb({code:ib.INITIALIZE_FAILED,name:tO.name,message:n,constraint:tO.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,retryFuncArgs:n,retriedCount:s}=e,o=s+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===o?(n[0].video&&(n[0].maxResolution=!1,(!_w||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===o?n[0].useDeviceIdOnly=!0:3===o&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&UL(n[0].microphoneId,!1),n[0].cameraId&&UL(n[0].cameraId,!0)},onRetrying:e=>{Ww.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{IM.logFailedEvent({eventType:fk.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{IM.logSuccessEvent({eventType:fk.GET_USER_MEDIA_RETRY}),IM.uploadEvent({log:"stat-".concat(fk.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function UL(e,t){return jC(this,null,(function*(){let i=(t?yield AL():yield IL()).find((t=>t.deviceId===e));i&&aD(i.getCapabilities)&&Ww.warn(MD(i.getCapabilities(),{keysToInclude:Bk}))}))}function FL(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!xL(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(dD(e.channelCount)&&(t.channelCount=e.channelCount),uD(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),uD(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),uD(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!xL(t)||t)}function BL(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&&!xL(i)?i:(e.width&&(i.width={ideal:e.width},t&&!mN&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!mN&&(i.height.max=e.height)),mN&&KN&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!xL(i)||i)}var HL=VL;function GL(e){return KL(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return jC(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function WL(e){return KL(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return jC(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function jL(e){return KL(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return jC(this,null,(function*(){try{return yield t.apply(this,r)}catch(Zw){e.call(this,Zw)}}))}))}function KL(e){return function(t,i,r){return r.value=e(r.value,i),r}}var JL=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&Ww.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{Ww.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),qL=0,zL=class{constructor(){GC(this,"log",Ww.createLogger({id:"fq".concat(++qL)})),GC(this,"isRunning",!1),GC(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=xC({},e),s=new Promise(((e,t)=>{n.resolve=e,n.reject=t}));return n.promise=s,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(),s}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()}))}},YL=new WeakMap,XL=new WeakMap;function QL(){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=YL.get(this)||new zL;for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];return YL.set(this,t),t.push({fn:n,args:r,context:this},e)},r}}function ZL(e){return function(t,i,r){let n=r.value;return r.value=function(){var t,i,r;let s=[];for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];return null==(i=null==(t=YL.get(this))?void 0:t.queue)||i.forEach((e=>s.push(e))),null==(r=XL.get(this))||r.forEach((e=>null==e?void 0:e.queue.forEach((e=>s.push(e))))),s.forEach((t=>{t.reject(new nb({code:ib.API_CALL_ABORTED,message:e}))})),YL.delete(this),XL.delete(this),n.apply(this,a)},r}}function $L(e){return function(t,i,r){let n=r.value,s=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=XL.get(this)||new Map,o=r.get(s(t))||new zL;return r.set(s(t),o),XL.set(this,r),o.push({fn:n,args:t,context:this})},r}}function ex(e,t){return KL(((i,r)=>function(){let r=e;try{for(var n=arguments.length,s=new Array(n),o=0;o<n;o++)s[o]=arguments[o];let e=i.apply(this,s),a=yD();return fD(e)?e.then((e=>(t?aP.addSuccessEvent({key:r,cost:yD()-a}):aP.addSuccessEvent({key:r}),e))).catch((e=>{throw aP.addFailedEvent({key:r,error:e}),e})):(aP.addSuccessEvent({key:r}),e)}catch(mb){throw aP.addFailedEvent({key:r,error:mb}),mb}}))}var tx=class e extends ML{constructor(e,t){super({mediaType:e,PlayerClass:t}),GC(this,"isRemote",!1),GC(this,"deviceId"),GC(this,"groupId",""),GC(this,"label",""),GC(this,"_isRecapturing",!1),GC(this,"_lastRecaptureTime",0),GC(this,"_onMuteTimeoutId",-1),GC(this,"_encodeCheckTimeoutId",-1),GC(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){yM(e,e).add(Bb.MUTE,this.onTrackMuted).add(Bb.UNMUTE,this.onTrackUnmuted).add(Bb.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Bb.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){SM(e)}setStateToCapture(){}capture(e){return jC(this,null,(function*(){var t;try{let i,r=yD();Fw.emit(Hw.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield HL(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),Fw.emit(Hw.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:yD()-r}),i}catch(Zw){throw Fw.emit(Hw.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:Zw}),this.log.error("getUserMedia error observed ".concat(Zw)),Zw}}))}setInputMediaStreamTrack(e){return this.state===uM.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),Fw.emit(Hw.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return jC(this,null,(function*(){if(this.mediaTrack&&HP){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return jC(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:s}=e;return function*(){return t===i&&(s!==Bb.AUDIO||t!==Pk||(yield kL(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),SL().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===Bb.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(Bb.AUDIO_INPUT);return!!bL.has(i)}(this.mediaTrack)||this.kind===Bb.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(Bb.VIDEO_INPUT);return!!bL.has(i)}(this.mediaTrack)||this._isRecapturing||e&&KN&&_w)}onTrackMuted(){if(super.onTrackMuted(),JL(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Fk)return void setTimeout((()=>this.onTrackMuted()),Fk);this._onMuteTimeoutId=setTimeout((()=>jC(this,null,(function*(){var e;if(null!=(e=this.mediaTrack)&&e.muted){if((lN||dN)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return jC(this,null,(function*(){if(WC(e.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Fk)return void setTimeout((()=>this.onTrackEnded()),Fk);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return jC(this,null,(function*(){var t;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),null==(t=this._inputTrack)||t.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let i={useExactDeviceId:!0};if("user"===e||"environment"===e)i.facingMode=e;else{let t;("audio"===this.kind?yield IL():yield AL()).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}),Fw.emit(Hw.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),Fw.emit(Hw.LOCAL_TRACK_RECAPTURE,{track:this,error:e})}))}))}getRecoverCaptureDeviceId(){return jC(this,null,(function*(){let e=this instanceof cx;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(rx.get(t)||0)+1;if(rx.set(t,i),i>=3){let r=e?(yield AL()).find((e=>!rx.has(e.deviceId))):(yield IL()).find((e=>!rx.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)}};HC([cM(uM.INIT,"capture",{ignoreError:!0,sync:!0})],tx.prototype,"setStateToCapture",1),HC([QL()],tx.prototype,"capture",1),HC([cM("capture","publish",{ignoreError:!0,success(){var e,t;this.room.localTracks.add(this),Fw.emit(Hw.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===Bb.AUDIO,t=this.stat.bytesSent>0;aP[t?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),t||(aP.addEnum({key:e?503701:513703,value:Mw()}),IM.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(ww()||Lw()),userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}}),5e3))},fail(e){let t="error";if(e.cause instanceof RTCError){let i=e.cause;i.message.includes("timeout")?t="timeout":i.code===ib.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),ex(521714,!1)],tx.prototype,"publish",1),HC([KL((e=>function(){return jC(this,null,(function*(){let t="publish"===this.state?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)}))})),cM([],"capture",{sync:!0})],tx.prototype,"unpublish",1);var ix=tx,rx=new Map;Fw.on(Hw.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&rx.delete(e.track.deviceId)}));var nx=class e extends ix{constructor(e){super(1,OL),GC(this,"mediaType",1),GC(this,"volume",0),GC(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),GC(this,"playerMuted",!0),GC(this,"pipeline"),GC(this,"earMonitorGainNode",new sL),GC(this,"_output",new sL),GC(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),this.manager=e,this.pipeline=new cL(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode.pipeTo(this._output),this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return _L.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(t){return jC(this,null,(function*(){let i=this.trackSettings||{};aP.addEnum({key:501701,value:i.channelCount||0,useUV:!1}),aP.addEnum({key:501702,value:i.sampleRate||0,useUV:!1}),aP.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:n}=i;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:r,channelCount:n}))),this.pipeline.replaceSource(t),yield WC(e.prototype,this,"setInputMediaStreamTrack").call(this,t),this.updatePlayingState(!!t)}))}capture(e){let{deviceId:t,customSource:i,useExactDeviceId:r=!0,retryWhenExactFailed:n=!0}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:n,customSource:i})}switchDevice(e){return jC(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==Pk)return;if(yield kL(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}),Fw.emit(Hw.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(mk){throw this.log.error("switch microphone failed ".concat(mk)),this.deviceId&&this.recapture(this.deviceId),mk}}}))}listenDeviceChange(){vL&&!vL.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&vL.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return jC(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e))),eF(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield IL();t[0]?this.recapture(t[0].deviceId):vL.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return jC(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:n}=e;return function*(){let e=!1;!cD(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!cD(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,e=!0),!cD(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&&aP.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(nL().createGain()),this._output.setNode(nL().destination)),this.earMonitorGainNode.node.gain.value=e}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;pw<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(aP.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1))}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}close(){this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),vL.off("audioInputAdded",this.handleMicrophoneAdded,this),vL.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(t){return jC(this,null,(function*(){try{yield WC(e.prototype,this,"recapture").call(this,t)}catch(mk){let r=(yield IL()).find((e=>e.deviceId!==t));if(!r)throw mk;yield WC(e.prototype,this,"recapture").call(this,r.deviceId)}}))}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight(((e,t)=>t?t({frame:e}):e),e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}},sx=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 s=e;s<=t;s++){let e=this.dataView.getInt8(s);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 s=e;s<=t;s++)switch(this.dataView.getInt8(s)){case 0:r++,i.push(this.dataView.getInt8(s));break;case 3:2!==r&&i.push(this.dataView.getInt8(s)),r=0;break;default:i.push(this.dataView.getInt8(s)),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}},ox=class{constructor(){GC(this,"_seiMessageList",[]),GC(this,"_smallSeiMessageList",[]),GC(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 o=0;o<i;o++)n.push(255);n.push(r);let s=new DataView(e);return n.push(...new Uint8Array(s.buffer)),n.push(128),new sx(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)}isEmpty(){return!this._seiMessageList.length}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),s=new ArrayBuffer(n+e.data.byteLength),o=new DataView(s),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++)o.setInt8(c++,r[e].dataView.getInt8(t));for(let i=0;i<e.data.byteLength;i++)o.setInt8(c++,a.getInt8(i));return e.data=s,r.length}return 0}},ax=class e extends ix{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,XM),GC(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),GC(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0}),GC(this,"small"),GC(this,"isNeedToSetBandwidth"),GC(this,"muteImage"),GC(this,"manager"),GC(this,"_seiCodec",new ox),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(VC(xC({},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(HP&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}setMute(t){return jC(this,null,(function*(){var i,r,n;if(lD(t)){if(this.muteImage===t)return;yield null==(i=this.manager)?void 0:i.deleteWatermark("mute"),yield null==(r=this.manager)?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:t}),this.muteImage=t,WC(e.prototype,this,"setMute").call(this,!1)}else yield null==(n=this.manager)?void 0:n.deleteWatermark("mute"),this.muteImage=void 0,WC(e.prototype,this,"setMute").call(this,t)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:r=!0,customSource:n,retryWhenExactFailed:s=!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:s,customSource:n})}setProfile(e){let t=xC({},e),i=t.width>t.height;t.width*t.height<=19200&&dN&&dw&&(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&&Iw&&(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(VC(xC({},this.profile),{width:1920,height:1080})))}applyProfile(){return jC(this,null,(function*(){var e;if(!this.mediaTrack)return;let t=this.settings;return(t.height!==this.profile.height||t.width!==this.profile.width||t.frameRate!==this.profile.frameRate)&&this.deviceId&&(16===vw?yield this.recapture(this.deviceId):(yield null==(e=this.mediaTrack)?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)?(this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:Bb.VIDEO,videoType:Bb.BIG})):void 0}))}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return HP&&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:VD()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||1===(null==(t=this.room.scheduleResult.trtcAutoConf)?void 0:t["2k4k"])}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return jC(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),Fw.emit(Hw.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(mk){throw this.log.error("switch camera failed ".concat(mk)),this.deviceId&&this.recapture(this.deviceId),mk}}))}listenDeviceChange(){vL&&!vL.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&vL.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return jC(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e))),eF(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield AL();t[0]?this.recapture(t[0].deviceId):vL.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return jC(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}encodeFrame(e,t){if(!this.manager)return e;let i=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight(((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 cD(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){vL.off("videoInputAdded",this.handleCameraAdded,this),vL.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return jC(this,null,(function*(){try{yield WC(e.prototype,this,"recapture").call(this,t)}catch(mk){let r=(yield AL()).find((e=>e.deviceId!==t));if(!r)throw mk;yield WC(e.prototype,this,"recapture").call(this,r.deviceId)}}))}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info("setContentHint ".concat(e)),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}};HC([WL((function(e){this.setContentHint(e.contentHint||"motion")}))],ax.prototype,"capture",1);var cx=ax,lx=jw();if("undefined"!=typeof navigator&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:lx,exposeOrigin:!0,permittedOrigins:["*"]})}catch(tW){}var dx=function(e){return jC(this,null,(function*(){let t=null,i=function(e){let t={preferCurrentTab:"current-tab"===e.preferDisplaySurface||!!e.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:_w?{max:e.width}:{ideal:e.width,max:e.width},height:_w?{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);Ww.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(uw&&pw<74||_w||mN)&&Ww.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(tO){Ww.warn("screen applyConstraints failed: ".concat(tO))}e.captureElement&&(yield function(e,t){return jC(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&aD(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==lx)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){Ww.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 cD(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);Ww.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},ux=class extends cx{constructor(e){super(e,2),GC(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),GC(this,"objectFit","contain"),GC(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return jC(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:r,echoCancellation:n,noiseSuppression:s,audioTrack:o,videoTrack:a,captureElement:c,preferDisplaySurface:l}=e;return function*(){try{let e;return a||o?(e=new MediaStream,a&&e.addTrack(a),o&&e.addTrack(o)):e=yield dx({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:r,echoCancellation:n,noiseSuppression:s,captureElement:c,preferDisplaySurface:l}),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(zw){throw t.log.error("getDisplayMedia error observed ".concat(zw)),zw instanceof nb?zw:new nb({code:ib.INITIALIZE_FAILED,name:zw.name,message:zw.message})}}()}))}switchDevice(e){return jC(this,null,(function*(){throw new Error("Method not implemented.")}))}};HC([WL((function(e){this.setContentHint(e.contentHint||"detail")}))],ux.prototype,"capture",1);var hx,px=class extends nx{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}},mx="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});";function _x(e){return jC(this,null,(function*(){let t=nL();hx||(hx=QM(t,URL.createObjectURL(new Blob([mx],{type:"application/javascript"})))),yield hx;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 lL{constructor(e){super(),this.room=e,GC(this,"_localAudioTrack"),GC(this,"_localScreenAudioTrack"),GC(this,"log",Ww.createLogger({id:"am"})),GC(this,"denoiser"),GC(this,"voiceChanger"),GC(this,"mixChangedDebounce"),GC(this,"encodePipeline",[]),GC(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 s=new AbortController,o=[],a=setTimeout((()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")}),1e3*e),c=()=>{for(let e=0;e<n.length;e++){let t=URL.createObjectURL(new Blob(o[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),s.abort("download")},l=_x(r).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>o[t]=o[t]?o[t].concat(e[0]):[e[0]]))}}),s).catch((e=>c))));return{then:l.then.bind(l),download:c}}getPCM(e){var t;if(cD(WritableStream))return void this.log.warn("getPCM failed: browser not support WritableStream");if(null==(t=this._localAudioPipline)||!t.source.node)return void this.log.warn("getPCM failed: no local audio track");this.log.warn("getPCM");let i=new Float32Array(1920),r=0,n=new AbortController;return _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.warn("stop getPCM reason:".concat(e)))))),n}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return!cD(this._localAudioTrack)}changeInput(e){return e instanceof px?(this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange()):e instanceof nx?(this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange()):e instanceof PU?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 px?delete this._localScreenAudioTrack:e instanceof nx&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,null==(t=this._localAudioTrack)||t.removeDenoiser(e)}addVoiceChanger(e,t){var i;this.voiceChanger=[e,t],null==(i=this._localAudioTrack)||i.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,null==(e=this._localAudioTrack)||e.pipeline.voiceChanger.deleteNode()}destroy(){this.close()}addEncodeProcessor(e){let{processor:t,type:i}=e;var r;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:i}=e;var r;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}};function 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 KL(((i,r)=>function(){for(var n=arguments.length,s=new Array(n),o=0;o<n;o++)s[o]=arguments[o];return new Promise(((n,o)=>{let a=setTimeout((()=>{let i=new nb({code:ib.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});Ww.warn(i),2===t?o(i):1===t&&n()}),1e3*e);i.apply(this,s).then(n,o).finally((()=>{clearTimeout(a)}))}))}))}var Tx={};function Ex(){}FC(Tx,{Events:()=>Mx,Inspect:()=>Rx,LastSink:()=>Cx,Sink:()=>bx,Subscribe:()=>kx,TimeoutError:()=>Lx,audit:()=>FV,bindCallback:()=>mV,bindNodeCallback:()=>_V,buffer:()=>zx,bufferCount:()=>qx,bufferTime:()=>SU,call:()=>vx,catchError:()=>AU,combineLatest:()=>Wx,concat:()=>Bx,concatMap:()=>dU,concatMapTo:()=>uU,count:()=>yV,create:()=>Nx,debounce:()=>GV,debounceTime:()=>WV,defer:()=>Qx,delay:()=>IU,deliver:()=>wx,dispose:()=>Sx,elementAt:()=>jV,empty:()=>TV,every:()=>YV,exhaustMap:()=>TU,exhaustMapTo:()=>EU,filter:()=>RV,find:()=>KV,findIndex:()=>JV,first:()=>qV,fromAnimationFrame:()=>hV,fromArray:()=>tV,fromEvent:()=>oV,fromEventPattern:()=>sV,fromFetch:()=>cV,fromIterable:()=>lV,fromPromise:()=>aV,fromReadableStream:()=>uV,fromReader:()=>dV,groupBy:()=>vU,identity:()=>yx,ignoreElements:()=>CV,iif:()=>Gx,inspect:()=>Ix,interval:()=>iV,last:()=>zV,map:()=>$V,mapTo:()=>eU,max:()=>SV,merge:()=>Ux,mergeMap:()=>mU,mergeMapTo:()=>_U,min:()=>IV,never:()=>fV,nothing:()=>Ex,of:()=>eV,pairwise:()=>QV,pipe:()=>Dx,race:()=>Fx,range:()=>pV,reduce:()=>vV,retry:()=>NU,scan:()=>XV,share:()=>Vx,shareReplay:()=>Hx,skip:()=>wV,skipUntil:()=>OV,skipWhile:()=>PV,startWith:()=>Kx,subject:()=>Xx,subscribe:()=>bU,sum:()=>AV,switchMap:()=>sU,switchMapTo:()=>aU,take:()=>bV,takeLast:()=>NV,takeUntil:()=>kV,takeWhile:()=>DV,tap:()=>kU,throttle:()=>VV,throwError:()=>gV,timeInterval:()=>yU,timeout:()=>DU,timer:()=>rV,toPromise:()=>RU,toReadableStream:()=>CU,withLatestFrom:()=>Jx,zip:()=>jx});var vx=e=>e(),yx=e=>e;function Sx(){this.dispose()}var Ix=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,Ax=1,Rx=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new Px(e,this,this.streamId++);return Mx.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},Cx=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=Ex,this.error=Ex,this.next=Ex,this.dispose=Ex,this.subscribe=Ex,this.doDefer()}subscribe(e){return e instanceof Rx?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(vx),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}},bx=class extends Cx{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)}},kx=class extends Cx{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ex,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Ex,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Ex;if(super(),this._next=t,this._error=i,this._complete=r,this.then=Ex,e instanceof Rx){let n={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{Mx.defer(n,0)})),Mx.create(n),Mx.pipe(n),this.sourceId=n.id,this.subscribe(e),Mx.subscribe({id:n.id,end:!0}),t==Ex?this._next=e=>Mx.next(n,0,e):this.next=e=>{Mx.next(n,0,e),t(e)},r==Ex?this._complete=()=>Mx.complete(n,0):this.complete=()=>{this.dispose(),Mx.complete(n,0),r()},i==Ex?this._error=e=>Mx.complete(n,0,e):this.error=e=>{this.dispose(),Mx.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 Dx(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 Nx(e,t,i){if(Ix()){let r=Object.defineProperties(Object.setPrototypeOf(e,Rx.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}});Mx.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof Rx&&Mx.addSource(r,t)}return r}return e}function wx(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 Rx){let n=Nx((t=>{let s=new e(t,...r);s.sourceId=n.id,s.subscribe(i)}),t,arguments);return n.source=i,Mx.pipe(n),n}return t=>i(new e(t,...r))}}}function Ox(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var Px=class extends bx{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{Mx.defer(this.source,this.id)}))}next(e){Mx.next(this.source,this.id,e),this.sink.next(e)}complete(){Mx.complete(this.source,this.id),this.sink.complete()}error(e){Mx.complete(this.source,this.id,e),this.sink.error(e)}},Mx={addSource(e,t){Ox("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){Ox("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;Ox("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){Ox("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){Ox("defer",{id:e.id,streamId:t})},pipe(e){Ox("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){Ox("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=Ax++),Ox("create",{name:e.toString(),id:e.id})}},Lx=class extends Error{constructor(e){super("timeout after ".concat(e,"ms")),this.timeout=e}},xx=class extends Cx{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 Vx(){return e=>{let t=new xx(e);if(e instanceof Rx){let i=Nx((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,Mx.pipe(i),i}return Nx(t.add.bind(t),"share",arguments)}}function Ux(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Nx((e=>{let i=new bx(e),r=t.length;i.complete=()=>{0==--r&&e.complete()},t.forEach(i.bindSubscribe)}),"merge",arguments)}function Fx(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Nx((e=>{let i=new Map;t.forEach((t=>{let r=new bx(e);i.set(t,r),r.complete=()=>{i.delete(t),0===i.size?e.complete():r.dispose()},r.next=e=>{i.delete(t),i.forEach((e=>e.dispose())),r.resetNext(),r.resetComplete(),r.next(e)}})),t.forEach((e=>i.get(e).subscribe(e)))}),"race",arguments)}function Bx(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Nx((e=>{let i=0,r=t.length,n=new bx(e);n.complete=()=>{i<r&&!n.disposed?(n.doDefer(),n.subscribe(t[i++])):e.complete()},n.complete()}),"concat",arguments)}function Hx(e){return t=>{let i=new xx(t),r=[];return i.next=function(t){r.push(t),r.length>e&&r.shift(),this.sinks.forEach((e=>e.next(t)))},Nx((e=>{e.defer((()=>i.remove(e))),r.forEach((t=>e.next(t))),i.add(e)}),"shareReplay",arguments)}}function Gx(e,t,i){return Nx((r=>e()?t(r):i(r)),"iif",arguments)}function Wx(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Nx((e=>{let i=t.length,r=i,n=i,s=new Array(i),o=()=>{0==--n&&e.complete()};t.forEach(((t,i)=>{let n=new bx(e);n.next=t=>{0==--r?(n.next=t=>{s[i]=t,e.next(s)},n.next(t)):s[i]=t},n.complete=o,n.subscribe(t)}))}),"combineLatest",arguments)}function jx(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Nx((e=>{let i=t.length,r=i,n=new Array(i),s=()=>{0==--r&&e.complete()};t.forEach(((t,i)=>{let r=new bx(e),o=[];n[i]=o,r.next=t=>{o.push(t),n.every((e=>e.length))&&e.next(n.map((e=>e.shift())))},r.complete=s,r.subscribe(t)}))}),"zip",arguments)}function Kx(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>Nx((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)}var Jx=wx(class extends bx{constructor(e){super(e);let t=new bx(this.sink);for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];t.next=e=>this.buffer=e,t.complete=Ex,t.subscribe(Wx(...r))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},"withLatestFrom"),qx=wx(class extends bx{constructor(e,t,i){super(e),this.bufferSize=t,this.startBufferEvery=i,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(e){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach((t=>{t.push(e)})),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(e),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach((e=>this.sink.next(e))),super.complete()}},"bufferCount"),zx=wx(class extends bx{constructor(e,t){super(e),this.buffer=[];let i=new bx(e);i.next=t=>{e.next(this.buffer),this.buffer=[]},i.complete=Ex,i.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),Yx=function(e,t,i,r){return new(i||(i=Promise))((function(n,s){function o(e){try{c(r.next(e))}catch(zw){s(zw)}}function a(e){try{c(r.throw(e))}catch(zw){s(zw)}}function c(e){e.done?n(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(o,a)}c((r=r.apply(e,t||[])).next())}))};function Xx(e){let t=arguments,i=Vx()(Nx((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=Ex,i.complete=Ex,i.error=Ex,i}function Qx(e){return Nx((t=>t.subscribe(e())),"defer",arguments)}var Zx=e=>t=>{setTimeout((()=>e(t)))},$x=e=>Zx((t=>{for(let i=0;!t.disposed&&i<e.length;i++)t.next(e[i]);t.complete()}));function eV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Nx($x(t),"of",arguments)}function tV(e){return Nx($x(e),"fromArray",arguments)}function iV(e){return Nx((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}function rV(e,t){return Nx((i=>{let r=0,n=setTimeout((()=>{if(i.removeDefer(s),i.next(r++),t){let e=setInterval((()=>i.next(r++)),t);i.defer((()=>{clearInterval(e)}))}else i.complete()}),e),s=()=>{clearTimeout(n)};i.defer(s)}),"timer",arguments)}function nV(e,t){return i=>{let r=e=>i.next(e);i.defer((()=>t(r))),e(r)}}function sV(e,t){return Nx(nV(e,t),"fromEventPattern",arguments)}function oV(e,t){if("on"in e&&"off"in e)return Nx(nV((i=>e.on(t,i)),(i=>e.off(t,i))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return Nx(nV((i=>e.addListener(t,i)),(i=>e.removeListener(t,i))),"fromEvent",arguments);if("addEventListener"in e)return Nx(nV((i=>e.addEventListener(t,i)),(i=>e.removeEventListener(t,i))),"fromEvent",arguments);throw"target is not a EventDispachter"}function aV(e){return Nx((t=>{e.then(t.next.bind(t),t.error.bind(t))}),"fromPromise",arguments)}function cV(e,t){return Nx(Qx((()=>aV(fetch(e,t)))),"fromFetch",arguments)}function lV(e){return Nx(Zx((t=>{try{for(let i of e){if(t.disposed)return;t.next(i)}t.complete()}catch(pb){t.error(pb)}})),"fromIterable",arguments)}function dV(e){let t=i=>Yx(this,void 0,void 0,(function*(){if(i.disposed)return;let{done:r,value:n}=yield e.read();r?i.complete():(i.next(n),t(i))}));return Nx((e=>{t(e)}),"fromReader",arguments)}function uV(e){return Nx((t=>{let i=new AbortController,r=i.signal;t.defer((()=>i.abort("cancelled"))),e.pipeTo(new WritableStream({write(e){t.next(e)},close(){t.complete()},abort(e){t.error(e)}}),{signal:r}).then((()=>t.complete()),(e=>t.error(e)))}),"fromReadableStream",arguments)}function hV(){return Nx((e=>{let t=requestAnimationFrame((function i(r){e.disposed||(e.next(r),t=requestAnimationFrame(i))}));e.defer((()=>cancelAnimationFrame(t)))}),"fromAnimationFrame",arguments)}function pV(e,t){return Nx((function(i){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t+e;for(;r<n&&!i.disposed;)i.next(r++);return i.complete(),"range"}),"range",arguments)}function mV(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return Nx((i=>{let n=r.concat((e=>(i.next(e),i.complete())));e.apply(t,n)}),"bindCallback",arguments)}function _V(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return Nx((i=>{let n=r.concat(((e,t)=>e?i.error(e):(i.next(t),i.complete())));e.apply(t,n)}),"bindNodeCallback",arguments)}function fV(){return Nx((()=>{}),"never",arguments)}function gV(e){return Nx((t=>t.error(e)),"throwError",arguments)}function TV(){return Nx((e=>e.complete()),"empty",arguments)}var EV=class extends bx{constructor(e,t,i){super(e),this.f=t;let r=()=>{this.sink.next(this.acc),this.sink.complete()};void 0===i?this.next=e=>{this.acc=e,this.complete=r,this.resetNext()}:(this.acc=i,this.complete=r)}next(e){this.acc=this.f(this.acc,e)}},vV=wx(EV,"reduce"),yV=e=>wx(EV,"count")(((t,i)=>e(i)?t+1:t),0),SV=()=>wx(EV,"max")(Math.max),IV=()=>wx(EV,"min")(Math.min),AV=()=>wx(EV,"sum")(((e,t)=>e+t),0),RV=wx(class extends bx{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"),CV=wx(class extends bx{next(e){}},"ignoreElements"),bV=wx(class extends bx{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&this.complete()}},"take"),kV=wx(class extends bx{constructor(e,t){super(e);let i=new bx(e);i.next=()=>e.complete(),i.complete=Sx,i.subscribe(t)}},"takeUntil"),DV=wx(class extends bx{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):this.complete()}},"takeWhile"),NV=e=>vV(((t,i)=>(t.push(i),t.length>e&&t.shift(),t)),[]),wV=wx(class extends bx{constructor(e,t){super(e),this.count=t}next(e){0==--this.count&&(this.next=super.next)}},"skip"),OV=wx(class extends bx{constructor(e,t){super(e),e.next=Ex;let i=new bx(e);i.next=()=>{i.dispose(),e.resetNext()},i.complete=Sx,i.subscribe(t)}},"skipUntil"),PV=wx(class extends bx{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),MV={leading:!0,trailing:!1},LV=class extends bx{constructor(e,t,i){super(e),this.durationSelector=t,this.trailing=i}cacheValue(e){this.last=e,this.disposed&&this.throttle(e)}send(e){this.sink.next(e),this.throttle(e)}throttle(e){this.reset(),this.subscribe(this.durationSelector(e))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},xV=class extends bx{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:MV;super(e),this.durationSelector=t,this.config=i,this._throttle=new LV(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(e){this._throttle.disposed&&this.config.leading?this._throttle.send(e):this._throttle.cacheValue(e)}complete(){this._throttle.throttle=Ex,this._throttle.complete(),super.complete()}},VV=wx(xV,"throttle"),UV={leading:!1,trailing:!0},FV=e=>wx(xV,"audit")(e,UV),BV=class extends bx{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},HV=class extends bx{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new BV(this.sink),this._debounce.dispose()}next(e){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=e,this._debounce.subscribe(this.durationSelector(e))}complete(){this._debounce.complete(),super.complete()}},GV=wx(HV,"debounce"),WV=e=>wx(HV,"debounceTime")((t=>rV(e))),jV=wx(class extends bx{constructor(e,t,i){super(e),this.count=t,this.defaultValue=i}next(e){0==this.count--&&(this.defaultValue=e,this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("not enough elements in sequence"))}},"elementAt"),KV=e=>t=>bV(1)(PV((t=>!e(t)))(t)),JV=wx(class extends bx{constructor(e,t){super(e),this.f=t,this.i=0}next(e){this.f(e)?(this.sink.next(this.i++),this.complete()):++this.i}},"findIndex"),qV=wx(class extends bx{constructor(e,t,i){super(e),this.f=t,this.defaultValue=i,this.index=0}next(e){(!this.f||this.f(e,this.index++))&&(this.defaultValue=e,this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"first"),zV=wx(class extends bx{constructor(e,t,i){super(e),this.f=t,this.defaultValue=i,this.index=0}next(e){(!this.f||this.f(e,this.index++))&&(this.defaultValue=e)}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"last"),YV=wx(class extends bx{constructor(e,t){super(e),this.predicate=t,this.index=0}next(e){this.predicate(e,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){void 0!==this.result?(this.sink.next(this.result),super.complete()):this.error(new Error("no elements in sequence"))}},"every"),XV=wx(class extends bx{constructor(e,t,i){super(e),this.f=t,void 0===i?this.next=e=>{this.acc=e,this.resetNext(),this.sink.next(this.acc)}:this.acc=i}next(e){this.sink.next(this.acc=this.f(this.acc,e))}},"scan"),QV=wx(class extends bx{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},"pairwise"),ZV=class extends bx{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},$V=wx(ZV,"map"),eU=e=>wx(ZV,"mapTo")((t=>e)),tU=class extends bx{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()}},iU=class extends bx{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()}},rU=class extends tU{},nU=class extends iU{next(e){this.subInner(e,rU),this.next=e=>{this.currentSink.dispose(),this.subInner(e,rU)}}},sU=wx(nU,"switchMap");function oU(e){return(t,i)=>e((()=>t),i)}var aU=oU(wx(nU,"switchMapTo")),cU=class extends tU{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},lU=class extends iU{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(e){this.next2(e),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),cU),this.disposed&&0===this.sources.length&&this.currentSink.resetComplete()}tryComplete(){0===this.sources.length&&this.currentSink.resetComplete(),this.dispose()}},dU=wx(lU,"concatMap"),uU=oU(wx(lU,"concatMapTo")),hU=class extends tU{tryComplete(){this.context.inners.delete(this),super.dispose(),0===this.context.inners.size&&this.context.resetComplete()}},pU=class extends iU{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,hU),this.inners.add(this.currentSink)}tryComplete(){1===this.inners.size?this.inners.forEach((e=>e.resetComplete())):this.dispose()}},mU=wx(pU,"mergeMap"),_U=oU(wx(pU,"mergeMapTo")),fU=class extends tU{dispose(){this.context.resetNext(),super.dispose()}},gU=class extends iU{next(e){this.next=Ex,this.subInner(e,fU)}},TU=wx(gU,"exhaustMap"),EU=oU(wx(gU,"exhaustMapTo")),vU=wx(class extends bx{constructor(e,t){super(e),this.f=t,this.groups=new Map}next(e){let t=this.f(e),i=this.groups.get(t);void 0===i&&(i=Xx(),i.key=t,this.groups.set(t,i),super.next(i)),i.next(e)}complete(){this.groups.forEach((e=>e.complete())),super.complete()}error(e){this.groups.forEach((t=>t.error(e))),super.error(e)}},"groupBy"),yU=wx(class extends bx{constructor(){super(...arguments),this.start=new Date}next(e){this.sink.next({value:e,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},"timeInterval"),SU=wx(class extends bx{constructor(e,t){super(e),this.miniseconds=t,this.buffer=[],this.id=setInterval((()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0}),this.miniseconds)}next(e){this.buffer.push(e)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},"bufferTime"),IU=wx(class extends bx{constructor(e,t){super(e),this.buffer=[],this.delayTime=t}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(e){this.timeoutId=setTimeout((()=>{let e=this.buffer.shift();if(e){let{time:t,data:i}=e;super.next(i),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}}),e)}next(e){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:e})}complete(){this.timeoutId=setTimeout((()=>super.complete()),this.delayTime)}},"delay"),AU=wx(class extends bx{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),RU=()=>e=>new Promise(((t,i)=>{let r;new kx(e,(e=>r=e),i,(()=>t(r)))})),CU=()=>e=>{let t;return new ReadableStream({start(i){t=new kx(e,i.enqueue.bind(i),i.error.bind(i),i.close.bind(i))},cancel(){t.dispose()}})},bU=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Ex,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ex,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Ex;return r=>new kx(r,e,t,i)},kU=wx(class extends bx{constructor(e,t){super(e),t instanceof Function?this.next=i=>{t(i),e.next(i)}:(t.next&&(this.next=i=>{t.next(i),e.next(i)}),t.complete&&(this.complete=()=>{t.complete(),e.complete()}),t.error&&(this.error=i=>{t.error(i),e.error(i)}))}},"tap"),DU=wx(class extends bx{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout((()=>this.error(new Lx(this.timeout))),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),NU=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0;return t=>{if(t instanceof Rx){let i=Nx((r=>{let n=e,s=new bx(r);s.error=e=>{n-- >0?s.subscribe(t):r.error(e)},s.sourceId=i.id,s.subscribe(t)}),"retry",[e]);return i.source=t,Mx.pipe(i),i}return i=>{let r=e,n=new bx(i);n.error=e=>{r-- >0?t(n):i.error(e)},t(n)}}},wU=class e extends ML{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,GC(this,"tinyId"),GC(this,"isRemote",!0),GC(this,"jitterBufferDelay",0),GC(this,"availableState"),GC(this,"remotePublishState"),GC(this,"_decodeCheckTimeoutId",-1),this.tinyId=t.tinyId,this.availableState=new uM("".concat(t.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new uM("".concat(t.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),Dx(Ux(oV(this,uM.STATECHANGED),oV(this.remotePublishState,uM.STATECHANGED)),$V((()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing))),bU((e=>{this.availableState.state!==(e?uM.ON:uM.OFF)&&(this.availableState.state=e?uM.ON:uM.OFF),this.updatePlayingState(e)})))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&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===e.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===uM.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){let i=this.kind===Bb.AUDIO;aP[e?"addSuccessEvent":"addFailedEvent"]({key:i?504700:514702}),e||(aP.addEnum({key:i?504701:514703,value:Mw()}),IM.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(ww()||Lw()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===Bb.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," isAvailable: ").concat(this.isRemotePublished," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?uM.ON:uM.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};GC(wU,"STATE_SUBSCRIBE","subscribe"),HC([gx(5,1)],wU.prototype,"waitHasMediaTrack",1),HC([cM(uM.INIT,wU.STATE_SUBSCRIBE,{success(){var e,t;this.log.info("subscribed"),Fw.emit(Hw.REMOTE_TRACK_SUBSCRIBED,{track:this}),!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&(this._decodeCheckTimeoutId=setTimeout((()=>{var e,t;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let e=this.kind===Bb.AUDIO,t=this.player.isPlaying||(e?this.getAudioLevel()>0:this.stat.framesDecoded>0);this.reportDecodeResult(t)}}),5e3),this.player.once(TM.ERROR,(e=>{e.code===MediaError.MEDIA_ERR_DECODE&&(clearTimeout(this._decodeCheckTimeoutId),this.reportDecodeResult(!1,3))})))},ignoreError:!0}),ex(521716,!1)],wU.prototype,"subscribe",1),HC([cM(wU.STATE_SUBSCRIBE,uM.INIT,{sync:!0,success(){this.log.info("unsubscribed"),Fw.emit(Hw.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],wU.prototype,"unsubscribe",1);var OU=wU,PU=class extends OU{constructor(e,t){super(e,t,1),GC(this,"volume",0),GC(this,"mediaType",1),GC(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}get dbVolume(){return _L.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let t=e;for(let i of this.manager.decodePipeline)if(i&&(t=i({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}},MU=[-1,-1,1,-1,-1,1,1,1],LU=[0,0,1,0,0,1,1,1],xU=class extends uM{constructor(e,t){if(super(),this.context=e,GC(this,"name"),GC(this,"input"),GC(this,"output"),GC(this,"texture"),GC(this,"ctx2d",null),GC(this,"fbo"),GC(this,"width",0),GC(this,"height",0),GC(this,"x",0),GC(this,"y",0),GC(this,"program"),GC(this,"vertexShader"),GC(this,"fragmentShader"),GC(this,"totalFrames",0),GC(this,"dropFrames",0),GC(this,"matchInputSize",!0),GC(this,"texCoordBuffer"),GC(this,"positionBuffer"),GC(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),GC(this,"cost",0),GC(this,"_canvas",null),GC(this,"_image"),GC(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 XU)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==vw?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);else try{let i=e.ctx;this.texCoordBuffer=this.createBuffer(LU),this.positionBuffer=this.createBuffer(MU),!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(Zw){this.context.destroy(new nb({code:ib.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(Zw.message||Zw)}))}}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 YU&&this.render(e)||this.context instanceof XU&&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(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;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 YU){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),"undefined"!=typeof VideoFrame&&e instanceof VideoFrame&&e.close()),!0)}getInfo(){var e;let{totalFrames:t,x:i,y:r,width:n,height:s,name:o,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:s,timestamp:c,fps:l,name:o,cost:a},xC({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}};HC([cM(uM.INIT,"connected",{sync:!0})],xU.prototype,"connect",1),HC([cM("connected",uM.INIT,{ignoreError:!0,sync:!0})],xU.prototype,"disconnect",1),HC([cM([],"closed",{sync:!0})],xU.prototype,"close",1);var VU=Dx(iV(250),$V((()=>performance.now())),Vx()),UU=[0,1,1,1,0,0,1,0],FU=class extends xU{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),GC(this,"_intervalId",0),GC(this,"_sequence",0),GC(this,"checkGLError",!1),GC(this,"checkVisibilityChange"),e instanceof XU?this.ctx2d=e.ctx||null:e.available&&null!=t&&t.mirrorUpAndDown&&this.setTexBuffer(UU)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),gM.clearTask(this._intervalId),this._intervalId=gM.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(gM.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof YU){let e=this.context.ctx.getError();e&&this.context.destroy(new nb({code:ib.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(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(this._intervalId&&(gM.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),gM.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),gM.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},BU=class extends FU{constructor(e,t){super(e,t),GC(this,"_videoTrack"),GC(this,"_muteOb"),GC(this,"_closedOb",oV(this,"closed")),GC(this,"_subscription"),GC(this,"_canvasContainer"),Number(gw)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=oV(this._videoTrack,"mute"),Dx(oV(this._videoTrack,"ended"),kV(this._closedOb),bU((()=>{this.context.destroy(new nb({code:ib.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){var e;this._subscription=Dx(this._muteOb,kV(this._closedOb),aU((e=5e3,t=>{let i=performance.now();Dx(VU,PV((t=>t-i<e)),bV(1))(t)})),bU((()=>{var e;null!=(e=this._videoTrack)&&e.muted&&this.context.destroy(new nb({code:ib.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()}},HU=class extends BU{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},GU=class extends BU{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))}},WU=class extends xU{constructor(e,t){super(e,xC({name:"imageSource"},t)),GC(this,"_lastImage"),GC(this,"_totalFrames",0),GC(this,"_autoResize",!1),GC(this,"_canvasRendered"),GC(this,"_videoCallbackId",0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===vw&&(this._canvasRendered=Xx(),Dx(this._canvasRendered,Kx(this._image),sU((e=>e instanceof HTMLCanvasElement?oV(e,"rendered"):TV())),kV(oV(this,"closed")),bU((()=>{this.update()}))))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),eM()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback(((e,t)=>{document.hidden||(this._totalFrames=t.presentedFrames,this.update(1))})))}_render(e,t){var i;let{width:r,height:n}=this,{image:s}=this;if(s instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(s),({videoWidth:r,videoHeight:n}=s),!r||!n)return!1;s.width=r,s.height=n}else if(s instanceof HTMLImageElement||s instanceof ImageData||s instanceof ImageBitmap){if(({width:r,height:n}=s),s!==this._lastImage)this._lastImage=s;else if(r===this.width&&n===this.height)return!1}else s instanceof HTMLCanvasElement||s instanceof OffscreenCanvas?(({width:r,height:n}=s),this._lastImage=s):"undefined"!=typeof VideoFrame&&s instanceof VideoFrame&&(({displayWidth:r,displayHeight:n}=s),null==(i=this._lastImage)||i.close(),this._lastImage=s);if(!this._autoResize)return!0;if(this.width===r&&this.height===n&&this.totalFrames){if(t){this.useTexture();let e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,s)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,s)}this.resize(r,n)}return!0}get image(){return this._image}set image(e){var t;null==(t=this._canvasRendered)||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},jU=class extends WU{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",Dx(oV(this._player,TM.PLAYER_STATE_CHANGED),kV(oV(this,"closed")),RV((e=>{let{state:t}=e;return"PLAYING"===t})),bU((()=>{this.tryVideoFrameCallback(this._player.element)})))}get image(){return this._player.element}},KU=class extends jU{constructor(e,t,i){super(e,new XM({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()}},JU=class extends uM{constructor(e){super(),GC(this,"frameRate"),GC(this,"_canvas"),GC(this,"log"),GC(this,"hasAlpha",!1),GC(this,"name"),GC(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 KU(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new BU(this,e)}createVideoImageSource(e,t){return new WU(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new jU(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};GC(JU,"_ids",0);var qU={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},zU=class extends JU{constructor(){super(...arguments),GC(this,"defaultProgam"),GC(this,"defaultVShader"),GC(this,"defaultFShader"),GC(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(JU._ids++)),this.ctx=this._canvas.getContext("webgl2",qU),!this.ctx)throw new nb({code:ib.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 nb({code:ib.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,aP.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}};GC(zU,"UNAVAILABLE","unavailable"),HC([cM(uM.INIT,"created",{sync:!0,fail(e){aP.addFailedEvent({key:512700,error:e.cause||e})},success(){aP.addSuccessEvent({key:512700})}})],zU.prototype,"create",1),HC([cM("created",uM.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(zU.UNAVAILABLE,e),this.removeAllListeners()}})],zU.prototype,"destroy",1);var YU=zU,XU=class extends JU{constructor(){super(...arguments),GC(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(JU._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new nb({code:ib.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,aP.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(),aP.addSuccessEvent({key:512703})}};HC([cM(uM.INIT,"created",{sync:!0,fail(e){aP.addFailedEvent({key:512701,error:e.cause||e})},success(){aP.addSuccessEvent({key:512701})}})],XU.prototype,"create",1),HC([cM("created",uM.INIT,{ignoreError:!0,sync:!0})],XU.prototype,"destroy",1);var QU=class extends OU{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),GC(this,"mediaType",4),GC(this,"source"),GC(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager,this.once("first-video-frame",(e=>{this.room.emit("first-video-frame",e)}))}play(e,t){return(uD(null==t?void 0:t.canvasRender)?t.canvasRender:17===vw)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then((()=>{this.player.calculateStat()}))}useCanvasPlayer(){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let e=new XU({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new FU(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),eM()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,i=(r=t,[15,30,45,60].reduce(((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)));var r;!dD(t)||t<=0?this.log.debug("updateCanvasPlayerFPS() ignore decoder: ".concat(t," ")):i!==e.frameRate?(this.log.info("updateCanvasPlayerFPS() decoder: ".concat(t,", closest: ").concat(i,", current: ").concat(e.frameRate)),e.frameRate=i):this.log.debug("updateCanvasPlayerFPS() ignore ClosestFPS ".concat(i," == ").concat(e.frameRate))}get decodeFPS(){var e;let{msg_video_status:t}=(null==(e=this.room.heartbeatReport)?void 0:e.msg_down_stream_info.find((e=>e.msg_user_info.str_identifier===this.userId)))||{},i=2===this.mediaType?7:this.isSmall?3:2;if(!t||0===t.length)return 0;let r=t.find((e=>e.uint32_video_stream_type===i));return(null==r?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&!(e=t({frame:e,track:this})))return;return e}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},ZU=class extends QU{constructor(e,t){super(e,t,2),GC(this,"mediaType",2),GC(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},$U=new Map;function eF(e,t){let i=VC(xC({},t),{timestamp:ob()});$U.has(e)?$U.get(e).push(i):$U.set(e,[i])}Fw.on(Hw.JOIN_SUCCESS,(e=>{let{room:t}=e;eF(t.userId,{eventId:32788})})),Fw.on(Hw.LEAVE_START,(e=>{let{room:t}=e;eF(t.userId,{eventId:32789})})),Fw.on(Hw.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),eF(t.room.userId,{eventId:e})}})),Fw.on(Hw.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),eF(t.room.userId,{eventId:e})}})),Fw.on(Hw.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Bb.AUDIO?eF(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):eF(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),Fw.on(Hw.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Bb.AUDIO?eF(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):eF(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),Fw.on(Hw.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&eF(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&eF(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&eF(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),Fw.on(Hw.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&eF(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&eF(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&eF(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),Fw.on(Hw.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&eF(t.room.userId,{eventId:t.kind===Bb.VIDEO?32780:32781})})),Fw.on(Hw.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&eF(t.room.userId,{eventId:t.kind===Bb.VIDEO?32782:32783})})),Fw.on(Hw.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&&eF(i.userId,{eventId:t})})),Fw.on(Hw.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:n,remoteUserId:s}=e,o=!!s;switch(n){case"CONNECTED":t="RECONNECTING"===r?o?32801:32798:o?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===r&&(t=o?32802:32799);break;case"RECONNECTING":t=o?32800:32797}t&&eF(i.userId,{eventId:t,remoteUserId:s})})),Fw.on(Hw.VIDEO_CODEC_IMPLEMENTATION_CHANGED,(e=>{let{implementation:t,userId:i,remoteUserId:r,codec:n,isHWCodec:s,prevImplementation:o,streamType:a}=e,c=s?1:0;o||(c=s?3:2);let l="h264"===n?0:2,d={eventId:4004,param1:c,param2:l,streamType:a||2};r&&(d.remoteUserId=r,d.eventId=4005),eF(i,d),aP.addEnum({key:r?514701:513701,value:c}),aP.addEnum({key:r?514700:513700,value:l})})),Fw.on(Hw.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===Bb.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),eF(t.userId,e)}}));var tF=BC(KC(),1),iF=class extends tF.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,GC(this,"userMap",new Map),GC(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 s={userId:i,tinyId:r,role:20===n?"anchor":"audience"};this.userMap.set(t,s),this.emit("1",s)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let r="peer leave [".concat(e,"]");cD(t)||(r+=":".concat(Vk[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:s}=e,o=CD(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:o,flag:r}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(o))),this.addUser({userId:n,tinyId:s,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:CD(0,n),muteState:o,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function rF(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return KL(((e,n)=>{let s=new WeakMap;return Fw.on(Hw.ROOM_DESTROY,(e=>{let{room:t}=e;return s.delete(t)})),function(){let o=s.get(this);for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(o||(o={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,o)),0===o.timestamp?o.timestamp=Date.now():Date.now()-o.timestamp>1e3&&(o.timestamp=Date.now(),o.callCountInSecond=0,o.totalSizeInSecond=0),r&&(o.totalSizeInSecond+=r(...c)),0!==o.timestamp&&Date.now()-o.timestamp<1e3&&(o.callCountInSecond>=t||o.totalSizeInSecond>i))throw new nb({code:ib.INVALID_OPERATION,message:QO({key:qO.CALL_FREQUENCY_LIMIT,data:{isTimes:o.callCountInSecond>=t,isSize:o.totalSizeInSecond>i,name:n,timesInSecond:t,maxSizeInSecond:i}})});o.callCountInSecond++,e.call(this,...c)}}))}var nF,sF=!0,oF={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",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"},aF={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},cF=((nF=cF||{})[nF.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",nF[nF.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",nF[nF.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",nF[nF.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",nF[nF.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",nF[nF.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",nF[nF.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",nF[nF.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",nF[nF.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",nF[nF.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",nF[nF.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",nF[nF.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",nF[nF.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",nF[nF.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",nF[nF.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",nF[nF.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",nF[nF.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",nF[nF.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",nF[nF.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",nF[nF.INVALID_OPERATION=5100]="INVALID_OPERATION",nF[nF.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",nF[nF.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",nF[nF.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",nF[nF.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",nF[nF.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",nF[nF.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",nF[nF.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",nF[nF.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",nF[nF.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",nF[nF.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",nF[nF.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",nF[nF.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",nF[nF.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",nF[nF.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",nF[nF.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",nF[nF.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",nF[nF.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",nF[nF.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",nF[nF.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",nF[nF.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",nF[nF.DEVICE_ERROR=5300]="DEVICE_ERROR",nF[nF.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",nF[nF.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",nF[nF.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",nF[nF.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",nF[nF.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",nF[nF.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",nF[nF.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",nF[nF.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",nF[nF.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",nF[nF.SERVER_ERROR=5400]="SERVER_ERROR",nF[nF.NEED_TO_BUY=5401]="NEED_TO_BUY",nF[nF.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",nF[nF.OPERATION_FAILED=5500]="OPERATION_FAILED",nF[nF.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",nF[nF.REJOIN_FAILED=5502]="REJOIN_FAILED",nF[nF.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",nF[nF.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",nF[nF.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",nF[nF.OPERATION_ABORT=5998]="OPERATION_ABORT",nF[nF.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",nF);var lF=VC(xC({},zO),{INVALID_PARAMETER(e){let{fnName:t}=e;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName: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,s="".concat(t||i.name),o="";return o=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(s,"' must be type of ").concat(o," when calling ").concat(r,"(), received type: ").concat(oD(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,s="".concat(t||i.name),o="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(s,"' must be instanceof ").concat(o," when calling ").concat(r,"(), received type: ").concat(oD(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: '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=dF(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=dF(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=dF(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=dF(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=dF(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=dF(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=dF(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 dF(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var uF=class e extends Error{constructor(e){let{code:t,extraCode:i,message:r="",messageParams:n,fnName:s="",originError:o}=e;var a;let c;c=r||function(e){let t,{code:i,params:r,enableDocLink:n=!1}=e,o="",a=cF[i];try{t=lF[a]}catch(s){t=lF.UNKNOWN_ERROR}return aD(t)?o=t(r):lD(t)&&(o=t),r.fnName&&!o.includes(r.fnName)&&("."!==o[o.length-1]&&(o+="."),o+=" thrown from ".concat(r.fnName,"()")),n&&(o+=" doc:"),o}({code:t===aF.SERVER_ERROR?t:i||t,params:xC({fnName:s,error:o},n)}),super(c),GC(this,"name","RtcError"),GC(this,"code"),GC(this,"extraCode"),GC(this,"functionName"),GC(this,"message"),GC(this,"handler"),GC(this,"originError"),this.name=cF[t],this.code=t,this.extraCode=i,this.functionName=s,this.originError=o,this.message=c,5302===this.extraCode&&null!=(a=this.originError)&&a.message.includes("system")&&(this.handler=()=>{let e=document.createElement("a");jN?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):KN&&(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(t,i,r){let n=t;if(t instanceof nb){let{stack:s}=t,o={code:aF.UNKNOWN_ERROR,fnName:i,originError:t};switch(t.getCode()){case ib.INVALID_PARAMETER:o.code=aF.INVALID_PARAMETER,o.message=t.message;break;case ib.INVALID_OPERATION:o.code=aF.INVALID_OPERATION;break;case ib.NOT_SUPPORTED:case ib.NOT_SUPPORTED_H264:o.code=aF.ENV_NOT_SUPPORTED,t.getCode()===ib.NOT_SUPPORTED_H264&&(o.extraCode=t.message.includes(zO.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case ib.JOIN_ROOM_FAILED:o.messageParams={fnParams:r};case ib.SERVER_TIMEOUT:case ib.SWITCH_ROLE_FAILED:o.code=aF.SERVER_ERROR,o.extraCode=t.getExtraCode();break;case ib.API_CALL_ABORTED:o.code=aF.OPERATION_ABORT;break;case ib.DEVICE_NOT_FOUND:case ib.DEVICE_AUTO_RECOVER_FAILED:case ib.INITIALIZE_FAILED:o.code=5300,t.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}(t.name));break;case ib.UNKNOWN:break;default:o.code=aF.OPERATION_FAILED}n=new e(o),s&&(n.stack+=s.substr(s.indexOf("\n")))}else{if(t instanceof e)return t;n=new e({code:aF.UNKNOWN_ERROR,fnName:i,originError:t})}return n}};var hF=uF,pF={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}}},mF={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}}},_F={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(lD(e)&&!document.getElementById(e))throw new hF({code:aF.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},fF={name:"userId",required:!0,type:"string"},gF={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[oF.AUDIO_PROFILE_STANDARD,oF.AUDIO_PROFILE_STANDARD_STEREO,oF.AUDIO_PROFILE_HIGH,oF.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function TF(e,t){if(!e)throw new hF({code:aF.INVALID_OPERATION,extraCode:5101,fnName:t})}function EF(e,t,i){if(!e)throw new hF({code:aF.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var vF={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 hF({code:aF.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(lD(e.roomId))throw new hF({code:aF.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new hF({code:aF.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new hF({code:aF.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new hF({code:aF.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:_F,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:pF},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&_P())throw new hF({code:aF.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:VC(xC({},_F),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:pF}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:gF},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&_P())throw new hF({code:aF.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:gF}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:_F,publish:{type:"boolean"},option:mF},validate(e,t,i,r,n){var s;if((null==(s=null==e?void 0:e.option)||!s.videoTrack)&&_P())throw new hF({code:aF.ENV_NOT_SUPPORTED,extraCode:5201});if(!yP())throw new hF({code:aF.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:_F,publish:{type:"boolean"},option:mF}},muteRemoteAudio:[fF,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[fF,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:_F,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){TF(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(EF(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new hF({code:aF.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:VC(xC({},_F),{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){TF(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(EF(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new hF({code:aF.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&&cD(e.streamType))throw new hF({code:aF.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){TF(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(!KP)throw new hF({code:aF.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new hF({code:aF.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new hF({code:aF.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new hF({code:aF.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});TF(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 hF({code:aF.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 hF({code:aF.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new hF({code:aF.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(TF(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new hF({code:aF.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}}},yF={TRTC:vF},SF=class extends Error{};function IF(e,t){let i=ND(e);for(let r=0;r<t.length;r++)DD(i[r],t[r]);return i}function AF(e){this._resolve=Promise.resolve(e)}function RF(e){this._reject=Promise.reject(e)}var CF=class e{constructor(t,i){this.instance=t,this.group=i,GC(this,"started",!1),GC(this,"ops",[]),GC(this,"startSame",(()=>!0)),GC(this,"mergeUpdate",IF);let r=e.instances.get(t);r?r.set(i,this):e.instances.set(t,new Map([[i,this]]))}static get(t,i){if(!i)return;let r=e.instances.get(t);return r&&r.get(i)||new e(t,i)}static gets(t,i){let r=e.instances.get(t),n=[];return r&&r.forEach(((e,t)=>{i.test(t)&&n.push(e)})),n}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 SF("start failed")),null==(r=this.currentOp)||r.action(),t},s={type:e,action:()=>t(...s.args).then(r,n),args:i,resolve:AF,reject:RF};try{switch(this.state){case 1:if(0===e)throw new SF("already started");break;case 4:if(2===e)throw new SF("not started");break;default:return this.cacheOp(s)}}catch($w){return Promise.reject($w)}return this.ops.push(s),s.promise=t(...s.args).then(r,n)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new SF("already start");break;case 3:switch(e.type){case 2:throw new SF("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new SF("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new SF("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 SF("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new SF("start not allowed after update");case 0:throw new SF("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new SF("keep start")),new SF("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}};GC(CF,"instances",new WeakMap);var bF=CF,kF=new WeakMap,DF=(e,t)=>{if(t instanceof SF){let{stack:i}=t;t=new hF({code:aF.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function NF(e,t){return KL(((i,r)=>function(){for(var n=arguments.length,s=new Array(n),o=0;o<n;o++)s[o]=arguments[o];let a=bF.get(this,"string"==typeof e?e:e.call(this,...s));return a?(t&&(a.startSame=t.bind(this)),a.action(0,i.bind(this),s).catch(DF.bind(null,r))):i.apply(this,s)}))}function wF(e,t){let{merge:i,debounce:r}=t||{};return KL(((t,n)=>function(){for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];let c=bF.get(this,"string"==typeof e?e:e.call(this,...o));if(!c)return t.apply(this,o);if(i&&(c.mergeUpdate=i.bind(this)),r&&r.isNeedToDebounce.apply(this,o)){let{delay:e,getKey:i}=r;return new Promise(((r,s)=>{var a,l;let d=null==(a=kF.get(this))?void 0:a.get(i(...o));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),o).catch(DF.bind(null,n)).then(r,s)}),e);kF.has(this)?null==(l=kF.get(this))||l.set(i(...o),{timeoutId:u,resolve:r}):kF.set(this,new Map([[i(...o),{timeoutId:u,resolve:r}]]))}))}return c.action(2,t.bind(this),o).catch(DF.bind(null,n))}))}function OF(e){return KL(((t,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];let o="function"==typeof e?e.call(this,...n):e;if(o instanceof RegExp)return Promise.all(bF.gets(this,o).map((e=>e.action(3,(()=>Promise.resolve()),n)))).then((()=>t.call(this,...n)));let a=bF.get(this,o);return a?a.action(3,t.bind(this),n).catch(DF.bind(null,i)):t.apply(this,n)}))}var PF={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame"},MF=new Set([PF.ERROR,PF.AUTOPLAY_FAILED,PF.KICKED_OUT,PF.REMOTE_USER_ENTER,PF.REMOTE_USER_EXIT,PF.REMOTE_AUDIO_AVAILABLE,PF.REMOTE_AUDIO_UNAVAILABLE,PF.REMOTE_VIDEO_AVAILABLE,PF.REMOTE_VIDEO_UNAVAILABLE,PF.CONNECTION_STATE_CHANGED,PF.PUBLISH_STATE_CHANGED,PF.SCREEN_SHARE_STOPPED,PF.DEVICE_CHANGED,PF.FIRST_VIDEO_FRAME]);function LF(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function xF(e){return e===oF.QOS_PREFERENCE_CLEAR?"detail":e===oF.QOS_PREFERENCE_SMOOTH?"motion":""}var VF={};FC(VF,{bytes2ms:()=>Qk,convertObjectNumberToInt:()=>BD,copyProperties:()=>Xk,deepClone:()=>ND,deepMerge:()=>DD,delay:()=>HD,fibonacci:()=>nD,formatedTime:()=>PD,getConstructorName:()=>TD,getContainerFromElement:()=>OD,getEnv:()=>Gk,getInternalVersion:()=>ID,getLoggerUrl:()=>jk,getMuteStateFromFlag:()=>CD,getNetworkType:()=>Jk,getNumNetworkType:()=>Yk,getReconnectionTimeout:()=>sD,getStringByteLength:()=>xD,getTurnServer:()=>bD,getUint32Version:()=>FD,getValueType:()=>oD,getViewListFromView:()=>wD,glog:()=>tD,ipv4ToUint32:()=>kD,isArray:()=>pD,isAudioWorkletSupported:()=>ED,isBoolean:()=>uD,isConstructor:()=>gD,isEmpty:()=>RD,isFunction:()=>aD,isLangChinese:()=>iD,isMediaStreamTrack:()=>mD,isNumber:()=>dD,isObject:()=>hD,isOverseaSdkAppId:()=>Wk,isPlainObject:()=>rD,isPortrait:()=>VD,isPromise:()=>fD,isRemoteTrack:()=>_D,isString:()=>lD,isUndefined:()=>cD,loadImage:()=>UD,ms2bytes:()=>$k,ms2samples:()=>eD,performanceNow:()=>yD,promiseAny:()=>vD,samples2ms:()=>Zk,setNetworkType:()=>zk,stringify:()=>MD,stringifyIncludeValue:()=>LD,throttlePromise:()=>GD});var UF={};FC(UF,{getAbilityConfigUrl:()=>JF,getScheduleDomain:()=>qF,isNeedToSchedule:()=>BF,scheduleProxy:()=>WF,sendScheduleRequest:()=>GF,setIsNeedToSchedule:()=>HF,setScheduleProxy:()=>jF});var FF=null,BF=!0;function HF(e){uD(e)&&e!==BF&&(BF=e,Ww.info("setIsNeedToSchedule ".concat(e)))}function GF(e){return jC(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:n,userSig:s,version:o,frameWorkType:a,role:c,latencyLevel:l}=e;return function*(){if(!BF&&FF)return{isCached:!0,result:FF};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",o),d.append("userSig",String(s)),c&&d.append("role",String(c)),l&&d.append("latencyLevel",String(l)),a&&d.append("frameWorkType",String(a));let u=yD(),h=yield function(e,t,i){return new Promise(((r,n)=>{let s=null;vD([YF((e=>t.count[0]=e+1),(e=>{let{error:r,retry:n,retriedCount:o,retryFuncArgs:a}=e;t.msg[0]=r.message,s||(o>=1&&(a[0]=KF(i,Bb.MAIN,!0)),n())}))(KF(i,Bb.MAIN),e,{get timeout(){return 1e3*nD(2+t.count[0])}}),YF((e=>t.count[1]=e+1),(e=>{let{error:r,retry:n,retriedCount:o,retryFuncArgs:a}=e;t.msg[1]=r.message,s||(o>=2&&(a[0]=KF(i,Bb.BACKUP,!0)),n())}))(KF(i,Bb.BACKUP),e,{get timeout(){return 1e3*nD(2+t.count[1])}})]).then((e=>{s=e,r(s)})).catch(n)}))}(d,e,i);h.config&&(h.config.loggerDomain&&Eb(h.config.loggerDomain),uD(h.config.scheduleCache)&&HF(!h.config.scheduleCache)),e.delta=yD()-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"),s=KF(e,Bb.MAIN),o=KF(e,Bb.BACKUP);for(let e of n)if(e.startTime>=i&&(e.name===s||e.name===o)&&e.transferSize>0){let i=e.name===s?Bb.MAIN:Bb.BACKUP,n=Math.round(e.duration),o=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];IM.uploadEvent({log:"stat-schedule-net:".concat(n,"(").concat(o,"(").concat(a,"->").concat(c,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=VC(xC({},r),{totalCost:n,local:o,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(s){Ww.error("getScheduleDetailCost error",s)}return r}(Number(i),t,u);return FF=h,{isCached:!1,result:h,detailCost:p}}catch(zw){let t=pD(zw)?zw[0]:zw,i=dD(t.code)?t.code:0,r="schedule failed".concat(t.message?": ".concat(t.message):""),n=new nb({code:ib.SCHEDULE_FAILED,extraCode:i,message:QO({key:qO.JOIN_ROOM_FAILED,data:{error:r,code:i}})});throw Ww.error(r,i),n}}()}))}"undefined"!=typeof document&&document.head.insertAdjacentHTML("beforeend",Object.values(Dk).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),Fw.on("28",(()=>HF(!0))),Fw.on("63",(()=>HF(!0))),Fw.on("84",(()=>HF(!0))),Fw.on("201",(e=>{"RECONNECTING"===e.state&&HF(!0)})),Fw.on("202",(e=>{"RECONNECTING"===e.state&&HF(!0)}));var WF={main:"",backup:""};function jF(e){pD(e)?(WF.main=e[0],WF.backup=e[1]):WF.main=e}function KF(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Bb.MAIN,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return"https://".concat(WF[t]||qF(e,t,i),"/api/v1/config")}function JF(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Bb.MAIN;return"https://".concat(WF[t]||qF(e,t),"/api/v1/trtcAutoConf")}function qF(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Bb.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=Wk(e)?r?i===Bb.MAIN?Dk.MAIN_OVERSEA_BACKUP:Dk.BACKUP_OVERSEA:i===Bb.MAIN?Dk.MAIN_OVERSEA:Dk.BACKUP_OVERSEA:i===Bb.MAIN?Dk.MAIN:Dk.BACKUP,t}function zF(e,t,i){return new Promise(((r,n)=>{WD({url:e,body:t,timeout:i.timeout,priority:"high"}).then((e=>{0===e.data.code?r(e.data.data):n({code:e.data.code,message:e.data.msg})})).catch(n)}))}var YF=(e,t)=>XD({retryFunction:zF,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var XF=class{constructor(){GC(this,"_log"),this._log=Ww.createLogger({id:"fd"})}download(e,t){return jC(this,null,(function*(){let{type:i="blob"}=t||{};try{let t,r=yD();if(t=aD(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let n=yD()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(n,"ms")),aP.addSuccessEvent({key:522700,cost:yD()-r}),t.data}catch(Zw){throw this._log.error("failed to download: ".concat(e,", error: ").concat(Zw)),aP.addFailedEvent({key:522700,error:Zw}),Zw}}))}downloadWithFetch(e,t){return jC(this,null,(function*(){this._log.info("download with fetch: ".concat(e,", return type: ").concat(t));try{let i,r=yield fetch(e);if(!r.ok)throw new Error("network response was not ok");return i="arraybuffer"===t?yield r.arrayBuffer():yield r.blob(),{data:i}}catch(mk){throw mk}}))}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType=t,n.onload=()=>{200===n.status||0===n.status&&n.response?i({data:n.response}):r(new Error("XHR failed"))},n.onerror=r,n.send(null)}))}loadWasm(e,t){return jC(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=yD(),r=null,n=null;if(aD(WebAssembly.instantiateStreaming)&&!e.startsWith("data:application/octet-stream;base64,")&&!(e=>e.startsWith("file://"))(e)&&aD(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(mb){n=mb}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(mb){n=mb}if(r){let t=yD()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),aP.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),aP.addFailedEvent({key:522701,error:n}),n}))}};HC([RM({settings:{timeout:0,retries:3},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],XF.prototype,"download",1);var QF=new XF;function ZF(e){let{TRTC:t,room:i,errorModule:r,assetsPath:n}=e;return{TRTC:t,room:i,assetsPath:n,fileDownloader:QF,innerEmitter:Fw,constants:lb,environment:ZD,utils:VF,eventLogger:IM,log:this.room.getLogger(),loggerManager:Ww,errorModule:r,kvStatManager:aP,rtcDectection:Jw,trtc:this,rx:Tx,enums:qw,schedule:UF,clearStarted:(e,t)=>{let i=e.getAlias(),r=bF.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:uL}}var $F=new WeakMap;function eB(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return KL(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];try{iB.call(this,t,n,i,this._name)}catch(Zw){return Promise.reject(Zw)}return e.apply(this,n)}))}function tB(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return KL(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];try{iB.call(this,t,n,i,this._name)}catch(Zw){throw Zw}return e.apply(this,n)}))}function iB(e,t,i,r){if(pD(e))for(let n=0;n<e.length;n++)rB.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else rB.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function rB(e){let{rule:t,value:i,key:r,fnName:n,className:s}=e;function o(e){return{code:aF.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(cD(i)){if(t.required)throw new hF(o(5001));if(cD(t.defaultValue))return void(aD(t.validate)&&t.validate.call(this,i,r,n,s,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),aD(t.type[r])&&i instanceof t.type[r]&&(e=!0),lD(t.type[r])&&oD(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new hF({code:aF.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>gD(e)?TD(e):lD(e)?e:oD(e)))},value:i}})}else if(!cD(t.type)&&oD(i)!==t.type)throw new hF(o(5002));if(!1===t.allowEmpty){let e=dD(i)&&(0===i||Number.isNaN(i)),t=lD(i)&&""===i.trim();if(e||t)throw new hF(o(5003))}if(t.notLessThanZero&&dD(i)&&i<0)throw new hF(o(5006));if(!cD(t.min)&&dD(i)&&i<t.min)throw new hF(o(5007));if(!cD(t.max)&&dD(i)&&i>t.max)throw new hF(o(5008));if(lD(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new hF(o(5004))}else if(aD(t.instanceOf)&&!(i instanceof t.instanceOf))throw new hF(o(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new hF(o(5005));let{properties:a}=t;rD(a)&&hD(i)&&Object.keys(a).forEach((e=>{rB.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:s})}));let{arrayItem:c}=t;rD(c)&&pD(i)&&i.forEach(((e,t)=>{rB.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:s})})),aD(t.validate)&&t.validate.call(this,i,r,n,s,this)}function nB(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r,ignoreLog:n}=e;return KL(((e,s)=>function(){for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];var l;function d(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...a);if(a[e.argIndex]===t)return e.value}if(t===a||e in a)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(oD(t)):(JSON.stringify(t),t)}catch(rO){return"type:".concat(oD(t))}}let u=this._log||Ww;if(null!=n&&n(...a))return e.apply(this,a);a.length>0?u.info("".concat(s,"() ").concat(JSON.stringify(a,((e,t)=>d(e,t,["userSig","privateMapKey"]))))):u.info("".concat(s,"()"));let h=r?r(...a):tP[s];try{let i=e.apply(this,a),r=yD();return fD(i)?i.then((e=>(u.info("".concat(s,"() success ").concat(t.call(this,...a))),aP.addSuccessEvent({key:h,cost:yD()-r}),e))).catch((e=>{var i;let r=(e=hF.convertFrom.call(this,e,s,1===a.length?a[0]:a)).extraCode||e.code,n=null!=(i=e.message)&&i.includes(r)?"":" code:".concat(r);throw u.error("".concat(s,"() failed ").concat(t.call(this,...a)," ").concat(e).concat(n," params: ").concat(JSON.stringify(a,d))),aP.addFailedEvent({key:h,error:e}),e})):(aP.addSuccessEvent({key:h}),i)}catch(p){let e=(p=hF.convertFrom.call(this,p,s)).extraCode||p.code,t=null!=(l=p.message)&&l.includes(e)?"":" code:".concat(e);throw u.error("".concat(s,"() failed ").concat(p).concat(t," params: ").concat(JSON.stringify(a,d))),aP.addFailedEvent({key:h,error:p}),p}}))}var sB=e=>KL(((t,i)=>function(r,n){return jC(this,null,(function*(){let s=this._plugins.get(r);if(!s)throw this._log.error("plugin ".concat(String(r)," is not found")),new hF({code:aF.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(aD(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new hF({code:aF.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return iB.call(this,s.getValidateRule(e),[n],i,"TRTC"),t.call(this,s,n)}))})),oB=0,aB=class{constructor(e,t){GC(this,"player"),GC(this,"publisher"),GC(this,"mixInput"),this.mixInput=new cL(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&&(cD(e.volume)||(this.volume=e.volume),cD(e.loop)||(this.loop=e.loop),cD(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 cB(e,t){if(t&&"function"!=typeof t)throw new hF({code:aF.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var lB=class e{constructor(e){this.core=e,GC(this,"log"),GC(this,"mixedMusicMap",new Map),GC(this,"cacheMusicMap",new Map),oB+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(oB)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat(oB)),this.core=e}getName(){return e.Name}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(t){switch(t){case"start":return e.startValidateRule;case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return jC(this,null,(function*(){let{room:t}=this.core;this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:i,url:r}=e;if(this.mixedMusicMap.has(i))return;let n=this.cacheMusicMap.get(i);n?e.url?n.reset():(n.mixInput.replaceSource(e.track),n.mixInput.connect()):(n=new aB(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.")),aP.addEnum({key:502700,value:3}),this.kvUpload(e)}))}update(e){return jC(this,null,(function*(){let{id:t,operation:i,seekFrom:r,playbackRate:n}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let s=this.mixedMusicMap.get(t);s?(s.updateSettings(e),s.updateListener(e),cD(i)||s.setOperation(i),cD(r)||s.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return jC(this,arguments,(function(e){var t=this;let{id:i}=e;return function*(){var e;t.mixedMusicMap.has(i)&&(t.log.info("remove music source, music id: ".concat(i)),null==(e=t.mixedMusicMap.get(i))||e.stop(),t.mixedMusicMap.delete(i)),"*"===i&&t.destroyAllMusic()}()}))}kvUpload(e){let{track:t,loop:i,volume:r,playbackRate:n,operation:s,seekFrom:o,onTimeUpdate:a,onDurationChange:c,onEnded:l}=e;t&&aP.addCount({key:502711}),i&&aP.addCount({key:502703}),r&&aP.addCount({key:502704}),n&&aP.addCount({key:502705}),s&&aP.addCount({key:502706}),o&&aP.addCount({key:502707}),"function"!=typeof a&&aP.addCount({key:502709}),"function"!=typeof l&&aP.addCount({key:502710}),"function"!=typeof c&&aP.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()}};GC(lB,"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(),s=r.indexOf(n)>=0,o=t.startsWith("blob"),a=t.startsWith("data");if(!(s||o||a))throw new hF({code:aF.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new hF({code:aF.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});cB("onTimeUpdate",e.onTimeUpdate),cB("onEnded",e.onEnded),cB("onDurationChange",e.onDurationChange)}}),GC(lB,"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){cB("onTimeUpdate",e.onTimeUpdate),cB("onEnded",e.onEnded),cB("onDurationChange",e.onDurationChange)}}),GC(lB,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),GC(lB,"Name","AudioMixer");var dB,uB=lB,hB=0,pB=class e{constructor(e){this.core=e,GC(this,"log"),GC(this,"audioContext",nL()),GC(this,"workletNode"),hB+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(hB)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(hB)),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 hF({code:aF.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return dB||(dB=this.doPreload(e)),dB}doPreload(e){return jC(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield QM(this.audioContext,i)}finally{URL.revokeObjectURL(i)}}))}getName(){return e.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(t){switch(t){case"start":return e.startValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return jC(this,null,(function*(){let{room:t}=this.core;if(yield this.preload("".concat(e.assetsPath,"/denoiser-wasm.js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:i,sign:r,status:n,message:s}=yield function(e){return jC(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:r,timestamp:n}=e;return function*(){let e="".concat(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Bb.MAIN;return"https://".concat(WF[t]||qF(e,t),"/api/v1/audioAiAuth")}(t),"?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(r,"×tamp=").concat(n),s=yield fetch(e),{data:{errCode:o,errMsg:a,sign:c,status:l}}=yield s.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d="Init RTCAIDenoiser failed.",u="";switch(o){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)}}()}))}(VC(xC({},e),{timestamp:t}));if(!i)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(i,". Message: ").concat(s)),new hF({code:aF.INVALID_PARAMETER,message:s});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(e.sdkAppId),userId:e.userId,timestamp:t,sign:r,status:n}}),this.workletNode.port.onmessage=e=>{let{data:t}=e;"cost"===t.type&&this.log.debug("[RTCAIDenoiser] ".concat(t.value))}}this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})}))}update(){return jC(this,null,(function*(){}))}stop(){return jC(this,null,(function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)}))}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};GC(pB,"updateValidateRule",{type:"object"}),GC(pB,"stopValidateRule",{type:"object"}),GC(pB,"Name","AIDenoiser");var mB=pB;var _B=BC(KC(),1),fB=class extends _B.EventEmitter{constructor(){super(),GC(this,"observer"),GC(this,"state","nominal"),this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return jC(this,null,(function*(){if(!this.observer)try{"PressureObserver"in window&&!dN&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(pb){IM.uploadEvent({log:"stat-pressure-detector-start-failed",error:pb})}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&Ww.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(mk){IM.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:mk})}}},gB=new fB;function TB(e){let[t,i]=e,r=i.byteLength,n=parseInt(String(r/255),10),s=r%255,o=[];o.push(0,0,0,1,6,t);for(let c=0;c<n;c++)o.push(255);o.push(s);let a=new DataView(i);return o.push(...new Uint8Array(a.buffer)),o.push(128),new sx(new DataView(new Uint8Array(o).buffer),!0)}function EB(e){return"empty"===e.type||0===e.data.byteLength}function vB(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}function yB(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 SB(e){let{frame:t,seiMessageList:i}=e;if(!i||0===i.length||0===t.data.byteLength)return t;let r=9-yB(t.data);if(r<=0)return t;let n=i.splice(0,r).reverse().map(TB),s=n.reduce(((e,t)=>e+t.dataView.byteLength),0),o=new ArrayBuffer(s+t.data.byteLength),a=new DataView(o),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=o,t}function IB(e){let{frame:t,onSEI:i}=e;try{let e=new DataView(t.data);if(EB(t)||!vB(e))return t;let r=[],n=0,s=-1,o=-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===s?s=a:-1===o&&(o=a,r.push(new sx(new DataView(e.buffer.slice(s,o)))),s=a,o=-1),6!==e.getUint8(i+1)){t.data=e.buffer.slice(a);break}}n=0}else n=0}null==i||i(r.reverse())}catch(pb){}return t}var AB=0,RB=class e{constructor(e){this.core=e,GC(this,"log"),GC(this,"_seiMessageList",[]),GC(this,"_smallSeiMessageList",[]),GC(this,"_subStreamSeiMessageList",[]),AB++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(AB)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(AB)),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 SB({frame:t,seiMessageList:8===i?this._smallSeiMessageList:2===i?this._subStreamSeiMessageList:this._seiMessageList})}catch(mk){this.log.warn(mk)}return t}decode(e){let{frame:t,track:i}=e;return IB({frame:t,onSEI:e=>{e.forEach((e=>{this.core.trtc.emit(PF.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:WP?this.encode:SB,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:WP?this.decode:IB,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update(e){let{buffer:t,options:i}=e;var r;let n=[i.seiPayloadType,t],s=!!i.small;i.toSubStream?this._subStreamSeiMessageList.push(n):(this._seiMessageList.push(n),s&&this._smallSeiMessageList.push(n)),null==(r=this.core.room.scriptTransformWorker)||r.postMessage({type:"sei",data:n,isMain:!i.toSubStream,small:s})}getName(){return e.Name}getAlias(){return"sei"}getGroup(){return"sei"}};GC(RB,"autoStart",!0),GC(RB,"Name","SEI");var CB=RB;function bB(e){let{frame:t,onDump:i}=e;return null==i||i(),t}function kB(e){let{frame:t,onDump:i}=e;return null==i||i(),t}var DB={"play() error: NotAllowedError:":{tips:e=>e.includes("main <video>")||e.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:e=>e.includes("↓")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:e=>e.includes("↓")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:"The remote stream audio playback is paused, which usually has two possibilities:\n 1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.\n 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.",color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:"The remote stream video playback is paused, which usually has two possibilities:\n 1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.\n 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.",color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach((e=>{DB["".concat(e,"()")]={tips:"Call trtc.".concat(e),color:"blue",class:"blue",textColor:"#fff"}}));var NB,wB=0,OB=class e{constructor(e){this.core=e,GC(this,"_core"),GC(this,"log"),GC(this,"dumpLocalVideoMap",{}),GC(this,"dumpRemoteVideoMap",{}),GC(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++wB)}),this.log.info("created")}getName(){return e.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(e){switch(e){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return jC(this,null,(function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&"true"!==(null==(e=window.sessionStorage)?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))||(yield this.openDebugDiaLog(),this.addVideoProcessor())}))}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return jC(this,null,(function*(){try{if(NB)yield NB;else{let e=Date.now(),t=new URLSearchParams(location.search).get("trtcDebugDialogVersion")||ub;NB=this.loadScript("https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@".concat(t,".js")),yield NB,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(Qw){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(Qw))}}))}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):bB,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):kB,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo(e){let{frame:t,mediaType:i}=e;return bB({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 kB({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())}})}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)}))}};GC(OB,"Name","Debug"),GC(OB,"autoStart",!0),HC([RM({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)}})],OB.prototype,"loadScript",1);var PB=OB,MB=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},LB=class{constructor(e,t,i){GC(this,"trackDoneOB"),GC(this,"startOB"),GC(this,"stopOB"),GC(this,"inputFrameCount",0),GC(this,"decodedFrameCount",0),GC(this,"type","auto"),GC(this,"config"),GC(this,"decoder"),GC(this,"_decodeSink");let{kvStatManager:r,trtc:n}=e;this.config=i.config,this.trackDoneOB=oV(t,uM.INIT),this.stopOB=Xx(this.trackDoneOB),this.startOB=Xx(),"auto"===i.type?this.type="webCodecs":this.type=i.type;let s=Xx();Dx(this.startOB,Kx(0),sU((e=>{let i=this.pipe(t);return s.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),Dx(i,kV(this.stopOB),bU((()=>{}),(i=>{t.log.error(i),r.addFailedEvent({key:MB(this.type),error:i}),e>4?this.startOB.error(i):this.startOB.next(e+1)}))),Dx(i,bV(1),AU(TV))})),kV(this.stopOB),bU((()=>{t.player.setOutput(),s.next("STARTED")}),(e=>{s.next("FAILED")}),(()=>{r.addSuccessEvent({key:MB(this.type)}),r.addSuccessEvent({key:504702})})))}mock(e){this._decodeSink?this._decodeSink.error(e):this.startOB.next(0)}close(e){this.stopOB.next(e)}pipe(e){return Vx()((t=>jC(this,null,(function*(){this._decodeSink=t,t.defer((()=>{var e;null==(e=this.decoder)||e.close()}));let{type:i}=this;try{if("webCodecs"===i)this.decoder=new AudioDecoder({error:i=>{e.log.error(i),t.error(4)},output:i=>{this.decodedFrameCount++,t.next(i),e.player.write(i)}});this.decoder.configure(this.config)}catch(Zw){e.log.error(Zw),t.error("webCodecs"===i?2:6)}}))))}decodeFrame(e){var t;this.inputFrameCount++,"configured"===(null==(t=this.decoder)?void 0:t.state)&&this.decoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"}))}},xB={type:"object"},VB=class e{constructor(e){this.core=e,GC(this,"log"),GC(this,"contextMap",new Map),GC(this,"decodeProcessorMap",new WeakMap),this.log=e.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return e.Name}getGroup(e){return e.track.userId+e.track.streamType}getName(){return e.Name}getValidateRule(e){return xB}start(e){let{track:t}=e;this.decodeProcessorMap.set(t,this.decode(e)),this.core.room.audioManager.addDecodeProcessor({processor:e=>{let{frame:t,track:i}=e;return this.decodeProcessorMap.has(i)?this.decodeProcessorMap.get(i)({frame:t,track:i}):t},type:3})}decode(e){return t=>{let{frame:i,track:r}=t;if(r!==e.track)return i;if(this.contextMap.has(r))return this.contextMap.get(r).decodeFrame(i);let n=new LB(this.core,r,e);return Dx(n.trackDoneOB,bV(1),bU((()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:r})}))),this.contextMap.set(r,n),n.decodeFrame(i)}}stop(e){let{track:t}=e,i=this.contextMap.get(t);i&&(i.close("stop"),this.contextMap.delete(t),0===this.contextMap.size&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(e){let t=this.contextMap.get(e.track);if(t){if("mock"===e.type)return void t.mock(10);t.close("update"),this.contextMap.set(e.track,new LB(this.core,e.track,e))}}};GC(VB,"Name","TRTCAudioDecoder");var UB=VB,FB=0,BB=new Set,HB=null;hb("5.9.1"),Kw.checkStorage(),$P();var GB={RtcError:hF,ErrorCode:aF,ErrorCodeDictionary:cF},WB=class e extends eb.EventEmitter{constructor(t,i){super(),GC(this,"_room"),GC(this,"_eventListened",new Set),GC(this,"_localVideoTrack",null),GC(this,"_localAudioTrack",null),GC(this,"_localScreenTrack",null),GC(this,"_localScreenAudioTrack",null),GC(this,"_localVideoConfig",null),GC(this,"_localScreenConfig",null),GC(this,"_localAudioConfig",null),GC(this,"_remoteVideoConfigMap",new Map),GC(this,"_remoteAudioConfigMap",new Map),GC(this,"_remoteAudioVolumeMap",new Map),GC(this,"_remoteAudioMuteMap",new Map),GC(this,"_mediaTrackMap",new WeakMap),GC(this,"_log",Ww.createLogger({id:"t".concat(++FB)})),GC(this,"_plugins",new Map),GC(this,"_networkQuality",null),GC(this,"_speakerId"),GC(this,"_getPCMAbortCtrl"),this._room=new t(xC({logger:this._log,frameWorkType:e.frameWorkType},i)),this._room.videoDecodeFallbackType=i.videoDecodeFallback,this._log.debug("TRTC.create() ".concat(JSON.stringify(i,((e,t)=>"plugins"===e?t.map((e=>e.Name)):t)))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(e){return this._room.audioManager.dump(e)}}}),i.plugins&&i.plugins.forEach((e=>{this._use(e,i.assetsPath)})),this._use(uB,i.assetsPath),this._use(mB,i.assetsPath),this._use(UB,i.assetsPath||Rb),this._use(PB),i.enableSEI&&KP&&this._use(CB),this._room.on("audio-volume",(e=>{!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*this._localAudioTrack.getAudioLevel())}),1===i.volumeType&&e.forEach((e=>{var t;let i=""===e.userId?this._localAudioTrack:null==(t=this.room.remotePublishedUserMap.get(e.userId))?void 0:t.remoteAudioTrack;i&&(e.volume=i.dbVolume)})),this.emit(PF.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{this._log.error(new hF({code:aF.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),s=0;s<r;s++)n[s]=arguments[s];try{return i.apply(e,n)}catch(Zw){let i=QO({key:qO.CATCH_HANDLER_ERROR,data:{name:t,event:n[0]},addDocLink:!1});return Ww.warn("".concat(i,"\n\n").concat(Zw.stack)),!1}}})(this,"trtc")}static create(e){}static _create(t,i){var r;sF&&(sF=!1,5!==Ww.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Ab,"/en/index.html")),console.info("* Changelog: ".concat(Ab,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),Ww.info("TRTC Web SDK Version:",ub),Aw||Ww.debug("Build Time:","2025-03-20 11:39:22"),Ww.info("UA:",navigator.userAgent),Ww.info("URL: ".concat(location.href).concat("IFRAME"===(null==(r=self.frameElement)?void 0:r.tagName)?" in iframe":"")),Nw().then((e=>{e&&Ww.info(Dw)})));let n=new e(t,i||{});return BB.add(n),n}get room(){return this._room}_listenEvents(){yM(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(PF.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(PF.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)})).add("banned",(e=>{this._exitRoom().finally((()=>{this.emit(PF.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().finally((()=>{this.emit(PF.ERROR,hF.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(PF.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e;let t=VC(xC({},e),{uplinkRTT:Math.min(e.uplinkRTT,Hk),downlinkRTT:Math.min(e.downlinkRTT,Hk)});this.emit(PF.NETWORK_QUALITY,t)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{yM(t,t).add("player-state-changed",(i=>{let r=VC(xC({},i),{userId:e.userId});t.kind===Bb.VIDEO&&(r.streamType=LF(t.streamType)),this.emit(t.kind===Bb.AUDIO?PF.AUDIO_PLAY_STATE_CHANGED:PF.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===ib.PLAY_NOT_ALLOWED&&this.emit(PF.AUTOPLAY_FAILED,{userId:t.userId,resume:()=>t.player.resume()})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{SM(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:r}=i,n=t.audioAvailable,s=t.videoAvailable,{audioAvailable:o,videoAvailable:a}=i;o||this._remoteAudioConfigMap.delete(r),a||this._remoteVideoConfigMap.delete("".concat(r,"_main")),i.hasAuxiliary||this._remoteVideoConfigMap.delete("".concat(r,"_sub")),s!==a&&(a?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(a?PF.REMOTE_VIDEO_AVAILABLE:PF.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),n!==o&&(o?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i}),this.emit(o?PF.REMOTE_AUDIO_AVAILABLE:PF.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),t.hasAuxiliary!==i.hasAuxiliary&&(i.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(i.hasAuxiliary?PF.REMOTE_VIDEO_AVAILABLE:PF.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))})).add("sei-message",(e=>{this.emit(PF.SEI_MESSAGE,VC(xC({},e),{streamType:LF(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(PF.ERROR,new hF({code:aF.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,i,r,n,s,o,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,Hk),upLoss:(null==(n=this._networkQuality)?void 0:n.uplinkLoss)||0,downLoss:(null==(s=this._networkQuality)?void 0:s.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(o=e.msg_up_stream_info.msg_audio_status)?void 0:o.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/VO},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)/VO},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(PF.STATISTICS,l)})).add("custom-message",(e=>{this.emit(PF.CUSTOM_MESSAGE,e)})).add("layerData",(e=>this.emit(PF.LAYER_DATA,e))).add("first-video-frame",(e=>{this.emit(PF.FIRST_VIDEO_FRAME,VC(xC({},e),{streamType:LF(e.streamType)}))})),yM(this,vL).add("audioInputAdded",(e=>{this.emit(PF.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(PF.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(PF.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(PF.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>jC(this,null,(function*(){if(this.emit(PF.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),HB&&HB.deviceId===Mk){let e=(yield CL()).find((e=>e.deviceId===Mk));e&&HB.groupId!==e.groupId&&(HB=e,this.emit(PF.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>jC(this,null,(function*(){this.emit(PF.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield CL())[0];if(!t||!HB||HB.groupId===t.groupId)return;let i=HB.deviceId===e.deviceId,r=HB.deviceId===Mk&&HB.deviceId===t.deviceId;(i||r)&&(HB=t,this.emit(PF.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||Rb)}_use(t,i){if(this._plugins.get(t.Name))return void this._log.warn("duplicate install plugin",t.Name);let r=new t(ZF.call(this,{TRTC:e,room:this._room,errorModule:GB,assetsPath:i}));this._plugins.set(t.Name,r),t.autoStart&&this.startPlugin(t.Name)}enterRoom(t){return jC(this,null,(function*(){var i,r;let{scene:n="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:o=!0,autoReceiveVideo:a=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!lD(t.proxy)&&t.proxy.turnServer&&(null==(r=(i=this._room).setTurnServer)||r.call(i,t.proxy.turnServer,t.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=a,uD(t.preferHW)&&(this._room.preferHW=t.preferHW);let c={sdkAppId:t.sdkAppId,userId:t.userId,userSig:t.userSig,privateMapKey:t.privateMapKey||null,latencyLevel:t.latencyLevel,role:"audience"===t.role?21:20,roomId:t.roomId||0,strRoomId:t.strRoomId||"",businessInfo:t.businessInfo||null,streamId:null,userDefineRecordId:t.userDefineRecordId||null,frameWorkType:t.frameWorkType,component:t.component,language:t.language,priority:t.priority,useVp8:t.useVp8};t.strRoomId&&!t.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(c,n,e.frameWorkType),this._checkTrackToPublish(),gB.start()}))}exitRoom(){return jC(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return jC(this,null,(function*(){null!=t&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),null!=t&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),"anchor"===e&&this._checkTrackToPublish()}))}destroy(){SM(this),this.removeAllListeners(),this._room.destroy(),BB.delete(this),0===BB.size&&gB.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)})),this._plugins.clear(),Fw.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return jC(this,arguments,(function(){var t=this;let i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(t._localAudioTrack)return void t._log.warn("local audio is already started");let{publish:r=!0,mute:n,option:s}=i,o=new nx(t._room.audioManager),a={},c={muted:!0};s&&(cD(s.microphoneId)?cD(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&dD(s.captureVolume)&&o.setCaptureVolume(s.captureVolume),cD(s.profile)||(lD(s.profile)?Vb[s.profile]&&o.setProfile(Vb[s.profile]):o.setProfile(s.profile)),dD(s.earMonitorVolume)&&(c.muted=!(s.earMonitorVolume>0),c.volume=s.earMonitorVolume),cD(s.echoCancellation)||(o.profile.echoCancellation=s.echoCancellation),cD(s.noiseSuppression)||(o.profile.noiseSuppression=s.noiseSuppression),cD(s.autoGainControl)||(o.profile.autoGainControl=s.autoGainControl)),o.on("5",(e=>{t.emit(PF.ERROR,new hF({code:aF.DEVICE_ERROR,extraCode:5309,messageParams:{error:e}}))})),o.on("2",(e=>{t.emit(PF.DEVICE_CHANGED,{type:"microphone",action:"active",device:e})})),o.on("4",(e=>{let i;e.error&&(i=hF.convertFrom(e.error)),t.emit(PF.PUBLISH_STATE_CHANGED,VC(xC({},e),{error:i}))})),t._listenOutputTrackChanged(o),t._speakerId&&o.setAudioOutput(t._speakerId),yield o.capture(a),cD(n)||o.setMute(n),yM(o,o).add("player-state-changed",(e=>{t.emit(PF.AUDIO_PLAY_STATE_CHANGED,VC(xC({},e),{userId:""}))})),t.listeners(PF.AUDIO_FRAME).length>0&&(t._getPCMAbortCtrl=t._room.audioManager.getPCM((i=>{t.emit(e.EVENT.AUDIO_FRAME,{data:i})}))),t._getPCMAbortCtrl&&o.on("input-media-track-changed",(()=>{t._getPCMAbortCtrl&&(t._getPCMAbortCtrl.abort("inputMediaTrackChanged"),t._getPCMAbortCtrl=t._room.audioManager.getPCM((i=>{t.emit(e.EVENT.AUDIO_FRAME,{data:i})})))})),r&&t._room.isJoined&&t._room.publish(o).catch((()=>{})),t._localAudioTrack=o,t._localAudioConfig=VC(xC({},i),{publish:r}),yield t._updateAudioPlayOption({playOption:c,track:o})}()}))}updateLocalAudio(e){return jC(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:r}=e,n={};r&&(r.microphoneId?yield this._localAudioTrack.switchDevice(r.microphoneId):cD(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),cD(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),cD(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!cD(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),cD(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),DD(this._localAudioConfig,e)}))}stopLocalAudio(){return jC(this,null,(function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),SM(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))}))}startLocalVideo(){return jC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:i,publish:r=!0,mute:n,option:s}=t,o=new cx(e._room.videoManager),a={},c={};s&&(s.cameraId?a.deviceId=s.cameraId:cD(s.useFrontCamera)?cD(s.videoTrack)||(a.customSource=s.videoTrack):a.facingMode=s.useFrontCamera?Bb.FACING_MODE_USER:Bb.FACING_MODE_ENVIRONMENT,s.qosPreference&&(a.contentHint=xF(s.qosPreference)),cD(s.profile)||(lD(s.profile)?Ub[s.profile]&&o.setProfile(Ub[s.profile]):o.setProfile(s.profile)),cD(s.fillMode)||(c.objectFit=s.fillMode),cD(s.mirror)||(c.mirror=s.mirror),cD(s.small)||(DP()?lD(s.small)?o.small=Ub[s.small]:!0===s.small?o.small=Ub["120p"]:o.small=s.small:e._log.warn("small stream is not supported"))),o.once("first-video-frame",(t=>{e.emit(PF.FIRST_VIDEO_FRAME,VC(xC({},t),{streamType:LF(t.streamType)}))})),o.on("5",(t=>{e.emit(PF.ERROR,new hF({code:aF.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(PF.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=hF.convertFrom(t.error)),e.emit(PF.PUBLISH_STATE_CHANGED,VC(xC({},t),{error:i}))})),e._listenOutputTrackChanged(o),yield o.capture(a),cD(n)||(yield o.setMute(n)),yM(o,o).add("player-state-changed",(t=>{e.emit(PF.VIDEO_PLAY_STATE_CHANGED,VC(xC({},t),{userId:"",streamType:"main"}))})),r&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localVideoTrack=o,e._localVideoConfig=VC(xC({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:o})}()}))}updateLocalVideo(e){return jC(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:r,option:n}=e,s={};if(n)if(cD(n.profile)||(lD(n.profile)?Ub[n.profile]&&this._localVideoTrack.setProfile(Ub[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&cD(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):cD(n.useFrontCamera)?cD(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?Bb.FACING_MODE_USER:Bb.FACING_MODE_ENVIRONMENT),cD(n.fillMode)||(s.objectFit=n.fillMode),cD(n.mirror)||(s.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(xF(n.qosPreference)),n.small){let e=!this._localVideoTrack.small;DP()?(!0===n.small?this._localVideoTrack.small=Ub["120p"]:lD(n.small)?this._localVideoTrack.small=Ub[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&&!cD(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),cD(r)||(yield this._localVideoTrack.setMute(r)),yield this._updateVideoPlayOption({view:t,playOption:s,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),DD(this._localVideoConfig,e)}))}stopLocalVideo(){return jC(this,null,(function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),SM(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return jC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:i=null,publish:r=!0,option:n}=t,s=new ux(e._room.videoManager);s.on("4",(t=>{let i;t.error&&(i=hF.convertFrom(t.error)),e.emit(PF.PUBLISH_STATE_CHANGED,VC(xC({},t),{error:i}))})),s.once("first-video-frame",(t=>{e.emit(PF.FIRST_VIDEO_FRAME,VC(xC({},t),{streamType:LF(t.streamType)}))})),e._listenOutputTrackChanged(s),"main"===t.streamType&&(s.mediaType=4);let o=null,a={},c={};n&&(cD(n.profile)||(lD(n.profile)?Fb[n.profile]&&s.setProfile(Fb[n.profile]):s.setProfile(n.profile)),n.systemAudio&&(a.systemAudio=!0,a.echoCancellation=n.echoCancellation,a.noiseSuppression=n.noiseSuppression,a.autoGainControl=n.autoGainControl),cD(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),n.qosPreference&&(a.contentHint=xF(n.qosPreference)));let l=yield s.capture(a);if(s.mediaTrack.addEventListener(Bb.ENDED,(()=>{e._stopScreenShare(),e.emit(PF.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(o=new px(e._room.audioManager),yield o.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&o.setAudioOutput(e._speakerId)),yM(s,s).add("player-state-changed",(t=>{e.emit(PF.VIDEO_PLAY_STATE_CHANGED,VC(xC({},t),{userId:"",streamType:"sub"}))})),r&&e._room.isJoined){let t=[s];o&&t.push(o),e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=s,e._localScreenAudioTrack=o,e._localScreenConfig=VC(xC({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:s})}()}))}updateScreenShare(e){return jC(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(cD(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let e=xF(r.qosPreference);this._localScreenTrack.setContentHint(e)}this._room.isJoined&&!cD(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}),DD(this._localScreenConfig,e)}))}stopScreenShare(){return jC(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return jC(this,null,(function*(){let{view:t,userId:i,streamType:r,option:n}=e,s="".concat(i,"_").concat(r);if(this._remoteVideoConfigMap.has(s))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(r));let o=this._room.remotePublishedUserMap.get(i);if(!o)return;let a={},c="main"===r?o.remoteVideoTrack:o.remoteAuxiliaryTrack;this._listenOutputTrackChanged(c),n&&(cD(n.fillMode)||(a.objectFit=n.fillMode),cD(n.mirror)||(a.mirror=n.mirror),a.canvasRender=n.canvasRender,"main"===r&&!cD(n.small)&&(!o.remoteVideoTrack.isSubscribing&&!o.remoteVideoTrack.isSubscribed&&o.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,c.user))),yield this._room.subscribe(c),yield this._enableVideoDecodeFallback(c,r),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._emitTrackEvent(c),this._remoteVideoConfigMap.set(s,{config:e}),n&&!cD(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return jC(this,null,(function*(){var t,i;let{view:r,userId:n,streamType:s,option:o}=e,a="".concat(n,"_").concat(s),c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(n))return;let l={};o&&(cD(o.fillMode)||(l.objectFit=o.fillMode),cD(o.mirror)||(l.mirror=o.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);if("main"===s&&null!=u&&u.muteState.hasVideo&&(d=u.remoteVideoTrack),"sub"===s&&null!=u&&u.muteState.hasAuxiliary&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:h}=c;"main"===s&&o&&!cD(o.small)&&this._room.changeType(o.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:h}),DD(h,e);let p=cD(null==o?void 0:o.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:o.receiveWhenViewVisible,m=cD(r)?h.view:r,_=cD(null==o?void 0:o.viewRoot)?null==(i=h.option)?void 0:i.viewRoot:o.viewRoot;this._observeView({remoteTrack:d,view:m,receiveWhenViewVisible:p,viewRoot:_})}))}stopRemoteVideo(e){return jC(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return jC(this,null,(function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:n,remoteAuxiliaryTrack:s}=r;"main"===e.streamType&&(n.stop(),t.hasVideo&&i.push(n)),"sub"===e.streamType&&(s.stop(),t.hasAuxiliary&&i.push(s))}for(let e of i)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.delete(e.outMediaTrack));let n=this._remoteVideoConfigMap.get("".concat(e.userId,"_").concat(e.streamType));n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete("".concat(e.userId,"_").concat(e.streamType))}))}muteRemoteAudio(e,t){return jC(this,null,(function*(){this._remoteAudioMuteMap.set(e,t);try{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}))}catch(Zw){throw this._remoteAudioMuteMap.delete(e),Zw}}))}setRemoteAudioVolume(e,t){if("*"===e){let e=[...this._room.remotePublishedUserMap.values()];for(let i of e)this._remoteAudioVolumeMap.set(i.userId,t),i.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),i&&i.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}startPlugin(e,t){return jC(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return jC(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return jC(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(t,i,r){return this.listeners(t).includes(i)||(this._log.debug("on",t),super.on(t,i,r),this._eventListened.add(t),t===e.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM((t=>{this.emit(e.EVENT.AUDIO_FRAME,{data:t})})),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",(()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM((t=>{this.emit(e.EVENT.AUDIO_FRAME,{data:t})})))})))),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{MF.has(e)&&this._log.debug("emit ".concat(e," ").concat(JSON.stringify(i)))}catch(Zw){}return super.emit(e,...i)}off(t,i,r){var n,s;return this._log.debug("off",t),"*"===t?(this._eventListened.clear(),this.removeAllListeners(),null==(n=this._getPCMAbortCtrl)||n.abort("off"),delete this._getPCMAbortCtrl):(super.off(t,i,r),t===e.EVENT.AUDIO_FRAME&&(null==(s=this._getPCMAbortCtrl)||s.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(lD(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&&e.muteState.hasVideo)return e.remoteVideoTrack.getVideoFrame();if("sub"===i&&null!=e&&e.muteState.hasAuxiliary)return e.remoteAuxiliaryTrack.getVideoFrame()}else{if("main"===i&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,i;this._speakerId=e,null==(t=this._localAudioTrack)||t.setAudioOutput(e),null==(i=this._localScreenAudioTrack)||i.setAudioOutput(e),this._room.remotePublishedUserMap.forEach((t=>t.remoteAudioTrack.setAudioOutput(e)))}setCurrentSpeaker(e){return jC(this,null,(function*(){(yield CL()).forEach((t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(PF.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),HB=t)})),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')}))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return jC(this,null,(function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let i=this._room.remotePublishedUserMap.get(t);if(!i)return;let r={},n=i.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let i=this._remoteAudioVolumeMap.get(t),s=dD(i)?i:100;r.volume=s,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),Dx(oV(n,"decode-failed"),kV(oV(n,uM.INIT)),bU((()=>{this.startPlugin(UB.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})}))),yield this._updateAudioPlayOption({playOption:r,track:n})}catch($w){throw this._remoteAudioConfigMap.delete(t),$w}this._emitTrackEvent(n)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return jC(this,null,(function*(){let i=this._room.remotePublishedUserMap.get(e.userId);i&&(i.remoteAudioTrack.stop(),i.muteState.hasAudio&&t&&(yield this._room.unsubscribe(i.remoteAudioTrack)),this._mediaTrackMap.delete(i.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId))}))}_enableVideoDecodeFallback(e,t){let i=this._room.videoDecodeFallbackType;!i||!this._plugins.has("VideoDecoderPlugin")||(this._log.debug("remote video will fall back when decode failed"),Dx(oV(e,"decode-failed"),kV(oV(e,uM.INIT)),kU((()=>{this.startPlugin("VideoDecoderPlugin",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:i})})),aU(oV(e,"decode-downgrade-state-changed")),bU((i=>{this.emit(PF.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,VC(xC({},i),{streamType:t,userId:e.userId}))}),(e=>{this._log.error("fallback",e)}),(()=>this._log.info("fallback complete")))))}_updateVideoPlayOption(e){return jC(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),cD(t)&&n&&n.view&&!RD(i)){let e=wD(n.view);e.length>0&&(yield r.play(e,i))}if(!cD(t)){let e=wD(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return jC(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:r}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t)}catch(mb){}cD(t.muted)||i.setPlayerMute(t.muted),cD(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(PF.TRACK,{userId:i,streamType:LF(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var e,t,i;let r=[];if(null!=(e=this._localAudioConfig)&&e.publish&&this._localAudioTrack&&r.push(this._localAudioTrack),null!=(t=this._localVideoConfig)&&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(cD(i))return;let s=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(LF(t.streamType)));if(!s)return;let o=s.observer||void 0;if(null===i||pD(i)&&0===i.length||!r)return null==o||o.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch((()=>{})));let a=s.visibleViewMap||new Map,c=-1;(!o||o.root!==n)&&(null==o||o.disconnect(),a.clear(),o=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(wD(i));a.forEach(((e,t)=>{l.has(t)||(o.unobserve(t),a.delete(t))})),l.forEach((e=>{a.set(e,!0),o.observe(e)})),o.takeRecords().forEach((e=>{a.set(e.target,e.isIntersecting)})),s.visibleViewMap=a,s.observer=o}_exitRoom(){return jC(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach((e=>{this._stopRemoteAudio({userId:e}).catch()})),[...this._remoteVideoConfigMap.keys()].forEach((e=>{let t=e.includes("main")?"main":"sub",i=e.split("_".concat(t))[0];i&&this._stopRemoteVideo({userId:i,streamType:t}).catch()})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),function(e){let t=$F.get(e);t&&(t.forEach((e=>clearTimeout(e))),$F.delete(e))}(this),this._room.remotePublishedUserMap.forEach((e=>{SM(e.remoteAudioTrack),SM(e.remoteVideoTrack),SM(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return jC(this,null,(function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield null==(e=this._room)?void 0:e.unpublish(...t).catch((()=>{}))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),SM(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_onLocalTrackCaptured(e){let{track:t}=e;"audio"===t.kind&&(!HB||yL(HB))&&(this._initActiveSpeaker(),Fw.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return jC(this,null,(function*(){if(HB&&!yL(HB))this.emit(PF.DEVICE_CHANGED,{type:"speaker",action:"active",device:HB});else{let e=yield CL();e[0]&&!yL(e[0])?(HB=e[0],this.emit(PF.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):Fw.on("102",this._onLocalTrackCaptured,this)}}))}_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,t=[e];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&t.push(r.remoteAudioTrack),this._room.subscribe(...t).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:VC(xC({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),aP.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),aP.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){Ww.setLogLevel(e),cD(t)||(t?Ww.enableUploadLog():Ww.disableUploadLog())}static isSupported(){return EP()}static getCameraList(){return AL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return IL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return CL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(t){return jC(this,null,(function*(){if(!dN||t!==oF.SPEAKER&&t!==oF.HEADSET)(yield CL()).forEach((e=>{e.deviceId===t&&(BB.forEach((i=>{i._setCurrentSpeaker(t),i.emit(PF.DEVICE_CHANGED,{type:"speaker",action:"active",device:e})})),HB=e)}));else{let i=yield e.getMicrophoneList(),r="";if(i.forEach((e=>{e.label===t&&(r=e.deviceId)})),!r)return;BB.forEach((e=>jC(this,null,(function*(){e._localAudioTrack&&(yield e.updateLocalAudio({option:{microphoneId:r}}))}))))}}))}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:s,version:o}=e;switch(o&&(oP.version=o),t){case"count":oP.addCount({key:i,useUV:s});break;case"enum":oP.addEnum({key:i,value:r,useUV:s});break;case"number":oP.addNumber({key:i,value:r,split:n})}}};GC(WB,"_loggerManager",Ww),GC(WB,"EVENT",PF),GC(WB,"ERROR_CODE",aF),GC(WB,"TYPE",oF),GC(WB,"frameWorkType",30),HC([nB({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"}})})],WB.prototype,"use",1),HC([eB(yF.TRTC.enterRoom),NF("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})),KL((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),nB()],WB.prototype,"enterRoom",1),HC([nB()],WB.prototype,"exitRoom",1),HC([eB(yF.TRTC.switchRole),wF("room",{merge:(e,t)=>t}),nB()],WB.prototype,"switchRole",1),HC([nB()],WB.prototype,"destroy",1),HC([eB(yF.TRTC.startLocalAudio),NF("audio",((e,t)=>{let[i]=e,[r]=t;var n,s;return(null==(n=null==i?void 0:i.option)?void 0:n.microphoneId)===(null==(s=null==r?void 0:r.option)?void 0:s.microphoneId)})),nB()],WB.prototype,"startLocalAudio",1),HC([eB(yF.TRTC.updateLocalAudio),wF("audio",{debounce:{delay:200,getKey:()=>"".concat(FB,"-localAudio"),isNeedToDebounce:e=>{var t;return!cD(null==(t=e.option)?void 0:t.captureVolume)}}}),nB()],WB.prototype,"updateLocalAudio",1),HC([OF("audio"),nB()],WB.prototype,"stopLocalAudio",1),HC([eB(yF.TRTC.startLocalVideo),NF("video",((e,t)=>{let[i]=e,[r]=t;var n,s;return(null==(n=null==i?void 0:i.option)?void 0:n.cameraId)===(null==(s=null==r?void 0:r.option)?void 0:s.cameraId)})),nB()],WB.prototype,"startLocalVideo",1),HC([eB(yF.TRTC.updateLocalVideo),wF("video"),nB()],WB.prototype,"updateLocalVideo",1),HC([OF("video"),nB()],WB.prototype,"stopLocalVideo",1),HC([eB(yF.TRTC.startScreenShare),NF("screen",(()=>!0)),nB()],WB.prototype,"startScreenShare",1),HC([eB(yF.TRTC.updateScreenShare),wF("screen"),nB()],WB.prototype,"updateScreenShare",1),HC([nB()],WB.prototype,"stopScreenShare",1),HC([eB(yF.TRTC.startRemoteVideo),NF((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),nB({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],WB.prototype,"startRemoteVideo",1),HC([eB(yF.TRTC.updateRemoteVideo),wF((e=>"v".concat(e.userId).concat(e.streamType))),nB({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],WB.prototype,"updateRemoteVideo",1),HC([eB(yF.TRTC.stopRemoteVideo),KL((e=>function(t){return jC(this,null,(function*(){if("*"===t.userId){let e=[];return this._room.remotePublishedUserMap.forEach((t=>{this._remoteVideoConfigMap.has("".concat(t.userId,"_main"))&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch((()=>{}))),this._remoteVideoConfigMap.has("".concat(t.userId,"_sub"))&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch((()=>{})))})),Promise.all(e)}return e.call(this,t)}))})),nB({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],WB.prototype,"stopRemoteVideo",1),HC([OF((e=>"v".concat(e.userId).concat(e.streamType)))],WB.prototype,"_stopRemoteVideo",1),HC([eB(...yF.TRTC.muteRemoteAudio),nB({getRemoteId:e=>e})],WB.prototype,"muteRemoteAudio",1),HC([tB(...yF.TRTC.setRemoteAudioVolume),function(e,t){return KL(((i,r)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];let o=$F.get(this);o||(o=new Map,$F.set(this,o));let a=t(...n),c=o.get(a);if(!c||c<=0){i.apply(this,n);let t=setTimeout((()=>{var e;null==(e=$F.get(this))||e.delete(a)}),e);o.set(a,t)}else{clearTimeout(c);let t=window.setTimeout((()=>{var e;i.apply(this,n),null==(e=$F.get(this))||e.delete(a)}),e);o.set(a,t)}}))}(200,(e=>e)),nB({getRemoteId:e=>e})],WB.prototype,"setRemoteAudioVolume",1),HC([sB("start"),WL((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),NF(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),nB({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>iP[e.getName()],ignoreLog:e=>"Debug"===e.getName()})],WB.prototype,"startPlugin",1),HC([sB("update"),wF(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),nB({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>rP[e.getName()]})],WB.prototype,"updatePlugin",1),HC([sB("stop"),OF(((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i})),nB({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>nP[e.getName()]})],WB.prototype,"stopPlugin",1),HC([tB(...yF.TRTC.enableAudioVolumeEvaluation)],WB.prototype,"enableAudioVolumeEvaluation",1),HC([nB()],WB.prototype,"getVideoSnapshot",1),HC([nB()],WB.prototype,"_setCurrentSpeaker",1),HC([NF((e=>"a".concat(e.userId)),(()=>!0))],WB.prototype,"_startRemoteAudio",1),HC([KL((e=>function(t){return jC(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(VC(xC({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),OF((e=>"a".concat(e.userId)))],WB.prototype,"_stopRemoteAudio",1),HC([OF("room")],WB.prototype,"_exitRoom",1),HC([OF("screen")],WB.prototype,"_stopScreenShare",1),HC([eB(...yF.TRTC.sendSEIMessage),rF({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}})],WB.prototype,"sendSEIMessage",1),HC([eB(yF.TRTC.sendCustomMessage),rF({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],WB.prototype,"sendCustomMessage",1),HC([eB(yF.TRTC.create)],WB,"_create",1);var jB=WB,KB=class{constructor(){GC(this,"_set",new Set),Fw.on(Hw.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 JB(){return jC(this,null,(function*(){let e,t;try{let t=yield IL();e=t&&t.length}catch(zw){}try{let e=yield AL();t=e&&e.length}catch(zw){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:s,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=Jw.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:n,vp8Decode:o},l={browser:a.browser,os:a.os,trtc:c,devices:i},d={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};IM.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),IM.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var qB=BC(KC()),zB="1",YB="2",XB="3",QB="4",ZB="5",$B="6",eH={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},tH=[eH.UPDATE_REMOTE_MUTE_STAT,eH.UPLINK_NETWORK_STATS,eH.USER_LIST_RES,eH.MUTE_RESULT,eH.SERVER_FIRST_PACKAGE_RECEIVED,eH.RECEIVE_CUSTOM_MSG],iH={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"},rH="publish_change",nH="join",sH="leave",oH="quality_report",aH="mute_uplink",cH="publish",lH="publish_state_change",dH="unpublish",uH="subscribe",hH="unsubscribe",pH="subscribe_change",mH="start_publishing",_H="stop_publishing",fH="start_push_user_cdn",gH="stop_push_user_cdn",TH="start_mcu_mix",EH="stop_mcu_mix",vH="start_publish_cdn_stream",yH="update_publish_cdn_stream",SH="stop_publish_cdn_stream",IH="get_user_list",AH="change_role",RH="update_constraint_config",CH="rebuild_pc",bH="join/v2",kH="publish/v2",DH="subscribe/v3",NH="ability_status_report",wH="reconnect",OH="channel_msg",PH=new Set;var MH=class extends qB.default{constructor(e){var t,i;super(),GC(this,"room"),GC(this,"url"),GC(this,"backupUrl"),GC(this,"race"),GC(this,"destroyed",!1),GC(this,"_socketInUse"),GC(this,"_socket"),GC(this,"_backupSocket"),GC(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0}),GC(this,"_currentState","DISCONNECTED"),GC(this,"_isReconnecting",!1),GC(this,"_seq",0),GC(this,"_log"),GC(this,"_lastMessageTime",-1),GC(this,"_connnectStartTime",-1),GC(this,"_stopConnectRetry"),GC(this,"bytesSent",0),GC(this,"bytesReceived",0),GC(this,"keepAlive",!1),GC(this,"signalDomainWhenUnifiedProxy"),GC(this,"stopKeepAliveTimeout"),GC(this,"rtt",0),this.room=e.room,this.race=!!cD(e.race)||e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,((null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0)-PH.size>0&&this.room.enableSPC&&(this.keepAlive=!0,PH.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=Ww.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));this.signalDomainWhenUnifiedProxy&&(e+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy)));let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+="&clientIp=".concat(t)),this.race?"".concat(e,"&race=1"):e}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return"CONNECTED"===this._currentState}get isConnecting(){return"CONNECTING"===this._currentState}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return jC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;return function*(){if(e.isConnected)return Promise.resolve();e._log.info("connect to [".concat(e.url,", ").concat(e.backupUrl,"]").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive))),e.emitConnectionStateChanged("CONNECTING"),e._connnectStartTime=yD();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 vD(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?Bb.BACKUP:Bb.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 s=-1;return new Promise(((e,t)=>{n.onclose=t,n.onerror=t,n.onopen=()=>e(n),i&&(s=setTimeout((()=>{this.unbindAndCloseSocket(r?Bb.MAIN:Bb.BACKUP),t(new nb({code:ib.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),i))})).finally((()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(s)}))}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===Bb.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(mk){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(mk){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn("".concat(e.target===this._socket?"main":"backup"," is closed code:").concat(e.code," ").concat(e.reason)),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||1e3!==e.code)&&this.startReconnection(),this.room.isJoining&&this.emit(ZB,new nb({code:ib.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(Bb.MAIN),this.unbindAndCloseSocket(Bb.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(ZB,new nb({code:ib.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=xD(e.data);let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values(eH),s=Object.keys(eH)[n.indexOf(i)],o=iH[s]||i;switch(tH.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),o&&this._log.info("Received event: [ ".concat(o," ]"))),i){case eH.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,r.svrTime&&function(e){sb=e-(new Date).getTime();let t=new Date;t.setTime(e),Ww.info("baseTime from server: ".concat(t," offset: ").concat(sb))}(r.svrTime),this._log.info("ChannelSetup Success ".concat(yD()-this._connnectStartTime)),aP.addSuccessEvent({key:521701,cost:yD()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(zB,{signalInfo:this._signalInfo});else{let e=new nb({code:ib.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:QO({key:qO.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),aP.addFailedEvent({key:521701,error:e}),this.emit(ZB,e)}break;case eH.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=r.relayOuterIp,this._signalInfo.relayInnerIp=r.relayInnerIp,this._signalInfo.relayPort=r.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=r.endReportExtend,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(o,{data:t});break;default:this.emit(String(o),{data:t})}}reGetSignalChannelUrl(){return jC(this,null,(function*(){try{if(!this.room.joinParams)return;HF(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(pb){}}))}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?Bb.MAIN:Bb.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return jC(this,null,(function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:i,relayInnerIp:r,relayPort:n}=this._signalInfo,{data:s}=yield this.sendWaitForResponse({command:wH,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:iH.CHANNEL_RECONNECT_RESULT});0===s.code?(this._log.warn("reconnect success"),this.stopReconnection(),aP.addSuccessEvent({key:521702,cost:yD()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(aP.addFailedEvent({key:521702,error:s.code}),this._log.warn("reconnect failed, ".concat(s.code," ").concat(s.message)),this.room.reJoin())}catch(pb){this._log.error(pb),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+=xD(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:s,enableLog:o=!0,addReceiveTime:a=!1}=e;return new Promise(((e,c)=>{let l=setTimeout((()=>{this.off(n,d);let e=new nb({code:ib.API_CALL_TIMEOUT,message:QO({key:qO.API_CALL_TIMEOUT,data:{commandDesc:s,command:t}})});o&&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 XD({retryFunction:this.sendWaitForResponse,onError:e=>{let{retry:t}=e;this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(XB,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),PH.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(Bb.MAIN),this.unbindAndCloseSocket(Bb.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(iH.JOIN_ROOM_RESULT,t)}),1e3*e);let t=e=>{0===e.data.code&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(iH.JOIN_ROOM_RESULT,t))};this.on(iH.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(YB,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(XB):"DISCONNECTED"===e&&this.emit($B))}};HC([RM({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())}})],MH.prototype,"connect",1);var LH=BC(KC()),xH=0,VH=!1,UH=new Set,FH=!1,BH=class{constructor(e){GC(this,"userId"),GC(this,"tinyId"),GC(this,"_sdpSemantics"),GC(this,"_isUplink"),GC(this,"_room"),GC(this,"_log"),GC(this,"_signalChannel"),GC(this,"_isErrorObserved",!1),GC(this,"_waitForPeerConnectionConnectedPromise"),GC(this,"_waitForPeerConnectionConnectedPromiseReject",null),GC(this,"_peerConnection",null),GC(this,"_emitter",new LH.default),GC(this,"_currentState","DISCONNECTED"),GC(this,"_isReconnecting",!1),GC(this,"_reconnectionCount",0),GC(this,"_reconnectionTimer",-1),GC(this,"_isFirstConnection",!0),GC(this,"_prevTime",-1),GC(this,"_localAddress"),GC(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=Ww.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=yD())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,aP.addSuccessEvent({key:521705,cost:Math.min(yD()-this._prevTime,3e4)})):this._isReconnecting&&aP.addSuccessEvent({key:521706,cost:yD()-this._prevTime}),this._prevTime=-1}catch(Qw){throw this._isFirstConnection?(this._isFirstConnection=!1,aP.addFailedEvent({key:521705,error:Qw})):this._isReconnecting&&this._reconnectionCount>=3&&aP.addFailedEvent({key:521706,error:Qw}),Qw}}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(),UH.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 nb({code:ib.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return lk;let e=null;if(this._isUplink){if(!OP()||0===this._peerConnection.getSenders().length)return lk;e=this._peerConnection.getSenders()[0].transport}else{if(!wP()||0===this._peerConnection.getReceivers().length)return lk;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:lk}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===dk.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===dk.FAILED||e.target.connectionState===dk.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new nb({message:r,code:ib.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===dk.CONNECTED||e.target.connectionState===dk.COMPLETED)&&(this.logSelectedCandidate(),IM.logSuccessEvent({userId:this._room.userId,eventType:fk.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(xH=0,VH=!1,FH=!0,UH.add(this)):UH.delete(this),Fw.emit(Hw.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return jC(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(AP(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(s),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(s),n(),t(new nb({code:ib.API_CALL_ABORTED,message:QO({key:qO.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{Fw.off(Hw.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},s=setTimeout((()=>{n();let e=new nb({code:ib.API_CALL_TIMEOUT,message:"connection timeout"});var i;xH+=1,i=this._signalChannel.isConnected,xH>2&&!VH&&0===UH.size&&i&&(this._log.warn("firewall restriction"),VH=!0,this._emitter.emit("firewall-restriction")),t(e)}),kk);Fw.on(Hw.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(XB,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=pk()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new nb({code:this._isUplink?ib.UPLINK_RECONNECTION_FAILED:ib.DOWNLINK_RECONNECTION_FAILED,message:QO({key:this._isUplink?qO.UPLINK_RECONNECTION_FAILED:qO.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",e),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this._reconnectionCount,"]")),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(XB,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)}};HC([ex(521712,!1)],BH.prototype,"setOffer",1),HC([ex(521713,!1)],BH.prototype,"setAnswer",1);var HH=BC($C()),GH=function(e){return HH.default.parse(e)},WH=function(e){return HH.default.write(e)};function jH(e){return Object.keys(e).filter((t=>e[t]))}var KH=class e extends BH{constructor(e){super(VC(xC({},e),{isUplink:!1})),GC(this,"_flag",0),GC(this,"isRobot",!1),GC(this,"role","anchor"),GC(this,"remoteAudioTrack"),GC(this,"remoteVideoTrack"),GC(this,"remoteAuxiliaryTrack"),GC(this,"ssrc",{audio:0,video:0,auxiliary:0}),GC(this,"_isSDPExchanging",!1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new PU(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new QU(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new ZU(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 CD(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===Bb.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===Zb?Bb.MAIN:Bb.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=Bb.AUDIO;i.kind===Bb.VIDEO&&(n=r===Bb.MAIN?Bb.VIDEO:Bb.AUXILIARY);let s=this.remoteAudioTrack;n===Bb.VIDEO?s=this.remoteVideoTrack:n===Bb.AUXILIARY&&(s=this.remoteAuxiliaryTrack),s.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=GH(e);return t.media.forEach((e=>{e.type===Bb.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),WH(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=GH(e);return i.media.forEach((e=>{e.ext&&(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),WH(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return jC(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===dk.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===dk.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(t," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else this.initialize(),yield this.connect(e)}catch(mb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(mb.message," ").concat(JSON.stringify(this.muteState))),new nb({code:ib.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):mb}}))}unsubscribe(e){return jC(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:r}=e;return function*(){if("CONNECTED"===t._currentState&&("main"===r&&!t.isMainStreamSubscribed||"auxiliary"===r&&!t.isAuxStreamSubscribed))return void t._log.info("".concat(r," stream already unsubscribed"));let e=xC({},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(jH(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=hH,n=iH.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=pH,n=iH.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 nb({code:i.code,message:QO({key:qO.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return jC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(t),yield e.waitForPeerConnectionConnected()}catch(mk){throw e.closePeerConnection(!0),mk}}()}))}exchangeSDP(e){return jC(this,null,(function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:i}=this._peerConnection.localDescription,r={type:t,sdp:i,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:uH,commandDesc:"exchange sdp",data:r,responseCommand:iH.SUBSCRIBE_RESULT,timeout:Ek});if(!this._peerConnection){let e=new nb({code:ib.INVALID_OPERATION,message:QO({key:qO.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(mk){throw this._isSDPExchanging=!1,mk}}))}createOffer(){return jC(this,null,(function*(){let e={voiceActivityDetection:!1};MP()&&this._sdpSemantics===vk?(this._peerConnection.addTransceiver(Bb.AUDIO,{direction:Hb.RECVONLY}),this._peerConnection.addTransceiver(Bb.VIDEO,{direction:Hb.RECVONLY}),this._peerConnection.addTransceiver(Bb.VIDEO,{direction:Hb.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield TP();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=GH(e);return t.media.forEach((e=>{var t,i;if(e.type===Bb.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(" ")}})),WH(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=GH(e);return t.media.forEach((e=>{e.type===Bb.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),WH(t)}(t.sdp),this._sdpSemantics===vk&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)}))}onSubscribeResult(e){return jC(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===Sk)throw new nb({code:ib.NOT_SUPPORTED_H264,message:QO({key:qO.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new nb({code:t,message:QO({key:qO.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(n)),yield this.setAnswer({type:r,sdp:n}),this.updateSSRC(n)}catch($w){throw this._log.error($w),$w}}))}updateSSRC(e){try{GH(e).media.forEach((e=>{if(e.ssrcs)if(e.type===Bb.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Zb)}));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(Zb)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes($b)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(mk){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return jC(this,null,(function*(){if(!(WC(e.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(mk){let t=sD(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}};HC([KL((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 nb({code:ib.API_CALL_ABORTED,message:QO({key:qO.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],KH.prototype,"subscribe",1),HC([ex(521717,!1)],KH.prototype,"unsubscribe",1),HC([WL(BH.prototype.afterConnect),GL(BH.prototype.beforeConnect)],KH.prototype,"connect",1);var JH=KH,qH={voiceActivityDetection:!1},zH=class e extends BH{constructor(e){super(VC(xC({},e),{isUplink:!0})),GC(this,"localMainAudioTrack",null),GC(this,"localMainVideoTrack",null),GC(this,"localAuxAudioTrack",null),GC(this,"localAuxVideoTrack",null),GC(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),GC(this,"_isPublishingAux",!1),GC(this,"_publishingLocalAudioTrack"),GC(this,"_publishingLocalVideoTrack"),GC(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}),GC(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 s=this._peerConnection.getSenders();s&&(PP()?(n.audio=!(null==(e=s[0])||!e.track),n.bigVideo=!(null==(t=s[1])||!t.track),n.smallVideo=!(null==(i=s[2])||!i.track),n.auxVideo=!(null==(r=s[3])||!r.track)):s.forEach((e=>{e.track&&(e.track.kind===Bb.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 s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:s,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:s,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:s,state:e}))),o}publish(e){return jC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){let e;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),r&&(t._publishingLocalVideoTrack=r),t._isPublishingAux=n,r&&!n&&r.small&&(e=t._room.videoManager.smallTrack),t.sendMediaSettings(),MP()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:e,isAuxiliary:n}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:r,smallTrack:e}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,n?(r&&(t.localAuxVideoTrack=r),i&&(t.localAuxAudioTrack=i)):(r&&(t.localMainVideoTrack=r),i&&(t.localMainAudioTrack=i)),t.installTrackMuteEvents(i,r),t.sendMutedFlag()}()}))}publishByTransceiver(e){return jC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n,isAuxiliary:s}=e;return function*(){t._log.info("publish by transceiver");let e=new MediaStream,o=null==r?void 0:r.outMediaTrack,a=null==i?void 0:i.outMediaTrack;a&&e.addTrack(a),o&&e.addTrack(o);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||Bb.AUDIO,{direction:Hb.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(s?Bb.VIDEO:o||Bb.VIDEO,{direction:Hb.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||Bb.VIDEO,{direction:Hb.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(s&&o||Bb.VIDEO,{direction:Hb.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:Bb.AUDIO})),o){let i=s?3:1;yield c[i].sender.replaceTrack(o),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:Bb.VIDEO,videoType:s?Bb.AUXILIARY:Bb.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:Bb.VIDEO,videoType:Bb.SMALL}),e.push(2))}yield t.setTransceiverDirection(Hb.SENDONLY,e),yield t.doPublishChange(),null==r||r.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),null==r||r.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()}))}publishByAddTrack(e){return jC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n}=e;return function*(){t._log.info("publish by addtrack");let e=null==r?void 0:r.outMediaTrack,s=null==i?void 0:i.outMediaTrack;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return i&&s&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(r)));let o=new MediaStream;if(s&&o.addTrack(s),e&&o.addTrack(e),s&&t._peerConnection.addTrack(s,o),e&&(t._peerConnection.addTrack(e,o),n)){let e=new MediaStream;e.addTrack(n),t._peerConnection.addTrack(n,e)}yield t.connect()}()}))}enableSmall(e){return jC(this,null,(function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(Hb.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Hb.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return jC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!PP())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,s=t._peerConnection.getSenders(),o=[];i&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localAuxAudioTrack&&!t.localMainAudioTrack&&(yield s[0].replaceTrack(null),o.push(0))),n&&(e?(yield s[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=VC(xC({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),o.push(3)):(yield s[1].replaceTrack(null),yield s[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=VC(xC({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),o.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.setTransceiverDirection(Hb.INACTIVE,o),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return jC(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:lH,data:t,responseCommand:iH.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:dH,commandDesc:"unpublish",responseCommand:iH.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===ib.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),HP){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:RH,data:this._mediaSettings,responseCommand:iH.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return jC(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Bb.AUXILIARY:Bb.MAIN," stream")),MP()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return jC(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Bb.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)&&i.small&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Hb.INACTIVE&&(yield this.setTransceiverDirection(Hb.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return jC(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;PP()&&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===Bb.VIDEO&&e instanceof cx&&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===yk||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=GH(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===Bb.VIDEO)return!0;return!1}removeSender(e){let t=null;PP()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&aD(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return jC(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?Bb.AUXILIARY:Bb.MAIN," stream")),MP()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return jC(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Bb.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(Hb.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return jC(this,null,(function*(){if(!mN)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 s=-1,o=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(Hb.INACTIVE,"|").concat(Hb.RECVONLY,"|").concat(Hb.SENDONLY,")")))&&s++,t.includes(s)){if(e===Hb.INACTIVE&&i.includes("a=".concat(Hb.RECVONLY)))return r=!0,"a=".concat(e);if(e===Hb.SENDONLY&&i.includes("a=".concat(Hb.INACTIVE)))return r=!0,"a=".concat(Hb.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:o}))}))}removeTrackBySender(e){return jC(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===Bb.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===Bb.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===Bb.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return jC(this,null,(function*(){var t;let i,r=null==(t=this._peerConnection)?void 0:t.getSenders();if(!r||0===r.length||!e.mediaTrack)return!1;if(i=MP()?e.kind===Bb.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?Bb.AUXILIARY:Bb.MAIN," stream")),e.kind===Bb.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===Bb.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack)),!0}))}updateOffer(e,t){return jC(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(qH);mN&&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===Bb.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 s=yield this._signalChannel.sendWaitForResponse({command:rH,data:n,responseCommand:iH.UPDATE_OFFER_RESULT,timeout:Tk,commandDesc:"update offer"}),{code:o,message:a}=s.data;0!==o&&this.checkPublishResultCode(o,a),yield this.acceptAnswer(s.data.data),i.sdp&&this.updateSSRC(i.sdp)}catch(Zw){throw this._log.error(Zw),Zw}}))}setBandwidth(e){return jC(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:s}=e;return function*(){if(!FP())return s?r===Bb.VIDEO?t.updateVideoBandwidthRestriction(s,i,n):t.updateAudioBandwidthRestriction(s,i):void 0;let e,o=t._peerConnection.getSenders();if(MP()){let t=0;r===Bb.VIDEO&&(t=n===Bb.SMALL?2:n===Bb.AUXILIARY?3:1),e=o[t]}else e=o.find((e=>e.track&&e.track.kind===r));if(e){let o=e.getParameters();(!o.encodings||0===o.encodings.length)&&(o.encodings=[{}]),o.encodings[0].maxBitrate=1e3*i;try{return yield e.setParameters(o),t._log.info("".concat(n||"").concat(r," bandwidth ").concat(i," kbps")),s}catch(a){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(a)),s)return r===Bb.VIDEO?t.updateVideoBandwidthRestriction(s,i,n):t.updateAudioBandwidthRestriction(s,i)}}return s}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";mN&&(r="TIAS",t*=1e3);let n=0,s=-1;return i===Bb.SMALL?n=1:i===Bb.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(s+=1,s===n?"".concat(e,"b=").concat(r,":").concat(t,"\r\n"):e)))}updateAudioBandwidthRestriction(e,t){let i="AS";return mN&&(i="TIAS",t*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,"m=audio $1\r\nc=IN $2\r\nb=".concat(i,":").concat(t,"\r\n"))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return jC(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(pb){throw this.closePeerConnection(!0),this.uninstallEvents(),pb}}))}exchangeSDP(){return jC(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(pb){throw pb}}))}createOffer(){return jC(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(qH);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(pb){throw pb}}))}doExchangeSDP(){let e={command:cH,responseCommand:iH.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof ux||this.localAuxVideoTrack instanceof ux,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=GH(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),WH(r)}acceptAnswer(e){return jC(this,null,(function*(){var t,i,r,n,s;try{let o;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),s=(null==(r=this._publishingLocalAudioTrack)?void 0:r.profile.bitrate)||(null==(n=this.localMainAudioTrack)?void 0:n.profile.bitrate);if(e){let t=this._isPublishingAux?Bb.AUXILIARY:Bb.BIG;o=yield this.setBandwidth({bandwidth:e,type:Bb.VIDEO,sdp:o,videoType:t})}s&&(o=yield this.setBandwidth({bandwidth:s,type:Bb.AUDIO,sdp:o}))}if(o=this.removeVideoOrientation(e.sdp),null!=(s=this._publishingLocalVideoTrack)&&s.small){let{smallStreamConfig:e}=this._room;o=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:Bb.VIDEO,videoType:Bb.SMALL,sdp:o})}let a={type:e.type,sdp:o};yield this.setAnswer(a),this._log.debug("accepted answer: ".concat(o))}catch(o){throw this._log.error("failed to accept remote answer ".concat(o)),o}}))}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(aH,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return jC(this,null,(function*(){if(!(WC(e.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:dH,responseCommand:iH.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(mk){let t=sD(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)&&Fw.emit(Hw.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{GH(e).media.forEach(((e,t)=>{if(e.type===Bb.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===yk&&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(mk){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Bb.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Bb.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Bb.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Bb.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Bb.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Sk?(this._log.error(zO.NOT_SUPPORTED_H264ENCODE),new nb({code:ib.NOT_SUPPORTED_H264,message:QO({key:qO.NOT_SUPPORTED_H264ENCODE})})):new nb({code:ib.UNKNOWN,message:QO({key:qO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:iH.PUBLISH_RESULT,code:e,message:t}})})}};HC([KL((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 nb({code:ib.API_CALL_ABORTED,message:QO({key:qO.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],zH.prototype,"publish",1),HC([ex(521715,!1)],zH.prototype,"unpublish",1),HC([WL(BH.prototype.afterConnect),GL(BH.prototype.beforeConnect)],zH.prototype,"connect",1);var YH=zH,XH=class{constructor(e,t){this.room=e,GC(this,"_log"),GC(this,"_prevReportTime",0),GC(this,"_prevReport",{}),GC(this,"_prevStats",null),GC(this,"_prevEncoderImplementation",""),GC(this,"_prevAuxEncoderImpl",""),GC(this,"_prevQualityLimitationReason",""),GC(this,"_prevAuxQualityLimitationReason",""),GC(this,"_prevDecoderImplementationMap",new Map),GC(this,"totalBytesSent",0),GC(this,"totalBytesReceived",0),GC(this,"_spcStats",null),this._log=t}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return jC(this,null,(function*(){var t;let i={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},r=e.getPeerConnection(),n=e.getSSRC();if(r)try{if((this._spcStats||(yield r.getStats())).forEach((t=>{var r,s,o;let a,c;if("outbound-rtp"===t.type)if((t.mediaType||t.kind)===Bb.VIDEO){if(t.ssrc===n.video?(a=Bb.VIDEO,c=e.localMainVideoTrack):t.ssrc===n.small?a=Bb.SMALL:t.ssrc===n.auxiliary&&(c=e.localAuxVideoTrack,a=Bb.AUXILIARY),!a)return;if(i[a].bytesSent=t.bytesSent,i[a].packetsSent=t.packetsSent,i[a].framesEncoded=t.framesEncoded,cD(t.keyFramesEncoded)||(i[a].keyFramesEncoded=t.keyFramesEncoded),cD(t.nackCount)||(i[a].nackCount=t.nackCount),cD(t.pliCount)||(i[a].pliCount=t.pliCount),cD(t.retransmittedPacketsSent)||(i[a].retransmittedPacketsSent=t.retransmittedPacketsSent),cD(t.totalEncodeTime)||(i[a].totalEncodeTime=t.totalEncodeTime),cD(t.totalPacketSendDelay)||(i[a].totalPacketSendDelay=t.totalPacketSendDelay),!cD(t.encoderImplementation)&&(a===Bb.VIDEO&&this._prevEncoderImplementation!==t.encoderImplementation||a===Bb.AUXILIARY&&this._prevAuxEncoderImpl!==t.encoderImplementation)){let i=2,r=this._prevEncoderImplementation;a===Bb.AUXILIARY&&(i=7,r=this._prevAuxEncoderImpl),Fw.emit("262",{userId:e.userId,streamType:i,prevImplementation:r,implementation:t.encoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientEncoder}),this[a===Bb.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=t.encoderImplementation,this._log.info("".concat(a===Bb.AUXILIARY?"aux ":"","encoderImplementation change to ").concat(t.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(t.powerEfficientEncoder))}t.ssrc===n.video?!cD(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),Fw.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&&!cD(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),Fw.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(s=e.localAuxVideoTrack)?void 0:s.isQosClearFirst}),this._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else i.audio.bytesSent=t.bytesSent,i.audio.packetsSent=t.packetsSent;else"candidate-pair"===t.type?AP(t)&&(this.totalBytesSent=t.bytesSent,dD(t.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*t.currentRoundTripTime))):"media-source"===t.type&&(t.kind===Bb.AUDIO?(i.audio.audioLevel=t.audioLevel||0,i.audio.totalAudioEnergy=t.totalAudioEnergy||0,t.echoReturnLoss,t.totalSamplesDuration&&(i.audio.totalSamplesDuration=t.totalSamplesDuration)):t.kind===Bb.VIDEO&&(t.trackIdentifier===e.getVideoTrackId(Bb.VIDEO)?i.video.fpsCapture=t.framesPerSecond:t.trackIdentifier===e.getVideoTrackId(Bb.AUXILIARY)?i.auxiliary.fpsCapture=t.framesPerSecond:i.small.fpsCapture=t.framesPerSecond));if(!cD(t.audioLevel)&&null!=(o=e.localMainAudioTrack)&&o.mediaTrack&&t.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(i.audio.audioLevel=t.audioLevel||0),!cD(t.frameWidth)){let r=Bb.SMALL;t.trackIdentifier===e.getVideoTrackId(Bb.VIDEO)||t.ssrc===n.video?r=Bb.VIDEO:(t.trackIdentifier===e.getVideoTrackId(Bb.AUXILIARY)||t.ssrc===n.auxiliary)&&(r=Bb.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===Bb.AUDIO?(e.localMainAudioTrack&&(e.localMainAudioTrack.stat=i[t]),e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=i[t])):t===Bb.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=i[t]):t===Bb.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=i[t])}))}catch(mb){this._log.warn("failed to getStats on sender connection ".concat(mb))}return 0===i.rtt&&(i.rtt=(null==(t=this.room.networkQuality)?void 0:t.uplinkRTT)||0),i}))}getReceiverStats(e){return jC(this,null,(function*(){var t,i,r;let n={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},s=e.getPeerConnection();if(s)try{let{ssrc:r}=e,{muteState:o,subscribeState:a}=e;(this._spcStats||(yield s.getStats())).forEach((t=>{if("inbound-rtp"===t.type){let i=(t.mediaType||t.kind)===Bb.AUDIO;if(i){if(t.ssrc!==r.audio||!o.hasAudio)return;n.audio.packetsReceived=t.packetsReceived,n.audio.bytesReceived=t.bytesReceived,n.audio.packetsLost=t.packetsLost,t.insertedSamplesForDeceleration&&(n.audio.insertedSamplesForDeceleration=t.insertedSamplesForDeceleration),t.removedSamplesForAcceleration&&(n.audio.removedSamplesForAcceleration=t.removedSamplesForAcceleration),t.totalSamplesDuration&&(n.audio.totalSamplesDuration=t.totalSamplesDuration),t.totalSamplesReceived&&(n.audio.totalSamplesReceived=t.totalSamplesReceived),t.concealedSamples&&(n.audio.concealedSamples=t.concealedSamples);let{remoteAudioTrack:i}=e;i.stat.packetsReceived=t.packetsReceived,i.stat.bytesReceived=t.bytesReceived,i.stat.packetsLost=t.packetsLost,n.audio.p2pDelay=i.stat.end2EndDelay,n.hasAudio=!0}else{if(mN&&0===t.bytesReceived)return;let i;t.ssrc===r.video&&o.hasVideo&&(n.video.packetsReceived=t.packetsReceived,n.video.bytesReceived=t.bytesReceived,n.video.packetsLost=t.packetsLost,n.video.framesReceived=t.framesReceived,n.video.framesDecoded=t.framesDecoded,n.video.fpsDecoded=t.framesPerSecond,n.hasVideo=!0,i=e.remoteVideoTrack,o.hasSmall&&a.smallVideo&&(n.isSmallSubscribed=!0),t.decoderImplementation&&(!this._prevDecoderImplementationMap.has(n.userId)||this._prevDecoderImplementationMap.get(n.userId)!==t.decoderImplementation)&&(this._log.info("".concat(n.userId," decoderImplementation change to ").concat(t.decoderImplementation," HWDecoder: ").concat(t.powerEfficientDecoder)),Fw.emit("262",{userId:this.room.userId,remoteUserId:n.userId,prevImplementation:this._prevDecoderImplementationMap.get(n.userId),implementation:t.decoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(n.userId,t.decoderImplementation))),t.ssrc===r.auxiliary&&o.hasAuxiliary&&(n.auxiliary.packetsReceived=t.packetsReceived,n.auxiliary.bytesReceived=t.bytesReceived,n.auxiliary.packetsLost=t.packetsLost,n.auxiliary.framesReceived=t.framesReceived,n.auxiliary.framesDecoded=t.framesDecoded,n.auxiliary.fpsDecoded=t.framesPerSecond,i=e.remoteAuxiliaryTrack,n.hasAuxiliary=!0),i&&(i.stat.packetsReceived=t.packetsReceived,i.stat.bytesReceived=t.bytesReceived,i.stat.packetsLost=t.packetsLost,i.stat.framesReceived=t.framesReceived,i.stat.framesDecoded=t.framesDecoded,t.jitterBufferDelay&&(i.stat.jitterBufferDelay=Math.floor(t.jitterBufferDelay/t.jitterBufferEmittedCount*1e3)))}t.jitterBufferDelay&&(i?(n.audio.totalJitter=t.jitterBufferDelay,n.audio.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.video&&o.hasVideo?(n.video.totalJitter=t.jitterBufferDelay,n.video.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.auxiliary&&o.hasAuxiliary&&(n.auxiliary.totalJitter=t.jitterBufferDelay,n.auxiliary.totalJitterCount=t.jitterBufferEmittedCount))}else"candidate-pair"===t.type&&AP(t)&&(this.totalBytesReceived=t.bytesReceived,dD(t.currentRoundTripTime)&&(n.rtt=Math.floor(1e3*t.currentRoundTripTime)));cD(t.frameWidth)||((t.trackIdentifier===e.getMainStreamVideoTrackId()||t.ssrc===r.video)&&(n.video.frameWidth=t.frameWidth,n.video.frameHeight=t.frameHeight,e.remoteVideoTrack.stat.frameWidth=t.frameWidth,e.remoteVideoTrack.stat.frameHeight=t.frameHeight),(t.trackIdentifier===e.getAuxStreamVideoTrackId()||t.ssrc===r.auxiliary)&&(n.auxiliary.frameWidth=t.frameWidth,n.auxiliary.frameHeight=t.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=t.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=t.frameHeight)),!cD(t.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&t.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(n.audio.audioLevel=t.audioLevel||0,n.audio.totalAudioEnergy=t.totalAudioEnergy||0)})),0===n.audio.audioLevel&&e.muteState.audioAvailable&&(n.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=n.audio.bytesReceived+n.video.bytesReceived+n.auxiliary.bytesReceived),cD(null==(t=e.remoteVideoTrack.player.stat)?void 0:t.fps)||(n.video.fpsRender=e.remoteVideoTrack.player.stat.fps),cD(null==(i=e.remoteAuxiliaryTrack.player.stat)?void 0:i.fps)||(n.auxiliary.fpsRender=e.remoteAuxiliaryTrack.player.stat.fps)}catch($w){this._log.warn("failed to getStats on receiver connection ".concat($w))}return 0===n.rtt&&(n.rtt=(null==(r=this.room.networkQuality)?void 0:r.uplinkRTT)||0),n}))}getStats(e,t){return jC(this,null,(function*(){let i={},r=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:i,receiverStats:r};let t=yD(),n=yield e.getStats(),s=yD();s-t>2e3&&this._log.warn("getStats cost ".concat(s-t,"ms"));let o=[],a=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);n.forEach((e=>a.has(e.type)&&o.push(e))),this._spcStats=o}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(xL(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(!xL(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*VO,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*VO),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:s}=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(ek)),n=i?i.duration:0,s={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.video.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.video.totalJitter,uint32_video_cache_ms_count:e.video.totalJitterCount};t.msg_video_status.push(s)}if(e.hasAuxiliary){let i=r.get("".concat(e.userId,"_").concat(tk)),n=i?i.duration:0,s={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.auxiliary.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.auxiliary.totalJitter,uint32_video_cache_ms_count:e.auxiliary.totalJitterCount};t.msg_video_status.push(s)}i.msg_down_stream_info.push(t)}));let o=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&&o.msg_up_stream_info.msg_audio_status){let e=o.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let r=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*r/s),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}null!=(n=o.msg_device_info)&&n.uint32_audio_capture_cost?i.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(o.msg_device_info.uint32_audio_capture_cost,i.msg_device_info.uint32_audio_capture_cost)/s):delete i.msg_device_info.uint32_audio_capture_cost}let c=o.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,o=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(r=t.uint32_video_codec_bitrate,n=t.uint32_video_enc_fps,o=t.uint32_video_codec_fps);let a=this.getDifferenceValue(r,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*a/s),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)/s),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_codec_fps)/s),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),cD(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),cD(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),cD(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),cD(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),cD(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/s)),cD(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/s))}));let l=o.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(xL(e.msg_audio_status)||xL(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 o=this.room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);o&&(o.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/s),i.uint32_audio_total_bitrate=Math.round(8*a/s)}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,o=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(o,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/s);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/s),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/s);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*s);if(n>1e3*s/5){let t=d.find((t=>t.msg_user_info.str_identifier===e.userId));t&&(t.msg_audio_status.uint32_audio_block_time=n)}}}})),i}getStatsReport(e){return jC(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:r,freezeMap:n}=e;return function*(){let e={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},s=yield t.getStats(i,r);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:s,report:e,freezeMap:n}),t._prevReportTime=Date.now(),e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},QH=BC(KC());function ZH(e){return new Promise((t=>jC(this,null,(function*(){let i=setTimeout((()=>{t({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})}),1e4),r=Date.now(),n="https://".concat(e,"/?t=").concat(r);try{yield fetch(n)}catch(mb){}clearTimeout(i);let s=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,s=r.fetchStart>0?Math.max(Math.round(r.domainLookupStart-r.fetchStart),0):0,o=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=VC(xC({},t),{totalCost:e,local:i,redirect:n,httpCache:s,dns:o,tcp:c,tls:a,request:l,response:d});break}}catch(i){}return t}(n);0===s.totalCost&&(s.totalCost=Date.now()-r),t(s)}))))}var $H=class e extends QH.default{constructor(e){let{signalChannel:t,room:i}=e;super(),GC(this,"_room"),GC(this,"_signalChannel"),GC(this,"_log"),GC(this,"uplinkRTT",0),GC(this,"uplinkLoss",0),GC(this,"downlinkRTT",0),GC(this,"downlinkLoss",0),GC(this,"pingResults",{}),GC(this,"_downlinkPrevStatMap",new Map),GC(this,"_downlinkLossAndRTTMap",new Map),GC(this,"_interval",-1),GC(this,"_uplinkNetworkQuality",0),GC(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=Ww.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(iH.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(YB,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 s=r.expectAudPkg+r.expectVidPkg,o=r.recvAudPkg+r.recvVidPkg,a=s-o;0===s&&0===o||(this.uplinkLoss=a<=0?0:Math.round(a/s*100),this.uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return jC(this,null,(function*(){if(0===this._room.remotePublishedUserMap.size)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],t=e.filter((e=>{var t;return(null==(t=e.getPeerConnection())?void 0:t.connectionState)===dk.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:s}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:s});continue}let o=0,a=this._downlinkPrevStatMap.get(e),c=r-a.totalPacketsLost,l=s-a.totalPacketsReceived;o=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:s}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:o,userId:t[n].getUserId(),audioDelay:t[n].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[n].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach((e=>{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:i,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=i,this.downlinkLoss=r,this.downlinkNetworkQuality=this.getNetworkQuality(r,i)}))}getStat(e){return jC(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!wP())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&&dD(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===Bb.AUDIO||e.mediaType===Bb.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return 0===t.rtt&&(t.rtt=this.uplinkRTT),t}catch(tO){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!==dk.DISCONNECTED&&e.connectionState!==dk.FAILED&&e.connectionState!==dk.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=gM.run("ric",(()=>{var t;this.handleDownlinkNetworkQuality();let i=[...this._downlinkLossAndRTTMap.values()];Fw.emit(Hw.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:i});let r=null==(t=this._room.scheduleResult.config)?void 0:t.pingDomainInfo,n={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};r&&(n=VC(xC({},n),{pingResults:this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold?this.pingResults:{}})),this.emit(e.EVENT_NETWORK_QUALITY,n);let s=Date.now();if(r&&(this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold)&&s-e.lastPingTime>1e3*r.interval){e.lastPingTime=Date.now();let t=r.domain.map((e=>ZH(e).then((t=>({domain:e,cost:t.totalCost})))));Promise.all(t).then((e=>{this.pingResults.isPoorNetwork=e.some((e=>e.cost>700)),this.pingResults.timestamp=s,this.pingResults.data=e,e.forEach((e=>{aP.addSuccessEvent({key:521718,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&&(gM.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,s=t.get(i);if(s){let e=this._room.remotePublishedUserMap.get(s);null==e||e.setDelay({videoDelay:r,audioDelay:n})}}))}};GC($H,"EVENT_NETWORK_QUALITY","0"),GC($H,"lastPingTime",0);var eG=$H;var tG=class{constructor(e){GC(this,"_frameWorkType"),GC(this,"_component"),GC(this,"_language"),GC(this,"connectionType"),GC(this,"_room"),GC(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0}),GC(this,"_keyPrefix"),GC(this,"_log"),GC(this,"_intervalId"),GC(this,"_firstPublishedUserList"),GC(this,"_networkQuality"),GC(this,"_basicInfo"),GC(this,"_pathJoinRoom"),GC(this,"_pathLeaveRoom"),GC(this,"_pathMainVideoMap"),GC(this,"_pathMainAudioMap"),GC(this,"_pathAuxiliaryMap"),GC(this,"_remoteStreamStatMap"),GC(this,"_localStreamStat"),GC(this,"_eventMap",new Map),GC(this,"_captureCostSum",0),GC(this,"_captureCostCount",0),GC(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=Ww.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&aD(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 s=t.apply(i,r);return fD(s)?s.catch((e=>Ww.error("".concat(t.name,"() error observed ").concat(e)))):s}catch(mk){Ww.error("".concat(t.name,"() error observed ").concat(mk))}}}({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:ub,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,Nw().then((e=>{this._basicInfo.string_os_version=Lw(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),Fw.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(Hw.JOIN_START,this.handleJoinStart).addEvent(Hw.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(Hw.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(Hw.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(Hw.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(Hw.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(Hw.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(Hw.JOIN_FAILED,this.handleJoinFailed).addEvent(Hw.LEAVE_START,this.handleLeaveStart).addEvent(Hw.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(Hw.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(Hw.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(Hw.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(Hw.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(Hw.PUBLISH_START,this.handlePublishStart).addEvent(Hw.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(Hw.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(Hw.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(Hw.PLAY_TRACK_START,this.handlePlayStart).addEvent(Hw.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(Hw.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!t.isRemote||!this.hitTest(t.room)||"PLAYING"===i&&(r===Bb.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(Hw.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(Hw.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(Hw.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(Hw.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,s=i.hasAuxiliary,o=r.hasAudio||r.hasVideo||r.hasSmall,a=r.hasAuxiliary;!n&&o&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")})).addEvent(Hw.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("pagehide",this.handleUnload),this._eventMap.forEach(((e,t)=>Fw.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),gM.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&&(cD(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),cD(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),cD(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:s,request:o,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=s,this._pathJoinRoom.int32_schedule_request=o,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 nb?Number(i.getExtraCode()||i.getCode()):ib.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}handleJoinFailed(e){let{room:t,error:i}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=i.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout((()=>{this.report()})))}handleReceivedPublishUserList(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(e,t){var i;let r="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(r)){let n={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:VC(xC({},rG),{msg_user_info:new nG({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:s,tinyId:o,role:a}=i,c=new nG({userId:s,tinyId:o,role:"anchor"===a?20:21}),l=Date.now(),d="".concat(s,"_").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:s,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:s,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(!t.isRemote||!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(!t.isRemote||!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(n){let{statsToReport:t}=n;if(t.uint32_video_render_first||"main"!==e.streamType?this.hasAuxFlag(e.userId):this.hasVideoFlag(e.userId)){let e=i-this._pathJoinRoom.uint64_start_time;t.uint32_video_render_first=e,aP.addNumber({key:516820,value:e})}}0===(null==r?void 0:r.statsToReport.uint64_render_first_frame_time)&&(r.statsToReport.uint64_render_first_frame_time=i)}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:s}=e,o=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(o)o.totalRTT+=t,o.totalLoss+=i,n&&(o.totalVideoDelay=(o.totalVideoDelay||0)+n,o.videoDelayCount=(o.videoDelayCount||0)+1),s&&(o.totalAudioDelay=(o.totalAudioDelay||0)+s,o.audioDelayCount=(o.audioDelayCount||0)+1),o.count++;else{let e,o,a,c;n&&(o=n,a=1),s&&(e=s,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:o,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/VO*100)>0&&(this._localStreamStat.totalAudioLevel+=e/VO,this._localStreamStat.audioLevelCount++)}r.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:r}=e,n=t.str_identifier,s=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"),o=this._remoteStreamStatMap.get(r);if(o&&(t&&null!=s&&s.remoteVideoTrack.isSubscribed||i&&null!=s&&s.remoteAuxiliaryTrack)){o.totalVideoFPS+=e.uint32_video_receive_fps,o.totalVideoBitrate+=e.uint32_video_codec_bitrate,o.videoCount++,0===o.statsToReport.uint32_video_width&&(o.statsToReport.uint32_video_width=e.uint32_video_width),0===o.statsToReport.uint32_video_height&&(o.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?s.remoteVideoTrack:s.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(o.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(o.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*MC(10,6)))}})),!RD(i)){let e="".concat(n,"_main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&null!=s&&s.remoteAudioTrack.isSubscribed&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,s.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=s.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/VO*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/VO,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 nb?i.getExtraCode()||i.getCode():ib.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&jb))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&qb))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Jb))>=0}hitTest(e){return e===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach(((e,t)=>{let{userId:i}=e,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(r){let{totalLoss:t,count:i,audioDelayCount:n,videoDelayCount:s,totalAudioDelay:o,totalVideoDelay:a}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),n&&o&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(o/n),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),s&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/s))}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,Bb.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,Bb.VIDEO)),e.statsToReport.uint32_video_render_first&&(e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,iG));let{badCaseDetector:s}=this._room,{dataFreeze:o,count:a}=s.getDataFreezeDuration(t),{renderFreeze:c}=s.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=a,e.statsToReport.uint32_video_block_time=Math.min(o,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),s.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})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>iG&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+iG):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>iG&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+iG):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>iG&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+iG)}getReportData(){this._basicInfo.uint32_networkType=Yk();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new nG({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:kD(this._signalInfo.relayIp),uint32_client_ip:kD(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*MC(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:kD(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return BD(e),e}report(){return jC(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(Qw){this._log.warn(Qw)}finally{this.isDestroyed&&(this._room=null)}}))}upload(e){return jC(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=yield jD(e),r=i instanceof ArrayBuffer,n="".concat(jk(t,Nb.KEY_POINT),"&gzip=").concat(+r),s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(n,i));let o=[this.uploadKVStat(aP),this.uploadKVStat(oP)];s||o.push(WD({url:n,body:i,priority:"low"})),yield Promise.all(o)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return jC(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=VC(xC({},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 jD(t),r="".concat(jk(+this._room.sdkAppId,Nb.KV_STAT),"&gzip=").concat(+(i instanceof ArrayBuffer)),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(r,i)),n||WD({url:r,body:i})}))}};HC([RM({settings:{timeout:500,retries:3}})],tG.prototype,"upload",1);var iG=5e3,rG={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_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},nG=class{constructor(e){GC(this,"str_identifier"),GC(this,"str_tinyid"),GC(this,"uint32_role"),this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},sG=tG,oG=class{constructor(){GC(this,"_startTime"),GC(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=yD())}stop(){0===this._endTime&&(this._endTime=yD())}getDuration(){return 0===this._endTime?yD()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},aG=class{constructor(e){GC(this,"_room",null),GC(this,"_durationMap"),GC(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(Hw.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(Hw.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(Hw.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;var n;let{userId:s}=r;if(!this.hitTest(t))return;i.hasAudio&&!r.hasAudio&&this.stopDurationItem("".concat(s,"_main"),Bb.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(s,"_main"),Bb.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(s,"_auxiliary"),Bb.VIDEO);let o=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(s);o&&(!i.hasAudio&&r.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,Bb.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,Bb.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,Bb.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>Fw.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>Fw.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{track:t}=e;if(!this.hitTest(t.room))return;let{userId:i,streamType:r,kind:n}=t;t.isSubscribed?this.addDuractionItem(i,n,r):this.stopDurationItem("".concat(i,"_").concat(r),n)}handleUnsubscribed(e){let{track:t}=e;this.hitTest(t.room)&&this.stopDurationItem("".concat(t.userId,"_").concat(t.streamType),t.kind)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new oG,s=this._durationMap.get(r);s?this.isRecording(s[t])||s[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===Bb.AUDIO?[n]:[],video:t===Bb.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()}},cG=class{constructor(e){GC(this,"_room"),GC(this,"_renderFreezeMap",new Map),GC(this,"_isVideoPlayingEventFiredMap",new Map),GC(this,"_dataFreezeMap",new Map),GC(this,"_monitorFreezeData",new Map),GC(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(Hw.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(Hw.PLAY_TRACK_START,this.onPlayTrackStart).set(Hw.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,s="".concat(n,"_").concat(i);this.stopDataFreeze({key:s,userId:n,type:i})})).set(Hw.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(Hw.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(t.isRemote&&t.room&&this.hitTest(t.room)&&n===Bb.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===Bb.MUTE?this.onVideoTrackMuted(t):r===Bb.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(Hw.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>Fw.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>Fw.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),s=new oG;n?n.durationItemList.push(s):this._dataFreezeMap.set(r,{userId:t,type:i,durationItemList:[s],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 s=n.durationItemList[n.durationItemList.length-1];s.stop();let o=s.getDuration();o>Ak?this._monitorFreezeData.set(t,{userId:i,type:r,duration:o}):n.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return jC(this,arguments,(function(e){var t=this;let{userId:i,fps:r,type:n}=e;return function*(){let e="".concat(i,"_").concat(n),s=t._renderFreezeMap.get(e);if(r<=2){let r=yD();s&&!s.isFreeze&&(s.freezeTimeline.push({startTime:r,endTime:0}),s.isFreeze=!0),s||t._renderFreezeMap.set(e,{userId:i,type:n,isFreeze:!0,freezeTimeline:[{startTime:r,endTime:0}],renderFreezeTotal:0})}else if(s&&s.isFreeze){s.isFreeze=!1;let e=s.freezeTimeline.pop();if(e){e.endTime=yD();let t=e.endTime-e.startTime;s.freezeTimeline.push(e),s.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room)||t.kind!==Bb.VIDEO||!t.isRemotePublished)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()<Ak&&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=yD()-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()}},lG=BC(KC(),1),dG=[1,0,0,0,1,1,0,1],uG=class extends xU{constructor(e,t){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:t}),e instanceof YU)try{this.setTexBuffer(dG)}catch(mk){e.destroy(new nb({code:ib.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(mk.message||mk)}))}}draw2d(e,t,i,r,n){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let s=super.draw2d(e,t,i,r,n);return this.ctx2d.restore(),s}return!1}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}},hG=class{constructor(e,t){this.node=e,this.layout=t,GC(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}},pG=class extends xU{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),GC(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new hG(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 YU&&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:s}=this,o=Date.now(),a=(e-this.lastInfo.totalFrames)/((o-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:i,width:r,height:n,timestamp:o,fps:a,name:s},xC({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 YU))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(tO){}}))}},mG=class extends KU{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log}),GC(this,"_bgTexture"),GC(this,"_waterMarkTexture"),GC(this,"_lastMaskTexture"),GC(this,"_lastMaskFbo"),GC(this,"_textureValid",!1),GC(this,"_selfieTextureValid",!1),GC(this,"_selfieSegmentation"),GC(this,"wasm"),GC(this,"_prePrograme"),GC(this,"_segmentationMask"),GC(this,"_weixin",!1),t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(t)}catch(Zw){e.log.error(Zw),e.destroy(new nb({code:ib.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(Zw.message||Zw)}))}}init(e){let t=e.Wasm,i=this.context.ctx;if(this.wasm=new t.AllIn1(i),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:i,width:r,height:n}=e.waterMark;this.wasm.setWaterMark(t,i,r,n)}if(e.beautyParams){let{beauty:t,brightness:i,ruddy:r}=e.beautyParams;this.wasm.setBeauty(t,i,r,null==e?void 0:e.width,null==e?void 0:e.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),i.uniform1i(i.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(i.uniform1i(i.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(i.uniform1i(i.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),i.uniform1i(i.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(i.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\nuniform sampler2D u_texture;\nuniform sampler2D mask;\n\nin vec2 v_texCoord;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);\n}"),t=this.context.createShader(i.VERTEX_SHADER,"#version 300 es\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_texCoord;\nvoid main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n v_texCoord = a_texCoord;\n}");this._prePrograme=this.context.createProgram(t,e),i.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),i.uniform1i(i.getUniformLocation(this._prePrograme,"mask"),1)}}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 s=this.context.ctx,{image:o}=this;this.tryVideoFrameCallback(o);let{videoWidth:a,videoHeight:c}=o;if(0===a||0===c)return!1;o.width=a,o.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?s.texSubImage2D(s.TEXTURE_2D,0,0,0,s.RGBA,s.UNSIGNED_BYTE,o):(this.resize(a,c),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,o)),this._weixin&&(s.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(s.activeTexture(s.TEXTURE1),null==(i=this._selfieSegmentation)||i.bindTexture2d(this._segmentationMask),s.bindFramebuffer(s.FRAMEBUFFER,this._lastMaskFbo||null)),s.drawArrays(s.TRIANGLE_STRIP,0,4),null==(r=this._selfieSegmentation)||r.bindTexture(),this._segmentationMask?s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,0,0,a,c):s.copyTexImage2D(s.TEXTURE_2D,0,s.RGBA,0,0,a,c,0)),null==(n=this._selfieSegmentation)||n.send(a,c),this.totalFrames||(s.activeTexture(s.TEXTURE2),s.bindTexture(s.TEXTURE_2D,this._bgTexture||null),s.activeTexture(s.TEXTURE3),s.bindTexture(s.TEXTURE_2D,this._waterMarkTexture||null),s.drawArrays(s.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()}},_G=class extends xU{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:"\n precision highp float;\n uniform sampler2D ySampler;\n uniform sampler2D uSampler;\n uniform sampler2D vSampler;\n varying highp vec2 textureCoord;\n const mat4 YUV2RGB = mat4(\n 1.1643828125, 0, 1.59602734375, -.87078515625,\n 1.1643828125, -.39176171875, -.81296875, .52959375,\n 1.1643828125, 2.017234375, 0, -1.081390625,\n 0, 0, 0, 1);\n void main() {\n vec3 yuv;\n yuv.r = texture2D(ySampler, textureCoord).r;\n yuv.g = texture2D(uSampler, textureCoord).r;\n yuv.b = texture2D(vSampler, textureCoord).r;\n gl_FragColor = vec4(yuv,1) * YUV2RGB;\n }\n ",vertexShaderSource:"\n attribute vec4 vertexPos;\n attribute vec2 texturePos;\n varying vec2 textureCoord;\n void main() {\n gl_Position = vertexPos;\n textureCoord = texturePos;\n }"}),GC(this,"yTextureRef"),GC(this,"uTextureRef"),GC(this,"vTextureRef"),GC(this,"Y"),GC(this,"U"),GC(this,"V"),this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let i=this.context.ctx,r=i.createTexture();return i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_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.bindTexture(i.TEXTURE_2D,null),i.uniform1i(i.getUniformLocation(this.program,e),t),r}render(e){let t=this.context.ctx,i=this.width,r=this.height;return this.useProgram(),t.viewport(0,0,i,r),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,i,r,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,i/2,r/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,i/2,r/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let i=this.context.ctx;i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,this.yTextureRef),i.texImage2D(i.TEXTURE_2D,0,i.LUMINANCE,e,t,0,i.LUMINANCE,i.UNSIGNED_BYTE,null),i.activeTexture(i.TEXTURE1),i.bindTexture(i.TEXTURE_2D,this.uTextureRef),i.texImage2D(i.TEXTURE_2D,0,i.LUMINANCE,e/2,t/2,0,i.LUMINANCE,i.UNSIGNED_BYTE,null),i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,this.vTextureRef),i.texImage2D(i.TEXTURE_2D,0,i.LUMINANCE,e/2,t/2,0,i.LUMINANCE,i.UNSIGNED_BYTE,null)}},fG=[e=>{e.codec="avc1.420028"},e=>{delete e.hardwareAcceleration}],gG=(e,t)=>{switch(e){case"webCodecs":return"videoFrame"===t?514705:514706;case"wasm":return"webgl"===t?514707:"videoFrame"===t?514708:514709}throw new Error("decoder type not supported")},TG=0,EG=class{constructor(e){GC(this,"id",TG++),GC(this,"trackDoneOB"),GC(this,"startOB"),GC(this,"stopOB"),GC(this,"decoder"),GC(this,"videoContext"),GC(this,"gop",0),GC(this,"gop_helper",0),GC(this,"waitFirstKeyFrame",!0),GC(this,"startTimestamp",0),GC(this,"startTime",0),GC(this,"startPerformanceTime",0),GC(this,"inputFrameCount",0),GC(this,"decodedFrameCount",0),GC(this,"downgradeLevel",0),GC(this,"config"),GC(this,"gop_before_configure",[]),GC(this,"videoElement"),GC(this,"type","wasm"),GC(this,"goodType","webCodecs"),GC(this,"renderer","2d"),GC(this,"wasmOption"),GC(this,"createDecoder"),GC(this,"_decodeSink"),GC(this,"isReported",!1),GC(this,"track"),GC(this,"stateChangeOB"),GC(this,"failedReason");let{track:t,createDecoder:i}=e;if(this.stateChangeOB=Xx(),this.track=t,this.createDecoder=i,this.wasmOption={yuvMode:"webgl"===e.renderer,wasmPath:e.wasmPath,workerMode:e.workerMode,canvas:e.canvas},this.config=e.config,this.videoElement=e.videoElement,this.renderer=e.renderer,this.trackDoneOB=oV(t.availableState,uM.OFF),this.stopOB=Xx(this.trackDoneOB),"auto"===e.type){switch(e.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode="webgl"===this.renderer}else this.type=e.type;this.changeRenderer(this.renderer),Dx(this.stateChangeOB,XV(((e,i)=>(e!==i&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:e,state:i}),i)),"INITIALIZED"),kV(this.stopOB),bU()),this.start()}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=Dx(this.pipe(this.track),kV(this.stopOB),Vx());Dx(t,bU((()=>{this.track.stat.framesDecoded++}),(t=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(t," retryCount: ").concat(e)),aP.addFailedEvent({key:gG(this.type,this.renderer),error:t}),e>4)this.failedReason=t,this.stateChangeOB.next("FAILED");else{if(this.goodType)return void this.start(e);switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":if("webgl"===this.renderer)this.changeRenderer("videoFrame")}this.start(e+1)}}),(()=>{this.track.log.warn("".concat(this.id," decoderOB completed")),aP.addSuccessEvent({key:gG(this.type,this.renderer)}),aP.addSuccessEvent({key:514704})}))),Dx(t,bV(1),bU((()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")})))}mock(e){this._decodeSink?this._decodeSink.error(e):this.start()}close(e){this.stopOB.next(e)}changeRenderer(e){this.renderer=e,"videoFrame"===this.renderer&&!fP()&&(this.renderer="2d"),this.wasmOption.yuvMode="webgl"===this.renderer}decode(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i;if(this.failedReason)return;let r=!1;switch(31&new Uint8Array(e.data)[4]){case 5:case 7:r=!0}if(this.inputFrameCount++,"configured"!==(null==(i=this.decoder)?void 0:i.state))return this.track.log.debug("not configured ".concat(this.inputFrameCount)),r&&(this.gop_before_configure=[]),this.gop_before_configure.push(xC({},e)),e;this.gop_before_configure.length>0&&!t&&(this.gop_before_configure.forEach((e=>{this.decode(e,!0)})),this.gop_before_configure=[]);let{timestamp:n}=e;if(r?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!r)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount));this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=yD()}let t=(n-this.startTimestamp)/90,i=Date.now()-this.startTime-t;switch(r&&((i<500?0:i/1e3|0)>0?this.downgradeLevel++:this.downgradeLevel>3&&this.downgradeLevel--),this.downgradeLevel){case 0:case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}return this.inputFrameCount<10&&this.track.log.debug("decode ".concat(this.inputFrameCount," ").concat(this.downgradeLevel," ").concat(this.gop_helper," ").concat(this.gop)),void this.decoder.decode(e)}return e}pipe(e){return t=>jC(this,null,(function*(){this._decodeSink=t,t.defer((()=>{var e,t;null==(e=this.decoder)||e.close(),null==(t=this.videoContext)||t.destroy(),delete this._decodeSink}));let{renderer:i,type:r}=this;e.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(r){case"wasm":this.decoder=this.createDecoder(r,this.wasmOption);break;case"webCodecs":for(let e=0;e<=fG.length;e++){let{supported:i}=yield VideoDecoder.isConfigSupported(this.config);if(i)break;if(e===fG.length)return void t.error(3);fG[e](this.config)}this.decoder=this.createDecoder(r);break;case"mse":throw new Error("not supported yet")}if(this.decoder.on("videoFrame",(e=>{this.decodedFrameCount++,t.next(e)})),this.decoder.on("error",(i=>{e.log.error(i),t.error("webCodecs"===r?4:8)})),yield this.decoder.initialize(this.videoElement),this.decoder.configure(this.config),"wasm"===r&&"webgl"===i){this.videoContext=new YU({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(YU.UNAVAILABLE,(i=>{e.log.error(i),t.error(7)}));let i=new _G(this.videoContext);this.decoder.on("videoCodecInfo",(e=>i.resize(e.width,e.height))),this.decoder.on("videoFrame",(e=>{[i.Y,i.U,i.V]=e,1===this.downgradeLevel?this.decodedFrameCount%2==0&&i.render(this.decodedFrameCount):i.render(this.decodedFrameCount)})),e.source=i,e.player.setCanvas(this.videoContext._canvas,2)}else if("videoFrame"===i){e.player.setCanvas();let i=new MediaStreamTrackGenerator({kind:"video"}),r=i.writable.getWriter();e.setInputMediaStreamTrack(i);let n=0;this.decoder.on("videoFrame",(t=>{n++,n<=10&&e.log.info("Frame ".concat(n," decoded width: ").concat(t.displayWidth," height: ").concat(t.displayHeight)),r.write(t)})),t.defer((()=>i.onmute=null))}else{this.videoContext=new XU({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create({alpha:!1});let t=this.videoContext.createVideoImageSource();this.decoder.on("videoFrame",(e=>{t.image=e,t.update()}));let i=new FU(this.videoContext,{name:"remotePlayer",logger:e.log});t.connect(i),e.source=t,e.player.setCanvas(this.videoContext._canvas,2)}}catch(tO){e.log.error(tO),t.error("webCodecs"===r?2:6)}}))}},vG=class extends lG.EventEmitter{constructor(e){super(),this.room=e,GC(this,"videoContext"),GC(this,"_glVideoContext"),GC(this,"_2dVideoContext"),GC(this,"destination"),GC(this,"smallVideoContext"),GC(this,"smallDestination"),GC(this,"smallTrackSource"),GC(this,"smallImageSource"),GC(this,"_isMirror",!1),GC(this,"cameraTrack"),GC(this,"cameraNode"),GC(this,"mirrorNode"),GC(this,"mixNode"),GC(this,"screenTrack"),GC(this,"screenNode"),GC(this,"selfModel",!1),GC(this,"blurRadius",3),GC(this,"arTrack"),GC(this,"Wasm"),GC(this,"waterMarkNode"),GC(this,"_waterMarkOption"),GC(this,"watermarkImageList",[]),GC(this,"_beautyParams"),GC(this,"isUsingArTrack",!1),GC(this,"_isMixScreen",!1),GC(this,"_virtualBackground"),GC(this,"_virtualBackgroundAbortCallback"),GC(this,"virtualBackgroundInstance"),GC(this,"_bgAssetPath"),GC(this,"log",Ww.createLogger({id:"vm"})),GC(this,"_checkId",0),GC(this,"_use2d",!1),GC(this,"_autoSwitchRenderMode",!0),GC(this,"_selfieSegmentation"),GC(this,"encodePipeline",[]),GC(this,"decodePipeline",[]),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new XU({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 XU({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 YU({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((e=>{this.log.error(e)}))}))}catch(pb){this.emit("error",pb)}}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=gM.run("interval",(()=>{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(),gM.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(fw||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?aP.addFailedEvent({key:t,error:e}):aP.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 YU({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:s}=i;r?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new GU(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),fw&&s.setCanvas(e);let o=e&&(null==(t=this.destination)?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),o=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info("set main output ".concat(o?o.label:"no output track")),i.setOutputMediaStreamTrack(o)}catch(Zw){this.log.error("set main output failed",Zw)}}update(){return jC(this,null,(function*(){var e,t;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:i,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),16===vw?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof KU?(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 KU?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 HU(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new mG(this.videoContext,{input:this.cameraTrack.mediaTrack,width:i.width,height:i.height,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 uG(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 pG(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 ux)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof cx)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof QU){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);let t=e.mediaTrack;return e.setOutputMediaStreamTrack(t)}this.log.warn("change unknown input",null==(n=e.mediaTrack)?void 0:n.label)}removeInput(e){var t;e instanceof ux?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof cx?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof QU&&e.source&&e.source.context.destroy()}setCameraTrack(e){return jC(this,null,(function*(){this.cameraTrack=e,this.update()}))}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return jC(this,null,(function*(){let i=document.createElement("canvas");t&&e&&(i.height=t,i.width=e);let r=i.getContext("2d");if(!r)throw new nb({code:ib.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort(((e,t)=>e.zIndex-t.zIndex)),this.watermarkImageList.forEach((e=>{let{image:t,x:i,y:n,width:s,height:o}=e;r.drawImage(t,i,n,s,o)})),UD(i.toDataURL())}))}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some((t=>t.imageUrl===e.imageUrl&&t.height===e.height&&t.width===e.width&&t.x===e.x&&t.y===e.y&&t.type===e.type&&t.zIndex===e.zIndex))||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==t))),this.watermarkImageList.push(e))}setBeautyParams(e){return jC(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return jC(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return jC(this,null,(function*(){var t,i;let r;try{r=yield UD((null==e?void 0:e.imageElement)||e.imageUrl)}catch(d){throw new nb({code:ib.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:n=0,y:s=0,width:o=r.width,height:a=r.height,type:c="watermark",zIndex:l=2}=e;this.watermarkImageList.some((e=>e.type===c))?(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==c)),this.pushWaterMarkImageList({x:n,y:s,width:o,height:a,image:r,zIndex:l,type:c,imageUrl:e.imageUrl}),r=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(i=this.cameraTrack)?void 0:i.settings.height),this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(r.width,r.height),this.waterMarkNode.image=r):this.update()):(this.pushWaterMarkImageList({x:n,y:s,width:o,height:a,image:r,zIndex:l,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,((e,t)=>"imageUrl"===e?void 0:t)))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return jC(this,null,(function*(){this.watermarkImageList=this.watermarkImageList.filter((t=>t.type!==e)),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,((e,t)=>"imageUrl"===e?void 0:t))),yield this.freshWatermark()}))}freshWatermark(){return jC(this,null,(function*(){var e,t,i;null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let r=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(i=this.cameraTrack)?void 0:i.settings.height);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()}))}setVirtualBackground(e){return jC(this,null,(function*(){if(e){if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,"image"===e.type?this._virtualBackground=yield UD(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 nb({code:ib.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})}))}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return jC(this,null,(function*(){var e;null!=(e=this.cameraTrack)&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))}))}disableAr(){var e;this.isUsingArTrack=!1,null==(e=this.arTrack)||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new EG(e)}clear(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(e){let{processor:t,type:i}=e;var r;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:i}=e;var r;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}};HC([jL((function(e){this.log.error("update failed",e)}))],vG.prototype,"update",1);var yG=0,SG=class extends uM{constructor(e){super("room"),GC(this,"seq",++yG),GC(this,"sdkAppId"),GC(this,"userId"),GC(this,"userSig"),GC(this,"privateMapKey"),GC(this,"latencyLevel"),GC(this,"tinyId"),GC(this,"scene"),GC(this,"roomId"),GC(this,"useStringRoomId"),GC(this,"role","anchor"),GC(this,"joinParams",null),GC(this,"localTracks",new Set),GC(this,"enableAutoPlayDialog",!0),GC(this,"autoReceiveAudio",!0),GC(this,"autoReceiveVideo",!0),GC(this,"proxy_ws"),GC(this,"proxy_wt"),GC(this,"proxy_unified"),GC(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}}),GC(this,"keyPointManager"),GC(this,"audioManager"),GC(this,"videoManager"),GC(this,"callDurationCalculator"),GC(this,"badCaseDetector"),GC(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),GC(this,"videoDecodeFallbackType"),GC(this,"_isUsingCachedSchedule",!1),GC(this,"_log",Ww.createLogger({id:"r".concat(this.seq)})),GC(this,"_joinedTimestamp",0),GC(this,"_sdkType"),GC(this,"heartbeatReport"),GC(this,"quality"),GC(this,"enableSEI"),GC(this,"isDestroyed",!1),this.useStringRoomId=!!e.useStringRoomId,uD(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),uD(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),uD(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new sG({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new aG({room:this}),this.badCaseDetector=new cG({room:this}),this.audioManager=new fx(this),this.videoManager=new vG(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(4&e.mediaType)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(2&e.mediaType)return e;return null}getLogger(){return this._log}get isJoining(){return"joining"===this.state.toString()}get isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return jC(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return jC(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return jC(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(lD(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(rD(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:r,scheduleProxy:n,unifiedProxy:s}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=s,s?(jF([s,s]),Eb("https://".concat(s))):(r&&Eb(r),n&&jF(n))}Fw.once(Hw.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:WF.main,sched_back_domain:WF.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return jC(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return jC(this,null,(function*(){var e;let t={rtt:(null==(e=this.quality)?void 0:e.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let i of this.quality.downlinkInfo)t.downlinksRTT[i.userId]=i.rtt;return t}))}getRemoteVideoStats(){return jC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"main";return function*(){let i={};return e.remotePublishedUserMap.forEach((e=>{let r="auxiliary"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;i[e.userId]=r.stat})),i}()}))}checkDestroy(){if(this.isDestroyed)throw new nb({code:ib.INVALID_OPERATION,message:QO({key:qO.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(zO.INVALID_DESTROY),new nb({code:ib.INVALID_OPERATION,message:QO({key:qO.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,Fw.emit(Hw.ROOM_DESTROY,{room:this})}schedule(e,t){return jC(this,null,(function*(){var i,r,n;let s=yD();try{let{isCached:o,result:a,detailCost:c}=yield GF({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:ub,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(MD(a,{keysToExclude:["username","credential"]}))),o&&Fw.once(Hw.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=xC(xC({},this.scheduleResult),a),dD(null==(i=a.config)?void 0:i.retryCount)&&hk(a.config.retryCount),lD(null==(r=a.config)?void 0:r.loggerDomain)&&Eb(a.config.loggerDomain),this.videoDecodeFallbackType=(null==(n=a.config)?void 0:n.videoDecodeFallback)||this.videoDecodeFallbackType,Fw.emit(Hw.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:c}),aP.addSuccessEvent({key:521700,cost:yD()-s,split:50})}catch(o){throw aP.addFailedEvent({key:521700,error:o}),o}}))}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}},IG=BC(KC()),AG=BC($C());function RG(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 CG=(e,t)=>jC(void 0,null,(function*(){var i;let r=GH(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 s=r.media[0],o=r.media[1];s.ext&&(n.audio.extensions=s.ext.map((e=>({id:e.value,uri:e.uri})))),o.ext&&(n.video.extensions=o.ext.map((e=>({id:e.value,uri:e.uri}))));let a={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channels:s.rtp[0].encoding,rtcpfb:[],rtx:0};null==(i=s.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=[...RG(o)].filter((e=>c.includes(e.codec.toLocaleLowerCase()))),n.video.decoders=(yield function(){return jC(this,null,(function*(){let e=new RTCPeerConnection;e.addTransceiver(Bb.VIDEO,{direction:Bb.TRANSCEIVER_DIRECTION_RECVONLY});let t=yield e.createOffer();if(!t.sdp)return[];let i=RG(GH(t.sdp).media[0]);return e.close(),i}))}()).filter((e=>["h264","vp8"].includes(e.codec.toLocaleLowerCase()))),n})),bG=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,s=GH(r),o={extmapAllowMixed:"extmap-allow-mixed",groups:s.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:Bb.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:s.media[0].port,protocol:s.media[0].protocol,type:Bb.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 o.media.push(a),[1,2,3].forEach((e=>{o.media.push(kG({mid:e,serverAbility:t,clientAbility:i,parsedOffer:s}))})),n&&o.media.push(s.media.find((e=>"dc"===e.mid))),WH(o)},kG=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,isDownlink:s=!1}=e,o={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:Bb.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:Bb.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(s){let e=i.video.decoders;(!e||0===e.length)&&(e=i.video.codecs),(!e||0===e.length)&&(e=r.video.decoders),e.forEach((e=>{DG(o,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];DG(o,t)}return o},DG=(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.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 NG=(e,t,i)=>{let r=AG.default.parse(e);return r.media.forEach(((e,n)=>{var s;if((e.type===Bb.AUDIO||e.type===Bb.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===Bb.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===Bb.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===Bb.VIDEO))if(n<4)e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach((t=>DG(e,t)));else if(i){e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[];let r=i.video.decoders;(!r||0===r.length)&&(r=i.video.codecs),(!r||0===r.length)&&(r=t.video.decoders),r.forEach((t=>DG(e,t)))}null!=(s=e.payloads)&&s.includes("datachannel")&&r.groups&&e.mid&&(r.groups[0].mids=r.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),AG.default.write(r)},wG=BC(KC()),OG=class extends wG.EventEmitter{constructor(e){super(),this.room=e,GC(this,"mainFpsHealth",1),GC(this,"mainBitrateHealth",1),GC(this,"badMainBitrateHealthCount",0),GC(this,"lastEmitBadHealthTime",0),GC(this,"log"),!dN&&dw&&Fw.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(){Fw.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};GC(OG,"EVENT_BAD_HEALTH","bad_health");var PG=OG;function MG(e){let{seiMessageList:t,isAudio:i,isMain:r}=e;return new TransformStream({transform(e,n){let s=e;i?audioEncodePipeline.forEach((e=>{s=e({frame:s})})):videoEncodePipeline.forEach((e=>{s=e({frame:s,seiMessageList:t,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:s.data,userId:"",streamType:r?"main":"auxiliary"})}})})),n.enqueue(s)}})}function LG(e,t,i){return new TransformStream({transform(r,n){let s=r;videoDecodePipeline.forEach((r=>{s=r({frame:s,onSEI:i=>{i.forEach((i=>{self.postMessage({type:"sei",seiPayloadType:i.seiPayloadType,data:i.seiPayload.buffer,userId:e,streamType:t})}))},onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:s.data,userId:e,streamType:t})}})})),n.enqueue(s)}})}var xG=(e=>(e.TRACK="track",e.DATA_CHANNEL_MESSAGE="data_channel_msg",e[e.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",e[e.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",e.RECONNECTED="spc-reconnected",e.RECONNECT_FAILED="spc-reconnect-failed",e.ERROR="error",e.SEI_MESSAGE="sei-message",e.DUMP="dump",e))(xG||{}),VG=0,UG=!1,FG=new Set,BG=1,HG=class extends IG.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),GC(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),GC(this,"currentState","DISCONNECTED"),GC(this,"_room"),GC(this,"_signalChannel"),GC(this,"_peerConnection",null),GC(this,"_datachannel",null),GC(this,"_enableCustomMessage"),GC(this,"_log"),GC(this,"_downlinkMIDMap",new Map),GC(this,"_downlinkMIDUserIDMap",new Map),GC(this,"_reconnectionTimer",-1),GC(this,"reconnectionCount",0),GC(this,"clientAbility"),GC(this,"_serverAbility",null),GC(this,"addDownlinkQueue",new Set),GC(this,"removeDownlinkQueue",new Set),GC(this,"_parsedAnswer",null),GC(this,"_updateSDPPromise",null),GC(this,"_waitForPCConnectedPromise"),GC(this,"clearConnectTimeout"),GC(this,"_isSDPLogged",!1),GC(this,"enableInsertableStreams",!1),GC(this,"insertableStreamsAbortMap",new Map),GC(this,"receiverRemoteTrackMap",new WeakMap),GC(this,"scriptTransformWorker"),GC(this,"_isRelayTried",!1),GC(this,"_rttOverCount",0),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=Ww.createLogger({id:"spc".concat(BG++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(WP?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=GH(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&&!cD(e.ssrcs[0].id)){let n=Number(e.ssrcs[0].id),s=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=s;break;case 2:i.smallVideoSsrc=n,i.smallVideoRtxSsrc=s;break;case 3:i.auxVideoSsrc=n,i.auxVideoRtxSsrc=s}}})),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(){jP&&(this.scriptTransformWorker=function(e){let t=[sx],i=[yB,EB,vB,TB,MG,LG],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,s=n.isReceiver?LG(n.userId,n.streamType,n.isAudio):MG({isAudio:n.isAudio,seiMessageList:n.isMain?n.small?i:e:t,isMain:n.isMain});r.transformer.readable.pipeThrough(s).pipeTo(r.transformer.writable)}}),")();").concat(r,"})()"),s=new Blob([n],{type:"text/javascript"}),o=URL.createObjectURL(s),a=new Worker(o);return URL.revokeObjectURL(o),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),"dump"===e.data.type&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e)})}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}initialize(){return jC(this,null,(function*(){var e;let t;try{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let e=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(e)),"checking"===e&&0===this.stat.iceStartTime?this.stat.iceStartTime=Date.now():"connected"===e&&0===this.stat.iceEndTime?(this.stat.iceEndTime=Date.now(),aP.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):"failed"===e&&aP.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var e;let t=(null==(e=this._peerConnection)?void 0:e.signalingState)||"";this._log["closed"===t?"debug":"info"]("signaling state: ".concat(t))},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 WG(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(Bb.AUDIO,{direction:Bb.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Bb.VIDEO,{direction:Bb.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Bb.VIDEO,{direction:Bb.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Bb.VIDEO,{direction:Bb.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield CG(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()))}),aP.addSuccessEvent({key:521707}),this.clientAbility}catch(Zw){throw aP.addFailedEvent({key:521707,error:Zw}),this._log.error("initialize failed ".concat(Zw," \noffer: ").concat(null==t?void 0:t.sdp)),Zw}}))}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(mk){this._log.warn("setPriority error ",mk)}}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return jC(this,null,(function*(){var i,r;try{if("CONNECTED"===this.currentState)return;let n=yD(),s={type:"answer",sdp:bG({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(s),yield this.waitForPeerConnectionConnected();let o=(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");o&&this.setPriority(o),t||aP.addSuccessEvent({key:521703,cost:yD()-n})}catch(mb){let i=mb instanceof nb&&mb.code===ib.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(mb),e),this.reset(),!i&&!this.isReconnecting&&(aP.addFailedEvent({key:521703,error:mb}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),mb}}))}reconnect(){return jC(this,null,(function*(){if(-1===this._reconnectionTimer){if(!this._signalChannel.isConnected)return this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(XB,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:CH,responseCommand:iH.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(0!==t.data.code)throw new nb({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),aP.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),Fw.emit(Hw.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(pb){if(!this.isReconnecting)return;if(null!=pb&&pb.message.includes("timeout")){let e=sD(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield HD(e,(e=>{this._reconnectionTimer=e})),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(null==pb?void 0:pb.code," ").concat(pb)),aP.addFailedEvent({key:521704,error:pb}),this.reconnectionCount>=pk()&&this._log.warn("SDK has tried reconnect for ".concat(pk()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")}))}getPeerConnection(){return this._peerConnection}startReconnection(){return jC(this,null,(function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())}))}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),null==(e=this.clearConnectTimeout)||e.call(this),this._signalChannel.off(XB,this.reconnect,this),"RECONNECTING"===this.currentState&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===dk.CLOSED&&this.startReconnection()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var t;let i=(null==(t=this._peerConnection)?void 0:t.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info("connectionState: ".concat(e.target.connectionState," ICE: ").concat(i," DTLS: ").concat(r)),e.target.connectionState===dk.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===dk.FAILED||e.target.connectionState===dk.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===dk.CONNECTED||e.target.connectionState===dk.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),Fw.emit(Hw.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 lk;let e=null;return OP()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,wP()&&0!==this._peerConnection.getReceivers().length&&e?e.state:lk):lk}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(xG.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return jC(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(AP(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&&zk(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(s),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(s),n(),t(new nb({code:ib.API_CALL_ABORTED,message:QO({key:qO.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{Fw.off(Hw.LEAVE_SUCCESS,r,this),this.off(xG.CONNECTION_STATE_CHANGED,i,this)},s=setTimeout((()=>{n();let e=new nb({code:ib.API_CALL_TIMEOUT,message:"connection timeout"});var i;VG+=1,i=this._signalChannel.isConnected,VG>2&&!UG&&0===FG.size&&i&&(this._log.warn("firewall restriction"),UG=!0,this.emit(xG.FIREWALL_RESTRICTION)),t(e)}),kk);this.clearConnectTimeout=()=>{n(),clearTimeout(s),delete this.clearConnectTimeout},Fw.on(Hw.LEAVE_SUCCESS,r,this),this.on(xG.CONNECTION_STATE_CHANGED,i,this)})),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally((()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}))),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise(((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)})):Promise.resolve()}addDownlink(e){return jC(this,null,(function*(){if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),0===this.addDownlinkQueue.size)try{yield this.updateSDP(),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(mk){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(mk)),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=Bb.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=GH(this._peerConnection.remoteDescription.sdp));let s,o,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)s=c[0],o=c[1],a=c[2];else if(3===n.length)s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[0]))),o=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(Bb.AUDIO,{direction:Bb.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Bb.VIDEO,{direction:Bb.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Bb.VIDEO,{direction:Bb.TRANSCEIVER_DIRECTION_RECVONLY}),s=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=kG({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:GH(this._peerConnection.localDescription.sdp),isDownlink:!0});o=JSON.parse(JSON.stringify(e)),a=JSON.parse(JSON.stringify(e)),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a)}s.direction=Bb.TRANSCEIVER_DIRECTION_SENDONLY;let l="".concat(r,"-").concat(t.audio);s.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(l)},{id:t.audio,attribute:"msid",value:"".concat(l,"-").concat(Bb.MAIN," ").concat(l,"-audio")}],o.direction=Bb.TRANSCEIVER_DIRECTION_SENDONLY,o.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(Bb.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(Bb.MAIN," ").concat(l,"-bigvideo")}],o.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=Bb.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(Bb.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(Bb.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Bb.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,[s.mid,o.mid,a.mid]),this._downlinkMIDUserIDMap.set(s.mid,i),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(a.mid,i)}removeDownlink(e){return jC(this,null,(function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(e,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),i=!1;this._peerConnection.getTransceivers().forEach((e=>{null!=t&&t.includes(Number(e.mid))&&(i=!0,e.direction="inactive")})),this._parsedAnswer||(this._parsedAnswer=GH(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((e=>{null!=t&&t.includes(Number(e.mid))&&(i=!0,e.direction="inactive",e.ssrcs=[],e.ssrcGroups=[])})),0===this.removeDownlinkQueue.size&&i&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),null==t||t.forEach((e=>this._downlinkMIDUserIDMap.delete(e))),this._log.info("removeDownlink(".concat(e,") done"))}))}setBandwidth(e){return jC(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(FP()){let e=this._peerConnection.getSenders().slice(0,4);for(let o=0;o<e.length;o++){let s,a=e[o];0===o&&t?s=t:1===o&&i?s=i:2===o&&r?s=r:3===o&&n&&(s=n),s&&(yield this.setSenderMaxBitrate(a,s))}let s=!1;i&&e[1].track&&(s=this.setStartBitrate(1,i)),n&&e[3].track&&(s=this.setStartBitrate(3,n)||s),s&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info("setBandwidth ".concat(JSON.stringify(e)))}catch($w){this._log.error("failed to set bandwidth: ".concat($w))}}))}setStartBitrate(e,t){var i,r;return!(null==(i=this._peerConnection)||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=GH(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 s=GH(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=GH(this._peerConnection.remoteDescription.sdp));let o=mN?"TIAS":"AS";t&&(s.media[0].bandwidth=[{type:o,limit:mN?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:o,limit:mN?1e3*t:t}]),i&&(s.media[1].bandwidth=[{type:o,limit:mN?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:o,limit:mN?1e3*i:i}]),r&&(s.media[2].bandwidth=[{type:o,limit:mN?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:o,limit:mN?1e3*r:r}]),n&&(s.media[3].bandwidth=[{type:o,limit:mN?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:o,limit:mN?1e3*n:n}]);let a={type:"offer",sdp:WH(s)};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(cD(n)?1===t:t===n)return;let s="setScaleResolutionDownBy ".concat(i," ").concat(t);return n&&(s+=" prevScale: ".concat(n)),this._log.warn(s),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=WH(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,r)=>jC(this,null,(function*(){var n,s;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(o){this._log.error(o),!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==(s=this._peerConnection.remoteDescription)?void 0:s.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(o)}})))),this._updateSDPPromise}setTransceiverDirection(e,t){return jC(this,null,(function*(){if(!mN||!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===Hb.INACTIVE&&t===Hb.RECVONLY&&(this._parsedAnswer.media[r].direction=e),e===Hb.SENDONLY&&t===Hb.INACTIVE&&(this._parsedAnswer.media[r].direction=Hb.RECVONLY)}yield this.updateSDP()}))}filterSDPDirection(){return GH(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((e=>e.direction))}setOffer(e){this._log.info("setting offer");let t=NG(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return jC(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach((i=>{var r;if(i.type===Bb.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=[],DG(i,n),t=!0)}})),t&&(this._log.warn("switch video encoder to ".concat(e)),yield this.updateSDP())}))}useHWEncoder(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;return jC(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];cD(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===Bb.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=[],DG(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(){this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach((e=>JD(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,s=Math.max(t,i),{rttRatioThreshold:o,rttThreshold:a}=(null==(r=this._room.scheduleResult.config)?void 0:r.useTurnTcpInfo)||{};if(!(o&&a&&n&&s))return;let c=Math.floor(s/n),l=(this._isRelayTried||c>o)&&s>a;l?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(n," upRTT: ").concat(t," downRTT: ").concat(i," ratio: ").concat(c," over-count: ").concat(this._rttOverCount," isOver: ").concat(l," isRelayTried: ").concat(this._isRelayTried," force-relay: ").concat(this._room.forceRelay)),this.isUsingRelay||this._isRelayTried?this._room.forceRelay&&this.switchRelay(!1):(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0))):this._rttOverCount=0}switchRelay(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return jC(this,null,(function*(){if(this.isUsingRelay===e)return;let i=e?"relay":"udp",r=e?521709:521710;try{this._room.forceRelay=e,this._log.warn("switchRelay ".concat(i));let t=Date.now();yield this.doSwitchRelay(i),this._log.warn("switchRelay ".concat(i," success")),aP.addSuccessEvent({key:r,cost:Date.now()-t})}catch(mb){this._log.warn("switchRelay ".concat(i," failed"),mb),aP.addFailedEvent({key:r,error:mb}),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.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};HC([ZL("reconnect")],HG.prototype,"startReconnection",1),HC([$L((e=>e.userId))],HG.prototype,"addDownlink",1),HC([$L((e=>e))],HG.prototype,"removeDownlink",1),HC([QL(!0)],HG.prototype,"updateSDP",1),HC([ex(521712,!1)],HG.prototype,"setOffer",1),HC([ex(521713,!1)],HG.prototype,"setAnswer",1);var GG=class{constructor(e){GC(this,"tag"),GC(this,"len"),GC(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}},WG=class{constructor(e){GC(this,"tinyId"),GC(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),s=new GG(new Uint8Array(e).slice(i,i+2+2+n).buffer);r.push(s),i+=4+n}r.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},jG=new Set;function KG(){let e=Math.floor(4294967296*Math.random());return jG.has(e)?KG():(jG.add(e),e)}var JG=BC(KC()),qG=class extends JG.default{constructor(e){super(),GC(this,"userId"),GC(this,"tinyId"),GC(this,"_sdpSemantics"),GC(this,"_isUplink"),GC(this,"_room"),GC(this,"_log"),GC(this,"_currentState","DISCONNECTED"),GC(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=Ww.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&&(Fw.emit(Hw.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"))}},zG=class extends qG{constructor(e){super(VC(xC({},e),{isUplink:!0})),GC(this,"localMainAudioTrack",null),GC(this,"localMainVideoTrack",null),GC(this,"localAuxAudioTrack",null),GC(this,"localAuxVideoTrack",null),GC(this,"_isPublishingAux",!1),GC(this,"_publishingLocalAudioTrack"),GC(this,"_publishingLocalVideoTrack"),GC(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}),GC(this,"_flag",0),GC(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:s,auxVideoRtxSsrc:o}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:s||0,auxiliaryRtx:o||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=gM.run("timeout",(()=>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(Lw()," ").concat(ww())),aP.addCount({key:521e3})}gM.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 s=this._peerConnection.getSenders();s&&(PP()?(n.audio=!(null==(e=s[0])||!e.track),n.bigVideo=!(null==(t=s[1])||!t.track),n.smallVideo=!(null==(i=s[2])||!i.track),n.auxVideo=!(null==(r=s[3])||!r.track)):s.forEach((e=>{e.track&&(e.track.kind===Bb.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}get publishingState(){let{publishState:e}=this,t=xC({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}get serverPublishState(){return{audio:!!(this.flag&qb),bigVideo:!!(this.flag&jb),smallVideo:!!(this.flag&Kb),auxVideo:!!(this.flag&Jb)}}get muteState(){var e,t,i;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(i=this.localAuxVideoTrack)||!i.muted)}}initialize(){this.installEvents()}close(e){var t;let i=(null==(t=this._peerConnection)?void 0:t.getSenders())||[];for(let r of i)r.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;null!=(e=this.singlePC)&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(t=this.singlePC)||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var i,r,n;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:s,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:s,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:s,state:e}))),o}onVideoEncodeFailed(e){var t,i;e&&e.isMediaTrackActive&&"h264"===this.videoCodec&&(this._log.warn("h264 encoder not working"),null!=(t=this.singlePC)&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),null==(i=this.singlePC)||i.switchVideoEncoder("vp8")))}publish(e){return jC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e,s,o,a,c,l,d;if(!t.singlePC)return;t.installEvents(),yield t.singlePC.waitForPeerConnectionConnected();let u,{publishState:h,muteState:p}=t;if(i&&(t._publishingLocalAudioTrack=i,h.audio=!0,p.audio=i.muted),r){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new nb({code:ib.NOT_SUPPORTED_H264,message:QO({key:qO.NOT_SUPPORTED_H264ENCODE})});dN&&115===lw()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to 480p"),r.setProfile(Ub["480p_2"]),yield r.applyProfile()),t._publishingLocalVideoTrack=r,n?(h.auxVideo=!0,p.auxVideo=r.muted):(h.bigVideo=!0,p.bigVideo=r.muted)}if(t._isPublishingAux=n,r&&!n&&r.small&&(u=t._room.videoManager.smallTrack,h.smallVideo=!0),yield t._signalChannel.sendWaitForResponseWithRetry({command:kH,responseCommand:iH.SPC_PUBLISH_RESULT,data:VC(xC({},t.singlePC.uplinkSSRC),{state:h,muteState:p}),retries:3}),yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:u,isAuxiliary:n}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r){t[n?"localAuxVideoTrack":"localMainVideoTrack"]=r;let{scaleResolutionDownBy:e}=r;yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[n?3:1],e,r.streamType)}i&&(t[n?"localAuxAudioTrack":"localMainAudioTrack"]=i),yield t.singlePC.setBandwidth({audio:(null==(e=t.localMainAudioTrack)?void 0:e.profile.bitrate)||(null==(s=t.localAuxAudioTrack)?void 0:s.profile.bitrate),bigVideo:null==(o=t.localMainVideoTrack)?void 0:o.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),(t._room.preferHW||null!=(d=t._room.scheduleResult.config)&&d.preferHW)&&r&&r.profile.width*r.profile.height>=921600&&t.singlePC.useHWEncoder(!0,n?7:2)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!MP())return;this._log.info("publish by transceiver");let s=null==i?void 0:i.outMediaTrack,o=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[],d=(e,t,i)=>{var r,n;let s=a[t].sender.replaceTrack(i);l.push(t),null!=(r=this.singlePC)&&r.enableInsertableStreams&&s.then((()=>this.createEncodedStreams(a[t].sender,e))),null!=(n=this.singlePC)&&n.scriptTransformWorker&&this.initSenderTransfrom(a[t].sender,e),c.push(s)};o&&d(t.mediaType,0,o),s&&d(i.mediaType,n?3:1,s),r&&d(8,2,r);let u=this.singlePC.setTransceiverDirection(Hb.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(),s=new AbortController;null==(i=this.singlePC)||i.addAbortController(e,s),(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)&&r.isUsingH264&&n?n.encodeFrame(e,8===t):e)}}),s):n.readable).pipeTo(n.writable,s).catch((e=>{this._log.debug("encoded stream error",e),"destory"!==e&&this._log.warn(e)}))}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)return;let i=2!==t,r=8===t;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:1===t,isMain:i,isSmall:r}))}enableSmall(e){return jC(this,null,(function*(){var t;if(!this.singlePC)return;let i=this._peerConnection.getTransceivers();if(e){if(this._room.videoManager.smallTrack){let{sender:e}=i[2];null!=(t=this.singlePC)&&t.enableInsertableStreams&&this.createEncodedStreams(e,8),yield e.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(Hb.SENDONLY,[2])}}else yield i[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Hb.INACTIVE,[2]);this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return jC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){let e=r&&r===t.localAuxVideoTrack,n=null==r?void 0:r.outMediaTrack,s=t._peerConnection.getSenders(),o=[];i&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localMainAudioTrack&&!t.localAuxAudioTrack&&(yield s[0].replaceTrack(null),o.push(0))),n&&(e?(yield s[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=VC(xC({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),o.push(3)):(yield s[1].replaceTrack(null),yield s[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=VC(xC({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),o.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.singlePC.setTransceiverDirection(Hb.INACTIVE,o),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return jC(this,null,(function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:lH,data:t,responseCommand:iH.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:dH,commandDesc:"unpublish",responseCommand:iH.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===ib.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),HP){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:RH,data:this._mediaSettings,responseCommand:iH.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return jC(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Bb.AUXILIARY:Bb.MAIN," stream")),PP()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return jC(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Bb.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)&&i.small&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Hb.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Hb.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return jC(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?Bb.AUXILIARY:Bb.MAIN," stream")),PP()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return jC(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Bb.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(Hb.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}replaceTrack(e){return jC(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!i||0===i.length||!r||i.find((e=>e.track===r)))return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(r.kind," track ").concat(r.id," ").concat(r.label," on ").concat(n?Bb.AUXILIARY:Bb.MAIN," stream")),r.kind===Bb.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===Bb.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0}))}setBandwidth(e){return jC(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===Bb.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:aH,responseCommand:iH.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&Fw.emit(Hw.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Bb.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Bb.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Bb.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Bb.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Bb.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Sk?(this._log.error(zO.NOT_SUPPORTED_H264ENCODE),new nb({code:ib.NOT_SUPPORTED_H264,message:QO({key:qO.NOT_SUPPORTED_H264ENCODE})})):new nb({code:ib.UNKNOWN,message:QO({key:qO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:iH.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return jC(this,null,(function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))}))}};HC([WL((function(e){let{localVideoTrack:t}=e;null==t||t.once("6",this.onVideoEncodeFailed,this)}))],zG.prototype,"publish",1),HC([WL((function(e){let{localVideoTrack:t}=e;null==t||t.off("6",this.onVideoEncodeFailed,this)}))],zG.prototype,"unpublish",1);var YG=zG;function XG(e){return Object.keys(e).filter((t=>e[t]))}var QG=class extends qG{constructor(e){super(VC(xC({},e),{isUplink:!1})),GC(this,"_flag",0),GC(this,"isRobot",!1),GC(this,"role","anchor"),GC(this,"remoteAudioTrack"),GC(this,"remoteVideoTrack"),GC(this,"remoteAuxiliaryTrack"),GC(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),GC(this,"jitterBufferTimeoutId",-1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new PU(this._room,this),this.remoteVideoTrack=new QU(this._room,this),this.remoteAuxiliaryTrack=new ZU(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 CD(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===Bb.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,i;let r=e.streams[0],{track:n,receiver:s}=e;if(!r.id.includes(this.tinyId))return;let o=r.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(o," ").concat(n.kind));let a=Bb.AUDIO;n.kind===Bb.VIDEO&&(a=o===Bb.MAIN?Bb.VIDEO:Bb.AUXILIARY);let c=this.remoteAudioTrack;a===Bb.VIDEO?c=this.remoteVideoTrack:a===Bb.AUXILIARY&&(c=this.remoteAuxiliaryTrack),null==(t=this.singlePC)||t.receiverRemoteTrackMap.set(s,c),null!=(i=this.singlePC)&&i.scriptTransformWorker&&this.initReceiverTransform(s,o,n.kind===Bb.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s),c.setInputMediaStreamTrack(n)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),i=new AbortController,r={abortController:i,enqueue:t=>{var i,r;let n=null==(i=this.singlePC)?void 0:i.receiverRemoteTrackMap.get(e);return n&&("video"!==n.kind||null!=(r=this.singlePC)&&r.isUsingH264)?n.decodeFrame(t):t}};t.readable.pipeThrough(new TransformStream({transform:(e,t)=>{let i=r.enqueue(e);i&&t.enqueue(i)}})).pipeTo(t.writable,i).catch((e=>{"destory"!==e&&this._log.warn(e)})),this.singlePC.addAbortController(e,i)}}initReceiverTransform(e,t,i){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:i,userId:this.userId,streamType:t}))}subscribe(e,t){return jC(this,null,(function*(){try{if(this._log.info("subscribe ".concat(t," ").concat(XG(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(Zw){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Zw.message," ").concat(JSON.stringify(this.muteState))),new nb({code:ib.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Zw}}))}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"),dw&&pw<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return jC(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:r}=e;return function*(){var e;if("main"===r&&!t.isMainStreamSubscribed||"auxiliary"===r&&!t.isAuxStreamSubscribed)return void t._log.info("".concat(r," stream already unsubscribed"));let n=xC({},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 s="subscribe_change";Object.values(n).find((e=>!0===e))||(s="unsubscribe"),t._log.info("".concat("unsubscribe"===s?s:"subscribe"," ").concat(r," [").concat(XG(n),"]")),"unsubscribe"===s&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(s,n),"unsubscribe"===s&&(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=hH,n=iH.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=pH,n=iH.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 nb({code:i.code,message:QO({key:qO.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return jC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected();try{if(i||!e.hasSSRC){let i={audioSsrc:KG(),bigVideoSsrc:KG(),bigVideoRtxSsrc:KG(),auxVideoSsrc:KG(),auxVideoRtxSsrc:KG()},{audioSsrc:n,bigVideoSsrc:s,bigVideoRtxSsrc:o,auxVideoSsrc:a,auxVideoRtxSsrc:c}=i;e.ssrc={audio:n,video:s,videoRtx:o,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:DH,responseCommand:iH.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 nb({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;tM&&(null!=t&&t.jitterDelay||null!=t&&t.jitterDelayAux)&&e.setJitterBufferDelay({mainDelay:t.jitterDelay,auxDelay:t.jitterDelayAux})}}}()}))}removeDownlink(){return jC(this,null,(function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(null!=e&&e.jitterDelay||null!=e&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)}))}setJitterBufferDelay(e){let{mainDelay:t,auxDelay:i}=e;if(!tM||!this.singlePC||!this._peerConnection||qD(t)&&qD(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return dD(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),dD(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,qD(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||qD(t)&&e.track===this.remoteAudioTrack.outMediaTrack;if(n&&qD(i)||!n&&qD(t))return;let s=n?i||0:t,o=(e.jitterBufferTarget||0)+100;o>s||(e.jitterBufferTarget=o,this._log.debug("set ".concat(n?"aux ":"").concat(null==(r=null==e?void 0:e.track)?void 0:r.kind," jitterBuffer delay ").concat(o," -> ").concat(s)))})),!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(mb){this._log.warn("set jitterBuffer delay error: ".concat(mb)),clearTimeout(this.jitterBufferTimeoutId),n()}}get audioReceiver(){var e;return(null==(e=this.singlePC)?void 0:e.getReceiversByUserId(this.userId)[0])||null}};HC([QL(),KL((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 nb({code:ib.API_CALL_ABORTED,message:QO({key:qO.CONNECTION_ABORTED,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],QG.prototype,"subscribe",1),HC([QL()],QG.prototype,"unsubscribe",1),HC([$L((()=>"jitter"))],QG.prototype,"setJitterBufferDelay",1);var ZG=QG;var $G=BC(KC());var eW=class e extends $G.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,GC(this,"log"),GC(this,"cmdIdSeqMap",new Map),GC(this,"messageMap",new Map),this.log=Ww.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(iH.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(OH,n),this.log.debug("send custom msg: ".concat(JSON.stringify(n)))}onReceiveMsg(t){let{data:i}=t.data,r=this.room.tinyIdToUserIdMap.get(i.srcTinyId);if(r){let t={userId:r,cmdId:i.cmdId,seq:i.streamSeq,data:Uint8Array.from(atob(i.msg),(e=>e.charCodeAt(0))).buffer};if(i.ordered){let i="".concat(r,"_").concat(t.cmdId),n=this.messageMap.get(i);if(n&&0!==n.lastSeq)if(Math.abs(n.lastSeq-t.seq)>e.SEQ_INTERVAL)this.messageMap.set(i,{lastSeq:t.seq,cachedMessageMap:new Map}),this.emitMessage(t);else if(t.seq>n.lastSeq){if(t.seq===n.lastSeq+1)this.emitMessage(t);else if(!n.cachedMessageMap.has(t.seq)){let e=setTimeout((()=>this.emitMessage(t,!0)),5e3);n.cachedMessageMap.set(t.seq,{message:t,timeoutId:e})}}else this.log.debug("drop message ".concat(t.userId,"-").concat(t.cmdId,"-").concat(t.seq));else n||(n={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(i,n),setTimeout((()=>this.emitMessage(t,!0)),100)),n.cachedMessageMap.set(t.seq,{message:t})}else this.emit("message",t)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(i.srcTinyId));let e=r=>{r.tinyId===i.srcTinyId&&(this.room.off("peer-join",e),this.onReceiveMsg(t))};this.room.on("peer-join",e),HD(2e3).then((()=>this.room.off("peer-join",e)))}}emitMessage(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i;let r=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),n=e;if(r){if(t){let e=[...r.cachedMessageMap.values()].sort(((e,t)=>e.message.seq-t.message.seq));e[0]&&(n=e[0].message)}0!==r.lastSeq&&n.seq-r.lastSeq>1&&this.log.debug("msg lost userId: ".concat(n.userId," seq: ").concat(r.lastSeq," -> ").concat(n.seq)),r.lastSeq=n.seq,clearTimeout(null==(i=r.cachedMessageMap.get(n.seq))?void 0:i.timeoutId),r.cachedMessageMap.delete(n.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(n))),this.emit("message",n);let s=null==r?void 0:r.cachedMessageMap.get(n.seq+1);s&&this.emitMessage(s.message)}};GC(eW,"SEQ_INTERVAL",300);var tW,iW=eW,{isString:rW,isUndefined:nW,getNetworkType:sW,isEmpty:oW}=cb,aW=class extends SG{constructor(e){super(e),GC(this,"_businessInfo"),GC(this,"userManager"),GC(this,"_version"),GC(this,"_heartbeat",-1),GC(this,"_lastHeartBeatTime",-1),GC(this,"_stats"),GC(this,"_joinTimeout",-1),GC(this,"_firstPublishedList",null),GC(this,"_joinReject",null),GC(this,"_isRelayChanged",!1),GC(this,"sdpSemantics"),GC(this,"signalChannel",null),GC(this,"uplinkConnection",null),GC(this,"singlePC",null),GC(this,"enableSPC",LP),GC(this,"_changeBigSmallRecords",new Map),GC(this,"networkQuality"),GC(this,"_iceTransportPolicy"),GC(this,"forceRelay",!1),GC(this,"_turnServers",[]),GC(this,"_syncUserListInterval",-1),GC(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),GC(this,"enableSEI",!1),GC(this,"_enableAudioVolumeEvaluation",!1),GC(this,"_audioVolumeIntervalId",0),GC(this,"_enableMultiAuxStream",!1),GC(this,"_pureAudioPushMode",!1),GC(this,"_customMessageManager"),GC(this,"preferHW",!1),GC(this,"healthDetector"),GC(this,"_updateAudioLevelTaskId",-1),this._stats=new XH(this,this._log),this.userManager=new iF(this.userId,this._log),this._version=ub,this.sdpSemantics=yk,nW(e.sdpSemantics)?Jw.isUnifiedPlanDefault()&&(this.sdpSemantics=vk):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(sW())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!nW(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&LP,!nW(e.enableSPC)&&LP&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new PG(this)}get isMainStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex((e=>e.muteState.hasAuxiliary))>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,i){return jC(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",(e=>{this.emit("peer-join",e)})),this.userManager.on("2",(e=>{this.closeDownLinkConnection(e,"remote user exitRoom"),this.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(e=>{var t=((e,t)=>{var i={};for(var r in e)wC.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&DC)for(var r of DC(e))t.indexOf(r)<0&&OC.call(e,r)&&(i[r]=e[r]);return i})(e,[]);Fw.emit(Hw.REMOTE_PUBLISH_STATE_CHANGED,xC({room:this},t)),this.emit("remote-publish-state-changed",xC({},t))})),this.joinParams=e,new Promise(((t,i)=>jC(this,null,(function*(){var r,n;this._joinReject=i;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(s){if(!(s instanceof nb&&s.code===ib.SPC_INITIALIZED_FAILED))return i(s);null==(r=this.signalChannel)||r.destroy(),yield this.initialize()}let o=yD();yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),aP.addSuccessEvent({key:521708,cost:yD()-o}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(Yw){aP.addFailedEvent({key:521708,error:Yw}),i(Yw)}this._joinReject=null}))))}))}initSinglePC(){return jC(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new HG({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",(e=>this.emit("sei-message",e))),this.singlePC.on("dump",(e=>this.emit("dump",e))),this.singlePC.once("error",(()=>this.fallbackToMPC()));try{return yield this.singlePC.initialize()}catch(pb){throw this.fallbackToMPC(),new nb({code:ib.SPC_INITIALIZED_FAILED,message:null==pb?void 0:pb.message})}}}))}doJoin(e,t){return new Promise(((i,r)=>jC(this,null,(function*(){var n,s,o;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(ZB,(e=>{this.clearJoinTimeout(),Fw.emit(Hw.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)})),uD(null==(s=null==(n=this.scheduleResult)?void 0:n.config)?void 0:s.singlePC)&&LP&&(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:xw(),netType:Yk(),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!=(o=this.scheduleResult.config)&&o.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{r(new nb({code:ib.JOIN_ROOM_FAILED,message:QO({key:qO.JOIN_ROOM_TIMEOUT})}))}),c),Fw.emit(Hw.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?bH:nH,a),this.signalChannel.once(iH.JOIN_ROOM_RESULT,(t=>{this.clearJoinTimeout();let{code:n,message:s,data:o,tinyId:a}=t.data;Fw.emit(Hw.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=o.publishers,this.singlePC&&this.singlePC.connect(VC(xC({},o.ability),{useVp8:o.ability.useVp8||!!e.useVp8})).catch((()=>{})),i()):(this._log.error("Join room failed result: ".concat(n," error: ").concat(s)),r(new nb({code:ib.JOIN_ROOM_FAILED,extraCode:n,message:QO({key:qO.JOIN_ROOM_FAILED,data:{error:s,code:n}})})))}))}))))}reJoin(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return jC(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let t,i=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,i.push(this.initSinglePC().then((e=>(t=e,e))))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),i.push(this.signalChannel.connect())),yield Promise.all(i),yield this.doJoin(VC(xC({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),IM.logSuccessEvent({userId:this.userId,eventType:fk.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(xG.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof YG&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(xG.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof YH&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(mk){this._log.warn("reJoin fail ".concat(mk)),this.reset(),IM.logFailedEvent({userId:this.userId,eventType:fk.REJOIN,error:mk}),this.emit("error",new nb({code:ib.JOIN_ROOM_FAILED,message:QO({key:qO.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return jC(this,null,(function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this.signalChannel||function(e){let t=[...PH.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 MH({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 iW(this,this.signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this.networkQuality||(this.networkQuality=new eG({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(eG.EVENT_NETWORK_QUALITY,(e=>{var t;this.emit("network-quality",e),null==(t=this.singlePC)||t.detectTCPAndUDP(e)}))),yM(this,this.signalChannel).add(YB,(e=>{Fw.emit(Hw.SIGNAL_CONNECTION_STATE_CHANGED,xC({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(QB,(e=>{this.reset(),this.emit("error",e)})).add(iH.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})).add(iH.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(iH.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(iH.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(IM.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(zB,(e=>{this.tinyId=e.signalInfo.tinyId,Fw.emit(Hw.JOIN_SIGNAL_CONNECTION_END,{room:this})})),Fw.emit(Hw.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&Fw.emit(Hw.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this.signalChannel=e,e||SM(this)}leave(){return jC(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(mk){}this._log.info("leave() => leaving room"),Fw.emit(Hw.LEAVE_SEND_CMD,{room:this}),null==(e=this.signalChannel)||e.send(sH)}))}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=gM.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),gM.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return jC(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});this.badCaseDetector.resetMonitor();let r=null!=(e=this.signalChannel)&&e.isConnected?function(e){if($U.has(e)){let t=$U.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 $U.delete(e),t}return[]}(this.userId):[],n=VC(xC({str_sdk_version:db,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:xC({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Yk()},i.msg_device_info)});if(this.heartbeatReport=n,Fw.emit(Hw.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(oH,n);let e=Date.now();this._lastHeartBeatTime>0&&e-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(e-this._lastHeartBeatTime)),this._lastHeartBeatTime=e,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",VC(xC({},n),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter((e=>e.flag!==Qb)).map((e=>{let{userId:t,srcTinyId:i,flag:r}=e;t===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=r);let n=this.remotePublishedUserMap.get(t);return n&&this.checkSubscribeBigSmallVideo(n),{userId:t,tinyId:i,flag:r}}));e.data.mixRobotList.forEach((e=>{let{userId:i,srcTinyId:r,flag:n,mixUserList:s}=e;t.unshift({userId:i,tinyId:r,flag:n,isRobot:!0,mixUserList:s})})),Fw.emit(Hw.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 YH&&(this.uplinkConnection=null)),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r,isRobot:n}=e,s=new(this.singlePC?ZG:JH)({userId:t,tinyId:i,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:n});this.userManager.addRemotePublishedUser(s),this.installDownlinkEvents(s,t),this.emit("remote-published",s)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",(e=>{let i=e.getCode();i!==ib.ICE_TRANSPORT_ERROR&&(i===ib.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",VC(xC({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=gM.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){gM.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:IH,responseCommand:iH.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 QO({key:qO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:iH.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||!FH)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)===dk.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof BH&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===dk.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return jC(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),IM.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 YH({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 JH({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 nb({code:ib.INVALID_OPERATION,message:QO({key:qO.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),gM.clearTask(this._audioVolumeIntervalId))}switchRole(e){return jC(this,null,(function*(){this.role!==e&&("audience"===e&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))}))}doSwitchRole(e){let t={command:AH,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:iH.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 nb({code:ib.SWITCH_ROLE_FAILED,message:QO({key:qO.SWITCH_ROLE_FAILED,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof nb&&e.getCode()===ib.API_CALL_TIMEOUT&&(e=new nb({code:ib.SWITCH_ROLE_FAILED,message:QO({key:qO.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e}))}publish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return jC(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof nx&&(t instanceof px?i.audio=t:e.audio=t),t instanceof cx&&(t instanceof ux&&2===t.mediaType?i.video=t:e.video=t)}));let r=oW(e),n=oW(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new YG({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new YH({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",VC(xC({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==ib.ICE_TRANSPORT_ERROR&&(t===ib.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})));let s=t.map((e=>e.kind)).join(",");r||(this._log.info("publish() => main ".concat(s)),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(s)),yield this.uplinkConnection.publish({localAudioTrack:i.audio,localVideoTrack:i.video,isAuxiliary:!0}),this._log.info("aux is published"))}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return jC(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let e={},i={};t.forEach((t=>{!t.mediaTrack||!t.isPublished||(t instanceof nx&&(t instanceof px?i.audio=t:e.audio=t),t instanceof cx&&(t instanceof ux&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");oW(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),oW(i)||(this._log.info("unpublish() => aux ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(tO){}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&&UP()?this.uplinkConnection.replaceTrack(e).then((t=>{t&&Fw.emit(Hw.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return jC(this,null,(function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return jC(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:Bb.VIDEO,videoType:Bb.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)}))}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return jC(this,null,(function*(){if(t=t.filter((e=>!e.isSubscribed)),0===t.length)return;let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let r=t.find((e=>2===e.mediaType))?"auxiliary":"main";try{let n=xC({},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 s=this._changeBigSmallRecords.get(e);s&&s.options.smallVideo&&i.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),Fw.emit(Hw.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(jH(n),"] prev: [").concat(jH(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());Fw.emit(Hw.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(mb){let i=mb instanceof nb?mb.getCode():ib.UNKNOWN,n=mb;throw mb instanceof nb?i===ib.REMOTE_STREAM_NOT_EXIST&&(n=new nb({code:ib.API_CALL_ABORTED,message:QO({key:qO.API_CALL_ABORTED,data:{message:mb.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new nb({code:i,message:QO({key:qO.SUBSCRIBE_FAILED,data:{message:mb.message,userId:e,streamType:r}})}),this._log.error(n)),n}}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return jC(this,null,(function*(){let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let r=t.find((e=>2===e.mediaType))?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(e," ").concat(r));try{yield i.unsubscribe({remoteTracks:t,streamType:r})}catch(mb){this._log.warn("unsubscribe() => failed ".concat(mb))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),Fw.emit(Hw.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 gM.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),Fw.emit(Hw.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&gM.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=gM.run("intervalInWorker",(()=>{var i;_L.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];null==(i=this.remotePublishedUserMap)||i.forEach((e=>{if(e.muteState.hasAudio){!_L.isRunning&&e.muteState.audioAvailable&&e.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(e):e.remoteAudioTrack.volume=0;let t=Math.floor(100*e.remoteAudioTrack.getAudioLevel());r.push({userId:e.userId,volume:t})}})),this.emit("audio-volume",r)}),{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return jC(this,null,(function*(){var i;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||-1!==this._updateAudioLevelTaskId)return;let r=null==(i=this.uplinkConnection.getPeerConnection())?void 0:i.getSenders()[0];if(!r)return;let n=Math.max(e,500);this._log.warn("updateAudioLevelFromSenderStat ".concat(n)),this._updateAudioLevelTaskId=gM.run("intervalInWorker",(()=>jC(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack)return void this.stopUpdateAudioLevelFromSenderStat();let e=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let t=this.uplinkConnection.localMainAudioTrack;e.forEach((e=>{"media-source"===e.type&&e.audioLevel&&(t.volume=e.audioLevel)}))}))),{delay:n,backgroundTask:t})}))}stopUpdateAudioLevelFromSenderStat(){var e;-1!==this._updateAudioLevelTaskId&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),gM.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(!BP||!i)return;let r=null==(t=i.getSynchronizationSources()[0])?void 0:t.audioLevel;dD(r)?e.remoteAudioTrack.volume=Math.min(2*r,1):i.getStats().then((t=>{t.forEach((t=>{"inbound-rtp"===t.type&&dD(t.audioLevel)&&(e.remoteAudioTrack.volume=t.audioLevel)}))}))}getLocalAudioStats(){return jC(this,null,(function*(){var e;let t={};return t[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},null!=(e=this.uplinkConnection)&&e.localMainAudioTrack&&(t[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),t}))}getLocalVideoStats(){return jC(this,null,(function*(){var e,t;let i={};return i[this.userId]=(null==(t=null==(e=this.uplinkConnection)?void 0:e.localMainVideoTrack)?void 0:t.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},i}))}getTransportStats(){return jC(this,null,(function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let i=yield this._stats.getReceiverStats(t);e.downlinksRTT[i.userId]=i.rtt}return e}))}getRemoteVideoStats(e){return jC(this,null,(function*(){let t={};for(let[i,r]of this.remotePublishedUserMap)"main"===e&&r.muteState.hasVideo&&(t[i]=r.remoteVideoTrack.stat),"auxiliary"===e&&r.muteState.hasAuxiliary&&(t[i]=r.remoteAuxiliaryTrack.stat);return t}))}getRemoteAudioStats(){return jC(this,null,(function*(){let e={};for(let[t,i]of this.remotePublishedUserMap)i.muteState.hasAudio&&(e[t]=i.remoteAudioTrack.stat);return e}))}setTurnServer(e,t){this._log.info("set turn server: ".concat(JSON.stringify(e)," ").concat(t||""));let i=[];Array.isArray(e)?e.forEach((e=>i.push(cb.getTurnServer(e)))):cb.isPlainObject(e)&&i.push(cb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:TH,data:e,timeout:5e3,responseCommand:iH.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:EH,data:e,timeout:5e3,responseCommand:iH.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?mH:fH,data:e,timeout:5e3,responseCommand:t?iH.START_PUBLISH_TENCENT_CDN_RES:iH.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?_H:gH,data:e,timeout:5e3,responseCommand:t?iH.STOP_PUBLISH_TENCENT_CDN_RES:iH.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:vH,data:e,timeout:5e3,responseCommand:iH.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:yH,data:e,timeout:5e3,responseCommand:iH.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:SH,data:e,timeout:5e3,responseCommand:iH.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:NH,data:e,timeout:5e3,responseCommand:iH.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=cb.getEnv();return t?(e.mainUrl="wss://".concat(t,".rtc.qq.com"),e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl="wss://".concat(this.proxy_unified),e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}getSignalInfo(){var e;return(null==(e=this.signalChannel)?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return jC(this,null,(function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:r,hasVideo:n}}=e;if(!r&&!n||!t.video&&!t.smallVideo)return;let s=this._changeBigSmallRecords.get(i);if(!s||s.isSubscribing||s.reSubscribeCount<=0)return;let{options:o,reSubscribeCount:a}=s;if(o.video&&t.video||o.smallVideo&&t.smallVideo&&r)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:o.video,smallVideo:o.smallVideo};try{if(!r&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;s.isSubscribing=!0,s.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(Uk-s.reSubscribeCount,".")),s.isSubscribing=!1,s.reSubscribeCount=Uk}catch(zw){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(Uk-s.reSubscribeCount,".")),s.isSubscribing=!1,0===s.reSubscribeCount&&this._changeBigSmallRecords.delete(i)}}))}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Uk};this._changeBigSmallRecords.set(t.userId,i),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big"));let r=this.remotePublishedUserMap.get(t.userId);r&&this.checkSubscribeBigSmallVideo(r)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(rW(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!nW(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new nb({code:ib.INVALID_PARAMETER,message:QO({key:qO.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!nW(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new nb({code:ib.INVALID_PARAMETER,message:QO({key:qO.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!nW(e.userDefinePushArgs)){if(!(rW(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new nb({code:ib.INVALID_PARAMETER,message:QO({key:qO.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}oW(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){return jC(this,null,(function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&WP)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()}))}sendSignalMessage(e){var t;return this.signalChannel?null==(t=this.signalChannel)?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new nb({code:ib.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 HC([cM(["left",uM.INIT],"joined"),RM({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"),HF(!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())}}),KL((e=>{let t=new KB;return function(i,r,n){return jC(this,null,(function*(){let s=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 nb({code:ib.INVALID_OPERATION,message:QO({key:qO.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new nb({code:ib.INVALID_OPERATION,message:QO({key:qO.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this.role=21===i.role?"audience":"anchor",this._log.info("Join() => joining room: ".concat(s," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),Fw.emit(Hw.JOIN_START,{room:this,roomId:s,params:i});let o=cb.getEnv();o||(o=wb.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Gb.OLD_CLOUD_LADDER)?o=wb.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Gb.WEBRTC)&&(o=wb.WEBRTC))),IM.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),Jw.checkSystemRequirementsInternal().then((e=>{this.checkSystemResult=e,JB.call(this)}));try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!cb.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=s,this._joinedTimestamp=cb.performanceNow(),Fw.emit(Hw.JOIN_SUCCESS,{room:this}),30===n&&!i.component&&IM.uploadEvent({log:"stat-conv-".concat(Number(Aw),"-").concat(location.hostname),userId:this.userId}),t}catch($w){throw t.delete({room:this,roomId:s}),Fw.emit(Hw.JOIN_FAILED,{room:this,error:$w}),$w}}))}}))],aW.prototype,"join",1),HC([cM("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),KL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return jC(this,null,(function*(){Fw.emit(Hw.LEAVE_START,{room:this}),yield e.call(this,...i),Fw.emit(Hw.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),ZL("leave room"),CM({fnName:"publish",validateArgs:!1}),CM({fnName:"unsubscribe",validateArgs:!1})],aW.prototype,"leave",1),HC([QL(),KL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return jC(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"capture"===e.state)),!i.length))return;Fw.emit("61",{room:this});let t=e.apply(this,i);return i.forEach((e=>e.publish(this,t))),t}))})),RM({settings:{retries:pk,timeout:e=>sD(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),Fw.emit(Hw.PUBLISH_FAILED,{room:this}))}})],aW.prototype,"publish",1),HC([CM({fnName:"publish"}),(tW="api-call",function(e,t,i){let r=i.value;return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let n=YL.get(this);if(n){let e=n.queue.filter(((e,i)=>{if(0===i)return!0;let r=!0;return e.args.forEach((e=>{t.find((t=>t===e))||(r=!1)})),!r||(e.reject(new nb({code:ib.API_CALL_ABORTED,message:tW})),!1)}));n.queue=e}return r.apply(this,t)},i}),QL(),KL((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})),WL((function(){var e,t;0===this.localTracks.size&&OP()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((e=>e.track&&e.replaceTrack(null))))}))],aW.prototype,"unpublish",1),HC([jL((e=>{if(e.code!==ib.API_CALL_ABORTED)throw e})),$L((e=>e.userId))],aW.prototype,"replaceTrack",1),HC([$L((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),gx(),KL((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})),RM({settings:{retries:pk,timeout:e=>sD(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),Fw.emit(Hw.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],aW.prototype,"subscribe",1),HC([CM({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")}))}}),$L((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],aW.prototype,"unsubscribe",1),jB.create=jB._create.bind(jB,aW),jB}));
|