trtc-sdk-v5 5.13.0-beta.14 → 5.13.0-beta.16
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/debug-dialog.js +1 -1
- package/index.d.ts +45 -1
- package/package.json +1 -1
- package/plugins/cdn-streaming/cdn-streaming.esm.js +1 -1
- package/plugins/cdn-streaming/cdn-streaming.umd.js +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/cross-room/cross-room.esm.js +1 -1
- package/plugins/cross-room/cross-room.umd.js +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/custom-encryption.esm.js +1 -1
- package/plugins/custom-encryption/custom-encryption.umd.js +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/device-detector.esm.js +28 -14
- package/plugins/device-detector/device-detector.umd.js +21 -7
- package/plugins/device-detector/package.json +1 -1
- package/plugins/small-stream-auto-switcher/package.json +1 -1
- package/plugins/small-stream-auto-switcher/small-stream-auto-switcher.esm.js +1 -1
- package/plugins/small-stream-auto-switcher/small-stream-auto-switcher.umd.js +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-decoder/video-decoder.esm.js +1 -1
- package/plugins/video-decoder/video-decoder.umd.js +1 -1
- package/plugins/video-effect/basic-beauty/basic-beauty.esm.js +1 -1
- package/plugins/video-effect/basic-beauty/basic-beauty.umd.js +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/beauty.esm.js +1 -1
- package/plugins/video-effect/beauty/beauty.umd.js +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/video-mixer/package.json +1 -1
- package/plugins/video-effect/video-mixer/video-mixer.esm.js +1 -1
- package/plugins/video-effect/video-mixer/video-mixer.umd.js +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/video-effect/watermark/watermark.esm.js +1 -1
- package/plugins/video-effect/watermark/watermark.umd.js +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/plugins/voice-changer/voice-changer.esm.js +1 -1
- package/plugins/voice-changer/voice-changer.umd.js +1 -1
- package/trtc.esm.js +28 -28
- package/trtc.js +1 -1
package/trtc.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TRTC=t()}(this,(function(){function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r=function(e){return e&&e.Math===Math&&e},n=r("object"==typeof globalThis&&globalThis)||r("object"==typeof window&&window)||r("object"==typeof self&&self)||r("object"==typeof t&&t)||r("object"==typeof t&&t)||function(){return this}()||Function("return this")(),o={},s=function(e){try{return!!e()}catch(t){return!0}},a=!s((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})),c=!s((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),l=c,d=Function.prototype.call,u=l?d.bind(d):function(){return d.apply(d,arguments)},h={},p={}.propertyIsEnumerable,m=Object.getOwnPropertyDescriptor,_=m&&!p.call({1:2},1);h.f=_?function(e){var t=m(this,e);return!!t&&t.enumerable}:p;var f,g,E=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},T=c,v=Function.prototype,y=v.call,S=T&&v.bind.bind(y,y),I=T?S:function(e){return function(){return y.apply(e,arguments)}},A=I,R=A({}.toString),C=A("".slice),b=function(e){return C(R(e),8,-1)},k=s,D=b,w=Object,N=I("".split),O=k((function(){return!w("z").propertyIsEnumerable(0)}))?function(e){return"String"===D(e)?N(e,""):w(e)}:w,M=function(e){return null==e},P=M,L=TypeError,x=function(e){if(P(e))throw new L("Can't call method on "+e);return e},V=O,U=x,F=function(e){return V(U(e))},B="object"==typeof document&&document.all,H=void 0===B&&void 0!==B?function(e){return"function"==typeof e||e===B}:function(e){return"function"==typeof e},W=H,G=function(e){return"object"==typeof e?null!==e:W(e)},j=n,J=H,K=function(e,t){return arguments.length<2?(i=j[e],J(i)?i:void 0):j[e]&&j[e][t];var i},q=I({}.isPrototypeOf),z=n.navigator,Y=z&&z.userAgent,X=Y?String(Y):"",Q=n,Z=X,$=Q.process,ee=Q.Deno,te=$&&$.versions||ee&&ee.version,ie=te&&te.v8;ie&&(g=(f=ie.split("."))[0]>0&&f[0]<4?1:+(f[0]+f[1])),!g&&Z&&(!(f=Z.match(/Edge\/(\d+)/))||f[1]>=74)&&(f=Z.match(/Chrome\/(\d+)/))&&(g=+f[1]);var re=g,ne=re,oe=s,se=n.String,ae=!!Object.getOwnPropertySymbols&&!oe((function(){var e=Symbol("symbol detection");return!se(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),ce=ae&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,le=K,de=H,ue=q,he=Object,pe=ce?function(e){return"symbol"==typeof e}:function(e){var t=le("Symbol");return de(t)&&ue(t.prototype,he(e))},me=String,_e=function(e){try{return me(e)}catch(t){return"Object"}},fe=H,ge=_e,Ee=TypeError,Te=function(e){if(fe(e))return e;throw new Ee(ge(e)+" is not a function")},ve=Te,ye=M,Se=function(e,t){var i=e[t];return ye(i)?void 0:ve(i)},Ie=u,Ae=H,Re=G,Ce=TypeError,be={exports:{}},ke=n,De=Object.defineProperty,we=function(e,t){try{De(ke,e,{value:t,configurable:!0,writable:!0})}catch(i){ke[e]=t}return t},Ne=n,Oe=we,Me="__core-js_shared__",Pe=be.exports=Ne[Me]||Oe(Me,{});(Pe.versions||(Pe.versions=[])).push({version:"3.40.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.40.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Le=be.exports,xe=Le,Ve=function(e,t){return xe[e]||(xe[e]=t||{})},Ue=x,Fe=Object,Be=function(e){return Fe(Ue(e))},He=Be,We=I({}.hasOwnProperty),Ge=Object.hasOwn||function(e,t){return We(He(e),t)},je=I,Je=0,Ke=Math.random(),qe=je(1..toString),ze=function(e){return"Symbol("+(void 0===e?"":e)+")_"+qe(++Je+Ke,36)},Ye=Ve,Xe=Ge,Qe=ze,Ze=ae,$e=ce,et=n.Symbol,tt=Ye("wks"),it=$e?et.for||et:et&&et.withoutSetter||Qe,rt=function(e){return Xe(tt,e)||(tt[e]=Ze&&Xe(et,e)?et[e]:it("Symbol."+e)),tt[e]},nt=u,ot=G,st=pe,at=Se,ct=function(e,t){var i,r;if("string"===t&&Ae(i=e.toString)&&!Re(r=Ie(i,e)))return r;if(Ae(i=e.valueOf)&&!Re(r=Ie(i,e)))return r;if("string"!==t&&Ae(i=e.toString)&&!Re(r=Ie(i,e)))return r;throw new Ce("Can't convert object to primitive value")},lt=TypeError,dt=rt("toPrimitive"),ut=function(e,t){if(!ot(e)||st(e))return e;var i,r=at(e,dt);if(r){if(void 0===t&&(t="default"),i=nt(r,e,t),!ot(i)||st(i))return i;throw new lt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ct(e,t)},ht=ut,pt=pe,mt=function(e){var t=ht(e,"string");return pt(t)?t:t+""},_t=G,ft=n.document,gt=_t(ft)&&_t(ft.createElement),Et=function(e){return gt?ft.createElement(e):{}},Tt=Et,vt=!a&&!s((function(){return 7!==Object.defineProperty(Tt("div"),"a",{get:function(){return 7}}).a})),yt=a,St=u,It=h,At=E,Rt=F,Ct=mt,bt=Ge,kt=vt,Dt=Object.getOwnPropertyDescriptor;o.f=yt?Dt:function(e,t){if(e=Rt(e),t=Ct(t),kt)try{return Dt(e,t)}catch(i){}if(bt(e,t))return At(!St(It.f,e,t),e[t])};var wt={},Nt=a&&s((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Ot=G,Mt=String,Pt=TypeError,Lt=function(e){if(Ot(e))return e;throw new Pt(Mt(e)+" is not an object")},xt=a,Vt=vt,Ut=Nt,Ft=Lt,Bt=mt,Ht=TypeError,Wt=Object.defineProperty,Gt=Object.getOwnPropertyDescriptor,jt="enumerable",Jt="configurable",Kt="writable";wt.f=xt?Ut?function(e,t,i){if(Ft(e),t=Bt(t),Ft(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Kt in i&&!i[Kt]){var r=Gt(e,t);r&&r[Kt]&&(e[t]=i.value,i={configurable:Jt in i?i[Jt]:r[Jt],enumerable:jt in i?i[jt]:r[jt],writable:!1})}return Wt(e,t,i)}:Wt:function(e,t,i){if(Ft(e),t=Bt(t),Ft(i),Vt)try{return Wt(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Ht("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var qt=wt,zt=E,Yt=a?function(e,t,i){return qt.f(e,t,zt(1,i))}:function(e,t,i){return e[t]=i,e},Xt={exports:{}},Qt=a,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=H,ni=Le,oi=I(Function.toString);ri(ni.inspectSource)||(ni.inspectSource=function(e){return oi(e)});var si,ai,ci,li=ni.inspectSource,di=H,ui=n.WeakMap,hi=di(ui)&&/native code/.test(String(ui)),pi=ze,mi=Ve("keys"),_i=function(e){return mi[e]||(mi[e]=pi(e))},fi={},gi=hi,Ei=n,Ti=G,vi=Yt,yi=Ge,Si=Le,Ii=_i,Ai=fi,Ri="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,si=function(e,t){if(ki.has(e))throw new Ci(Ri);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");Ai[Di]=!0,si=function(e,t){if(yi(e,Di))throw new Ci(Ri);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 wi={set:si,get:ai,has:ci,enforce:function(e){return ci(e)?ai(e):si(e,{})},getterFor:function(e){return function(t){var i;if(!Ti(t)||(i=ai(t)).type!==e)throw new Ci("Incompatible receiver, "+e+" required");return i}}},Ni=I,Oi=s,Mi=H,Pi=Ge,Li=a,xi=ii.CONFIGURABLE,Vi=li,Ui=wi.enforce,Fi=wi.get,Bi=String,Hi=Object.defineProperty,Wi=Ni("".slice),Gi=Ni("".replace),ji=Ni([].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("===Wi(Bi(t),0,7)&&(t="["+Gi(Bi(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Pi(e,"name")||xi&&e.name!==t)&&(Li?Hi(e,"name",{value:t,configurable:!0}):e.name=t),Ji&&i&&Pi(i,"arity")&&e.length!==i.arity&&Hi(e,"length",{value:i.arity});try{i&&Pi(i,"constructor")&&i.constructor?Li&&Hi(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var r=Ui(e);return Pi(r,"source")||(r.source=ji(Ki,"string"==typeof t?t:"")),e};Function.prototype.toString=qi((function(){return Mi(this)&&Fi(this).source||Vi(this)}),"toString");var zi=Xt.exports,Yi=H,Xi=wt,Qi=zi,Zi=we,$i=function(e,t,i,r){r||(r={});var n=r.enumerable,o=void 0!==r.name?r.name:t;if(Yi(i)&&Qi(i,o,r),r.global)n?e[t]=i:Zi(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch(s){}n?e[t]=i:Xi.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},er={},tr=Math.ceil,ir=Math.floor,rr=Math.trunc||function(e){var t=+e;return(t>0?ir:tr)(t)},nr=rr,or=function(e){var t=+e;return t!=t||0===t?0:nr(t)},sr=or,ar=Math.max,cr=Math.min,lr=function(e,t){var i=sr(e);return i<0?ar(i+t,0):cr(i,t)},dr=or,ur=Math.min,hr=function(e){var t=dr(e);return t>0?ur(t,9007199254740991):0},pr=hr,mr=function(e){return pr(e.length)},_r=F,fr=lr,gr=mr,Er=function(e){return function(t,i,r){var n=_r(t),o=gr(n);if(0===o)return!e&&-1;var s,a=fr(r,o);if(e&&i!=i){for(;o>a;)if((s=n[a++])!=s)return!0}else for(;o>a;a++)if((e||a in n)&&n[a]===i)return e||a||0;return!e&&-1}},Tr={includes:Er(!0),indexOf:Er(!1)},vr=Ge,yr=F,Sr=Tr.indexOf,Ir=fi,Ar=I([].push),Rr=function(e,t){var i,r=yr(e),n=0,o=[];for(i in r)!vr(Ir,i)&&vr(r,i)&&Ar(o,i);for(;t.length>n;)vr(r,i=t[n++])&&(~Sr(o,i)||Ar(o,i));return o},Cr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],br=Rr,kr=Cr.concat("length","prototype");er.f=Object.getOwnPropertyNames||function(e){return br(e,kr)};var Dr={};Dr.f=Object.getOwnPropertySymbols;var wr=K,Nr=er,Or=Dr,Mr=Lt,Pr=I([].concat),Lr=wr("Reflect","ownKeys")||function(e){var t=Nr.f(Mr(e)),i=Or.f;return i?Pr(t,i(e)):t},xr=Ge,Vr=Lr,Ur=o,Fr=wt,Br=function(e,t,i){for(var r=Vr(t),n=Fr.f,o=Ur.f,s=0;s<r.length;s++){var a=r[s];xr(e,a)||i&&xr(i,a)||n(e,a,o(t,a))}},Hr=s,Wr=H,Gr=/#|\.prototype\./,jr=function(e,t){var i=Kr[Jr(e)];return i===zr||i!==qr&&(Wr(t)?Hr(t):!!t)},Jr=jr.normalize=function(e){return String(e).replace(Gr,".").toLowerCase()},Kr=jr.data={},qr=jr.NATIVE="N",zr=jr.POLYFILL="P",Yr=jr,Xr=n,Qr=o.f,Zr=Yt,$r=$i,en=we,tn=Br,rn=Yr,nn=function(e,t){var i,r,n,o,s,a=e.target,c=e.global,l=e.stat;if(i=c?Xr:l?Xr[a]||en(a,{}):Xr[a]&&Xr[a].prototype)for(r in t){if(o=t[r],n=e.dontCallGetSet?(s=Qr(i,r))&&s.value:i[r],!rn(c?r:a+(l?".":"#")+r,e.forced)&&void 0!==n){if(typeof o==typeof n)continue;tn(o,n)}(e.sham||n&&n.sham)&&Zr(o,"sham",!0),$r(i,r,o,e)}},on={};on[rt("toStringTag")]="z";var sn="[object z]"===String(on),an=H,cn=b,ln=rt("toStringTag"),dn=Object,un="Arguments"===cn(function(){return arguments}()),hn=sn?cn:function(e){var t,i,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(i){}}(t=dn(e),ln))?i:un?cn(t):"Object"===(r=cn(t))&&an(t.callee)?"Arguments":r},pn=hn,mn=String,_n=function(e){if("Symbol"===pn(e))throw new TypeError("Cannot convert a Symbol value to a string");return mn(e)},fn=zi,gn=wt,En=function(e,t,i){return i.get&&fn(i.get,t,{getter:!0}),i.set&&fn(i.set,t,{setter:!0}),gn.f(e,t,i)},Tn=nn,vn=a,yn=I,Sn=Ge,In=H,An=q,Rn=_n,Cn=En,bn=Br,kn=n.Symbol,Dn=kn&&kn.prototype;if(vn&&In(kn)&&(!("description"in Dn)||void 0!==kn().description)){var wn={},Nn=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:Rn(arguments[0]),t=An(Dn,this)?new kn(e):void 0===e?kn():kn(e);return""===e&&(wn[t]=!0),t};bn(Nn,kn),Nn.prototype=Dn,Dn.constructor=Nn;var On="Symbol(description detection)"===String(kn("description detection")),Mn=yn(Dn.valueOf),Pn=yn(Dn.toString),Ln=/^Symbol\((.*)\)[^)]+$/,xn=yn("".replace),Vn=yn("".slice);Cn(Dn,"description",{configurable:!0,get:function(){var e=Mn(this);if(Sn(wn,e))return"";var t=Pn(e),i=On?Vn(t,7,-1):xn(t,Ln,"$1");return""===i?void 0:i}}),Tn({global:!0,constructor:!0,forced:!0},{Symbol:Nn})}var Un={},Fn=Rr,Bn=Cr,Hn=Object.keys||function(e){return Fn(e,Bn)},Wn=a,Gn=Nt,jn=wt,Jn=Lt,Kn=F,qn=Hn;Un.f=Wn&&!Gn?Object.defineProperties:function(e,t){Jn(e);for(var i,r=Kn(t),n=qn(t),o=n.length,s=0;o>s;)jn.f(e,i=n[s++],r[i]);return e};var zn,Yn=K("document","documentElement"),Xn=Lt,Qn=Un,Zn=Cr,$n=fi,eo=Yn,to=Et,io="prototype",ro="script",no=_i("IE_PROTO"),oo=function(){},so=function(e){return"<"+ro+">"+e+"</"+ro+">"},ao=function(e){e.write(so("")),e.close();var t=e.parentWindow.Object;return e=null,t},co=function(){try{zn=new ActiveXObject("htmlfile")}catch(n){}var e,t,i;co="undefined"!=typeof document?document.domain&&zn?ao(zn):(t=to("iframe"),i="java"+ro+":",t.style.display="none",eo.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(so("document.F=Object")),e.close(),e.F):ao(zn);for(var r=Zn.length;r--;)delete co[io][Zn[r]];return co()};$n[no]=!0;var lo=Object.create||function(e,t){var i;return null!==e?(oo[io]=Xn(e),i=new oo,oo[io]=null,i[no]=e):i=co(),void 0===t?i:Qn.f(i,t)},uo=rt,ho=lo,po=wt.f,mo=uo("unscopables"),_o=Array.prototype;void 0===_o[mo]&&po(_o,mo,{configurable:!0,value:ho(null)});var fo=function(e){_o[mo][e]=!0},go=Tr.includes,Eo=fo;nn({target:"Array",proto:!0,forced:s((function(){return!Array(1).includes()}))},{includes:function(e){return go(this,e,arguments.length>1?arguments[1]:void 0)}}),Eo("includes");var To,vo,yo,So={},Io=!s((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Ao=Ge,Ro=H,Co=Be,bo=Io,ko=_i("IE_PROTO"),Do=Object,wo=Do.prototype,No=bo?Do.getPrototypeOf:function(e){var t=Co(e);if(Ao(t,ko))return t[ko];var i=t.constructor;return Ro(i)&&t instanceof i?i.prototype:t instanceof Do?wo:null},Oo=s,Mo=H,Po=G,Lo=No,xo=$i,Vo=rt("iterator"),Uo=!1;[].keys&&("next"in(yo=[].keys())?(vo=Lo(Lo(yo)))!==Object.prototype&&(To=vo):Uo=!0);var Fo=!Po(To)||Oo((function(){var e={};return To[Vo].call(e)!==e}));Fo&&(To={}),Mo(To[Vo])||xo(To,Vo,(function(){return this}));var Bo={IteratorPrototype:To,BUGGY_SAFARI_ITERATORS:Uo},Ho=wt.f,Wo=Ge,Go=rt("toStringTag"),jo=function(e,t,i){e&&!i&&(e=e.prototype),e&&!Wo(e,Go)&&Ho(e,Go,{configurable:!0,value:t})},Jo=Bo.IteratorPrototype,Ko=lo,qo=E,zo=jo,Yo=So,Xo=function(){return this},Qo=function(e,t,i,r){var n=t+" Iterator";return e.prototype=Ko(Jo,{next:qo(+!r,i)}),zo(e,n,!1),Yo[n]=Xo,e},Zo=I,$o=Te,es=G,ts=function(e){return es(e)||null===e},is=String,rs=TypeError,ns=function(e,t,i){try{return Zo($o(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},os=G,ss=x,as=function(e){if(ts(e))return e;throw new rs("Can't set "+is(e)+" as a prototype")},cs=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=ns(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return ss(i),as(r),os(i)?(t?e(i,r):i.__proto__=r,i):i}}():void 0),ls=nn,ds=u,us=H,hs=Qo,ps=No,ms=cs,_s=jo,fs=Yt,gs=$i,Es=So,Ts=ii.PROPER,vs=ii.CONFIGURABLE,ys=Bo.IteratorPrototype,Ss=Bo.BUGGY_SAFARI_ITERATORS,Is=rt("iterator"),As="keys",Rs="values",Cs="entries",bs=function(){return this},ks=function(e,t,i,r,n,o,s){hs(i,t,r);var a,c,l,d=function(e){if(e===n&&_)return _;if(!Ss&&e&&e in p)return p[e];switch(e){case As:case Rs:case Cs:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[Is]||p["@@iterator"]||n&&p[n],_=!Ss&&m||d(n),f="Array"===t&&p.entries||m;if(f&&(a=ps(f.call(new e)))!==Object.prototype&&a.next&&(ps(a)!==ys&&(ms?ms(a,ys):us(a[Is])||gs(a,Is,bs)),_s(a,u,!0)),Ts&&n===Rs&&m&&m.name!==Rs&&(vs?fs(p,"name",Rs):(h=!0,_=function(){return ds(m,this)})),n)if(c={values:d(Rs),keys:o?_:d(As),entries:d(Cs)},s)for(l in c)(Ss||h||!(l in p))&&gs(p,l,c[l]);else ls({target:t,proto:!0,forced:Ss||h},c);return p[Is]!==_&&gs(p,Is,_,{name:n}),Es[t]=_,c},Ds=function(e,t){return{value:e,done:t}},ws=F,Ns=fo,Os=So,Ms=wi,Ps=wt.f,Ls=ks,xs=Ds,Vs=a,Us="Array Iterator",Fs=Ms.set,Bs=Ms.getterFor(Us),Hs=Ls(Array,"Array",(function(e,t){Fs(this,{type:Us,target:ws(e),index:0,kind:t})}),(function(){var e=Bs(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,xs(void 0,!0);switch(e.kind){case"keys":return xs(i,!1);case"values":return xs(t[i],!1)}return xs([i,t[i]],!1)}),"values"),Ws=Os.Arguments=Os.Array;if(Ns("keys"),Ns("values"),Ns("entries"),Vs&&"values"!==Ws.name)try{Ps(Ws,"name",{value:"values"})}catch(RJ){}var Gs=Te,js=Be,Js=O,Ks=mr,qs=TypeError,zs="Reduce of empty array with no initial value",Ys=function(e){return function(t,i,r,n){var o=js(t),s=Js(o),a=Ks(o);if(Gs(i),0===a&&r<2)throw new qs(zs);var c=e?a-1:0,l=e?-1:1;if(r<2)for(;;){if(c in s){n=s[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw new qs(zs)}for(;e?c>=0:a>c;c+=l)c in s&&(n=i(n,s[c],c,o));return n}},Xs={left:Ys(!1),right:Ys(!0)},Qs=s,Zs=function(e,t){var i=[][e];return!!i&&Qs((function(){i.call(null,t||function(){return 1},1)}))},$s=n,ea=X,ta=b,ia=function(e){return ea.slice(0,e.length)===e},ra=ia("Bun/")?"BUN":ia("Cloudflare-Workers")?"CLOUDFLARE":ia("Deno/")?"DENO":ia("Node.js/")?"NODE":$s.Bun&&"string"==typeof Bun.version?"BUN":$s.Deno&&"object"==typeof Deno.version?"DENO":"process"===ta($s.process)?"NODE":$s.window&&$s.document?"BROWSER":"REST",na="NODE"===ra,oa=Xs.left;nn({target:"Array",proto:!0,forced:!na&&re>79&&re<83||!Zs("reduce")},{reduce:function(e){var t=arguments.length;return oa(this,e,t,t>1?arguments[1]:void 0)}});var sa=Xs.right;nn({target:"Array",proto:!0,forced:!na&&re>79&&re<83||!Zs("reduceRight")},{reduceRight:function(e){return sa(this,e,arguments.length,arguments.length>1?arguments[1]:void 0)}});var aa=b,ca=Array.isArray||function(e){return"Array"===aa(e)},la=nn,da=ca,ua=I([].reverse),ha=[1,2];la({target:"Array",proto:!0,forced:String(ha)===String(ha.reverse())},{reverse:function(){return da(this)&&(this.length=this.length),ua(this)}});var pa=_e,ma=TypeError,_a=I([].slice),fa=_a,ga=Math.floor,Ea=function(e,t){var i=e.length;if(i<8)for(var r,n,o=1;o<i;){for(n=o,r=e[o];n&&t(e[n-1],r)>0;)e[n]=e[--n];n!==o++&&(e[n]=r)}else for(var s=ga(i/2),a=Ea(fa(e,0,s),t),c=Ea(fa(e,s),t),l=a.length,d=c.length,u=0,h=0;u<l||h<d;)e[u+h]=u<l&&h<d?t(a[u],c[h])<=0?a[u++]:c[h++]:u<l?a[u++]:c[h++];return e},Ta=Ea,va=X.match(/firefox\/(\d+)/i),ya=!!va&&+va[1],Sa=/MSIE|Trident/.test(X),Ia=X.match(/AppleWebKit\/(\d+)\./),Aa=!!Ia&&+Ia[1],Ra=nn,Ca=I,ba=Te,ka=Be,Da=mr,wa=function(e,t){if(!delete e[t])throw new ma("Cannot delete property "+pa(t)+" of "+pa(e))},Na=_n,Oa=s,Ma=Ta,Pa=Zs,La=ya,xa=Sa,Va=re,Ua=Aa,Fa=[],Ba=Ca(Fa.sort),Ha=Ca(Fa.push),Wa=Oa((function(){Fa.sort(void 0)})),Ga=Oa((function(){Fa.sort(null)})),ja=Pa("sort"),Ja=!Oa((function(){if(Va)return Va<70;if(!(La&&La>3)){if(xa)return!0;if(Ua)return Ua<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++)Fa.push({k:t+r,v:i})}for(Fa.sort((function(e,t){return t.v-e.v})),r=0;r<Fa.length;r++)t=Fa[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));Ra({target:"Array",proto:!0,forced:Wa||!Ga||!ja||!Ja},{sort:function(e){void 0!==e&&ba(e);var t=ka(this);if(Ja)return void 0===e?Ba(t):Ba(t,e);var i,r,n=[],o=Da(t);for(r=0;r<o;r++)r in t&&Ha(n,t[r]);for(Ma(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=Da(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)wa(t,r++);return t}});var Ka="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,qa=$i,za=function(e,t,i){for(var r in t)qa(e,r,t[r],i);return e},Ya=q,Xa=TypeError,Qa=function(e,t){if(Ya(t,e))return e;throw new Xa("Incorrect invocation")},Za=or,$a=hr,ec=RangeError,tc=function(e){if(void 0===e)return 0;var t=Za(e),i=$a(t);if(t!==i)throw new ec("Wrong length or index");return i},ic=Math.sign||function(e){var t=+e;return 0===t||t!=t?t:t<0?-1:1},rc=4503599627370496,nc=ic,oc=function(e){return e+rc-rc},sc=Math.abs,ac=function(e,t,i,r){var n=+e,o=sc(n),s=nc(n);if(o<r)return s*oc(o/r/t)*r*t;var a=(1+t/2220446049250313e-31)*o,c=a-(a-o);return c>i||c!=c?Infinity*s:s*c},cc=Math.fround||function(e){return ac(e,1.1920928955078125e-7,34028234663852886e22,11754943508222875e-54)},lc=Array,dc=Math.abs,uc=Math.pow,hc=Math.floor,pc=Math.log,mc=Math.LN2,_c={pack:function(e,t,i){var r,n,o,s=lc(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?uc(2,-24)-uc(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=dc(e))!=e||Infinity===e?(n=e!=e?1:0,r=c):(r=hc(pc(e)/mc),e*(o=uc(2,-r))<1&&(r--,o*=2),(e+=r+l>=1?d/o:d*uc(2,1-l))*o>=2&&(r++,o/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*o-1)*uc(2,t),r+=l):(n=e*uc(2,l-1)*uc(2,t),r=0));t>=8;)s[h++]=255&n,n/=256,t-=8;for(r=r<<t|n,a+=t;a>0;)s[h++]=255&r,r/=256,a-=8;return s[h-1]|=128*u,s},unpack:function(e,t){var i,r=e.length,n=8*r-t-1,o=(1<<n)-1,s=o>>1,a=n-7,c=r-1,l=e[c--],d=127&l;for(l>>=7;a>0;)d=256*d+e[c--],a-=8;for(i=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)i=256*i+e[c--],a-=8;if(0===d)d=1-s;else{if(d===o)return i?NaN:l?-Infinity:Infinity;i+=uc(2,t),d-=s}return(l?-1:1)*i*uc(2,d-t)}},fc=Be,gc=lr,Ec=mr,Tc=function(e){for(var t=fc(this),i=Ec(t),r=arguments.length,n=gc(r>1?arguments[1]:void 0,i),o=r>2?arguments[2]:void 0,s=void 0===o?i:gc(o,i);s>n;)t[n++]=e;return t},vc=H,yc=G,Sc=cs,Ic=function(e,t,i){var r,n;return Sc&&vc(r=t.constructor)&&r!==i&&yc(n=r.prototype)&&n!==i.prototype&&Sc(e,n),e},Ac=n,Rc=I,Cc=a,bc=Ka,kc=Yt,Dc=En,wc=za,Nc=s,Oc=Qa,Mc=or,Pc=hr,Lc=tc,xc=cc,Vc=_c,Uc=No,Fc=cs,Bc=Tc,Hc=_a,Wc=Ic,Gc=Br,jc=jo,Jc=wi,Kc=ii.PROPER,qc=ii.CONFIGURABLE,zc="ArrayBuffer",Yc="DataView",Xc="prototype",Qc="Wrong index",Zc=Jc.getterFor(zc),$c=Jc.getterFor(Yc),el=Jc.set,tl=Ac[zc],il=tl,rl=il&&il[Xc],nl=Ac[Yc],ol=nl&&nl[Xc],sl=Object.prototype,al=Ac.Array,cl=Ac.RangeError,ll=Rc(Bc),dl=Rc([].reverse),ul=Vc.pack,hl=Vc.unpack,pl=function(e){return[255&e]},ml=function(e){return[255&e,e>>8&255]},_l=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},fl=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},gl=function(e){return ul(xc(e),23,4)},El=function(e){return ul(e,52,8)},Tl=function(e,t,i){Dc(e[Xc],t,{configurable:!0,get:function(){return i(this)[t]}})},vl=function(e,t,i,r){var n=$c(e),o=Lc(i),s=!!r;if(o+t>n.byteLength)throw new cl(Qc);var a=n.bytes,c=o+n.byteOffset,l=Hc(a,c,c+t);return s?l:dl(l)},yl=function(e,t,i,r,n,o){var s=$c(e),a=Lc(i),c=r(+n),l=!!o;if(a+t>s.byteLength)throw new cl(Qc);for(var d=s.bytes,u=a+s.byteOffset,h=0;h<t;h++)d[u+h]=c[l?h:t-h-1]};if(bc){var Sl=Kc&&tl.name!==zc;Nc((function(){tl(1)}))&&Nc((function(){new tl(-1)}))&&!Nc((function(){return new tl,new tl(1.5),new tl(NaN),1!==tl.length||Sl&&!qc}))?Sl&&qc&&kc(tl,"name",zc):((il=function(e){return Oc(this,rl),Wc(new tl(Lc(e)),this,il)})[Xc]=rl,rl.constructor=il,Gc(il,tl)),Fc&&Uc(ol)!==sl&&Fc(ol,sl);var Il=new nl(new il(2)),Al=Rc(ol.setInt8);Il.setInt8(0,2147483648),Il.setInt8(1,2147483649),!Il.getInt8(0)&&Il.getInt8(1)||wc(ol,{setInt8:function(e,t){Al(this,e,t<<24>>24)},setUint8:function(e,t){Al(this,e,t<<24>>24)}},{unsafe:!0})}else rl=(il=function(e){Oc(this,rl);var t=Lc(e);el(this,{type:zc,bytes:ll(al(t),0),byteLength:t}),Cc||(this.byteLength=t,this.detached=!1)})[Xc],ol=(nl=function(e,t,i){Oc(this,ol),Oc(e,rl);var r=Zc(e),n=r.byteLength,o=Mc(t);if(o<0||o>n)throw new cl("Wrong offset");if(o+(i=void 0===i?n-o:Pc(i))>n)throw new cl("Wrong length");el(this,{type:Yc,buffer:e,byteLength:i,byteOffset:o,bytes:r.bytes}),Cc||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[Xc],Cc&&(Tl(il,"byteLength",Zc),Tl(nl,"buffer",$c),Tl(nl,"byteLength",$c),Tl(nl,"byteOffset",$c)),wc(ol,{getInt8:function(e){return vl(this,1,e)[0]<<24>>24},getUint8:function(e){return vl(this,1,e)[0]},getInt16:function(e){var t=vl(this,2,e,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=vl(this,2,e,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return fl(vl(this,4,e,arguments.length>1&&arguments[1]))},getUint32:function(e){return fl(vl(this,4,e,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(e){return hl(vl(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return hl(vl(this,8,e,arguments.length>1&&arguments[1]),52)},setInt8:function(e,t){yl(this,1,e,pl,t)},setUint8:function(e,t){yl(this,1,e,pl,t)},setInt16:function(e,t){yl(this,2,e,ml,t,arguments.length>2&&arguments[2])},setUint16:function(e,t){yl(this,2,e,ml,t,arguments.length>2&&arguments[2])},setInt32:function(e,t){yl(this,4,e,_l,t,arguments.length>2&&arguments[2])},setUint32:function(e,t){yl(this,4,e,_l,t,arguments.length>2&&arguments[2])},setFloat32:function(e,t){yl(this,4,e,gl,t,arguments.length>2&&arguments[2])},setFloat64:function(e,t){yl(this,8,e,El,t,arguments.length>2&&arguments[2])}});jc(il,zc),jc(nl,Yc);var Rl={ArrayBuffer:il,DataView:nl},Cl=K,bl=En,kl=a,Dl=rt("species"),wl=function(e){var t=Cl(e);kl&&t&&!t[Dl]&&bl(t,Dl,{configurable:!0,get:function(){return this}})},Nl=wl,Ol="ArrayBuffer",Ml=Rl[Ol];nn({global:!0,constructor:!0,forced:n[Ol]!==Ml},{ArrayBuffer:Ml}),Nl(Ol);var Pl=b,Ll=I,xl=function(e){if("Function"===Pl(e))return Ll(e)},Vl=nn,Ul=xl,Fl=s,Bl=Lt,Hl=lr,Wl=hr,Gl=Rl.ArrayBuffer,jl=Rl.DataView,Jl=jl.prototype,Kl=Ul(Gl.prototype.slice),ql=Ul(Jl.getUint8),zl=Ul(Jl.setUint8);Vl({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:Fl((function(){return!new Gl(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(Kl&&void 0===t)return Kl(Bl(this),e);for(var i=Bl(this).byteLength,r=Hl(e,i),n=Hl(void 0===t?i:t,i),o=new Gl(Wl(n-r)),s=new jl(this),a=new jl(o),c=0;r<n;)zl(a,c++,ql(s,r++));return o}});var Yl=I,Xl=s,Ql=H,Zl=hn,$l=li,ed=function(){},td=K("Reflect","construct"),id=/^\s*(?:class|function)\b/,rd=Yl(id.exec),nd=!id.test(ed),od=function(e){if(!Ql(e))return!1;try{return td(ed,[],e),!0}catch(RJ){return!1}},sd=function(e){if(!Ql(e))return!1;switch(Zl(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return nd||!!rd(id,$l(e))}catch(RJ){return!0}};sd.sham=!0;var ad,cd,ld,dd,ud=!td||Xl((function(){var e;return od(od.call)||!od(Object)||!od((function(){e=!0}))||e}))?sd:od,hd=ud,pd=_e,md=TypeError,_d=function(e){if(hd(e))return e;throw new md(pd(e)+" is not a constructor")},fd=Lt,gd=_d,Ed=M,Td=rt("species"),vd=function(e,t){var i,r=fd(e).constructor;return void 0===r||Ed(i=fd(r)[Td])?t:gd(i)},yd=c,Sd=Function.prototype,Id=Sd.apply,Ad=Sd.call,Rd="object"==typeof Reflect&&Reflect.apply||(yd?Ad.bind(Id):function(){return Ad.apply(Id,arguments)}),Cd=Te,bd=c,kd=xl(xl.bind),Dd=function(e,t){return Cd(e),void 0===t?e:bd?kd(e,t):function(){return e.apply(t,arguments)}},wd=TypeError,Nd=function(e,t){if(e<t)throw new wd("Not enough arguments");return e},Od=/(?:ipad|iphone|ipod).*applewebkit/i.test(X),Md=n,Pd=Rd,Ld=Dd,xd=H,Vd=Ge,Ud=s,Fd=Yn,Bd=_a,Hd=Et,Wd=Nd,Gd=Od,jd=na,Jd=Md.setImmediate,Kd=Md.clearImmediate,qd=Md.process,zd=Md.Dispatch,Yd=Md.Function,Xd=Md.MessageChannel,Qd=Md.String,Zd=0,$d={},eu="onreadystatechange";Ud((function(){ad=Md.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){Md.postMessage(Qd(e),ad.protocol+"//"+ad.host)};Jd&&Kd||(Jd=function(e){Wd(arguments.length,1);var t=xd(e)?e:Yd(e),i=Bd(arguments,1);return $d[++Zd]=function(){Pd(t,void 0,i)},cd(Zd),Zd},Kd=function(e){delete $d[e]},jd?cd=function(e){qd.nextTick(iu(e))}:zd&&zd.now?cd=function(e){zd.now(iu(e))}:Xd&&!Gd?(dd=(ld=new Xd).port2,ld.port1.onmessage=ru,cd=Ld(dd.postMessage,dd)):Md.addEventListener&&xd(Md.postMessage)&&!Md.importScripts&&ad&&"file:"!==ad.protocol&&!Ud(nu)?(cd=nu,Md.addEventListener("message",ru,!1)):cd=eu in Hd("script")?function(e){Fd.appendChild(Hd("script"))[eu]=function(){Fd.removeChild(this),tu(e)}}:function(e){setTimeout(iu(e),0)});var ou={set:Jd,clear:Kd},su=n,au=a,cu=Object.getOwnPropertyDescriptor,lu=function(e){if(!au)return su[e];var t=cu(su,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(X)&&"undefined"!=typeof Pebble,Eu=/web0s(?!.*chrome)/i.test(X),Tu=n,vu=lu,yu=Dd,Su=ou.set,Iu=fu,Au=Od,Ru=gu,Cu=Eu,bu=na,ku=Tu.MutationObserver||Tu.WebKitMutationObserver,Du=Tu.document,wu=Tu.process,Nu=Tu.Promise,Ou=vu("queueMicrotask");if(!Ou){var Mu=new Iu,Pu=function(){var e,t;for(bu&&(e=wu.domain)&&e.exit();t=Mu.get();)try{t()}catch(RJ){throw Mu.head&&uu(),RJ}e&&e.enter()};Au||bu||Cu||!ku||!Du?!Ru&&Nu&&Nu.resolve?((mu=Nu.resolve(void 0)).constructor=Nu,_u=yu(mu.then,mu),uu=function(){_u(Pu)}):bu?uu=function(){wu.nextTick(Pu)}:(Su=yu(Su,Tu),uu=function(){Su(Pu)}):(hu=!0,pu=Du.createTextNode(""),new ku(Pu).observe(pu,{characterData:!0}),uu=function(){pu.data=hu=!hu}),Ou=function(e){Mu.head||uu(),Mu.add(e)}}var Lu=Ou,xu=function(e){try{return{error:!1,value:e()}}catch(RJ){return{error:!0,value:RJ}}},Vu=n.Promise,Uu=n,Fu=Vu,Bu=H,Hu=Yr,Wu=li,Gu=rt,ju=ra,Ju=re;Fu&&Fu.prototype;var Ku=Gu("species"),qu=!1,zu=Bu(Uu.PromiseRejectionEvent),Yu=Hu("Promise",(function(){var e=Wu(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=Te,$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=nn,oh=na,sh=n,ah=u,ch=$i,lh=cs,dh=jo,uh=wl,hh=Te,ph=H,mh=G,_h=Qa,fh=vd,gh=ou.set,Eh=Lu,Th=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(RJ){}},vh=xu,yh=fu,Sh=wi,Ih=Vu,Ah=Qu,Rh="Promise",Ch=Xu.CONSTRUCTOR,bh=Xu.REJECTION_EVENT,kh=Xu.SUBCLASSING,Dh=Sh.getterFor(Rh),wh=Sh.set,Nh=Ih&&Ih.prototype,Oh=Ih,Mh=Nh,Ph=sh.TypeError,Lh=sh.document,xh=sh.process,Vh=Ah.f,Uh=Vh,Fh=!!(Lh&&Lh.createEvent&&sh.dispatchEvent),Bh="unhandledrejection",Hh=function(e){var t;return!(!mh(e)||!ph(t=e.then))&&t},Wh=function(e,t){var i,r,n,o=t.value,s=1===t.state,a=s?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{a?(s||(2===t.rejection&&qh(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),n=!0)),i===e.promise?l(new Ph("Promise-chain cycle")):(r=Hh(i))?ah(r,i,c,l):c(i)):l(o)}catch(RJ){d&&!n&&d.exit(),l(RJ)}},Gh=function(e,t){e.notified||(e.notified=!0,Eh((function(){for(var i,r=e.reactions;i=r.get();)Wh(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),sh.dispatchEvent(r)):r={promise:t,reason:i},!bh&&(n=sh["on"+e])?n(r):e===Bh&&Th("Unhandled promise rejection",i)},Jh=function(e){ah(gh,sh,(function(){var t,i=e.facade,r=e.value;if(Kh(e)&&(t=vh((function(){oh?xh.emit("unhandledRejection",r,i):jh(Bh,i,r)})),e.rejection=oh||Kh(e)?2:1,t.error))throw t.value}))},Kh=function(e){return 1!==e.rejection&&!e.parent},qh=function(e){ah(gh,sh,(function(){var t=e.facade;oh?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,Gh(e,!0))},Xh=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new Ph("Promise can't be resolved itself");var r=Hh(t);r?Eh((function(){var i={done:!1};try{ah(r,t,zh(Xh,i,e),zh(Yh,i,e))}catch(RJ){Yh(i,RJ,e)}})):(e.value=t,e.state=1,Gh(e,!1))}catch(RJ){Yh({done:!1},RJ,e)}}};if(Ch&&(Mh=(Oh=function(e){_h(this,Mh),hh(e),ah(th,this);var t=Dh(this);try{e(zh(Xh,t),zh(Yh,t))}catch(RJ){Yh(t,RJ)}}).prototype,(th=function(e){wh(this,{type:Rh,done:!1,notified:!1,parent:!1,reactions:new yh,rejection:!1,state:0,value:null})}).prototype=ch(Mh,"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=oh?xh.domain:void 0,0===i.state?i.reactions.add(r):Eh((function(){Wh(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)},Ah.f=Vh=function(e){return e===Oh||undefined===e?new ih(e):Uh(e)},ph(Ih)&&Nh!==Object.prototype)){rh=Nh.then,kh||ch(Nh,"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 Nh.constructor}catch(RJ){}lh&&lh(Nh,Mh)}nh({global:!0,constructor:!0,wrap:!0,forced:Ch},{Promise:Oh}),dh(Oh,Rh,!1),uh(Rh);var Qh=So,Zh=rt("iterator"),$h=Array.prototype,ep=function(e){return void 0!==e&&(Qh.Array===e||$h[Zh]===e)},tp=hn,ip=Se,rp=M,np=So,op=rt("iterator"),sp=function(e){if(!rp(e))return ip(e,op)||ip(e,"@@iterator")||np[tp(e)]},ap=u,cp=Te,lp=Lt,dp=_e,up=sp,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=u,_p=Lt,fp=Se,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(RJ){n=!0,r=RJ}if("throw"===t)throw i;if(n)throw r;return _p(r),i},Ep=Dd,Tp=u,vp=Lt,yp=_e,Sp=ep,Ip=mr,Ap=q,Rp=pp,Cp=sp,bp=gp,kp=TypeError,Dp=function(e,t){this.stopped=e,this.result=t},wp=Dp.prototype,Np=function(e,t,i){var r,n,o,s,a,c,l,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),_=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(o=0,s=Ip(e);s>o;o++)if((a=g(e[o]))&&Ap(wp,a))return a;return new Dp(!1)}r=Rp(e,n)}for(c=h?e.next:r.next;!(l=Tp(c,r)).done;){try{a=g(l.value)}catch(RJ){bp(r,"throw",RJ)}if("object"==typeof a&&a&&Ap(wp,a))return a}return new Dp(!1)},Op=rt("iterator"),Mp=!1;try{var Pp=0,Lp={next:function(){return{done:!!Pp++}},return:function(){Mp=!0}};Lp[Op]=function(){return this},Array.from(Lp,(function(){throw 2}))}catch(RJ){}var xp=function(e,t){try{if(!t&&!Mp)return!1}catch(RJ){return!1}var i=!1;try{var r={};r[Op]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(RJ){}return i},Vp=Vu,Up=Xu.CONSTRUCTOR||!xp((function(e){Vp.all(e).then(void 0,(function(){}))})),Fp=u,Bp=Te,Hp=Qu,Wp=xu,Gp=Np;nn({target:"Promise",stat:!0,forced:Up},{all:function(e){var t=this,i=Hp.f(t),r=i.resolve,n=i.reject,o=Wp((function(){var i=Bp(t.resolve),o=[],s=0,a=1;Gp(e,(function(e){var c=s++,l=!1;a++,Fp(i,t,e).then((function(e){l||(l=!0,o[c]=e,--a||r(o))}),n)})),--a||r(o)}));return o.error&&n(o.value),i.promise}});var jp=nn,Jp=Xu.CONSTRUCTOR,Kp=Vu,qp=K,zp=H,Yp=$i,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=u,$p=Te,em=Qu,tm=xu,im=Np;nn({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;nn({target:"Promise",stat:!0,forced:Xu.CONSTRUCTOR},{reject:function(e){var t=rm.f(this);return(0,t.reject)(e),t.promise}});var nm=Lt,om=G,sm=Qu,am=function(e,t){if(nm(e),om(t)&&t.constructor===e)return t;var i=sm.f(e);return(0,i.resolve)(t),i.promise},cm=nn,lm=Xu.CONSTRUCTOR,dm=am;K("Promise"),cm({target:"Promise",stat:!0,forced:lm},{resolve:function(e){return dm(this,e)}});var um=nn,hm=Vu,pm=s,mm=K,_m=H,fm=vd,gm=am,Em=$i,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=b,Im=rt("match"),Am=function(e){var t;return ym(e)&&(void 0!==(t=e[Im])?!!t:"RegExp"===Sm(e))},Rm=Lt,Cm=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},bm=u,km=Ge,Dm=q,wm=Cm,Nm=RegExp.prototype,Om=function(e){var t=e.flags;return void 0!==t||"flags"in Nm||km(e,"flags")||!Dm(Nm,e)?t:bm(wm,e)},Mm=s,Pm=n.RegExp,Lm=Mm((function(){var e=Pm("a","y");return e.lastIndex=2,null!==e.exec("abcd")})),xm=Lm||Mm((function(){return!Pm("a","y").sticky})),Vm=Lm||Mm((function(){var e=Pm("^r","gy");return e.lastIndex=2,null!==e.exec("str")})),Um={BROKEN_CARET:Vm,MISSED_STICKY:xm,UNSUPPORTED_Y:Lm},Fm=wt.f,Bm=s,Hm=n.RegExp,Wm=Bm((function(){var e=Hm(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)})),Gm=s,jm=n.RegExp,Jm=Gm((function(){var e=jm("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Km=a,qm=n,zm=I,Ym=Yr,Xm=Ic,Qm=Yt,Zm=lo,$m=er.f,e_=q,t_=Am,i_=_n,r_=Om,n_=Um,o_=function(e,t,i){i in e||Fm(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},s_=$i,a_=s,c_=Ge,l_=wi.enforce,d_=wl,u_=Wm,h_=Jm,p_=rt("match"),m_=qm.RegExp,__=m_.prototype,f_=qm.SyntaxError,g_=zm(__.exec),E_=zm("".charAt),T_=zm("".replace),v_=zm("".indexOf),y_=zm("".slice),S_=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,I_=/a/g,A_=/a/g,R_=new m_(I_)!==I_,C_=n_.MISSED_STICKY,b_=n_.UNSUPPORTED_Y,k_=Km&&(!R_||C_||u_||h_||a_((function(){return A_[p_]=!1,m_(I_)!==I_||m_(A_)===A_||"/a/i"!==String(m_(I_,"i"))})));if(Ym("RegExp",k_)){for(var D_=function(e,t){var i,r,n,o,s,a,c=e_(__,this),l=t_(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===D_)return e;if((l||e_(__,e))&&(e=e.source,d&&(t=r_(h))),e=void 0===e?"":i_(e),t=void 0===t?"":i_(t),h=e,u_&&"dotAll"in I_&&(r=!!t&&v_(t,"s")>-1)&&(t=T_(t,/s/g,"")),i=t,C_&&"sticky"in I_&&(n=!!t&&v_(t,"y")>-1)&&b_&&(t=T_(t,/y/g,"")),h_&&(o=function(e){for(var t,i=e.length,r=0,n="",o=[],s=Zm(null),a=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=E_(e,r)))t+=E_(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:if(n+=t,"?:"===y_(e,r+1,r+3))continue;g_(S_,y_(e,r+1))&&(r+=2,c=!0),l++;continue;case">"===t&&c:if(""===d||c_(s,d))throw new f_("Invalid capture group name");s[d]=!0,o[o.length]=[d,l],c=!1,d="";continue}c?d+=t:n+=t}return[n,o]}(e),e=o[0],u=o[1]),s=Xm(m_(e,t),c?this:__,D_),(r||n||u.length)&&(a=l_(s),r&&(a.dotAll=!0,a.raw=D_(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=E_(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+E_(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Qm(s,"source",""===h?"(?:)":h)}catch(RJ){}return s},w_=$m(m_),N_=0;w_.length>N_;)o_(D_,m_,w_[N_++]);__.constructor=D_,D_.prototype=__,s_(qm,"RegExp",D_,{constructor:!0})}d_("RegExp");var O_=u,M_=I,P_=_n,L_=Cm,x_=Um,V_=lo,U_=wi.get,F_=Wm,B_=Jm,H_=Ve("native-string-replace",String.prototype.replace),W_=RegExp.prototype.exec,G_=W_,j_=M_("".charAt),J_=M_("".indexOf),K_=M_("".replace),q_=M_("".slice),z_=function(){var e=/a/,t=/b*/g;return O_(W_,e,"a"),O_(W_,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Y_=x_.BROKEN_CARET,X_=void 0!==/()??/.exec("")[1];(z_||X_||Y_||F_||B_)&&(G_=function(e){var t,i,r,n,o,s,a,c=this,l=U_(c),d=P_(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=O_(G_,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Y_&&c.sticky,m=O_(L_,c),_=c.source,f=0,g=d;if(p&&(m=K_(m,"y",""),-1===J_(m,"g")&&(m+="g"),g=q_(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==j_(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),X_&&(i=new RegExp("^"+_+"$(?!\\s)",m)),z_&&(r=c.lastIndex),n=O_(W_,p?i:c,g),p?n?(n.input=q_(n.input,f),n[0]=q_(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:z_&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),X_&&n&&n.length>1&&O_(H_,n[0],i,(function(){for(o=1;o<arguments.length-2;o++)void 0===arguments[o]&&(n[o]=void 0)})),n&&h)for(n.groups=s=V_(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=n[a[1]];return n});var Q_=G_;nn({target:"RegExp",proto:!0,forced:/./.exec!==Q_},{exec:Q_});var Z_=or,$_=_n,ef=x,tf=RangeError,rf=I,nf=hr,of=_n,sf=function(e){var t=$_(ef(this)),i="",r=Z_(e);if(r<0||Infinity===r)throw new tf("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},af=x,cf=rf(sf),lf=rf("".slice),df=Math.ceil,uf=function(e){return function(t,i,r){var n,o,s=of(af(t)),a=nf(i),c=s.length,l=void 0===r?" ":of(r);return a<=c||""===l?s:((o=cf(l,df((n=a-c)/l.length))).length>n&&(o=lf(o,0,n)),e?s+o:o+s)}},hf={start:uf(!1),end:uf(!0)},pf=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(X),mf=hf.start;nn({target:"String",proto:!0,forced:pf},{padStart:function(e){return mf(this,e,arguments.length>1?arguments[1]:void 0)}});var _f=u,ff=$i,gf=Q_,Ef=s,Tf=rt,vf=Yt,yf=Tf("species"),Sf=RegExp.prototype,If=I,Af=or,Rf=_n,Cf=x,bf=If("".charAt),kf=If("".charCodeAt),Df=If("".slice),wf=function(e){return function(t,i){var r,n,o=Rf(Cf(t)),s=Af(i),a=o.length;return s<0||s>=a?e?"":void 0:(r=kf(o,s))<55296||r>56319||s+1===a||(n=kf(o,s+1))<56320||n>57343?e?bf(o,s):r:e?Df(o,s,s+2):n-56320+(r-55296<<10)+65536}},Nf={codeAt:wf(!1),charAt:wf(!0)},Of=Nf.charAt,Mf=I,Pf=Be,Lf=Math.floor,xf=Mf("".charAt),Vf=Mf("".replace),Uf=Mf("".slice),Ff=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Bf=/\$([$&'`]|\d{1,2})/g,Hf=function(e,t,i,r,n,o){var s=i+e.length,a=r.length,c=Bf;return void 0!==n&&(n=Pf(n),c=Ff),Vf(o,c,(function(o,c){var l;switch(xf(c,0)){case"$":return"$";case"&":return e;case"`":return Uf(t,0,i);case"'":return Uf(t,s);case"<":l=n[Uf(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Lf(d/10);return 0===u?o:u<=a?void 0===r[u-1]?xf(c,1):r[u-1]+xf(c,1):o}l=r[d-1]}return void 0===l?"":l}))},Wf=u,Gf=Lt,jf=H,Jf=b,Kf=Q_,qf=TypeError,zf=Rd,Yf=u,Xf=I,Qf=function(e,t,i,r){var n=Tf(e),o=!Ef((function(){var t={};return t[n]=function(){return 7},7!==""[e](t)})),s=o&&!Ef((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[yf]=function(){return i},i.flags="",i[n]=/./[n]),i.exec=function(){return t=!0,null},i[n](""),!t}));if(!o||!s||i){var a=/./[n],c=t(n,""[e],(function(e,t,i,r,n){var s=t.exec;return s===gf||s===Sf.exec?o&&!n?{done:!0,value:_f(a,t,i,r)}:{done:!0,value:_f(e,i,t,r)}:{done:!1}}));ff(String.prototype,e,c[0]),ff(Sf,n,c[1])}r&&vf(Sf[n],"sham",!0)},Zf=s,$f=Lt,eg=H,tg=M,ig=or,rg=hr,ng=_n,og=x,sg=function(e,t,i){return t+(i?Of(e,t).length:1)},ag=Se,cg=Hf,lg=function(e,t){var i=e.exec;if(jf(i)){var r=Wf(i,e,t);return null!==r&&Gf(r),r}if("RegExp"===Jf(e))return Wf(Kf,e,t);throw new qf("RegExp#exec called on incompatible receiver")},dg=rt("replace"),ug=Math.max,hg=Math.min,pg=Xf([].concat),mg=Xf([].push),_g=Xf("".indexOf),fg=Xf("".slice),gg="$0"==="a".replace(/./,"$0"),Eg=!!/./[dg]&&""===/./[dg]("a","$0"),Tg=!Zf((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));Qf("replace",(function(e,t,i){var r=Eg?"$":"$0";return[function(e,i){var r=og(this),n=tg(e)?void 0:ag(e,dg);return n?Yf(n,e,r,i):Yf(t,ng(r),e,i)},function(e,n){var o=$f(this),s=ng(e);if("string"==typeof n&&-1===_g(n,r)&&-1===_g(n,"$<")){var a=i(t,o,s,n);if(a.done)return a.value}var c=eg(n);c||(n=ng(n));var l,d=o.global;d&&(l=o.unicode,o.lastIndex=0);for(var u,h=[];null!==(u=lg(o,s))&&(mg(h,u),d);){""===ng(u[0])&&(o.lastIndex=sg(s,rg(o.lastIndex),l))}for(var p,m="",_=0,f=0;f<h.length;f++){for(var g,E=ng((u=h[f])[0]),T=ug(hg(ig(u.index),s.length),0),v=[],y=1;y<u.length;y++)mg(v,void 0===(p=u[y])?p:String(p));var S=u.groups;if(c){var I=pg([E],v,T,s);void 0!==S&&mg(I,S),g=ng(zf(n,void 0,I))}else g=cg(E,s,T,v,S,n);T>=_&&(m+=fg(s,_,T)+g,_=T+E.length)}return m+fg(s,_)}]}),!Tg||!gg||Eg);var vg="\t\n\v\f\r \u2028\u2029\ufeff",yg=x,Sg=_n,Ig=vg,Ag=I("".replace),Rg=RegExp("^["+Ig+"]+"),Cg=RegExp("(^|[^"+Ig+"])["+Ig+"]+$"),bg=function(e){return function(t){var i=Sg(yg(t));return 1&e&&(i=Ag(i,Rg,"")),2&e&&(i=Ag(i,Cg,"$1")),i}},kg={start:bg(1),end:bg(2),trim:bg(3)},Dg=ii.PROPER,wg=s,Ng=vg,Og=kg.trim;nn({target:"String",proto:!0,forced:function(e){return wg((function(){return!!Ng[e]()||"
"!=="
"[e]()||Dg&&Ng[e].name!==e}))}("trim")},{trim:function(){return Og(this)}});var Mg,Pg,Lg,xg={exports:{}},Vg=Ka,Ug=a,Fg=n,Bg=H,Hg=G,Wg=Ge,Gg=hn,jg=_e,Jg=Yt,Kg=$i,qg=En,zg=q,Yg=No,Xg=cs,Qg=rt,Zg=ze,$g=wi.enforce,eE=wi.get,tE=Fg.Int8Array,iE=tE&&tE.prototype,rE=Fg.Uint8ClampedArray,nE=rE&&rE.prototype,oE=tE&&Yg(tE),sE=iE&&Yg(iE),aE=Object.prototype,cE=Fg.TypeError,lE=Qg("toStringTag"),dE=Zg("TYPED_ARRAY_TAG"),uE="TypedArrayConstructor",hE=Vg&&!!Xg&&"Opera"!==Gg(Fg.opera),pE=!1,mE={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},_E={BigInt64Array:8,BigUint64Array:8},fE=function(e){var t=Yg(e);if(Hg(t)){var i=eE(t);return i&&Wg(i,uE)?i[uE]:fE(t)}},gE=function(e){if(!Hg(e))return!1;var t=Gg(e);return Wg(mE,t)||Wg(_E,t)};for(Mg in mE)(Lg=(Pg=Fg[Mg])&&Pg.prototype)?$g(Lg)[uE]=Pg:hE=!1;for(Mg in _E)(Lg=(Pg=Fg[Mg])&&Pg.prototype)&&($g(Lg)[uE]=Pg);if((!hE||!Bg(oE)||oE===Function.prototype)&&(oE=function(){throw new cE("Incorrect invocation")},hE))for(Mg in mE)Fg[Mg]&&Xg(Fg[Mg],oE);if((!hE||!sE||sE===aE)&&(sE=oE.prototype,hE))for(Mg in mE)Fg[Mg]&&Xg(Fg[Mg].prototype,sE);if(hE&&Yg(nE)!==sE&&Xg(nE,sE),Ug&&!Wg(sE,lE))for(Mg in pE=!0,qg(sE,lE,{configurable:!0,get:function(){return Hg(this)?this[dE]:void 0}}),mE)Fg[Mg]&&Jg(Fg[Mg],dE,Mg);var EE={NATIVE_ARRAY_BUFFER_VIEWS:hE,TYPED_ARRAY_TAG:pE&&dE,aTypedArray:function(e){if(gE(e))return e;throw new cE("Target is not a typed array")},aTypedArrayConstructor:function(e){if(Bg(e)&&(!Xg||zg(oE,e)))return e;throw new cE(jg(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(Ug){if(i)for(var n in mE){var o=Fg[n];if(o&&Wg(o.prototype,e))try{delete o.prototype[e]}catch(RJ){try{o.prototype[e]=t}catch(s){}}}sE[e]&&!i||Kg(sE,e,i?t:hE&&iE[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(Ug){if(Xg){if(i)for(r in mE)if((n=Fg[r])&&Wg(n,e))try{delete n[e]}catch(RJ){}if(oE[e]&&!i)return;try{return Kg(oE,e,i?t:hE&&oE[e]||t)}catch(RJ){}}for(r in mE)!(n=Fg[r])||n[e]&&!i||Kg(n,e,t)}},getTypedArrayConstructor:fE,isView:function(e){if(!Hg(e))return!1;var t=Gg(e);return"DataView"===t||Wg(mE,t)||Wg(_E,t)},isTypedArray:gE,TypedArray:oE,TypedArrayPrototype:sE},TE=n,vE=s,yE=xp,SE=EE.NATIVE_ARRAY_BUFFER_VIEWS,IE=TE.ArrayBuffer,AE=TE.Int8Array,RE=!SE||!vE((function(){AE(1)}))||!vE((function(){new AE(-1)}))||!yE((function(e){new AE,new AE(null),new AE(1.5),new AE(e)}),!0)||vE((function(){return 1!==new AE(new IE(2),1,void 0).length})),CE=G,bE=Math.floor,kE=Number.isInteger||function(e){return!CE(e)&&isFinite(e)&&bE(e)===e},DE=or,wE=RangeError,NE=function(e){var t=DE(e);if(t<0)throw new wE("The argument can't be less than 0");return t},OE=RangeError,ME=function(e,t){var i=NE(e);if(i%t)throw new OE("Wrong offset");return i},PE=Math.round,LE=hn,xE=ut,VE=TypeError,UE=function(e){var t=xE(e,"number");if("number"==typeof t)throw new VE("Can't convert number to bigint");return BigInt(t)},FE=Dd,BE=u,HE=_d,WE=Be,GE=mr,jE=pp,JE=sp,KE=ep,qE=function(e){var t=LE(e);return"BigInt64Array"===t||"BigUint64Array"===t},zE=EE.aTypedArrayConstructor,YE=UE,XE=function(e){var t,i,r,n,o,s,a,c,l=HE(this),d=WE(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=JE(d);if(m&&!KE(m))for(c=(a=jE(d,m)).next,d=[];!(s=BE(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=FE(h,arguments[2])),i=GE(d),r=new(zE(l))(i),n=qE(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?YE(o):+o;return r},QE=ca,ZE=ud,$E=G,eT=rt("species"),tT=Array,iT=function(e){var t;return QE(e)&&(t=e.constructor,(ZE(t)&&(t===tT||QE(t.prototype))||$E(t)&&null===(t=t[eT]))&&(t=void 0)),void 0===t?tT:t},rT=Dd,nT=O,oT=Be,sT=mr,aT=function(e,t){return new(iT(e))(0===t?0:t)},cT=I([].push),lT=function(e){var t=1===e,i=2===e,r=3===e,n=4===e,o=6===e,s=7===e,a=5===e||o;return function(c,l,d,u){for(var h,p,m=oT(c),_=nT(m),f=sT(_),g=rT(l,d),E=0,T=u||aT,v=t?T(c,f):i||s?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:cT(v,h)}else switch(e){case 4:return!1;case 7:cT(v,h)}return o?-1:r||n?n:v}},dT={forEach:lT(0),map:lT(1),filter:lT(2),some:lT(3),every:lT(4),find:lT(5),findIndex:lT(6),filterReject:lT(7)},uT=mr,hT=nn,pT=n,mT=u,_T=a,fT=RE,gT=EE,ET=Rl,TT=Qa,vT=E,yT=Yt,ST=kE,IT=hr,AT=tc,RT=ME,CT=function(e){var t=PE(e);return t<0?0:t>255?255:255&t},bT=mt,kT=Ge,DT=hn,wT=G,NT=pe,OT=lo,MT=q,PT=cs,LT=er.f,xT=XE,VT=dT.forEach,UT=wl,FT=En,BT=wt,HT=o,WT=function(e,t,i){for(var r=0,n=arguments.length>2?i:uT(t),o=new e(n);n>r;)o[r]=t[r++];return o},GT=Ic,jT=wi.get,JT=wi.set,KT=wi.enforce,qT=BT.f,zT=HT.f,YT=pT.RangeError,XT=ET.ArrayBuffer,QT=XT.prototype,ZT=ET.DataView,$T=gT.NATIVE_ARRAY_BUFFER_VIEWS,ev=gT.TYPED_ARRAY_TAG,tv=gT.TypedArray,iv=gT.TypedArrayPrototype,rv=gT.isTypedArray,nv="BYTES_PER_ELEMENT",ov="Wrong length",sv=function(e,t){FT(e,t,{configurable:!0,get:function(){return jT(this)[t]}})},av=function(e){var t;return MT(QT,e)||"ArrayBuffer"===(t=DT(e))||"SharedArrayBuffer"===t},cv=function(e,t){return rv(e)&&!NT(t)&&t in e&&ST(+t)&&t>=0},lv=function(e,t){return t=bT(t),cv(e,t)?vT(2,e[t]):zT(e,t)},dv=function(e,t,i){return t=bT(t),!(cv(e,t)&&wT(i)&&kT(i,"value"))||kT(i,"get")||kT(i,"set")||i.configurable||kT(i,"writable")&&!i.writable||kT(i,"enumerable")&&!i.enumerable?qT(e,t,i):(e[t]=i.value,e)};_T?($T||(HT.f=lv,BT.f=dv,sv(iv,"buffer"),sv(iv,"byteOffset"),sv(iv,"byteLength"),sv(iv,"length")),hT({target:"Object",stat:!0,forced:!$T},{getOwnPropertyDescriptor:lv,defineProperty:dv}),xg.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=pT[n],c=a,l=c&&c.prototype,d={},u=function(e,t){qT(e,t,{get:function(){return function(e,t){var i=jT(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=jT(e);o.view[s](t*r+o.byteOffset,i?CT(n):n,!0)}(this,t,e)},enumerable:!0})};$T?fT&&(c=t((function(e,t,i,n){return TT(e,l),GT(wT(t)?av(t)?void 0!==n?new a(t,RT(i,r),n):void 0!==i?new a(t,RT(i,r)):new a(t):rv(t)?WT(c,t):mT(xT,c,t):new a(AT(t)),e,c)})),PT&&PT(c,tv),VT(LT(a),(function(e){e in c||yT(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,n){TT(e,l);var o,s,a,d=0,h=0;if(wT(t)){if(!av(t))return rv(t)?WT(c,t):mT(xT,c,t);o=t,h=RT(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw new YT(ov);if((s=p-h)<0)throw new YT(ov)}else if((s=IT(n)*r)+h>p)throw new YT(ov);a=s/r}else a=AT(t),o=new XT(s=a*r);for(JT(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new ZT(o)});d<a;)u(e,d++)})),PT&&PT(c,tv),l=c.prototype=OT(iv)),l.constructor!==c&&yT(l,"constructor",c),KT(l).TypedArrayConstructor=c,ev&&yT(l,ev,n);var h=c!==a;d[n]=c,hT({global:!0,constructor:!0,forced:h,sham:!$T},d),nv in c||yT(c,nv,r),nv in l||yT(l,nv,r),UT(n)}):xg.exports=function(){};var uv=xg.exports;uv("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}})),uv("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var hv=Tc,pv=UE,mv=hn,_v=u,fv=s,gv=EE.aTypedArray,Ev=EE.exportTypedArrayMethod,Tv=I("".slice);Ev("fill",(function(e){var t=arguments.length;gv(this);var i="Big"===Tv(mv(this),0,3)?pv(e):+e;return _v(hv,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),fv((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e}))),(0,EE.exportTypedArrayStaticMethod)("from",XE,RE);var vv=n,yv=u,Sv=EE,Iv=mr,Av=ME,Rv=Be,Cv=s,bv=vv.RangeError,kv=vv.Int8Array,Dv=kv&&kv.prototype,wv=Dv&&Dv.set,Nv=Sv.aTypedArray,Ov=Sv.exportTypedArrayMethod,Mv=!Cv((function(){var e=new Uint8ClampedArray(2);return yv(wv,e,{length:1,0:3},1),3!==e[1]})),Pv=Mv&&Sv.NATIVE_ARRAY_BUFFER_VIEWS&&Cv((function(){var e=new kv(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));Ov("set",(function(e){Nv(this);var t=Av(arguments.length>1?arguments[1]:void 0,1),i=Rv(e);if(Mv)return yv(wv,this,i,t);var r=this.length,n=Iv(i),o=0;if(n+t>r)throw new bv("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!Mv||Pv);var Lv=xl,xv=s,Vv=Te,Uv=Ta,Fv=ya,Bv=Sa,Hv=re,Wv=Aa,Gv=EE.aTypedArray,jv=EE.exportTypedArrayMethod,Jv=n.Uint16Array,Kv=Jv&&Lv(Jv.prototype.sort),qv=!(!Kv||xv((function(){Kv(new Jv(2),null)}))&&xv((function(){Kv(new Jv(2),{})}))),zv=!!Kv&&!xv((function(){if(Hv)return Hv<74;if(Fv)return Fv<67;if(Bv)return!0;if(Wv)return Wv<602;var e,t,i=new Jv(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(Kv(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));jv("sort",(function(e){return void 0!==e&&Vv(e),zv?Kv(this,e):Uv(Gv(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))}),!zv||qv);var Yv=nn,Xv=u,Qv=I,Zv=x,$v=H,ey=M,ty=Am,iy=_n,ry=Se,ny=Om,oy=Hf,sy=rt("replace"),ay=TypeError,cy=Qv("".indexOf);Qv("".replace);var ly=Qv("".slice),dy=Math.max;Yv({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,n,o,s,a,c,l,d,u=Zv(this),h=0,p="";if(!ey(e)){if(ty(e)&&(i=iy(Zv(ny(e))),!~cy(i,"g")))throw new ay("`.replaceAll` does not allow non-global regexes");if(r=ry(e,sy))return Xv(r,e,u,t)}for(n=iy(u),o=iy(e),(s=$v(t))||(t=iy(t)),a=o.length,c=dy(1,a),l=cy(n,o);-1!==l;)d=s?iy(t(o,l,n)):oy(o,n,l,[],void 0,t),p+=ly(n,h,l)+d,h=l+a,l=l+c>n.length?-1:cy(n,o,l+c);return h<n.length&&(p+=ly(n,h)),p}});var uy={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},hy=Et("span").classList,py=hy&&hy.constructor&&hy.constructor.prototype,my=py===Object.prototype?void 0:py,_y=dT.forEach,fy=Zs("forEach")?[].forEach:function(e){return _y(this,e,arguments.length>1?arguments[1]:void 0)},gy=n,Ey=uy,Ty=my,vy=fy,yy=Yt,Sy=function(e){if(e&&e.forEach!==vy)try{yy(e,"forEach",vy)}catch(RJ){e.forEach=vy}};for(var Iy in Ey)Ey[Iy]&&Sy(gy[Iy]&&gy[Iy].prototype);Sy(Ty);var Ay=n,Ry=uy,Cy=my,by=Hs,ky=Yt,Dy=jo,wy=rt("iterator"),Ny=by.values,Oy=function(e,t){if(e){if(e[wy]!==Ny)try{ky(e,wy,Ny)}catch(RJ){e[wy]=Ny}if(Dy(e,t,!0),Ry[t])for(var i in by)if(e[i]!==by[i])try{ky(e,i,by[i])}catch(RJ){e[i]=by[i]}}};for(var My in Ry)Oy(Ay[My]&&Ay[My].prototype,My);Oy(Cy,"DOMTokenList");var Py=Nf.charAt,Ly=_n,xy=wi,Vy=ks,Uy=Ds,Fy="String Iterator",By=xy.set,Hy=xy.getterFor(Fy);Vy(String,"String",(function(e){By(this,{type:Fy,string:Ly(e),index:0})}),(function(){var e,t=Hy(this),i=t.string,r=t.index;return r>=i.length?Uy(void 0,!0):(e=Py(i,r),t.index+=e.length,Uy(e,!1))}));var Wy=s,Gy=a,jy=rt("iterator"),Jy=!Wy((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&&!Gy||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[jy]||"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=a,qy=I,zy=u,Yy=s,Xy=Hn,Qy=Dr,Zy=h,$y=Be,eS=O,tS=Object.assign,iS=Object.defineProperty,rS=qy([].concat),nS=!tS||Yy((function(){if(Ky&&1!==tS({b:1},tS(iS({},"a",{enumerable:!0,get:function(){iS(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!==tS({},e)[i]||Xy(tS({},t)).join("")!==r}))?function(e,t){for(var i=$y(e),r=arguments.length,n=1,o=Qy.f,s=Zy.f;r>n;)for(var a,c=eS(arguments[n++]),l=o?rS(Xy(c),o(c)):Xy(c),d=l.length,u=0;d>u;)a=l[u++],Ky&&!zy(s,c,a)||(i[a]=c[a]);return i}:tS,oS=Lt,sS=gp,aS=a,cS=wt,lS=E,dS=Dd,uS=u,hS=Be,pS=function(e,t,i,r){try{return r?t(oS(i)[0],i[1]):t(i)}catch(RJ){sS(e,"throw",RJ)}},mS=ep,_S=ud,fS=mr,gS=function(e,t,i){aS?cS.f(e,t,lS(0,i)):e[t]=i},ES=pp,TS=sp,vS=Array,yS=I,SS=2147483647,IS=/[^\0-\u007E]/,AS=/[.\u3002\uFF0E\uFF61]/g,RS="Overflow: input needs wider integers to process",CS=RangeError,bS=yS(AS.exec),kS=Math.floor,DS=String.fromCharCode,wS=yS("".charCodeAt),NS=yS([].join),OS=yS([].push),MS=yS("".replace),PS=yS("".split),LS=yS("".toLowerCase),xS=function(e){return e+22+75*(e<26)},VS=function(e,t,i){var r=0;for(e=i?kS(e/700):e>>1,e+=kS(e/t);e>455;)e=kS(e/35),r+=36;return kS(r+36*e/(e+38))},US=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=wS(e,i++);if(n>=55296&&n<=56319&&i<r){var o=wS(e,i++);56320==(64512&o)?OS(t,((1023&n)<<10)+(1023&o)+65536):(OS(t,n),i--)}else OS(t,n)}return t}(e);var i,r,n=e.length,o=128,s=0,a=72;for(i=0;i<e.length;i++)(r=e[i])<128&&OS(t,DS(r));var c=t.length,l=c;for(c&&OS(t,"-");l<n;){var d=SS;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>kS((SS-s)/u))throw new CS(RS);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++s>SS)throw new CS(RS);if(r===o){for(var h=s,p=36;;){var m=p<=a?1:p>=a+26?26:p-a;if(h<m)break;var _=h-m,f=36-m;OS(t,DS(xS(m+_%f))),h=kS(_/f),p+=36}OS(t,DS(xS(h))),a=VS(s,u,l===c),s=0,l++}}s++,o++}return NS(t,"")},FS=nn,BS=I,HS=lr,WS=RangeError,GS=String.fromCharCode,jS=String.fromCodePoint,JS=BS([].join);FS({target:"String",stat:!0,arity:1,forced:!!jS&&1!==jS.length},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,n=0;r>n;){if(t=+arguments[n++],HS(t,1114111)!==t)throw new WS(t+" is not a valid code point");i[n]=t<65536?GS(t):GS(55296+((t-=65536)>>10),t%1024+56320)}return JS(i,"")}});var KS=nn,qS=n,zS=lu,YS=K,XS=u,QS=I,ZS=a,$S=Jy,eI=$i,tI=En,iI=za,rI=jo,nI=Qo,oI=wi,sI=Qa,aI=H,cI=Ge,lI=Dd,dI=hn,uI=Lt,hI=G,pI=_n,mI=lo,_I=E,fI=pp,gI=sp,EI=Ds,TI=Nd,vI=Ta,yI=rt("iterator"),SI="URLSearchParams",II=SI+"Iterator",AI=oI.set,RI=oI.getterFor(SI),CI=oI.getterFor(II),bI=zS("fetch"),kI=zS("Request"),DI=zS("Headers"),wI=kI&&kI.prototype,NI=DI&&DI.prototype,OI=qS.TypeError,MI=qS.encodeURIComponent,PI=String.fromCharCode,LI=YS("String","fromCodePoint"),xI=parseInt,VI=QS("".charAt),UI=QS([].join),FI=QS([].push),BI=QS("".replace),HI=QS([].shift),WI=QS([].splice),GI=QS("".split),jI=QS("".slice),JI=QS(/./.exec),KI=/\+/g,qI=/^[0-9a-f]+$/i,zI=function(e,t){var i=jI(e,t,t+2);return JI(qI,i)?xI(i,16):NaN},YI=function(e){for(var t=0,i=128;i>0&&e&i;i>>=1)t++;return t},XI=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},QI=function(e){for(var t=(e=BI(e,KI," ")).length,i="",r=0;r<t;){var n=VI(e,r);if("%"===n){if("%"===VI(e,r+1)||r+3>t){i+="%",r++;continue}var o=zI(e,r+1);if(o!=o){i+=n,r++;continue}r+=2;var s=YI(o);if(0===s)n=PI(o);else{if(1===s||s>4){i+="�",r++;continue}for(var a=[o],c=1;c<s&&!(++r+3>t||"%"!==VI(e,r));){var l=zI(e,r+1);if(l!=l){r+=3;break}if(l>191||l<128)break;FI(a,l),r+=2,c++}if(a.length!==s){i+="�";continue}var d=XI(a);null===d?i+="�":n=LI(d)}}i+=n,r++}return i},ZI=/[!'()~]|%20/g,$I={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},eA=function(e){return $I[e]},tA=function(e){return BI(MI(e),ZI,eA)},iA=nI((function(e,t){AI(this,{type:II,target:RI(e).entries,index:0,kind:t})}),SI,(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),rA=function(e){this.entries=[],this.url=null,void 0!==e&&(hI(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===VI(e,0)?jI(e,1):e:pI(e)))};rA.prototype={type:SI,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,s,a,c=this.entries,l=gI(e);if(l)for(i=(t=fI(e,l)).next;!(r=XS(i,t)).done;){if(o=(n=fI(uI(r.value))).next,(s=XS(o,n)).done||(a=XS(o,n)).done||!XS(o,n).done)throw new OI("Expected sequence with length 2");FI(c,{key:pI(s.value),value:pI(a.value)})}else for(var d in e)cI(e,d)&&FI(c,{key:d,value:pI(e[d])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,n=GI(e,"&"),o=0;o<n.length;)(t=n[o++]).length&&(i=GI(t,"="),FI(r,{key:QI(HI(i)),value:QI(UI(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],FI(i,tA(e.key)+"="+tA(e.value));return UI(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var nA=function(){sI(this,oA);var e=AI(this,new rA(arguments.length>0?arguments[0]:void 0));ZS||(this.size=e.entries.length)},oA=nA.prototype;if(iI(oA,{append:function(e,t){var i=RI(this);TI(arguments.length,2),FI(i.entries,{key:pI(e),value:pI(t)}),ZS||this.length++,i.updateURL()},delete:function(e){for(var t=RI(this),i=TI(arguments.length,1),r=t.entries,n=pI(e),o=i<2?void 0:arguments[1],s=void 0===o?o:pI(o),a=0;a<r.length;){var c=r[a];if(c.key!==n||void 0!==s&&c.value!==s)a++;else if(WI(r,a,1),void 0!==s)break}ZS||(this.size=r.length),t.updateURL()},get:function(e){var t=RI(this).entries;TI(arguments.length,1);for(var i=pI(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=RI(this).entries;TI(arguments.length,1);for(var i=pI(e),r=[],n=0;n<t.length;n++)t[n].key===i&&FI(r,t[n].value);return r},has:function(e){for(var t=RI(this).entries,i=TI(arguments.length,1),r=pI(e),n=i<2?void 0:arguments[1],o=void 0===n?n:pI(n),s=0;s<t.length;){var a=t[s++];if(a.key===r&&(void 0===o||a.value===o))return!0}return!1},set:function(e,t){var i=RI(this);TI(arguments.length,1);for(var r,n=i.entries,o=!1,s=pI(e),a=pI(t),c=0;c<n.length;c++)(r=n[c]).key===s&&(o?WI(n,c--,1):(o=!0,r.value=a));o||FI(n,{key:s,value:a}),ZS||(this.size=n.length),i.updateURL()},sort:function(){var e=RI(this);vI(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=RI(this).entries,r=lI(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 iA(this,"keys")},values:function(){return new iA(this,"values")},entries:function(){return new iA(this,"entries")}},{enumerable:!0}),eI(oA,yI,oA.entries,{name:"entries"}),eI(oA,"toString",(function(){return RI(this).serialize()}),{enumerable:!0}),ZS&&tI(oA,"size",{get:function(){return RI(this).entries.length},configurable:!0,enumerable:!0}),rI(nA,SI),KS({global:!0,constructor:!0,forced:!$S},{URLSearchParams:nA}),!$S&&aI(DI)){var sA=QS(NI.has),aA=QS(NI.set),cA=function(e){if(hI(e)){var t,i=e.body;if(dI(i)===SI)return t=e.headers?new DI(e.headers):new DI,sA(t,"content-type")||aA(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),mI(e,{body:_I(0,pI(i)),headers:_I(0,t)})}return e};if(aI(bI)&&KS({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return bI(e,arguments.length>1?cA(arguments[1]):{})}}),aI(kI)){var lA=function(e){return sI(this,wI),new kI(e,arguments.length>1?cA(arguments[1]):{})};wI.constructor=lA,lA.prototype=wI,KS({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:lA})}}var dA,uA=nn,hA=a,pA=Jy,mA=n,_A=Dd,fA=I,gA=$i,EA=En,TA=Qa,vA=Ge,yA=nS,SA=function(e){var t=hS(e),i=_S(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=dS(n,r>2?arguments[2]:void 0));var s,a,c,l,d,u,h=TS(t),p=0;if(!h||this===vS&&mS(h))for(s=fS(t),a=i?new this(s):vS(s);s>p;p++)u=o?n(t[p],p):t[p],gS(a,p,u);else for(a=i?new this:[],d=(l=ES(t,h)).next;!(c=uS(d,l)).done;p++)u=o?pS(l,n,[c.value,p],!0):c.value,gS(a,p,u);return a.length=p,a},IA=_a,AA=Nf.codeAt,RA=function(e){var t,i,r=[],n=PS(MS(LS(e),AS,"."),".");for(t=0;t<n.length;t++)i=n[t],OS(r,bS(IS,i)?"xn--"+US(i):i);return NS(r,".")},CA=_n,bA=jo,kA=Nd,DA={URLSearchParams:nA,getState:RI},wA=wi,NA=wA.set,OA=wA.getterFor("URL"),MA=DA.URLSearchParams,PA=DA.getState,LA=mA.URL,xA=mA.TypeError,VA=mA.parseInt,UA=Math.floor,FA=Math.pow,BA=fA("".charAt),HA=fA(/./.exec),WA=fA([].join),GA=fA(1..toString),jA=fA([].pop),JA=fA([].push),KA=fA("".replace),qA=fA([].shift),zA=fA("".split),YA=fA("".slice),XA=fA("".toLowerCase),QA=fA([].unshift),ZA="Invalid scheme",$A="Invalid host",eR="Invalid port",tR=/[a-z]/i,iR=/[\d+-.a-z]/i,rR=/\d/,nR=/^0x/i,oR=/^[0-7]+$/,sR=/^\d+$/,aR=/^[\da-f]+$/i,cR=/[\0\t\n\r #%/:<>?@[\\\]^|]/,lR=/[\0\t\n\r #/:<>?@[\\\]^|]/,dR=/^[\u0000-\u0020]+/,uR=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,hR=/[\t\n\r]/g,pR=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)QA(t,e%256),e=UA(e/256);return WA(t,".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,i=1,r=null,n=0,o=0;o<8;o++)0!==e[o]?(n>i&&(t=r,i=n),r=null,n=0):(null===r&&(r=o),++n);return n>i?r:t}(e),i=0;i<8;i++)n&&0===e[i]||(n&&(n=!1),r===i?(t+=i?":":"::",n=!0):(t+=GA(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},mR={},_R=yA({},mR,{" ":1,'"':1,"<":1,">":1,"`":1}),fR=yA({},_R,{"#":1,"?":1,"{":1,"}":1}),gR=yA({},fR,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),ER=function(e,t){var i=AA(e,0);return i>32&&i<127&&!vA(t,e)?e:encodeURIComponent(e)},TR={ftp:21,file:null,http:80,https:443,ws:80,wss:443},vR=function(e,t){var i;return 2===e.length&&HA(tR,BA(e,0))&&(":"===(i=BA(e,1))||!t&&"|"===i)},yR=function(e){var t;return e.length>1&&vR(YA(e,0,2))&&(2===e.length||"/"===(t=BA(e,2))||"\\"===t||"?"===t||"#"===t)},SR=function(e){return"."===e||"%2e"===XA(e)},IR={},AR={},RR={},CR={},bR={},kR={},DR={},wR={},NR={},OR={},MR={},PR={},LR={},xR={},VR={},UR={},FR={},BR={},HR={},WR={},GR={},jR=function(e,t,i){var r,n,o,s=CA(e);if(t){if(n=this.parse(s))throw new xA(n);this.searchParams=null}else{if(void 0!==i&&(r=new jR(i,!0)),n=this.parse(s,null,r))throw new xA(n);(o=PA(new MA)).bindURL(this),this.searchParams=o}};jR.prototype={type:"URL",parse:function(e,t,i){var r,n,o,s,a,c=this,l=t||IR,d=0,u="",h=!1,p=!1,m=!1;for(e=CA(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=KA(e,dR,""),e=KA(e,uR,"$1")),e=KA(e,hR,""),r=SA(e);d<=r.length;){switch(n=r[d],l){case IR:if(!n||!HA(tR,n)){if(t)return ZA;l=RR;continue}u+=XA(n),l=AR;break;case AR:if(n&&(HA(iR,n)||"+"===n||"-"===n||"."===n))u+=XA(n);else{if(":"!==n){if(t)return ZA;u="",l=RR,d=0;continue}if(t&&(c.isSpecial()!==vA(TR,u)||"file"===u&&(c.includesCredentials()||null!==c.port)||"file"===c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&TR[c.scheme]===c.port&&(c.port=null));u="","file"===c.scheme?l=xR:c.isSpecial()&&i&&i.scheme===c.scheme?l=CR:c.isSpecial()?l=wR:"/"===r[d+1]?(l=bR,d++):(c.cannotBeABaseURL=!0,JA(c.path,""),l=HR)}break;case RR:if(!i||i.cannotBeABaseURL&&"#"!==n)return ZA;if(i.cannotBeABaseURL&&"#"===n){c.scheme=i.scheme,c.path=IA(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=GR;break}l="file"===i.scheme?xR:kR;continue;case CR:if("/"!==n||"/"!==r[d+1]){l=kR;continue}l=NR,d++;break;case bR:if("/"===n){l=OR;break}l=BR;continue;case kR:if(c.scheme=i.scheme,n===dA)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=IA(i.path),c.query=i.query;else if("/"===n||"\\"===n&&c.isSpecial())l=DR;else if("?"===n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=IA(i.path),c.query="",l=WR;else{if("#"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=IA(i.path),c.path.length--,l=BR;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=IA(i.path),c.query=i.query,c.fragment="",l=GR}break;case DR:if(!c.isSpecial()||"/"!==n&&"\\"!==n){if("/"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=BR;continue}l=OR}else l=NR;break;case wR:if(l=NR,"/"!==n||"/"!==BA(u,d+1))continue;d++;break;case NR:if("/"!==n&&"\\"!==n){l=OR;continue}break;case OR:if("@"===n){h&&(u="%40"+u),h=!0,o=SA(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!==f||m){var g=ER(f,gR);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n===dA||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(h&&""===u)return"Invalid authority";d-=SA(u).length+1,u="",l=MR}else u+=n;break;case MR:case PR:if(t&&"file"===c.scheme){l=UR;continue}if(":"!==n||p){if(n===dA||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(c.isSpecial()&&""===u)return $A;if(t&&""===u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=FR,t)return;continue}"["===n?p=!0:"]"===n&&(p=!1),u+=n}else{if(""===u)return $A;if(s=c.parseHost(u))return s;if(u="",l=LR,t===PR)return}break;case LR:if(!HA(rR,n)){if(n===dA||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()||t){if(""!==u){var E=VA(u,10);if(E>65535)return eR;c.port=c.isSpecial()&&E===TR[c.scheme]?null:E,u=""}if(t)return;l=FR;continue}return eR}u+=n;break;case xR:if(c.scheme="file","/"===n||"\\"===n)l=VR;else{if(!i||"file"!==i.scheme){l=BR;continue}switch(n){case dA:c.host=i.host,c.path=IA(i.path),c.query=i.query;break;case"?":c.host=i.host,c.path=IA(i.path),c.query="",l=WR;break;case"#":c.host=i.host,c.path=IA(i.path),c.query=i.query,c.fragment="",l=GR;break;default:yR(WA(IA(r,d),""))||(c.host=i.host,c.path=IA(i.path),c.shortenPath()),l=BR;continue}}break;case VR:if("/"===n||"\\"===n){l=UR;break}i&&"file"===i.scheme&&!yR(WA(IA(r,d),""))&&(vR(i.path[0],!0)?JA(c.path,i.path[0]):c.host=i.host),l=BR;continue;case UR:if(n===dA||"/"===n||"\\"===n||"?"===n||"#"===n){if(!t&&vR(u))l=BR;else if(""===u){if(c.host="",t)return;l=FR}else{if(s=c.parseHost(u))return s;if("localhost"===c.host&&(c.host=""),t)return;u="",l=FR}continue}u+=n;break;case FR:if(c.isSpecial()){if(l=BR,"/"!==n&&"\\"!==n)continue}else if(t||"?"!==n)if(t||"#"!==n){if(n!==dA&&(l=BR,"/"!==n))continue}else c.fragment="",l=GR;else c.query="",l=WR;break;case BR:if(n===dA||"/"===n||"\\"===n&&c.isSpecial()||!t&&("?"===n||"#"===n)){if(".."===(a=XA(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"===n||"\\"===n&&c.isSpecial()||JA(c.path,"")):SR(u)?"/"===n||"\\"===n&&c.isSpecial()||JA(c.path,""):("file"===c.scheme&&!c.path.length&&vR(u)&&(c.host&&(c.host=""),u=BA(u,0)+":"),JA(c.path,u)),u="","file"===c.scheme&&(n===dA||"?"===n||"#"===n))for(;c.path.length>1&&""===c.path[0];)qA(c.path);"?"===n?(c.query="",l=WR):"#"===n&&(c.fragment="",l=GR)}else u+=ER(n,fR);break;case HR:"?"===n?(c.query="",l=WR):"#"===n?(c.fragment="",l=GR):n!==dA&&(c.path[0]+=ER(n,mR));break;case WR:t||"#"!==n?n!==dA&&("'"===n&&c.isSpecial()?c.query+="%27":c.query+="#"===n?"%23":ER(n,mR)):(c.fragment="",l=GR);break;case GR:n!==dA&&(c.fragment+=ER(n,_R))}d++}},parseHost:function(e){var t,i,r;if("["===BA(e,0)){if("]"!==BA(e,e.length-1))return $A;if(t=function(e){var t,i,r,n,o,s,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return BA(e,u)};if(":"===h()){if(":"!==BA(e,1))return;u+=2,d=++l}for(;h();){if(8===l)return;if(":"!==h()){for(t=i=0;i<4&&HA(aR,h());)t=16*t+VA(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(!HA(rR,h()))return;for(;HA(rR,h());){if(o=VA(h(),10),null===n)n=o;else{if(0===n)return;n=10*n+o}if(n>255)return;u++}c[l]=256*c[l]+n,2!=++r&&4!==r||l++}if(4!==r)return;break}if(":"===h()){if(u++,!h())return}else if(h())return;c[l++]=t}else{if(null!==d)return;u++,d=++l}}if(null!==d)for(s=l-d,l=7;0!==l&&s>0;)a=c[l],c[l--]=c[d+s-1],c[d+--s]=a;else if(8!==l)return;return c}(YA(e,1,-1)),!t)return $A;this.host=t}else if(this.isSpecial()){if(e=RA(e),HA(cR,e))return $A;if(t=function(e){var t,i,r,n,o,s,a,c=zA(e,".");if(c.length&&""===c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],r=0;r<t;r++){if(""===(n=c[r]))return e;if(o=10,n.length>1&&"0"===BA(n,0)&&(o=HA(nR,n)?16:8,n=YA(n,8===o?1:2)),""===n)s=0;else{if(!HA(10===o?sR:8===o?oR:aR,n))return e;s=VA(n,o)}JA(i,s)}for(r=0;r<t;r++)if(s=i[r],r===t-1){if(s>=FA(256,5-t))return null}else if(s>255)return null;for(a=jA(i),r=0;r<i.length;r++)a+=i[r]*FA(256,3-r);return a}(e),null===t)return $A;this.host=t}else{if(HA(lR,e))return $A;for(t="",i=SA(e),r=0;r<i.length;r++)t+=ER(i[r],mR);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return vA(TR,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&vR(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,r=e.password,n=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,l=t+":";return null!==n?(l+="//",e.includesCredentials()&&(l+=i+(r?":"+r:"")+"@"),l+=pR(n),null!==o&&(l+=":"+o)):"file"===t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+WA(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw new xA(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new JR(e.path[0]).origin}catch(RJ){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+pR(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(CA(e)+":",IR)},getUsername:function(){return this.username},setUsername:function(e){var t=SA(CA(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=ER(t[i],gR)}},getPassword:function(){return this.password},setPassword:function(e){var t=SA(CA(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=ER(t[i],gR)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?pR(e):pR(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,MR)},getHostname:function(){var e=this.host;return null===e?"":pR(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,PR)},getPort:function(){var e=this.port;return null===e?"":CA(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=CA(e))?this.port=null:this.parse(e,LR))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+WA(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,FR))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=CA(e))?this.query=null:("?"===BA(e,0)&&(e=YA(e,1)),this.query="",this.parse(e,WR)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=CA(e))?("#"===BA(e,0)&&(e=YA(e,1)),this.fragment="",this.parse(e,GR)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var JR=function(e){var t=TA(this,KR),i=kA(arguments.length,1)>1?arguments[1]:void 0,r=NA(t,new jR(e,!1,i));hA||(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())},KR=JR.prototype,qR=function(e,t){return{get:function(){return OA(this)[e]()},set:t&&function(e){return OA(this)[t](e)},configurable:!0,enumerable:!0}};if(hA&&(EA(KR,"href",qR("serialize","setHref")),EA(KR,"origin",qR("getOrigin")),EA(KR,"protocol",qR("getProtocol","setProtocol")),EA(KR,"username",qR("getUsername","setUsername")),EA(KR,"password",qR("getPassword","setPassword")),EA(KR,"host",qR("getHost","setHost")),EA(KR,"hostname",qR("getHostname","setHostname")),EA(KR,"port",qR("getPort","setPort")),EA(KR,"pathname",qR("getPathname","setPathname")),EA(KR,"search",qR("getSearch","setSearch")),EA(KR,"searchParams",qR("getSearchParams")),EA(KR,"hash",qR("getHash","setHash"))),gA(KR,"toJSON",(function(){return OA(this).serialize()}),{enumerable:!0}),gA(KR,"toString",(function(){return OA(this).serialize()}),{enumerable:!0}),LA){var zR=LA.createObjectURL,YR=LA.revokeObjectURL;zR&&gA(JR,"createObjectURL",_A(zR,LA)),YR&&gA(JR,"revokeObjectURL",_A(YR,LA))}bA(JR,"URL"),uA({global:!0,constructor:!0,forced:!pA,sham:!hA},{URL:JR});var XR=u;nn({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return XR(URL.prototype.toString,this)}});let QR=!0,ZR=!0;function $R(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function eC(e,t,i){if(!e.RTCPeerConnection)return;const r=e.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return n.apply(this,arguments);const o=e=>{const t=i(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,o),n.apply(this,[e,o])};const o=r.removeEventListener;r.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.apply(this,arguments);const r=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,r])},Object.defineProperty(r,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function tC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(QR=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function iC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ZR=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function rC(){if("object"==typeof window){if(QR)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function nC(e,t){ZR&&console.warn(e+" is deprecated, please use "+t+" instead.")}function oC(e){return"[object Object]"===Object.prototype.toString.call(e)}function sC(e){return oC(e)?Object.keys(e).reduce((function(t,i){const r=oC(e[i]),n=r?sC(e[i]):e[i],o=r&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[i]:n})}),{}):e}function aC(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?aC(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{aC(e,e.get(t),i)}))})))}function cC(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((i=>{i.type===r&&i.trackId===t.id&&aC(e,i,n)}))})),n}const lC=rC;function dC(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const r=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const r="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==r.ideal){t.optional=t.optional||[];let e={};"number"==typeof r.ideal?(e[n("min",i)]=r.ideal,t.optional.push(e),e={},e[n("max",i)]=r.ideal,t.optional.push(e)):(e[n("",i)]=r.ideal,t.optional.push(e))}void 0!==r.exact&&"number"!=typeof r.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",i)]=r.exact):["min","max"].forEach((e=>{void 0!==r[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,i)]=r[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=r(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{i=i.filter((e=>"videoinput"===e.kind));let s=i.find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=r(e.video),lC("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return lC("chrome: "+JSON.stringify(e)),n(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,r){n(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{r&&r(o(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function uC(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function hC(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 eC(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function pC(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 mC(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,r]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const r=function(e){i(o(n(e)))};return t.apply(this,[r,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(o(n(t)))},i])})).then(i,r)}}function _C(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=>cC(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}),eC(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>cC(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 fC(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 gC(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return fC(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}r.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const r=[].slice.call(arguments,1);if(1!==r.length||!r[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const n=this._streams[i.id];if(n)n.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const r=new e.MediaStream([t]);this._streams[i.id]=r,this._reverseStreams[r.id]=i,this.addStream(r)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=r[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function 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){eC(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var vC=Object.freeze({__proto__:null,shimMediaStream:uC,shimOnTrack:hC,shimGetSendersWithDtmf:pC,shimGetStats:mC,shimSenderReceiverGetStats:_C,shimAddTrackRemoveTrackWithNative:fC,shimAddTrackRemoveTrack:gC,shimPeerConnection:EC,fixNegotiationNeeded:TC,shimGetUserMedia:dC,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const r=i.video&&i.video.width,n=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},r&&(i.video.mandatory.maxWidth=r),n&&(i.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function yC(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){nC("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},r&&r.prototype.getSettings){const t=r.prototype.getSettings;r.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(r&&r.prototype.applyConstraints){const t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function SC(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function IC(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,o]=arguments;return r.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(zb){if("TypeError"!==zb.name)throw zb;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,o)}}function AC(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function RC(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}),eC(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){nC("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function bC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function kC(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 DC(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 wC(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 NC(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 OC=Object.freeze({__proto__:null,shimOnTrack:SC,shimPeerConnection:IC,shimSenderGetStats:AC,shimReceiverGetStats:RC,shimRemoveStream:CC,shimRTCDataChannel:bC,shimAddTransceiver:kC,shimGetParameters:DC,shimCreateOffer:wC,shimCreateAnswer:NC,shimGetUserMedia:yC,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function MC(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function PC(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function LC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,i){const r=n.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r};t.setLocalDescription=a,a=function(e,t,i){const r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.setRemoteDescription=a,a=function(e,t,i){const r=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.addIceCandidate=a}function xC(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(VC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function VC(e){return e&&void 0!==e.video?Object.assign({},e,{video:sC(e.video)}):e}function UC(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?(nC("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 FC(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 BC(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 HC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var WC=Object.freeze({__proto__:null,shimLocalStreamsAPI:MC,shimRemoteStreamsAPI:PC,shimCallbacksAPI:LC,shimGetUserMedia:xC,shimConstraints:VC,shimRTCIceServerUrls:UC,shimTrackEventTransceiver:FC,shimCreateOfferLegacy:BC,shimAudioContext:HC}),GC={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let r=8;r<t.length;r+=2)switch(t[r]){case"raddr":i.relatedAddress=t[r+1];break;case"rport":i.relatedPort=parseInt(t[r+1],10);break;case"tcptype":i.tcpType=t[r+1];break;case"ufrag":i.ufrag=t[r+1],i.usernameFragment=t[r+1];break;default:void 0===i[t[r]]&&(i[t[r]]=t[r+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const r=e.substring(e.indexOf(" ")+1).split(";");for(let n=0;n<r.length;n++)i=r[n].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const r=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+i+" "+r.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substring(t+1,r),i.value=e.substring(r+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const r=t.matchPrefix(e+i,"a=ice-ufrag:")[0],n=t.matchPrefix(e+i,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substring(12),password:n.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(" ");i.profile=r[2];for(let o=3;o<r.length;o++){const n=r[o],s=t.matchPrefix(e,"a=rtpmap:"+n+" ")[0];if(s){const r=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+n+" ");switch(r.parameters=o.length?t.parseFmtp(o[0]):{},r.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+n+" ").map(t.parseRtcpFb),i.codecs.push(r),r.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(r.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const n=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{n.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let r="";r+="m="+e+" ",r+=i.codecs.length>0?"9":"0",r+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{r+=t.writeRtpMap(e),r+=t.writeFmtp(e),r+=t.writeRtcpFb(e)}));let n=0;return i.codecs.forEach((e=>{e.maxptime>n&&(n=e.maxptime)})),n>0&&(r+="a=maxptime:"+n+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{r+=t.writeExtmap(e)})),r},t.parseRtpEncodingParameters=function(e){const i=[],r=t.parseRtpParameters(e),n=-1!==r.fecMechanisms.indexOf("RED"),o=-1!==r.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===a&&(c=l[0][1]),r.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),n&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=d}))),i},t.parseRtcpParameters=function(e){const i={},r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=n.length>0,i.compound=0===n.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const r=t.matchPrefix(e,"a=msid:");if(1===r.length)return i=r[0].substring(7).split(" "),{stream:i[0],track:i[1]};const n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return n.length>0?(i=n[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),r=t.matchPrefix(e,"a=max-message-size:");let n;r.length>0&&(n=parseInt(r[0].substring(19),10)),isNaN(n)&&(n=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:n};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,r){let n;const o=void 0!==i?i:2;n=e||t.generateSessionId();return"v=0\r\no="+(r||"thisisadapterortc")+" "+n+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const r=t.splitLines(e);for(let t=0;t<r.length;t++)switch(r[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(GC);var jC=GC.exports,JC=i(jC),KC=e({__proto__:null,default:JC},[jC]);function qC(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=JC.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,eC(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function zC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||eC(e,"icecandidate",(e=>{if(e.candidate){const t=JC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function YC(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=JC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=JC.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=JC.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?r=parseInt(n[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(r=2147483637),r}(arguments[0],e);let n;n=0===i&&0===r?Number.POSITIVE_INFINITY:0===i||0===r?Math.max(i,r):Math.min(i,r);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>n}),this._sctp=o}return i.apply(this,arguments)}}function XC(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},eC(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function QC(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 ZC(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 $C(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 eb(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 tb=Object.freeze({__proto__:null,shimRTCIceCandidate:qC,shimRTCIceCandidateRelayProtocol:zC,shimMaxMessageSize:YC,shimSendThrowTypeError:XC,shimConnectionState:QC,removeExtmapAllowMixed:ZC,shimAddIceCandidateNullOrEmpty:$C,shimParameterlessSetLocalDescription:eb});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=rC,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=$R(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=$R(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=$R(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:tb,extractVersion:$R,disableLog:tC,disableWarnings:iC,sdp:KC};switch(r.browser){case"chrome":if(!vC||!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=vC,$C(e,r),eb(e),dC(e,r),uC(e),EC(e,r),hC(e),gC(e,r),pC(e),mC(e),_C(e),TC(e,r),qC(e),zC(e),QC(e),YC(e,r),XC(e),ZC(e,r);break;case"firefox":if(!OC||!IC||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=OC,$C(e,r),eb(e),yC(e,r),IC(e,r),SC(e),CC(e),AC(e),RC(e),bC(e),kC(e),DC(e),wC(e),NC(e),qC(e),QC(e),YC(e,r),XC(e);break;case"safari":if(!WC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=WC,$C(e,r),eb(e),UC(e),BC(e),LC(e),MC(e),PC(e),FC(e),xC(e),HC(e),qC(e),zC(e),YC(e,r),XC(e),ZC(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var ib,rb=Object.create,nb=Object.defineProperty,ob=Object.defineProperties,sb=Object.getOwnPropertyDescriptor,ab=Object.getOwnPropertyDescriptors,cb=Object.getOwnPropertyNames,lb=Object.getOwnPropertySymbols,db=Object.getPrototypeOf,ub=Object.prototype.hasOwnProperty,hb=Object.prototype.propertyIsEnumerable,pb=Reflect.get,mb=Math.pow,_b=(e,t,i)=>t in e?nb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,fb=(e,t)=>{for(var i in t||(t={}))ub.call(t,i)&&_b(e,i,t[i]);if(lb)for(var i of lb(t))hb.call(t,i)&&_b(e,i,t[i]);return e},gb=(e,t)=>ob(e,ab(t)),Eb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Tb=(e,t)=>{for(var i in t)nb(e,i,{get:t[i],enumerable:!0})},vb=(e,t,i)=>(i=null!=e?rb(db(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of cb(t))!ub.call(e,n)&&n!==i&&nb(e,n,{get:()=>t[n],enumerable:!(r=sb(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:nb(i,"default",{value:e,enumerable:!0}),e)),yb=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?sb(t,i):t,s=e.length-1;s>=0;s--)(n=e[s])&&(o=(r?n(t,i,o):n(o))||o);return r&&o&&nb(t,i,o),o},Sb=(e,t,i)=>_b(e,"symbol"!=typeof t?t+"":t,i),Ib=(e,t,i)=>pb(db(e),i,t),Ab=(e,t,i)=>new Promise(((r,n)=>{var o=e=>{try{a(i.next(e))}catch(yM){n(yM)}},s=e=>{try{a(i.throw(e))}catch(yM){n(yM)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),Rb=Eb(((e,t)=>{var i=Object.prototype.hasOwnProperty,r="~";function n(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,i,n,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new o(i,n||e,s),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function c(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),c.prototype.eventNames=function(){var e,t,n=[];if(0===this._eventsCount)return n;for(t in e=this._events)i.call(e,t)&&n.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},c.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,o=i.length,s=new Array(o);n<o;n++)s[n]=i[n].fn;return s},c.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},c.prototype.emit=function(e,t,i,n,o,s){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,d=this._events[a],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,n),!0;case 5:return d.fn.call(d.context,t,i,n,o),!0;case 6:return d.fn.call(d.context,t,i,n,o,s),!0}for(l=1,c=new Array(u-1);l<u;l++)c[l-1]=arguments[l];d.fn.apply(d.context,c)}else{var h,p=d.length;for(l=0;l<p;l++)switch(d[l].once&&this.removeListener(e,d[l].fn,void 0,!0),u){case 1:d[l].fn.call(d[l].context);break;case 2:d[l].fn.call(d[l].context,t);break;case 3:d[l].fn.call(d[l].context,t,i);break;case 4:d[l].fn.call(d[l].context,t,i,n);break;default:if(!c)for(h=1,c=new Array(u-1);h<u;h++)c[h-1]=arguments[h];d[l].fn.apply(d[l].context,c)}}return!0},c.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},c.prototype.removeListener=function(e,t,i,n){var o=r?r+e:e;if(!this._events[o])return this;if(!t)return a(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!n||s.once)&&(!i||s.context===i)&&a(this,o);else{for(var c=0,l=[],d=s.length;c<d;c++)(s[c].fn!==t||n&&!s[c].once||i&&s[c].context!==i)&&l.push(s[c]);l.length?this._events[o]=1===l.length?l[0]:l:a(this,o)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new n,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,void 0!==t&&(t.exports=c)})),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")}))}))})),bb=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 o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=Cb(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),kb=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""}}))},o=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||s,n=t.innerOrder||a,c=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),Db=Eb((e=>{var t=bb(),i=kb(),r=Cb();e.grammar=r,e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),wb=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")}))}))})),Nb=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 o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=wb(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),Ob=Eb(((e,t)=>{var i=wb(),r=/%[sdv%]/g,n=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},o=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||s,n=t.innerOrder||a,c=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),Mb=Eb((e=>{var t=Nb(),i=Ob();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),Pb=vb(Rb()),Lb=((ib=Lb||{})[ib.INVALID_PARAMETER=4096]="INVALID_PARAMETER",ib[ib.INVALID_OPERATION=4097]="INVALID_OPERATION",ib[ib.NOT_SUPPORTED=4098]="NOT_SUPPORTED",ib[ib.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",ib[ib.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",ib[ib.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",ib[ib.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",ib[ib.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",ib[ib.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",ib[ib.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",ib[ib.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",ib[ib.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",ib[ib.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",ib[ib.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",ib[ib.CLIENT_BANNED=16448]="CLIENT_BANNED",ib[ib.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",ib[ib.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",ib[ib.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",ib[ib.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",ib[ib.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",ib[ib.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",ib[ib.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",ib[ib.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",ib[ib.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",ib[ib.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",ib[ib.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",ib[ib.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",ib[ib.API_CALL_ABORTED=16461]="API_CALL_ABORTED",ib[ib.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",ib[ib.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",ib[ib.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",ib[ib.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",ib[ib.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",ib[ib.UNKNOWN=65535]="UNKNOWN",ib),xb=Lb,Vb=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=xb.UNKNOWN,extraCode:n=0,constraint:o}=e,s="<".concat(function(e){for(let t in xb)if(xb[t]===e)return t;return"UNKNOWN"}(r)," 0x").concat(r.toString(16),">"),a="".concat(i).concat(o?" constraint: ".concat(o):"").concat(null!=i&&i.includes(s)?"":" ".concat(s));super(a),Sb(this,"code"),Sb(this,"extraCode"),Sb(this,"message"),Sb(this,"originMessage"),Sb(this,"name"),Sb(this,"constraint"),this.code=r,this.extraCode=n,this.name=t,this.message=a,this.constraint=o,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},Ub=Vb,Fb=((new Date).getTime(),0),Bb=function(){return(new Date).getTime()+Fb},Hb=function(){let e=new Date;return e.setTime(Bb()),e.toLocaleString()},Wb=function(e){let t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),"".concat(e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(t)},Gb={};Tb(Gb,{REPORT_TYPE:()=>Zw,buildSSOPackage:()=>$w,bytes2ms:()=>$D,calculateScaleResolutionDownNumber:()=>zw,convertObjectNumberToInt:()=>Gw,copyProperties:()=>ZD,deepClone:()=>Mw,deepCloneBasic:()=>Qw,deepMerge:()=>Ow,delay:()=>jw,fibonacci:()=>sw,formatedTime:()=>xw,getConstructorName:()=>vw,getContainerFromElement:()=>Lw,getEnv:()=>jD,getInternalVersion:()=>Cw,getLoggerUrl:()=>KD,getMediaStreamTrackInfo:()=>qw,getMuteStateFromFlag:()=>Dw,getNetworkType:()=>zD,getNumNetworkType:()=>QD,getReconnectionTimeout:()=>aw,getStringByteLength:()=>Fw,getTurnServer:()=>ww,getUint32Version:()=>Ww,getValueType:()=>cw,getViewListFromView:()=>Pw,glog:()=>rw,ipv4ToUint32:()=>Nw,isArray:()=>_w,isAudioWorkletSupported:()=>yw,isBoolean:()=>pw,isConstructor:()=>Tw,isEmpty:()=>kw,isFunction:()=>lw,isLangChinese:()=>nw,isMediaStreamTrack:()=>fw,isNumber:()=>hw,isObject:()=>mw,isOverseaSdkAppId:()=>JD,isPlainObject:()=>ow,isPortrait:()=>Bw,isPromise:()=>Ew,isRemoteTrack:()=>gw,isRotate90Or270:()=>Yw,isSetSinkIdSupported:()=>Sw,isString:()=>uw,isUndefined:()=>dw,loadImage:()=>Hw,loadVideo:()=>Xw,ms2bytes:()=>tw,ms2samples:()=>iw,normalizeUrl:()=>Kw,performanceNow:()=>Aw,promiseAny:()=>Iw,samples2ms:()=>ew,setNetworkType:()=>XD,stringify:()=>Vw,stringifyIncludeValue:()=>Uw,throttlePromise:()=>Jw});var jb={};Tb(jb,{AUDIO_MUTE_BIT:()=>wk,AUDIO_STAT_BIT:()=>Dk,AUX_STAT_BIT:()=>kk,AUX_STREAM_MSID:()=>Lk,BACKEND_ENV:()=>Ak,BASE_DOC_URL:()=>ok,BASE_HOST:()=>tk,CAPABILITIES_KEYS:()=>SD,CLASS_NAME:()=>pD,CLOUD_CONSOLE_URL:()=>nk,CROSS_ROOM_BIT:()=>Mk,DATA_FREEZE_TIMING:()=>sD,DOC_URL:()=>sk,DTLS_STATE_UNKNOWN:()=>Jk,ENV_NAME:()=>uk,EXCHANGE_SDP_TIMEOUT:()=>tD,IS_WORKER:()=>Xb,IS_WORKLET:()=>Qb,KIBANA_EVENT:()=>Zk,LOCAL_STREAM_PUBLISH_STATE:()=>oD,LOGGER_CMD_TYPE:()=>dk,LOGGER_DOMAIN:()=>ak,LOGGER_DOMAIN_OVERSEA:()=>ck,LOG_LEVEL:()=>hk,LOG_LEVEL_NAME:()=>ED,MAIN_STREAM_MSID:()=>Pk,MAX_RTT:()=>ID,MICROPHONE_COMMUNICATIONS:()=>gD,MICROPHONE_DEFAULT:()=>_D,MUTE_ALL_BIT:()=>Ok,NAME:()=>Sk,NETWORK_TYPE:()=>_k,NOT_SUPPORTED_H264:()=>nD,PAUSED_RETRY_COUNT:()=>mD,PEERCONNECTION_CONNECTING_TIMEOUT:()=>dD,PEER_CONNECTION_STATE:()=>Kk,PEER_LEAVE_REASON:()=>TD,RECOVER_CAPTURE_INTERVAL:()=>yD,REMOTE_STREAM_TYPE_AUX:()=>Vk,REMOTE_STREAM_TYPE_MAIN:()=>xk,RENDER_FREEZE_TIMING:()=>aD,SCHEDULE_DOMAIN:()=>uD,SCHEDULE_TIMEOUT:()=>hD,SDP_SEMANTICS_PLAN_B:()=>rD,SDP_SEMANTICS_UNIFIED_PLAN:()=>iD,SECOND_HOST:()=>ik,SIGNAL_PING_PONG_INTERVAL:()=>mk,SIGNAL_PING_TIMEOUT:()=>pk,SIGNAL_RECONNECTION_COUNT:()=>Qk,SMALL_STAT_BIT:()=>bk,SPEAKER_DEFAULT:()=>fD,STORAGE_EXPIRES_TIME:()=>fk,STREAM_TYPE_BIG:()=>cD,STREAM_TYPE_SMALL:()=>lD,SUBSCRIBE_SMALL_RETRY_COUNT:()=>vD,SYNC_USER_LIST_INTERVAL:()=>$k,Scene:()=>Rk,THIRD_HOST:()=>rk,TRANSPORT_DIRECTION:()=>Ik,TRTC_ERROR_ASSISTANCE:()=>lk,TRTC_QUALITY_BAD:()=>Wk,TRTC_QUALITY_DISCONNECTED:()=>jk,TRTC_QUALITY_EXCELLENT:()=>Fk,TRTC_QUALITY_GOOD:()=>Bk,TRTC_QUALITY_POOR:()=>Hk,TRTC_QUALITY_UNKNOWN:()=>Uk,TRTC_QUALITY_VERY_BAD:()=>Gk,UPDATE_OFFER_TIMEOUT:()=>eD,VIDEO_MUTE_BIT:()=>Nk,VIDEO_STAT_BIT:()=>Ck,audioProfileMap:()=>gk,defaultBigVideoProfile:()=>Tk,defaultSmallVideoProfile:()=>vk,getRetryCount:()=>Yk,getScriptDir:()=>Zb,innerVersion:()=>Jb,loggerProxy:()=>$b,screenProfileMap:()=>yk,setLoggerProxy:()=>ek,setRetryCount:()=>zk,setVersion:()=>qb,version:()=>Kb,videoProfileMap:()=>Ek});var Jb="4.15.00.1600",Kb="5.0.0";function qb(e){Kb=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));Jb="".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 zb,Yb,Xb="undefined"!=typeof importScripts,Qb="undefined"!=typeof registerProcessor,Zb=()=>{let e=Xb?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},$b="",ek=e=>$b=e,tk="web.sdk.qcloud.com",ik="web.sdk.tencent.cn",rk="web.sdk.cloud.tencent.cn",nk="https://console.cloud.tencent.com/trtc",ok="https://".concat(tk,"/trtc/webrtc/v5/doc"),sk="".concat(ok,"/zh-cn/"),ak="https://yun.tim.qq.com",ck="https://apisgp.my-imcloud.com",lk="trtc_error_assistance",dk={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},uk={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},hk=((Yb=hk||{})[Yb.TRACE=0]="TRACE",Yb[Yb.DEBUG=1]="DEBUG",Yb[Yb.INFO=2]="INFO",Yb[Yb.WARN=3]="WARN",Yb[Yb.ERROR=4]="ERROR",Yb[Yb.NONE=5]="NONE",Yb),pk=18e3,mk=2e3,_k={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},fk=6048e5,gk={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=Ek["480p_2"],vk=Ek["120p_2"],yk={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},Sk={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",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"},Ik={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Ak={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Rk=((zb=Rk||{}).LIVE="live",zb.RTC="rtc",zb),Ck=1,bk=2,kk=4,Dk=8,wk=64,Nk=16,Ok=112,Mk=128,Pk="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Lk="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",xk=Sk.MAIN,Vk=Sk.AUXILIARY,Uk=0,Fk=1,Bk=2,Hk=3,Wk=4,Gk=5,jk=6,Jk="unknown",Kk={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},qk=1/0;function zk(e){qk=e}function Yk(){return qk}var Xk,Qk=30,Zk={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"},$k=1e4,eD=1e4,tD=1e4,iD="unified-plan",rD="plan-b",nD=1028,oD=((Xk=oD||{})[Xk.UNPUBLISH=-1]="UNPUBLISH",Xk[Xk.PUBLISHING=0]="PUBLISHING",Xk[Xk.PUBLISHED=1]="PUBLISHED",Xk),sD=500,aD=1e3,cD=Sk.BIG,lD=Sk.SMALL,dD=1e4,uD={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"},hD=2e3,pD={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},mD=5,_D="default",fD=_D,gD="communications",ED=Object.keys(hk),TD=["normal leave","timeout leave","kick","role change"],vD=10,yD=2e3,SD=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],ID=1e4,AD=function(e,t,i,r){return new(i||(i=Promise))((function(n,o){function s(e){try{c(r.next(e))}catch(t){o(t)}}function a(e){try{c(r.throw(e))}catch(t){o(t)}}function c(e){e.done?n(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(s,a)}c((r=r.apply(e,t||[])).next())}))},RD=Symbol(32),CD=Symbol(16),bD=Symbol(8),kD=class{constructor(e){this.g=e,this.consumed=0,e&&(this.need=e.next().value)}setG(e){this.g=e,this.demand(e.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(e,t){return t&&this.consume(),this.need=e,this.flush()}read(e){return AD(this,void 0,void 0,(function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise(((t,i)=>{var r;this.reject=i,this.resolve=e=>{delete this.lastReadPromise,delete this.resolve,delete this.need,t(e)},this.demand(e,!0)||null===(r=this.pull)||void 0===r||r.call(this,e)}))}))}readU32(){return this.read(RD)}readU16(){return this.read(CD)}readU8(){return this.read(bD)}close(){var e;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),null===(e=this.reject)||void 0===e||e.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let e=null,t=this.buffer.subarray(this.consumed),i=0,r=e=>t.length<(i=e);if("number"==typeof this.need){if(r(this.need))return;e=t.subarray(0,i)}else if(this.need===RD){if(r(4))return;e=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===CD){if(r(2))return;e=t[0]<<8|t[1]}else if(this.need===bD){if(r(1))return;e=t[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(t.subarray(0,i)),e=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(t.subarray(0,i)),e=this.need}return this.consumed+=i,this.g?this.demand(this.g.next(e).value,!0):this.resolve&&this.resolve(e),e}write(e){if(e instanceof Uint8Array?this.malloc(e.length).set(e):"buffer"in e?this.malloc(e.byteLength).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):this.malloc(e.byteLength).set(new Uint8Array(e)),!this.g&&!this.resolve)return new Promise((e=>this.pull=e));this.flush()}writeU32(e){this.malloc(4).set([e>>24&255,e>>16&255,e>>8&255,255&e]),this.flush()}writeU16(e){this.malloc(2).set([e>>8&255,255&e]),this.flush()}writeU8(e){this.malloc(1)[0]=e,this.flush()}malloc(e){if(this.buffer){let t=this.buffer.length,i=t+e;if(i<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,i);else{let e=new Uint8Array(i);e.set(this.buffer),this.buffer=e}return this.buffer.subarray(t,i)}return this.buffer=new Uint8Array(e),this.buffer}};kD.U32=RD,kD.U16=CD,kD.U8=bD;var DD=128;function wD(e){let t=new kD;for(;e>=128;)t.malloc(1)[0]=255&e|DD,e>>>=7;return t.malloc(1)[0]=255&e,t.buffer||new Uint8Array(0)}function ND(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=new kD,r=t<<3;switch(typeof e){case"boolean":let n=i.malloc(2);n[0]=r,n[1]=e?1:0;break;case"number":i.malloc(1)[0]=r,i.write(wD(e));break;case"string":i.malloc(1)[0]=2|r;let o=(new TextEncoder).encode(e);i.write(wD(o.length));let s=i.malloc(o.length);for(let e=0;e<o.length;e++)s[e]=o[e];break;case"object":let a=new kD;if(Array.isArray(e))for(let t=0;t<e.length;t++){let i=ND(e[t],t+1);i&&a.write(i)}else{let t=1;for(let i in e){let r=ND(e[i],t++);r&&a.write(r)}}0===t?a.buffer&&i.write(a.buffer):(i.malloc(1)[0]=2|r,a.buffer&&(i.write(wD(a.buffer.length)),i.write(a.buffer)))}return i.buffer||new Uint8Array(0)}var OD=class{constructor(){Sb(this,"buffer"),this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(e){this.buffer.push(e>>>24&255),this.buffer.push(e>>>16&255),this.buffer.push(e>>>8&255),this.buffer.push(255&e)}writeInt16(e){this.buffer.push(e>>>8&255),this.buffer.push(255&e)}writeByte(e){this.buffer.push(255&e)}writeBytes(e){for(let t=0;t<e.length;t++)this.buffer.push(e[t])}};function MD(e,t,i){e[i]=t>>>24&255,e[i+1]=t>>>16&255,e[i+2]=t>>>8&255,e[i+3]=255&t}function PD(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function LD(e,t){return e[t]}function xD(e,t,i){return(new TextDecoder).decode(function(e,t,i){return e.slice(t,t+i)}(e,t,i))}var VD=0,UD=2654435769,FD=16,BD=2,HD=7;function WD(e,t){let i=new OD,r=function(e,t,i){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"AVQualityReportSvc.C2S";return{version:arguments.length>4&&void 0!==arguments[4]?arguments[4]:2e3,encryption:arguments.length>5&&void 0!==arguments[5]?arguments[5]:2,d2:"",d2Len:0,uinType:arguments.length>6&&void 0!==arguments[6]?arguments[6]:30,uin:"",uinLen:0,reqHead:{seqNumber:i,appId:e,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:r,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:t}}(t,e,VD);VD=VD+1&2147483647,i.writeInt32(0),i.writeInt32(r.version),i.writeByte(r.encryption);let n=(new TextEncoder).encode(r.d2);i.writeInt32(n.length+4),n&&i.writeBytes(n),i.writeByte(r.uinType);let o=(new TextEncoder).encode(r.uin);i.writeInt32(o.length+4),o.length&&i.writeBytes(o);let s=new OD;s.writeInt32(0),s.writeInt32(r.reqHead.seqNumber),s.writeInt32(r.reqHead.appId),s.writeByte(r.reqHead.appId>>>24&255),s.writeByte(r.reqHead.appId>>>16&255),s.writeByte(r.reqHead.appId>>>8&255),s.writeByte(255&r.reqHead.appId);for(let E=4;E<16;E++)s.writeByte(0);let a=(new TextEncoder).encode(r.reqHead.a2);s.writeInt32(a.length+4),a.length&&s.writeBytes(a);let c=(new TextEncoder).encode(r.reqHead.serviceCmd);s.writeInt32(c.length+4),c.length&&s.writeBytes(c);let l=(new TextEncoder).encode(r.reqHead.cookie);s.writeInt32(l.length+4),l.length&&s.writeBytes(l);let d=(new TextEncoder).encode(r.reqHead.imei);s.writeInt32(d.length+4),d.length&&s.writeBytes(d);let u=(new TextEncoder).encode(r.reqHead.ksid);s.writeInt32(u.length+4),u.length&&s.writeBytes(u);let h=(new TextEncoder).encode(r.reqHead.clientVersionInfo);s.writeInt16(h.length+2),h.length&&s.writeBytes(h);let p=s.length;s.data[0]=p>>>24&255,s.data[1]=p>>>16&255,s.data[2]=p>>>8&255,s.data[3]=255&p,uw(e)&&(e=(new TextEncoder).encode(e)),s.writeInt32(e.length+4),e.length&&s.writeBytes(e);let m=new Uint8Array(s.data),_=null;1===r.encryption?_=(new TextEncoder).encode(r.uin):2===r.encryption&&(_=new Uint8Array(16)),_&&(m=function(e,t){let i=e.length,r=(i+1+BD+HD)%8;r&&(r=8-r);let n=i+1+BD+HD+r,o=new Uint8Array(n),s=0,a=new Uint8Array(8),c=new Uint8Array(8),l=new Uint8Array(8),d=0;a[0]=248&Math.floor(256*Math.random())|r,d=1;for(let h=0;h<r;h++)a[d]=255&Math.floor(256*Math.random()),d+=1;for(let h=0;h<BD;)if(d<8&&(a[d]=255&Math.floor(256*Math.random()),d+=1,h+=1),8===d){GD(a,t,c,l,o,s),s+=8,d=0;for(let e=0;e<8;e++)l[e]=o[s-8+e]}let u=0;for(;u<i;)if(d<8&&(a[d]=e[u],d+=1,u+=1),8===d){GD(a,t,c,l,o,s),s+=8,d=0;for(let e=0;e<8;e++)l[e]=o[s-8+e]}for(let h=0;h<HD;)if(d<8&&(a[d]=0,d+=1,h+=1),8===d){GD(a,t,c,l,o,s),s+=8,d=0;for(let e=0;e<8;e++)l[e]=o[s-8+e]}return o}(m,_)),i.writeBytes(m);let f=new Uint8Array(i.data),g=f.length;return f[0]=g>>>24&255,f[1]=g>>>16&255,f[2]=g>>>8&255,f[3]=255&g,f}function GD(e,t,i,r,n,o){for(let s=0;s<8;s++)e[s]^=r[s];!function(e,t,i,r){let n=PD(e,0),o=PD(e,4),s=[];for(let c=0;c<4;c++)s[c]=PD(t,4*c);let a=0;for(let c=0;c<FD;c++)a+=UD,a>>>=0,n+=(o<<4)+s[0]^o+a^(o>>>5)+s[1],n>>>=0,o+=(n<<4)+s[2]^n+a^(n>>>5)+s[3],o>>>=0;MD(i,n,r),MD(i,o,r+4)}(e,t,n,o);for(let s=0;s<8;s++)n[o+s]^=i[s];for(let s=0;s<8;s++)i[s]=e[s]}var jD=function(){return new URLSearchParams(location.search).get("trtc_env")||""},JD=e=>Number(e)<14e8,KD=function(e,t){let i;i=$b||(JD(e)?ck:ak);let r=Math.floor(Math.random()*mb(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},qD="unknown";function zD(){if("unknown"!==qD)return qD;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&&(qD=YD(r,n)),qD}function YD(e,t){if(_k[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function XD(e){qD=YD(e)}function QD(){return _k[zD()]}function ZD(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 $D(e){return ew(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function ew(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function tw(e){return 4*iw(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function iw(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var rw="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},nw=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},ow=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 sw(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:sw(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function aw(e){return e>8?3e4:1e3*sw(e)}function cw(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var lw=e=>"function"==typeof e,dw=e=>void 0===e,uw=e=>"string"==typeof e,hw=e=>"number"==typeof e,pw=e=>"boolean"==typeof e,mw=e=>"object"===cw(e),_w=e=>"array"===cw(e),fw=e=>cw(e)==="MediaStreamTrack".toLowerCase(),gw=e=>e.isRemote,Ew=e=>"promise"===cw(e),Tw=e=>lw(e)&&e.prototype.constructor===e,vw=e=>Tw(e)?e.prototype.constructor.name:"",yw="undefined"!=typeof AudioWorkletNode,Sw="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype;function Iw(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 Aw(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var Rw=e=>+e<10?"0".concat(e):e,Cw=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=Rw(i[1])+Rw(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},bw=Object.prototype.hasOwnProperty;function kw(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(ow(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(bw.call(e,t))return!1;return!0}return!1}function Dw(e,t){return{userId:t,hasAudio:!!(e&Dk),hasVideo:!!(e&Ck),hasAuxiliary:!!(e&kk),hasSmall:!!(e&bk),audioMuted:!!(e&wk),videoMuted:!!(e&Nk),audioAvailable:!(!(e&Dk)||e&wk),videoAvailable:!(!(e&Ck)||e&Nk)}}function ww(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!dw(e.username)&&!dw(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",dw(e.credentialType)||(t.credentialType=e.credentialType)),t}function Nw(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!uw(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 Ow=function(e,t,i,r){if(!mw(e)||!mw(t))return 0;let n,o=0,s=Object.keys(t);for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(dw(t[n])||i&&i.includes(n)))if(mw(e[n])&&mw(t[n]))o+=Ow(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=Mw(t[n]),o+=1)}return o};function Mw(e){if(_w(e)){let t=[];return e.forEach(((e,i)=>{t[i]=Mw(e)})),t}if(mw(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=Mw(e[i])})),t}return e}var Pw=e=>{let t=[];if(_w(e))t=[...e];else if(uw(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},Lw=e=>uw(e)?document.getElementById(e):e,xw=()=>(e=>{let t=e=>e<10?"0".concat(e):"".concat(e),i=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),o=t(e.getHours()),s=t(e.getMinutes()),a=t(e.getSeconds());return"".concat(i,"/").concat(r,"/").concat(n," ").concat(o,":").concat(s,":").concat(a)})(new Date);function Vw(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(_w(e))return"[".concat(e.map((e=>Vw(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!ow(e)||!_w(i)&&!_w(r))return JSON.stringify(e);let t={},n=new Set(i),o=new Set(r);return Object.keys(e).forEach((s=>{(0===o.size&&n.has(s)||0===n.size&&!o.has(s))&&(t[s]=ow(e[s])||_w(e[s])?JSON.parse(Vw(e[s],{keysToExclude:r,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(Xk){return"{}"}}function Uw(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)})),Vw(e,{keysToInclude:i})}function Fw(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Bw=()=>{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},Hw=e=>Ab(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(uw(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 Ub({code:xb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}}))})),Ww=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},Gw=e=>(Object.keys(e).forEach((t=>{hw(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(ow(e[t])||_w(e[t]))&&Gw(e[t])})),e);function jw(e,t){return new Promise((i=>{let r=setTimeout(i,e);t&&t(r)}))}function Jw(e,t){let i=null;return function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return i||(i=e.apply(t||this,n),i.finally((()=>i=null)),i)}}function Kw(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function qw(e){var t;try{let{width:i,height:r,frameRate:n,sampleRate:o,sampleSize:s,channelCount:a}=null==(t=e.getSettings)?void 0:t.call(e),c=e.kind===Sk.AUDIO?"".concat(o,"x").concat(s,"@").concat(a):"".concat(i,"x").concat(r,"@").concat(n),l=e.stats?" stats: ".concat(JSON.stringify(e.stats).replaceAll('"',"")):"";return"".concat(e.id," ").concat(e.readyState," muted:").concat(e.muted," ").concat(e.kind," ").concat(e.label," ").concat(c).concat(l)}catch(zb){return""}}function zw(e,t){return e.width*e.height==t.width*t.height?1:Bw()&&t.width>t.height&&e.height>t.width?Math.max(e.width/t.height,e.height/t.width,1):Math.max(e.width/t.width,e.height/t.height,1)}function Yw(e){return 90===e||270===e}function Xw(e){return Ab(this,null,(function*(){return new Promise(((t,i)=>{let r=document.createElement("video");r.crossOrigin="anonymous",r.src=e,r.muted=!0,r.loop=!0,r.playsInline=!0,r.play().then((()=>t(r))),r.onerror=()=>{i(r.error)}}))}))}function Qw(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new WeakMap;if("object"!=typeof e||null===e)return e;if(t.has(e))return t.get(e);if(Array.isArray(e)){let i=[];return t.set(e,i),e.forEach(((e,r)=>{i[r]=Qw(e,t)})),i}if("[object Object]"===Object.prototype.toString.call(e)){let i={};return t.set(e,i),Reflect.ownKeys(e).forEach((r=>{i[r]=Qw(e[r],t)})),i}return e}var Zw=(e=>(e[e.END_REPORT=2001]="END_REPORT",e[e.LOG=2002]="LOG",e[e.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",e))(Zw||{});function $w(e,t,i,r){try{let n=function(e,t,i,r){let n={data:e,random:Math.floor(2147483648*Math.random()),sdkAppId:i};return dw(r)||(n=gb(fb({},n),{gzip:+r})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:t,bytes_report_data:JSON.stringify(n)}}}(e,t,i,r);return WD(ND(n),i)}catch(AM){return JSON.stringify(e)}}function eN(e){let t=function(e){try{let t={},i=0;t.totalLength=PD(e,i),i+=4,t.version=PD(e,i),i+=4,t.encryption=LD(e,i),i+=1,t.uinType=LD(e,i),i+=1,t.uinLength=PD(e,i),i+=4,t.uin=t.uinLength>4?xD(e,i,t.uinLength-4):"",i+=t.uinLength-4;let r=e.slice(i);if(2===t.encryption){e=function(e,t){let i=0,r=new Uint8Array(8).fill(0),n=new Uint8Array(e.slice(0,8)),o=tN(n,t),s=7&o[0],a=e.length-1-s-BD-HD,c=new Uint8Array(a),l=0,d=r,u=e.slice(0,8);i=8;let h=1;h+=s;for(let m=1;m<=BD;)if(h<8)h++,m++;else if(8===h){let r=iN(e,i,d,u,o,t);d=r.ivPreCrypt,u=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,h=0}let p=a;for(;p>0;)if(h<8)c[l++]=o[h]^d[h],h++,p--;else if(8===h){let r=iN(e,i,d,u,o,t);d=r.ivPreCrypt,u=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,h=0}for(let m=1;m<=HD;)if(h<8)o[h],d[h],h++,m++;else if(8===h){if(i>=e.length)break;let r=iN(e,i,d,u,o,t);if(!r.success)break;d=r.ivPreCrypt,u=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,h=0}return c}(r,new Uint8Array(16).fill(0)),t.decrypted=!0,i=0}else e=r,i=0;return t.rspHeadLength=PD(e,i),i+=4,t.seqNo=PD(e,i),i+=4,t.retCode=PD(e,i),i+=4,t.retStrLength=PD(e,i),i+=4,t.retStr=t.retStrLength?xD(e,i,t.retStrLength-4):"",i+=t.retStrLength-4,t.serviceCmdLength=PD(e,i),i+=4,t.serviceCmd=t.serviceCmdLength?xD(e,i,t.serviceCmdLength-4):"",i+=t.serviceCmdLength-4,t.cookieLength=PD(e,i),i+=4,t.cookie=t.cookieLength?xD(e,i,t.cookieLength-4):"",i+=t.cookieLength-4,t.flag=PD(e,i),i+=4,t.busiBuffLength=PD(e,i),i+=4,t.busiBuff=t.busiBuffLength?xD(e,i,t.busiBuffLength-4):"",i+=t.busiBuffLength-4,t}catch(t){}}(e);return null==t?void 0:t.busiBuff}function tN(e,t){let i=e[0]<<24|e[1]<<16|e[2]<<8|e[3],r=e[4]<<24|e[5]<<16|e[6]<<8|e[7];i>>>=0,r>>>=0;let n=UD*FD>>>0;for(let o=0;o<FD;o++)r-=(i<<4)+t[2]^i+n^(i>>>5)+t[3],r>>>=0,i-=(r<<4)+t[0]^r+n^(r>>>5)+t[1],i>>>=0,n-=UD,n>>>=0;return new Uint8Array([i>>>24&255,i>>>16&255,i>>>8&255,255&i,r>>>24&255,r>>>16&255,r>>>8&255,255&r])}function iN(e,t,i,r,n,o){if(t+8>e.length)return{success:!1};let s=new Uint8Array(r),a=e.slice(t,t+8),c=new Uint8Array(8);for(let l=0;l<8;l++)c[l]=n[l]^a[l];return{success:!0,ivPreCrypt:s,ivCurCrypt:a,debiBuf:tN(c,o),bufPos:t+8}}var rN="undefined"!=typeof TextDecoder?new TextDecoder:void 0;function nN(e){let{url:t,body:i,method:r="POST",timeout:n,priority:o}=e;return new Promise(((e,s)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:o}).then((e=>e.clone().json().then((e=>({data:e})),(()=>e.arrayBuffer().then((e=>({data:eN(new Uint8Array(e))||(rN?rN.decode(e):e)}))))))).then(e,s);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 s({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=n||5e3,a.open(r,t,!0),a.send(i)}))}function oN(e){return Ab(this,null,(function*(){let t=Aw(),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 _M.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(Aw()-t,"ms")),r}catch(Xk){return i}}))}var sN=Object.prototype.hasOwnProperty,aN=e=>"function"==typeof e,cN=e=>void 0===e,lN=e=>"boolean"==typeof e,dN=e=>e.isRemote,uN=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)};var hN=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:n,onRetryFailed:o,onRetrySuccess:s,context:a}=e;return function(){for(var e=arguments.length,c=new Array(e),l=0;l<e;l++)c[l]=arguments[l];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,_=(e,i)=>Ab(this,null,(function*(){let l=a||this;try{let i=yield t.apply(l,c);h>0&&s&&s.call(this,h),h=0,e(i)}catch(DP){let s=()=>{clearTimeout(p),h=0,m=2,i(DP)},a=()=>{2!==m&&h<(aN(d)?d():d)?(h++,m=1,aN(n)&&n.call(this,h,s),p=window.setTimeout((()=>{p=-1,_(e,i)}),aN(u)?u(h):u)):(s(),aN(o)&&o.call(this,DP))};aN(r)?r.call(this,{error:DP,retry:a,reject:i,retryFuncArgs:c,retriedCount:h}):a()}}));return new Promise(_)}},pN=class{constructor(e){Sb(this,"userId"),Sb(this,"remoteUserId"),Sb(this,"id"),Sb(this,"sdkAppId"),Sb(this,"type"),Sb(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!lN(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):"","]")),_M.log(e,t,cN(this.userId)||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(uN(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(sN.call(e,t))return!1;return!0}return!1}(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:()=>NO,CHROME_VERSION:()=>OO,EDGE_VERSION:()=>PN,EDG_MAJOR_VERSION:()=>VN,EDG_VERSION:()=>xN,FIREFOX_MAJOR_VERSION:()=>ON,FIREFOX_VERSION:()=>NN,HUAWEI_VERSION:()=>EO,IE_VERSION:()=>zN,IOS_MAIN_VERSION:()=>BO,IOS_VERSION:()=>VO,IPADQQB_VERSION:()=>oO,IS_ANDROID:()=>CN,IS_ANDROID_WEBVIEW:()=>xO,IS_ANY_SAFARI:()=>PO,IS_CHROME:()=>DO,IS_CHROME_OS:()=>lO,IS_CHROMIUM_BASE:()=>kO,IS_DESKTOP_IOS_CHROME:()=>JO,IS_EDG:()=>LN,IS_EDGE:()=>MN,IS_ELECTRON:()=>hO,IS_FIREFOX:()=>wN,IS_HEADLESS_CHROME:()=>wO,IS_HONOR:()=>gO,IS_HUAWEI:()=>fO,IS_HUAWEIBROWSER:()=>_O,IS_IE:()=>qN,IS_IE8:()=>KN,IS_IOS:()=>RN,IS_IOS_13_OR_14:()=>GO,IS_IOS_15_1:()=>WO,IS_IOS_CHROME:()=>jO,IS_IPAD:()=>yN,IS_IPADQQB:()=>nO,IS_IPAD_PRO:()=>SN,IS_IPHONE:()=>IN,IS_IPOD:()=>AN,IS_LINUX:()=>cO,IS_LOCAL:()=>KO,IS_MAC:()=>aO,IS_MACQQB:()=>iO,IS_MIBROWSER:()=>pO,IS_MQQB:()=>ZN,IS_NATIVE_ANDROID:()=>DN,IS_OLD_ANDROID:()=>kN,IS_OPENHARMONY:()=>RO,IS_OPPOBROWSER:()=>yO,IS_SAFARI:()=>MO,IS_SAFARI_15_1:()=>HO,IS_SAMSUNGBROWSER:()=>TO,IS_SOGOU:()=>BN,IS_SOGOUM:()=>UN,IS_TBS:()=>WN,IS_UCBROWSER:()=>uO,IS_VIVOBROWSER:()=>IO,IS_WECHAT:()=>YN,IS_WIN:()=>sO,IS_WQQB:()=>eO,IS_WX:()=>dO,IS_X5MQQB:()=>QN,IS_XWEB:()=>jN,MACQQB_VERSION:()=>rO,MI_VERSION:()=>mO,MQQB_VERSION:()=>$N,OPENHARMONY_VERSION:()=>CO,OPPO_VERSION:()=>SO,SAFARI_VERSION:()=>LO,SAMSUNG_VERSION:()=>vO,SOGOUM_VERSION:()=>FN,SOGOU_VERSION:()=>HN,TBS_VERSION:()=>GN,UA_DATA_STRING:()=>ZO,USER_AGENT:()=>_N,VIVO_VERSION:()=>AO,WECHAT_VERSION:()=>XN,WQQB_VERSION:()=>tO,XWEB_VERSION:()=>JN,browserInfo:()=>zO,getBrowserCoreNumber:()=>oM,getBrowserInfo:()=>YO,getChromeMajorVersion:()=>bO,getDeviceModel:()=>tM,getGPUInfo:()=>eM,getOSName:()=>rM,getOSNumber:()=>nM,getOSString:()=>sM,getOSType:()=>cM,getTerminalType:()=>aM,getUserAgentData:()=>$O,isLocalStorageEnabled:()=>qO,isMobile:()=>QO,isVersionLargerThan:()=>FO,isVersionSmallerThan:()=>UO});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,AN=fN("iPod"),RN=IN||yN||AN||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,wN=fN("Firefox"),NN=gN("Firefox"),ON=EN("Firefox"),MN=fN("Edge"),PN=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"),WN=fN("TBS"),GN=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=!WN&&fN("MQQBrowser")&&fN("COVC"),ZN=!WN&&fN("MQQBrowser")&&!fN("COVC"),$N=ZN||QN?gN("MQQBrowser"):"",eO=!WN&&fN(" QQBrowser"),tO=gN(" QQBrowser"),iO=!WN&&fN("QQBrowserLite"),rO=gN("QQBrowserLite"),nO=!WN&&fN("MQBHD"),oO=gN("MQBHD"),sO=fN("Windows"),aO=!RN&&fN("MAC OS X"),cO=!CN&&fN("Linux"),lO=fN("CrOS"),dO=fN("MicroMessenger"),uO=fN("UCBrowser"),hO=fN("Electron"),pO=fN("MiuiBrowser"),mO=gN("MiuiBrowser"),_O=fN("HuaweiBrowser"),fO=fN("Huawei")||fN("HUAWEI"),gO=fN("Honor")||fN("HONOR"),EO=gN("HuaweiBrowser"),TO=fN("SamsungBrowser"),vO=gN("SamsungBrowser"),yO=fN("HeyTapBrowser"),SO=gN("HeyTapBrowser"),IO=fN("VivoBrowser"),AO=gN("VivoBrowser"),RO=fN("OpenHarmony"),CO=gN("OpenHarmony"),bO=()=>EN("Chrome"),kO=fN("Chrome"),DO=!MN&&!BN&&!UN&&!WN&&!jN&&!LN&&!eO&&!pO&&!_O&&!TO&&!yO&&!IO&&kO,wO=fN("HeadlessChrome"),NO=bO(),OO=gN("Chrome"),MO=!kO&&!ZN&&!QN&&!iO&&!nO&&fN("Safari"),PO=MO||RN,LO=gN("Version"),xO=/Android.*(wv|.0.0.0)/.test(_N),VO=(()=>{if(SN)return LO;if(RN){let e=_N.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})();function UO(e,t){let i=e.split(".").map((e=>Number(e))),r=t.split(".").map((e=>Number(e)));for(let n=0;n<Math.max(i.length,r.length);n++){let e=i[n]||0,t=r[n]||0;if(e<t)return!0;if(e>t)return!1}return!1}function FO(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=e.split(".").map((e=>Number(e))),n=t.split(".").map((e=>Number(e)));for(let o=0;o<Math.max(r.length,n.length);o++){let e=r[o]||0,t=n[o]||0;if(e>t)return!0;if(e<t)return!1}return i}var BO=Number(VO.split(".")[0]),HO="15.1"===LO,WO="15.1"===VO,GO=(()=>{let e=Number(VO.split(".")[0]);return 14===e||13===e})(),jO=fN("CriOS"),JO=jO&&"11.1.1"===LO,KO="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),qO=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(IM){e=!1}return e}})(),zO=YO();function YO(){let e=new Map([[wN,["Firefox",NN]],[LN,["Edg",xN]],[DO,["Chrome",OO]],[MO,["Safari",LO]],[WN,["TBS",GN]],[jN,["XWEB",JN]],[YN&&IN,["WeChat",XN]],[eO,["QQ(Win)",tO]],[ZN,["QQ(Mobile)",$N]],[QN,["QQ(Mobile X5)",$N]],[iO,["QQ(Mac)",rO]],[nO,["QQ(iPad)",oO]],[pO,["MI",mO]],[_O,["HW",EO]],[TO,["Samsung",vO]],[yO,["OPPO",SO]],[IO,["VIVO",AO]],[MN,["EDGE",PN]],[UN,["SogouMobile",FN]],[BN,["Sogou",HN]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var XO=null;function QO(){return XO&&"boolean"==typeof XO.mobile?XO.mobile:CN||RN||IN||yN||RO}var ZO="";function $O(){return Ab(this,null,(function*(){if(XO)return XO;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(XO=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!ZO&&(ZO="UAData: ".concat(XO.platform,"/").concat(XO.platformVersion),XO.architecture&&XO.bitness&&(ZO+=" ".concat(XO.architecture,"/").concat(XO.bitness)),XO.mobile&&(ZO+=" mobile"),XO.model&&(ZO+=" model: ".concat(XO.model.replace(/\s+/g,"/"))),XO.fullVersionList&&(ZO+=" ".concat(XO.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),XO}catch(EJ){return null}}))}function eM(){try{let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"";let i=t.getExtension("WEBGL_debug_renderer_info");if(i){let e=t.getParameter(i.UNMASKED_VENDOR_WEBGL),r=t.getParameter(i.UNMASKED_RENDERER_WEBGL);return"".concat(e," ").concat(r)}return""}catch(EJ){return""}}function tM(){return(null==XO?void 0:XO.model)||""}var iM=new Map([[CN,"Android"],[RN,"iOS"],[sO,"Windows"],[aO,"MacOS"],[cO,"Linux"],[lO,"ChromeOS"]]),rM=function(){return iM.get(!0)?iM.get(!0):XO?XO.platform:"unknown"};function nM(){return sO?1:CN?2:aO?3:RN?4:cO?5:lO?6:RO?7:0}function oM(){return kO?1:MO?2:wN?3:0}var sM=()=>{let e=rM();return e+="/".concat(zO.name,"/").concat(MO?zO.version:zO.version.split(".")[0]),null!=XO&&XO.platformVersion&&(e+="/".concat(XO.platformVersion)),null!=XO&&XO.architecture&&(e+="/".concat(XO.architecture)),e};function aM(){return CN?4:IN?2:yN?3:aO?12:sO?5:cO?13:RO?22:1}function cM(){return CN?"Android":IN?"iPhone":yN?"iPad":aO?"Mac":sO?"Windows":cO?"Linux":"unknown"}var lM,dM=new(vb(Rb(),1).default),uM=((lM=uM||{}).ROOM_DESTROY="1",lM.JOIN_START="21",lM.JOIN_SCHEDULE_SUCCESS="22",lM.JOIN_SIGNAL_CONNECTION_START="23",lM.JOIN_SIGNAL_CONNECTION_END="24",lM.JOIN_SEND_CMD="25",lM.JOIN_RECEIVED_CMD_RES="26",lM.JOIN_SUCCESS="27",lM.JOIN_FAILED="28",lM.LEAVE_START="51",lM.LEAVE_SEND_CMD="52",lM.LEAVE_SUCCESS="53",lM.PUBLISH_START="61",lM.SEND_FIRST_VIDEO_FRAME="62",lM.PUBLISH_FAILED="63",lM.SUBSCRIBE_START="81",lM.SUBSCRIBE_SUCCESS="82",lM.SUBSCRIBE_FAILED="84",lM.UNSUBSCRIBE_SUCCESS="83",lM.LOCAL_TRACK_CAPTURE_START="101",lM.LOCAL_TRACK_CAPTURE_SUCCESS="102",lM.LOCAL_TRACK_CAPTURE_FAILED="103",lM.LOCAL_TRACK_PUBLISHED="104",lM.LOCAL_TRACK_UNPUBLISHED="105",lM.LOCAL_TRACK_REPLACED="106",lM.SWITCH_DEVICE_SUCCESS="107",lM.TRACK_MUTED="108",lM.TRACK_UNMUTED="109",lM.REMOTE_TRACK_SUBSCRIBED="110",lM.REMOTE_TRACK_UNSUBSCRIBED="111",lM.LOCAL_TRACK_RECAPTURE="112",lM.LOCAL_AUDIO_STARTED="113",lM.LOCAL_AUDIO_STOPPED="114",lM.REMOTE_AUDIO_STARTED="115",lM.REMOTE_AUDIO_STOPPED="116",lM.PLAY_TRACK_START="151",lM.PLAYER_STATE_CHANGED="152",lM.VIDEO_LOADED_DATA="153",lM.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",lM.AUDIO_CONTEXT_LONG_SUSPENDED="155",lM.SIGNAL_CONNECTION_STATE_CHANGED="201",lM.PEER_CONNECTION_STATE_CHANGED="202",lM.SINGLE_CONNECTION_STAT="203",lM.SPC_RECONNECTED="204",lM.HEARTBEAT_REPORT="251",lM.RECEIVED_PUBLISHED_USER_LIST="252",lM.REMOTE_PUBLISH_STATE_CHANGED="253",lM.AUDIO_LEVEL_INTERVAL="260",lM.NETWORK_QUALITY="261",lM.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",lM.QUALITY_LIMITATION_CHANGED="263",lM.LOG="264",lM.AUDIO_PROCESSOR_DEBUG="265",lM.SSO_SWITCH="266",lM.SWITCH_ROOM_START="401",lM.SWITCH_ROOM_SUCCESS="407",lM.SWITCH_ROOM_FAILED="408",lM),hM=uM,pM=new class{constructor(){Sb(this,"enable",!1),Sb(this,"ssoFailCount",0),dM.on("22",(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.sso&&dM.emit("266",{enable:!0})})),dM.on("266",(e=>{let{enable:t}=e;this.enable=t}))}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&dM.emit("266",{enable:!1})}},mM=class e{constructor(){Sb(this,"_isEnableUploadLog",!0),Sb(this,"_localJoinedUser",new Map),Sb(this,"_queue",[]),Sb(this,"_timeoutId",-1),Sb(this,"_logLevel",1),Sb(this,"_logLevelToUpload",2),!Xb&&!Qb&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){dM.on(hM.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.logLevelToUpload&&hk[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),dM.on(hM.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),dM.once(hM.JOIN_FAILED,(()=>{this.startUpload()})),dM.on(hM.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(uw(i.userId)&&hw(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 Ab(this,null,(function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;e<t.length;e++){let{userId:i,sdkAppId:r,logs:n}=t[e],o={timestamp:Hb(),sdkAppId:String(r),userId:i,version:Kb,log:n.map((e=>e.log)).join("\n")},s=JSON.stringify(o),a=pM.enable?$w(o,2002,r):s;yield this.uploadLogWithRetry(a,r,a instanceof Uint8Array,s),n.forEach((e=>e.uploaded=!0))}}catch(AM){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t,i,r){return hN({retryFunction:()=>nN({url:KD(t,dk.LOG),body:e,timeout:5e3,priority:"low"}).then((e=>{i&&"ok"!==e.data&&(pM.handleUploadFailed(),this.uploadLogWithRetry(r,t,!1,r))})),settings:{retries:3,timeout:2e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;return t.setTime(Bb()),"[".concat(Wb(t),"] <").concat(hk[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){dw(hk[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(uw(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(zb){return""}}log(t,i){let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0;var s;i.unshift(this.getPrefix(t));let a={log:i.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:t,userId:n,sdkAppId:o,forAllJoinedClients:r};if(dM.emit(hM.LOG,{log:a}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(a),t<this._logLevel)return;let c=(null==(s=hk[t])?void 0:s.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;hk[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};Sb(mM,"PRINT_LOG_TAG",!(RN||CN||wO));var _M=new mM,fM=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)}))},gM=new class{constructor(){Sb(this,"_prefix","TRTC"),Sb(this,"_queue",new Map)}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){qO()&&(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(AM){return!1}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(qO())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(IM){_M.warn(IM)}}getItem(e){if(!qO())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(zb){_M.warn(zb)}}setItem(e,t){if(qO())try{let i={expiresIn:Date.now()+fk,value:t};this._queue.set(this.getRealKey(e),i)}catch(Xk){_M.warn(Xk)}}deleteItem(e){if(!qO())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(zb){return _M.warn(zb),!1}}clear(){if(qO())try{localStorage.clear()}catch(IM){_M.warn(IM)}}},EM={};Tb(EM,{HTTPS_API:()=>rL,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>RL,IS_GET_CAPABILITIES_SUPPORTED:()=>AL,IS_GET_SETTINGS_SUPPORTED:()=>IL,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>SL,IS_INSERTABLE_STREAM_SUPPORTED:()=>CL,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>FL,IS_RTC_RTP_SENDER_SUPPORTED:()=>TL,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>bL,IS_SEI_SUPPORTED:()=>kL,IS_SPC_SUPPORTED:()=>gL,basis:()=>PL,capabilityCheck:()=>VL,checkSystemRequirementsInternal:()=>QP,decodeSupportStatus:()=>XP,detectVideoCodecCapabilities:()=>WL,detectVideoDecoderCapabilities:()=>jL,detectVideoEncoderCapabilities:()=>GL,encodeSupportStatus:()=>YP,getBrowserInfo:()=>WP,getDisplayResolution:()=>oL,isAddTransceiverSupported:()=>fL,isBrowserSupported:()=>GP,isCanvasCaptureStreamAPISupported:()=>cL,isCanvasSmallStreamSupported:()=>lL,isGetReceiversSupported:()=>pL,isGetSendersSupported:()=>mL,isGetTransceiversSupported:()=>_L,isGetUserMediaSupported:()=>sL,isMediaDevicesSupported:()=>JP,isMediaSessionSupported:()=>NL,isMediaStreamTrackProcessorSupported:()=>zP,isReplaceTrackSupported:()=>vL,isRequestVideoFrameCallbackSupported:()=>UL,isSIMDSupported:()=>ML,isScaleResolutionDownBySupported:()=>dL,isScreenCaptureApiAvailable:()=>$P,isSelectedCandidatePair:()=>nL,isSetParametersSupported:()=>yL,isSetSinkIdSupported:()=>eL,isSmallStreamSupported:()=>uL,isStopTransceiverSupported:()=>EL,isTRTCSupported:()=>ZP,isUnifiedPlanDefault:()=>hL,isUsedInHttpProtocol:()=>qP,isWebAudioSupported:()=>aL,isWebCodecSupported:()=>wL,isWebCodecsSupported:()=>jP,isWebRTCSupported:()=>DL,isWebTransportSupported:()=>OL});var TM={};Tb(TM,{AUDIO_LEVEL_SCALE:()=>dP,AudioCodecPipelineType:()=>_P,AudioDecoderDowngradeState:()=>JM,AudioPlayerMode:()=>aP,AudioType:()=>QM,BASIC_TYPE:()=>hP,BannedReason:()=>cP,CONNECTION_CLOSED_REASON:()=>OM,CheckPermissionType:()=>yP,ClientEvent:()=>MM,CodecType:()=>fP,ConnectionEvent:()=>NM,ConnectionState:()=>jM,DECODE_FAILED_ERROR_CODE:()=>gP,DeviceType:()=>SP,FacingMode:()=>oP,FrameWorkType:()=>wM,LeaveReason:()=>lP,LocalTrackEvent:()=>LM,MULTI_VIDEO_DATA_TYPE:()=>tP,MediaType:()=>YM,MediaTypeLabel:()=>XM,MonitorEventId:()=>iP,MutedFlag:()=>BM,NetworkQualityValue:()=>rP,PlayerState:()=>xM,ReceiveMode:()=>nP,RemoteStreamType:()=>eP,RemoteTrackEvent:()=>FM,RoomEvent:()=>VM,SMALL_MODE:()=>vP,SceneNumber:()=>HM,StreamEvent:()=>PM,StreamType:()=>$M,SubscribeMediaType:()=>uP,TIMER_TYPE:()=>TP,TRACK_ACTION:()=>zM,TRACK_KIND:()=>qM,TrackEvent:()=>UM,UserRole:()=>GM,UserRoleNumber:()=>WM,VideoCodec:()=>pP,VideoCodecPipelineType:()=>mP,VideoContentHint:()=>EP,VideoDecoderDowngradeState:()=>KM,VideoPlayerMode:()=>sP,VideoType:()=>ZM});var vM,yM,SM,IM,AM,RM,CM,bM,kM,DM,wM=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(wM||{}),NM=((DM=NM||{}).TRACK_ADDED="track-added",DM.TRACK_UPDATED="track-updated",DM.TRACK_SUBSCRIBED="track-subscribed",DM.STREAM_ADDED="stream-added",DM.STREAM_REMOVED="stream-removed",DM.STREAM_UPDATED="stream-updated",DM.STREAM_PUBLISHED="stream-published",DM.STREAM_SUBSCRIBED="stream-subscribed",DM.STREAM_UNSUBSCRIBED="stream-unsubscribed",DM.STATE_CHANGED="state-changed",DM.ERROR="error",DM.CONNECTION_STATE_CHANGED="connection-state-changed",DM.FIREWALL_RESTRICTION="firewall-restriction",DM.SEI_MESSAGE="sei-message",DM.CLOSED="closed",DM),OM=(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))(OM||{}),MM=((kM=MM||{}).STREAM_ADDED="stream-added",kM.STREAM_REMOVED="stream-removed",kM.STREAM_UPDATED="stream-updated",kM.STREAM_SUBSCRIBED="stream-subscribed",kM.CONNECTION_STATE_CHANGED="connection-state-changed",kM.PEER_JOIN="peer-join",kM.PEER_LEAVE="peer-leave",kM.MUTE_AUDIO="mute-audio",kM.MUTE_VIDEO="mute-video",kM.UNMUTE_AUDIO="unmute-audio",kM.UNMUTE_VIDEO="unmute-video",kM.CLIENT_BANNED="client-banned",kM.NETWORK_QUALITY="network-quality",kM.AUDIO_VOLUME="audio-volume",kM.SEI_MESSAGE="sei-message",kM.ERROR="error",kM),PM=((bM=PM||{}).PLAYER_STATE_CHANGED="player-state-changed",bM.SCREEN_SHARING_STOPPED="screen-sharing-stopped",bM.CONNECTION_STATE_CHANGED="connection-state-changed",bM.DEVICE_AUTO_RECOVERED="device-auto-recovered",bM.ERROR="error",bM),LM=((CM=LM||{}).DEVICE_AUTO_RECOVERED="1",CM.DEVICE_RECOVER_FAILED="5",CM.DEVICE_CHANGED="2",CM.ERROR="3",CM.PUBLISH_STATE_CHANGED="4",CM.ENCODE_FAILED="6",CM.TRACK_ENDED="7",CM),xM=(e=>(e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e))(xM||{}),VM=((RM=VM||{}).PEER_JOIN="peer-join",RM.PEER_LEAVE="peer-leave",RM.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",RM.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",RM.BANNED="banned",RM.NETWORK_QUALITY="network-quality",RM.AUDIO_VOLUME="audio-volume",RM.SEI_MESSAGE="sei-message",RM.ERROR="error",RM.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",RM.REMOTE_PUBLISHED="remote-published",RM.REMOTE_UNPUBLISHED="remote-unpublished",RM.FIREWALL_RESTRICTION="firewall-restriction",RM.HEARTBEAT_REPORT="heartbeat-report",RM.CUSTOM_MESSAGE="custom-message",RM.LAYER_DATA="layerData",RM.FIRST_VIDEO_FRAME="first-video-frame",RM.DUMP="dump",RM.AUDIO_FRAME="audio-frame",RM.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",RM.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",RM),UM=(e=>(e.PLAYER_STATE_CHANGED="player-state-changed",e.MUTE="mute",e.UNMUTE="unmute",e.ERROR="error",e.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",e.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",e.FIRST_VIDEO_FRAME="first-video-frame",e))(UM||{}),FM=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(FM||{}),BM=(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))(BM||{}),HM=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(HM||{}),WM=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(WM||{}),GM=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(GM||{}),jM=(e=>(e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e))(jM||{}),JM=((AM=JM||{}).INITIALIZED="INITIALIZED",AM.STARTING="STARTING",AM.STARTED="STARTED",AM.FAILED="FAILED",AM),KM=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(KM||{}),qM=(e=>(e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e))(qM||{}),zM=(e=>(e.ADD="add",e.REMOVE="remove",e))(zM||{}),YM=(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))(YM||{}),XM={1:"audio",2:"auxVideo",4:"video"},QM=((IM=QM||{})[IM.opus=111]="opus",IM),ZM=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(ZM||{}),$M=(e=>(e.Big="big",e.Small="small",e))($M||{}),eP=(e=>(e.Main="main",e.Aux="auxiliary",e))(eP||{}),tP=(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))(tP||{}),iP=((SM=iP||{})[SM.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",SM[SM.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",SM[SM.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",SM[SM.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",SM[SM.MUTE_AUDIO=32772]="MUTE_AUDIO",SM[SM.MUTE_VIDEO=32773]="MUTE_VIDEO",SM[SM.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",SM[SM.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",SM[SM.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",SM[SM.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",SM[SM.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",SM[SM.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",SM[SM.SWITCH_CAMERA=32780]="SWITCH_CAMERA",SM[SM.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",SM[SM.REPLACE_VIDEO=32782]="REPLACE_VIDEO",SM[SM.REPLACE_AUDIO=32783]="REPLACE_AUDIO",SM[SM.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",SM[SM.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",SM[SM.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",SM[SM.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",SM[SM.JOIN=32788]="JOIN",SM[SM.LEAVE=32789]="LEAVE",SM[SM.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",SM[SM.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",SM[SM.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",SM[SM.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",SM[SM.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",SM[SM.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",SM[SM.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",SM[SM.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",SM[SM.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",SM[SM.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",SM[SM.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",SM[SM.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",SM[SM.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",SM[SM.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",SM[SM.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",SM[SM.PUBLISH_AUX=32805]="PUBLISH_AUX",SM[SM.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",SM[SM.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",SM[SM.VIDEO_ENCODER=4004]="VIDEO_ENCODER",SM[SM.VIDEO_DECODER=4005]="VIDEO_DECODER",SM),rP=(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))(rP||{}),nP=(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))(nP||{}),oP=(e=>(e.user="user",e.environment="environment",e))(oP||{}),sP=(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))(sP||{}),aP=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(aP||{}),cP=(e=>(e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e))(cP||{}),lP=((yM=lP||{})[yM.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",yM[yM.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",yM[yM.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",yM[yM.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",yM[yM.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",yM[yM.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",yM[yM.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",yM[yM.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",yM[yM.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",yM),dP=1e8,uP=class{constructor(){Sb(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)}},hP=(e=>(e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e))(hP||{}),pP=(e=>(e.H264="h264",e.H265="h265",e.VP8="vp8",e.VP9="vp9",e.AV1="av1",e))(pP||{}),mP=(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))(mP||{}),_P=(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))(_P||{}),fP=(e=>(e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e))(fP||{}),gP=((vM=gP||{})[vM.SUCCESS=0]="SUCCESS",vM[vM.FAILED=1]="FAILED",vM[vM.WEBCODEC_INIT=2]="WEBCODEC_INIT",vM[vM.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",vM[vM.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",vM[vM.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",vM[vM.WASM_INIT=6]="WASM_INIT",vM[vM.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",vM[vM.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",vM[vM.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",vM[vM.TEST=10]="TEST",vM[vM.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",vM),EP=(e=>(e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e))(EP||{}),TP=(e=>(e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e))(TP||{}),vP=(e=>(e.CANVAS="canvas",e.API="api",e))(vP||{}),yP=(e=>(e[e.NONE=0]="NONE",e[e.MICROPHONE=1]="MICROPHONE",e[e.CAMERA=2]="CAMERA",e[e.BOTH=3]="BOTH",e))(yP||{}),SP=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(SP||{}),IP={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"},AP={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(r,"(), received type: ").concat(cw(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(r,"(), received type: ").concat(cw(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,"()")},RP=(e,t)=>t?"".concat(ok,"/").concat(e,"/").concat(t):"".concat(ok,"/").concat(e,"/index.html"),CP=()=>{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(lk);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 bP(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",s="",a="";lw(AP[t])?o=AP[t](i):uw(AP[t])&&(o=AP[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=CP();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(lw(l[t])?a=l[t](i):uw(l[t])&&(a=l[t]));let d=o;return nw()&&(c&&c[t]&&(lw(c[t])?s=c[t](i):uw(c[t])&&(s=c[t])),s&&(d=n?"".concat(s,"\n请查看文档: ").concat(RP("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(RP("en",a),"\n")),d}var kP,DP,wP=vb(Db(),1),NP=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];Sb(this,"countMap",new Map),Sb(this,"distributionMap",new Map),Sb(this,"version"),Sb(this,"log",_M.createLogger({id:"kv"})),e&&(dM.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===Sk.AUDIO?501700:511700,cost:i})})),dM.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===Sk.AUDIO?501700:511700,error:i})})),dM.on("266",(e=>{let{enable:t}=e;this.log.info("".concat(t?"enable":"disable"," sso")),t?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:Ww(this.version||Kb),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,uint32_count:i}})),stats_distribution:[...this.distributionMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,distribution_items:[...i.entries()].map((e=>{let[t,i]=e;return{uint32_item_key:t,uint32_item_value:i}}))}}))};return this.countMap.clear(),this.distributionMap.clear(),e}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){let t=+String(e).slice(-3);return t>=700&&t<799}isErrorCodeKey(e){let t=+String(e).slice(-3);return t>=600&&t<699}isCountKey(e){let t=+String(e).slice(-3);return t>=0&&t<599}isNumberKey(e){let t=+String(e).slice(-3);return t>=800&&t<899}addCount(e){let{key:t,useUV:i=!1}=e;this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}addEnum(e){let{key:t,value:i,useUV:r=!0}=e;var n;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=(null==(n=this.distributionMap)?void 0:n.get(t))||new Map;o.set(i,(o.get(i)||0)+1),this.distributionMap.set(t,o)}addNumber(e){let{key:t,value:i,split:r=100,useUV:n=!1,max:o=5e3}=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;i>o&&(i=o),this.countMap.set(t,(this.countMap.get(t)||0)+1);let a=(null==(s=this.distributionMap)?void 0:s.get(t))||new Map,c=0;if(hw(r))c=Math.floor(i/r);else for(let l=r.length-1;l>0;l--)if(i>r[l]){c=l;break}a.set(c,(a.get(c)||0)+1),this.distributionMap.set(t,a)}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=xb.UNKNOWN;i&&(hw(i)?r=i:(!dw(i.extraCode)||!dw(i.code))&&(r=i.extraCode||i.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:Math.abs(r),useUV:!1})}},OP=((kP=OP||{})[kP.enterRoom=500700]="enterRoom",kP[kP.exitRoom=500701]="exitRoom",kP[kP.switchRole=500702]="switchRole",kP[kP.destroy=500703]="destroy",kP[kP.startLocalAudio=500704]="startLocalAudio",kP[kP.updateLocalAudio=500705]="updateLocalAudio",kP[kP.stopLocalAudio=500706]="stopLocalAudio",kP[kP.startLocalVideo=500707]="startLocalVideo",kP[kP.updateLocalVideo=500708]="updateLocalVideo",kP[kP.stopLocalVideo=500709]="stopLocalVideo",kP[kP.startScreenShare=500710]="startScreenShare",kP[kP.updateScreenShare=500711]="updateScreenShare",kP[kP.stopScreenShare=500712]="stopScreenShare",kP[kP.startRemoteVideo=500713]="startRemoteVideo",kP[kP.updateRemoteVideo=500714]="updateRemoteVideo",kP[kP.stopRemoteVideo=500715]="stopRemoteVideo",kP[kP.muteRemoteAudio=500716]="muteRemoteAudio",kP[kP.setRemoteAudioVolume=500717]="setRemoteAudioVolume",kP[kP.use=500718]="use",kP[kP.switchRoom=500719]="switchRoom",kP[kP.sendSEIMessage=5e5]="sendSEIMessage",kP[kP.sendCustomMessage=500001]="sendCustomMessage",kP),MP=(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[e.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",e[e.VideoMixer=594700]="VideoMixer",e[e.AudioProcessor=595700]="AudioProcessor",e))(MP||{}),PP=(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[e.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",e[e.VideoMixer=594701]="VideoMixer",e[e.AudioProcessor=595701]="AudioProcessor",e))(PP||{}),LP=(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[e.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",e[e.VideoMixer=594702]="VideoMixer",e[e.AudioProcessor=595702]="AudioProcessor",e))(LP||{}),xP=((DP=xP||{})[DP.DECODER_TYPE=514700]="DECODER_TYPE",DP[DP.DECODER_HW_SW=514701]="DECODER_HW_SW",DP[DP.DECODE_RESULT=514702]="DECODE_RESULT",DP[DP.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",DP[DP.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",DP[DP.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",DP[DP.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",DP[DP.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",DP[DP.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",DP[DP.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",DP[DP.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",DP[DP.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",DP[DP.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",DP[DP.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",DP[DP.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",DP[DP.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",DP[DP.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",DP),VP=new NP(!0),UP=new NP(!1),FP=VP,BP={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},HP=new Map([[wN,["Firefox",NN]],[LN,["Edg",xN]],[DO,["Chrome",OO]],[MO,["Safari",LO]],[WN,["TBS",GN]],[jN,["XWEB",JN]],[YN&&IN,["WeChat",XN]],[eO,["QQ(Win)",tO]],[ZN,["QQ(Mobile)",$N]],[QN,["QQ(Mobile X5)",$N]],[iO,["QQ(Mac)",rO]],[nO,["QQ(iPad)",oO]],[pO,["MI",mO]],[_O,["HW",EO]],[TO,["Samsung",vO]],[yO,["OPPO",SO]],[IO,["VIVO",AO]],[MN,["EDGE",PN]],[UN,["SogouMobile",FN]],[BN,["Sogou",HN]]]);function WP(){let e=HP.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var GP=function(){return!(uO||MN||LN&&VN<80||wN&&ON<56)},jP=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every((e=>e in window))},JP=function(){if(!navigator.mediaDevices)return qP()||_M.error(AP.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},KP=!1;function qP(){return"http:"===location.protocol&&!KO&&(KP||_M.error(bP({key:IP.NOT_SUPPORTED_HTTP})),KP=!0,!0)}var zP=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},YP=function(){return Ab(this,null,(function*(){var e,t,i;if(BP.detail.isH264EncodeSupported&&BP.detail.isVp8EncodeSupported)return{isH264EncodeSupported:BP.detail.isH264EncodeSupported,isVp8EncodeSupported:BP.detail.isVp8EncodeSupported,isH265EncodeSupported:BP.detail.isH265EncodeSupported};let r,n=!1,o=!1,s=!1;try{let a=new RTCPeerConnection,c=document.createElement(Sk.CANVAS);c.getContext("2d");let l=c.captureStream(0);return a.addTrack(l.getVideoTracks()[0],l),r=yield a.createOffer(),n=-1!==(null==(e=r.sdp)?void 0:e.toLowerCase().indexOf("h264")),o=-1!==(null==(t=r.sdp)?void 0:t.toLowerCase().indexOf("vp8")),s=-1!==(null==(i=r.sdp)?void 0:i.toLowerCase().indexOf("h265")),a.close(),{isH264EncodeSupported:n,isVp8EncodeSupported:o,isH265EncodeSupported:s}}catch(CM){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}}))},XP=function(){return Ab(this,null,(function*(){var e;if(BP.detail.isH264DecodeSupported&&BP.detail.isVp8DecodeSupported)return{isH264DecodeSupported:BP.detail.isH264DecodeSupported,isVp8DecodeSupported:BP.detail.isVp8DecodeSupported,isH265DecodeSupported:BP.detail.isH265DecodeSupported};let t,i=!1,r=!1;try{let n=new RTCPeerConnection;fL()?(n.addTransceiver(Sk.VIDEO,{direction:"recvonly"}),t=yield n.createOffer()):t=yield n.createOffer({offerToReceiveVideo:!0}),-1!==t.sdp.toLowerCase().indexOf("h264")&&(i=!0),-1!==t.sdp.toLowerCase().indexOf("vp8")&&(r=!0);let o=-1!==(null==(e=t.sdp)?void 0:e.toLowerCase().indexOf("h265"));return n.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:r,isH265DecodeSupported:o}}catch(AM){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}}))};var QP=Jw((e=>Ab(void 0,null,(function*(){let t=Date.now(),i=DL(),r=JP(),n=jP();if(BP.detail.isWebRTCSupported=i,BP.detail.isMediaDevicesSupported=r,BP.detail.isWebCodecsSupported=n,BP.detail.isScreenShareSupported=$P(),BP.detail.isSmallStreamSupported=uL(),37===e)return Object.assign(BP.detail,yield function(){return Ab(this,null,(function*(){return iL||(iL=new Promise((e=>Ab(this,null,(function*(){let t={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!jP())return void e(t);let i=null,r=null,n=null,o=()=>{n&&clearTimeout(n),i=null,r=null};try{i=document.createElement("canvas"),r=i.getContext("2d"),i.width=320,i.height=240;let s=0,a=()=>{!r||!i||(r.fillStyle="hsl(".concat(s%360,", 50%, 50%)"),r.fillRect(0,0,i.width,i.height),r.fillStyle="white",r.font="20px Arial",r.fillText("Frame ".concat(s),10,30),s++)};n=setTimeout((()=>{o(),e(t)}),5e3);let c=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(c.map((e=>Ab(this,null,(function*(){let t,r={type:e.type,encodeSupported:!1,decodeSupported:!1};try{t=yield new Promise(((t,n)=>Ab(this,null,(function*(){try{let o=new VideoEncoder({output:e=>{t(e),r.encodeSupported=!0},error:n});o.configure(e.encodeConfig),a();let s=new VideoFrame(i,{timestamp:0});o.encode(s,{keyFrame:!0}),s.close(),yield o.flush(),o.close()}catch(DM){n(DM)}}))))}catch(p){return _M.warn("".concat(e.type," encoder error:"),p),r}try{yield new Promise(((i,n)=>Ab(this,null,(function*(){try{let o=new VideoDecoder({output:e=>{r.decodeSupported=!0,i(0),e.close()},error:n});o.configure(e.decodeConfig),o.decode(t),yield o.flush(),o.close()}catch(DM){n(DM)}}))))}catch(p){_M.warn("".concat(e.type," decoder error:"),p)}return r})))))).forEach((e=>{"h264"===e.type?(t.isH264EncodeSupported=e.encodeSupported,t.isH264DecodeSupported=e.decodeSupported):"vp8"===e.type&&(t.isVp8EncodeSupported=e.encodeSupported,t.isVp8DecodeSupported=e.decodeSupported)})),o(),e(t)}catch(s){o(),_M.warn("detectWebCodecsSupported failed:",s),e(t)}})))),iL)}))}()),BP.detail.isBrowserSupported=n,BP.result=r&&n,BP.result||_M.error("".concat(navigator.userAgent," ").concat(Uw(BP.detail,!1))),xL(e),FP.addNumber({key:523800,value:Date.now()-t}),BP;if(BP.result&&BP.detail.isH264EncodeSupported&&BP.detail.isVp8EncodeSupported&&BP.detail.isH265EncodeSupported&&BP.detail.isH264DecodeSupported&&BP.detail.isVp8DecodeSupported&&BP.detail.isH265DecodeSupported)return BP;let o=GP(),{encode:s,decode:a}=yield function(){return Ab(this,null,(function*(){let[e,t]=yield Promise.all([YP(),XP()]);return{encode:{h264:e.isH264EncodeSupported,vp8:e.isVp8EncodeSupported,h265:e.isH265EncodeSupported},decode:{h264:t.isH264DecodeSupported,vp8:t.isVp8DecodeSupported,h265:t.isH265DecodeSupported}}}))}(),{h264:c,vp8:l}=s,{h264:d}=a,{h265:u}=s,{vp8:h,h265:p}=a;if(!c||!l){let e=yield YP();_M.warn("detect encode again h264:".concat(c," vp8:").concat(l," result: ").concat(JSON.stringify(e))),c=e.isH264EncodeSupported,l=e.isVp8EncodeSupported}if(c&&d&&CN&&kO&&!jN&&!WN){let{encode:e,decode:t}=yield function(){return Ab(this,null,(function*(){return tL||(tL=new Promise((e=>Ab(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{let r=document.createElement("canvas"),n=r.getContext("2d");r.width=320,r.height=240;let o=setInterval((()=>{n.fillText("test",Math.floor(320*Math.random()),Math.floor(240*Math.random()))}),66),s=-1,a=-1;i=()=>{clearInterval(s),clearInterval(o),clearTimeout(a),l.close(),d.close(),c.getTracks().forEach((e=>e.stop()))},a=setTimeout((()=>{i(),e(t)}),2e3);let c=r.captureStream(),l=new RTCPeerConnection({}),d=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",(e=>d.addIceCandidate(e.candidate))),d.addEventListener("icecandidate",(e=>l.addIceCandidate(e.candidate))),l.addTrack(c.getVideoTracks()[0],c);let u=yield l.createOffer();yield l.setLocalDescription(u),yield d.setRemoteDescription(u);let h=yield d.createAnswer(),p=wP.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=wP.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval((()=>Ab(this,null,(function*(){t.encode&&t.decode&&(i(),e(t));let[r,n]=yield Promise.all([l.getSenders()[0].getStats(),d.getReceivers()[0].getStats()]);t.encode||r.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===Sk.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===Sk.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(r){i(),_M.warn("detectH264Supported failed",r),e({encode:!0,decode:!0})}})))).then((e=>(e.encode||(e.decode=!0),(!e.encode||!e.decode)&&_M.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(ZO)),e))),tL)}))}();c=e,d=t}return BP.result=o&&i&&r&&(c||l)&&(d||h),BP.detail.isBrowserSupported=o,BP.detail.isWebRTCSupported=i,BP.detail.isH264EncodeSupported=c,BP.detail.isVp8EncodeSupported=l,BP.detail.isH265EncodeSupported=u,BP.detail.isH264DecodeSupported=d,BP.detail.isVp8DecodeSupported=h,BP.detail.isH265DecodeSupported=p,BP.result||_M.error("".concat(navigator.userAgent," ").concat(Uw(BP.detail,!1))),xL(),FP.addNumber({key:523800,value:Date.now()-t}),BP})))),ZP=function(){return BP.result},$P=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},eL="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype,tL=null;var iL=null;var rL=(e,t,i)=>{"http:"===location.protocol&&!KO&&(e[t]=()=>{throw new Ub({code:xb.INVALID_OPERATION,message:AP.NOT_SUPPORTED_HTTP})})},nL=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(pw(e.selected)&&!e.selected)};function oL(){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 sL(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function aL(){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 cL(){return"captureStream"in HTMLCanvasElement.prototype}function lL(){return!(YN||RN||NO&&NO<63)&&!(!GP()||!cL())}function dL(){return!(NO<74||MN||BO<11||ON<46)}function uL(){return lL()||dL()}var hL=function(){if(dw(window.RTCRtpTransceiver)||!fL()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:iD}),e.addTransceiver(Sk.AUDIO),t=!0}catch(zb){}return null==e||e.close(),t};function pL(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function mL(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function _L(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function fL(){return!(11===BO&&!JO)&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var gL=!(!fL()||kO&&NO<86);function EL(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var TL="RTCRtpSender"in window;function vL(){return TL&&"replaceTrack"in window.RTCRtpSender.prototype}function yL(){return TL&&"setParameters"in window.RTCRtpSender.prototype&&mL()}var SL="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,IL=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,AL=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,RL="undefined"!=typeof InputDeviceInfo&&"getCapabilities"in InputDeviceInfo.prototype,CL=TL&&"createEncodedStreams"in window.RTCRtpSender.prototype&&bO()>=86,bL="RTCRtpScriptTransform"in window,kL=TL&&(CL||bL),DL=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function wL(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return dw(window.AudioDecoder)||(e.AudioDecoder=!0),dw(window.AudioEncoder)||(e.AudioEncoder=!0),dw(window.VideoDecoder)||(e.VideoDecoder=!0),dw(window.VideoEncoder)||(e.VideoEncoder=!0),dw(window.ImageDecoder)||(e.ImageDecoder=!0),e}function NL(){return"mediaSession"in navigator&&!dw(navigator.mediaSession.setActionHandler)}function OL(){return!dw(window.WebTransport)}function ML(){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 PL(){let e={browser:"".concat(zO.name,"/").concat(zO.version),os:rM(),displayResolution:oL(),isScreenShareSupported:$P(),isWebRTCSupported:DL(),isGetUserMediaSupported:sL(),isWebAudioSupported:aL(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:wL(),isMediaSessionSupported:NL(),isWebTransportSupported:OL()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var LL="checkResult";function xL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30;gM.setItem(LL+e,{ua:navigator.userAgent,checkResult:BP})}function VL(e){qP();let t=gM.getItem(LL+e);t&&t.ua===navigator.userAgent&&t.checkResult&&function(e,t){return!!mw(e)&&Object.keys(t).every((t=>t in e))}(t.checkResult.detail,BP.detail)&&(BP=t.checkResult),QP(e)}function UL(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var FL="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function BL(e){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[e]}var HL=!1;function WL(){return Ab(this,null,(function*(){var e;try{if(HL||null==(e=null==navigator?void 0:navigator.mediaCapabilities)||!e.encodingInfo)return;let t=nM(),i=oM();if(0===t||0===i)return;HL=!0;let r=["H264","VP8","VP9","AV1","H265"],[n,o]=yield Promise.all([GL(r),jL(r)]);n&&Object.keys(n).forEach((e=>{let r=BL(e.toLowerCase());FP.addEnum({key:513707,value:+"".concat(r).concat(+n[e].supported).concat(+n[e].powerEfficient).concat(t).concat(i),useUV:!1})})),o&&Object.keys(o).forEach((e=>{let r=BL(e.toLowerCase());FP.addEnum({key:514713,value:+"".concat(r).concat(+o[e].supported).concat(+o[e].powerEfficient).concat(t).concat(i),useUV:!1})}))}catch(IM){_M.info("detectVideoCodecCapabilities failed",IM)}}))}function GL(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1920,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1080,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:30,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:3e3;return Ab(this,null,(function*(){let o={};try{for(let s of e){let e=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:"video/".concat(s),width:t,height:i,bitrate:n,framerate:r}});o[s]=e}}catch(Yb){}return o}))}function jL(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1920,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1080,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:30,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:3e3;return Ab(this,null,(function*(){let o={};try{for(let s of e){let e=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:"video/".concat(s),width:t,height:i,bitrate:n,framerate:r}});o[s]=e}}catch(Yb){}return o}))}var JL=vb(Rb(),1),KL=Symbol("instance"),qL=Symbol("cacheResult"),zL=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,$L.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},YL=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var XL=new Map;function QL(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,n,o)=>{let s=i.action||n;if(!i.context){let i=XL.get(r)||[];XL.has(r)||XL.set(r,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let r=this;for(var n=arguments.length,o=new Array(n),c=0;c<n;c++)o[c]=arguments[c];if(i.context&&(r=ex.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return i.sync?r[qL]:Promise.resolve(r[qL]);r.state instanceof zL&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof zL&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new YL(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e.join("|")))):e!==r.state&&(l=new YL(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e)));let d=e=>{if(i.fail&&i.fail.call(this,e),i.sync){if(i.ignoreError)return e;throw e}return i.ignoreError?Promise.resolve(e):Promise.reject(e)};if(l)return d(l);let u=r.state,h=new zL(u,t,s);$L.call(r,h);let p=e=>{var n;return r[qL]=e,h.aborted||($L.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[qL])),e},m=e=>($L.call(r,u,e),d(e));try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(p).catch(m):i.sync?p(e):Promise.resolve(p(e))}catch(kM){return m(new YL(r._state,"".concat(r.name," ").concat(s," from ").concat(e," to ").concat(t," failed: ").concat(kM),kM instanceof Error?kM:new Error(String(kM))))}}}}var ZL="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 $L(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(ex.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var ex=class e extends JL.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[KL];n?this.name=n.name+"-"+n.count++:r[KL]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=XL.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);XL.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?r.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:o})})):n.push({to:i,action:o})})),r.forEach((e=>{let{from:t,to:r,action:n}=e;o.add(t),o.add(r),o.add(n+"ing"),i.add("".concat(t," --\x3e ").concat(n,"ing : ").concat(n)),i.add("".concat(n,"ing --\x3e ").concat(r," : ").concat(n," 🟢")),i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🔴"))})),n.forEach((e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(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]:{};ZL(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){$L.call(this,e)}};ex.STATECHANGED="stateChanged",ex.UPDATEAFSM="updateAFSM",ex.INIT="[*]",ex.ON="on",ex.OFF="off",ex.instances=new Map,ex.instances2=new WeakMap;var tx="undefined"!=typeof window,ix=tx&&window.requestIdleCallback||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},rx=tx&&window.cancelIdleCallback||function(e){clearTimeout(e)},nx=tx&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),ox=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=fb("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=gb(fb({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&&(e.isBreakLoop(r)?(null==(i=e.sharedWorker)||i.postMessage({type:"stop",taskId:r.taskID}),e.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),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=Aw(),n=()=>{if(i=Aw()-r,i>=t.delay&&(r=Aw()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!e.isBreakLoop(t))return t.ricID=ix(n,{timeout:t.delay})};return t.ricID=ix(n,{timeout:t.delay})}static raf(t){let i,r=Aw(),n=()=>document.hidden&&t.backgroundTask?(i=Aw()-r,r=Aw(),t.callback(),t.loopCount+=1,e.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(n,t.delay-Math.floor(i%t.delay))):(i=Aw()-r,i>=t.delay&&(r=Aw()-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=Aw()-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:o}=this.taskMap.get(e);return t&&clearInterval(t),i&&clearTimeout(i),r&&nx&&nx(r),n&&rx(n),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.hasTask(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};Sb(ox,"taskMap",new Map),Sb(ox,"currentTaskID",1),Sb(ox,"sharedWorker",null),Sb(ox,"workerTasks",new Map);var sx=ox;Sk.SEI_MESSAGE;var ax={LOADED_DATA:Sk.LOADEDDATA,LOADED_META_DATA:Sk.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},cx={};Tb(cx,{create:()=>dx,remove:()=>ux});var lx=new WeakMap;function dx(e,t){lx.has(e)||lx.set(e,[]);let i=lx.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 ux(e){let t=lx.get(e);t&&(t.forEach((e=>e())),lx.delete(e))}var hx=new class{constructor(){Sb(this,"_roomIdMap",new Map),Sb(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:Kb,env:uk.QCLOUD,browserVersion:zO.name+zO.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){KO||!_M.isAbleToUpload||this._configs.env===uk.QCLOUD&&this.uploadEventToKibana(gb(fb({},e),{result:"success"}))}logFailedEvent(e){if(KO||!_M.isAbleToUpload)return;let{eventType:t,code:i,error:r,userId:n}=e,o={roomId:this._roomIdMap.get(n||this._configs.userId),userId:n,eventType:t,result:"failed",code:i||(null==r?void 0:r.extraCode)||(null==r?void 0:r.code)||xb.UNKNOWN};this._configs.env===uk.QCLOUD&&this.uploadEventToKibana(gb(fb({},o),{error:r}))}uploadEventToKibana(e){let t="stat-".concat(e.eventType,"-").concat(e.result);("delta-join"===e.eventType||"delta-leave"===e.eventType||"delta-publish"===e.eventType)&&(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}uploadEvent(e){let{log:t,userId:i,error:r}=e,n={timestamp:Hb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:Kb,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+="\n".concat(r.stack)));let o=pM.enable?$w(n,2002,Number(this._configs.sdkAppId)):JSON.stringify(n);this.sendRequest(KD(this._configs.sdkAppId,dk.LOG),o)}sendRequest(e,t){setTimeout((()=>nN({url:e,body:t,priority:"low"}).catch((()=>{}))),2e3)}},px=new WeakMap;function mx(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,s){let a=hN({retryFunction:s.value,settings:t,onError(t){let{error:r,retry:n,reject:s,retryFuncArgs:a}=t;var c;i?i.call(this,r,(()=>{var t;null!=(t=px.get(e))&&t.has(o)?n():s(r)}),s,a):null!=(c=px.get(e))&&c.has(o)?n():s(r)},onRetrying(t,i){var n;aN(r)&&r.call(this,t,i),null!=(n=px.get(e))&&n.has(o)&&(px.get(e).get(o).stopRetry=i)},onRetryFailed:n});return s.value=function(){let t=px.get(e);for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return t?t.set(o,{args:r}):px.set(e,new Map([[o,{args:r}]])),a.apply(this,r).finally((()=>{var t;return null==(t=px.get(e))?void 0:t.delete(o)}))},s}}function _x(e){let{fnName:t,callback:i,validateArgs:r=!0}=e;return function(e,n,o){let s=o.value;return o.value=function(){for(var n,o,a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(null!=(n=px.get(e))&&n.has(t)){let{stopRetry:n,args:s}=px.get(e).get(t),a=!0;if(r)for(let e of s)if(!c.find((t=>t===e))){a=!1;break}a&&(i&&i.apply(this,c),n&&n(),null==(o=px.get(e))||o.delete(t))}return s.apply(this,c)},o}}var fx=class extends ex{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,Sb(this,"id"),Sb(this,"element",null),Sb(this,"track"),Sb(this,"url"),Sb(this,"attr"),Sb(this,"mode"),Sb(this,"muted"),Sb(this,"_log"),Sb(this,"_pausedRetryCount"),Sb(this,"_isElementPlayingFired",!1),Sb(this,"_interval"),Sb(this,"_delayDestroyTimeoutId",0),Sb(this,"_playSuccessResolve"),Sb(this,"_isReplayByRecreateMediaStreamCalled",!1),Sb(this,"isInAutoPlayFailedState",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=mD,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){var e;return"PLAYING"===this._state&&!1===(null==(e=this.element)?void 0:e.paused)}get isPaused(){var e;return"PAUSED"===this._state||!0===(null==(e=this.element)?void 0:e.paused)}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,null!==e&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return Ab(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(zb){let t=bP({key:IP.PLAY_FAILED,data:{media:this.kind,error:zb}});if(this._log.warn(zb),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new Ub({code:xb.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&&!PO?this._delayDestroyTimeoutId||(this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout((()=>this.destroyElement()),3*e)):this.destroyElement(),this.handleStopped(Sk.ENDED),this._interval>0&&sx.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():WO?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 dx(this.element,this.element).add(Sk.PLAYING,e).add(Sk.ENDED,e).add(Sk.PAUSE,e).add(Sk.ERROR,e).add(Sk.LOADEDDATA,e).add(Sk.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==cx||cx.create(e,e).add(Sk.ENDED,t).add(Sk.MUTE,t).add(Sk.UNMUTE,t),e.readyState===Sk.ENDED&&this.handleTrackEvent({type:Sk.ENDED}),e.muted&&this.handleTrackEvent({type:Sk.MUTE})}}bindAutoPlayEvent(){dM.on(hM.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;e&&ux(e)}unbindEvents(){this.element&&ux(this.element),this.unbindTrackEvents(),dM.off(hM.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case Sk.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(Sk.PLAYING),this._interval&&(sx.clearTask(this._interval),this._interval=-1);break;case Sk.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(Sk.ENDED);break;case Sk.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(Sk.PAUSE),RN&&(this._interval=sx.run("timeout",(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case Sk.ERROR:if(this.element&&this.element.error){this.handlePaused(Sk.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)),hx.uploadEvent({log:"stat-".concat(this.kind,"-").concat(Zk.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),gO||fO?this.emit(ax.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case Sk.LOADEDDATA:this.kind===Sk.VIDEO&&this.emit(ax.LOADED_DATA);break;case Sk.LOADEDMETADATA:this.kind===Sk.VIDEO&&this.emit(ax.LOADED_META_DATA)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),hx.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),FP.addSuccessEvent({key:this.kind===Sk.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),hx.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),FP.addFailedEvent({key:this.kind===Sk.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(ax.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,i)=>{jw(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)}),jw(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){return Ab(this,null,(function*(){switch(e.type){case Sk.ENDED:this.handleStopped(Sk.ENDED);break;case Sk.MUTE:this.handlePaused(Sk.MUTE);break;case Sk.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&(this._log.warn("track unmuted and element is paused, resume"),yield this.resume()),!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(Sk.UNMUTE))}}))}handlePlaying(e){var t;this._log.debug("handlePlaying",e),null==(t=this._playSuccessResolve)||t.call(this,e),this.emit(ax.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this._log.debug("handlePaused",e),this.emit(ax.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this._log.debug("handleStopped",e),this.emit(ax.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};yb([mx({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],fx.prototype,"doReplayByRecreateMediaStream",1),yb([QL([],"PLAYING",{sync:!0})],fx.prototype,"handlePlaying",1),yb([QL("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],fx.prototype,"handlePaused",1),yb([QL([],"STOPPED",{sync:!0})],fx.prototype,"handleStopped",1);var gx,Ex="trtc_autoplay",Tx="".concat(Ex,"_mask"),vx="".concat(Ex,"_wrapper"),yx="".concat(Ex,"_header"),Sx="".concat(Ex,"_content"),Ix="".concat(Ex,"_action_wrapper"),Ax="".concat(Ex,"_question"),Rx="".concat(Ex,"_collapse"),Cx="".concat(Ex,"_action_confirm"),bx="".concat(Ex,"_detail"),kx="#2473E8",Dx="dialog",wx="".concat(Dx,"-show"),Nx="".concat(Dx,"-1"),Ox="".concat(Dx,"-2"),Mx=!1,Px=()=>!!document.querySelector(".".concat(vx)),Lx="".concat(ok,"/").concat(nw()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),xx="<br><a href='".concat(Lx,"' target='_blank'>").concat(nw()?"其他方案?":"Any other solution?","</a>"),Vx="".concat(nw()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(xx):"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(xx)),Ux=class{constructor(){if(Sb(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),Sb(this,"_dialogNode",null),Sb(this,"_bodyPosition",""),Sb(this,"_showDetail",!1),Sb(this,"_isCollapseClicked",!1),Sb(this,"_isQuestionClicked",!1),nw()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Mx){let e=document.createElement("style");e.innerHTML=".".concat(Tx,"{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(Tx," div:not(.").concat(Ix,"){display:block !important;}.").concat(vx,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(vx," a{color:").concat(kx,";}.").concat(yx,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(Sx,"{margin:8px 0;}.").concat(Ix,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(Rx,"{margin-right:auto;cursor:pointer}.").concat(Ax,"{height:100%;line-height:16px;cursor:pointer;}.").concat(Cx,"{margin-left:8px;color:#fff;background:").concat(kx,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(Cx,":hover{opacity:0.9;}.").concat(Rx,",.").concat(Cx,",.").concat(Sx,",.").concat(Ax,"{font-size:14px;}@media screen and (max-width:750px){.").concat(vx,"{width:80vw;}}"),document.head.appendChild(e),Mx=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(Tx,"\"><div class='").concat(vx,"'><div class='").concat(yx,"'>").concat(location.host,"</div><div class='").concat(Sx,"'>").concat(this.content,"</div><div class='").concat(bx,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(Vx,"</div><div class='").concat(Ix,"'></div></div></div>").trim();let t=document.createElement("button");t.className=Cx,t.innerText=nw()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=Ax,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=Rx,r.innerText="".concat(nw()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(Ix));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){Px()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(vx)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",_M.info("show autoplay dialog"),hx.uploadEvent({log:wx}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){_M.warn("confirm clicked, try resume stream"),dM.emit(hM.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(bx));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||hx.uploadEvent({log:Nx}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Lx,"_blank"),this._isQuestionClicked||hx.uploadEvent({log:Ox}),this._isQuestionClicked=!0}},Fx=class extends fx{constructor(e){super(e,Sk.VIDEO),Sb(this,"stat",{}),Sb(this,"_calculateTimeout",-1),Sb(this,"viewMirror",!1),Sb(this,"objectFit"),Sb(this,"container"),Sb(this,"canvas"),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,dw(e.viewMirror)||(this.viewMirror=e.viewMirror),dw(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return!("PLAYING"!==this._state||this.element&&this.element.paused)&&("live"===(null==(e=this.track)?void 0:e.readyState)&&!this.track.muted)}initializeElement(){var e;let t=document.createElement(Sk.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.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(Sk.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(Sk.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===Sk.MUTE&&null!=(t=this.stat)&&t.fps&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var t,i;if(2===this.mode)return;super.handleElementEvent(e);let r=e.type;if(r===Sk.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id)),this.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=mD,this._log.info("view container ".concat(null==(i=this.container)?void 0:i.id," is recreated"))),this._pausedRetryCount>0&&!Px()&&(this._log.info("[".concat(mD-this._pausedRetryCount+1,"/").concat(mD,"] ").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;r===Sk.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):r===Sk.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,o;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==(o=this.container)||o.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(ax.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(UL()&&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(zb){this._log.warn("init stat failed",zb)}}};function Bx(e,t){return Ab(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),_M.info("worklet addModule success")}catch(zb){throw _M.info("worklet addModule catch error. ".concat(zb.message)),zb}}))}"undefined"!=typeof AudioContext?gx=AudioContext:"undefined"!=typeof webkitAudioContext?gx=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(gx=mozAudioContext);var Hx,Wx=1500,Gx=-1,jx=0,Jx=-1,Kx=!1;!function e(){try{if(Hx)return;(Hx=new gx({sampleRate:48e3})).onstatechange=()=>{_M.info("context state: ".concat(Hx.state).concat("running"!==Hx.state?" visibilityState: ".concat(document.visibilityState):"")),qx()},clearTimeout(Gx)}catch(EJ){_M.error("initAudioContext failed: ".concat(EJ," typeof AudioContextClass: ").concat(typeof gx)),Gx=setTimeout(e,1e3)}}();var qx=()=>{"suspended"===Hx.state?(jx=Aw(),-1===Jx&&(Jx=setTimeout((()=>{"suspended"===Hx.state&&(Kx=!0,dM.emit("155",{isSuspended:!0}))}),Wx)),Xx(),document.addEventListener("click",qx)):"interrupted"===Hx.state?Xx():(jx&&(FP.addNumber({key:507800,value:Aw()-jx,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),jx=0),-1!==Jx&&(clearTimeout(Jx),Jx=-1,Kx&&(Kx=!1,dM.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",qx),document.removeEventListener("click",qx))},zx=0,Yx=-1;function Xx(){return new Promise(((e,t)=>{if("running"===Hx.state)return e();Date.now()-zx<1e3?(clearTimeout(Yx),Yx=setTimeout((()=>{zx=Date.now(),Hx.resume().then(e,t)}),1e3)):(clearTimeout(Yx),zx=Date.now(),Hx.resume().then(e,t))})).catch((e=>{_M.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",qx)}))}document.addEventListener("click",qx);var Qx=e=>Hx,Zx=class{constructor(e){this.name=e,Sb(this,"node"),Sb(this,"node2"),Sb(this,"pre",new Set),Sb(this,"next",new Set),Sb(this,"context"),Sb(this,"connectedNodes",new Set),Sb(this,"nextInputChannelMap",new Map),Sb(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(e){this._channelCount=e,this.setChannelCount(this.node,e),this.setChannelCount(this.node2,e),this.next.forEach((t=>t.channelCount=e))}setChannelCount(e,t){!e||e instanceof ScriptProcessorNode||(e.channelCountMode="explicit",e.channelCount=t||this.channelCount||1)}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.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(Xk){_M.error(Xk)}}setNode(e,t){var i;if(!this.node)try{null==(i=this.context)||i.addMixWeight(),this.node=e,this.setChannelCount(this.node),t&&(this.node2=t,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),FP.addSuccessEvent({key:502701})}catch(AM){_M.error(AM),FP.addFailedEvent({key:502701,error:AM})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),FP.addSuccessEvent({key:502702})}catch(zb){_M.error(zb),FP.addFailedEvent({key:502702,error:zb})}}preNodeReconnect(){this.pre.forEach((e=>{e.node?e.reconnect():e.preNodeReconnect()}))}connectNext(e){this.next.forEach((t=>{let i=this.nextInputChannelMap.get(t);e._connect(t.node,i)||t.connectNext(e)}))}_connect(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return!(!this.node||!e)&&((this.node2||this.node).connect(e,0,t),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(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return this.next.add(e),e.pre.add(this),this.nextInputChannelMap.set(e,t),e}},$x=class extends Zx{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,Sb(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}},eV=class{constructor(){Sb(this,"source",new Zx),Sb(this,"gain",new Zx),Sb(this,"destination",new Zx)}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(Qx().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.replaceNode(nV(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}},tV=class extends eV{constructor(e){super(),this.context=e,Sb(this,"aec",new Zx("aec")),Sb(this,"mixNode",new Zx("mixNode")),Sb(this,"silentNode",new Zx("silentNode")),Sb(this,"denoiser",new Zx("denoiser")),Sb(this,"voiceChanger",new Zx("voiceChanger")),this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.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.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.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()}},iV=class{constructor(){Sb(this,"audioContext",Qx()),Sb(this,"destination",this.audioContext.createMediaStreamDestination()),Sb(this,"inputs",new Set),Sb(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]}},rV=new WeakMap;function nV(e){let t=rV.get(e);if(t)return t;let i=Qx();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return rV.set(e,t),t}var oV=class e{constructor(e){Sb(this,"_volume",0),Sb(this,"_volumeDb",0),Sb(this,"_log"),Sb(this,"_scriptProcessorNode",null),Sb(this,"_audioWorkletNode",null),Sb(this,"_interval",200),Sb(this,"ready",this.preload());let{log:t}=e;this._log=t,dM.on(hM.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=Bx(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(IM){this._log.error("volumeMeter init audio worklet error: ".concat(IM)),hx.logFailedEvent({userId:this._log.userId,eventType:Zk.LOAD_WORKLET,error:IM}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Qx().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(IM){this._log.error("volumeMeter init script processor error: ".concat(IM))}}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,dM.off(hM.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})}};Sb(oV,"lastMessageTime",0),Sb(oV,"audioContext",Qx()),Sb(oV,"workletReady");var sV=oV,aV=class extends Zx{constructor(e){super(),Sb(this,"_volumeMeter"),this._volumeMeter=new sV(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return Ab(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()}}},cV=sV,lV=vb(Rb(),1),dV=e=>t=>t.deviceId===e,uV=class{constructor(e,t){Sb(this,"kind"),Sb(this,"type"),Sb(this,"devices",[]),this.kind=e,this.type=t}update(e,t){let i=e.filter((e=>e.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase())));1===this.devices.length&&mV(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(dV(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");_M.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(dV(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");_M.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},hV=class extends lV.EventEmitter{constructor(){super(),Sb(this,"audioInputs",new uV(Sk.AUDIO,"Input")),Sb(this,"videoInputs",new uV(Sk.VIDEO,"Input")),Sb(this,"audioOutputs",new uV(Sk.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||sx.run("interval",(()=>{this.update()}),{delay:1e4}))}init(){_V().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield _V(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},pV=Qb||Xb?null:new hV;function mV(e){return e.deviceId===e.groupId&&""===e.groupId}function _V(){return Ab(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(qP()||!JP())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{mV(e)&&(e.kind===Sk.AUDIO_INPUT?i.audio=!0:e.kind===Sk.VIDEO_INPUT&&(i.video=!0))})),2===e&&(i.audio=!1),1===e&&(i.video=!1),i.audio||i.video){let e;try{e=yield navigator.mediaDevices.getUserMedia(i),i.audio&&Xx()}catch(AM){_M.debug("capture before getDevices failed: ",AM)}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&&vV.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function fV(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return pV.update(e?1:0).then((e=>e.audioInputs.devices))}function gV(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return pV.update(e?2:0).then((e=>e.videoInputs.devices))}var EV=!1;function TV(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Ab(this,null,(function*(){return(RN||MO)&&(e=!1),pV.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var vV=new Set;function yV(e,t){return Ab(this,null,(function*(){let i=(yield fV()).find((e=>e.deviceId===_D));return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t}))}var SV,IV=class extends eV{constructor(e){super(),this.log=e,Sb(this,"volumeMeter"),Sb(this,"volumeMeterAfter3A"),Sb(this,"volumeDestination"),Sb(this,"analyser",new $x),this.volumeMeter=new aV({log:this.log}),this.volumeMeterAfter3A=new aV({log:this.log}),this.volumeDestination=new Zx,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},AV=class e extends fx{constructor(e){super(e,Sk.AUDIO),Sb(this,"_outputDeviceId"),Sb(this,"_volume",1),Sb(this,"_destination",Qx().createMediaStreamDestination()),Sb(this,"pipeline"),Sb(this,"volumeMeterMode","worklet"),this.mode=0,this.pipeline=new IV(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(("15.2"===VO||"15.3"===VO||"15.4"===VO)&&this.muted)return void this._log.info("audioElement is muted.");let t=SV||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,hw(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),t===SV&&(SV=void 0),this.bindElementEvents()}play(t){return Ab(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(),this.pipeline.volumeMeterAfter3A.init()):"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(Qx().createAnalyser()),function(){Ab(this,null,(function*(){try{EV||(EV=!0,_M.info("speakers:".concat((yield TV()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(e){}}))}(),Ib(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 Ab(this,null,(function*(){var t,i;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield null==(i=(t=this.element).setSinkId)?void 0:i.call(t,e))}))}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()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},RV=class extends AV{setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ax.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)}},CV=class extends AV{constructor(e){super(e),Sb(this,"_sourceElement"),Sb(this,"_output",new Zx),this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Qx().destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,i,r;(null==(i=null==(t=this.element)?void 0:t.error)?void 0:i.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ax.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=(null==(r=e.getSettings())?void 0:r.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?this.element?(this._log.info("set element volume: ".concat(e)),this.element.volume=e):this._log.info("set element volume: no element"):RN||(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),ux(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&&PO&&(SV=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},bV=class extends ex{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:o=(1===r?CV:Fx)}=e;var s;super(),Sb(this,"id",fM()),Sb(this,"userId",""),Sb(this,"isRemote"),Sb(this,"mediaType"),Sb(this,"room"),Sb(this,"user"),Sb(this,"_log"),Sb(this,"_inputTrack"),Sb(this,"_outputTrack"),Sb(this,"isPlayCalled"),Sb(this,"container",null),Sb(this,"player"),Sb(this,"subVideoPlayerMap"),Sb(this,"muted",!1),Sb(this,"abortCtrl"),Sb(this,"objectFit","cover"),Sb(this,"mirror"),Sb(this,"rotation"),Sb(this,"isScreen",!1),Sb(this,"manager"),Sb(this,"trackSettings"),Sb(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=_M.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=n||this.room)?void 0:s.userId,remoteUserId:this instanceof lB?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof lB}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(ax.PLAYER_STATE_CHANGED,(e=>{dM.emit(hM.PLAYER_STATE_CHANGED,fb({track:this},e)),this.emit("player-state-changed",e)})),this.kind===Sk.VIDEO&&(this.player.on(ax.LOADED_DATA,(()=>{this.emitFirstVideoFrameEvent(ax.LOADED_DATA),dM.emit(hM.VIDEO_LOADED_DATA,{track:this})})),this.player.on(ax.LOADED_META_DATA,(()=>{this.emitFirstVideoFrameEvent(ax.LOADED_META_DATA)})),this.player.on(ax.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(ax.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||_M}get kind(){return 1===this.mediaType?Sk.AUDIO:Sk.VIDEO}get strMediaType(){return 4===this.mediaType?Sk.VIDEO:2===this.mediaType?Sk.SCREEN:Sk.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&(!this.mediaTrack.muted&&"live"===this.mediaTrack.readyState&&this.mediaTrack.enabled)}play(e,t){return Ab(this,null,(function*(){let i=_w(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!dw(t.muted)&&this.setPlayerMute(t.muted),t&&!dw(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof Fx&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),_w(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!dw(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===Sk.VIDEO)&&this.setPlayerMute(!0),t&&!dw(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof Fx&&(this.player.setObjectFit(this.objectFit),t&&!dw(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof Fx&&this.player.setContainer(i)),dM.emit(hM.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),_w(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(bM){throw this.handleAutoPlayFailed(bM),bM}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==Sk.VIDEO||dw(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(pw(this.mirror))return i.setViewMirror(this.mirror),void(!this.isRemote&&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 Ab(this,null,(function*(){if(!this._outputTrack||this.kind===Sk.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,i)=>{var r;e.find((e=>i===e))||(t.stop(),null==(r=this.subVideoPlayerMap)||r.delete(i))}));for(let[r,n]of e.entries()){let e=this.subVideoPlayerMap.get(n);e?t&&(dw(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new Fx({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 Ab(this,null,(function*(){var e;this.isPlayCalled&&(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),dM.emit(e?hM.TRACK_MUTED:hM.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){dx(e,e).add(Sk.MUTE,this.onTrackMuted).add(Sk.UNMUTE,this.onTrackUnmuted).add(Sk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Sk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ux(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 Ux;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 Fx?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var t,i,r;if(this.isFirstVideoFrameEmitted)return;let n=null==(t=this.mediaTrack)?void 0:t.getSettings(),o=(null==n?void 0:n.width)||(null==(i=this.player.element)?void 0:i.videoWidth)||0,s=(null==n?void 0:n.height)||(null==(r=this.player.element)?void 0:r.videoHeight)||0;e===ax.LOADED_META_DATA&&!o&&!s||(e===ax.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,Yw(this.rotation)&&([o,s]=[s,o]),this.emit("first-video-frame",{width:o,height:s,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"))}};yb([QL([],ex.INIT,{sync:!0})],bV.prototype,"close",1);var kV=Object.prototype.hasOwnProperty;var DV=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(ow(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(kV.call(e,t))return!1;return!0}return!1},wV=hN({retryFunction:function(e){return Ab(this,null,(function*(){let t=function(e){return{audio:OV(e),video:MV(e)}}(e);_M.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId","groupId"];t.audio&&(i=yield fV(),_M.info("microphones: ".concat(Vw(i.map((e=>gb(fb({},e),{groupId:e.groupId.substring(0,8)}))),{keysToInclude:n})))),t.video&&(r=yield gV(),_M.info("cameras: ".concat(Vw(r,{keysToInclude:n}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return AL&&e.getTracks().forEach((e=>{_M.info("".concat(e.kind," capabilities: ").concat(Vw(e.getCapabilities(),{keysToInclude:SD})))})),t.audio&&Xx(),e}catch(bM){let{message:n}=bM;throw"NotFoundError"===bM.name&&(e.video&&r&&0===r.length&&(n=bP({key:IP.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(n=bP({key:IP.MICROPHONE_NOT_FOUND}))),new Ub({code:xb.INITIALIZE_FAILED,name:bM.name,message:n,constraint:bM.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,retryFuncArgs:n,retriedCount:o}=e,s=o+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===s?(n[0].video&&(n[0].maxResolution=!1,(!MO||n[0].width*n[0].height<=2073600)&&n[0].frameRate&&(n[0].frameRate=n[0].frameRate>10?10:5)),n[0].retryWhenExactFailed&&n[0].useExactDeviceId&&(n[0].useExactDeviceId=!1)):2===s?n[0].useDeviceIdOnly=!0:3===s&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&NV(n[0].microphoneId,!1),n[0].cameraId&&NV(n[0].cameraId,!0)},onRetrying:e=>{_M.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{hx.logFailedEvent({eventType:Zk.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{hx.logSuccessEvent({eventType:Zk.GET_USER_MEDIA_RETRY}),hx.uploadEvent({log:"stat-".concat(Zk.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function NV(e,t){return Ab(this,null,(function*(){let i=(t?yield gV():yield fV()).find((t=>t.deviceId===e));i&&lw(i.getCapabilities)&&_M.warn(Vw(i.getCapabilities(),{keysToInclude:SD}))}))}function OV(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!DV(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(hw(e.channelCount)&&(t.channelCount=e.channelCount),pw(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),pw(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),pw(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!DV(t)||t)}function MV(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&&!DV(i)?i:(e.width&&(i.width={ideal:e.width},t&&!wN&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!wN&&(i.height.max=e.height)),wN&&aO&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!DV(i)||i)}var PV=wV;function LV(e){return UV(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Ab(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function xV(e){return UV(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Ab(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function VV(e){return UV(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Ab(this,null,(function*(){try{return yield t.apply(this,r)}catch(AM){e.call(this,AM)}}))}))}function UV(e){return function(t,i,r){return r.value=e(r.value,i),r}}var FV=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&_M.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{_M.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),BV=0,HV=class{constructor(){Sb(this,"log",_M.createLogger({id:"fq".concat(++BV)})),Sb(this,"isRunning",!1),Sb(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=fb({},e),o=new Promise(((e,t)=>{n.resolve=e,n.reject=t}));return n.promise=o,t?this.length<=1?this.queue.push(n):null==(r=null==(i=this.lastQueueItem)?void 0:i.promise)||r.then(n.resolve,n.reject):this.queue.push(n),this.log.debug("push ".concat(this.length)),this.isRunning||this.callNext(),o}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length)),e}callNext(){if(this.isRunning||0===this.length)return;this.log.debug("callNext ",this.length);let{fn:e,args:t,context:i,resolve:r,reject:n}=this.queue[0];this.isRunning=!0,e.apply(i,t).then(r,n).finally((()=>{this.isRunning=!1,this.shift(),this.callNext()}))}},WV=new WeakMap,GV=new WeakMap;function jV(){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=WV.get(this)||new HV;for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return WV.set(this,t),t.push({fn:n,args:r,context:this},e)},r}}function JV(e){return function(t,i,r){let n=r.value;return r.value=function(){var t,i,r;let o=[];for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return null==(i=null==(t=WV.get(this))?void 0:t.queue)||i.forEach((e=>o.push(e))),null==(r=GV.get(this))||r.forEach((e=>null==e?void 0:e.queue.forEach((e=>o.push(e))))),o.forEach((t=>{t.reject(new Ub({code:xb.API_CALL_ABORTED,message:e}))})),WV.delete(this),GV.delete(this),n.apply(this,a)},r}}function KV(e){return function(t,i,r){let n=r.value,o=t=>e(...t);return r.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=GV.get(this)||new Map,s=r.get(o(t))||new HV;return r.set(o(t),s),GV.set(this,r),s.push({fn:n,args:t,context:this})},r}}function qV(e,t){return UV(((i,r)=>function(){let r=e;try{for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let e=i.apply(this,o),a=Aw();return Ew(e)?e.then((e=>(t?FP.addSuccessEvent({key:r,cost:Aw()-a}):FP.addSuccessEvent({key:r}),e))).catch((e=>{throw FP.addFailedEvent({key:r,error:e}),e})):(FP.addSuccessEvent({key:r}),e)}catch(Yb){throw FP.addFailedEvent({key:r,error:Yb}),Yb}}))}var zV={};function YV(){}Tb(zV,{Events:()=>dU,Inspect:()=>tU,LastSink:()=>iU,Sink:()=>rU,Subscribe:()=>nU,TimeoutError:()=>uU,audit:()=>_F,bindCallback:()=>jU,bindNodeCallback:()=>JU,buffer:()=>AU,bufferCount:()=>IU,bufferTime:()=>ZF,call:()=>XV,catchError:()=>eB,combineLatest:()=>TU,concat:()=>fU,concatMap:()=>BF,concatMapTo:()=>HF,count:()=>QU,create:()=>sU,debounce:()=>EF,debounceTime:()=>TF,defer:()=>bU,delay:()=>$F,deliver:()=>aU,dispose:()=>ZV,elementAt:()=>vF,empty:()=>zU,every:()=>RF,exhaustMap:()=>zF,exhaustMapTo:()=>YF,filter:()=>tF,find:()=>yF,findIndex:()=>SF,first:()=>IF,fromAnimationFrame:()=>WU,fromArray:()=>NU,fromEvent:()=>xU,fromEventPattern:()=>LU,fromFetch:()=>UU,fromIterable:()=>FU,fromPromise:()=>VU,fromReadableStream:()=>HU,fromReader:()=>BU,groupBy:()=>XF,identity:()=>QV,ignoreElements:()=>iF,iif:()=>EU,inspect:()=>$V,interval:()=>OU,last:()=>AF,map:()=>DF,mapTo:()=>wF,max:()=>ZU,merge:()=>mU,mergeMap:()=>jF,mergeMapTo:()=>JF,min:()=>$U,never:()=>KU,nothing:()=>YV,of:()=>wU,pairwise:()=>bF,pipe:()=>oU,race:()=>_U,range:()=>GU,reduce:()=>XU,retry:()=>sB,scan:()=>CF,share:()=>pU,shareReplay:()=>gU,skip:()=>aF,skipUntil:()=>cF,skipWhile:()=>lF,startWith:()=>yU,subject:()=>CU,subscribe:()=>rB,sum:()=>eF,switchMap:()=>LF,switchMapTo:()=>VF,take:()=>rF,takeLast:()=>sF,takeUntil:()=>nF,takeWhile:()=>oF,tap:()=>nB,throttle:()=>pF,throwError:()=>qU,timeInterval:()=>QF,timeout:()=>oB,timer:()=>MU,toPromise:()=>tB,toReadableStream:()=>iB,withLatestFrom:()=>SU,zip:()=>vU});var XV=e=>e(),QV=e=>e;function ZV(){this.dispose()}var $V=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,eU=1,tU=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new lU(e,this,this.streamId++);return dU.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},iU=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=YV,this.error=YV,this.next=YV,this.dispose=YV,this.subscribe=YV,this.doDefer()}subscribe(e){return e instanceof tU?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(XV),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}},rU=class extends iU{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)}},nU=class extends iU{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:YV,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:YV,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:YV;if(super(),this._next=t,this._error=i,this._complete=r,this.then=YV,e instanceof tU){let n={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{dU.defer(n,0)})),dU.create(n),dU.pipe(n),this.sourceId=n.id,this.subscribe(e),dU.subscribe({id:n.id,end:!0}),t==YV?this._next=e=>dU.next(n,0,e):this.next=e=>{dU.next(n,0,e),t(e)},r==YV?this._complete=()=>dU.complete(n,0):this.complete=()=>{this.dispose(),dU.complete(n,0),r()},i==YV?this._error=e=>dU.complete(n,0,e):this.error=e=>{this.dispose(),dU.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 oU(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 sU(e,t,i){if($V()){let r=Object.defineProperties(Object.setPrototypeOf(e,tU.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}});dU.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof tU&&dU.addSource(r,t)}return r}return e}function aU(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 tU){let n=sU((t=>{let o=new e(t,...r);o.sourceId=n.id,o.subscribe(i)}),t,arguments);return n.source=i,dU.pipe(n),n}return t=>i(new e(t,...r))}}}function cU(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var lU=class extends rU{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{dU.defer(this.source,this.id)}))}next(e){dU.next(this.source,this.id,e),this.sink.next(e)}complete(){dU.complete(this.source,this.id),this.sink.complete()}error(e){dU.complete(this.source,this.id,e),this.sink.error(e)}},dU={addSource(e,t){cU("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){cU("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;cU("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){cU("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){cU("defer",{id:e.id,streamId:t})},pipe(e){cU("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){cU("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=eU++),cU("create",{name:e.toString(),id:e.id})}},uU=class extends Error{constructor(e){super("timeout after ".concat(e,"ms")),this.timeout=e}},hU=class extends iU{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 pU(){return e=>{let t=new hU(e);if(e instanceof tU){let i=sU((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,dU.pipe(i),i}return sU(t.add.bind(t),"share",arguments)}}function mU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sU((e=>{let i=new rU(e),r=t.length;i.complete=()=>{0==--r&&e.complete()},t.forEach(i.bindSubscribe)}),"merge",arguments)}function _U(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sU((e=>{let i=new Map;t.forEach((t=>{let r=new rU(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 fU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sU((e=>{let i=0,r=t.length,n=new rU(e);n.complete=()=>{i<r&&!n.disposed?(n.doDefer(),n.subscribe(t[i++])):e.complete()},n.complete()}),"concat",arguments)}function gU(e){return t=>{let i=new hU(t),r=[];return i.next=function(t){r.push(t),r.length>e&&r.shift(),this.sinks.forEach((e=>e.next(t)))},sU((e=>{e.defer((()=>i.remove(e))),r.forEach((t=>e.next(t))),i.add(e)}),"shareReplay",arguments)}}function EU(e,t,i){return sU((r=>e()?t(r):i(r)),"iif",arguments)}function TU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sU((e=>{let i=t.length,r=i,n=i,o=new Array(i),s=()=>{0==--n&&e.complete()};t.forEach(((t,i)=>{let n=new rU(e);n.next=t=>{0==--r?(n.next=t=>{o[i]=t,e.next(o)},n.next(t)):o[i]=t},n.complete=s,n.subscribe(t)}))}),"combineLatest",arguments)}function vU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sU((e=>{let i=t.length,r=i,n=new Array(i),o=()=>{0==--r&&e.complete()};t.forEach(((t,i)=>{let r=new rU(e),s=[];n[i]=s,r.next=t=>{s.push(t),n.every((e=>e.length))&&e.next(n.map((e=>e.shift())))},r.complete=o,r.subscribe(t)}))}),"zip",arguments)}function yU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>sU((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 SU=aU(class extends rU{constructor(e){super(e);let t=new rU(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=YV,t.subscribe(TU(...r))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},"withLatestFrom"),IU=aU(class extends rU{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"),AU=aU(class extends rU{constructor(e,t){super(e),this.buffer=[];let i=new rU(e);i.next=t=>{e.next(this.buffer),this.buffer=[]},i.complete=YV,i.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),RU=function(e,t,i,r){return new(i||(i=Promise))((function(n,o){function s(e){try{c(r.next(e))}catch(t){o(t)}}function a(e){try{c(r.throw(e))}catch(t){o(t)}}function c(e){e.done?n(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(s,a)}c((r=r.apply(e,t||[])).next())}))};function CU(e){let t=arguments,i=pU()(sU((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=YV,i.complete=YV,i.error=YV,i}function bU(e){return sU((t=>t.subscribe(e())),"defer",arguments)}var kU=e=>t=>{setTimeout((()=>e(t)))},DU=e=>kU((t=>{for(let i=0;!t.disposed&&i<e.length;i++)t.next(e[i]);t.complete()}));function wU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sU(DU(t),"of",arguments)}function NU(e){return sU(DU(e),"fromArray",arguments)}function OU(e){return sU((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}function MU(e,t){return sU((i=>{let r=0,n=setTimeout((()=>{if(i.removeDefer(o),i.next(r++),t){let e=setInterval((()=>i.next(r++)),t);i.defer((()=>{clearInterval(e)}))}else i.complete()}),e),o=()=>{clearTimeout(n)};i.defer(o)}),"timer",arguments)}function PU(e,t){return i=>{let r=e=>i.next(e);i.defer((()=>t(r))),e(r)}}function LU(e,t){return sU(PU(e,t),"fromEventPattern",arguments)}function xU(e,t){if("on"in e&&"off"in e)return sU(PU((i=>e.on(t,i)),(i=>e.off(t,i))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return sU(PU((i=>e.addListener(t,i)),(i=>e.removeListener(t,i))),"fromEvent",arguments);if("addEventListener"in e)return sU(PU((i=>e.addEventListener(t,i)),(i=>e.removeEventListener(t,i))),"fromEvent",arguments);throw"target is not a EventDispachter"}function VU(e){return sU((t=>{e.then(t.next.bind(t),t.error.bind(t))}),"fromPromise",arguments)}function UU(e,t){return sU(bU((()=>VU(fetch(e,t)))),"fromFetch",arguments)}function FU(e){return sU(kU((t=>{try{for(let i of e){if(t.disposed)return;t.next(i)}t.complete()}catch(zb){t.error(zb)}})),"fromIterable",arguments)}function BU(e){let t=i=>RU(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 sU((e=>{t(e)}),"fromReader",arguments)}function HU(e){return sU((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 WU(){return sU((e=>{let t=requestAnimationFrame((function i(r){e.disposed||(e.next(r),t=requestAnimationFrame(i))}));e.defer((()=>cancelAnimationFrame(t)))}),"fromAnimationFrame",arguments)}function GU(e,t){return sU((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 jU(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 sU((i=>{let n=r.concat((e=>(i.next(e),i.complete())));e.apply(t,n)}),"bindCallback",arguments)}function JU(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 sU((i=>{let n=r.concat(((e,t)=>e?i.error(e):(i.next(t),i.complete())));e.apply(t,n)}),"bindNodeCallback",arguments)}function KU(){return sU((()=>{}),"never",arguments)}function qU(e){return sU((t=>t.error(e)),"throwError",arguments)}function zU(){return sU((e=>e.complete()),"empty",arguments)}var YU=class extends rU{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)}},XU=aU(YU,"reduce"),QU=e=>aU(YU,"count")(((t,i)=>e(i)?t+1:t),0),ZU=()=>aU(YU,"max")(Math.max),$U=()=>aU(YU,"min")(Math.min),eF=()=>aU(YU,"sum")(((e,t)=>e+t),0),tF=aU(class extends rU{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"),iF=aU(class extends rU{next(e){}},"ignoreElements"),rF=aU(class extends rU{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&this.complete()}},"take"),nF=aU(class extends rU{constructor(e,t){super(e);let i=new rU(e);i.next=()=>e.complete(),i.complete=ZV,i.subscribe(t)}},"takeUntil"),oF=aU(class extends rU{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):this.complete()}},"takeWhile"),sF=e=>XU(((t,i)=>(t.push(i),t.length>e&&t.shift(),t)),[]),aF=aU(class extends rU{constructor(e,t){super(e),this.count=t}next(e){0==--this.count&&(this.next=super.next)}},"skip"),cF=aU(class extends rU{constructor(e,t){super(e),e.next=YV;let i=new rU(e);i.next=()=>{i.dispose(),e.resetNext()},i.complete=ZV,i.subscribe(t)}},"skipUntil"),lF=aU(class extends rU{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),dF={leading:!0,trailing:!1},uF=class extends rU{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)}},hF=class extends rU{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:dF;super(e),this.durationSelector=t,this.config=i,this._throttle=new uF(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=YV,this._throttle.complete(),super.complete()}},pF=aU(hF,"throttle"),mF={leading:!1,trailing:!0},_F=e=>aU(hF,"audit")(e,mF),fF=class extends rU{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},gF=class extends rU{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new fF(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()}},EF=aU(gF,"debounce"),TF=e=>aU(gF,"debounceTime")((t=>MU(e))),vF=aU(class extends rU{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"),yF=e=>t=>rF(1)(lF((t=>!e(t)))(t)),SF=aU(class extends rU{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"),IF=aU(class extends rU{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"),AF=aU(class extends rU{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"),RF=aU(class extends rU{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"),CF=aU(class extends rU{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"),bF=aU(class extends rU{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},"pairwise"),kF=class extends rU{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},DF=aU(kF,"map"),wF=e=>aU(kF,"mapTo")((t=>e)),NF=class extends rU{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()}},OF=class extends rU{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()}},MF=class extends NF{},PF=class extends OF{next(e){this.subInner(e,MF),this.next=e=>{this.currentSink.dispose(),this.subInner(e,MF)}}},LF=aU(PF,"switchMap");function xF(e){return(t,i)=>e((()=>t),i)}var VF=xF(aU(PF,"switchMapTo")),UF=class extends NF{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},FF=class extends OF{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(),UF),this.disposed&&0===this.sources.length&&this.currentSink.resetComplete()}tryComplete(){0===this.sources.length&&this.currentSink.resetComplete(),this.dispose()}},BF=aU(FF,"concatMap"),HF=xF(aU(FF,"concatMapTo")),WF=class extends NF{tryComplete(){this.context.inners.delete(this),super.dispose(),0===this.context.inners.size&&this.context.resetComplete()}},GF=class extends OF{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,WF),this.inners.add(this.currentSink)}tryComplete(){1===this.inners.size?this.inners.forEach((e=>e.resetComplete())):this.dispose()}},jF=aU(GF,"mergeMap"),JF=xF(aU(GF,"mergeMapTo")),KF=class extends NF{dispose(){this.context.resetNext(),super.dispose()}},qF=class extends OF{next(e){this.next=YV,this.subInner(e,KF)}},zF=aU(qF,"exhaustMap"),YF=xF(aU(qF,"exhaustMapTo")),XF=aU(class extends rU{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=CU(),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"),QF=aU(class extends rU{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"),ZF=aU(class extends rU{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"),$F=aU(class extends rU{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"),eB=aU(class extends rU{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),tB=()=>e=>new Promise(((t,i)=>{let r;new nU(e,(e=>r=e),i,(()=>t(r)))})),iB=()=>e=>{let t;return new ReadableStream({start(i){t=new nU(e,i.enqueue.bind(i),i.error.bind(i),i.close.bind(i))},cancel(){t.dispose()}})},rB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:YV,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:YV,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:YV;return r=>new nU(r,e,t,i)},nB=aU(class extends rU{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"),oB=aU(class extends rU{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout((()=>this.error(new uU(this.timeout))),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),sB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0;return t=>{if(t instanceof tU){let i=sU((r=>{let n=e,o=new rU(r);o.error=e=>{n-- >0?o.subscribe(t):r.error(e)},o.sourceId=i.id,o.subscribe(t)}),"retry",[e]);return i.source=t,dU.pipe(i),i}return i=>{let r=e,n=new rU(i);n.error=e=>{r-- >0?t(n):i.error(e)},t(n)}}},aB=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(aB||{}),cB=class e extends bV{constructor(e,t){super({mediaType:e,PlayerClass:t}),Sb(this,"isRemote",!1),Sb(this,"deviceId"),Sb(this,"groupId",""),Sb(this,"label",""),Sb(this,"sourceTrack"),Sb(this,"enableAutoSwitchWhenRecapturing",!0),Sb(this,"_isRecapturing",!1),Sb(this,"_lastRecaptureTime",0),Sb(this,"_onMuteTimeoutId",-1),Sb(this,"_encodeCheckTimeoutId",-1),Sb(this,"recaptureMode",0),Sb(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return"publishing"===this.state.toString()}get isPublished(){return"publish"===this.state}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){dx(e,e).add(Sk.MUTE,this.onTrackMuted).add(Sk.UNMUTE,this.onTrackUnmuted).add(Sk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Sk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ux(e)}setStateToReady(){}capture(e){return Ab(this,null,(function*(){var t;try{let i,r=Aw();dM.emit(hM.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.sourceTrack)||t.stop(),i=yield PV(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.sourceTrack=n,this.updateDeviceIdInUse(),this.listenDeviceChange()),dM.emit(hM.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Aw()-r}),i}catch(AM){throw dM.emit(hM.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:AM}),this.log.error("getUserMedia error observed ".concat(AM)),AM}}))}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return null==(t=this.room)?void 0:t.replaceTrack(this)}get hasFlag(){var e,t;let i=Dw((null==(e=this.room)?void 0:e.localPublishFlag)||0,(null==(t=this.room)?void 0:t.userId)||"");return 4===this.mediaType&&i.hasVideo||1===this.mediaType&&i.hasAudio||2===this.mediaType&&i.hasAuxiliary}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),Promise.all([t,new Promise(((t,i)=>Ab(this,null,(function*(){var r,n;this.hasFlag?t():oU(xU(e,"local-publish-flag-changed"),tF((()=>this.hasFlag)),nF(mU(xU(this,ex.INIT),xU(this,"ready"))),rB(t)),!(((null==(n=null==(r=this.room)?void 0:r.networkQuality)?void 0:n.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout((()=>{var e,t,r,n,o,s;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===Sk.AUDIO,t=this.stat.bytesSent>0;if(FP[t?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),!e){let e={H264:513704,H265:513705,VP8:513706}[(null==(n=null==(r=this.room)?void 0:r.videoCodec)?void 0:n.toUpperCase())||"H264"];e&&FP[t?"addSuccessEvent":"addFailedEvent"]({key:e})}t||(FP.addEnum({key:e?503701:513703,value:nM()}),hx.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(tM()||sM()),userId:this.userId}),this.log.warn(e?"encode failed":"".concat(null==(s=null==(o=this.room)?void 0:o.videoCodec)?void 0:s.toUpperCase()," encode failed")),this.emit("6",this),i(new Ub({message:"".concat(this.strMediaType," encode failed"),code:e?xb.AUDIO_ENCODE_FAILED:xb.VIDEO_ENCODE_FAILED})))}}),5e3))}))))])}unpublish(){this.room&&this.room.localTracks.delete(this),dM.emit(hM.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return Ab(this,null,(function*(){if(this.sourceTrack&&IL){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:i}=this.sourceTrack;(yield function(e){return Ab(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==Sk.AUDIO||t!==_D||(yield yV(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),_V().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.sourceTrack||this.kind===Sk.AUDIO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("麦克风"))return!0;let i="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(Sk.AUDIO_INPUT);return!!vV.has(i)}(this.sourceTrack)||this.kind===Sk.VIDEO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let i="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(Sk.VIDEO_INPUT);return!!vV.has(i)}(this.sourceTrack)||this._isRecapturing||e&&aO&&MO)}onTrackMuted(){if(super.onTrackMuted(),FV(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<yD)return void setTimeout((()=>this.onTrackMuted()),yD);this._onMuteTimeoutId=setTimeout((()=>Ab(this,null,(function*(){var e;if(null!=(e=this.sourceTrack)&&e.muted){if((RN||CN)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return Ab(this,null,(function*(){if(Ib(e.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&0===this.recaptureMode){if(Date.now()-this._lastRecaptureTime<yD)return void setTimeout((()=>this.onTrackEnded()),yD);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return Ab(this,null,(function*(){var t;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying"),null==(t=this.sourceTrack)||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 fV():yield gV()).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}),dM.emit(hM.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),dM.emit(hM.LOCAL_TRACK_RECAPTURE,{track:this,error:e})}))}))}getRecoverCaptureDeviceId(){return Ab(this,null,(function*(){let e=this instanceof _B;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(dB.get(t)||0)+1;if(dB.set(t,i),i>=3&&this.enableAutoSwitchWhenRecapturing){let r=e?(yield gV()).find((e=>!dB.has(e.deviceId))):(yield fV()).find((e=>!dB.has(e.deviceId)));r&&(this.log.warn("".concat(t," capture fail ").concat(i," times, change new ").concat(r.deviceId)),t=r.deviceId)}}return t}))}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),null==(e=this.manager)||e.removeInput(this)}close(){super.close(),this.stopCapture()}};yb([QL(ex.INIT,"ready",{ignoreError:!0,sync:!0})],cB.prototype,"setStateToReady",1),yb([jV()],cB.prototype,"capture",1),yb([QL("ready","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),dM.emit(hM.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(e){let t="error";if(e.cause instanceof Ub){let i=e.cause;i.message.includes("timeout")?t="timeout":i.code===xb.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),qV(521714,!1)],cB.prototype,"publish",1),yb([UV((e=>function(){return Ab(this,null,(function*(){let t="publish"===this.state?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)}))})),QL([],"ready",{sync:!0})],cB.prototype,"unpublish",1);var lB=cB,dB=new Map;dM.on(hM.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&dB.delete(e.track.deviceId)}));var uB=class e extends lB{constructor(e){super(1,RV),Sb(this,"mediaType",1),Sb(this,"volume",0),Sb(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),Sb(this,"playerMuted",!0),Sb(this,"pipeline"),Sb(this,"earMonitorGainNode",new Zx),Sb(this,"_output",new Zx),Sb(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),Sb(this,"mixedAudioReferenceMap",new Map),Sb(this,"isAudioContextLongSuspended",!1),this.manager=e,this.pipeline=new tV(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),dM.on(hM.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return cV.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}getInternalAudioLevelAfter3A(){if(this.pipeline.aec.node||this.pipeline.denoiser.node)return this.player.getInternalAudioLevelAfter3A()}setInputMediaStreamTrack(t){return Ab(this,null,(function*(){let i=this.trackSettings||{};FP.addEnum({key:501701,value:i.channelCount||0,useUV:!1}),FP.addEnum({key:501702,value:i.sampleRate||0,useUV:!1}),FP.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.source.channelCount=n||1,this.pipeline.replaceSource(t),yield Ib(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 Ab(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource){if(e!==_D)return;if(yield yV(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),dM.emit(hM.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(Xk){throw this.log.error("switch microphone failed ".concat(Xk)),this.deviceId&&this.recapture(this.deviceId),Xk}}}))}listenDeviceChange(){pV&&!pV.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&pV.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return Ab(this,null,(function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(aB[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){tH(this.userId,{eventId:2003,param1:6,streamType:1});let e=yield fV();e[0]?this.recapture(e[0].deviceId):t=!0}t&&pV.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){1===this.recaptureMode&&e.deviceId!==this.deviceId||(pV.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}update3A(e){return Ab(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:n}=e;return function*(){let e=t.sourceTrack||t.mediaTrack;if(!e)return;let o=e.getConstraints(),s=!1;!dw(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,o.echoCancellation=i,s=!0),!dw(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,o.noiseSuppression=r,s=!0),!dw(n)&&n!==t.profile.autoGainControl&&(t.profile.autoGainControl=n,o.autoGainControl=n,s=!0),s&&(wN||MO?yield e.applyConstraints(o).catch((e=>t._log.warn("update3A failed: ",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&&FP.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),RN&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Qx().createGain()),this._output.setNode(Qx().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!MO&&!RN)return this.update3A({echoCancellation:e})}addDenoiser(e){var t;NO<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(FP.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1))}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info("mixAudioReference() => ".concat(t));let i=nV(e),r=new Zx,n=Qx().createGain();n.gain.value=1;let o=new Zx;r.pipeTo(o).pipeTo(this.pipeline.mixNode),r.setNode(i),o.setNode(n),this.mixedAudioReferenceMap.set(t,[r,o])}unMixAudioReference(e){let[t,i]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info("unMixAudioReference() => ".concat(e)),t.deleteNode(),null==i||i.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[i,r]=this.mixedAudioReferenceMap.get(e)||[];null!=r&&r.node&&(r.node.gain.value=t/100,this.log.info("setAudioReferenceVolume() => ".concat(e," ").concat(r.node.gain.value)))}addAudioProcessor(e,t,i,r){this.pipeline.silentNode.setNode(i),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e),this.enableTrackAEC(!1)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e,t,i,r){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}close(){this.mixedAudioReferenceMap.forEach((e=>{let[t,i]=e;t.deleteNode(),i.deleteNode()})),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),pV.off("audioInputAdded",this.handleMicrophoneAdded,this),pV.off("audioInputRemoved",this.handleMicrophoneRemoved,this),dM.off(hM.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(t){return Ab(this,null,(function*(){try{yield Ib(e.prototype,this,"recapture").call(this,t)}catch(Xk){let r=(yield fV()).find((e=>e.deviceId!==t));if(!r)throw Xk;yield Ib(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))}handleAudioContextLongSuspended(e){let{isSuspended:t}=e;if(this.pipeline.isProcessEnabled)if(t){this.isAudioContextLongSuspended=!0,this.log.warn("context has suspended for ".concat(1.5," seconds, change to source audio").concat(PO?"":", non-Safari"));let e=this.sourceTrack||this.mediaTrack;e&&this.setOutputMediaStreamTrack(e)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}},hB=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,i=[],r=0;for(let o=e;o<=t;o++){let e=this.dataView.getInt8(o);switch(e){case 0:case 1:case 2:case 3:2===r&&(i.push(3),r=0),0==e?r++:r=0,i.push(e);break;default:r=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],r=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:r++,i.push(this.dataView.getInt8(o));break;case 3:2!==r&&i.push(this.dataView.getInt8(o)),r=0;break;default:i.push(this.dataView.getInt8(o)),r=0}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}get isSEI(){return 6===this.dataView.getUint8(4)}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let n=6;n<this.dataView.buffer.byteLength;n++){let i=this.dataView.getUint8(n);if(t++,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),r=new DataView(i);for(let n=0;n<i.byteLength;n++,t++)r.setInt8(n,this.dataView.getInt8(t));return r}},pB=class{constructor(){Sb(this,"_seiMessageList",[]),Sb(this,"_smallSeiMessageList",[]),Sb(this,"_seiPayloadType",243)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),r=t%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let s=0;s<i;s++)n.push(255);n.push(r);let o=new DataView(e);return n.push(...new Uint8Array(o.buffer)),n.push(128),new hB(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),o=new ArrayBuffer(n+e.data.byteLength),s=new DataView(o),a=new DataView(e.data),c=0;for(let e=0;e<r.length;e++)for(let t=0;t<r[e].dataView.byteLength;t++)s.setInt8(c++,r[e].dataView.getInt8(t));for(let i=0;i<e.data.byteLength;i++)s.setInt8(c++,a.getInt8(i));return e.data=o,r.length}return 0}},mB=class e extends lB{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,Fx),Sb(this,"profile",fb({},Tk)),Sb(this,"avoidCropping",!1),Sb(this,"_scaleResolutionDownBy"),Sb(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0}),Sb(this,"small"),Sb(this,"isNeedToSetBandwidth"),Sb(this,"muteImage"),Sb(this,"manager"),Sb(this,"_seiCodec",new pB),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(gb(fb({},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(IL&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return(null==(e=this._inputTrack)?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}setMute(t){return Ab(this,null,(function*(){var i,r,n;if(uw(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,Ib(e.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield null==(n=this.manager)?void 0:n.deleteWatermark("mute"),this.muteImage=void 0),Ib(e.prototype,this,"setMute").call(this,t)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:r=!0,customSource:n,retryWhenExactFailed:o=!0}=e;return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:o,customSource:n})}setProfile(e){let t=this.fallbackProfile(e);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(gb(fb({},this.profile),{width:1920,height:1080})))}applyProfile(){return Ab(this,null,(function*(){var e;if(!this.mediaTrack)return;let{width:t=0,height:i=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=t*i,n=this.settings,o=n.height!==this.profile.height||n.width!==this.profile.width||n.frameRate!==this.profile.frameRate;if(o&&(16===BO&&this.deviceId?yield this.recapture(this.deviceId):(yield null==(e=this.sourceTrack||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;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),i=e*t;return o&&i&&r&&i===r?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:Sk.VIDEO,videoType:Sk.BIG})}}))}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return IL&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:zw(this.settings,this.profile)}isAllowed2k4k(e){var t;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||1===(null==(t=this.room.scheduleResult.trtcAutoConf)?void 0:t["2k4k"])}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return Ab(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};if("user"===e||"environment"===e){t.facingMode=e;try{if((fO||RO)&&"environment"===e&&RL){let e=(yield gV(!0)).map((e=>{var t;return gb(fb({},e),{capabilities:null==(t=e.getCapabilities)?void 0:t.call(e)})})).filter((e=>{var t,i;return null==(i=null==(t=e.capabilities)?void 0:t.facingMode)?void 0:i.includes("environment")})),i=e[0];e.forEach((e=>{var t,r,n,o;let{capabilities:s}=e;(null!=(t=s.width)&&t.max&&null!=(r=s.height)&&r.max?s.width.max*s.height.max:0)>(null!=(n=i.capabilities.width)&&n.max&&null!=(o=i.capabilities.height)&&o.max?i.capabilities.width.max*i.capabilities.height.max:0)&&(i=e)})),null!=i&&i.capabilities&&(delete t.facingMode,this._log.info("switch to max res camera",i),t.deviceId=i.deviceId)}}catch(AM){this._log.warn("get max res camera failed",AM)}}else t.deviceId=e;this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),dM.emit(hM.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(Xk){throw this.log.error("switch camera failed ".concat(Xk)),this.deviceId&&this.recapture(this.deviceId),Xk}}))}updateSmallConfig(e){var t,i;this._log.info("update small stream config: ".concat(JSON.stringify(e)));let r=!this.small;this.small=this.fallbackProfile(e,!0),null==(t=this.manager)||t.update(),r&&(null==(i=this.room)||i.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=e.width>e.height,r=fb({},e);return e.width*e.height<=19200&&CN&&kO&&(this.log.warn("".concat(t?"small ":"","resolution is ").concat(e.width,"*").concat(e.height,", fallback to 240*180 for android chrome")),r.width=i?240:180,r.height=i?180:240,r.bitrate=Math.max(e.bitrate,150)),e.width*e.height>921600&&GO&&(r.width=i?1280:720,r.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),UO(VO,"14.3")&&FO(VO,"14.0",!0)&&this.on("7",(()=>{let e=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=e?640:480,this.profile.height=e?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>230400&&(this.profile.width=e?640:360,this.profile.height=e?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))})),!t&&this.avoidCropping&&(kO||wN)&&!QO()&&e.width*e.height<=230400&&e.width/e.height==16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn("capture 720p, scale: ".concat(this._scaleResolutionDownBy))),r}stopSmall(){var e,t;this.small&&(delete this.small,null==(e=this.manager)||e.update(),null==(t=this.room)||t.enableSmall(!1))}listenDeviceChange(){pV&&!pV.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&pV.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return Ab(this,null,(function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(aB[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){tH(this.userId,{eventId:2003,param1:7,streamType:2});let e=yield gV();e[0]?this.recapture(e[0].deviceId):t=!0}t&&pV.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return Ab(this,null,(function*(){1===this.recaptureMode&&e.deviceId!==this.deviceId||(pV.off("videoInputAdded",this.handleCameraAdded,this),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 dw(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){pV.off("videoInputAdded",this.handleCameraAdded,this),pV.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return Ab(this,null,(function*(){try{yield Ib(e.prototype,this,"recapture").call(this,t)}catch(Xk){let r=(yield gV()).find((e=>e.deviceId!==t));if(!r)throw Xk;yield Ib(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))}setRotation(e){this.manager&&(this.isScreen||dw(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};yb([xV((function(e){this.setContentHint(e.contentHint||"motion")}))],mB.prototype,"capture",1);var _B=mB,fB={};Tb(fB,{REPORT_TYPE:()=>Zw,buildSSOPackage:()=>$w,bytes2ms:()=>$D,calculateScaleResolutionDownNumber:()=>zw,convertObjectNumberToInt:()=>Gw,copyProperties:()=>ZD,deepClone:()=>Mw,deepCloneBasic:()=>Qw,deepMerge:()=>Ow,delay:()=>jw,fibonacci:()=>sw,formatedTime:()=>xw,getConstructorName:()=>vw,getContainerFromElement:()=>Lw,getEnv:()=>jD,getInternalVersion:()=>Cw,getLoggerUrl:()=>KD,getMediaStreamTrackInfo:()=>qw,getMuteStateFromFlag:()=>Dw,getNetworkType:()=>zD,getNumNetworkType:()=>QD,getReconnectionTimeout:()=>aw,getStringByteLength:()=>Fw,getTurnServer:()=>ww,getUint32Version:()=>Ww,getValueType:()=>cw,getViewListFromView:()=>Pw,glog:()=>rw,ipv4ToUint32:()=>Nw,isArray:()=>_w,isAudioWorkletSupported:()=>yw,isBoolean:()=>pw,isConstructor:()=>Tw,isEmpty:()=>kw,isFunction:()=>lw,isLangChinese:()=>nw,isMediaStreamTrack:()=>fw,isNumber:()=>hw,isObject:()=>mw,isOverseaSdkAppId:()=>JD,isPlainObject:()=>ow,isPortrait:()=>Bw,isPromise:()=>Ew,isRemoteTrack:()=>gw,isRotate90Or270:()=>Yw,isSetSinkIdSupported:()=>Sw,isString:()=>uw,isUndefined:()=>dw,loadImage:()=>Hw,loadVideo:()=>Xw,ms2bytes:()=>tw,ms2samples:()=>iw,normalizeUrl:()=>Kw,performanceNow:()=>Aw,promiseAny:()=>Iw,samples2ms:()=>ew,setNetworkType:()=>XD,stringify:()=>Vw,stringifyIncludeValue:()=>Uw,throttlePromise:()=>Jw});var gB=[-1,-1,1,-1,-1,1,1,1],EB=[0,0,1,0,0,1,1,1],TB=class extends ex{constructor(e,t){if(super(),this.context=e,Sb(this,"name"),Sb(this,"input"),Sb(this,"output"),Sb(this,"texture"),Sb(this,"ctx2d",null),Sb(this,"fbo"),Sb(this,"width",0),Sb(this,"height",0),Sb(this,"x",0),Sb(this,"y",0),Sb(this,"program"),Sb(this,"vertexShader"),Sb(this,"fragmentShader"),Sb(this,"totalFrames",0),Sb(this,"dropFrames",0),Sb(this,"matchInputSize",!0),Sb(this,"texCoordBuffer"),Sb(this,"positionBuffer"),Sb(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),Sb(this,"cost",0),Sb(this,"_canvas",null),Sb(this,"_image"),Sb(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 PB)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==BO?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(EB),this.positionBuffer=this.createBuffer(gB),!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(AM){this.context.destroy(new Ub({code:xb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(AM.message||AM)}))}}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 MB&&this.render(e)||this.context instanceof PB&&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 MB){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,o,s,a,c){let l=!(dw(o)||dw(s)||dw(a)||dw(c));return!(!this.ctx2d||!e)&&(e instanceof ImageData?l?this.ctx2d.putImageData(e,t,i,o,s,a,c):this.ctx2d.putImageData(e,t,i):l?this.ctx2d.drawImage(e,o,s,a,c,t,i,r,n):this.ctx2d.drawImage(e,t,i,r,n),this.emit("render",e),"undefined"!=typeof VideoFrame&&e instanceof VideoFrame&&e.close(),!0)}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var e;let{totalFrames:t,x:i,y:r,width:n,height:o,name:s,cost:a}=this,c=Date.now(),l=(t-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:t,x:i,y:r,width:n,height:o,timestamp:c,fps:l,name:s,cost:a},fb({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}};yb([QL(ex.INIT,"connected",{sync:!0})],TB.prototype,"connect",1),yb([QL("connected",ex.INIT,{ignoreError:!0,sync:!0})],TB.prototype,"disconnect",1),yb([QL([],"closed",{sync:!0})],TB.prototype,"close",1);var vB=oU(OU(250),DF((()=>performance.now())),pU()),yB=[0,1,1,1,0,0,1,0],SB=class extends TB{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),Sb(this,"_intervalId",0),Sb(this,"_sequence",0),Sb(this,"checkGLError",!1),Sb(this,"checkVisibilityChange"),e instanceof PB?this.ctx2d=e.ctx||null:e.available&&null!=t&&t.mirrorUpAndDown&&this.setTexBuffer(yB)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),sx.clearTask(this._intervalId),this._intervalId=sx.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(sx.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof MB){let e=this.context.ctx.getError();e&&this.context.destroy(new Ub({code:xb.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(),this.emit("render",this.context._canvas),!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;this._intervalId&&(sx.clearTask(this._intervalId),this._intervalId=0,1===e&&(this.log.info("".concat(this.name," use requestVideoFrameCallback")),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),sx.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),sx.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},IB=class extends SB{constructor(e,t){super(e,t),Sb(this,"_videoTrack"),Sb(this,"_muteOb"),Sb(this,"_closedOb",xU(this,"closed")),Sb(this,"_subscription"),Sb(this,"_canvasContainer"),Number(LO)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=xU(this._videoTrack,"mute"),oU(xU(this._videoTrack,"ended"),nF(this._closedOb),rB((()=>{this.context.destroy(new Ub({code:xb.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){var e;this._subscription=oU(this._muteOb,nF(this._closedOb),VF((e=5e3,t=>{let i=performance.now();oU(vB,lF((t=>t-i<e)),rF(1))(t)})),tF((()=>{var e;return!(null==(e=this._videoTrack)||!e.muted||document.hidden)})),rB((()=>{this.context.destroy(new Ub({code:xb.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()}},AB=class extends IB{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},RB=class extends IB{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))}},CB=class extends TB{constructor(e,t){super(e,fb({name:"imageSource"},t)),Sb(this,"_lastImage"),Sb(this,"_totalFrames",0),Sb(this,"_autoResize",!1),Sb(this,"_canvasRendered"),Sb(this,"videoCallbackId",0),Sb(this,"waitingFirstFrame",!0),Sb(this,"shouldUpdate",!0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===BO&&(this._canvasRendered=CU(),oU(this._canvasRendered,yU(this._image),LF((e=>e instanceof HTMLCanvasElement?xU(e,"rendered"):zU())),nF(xU(this,"closed")),rB((()=>{this.update()}))))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),UL()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback(((e,t)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=t.presentedFrames,this.update(1))})))}_render(e,t){var i;let{width:r,height:n}=this,{image:o}=this;if(o instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),({videoWidth:r,videoHeight:n}=o),!r||!n)return!1;o.width=r,o.height=n}else if(o instanceof HTMLImageElement||o instanceof ImageData||o instanceof ImageBitmap){if(({width:r,height:n}=o),o!==this._lastImage)this._lastImage=o;else if(r===this.width&&n===this.height)return!0}else o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas?(({width:r,height:n}=o),this._lastImage=o):"undefined"!=typeof VideoFrame&&o instanceof VideoFrame&&(({displayWidth:r,displayHeight:n}=o),null==(i=this._lastImage)||i.close(),this._lastImage=o);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,o)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,o)}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)}},bB=class extends CB{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",oU(xU(this._player,ax.PLAYER_STATE_CHANGED),nF(xU(this,"closed")),tF((e=>{let{state:t}=e;return"PLAYING"===t})),rB((()=>{this.tryVideoFrameCallback()})))}get image(){return this._player.element}},kB=class extends bB{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,t,i){super(e,new Fx({id:i.name,track:t,muted:!0,container:null,objectFit:"contain",log:i.logger}),i),this.name="videoTrackSource",this._player.play()}replaceTrack(e){this.waitingFirstFrame=!0,this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},DB=class extends TB{constructor(e,t,i){super(e,gb(fb({name:"textSource"},i),{create2d:!0})),Sb(this,"hasChange",!0),Sb(this,"content",""),this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return(null==(e=this.ctx2d)?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return(null==(e=this.ctx2d)?void 0:e.fillStyle)||""}render2d(e){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:i,font:r}=this;super.resize(e,t),this.color=i,this.font=r}drawMultilineText(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1.2;if(!this.ctx2d)return;let r=this.ctx2d.measureText(this.content);t+=r.fontBoundingBoxAscent||r.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),o=(n?parseInt(n[1],10):16)*i,s=this.content.split("\n");for(let a=0;a<s.length;a++)this.ctx2d.fillText(s[a],e,t+a*o)}},wB=class extends ex{constructor(e){super(),Sb(this,"frameRate"),Sb(this,"_canvas"),Sb(this,"log"),Sb(this,"hasAlpha",!1),Sb(this,"name"),Sb(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 kB(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new IB(this,e)}createVideoImageSource(e,t){return new CB(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new bB(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new DB(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};Sb(wB,"_ids",0);var NB={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},OB=class extends wB{constructor(){super(...arguments),Sb(this,"defaultProgam"),Sb(this,"defaultVShader"),Sb(this,"defaultFShader"),Sb(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(wB._ids++)),this.ctx=this._canvas.getContext("webgl2",NB),!this.ctx)throw new Ub({code:xb.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 Ub({code:xb.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}))}destroy(e){let t="";return e&&(t=e.message,this.error=e,FP.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}};Sb(OB,"UNAVAILABLE","unavailable"),yb([QL(ex.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),FP.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),FP.addSuccessEvent({key:512700})}})],OB.prototype,"create",1),yb([QL("created",ex.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(OB.UNAVAILABLE,e),this.removeAllListeners()}})],OB.prototype,"destroy",1);var MB=OB,PB=class extends wB{constructor(){super(...arguments),Sb(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(wB._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new Ub({code:xb.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",(()=>{this.log.error("2d context lost")})),this._canvas.addEventListener("contextrestored",(()=>{this.log.warn("2d context restored")}))}destroy(e){let t="";e&&(t=e.message,this.error=e,FP.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(),FP.addSuccessEvent({key:512703})}};function LB(e,t,i,r,n){arguments.length>5&&void 0!==arguments[5]&&arguments[5]&&([i,r]=[r,i]);let o={sWidth:e,sHeight:t,dWidth:i,dHeight:r,sx:0,sy:0,dx:0,dy:0};if(0===e||0===t)return o;switch(n){case void 0:case"fill":break;case"contain":{let n=Math.min(i/e,r/t);o.dWidth=e*n,o.dHeight=t*n,o.dx=(i-o.dWidth)/2,o.dy=(r-o.dHeight)/2;break}case"cover":{let n=Math.max(i/e,r/t),s=i/n,a=r/n;o.sx=(e-s)/2,o.sy=(t-a)/2,o.sWidth=s,o.sHeight=a;break}}return o}yb([QL(ex.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),FP.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),FP.addSuccessEvent({key:512701})}})],PB.prototype,"create",1),yb([QL("created",ex.INIT,{ignoreError:!0,sync:!0})],PB.prototype,"destroy",1);var xB=class{constructor(e,t){this.node=e,this.layout=t,Sb(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},VB=class extends TB{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),Sb(this,"inputs",[]),Sb(this,"backgroundColor","black")}addInput(e,t){let i=0,r=this.inputs.length;for(;i<r;){let e=Math.floor((i+r)/2);if(this.inputs[e].layout.zIndex<t.zIndex)i=e+1;else{if(!(this.inputs[e].layout.zIndex>t.zIndex))throw new Error("input already exists at zIndex ".concat(t.zIndex));r=e}}let n=new xB(e,t);this.inputs.splice(i,0,n)}changeInputLayout(e,t){let i=this.inputs.findIndex((t=>t.node===e));if(i<0)return;let{x:r,y:n,width:o,height:s,zIndex:a,fillMode:c,rotation:l,hidden:d}=t;if(!dw(a)&&this.inputs.some((t=>t.layout.zIndex===a&&t.node!==e)))throw new Error("input already exists at zIndex ".concat(t.zIndex));let u=this.inputs[i];dw(r)||(u.layout.x=r),dw(n)||(u.layout.y=n),dw(o)||(u.layout.width=o),dw(s)||(u.layout.height=s),dw(l)||(u.layout.rotation=l),dw(d)||(u.layout.hidden=d),c&&(u.layout.fillMode=c),!dw(a)&&a!==u.layout.zIndex&&(u.layout.zIndex=a,this.inputs.sort(((e,t)=>e.layout.zIndex-t.layout.zIndex)))}hasInput(e){return this.inputs.some((t=>t.node===e))}hasNoInput(){return 0===this.inputs.length}resize(e,t){if(!this.matchInputSize)return void super.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 MB&&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.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter((t=>t.node!==e)),0===this.inputs.length&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce(((t,i)=>i.node.requestFrame(e)||t),!1)&&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.forEach((t=>t.node.requestFrame(e))),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];if(t.hidden)continue;let i=LB(t.node.width,t.node.height,t.width,t.height,t.fillMode,Yw(t.rotation));this.draw2d(t.node.image,t.x+i.dx,t.y+i.dy,i.dWidth,i.dHeight,i.sx,i.sy,i.sWidth,i.sHeight)}return!0}return!1}debugLayout(e,t,i,r){let n=arguments.length>4&&void 0!==arguments[4]&&arguments[4];this.ctx2d&&(n&&([i,r]=[r,i]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,i,r),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:i,width:r,height:n,name:o}=this,s=Date.now(),a=(e-this.lastInfo.totalFrames)/((s-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:i,width:r,height:n,timestamp:s,fps:a,name:o},fb({parent:this.inputs.filter((e=>e)).map((e=>e.node.getInfo()))},this.lastInfo)}removeAllInputs(){this.inputs.forEach((e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof MB)try{null==(t=this.context.ctx)||t.deleteBuffer(e.positionBuffer)}catch(AM){}}))}close(){super.close(),this.removeAllInputs()}},UB=[1,0,0,0,1,1,0,1],FB=class extends TB{constructor(e,t,i,r){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t}),Sb(this,"mirror",!1),Sb(this,"rotation",0),i&&(this.mirror=i),r&&(this.rotation=r),e instanceof MB)try{this.setTexBuffer(UB)}catch(Yb){e.destroy(new Ub({code:xb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(Yb.message||Yb)}))}}draw2d(e,t,i,r,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),90===this.rotation?(this.ctx2d.translate(r,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/r,r/n)):180===this.rotation?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):270===this.rotation&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/r,r/n));let o=super.draw2d(e,t,i,r,n);return this.ctx2d.restore(),o}return!1}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}resize(e,t){Yw(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}},BB=class extends lB{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,Fx),Sb(this,"inputLocalVideoTracks",new Map),Sb(this,"inputLocalScreenTracks",new Map),Sb(this,"cameraNodeMap",new Map),Sb(this,"screenNodeMap",new Map),Sb(this,"textNodeMap",new Map),Sb(this,"imageNodeMap",new Map),Sb(this,"videoNodeMap",new Map),Sb(this,"endedIds",new Set),Sb(this,"videoContext"),Sb(this,"mixNode"),Sb(this,"destination"),Sb(this,"manager"),Sb(this,"stat"),Sb(this,"_checkId",0),Sb(this,"autoSetFps",!0),this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on("render",(e=>{this.emit("render",e)})),this.mixNode=new VB(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=sx.run("interval",(()=>{this.destination&&this.log.debug(this.destination.getInfo())}),{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new PB({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout((()=>{var e;return null==(e=this.destination)?void 0:e.start(this.videoContext.frameRate)}),500)}setFpsAuto(){var e;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let t=null,i=0,r=!0;for(let[n,o]of this.inputLocalVideoTracks)if(o.profile.frameRate>i){if(this.endedIds.has(n)){let e=this.cameraNodeMap.get(n);e&&e.image.cancelVideoFrameCallback(e.videoCallbackId);continue}i=o.profile.frameRate,t=n}for(let[n,o]of this.inputLocalScreenTracks)if(o.profile.frameRate>i){if(this.endedIds.has(n)){let e=this.screenNodeMap.get(n);e&&e.image.cancelVideoFrameCallback(e.videoCallbackId);continue}i=o.profile.frameRate,t=n,r=!1}if(null!==t){let e=r?this.cameraNodeMap.get(t):this.screenNodeMap.get(t);e&&(e.shouldUpdate=!0,e.tryVideoFrameCallback()),this.log.info("set mix fps: ",i)}else null==(e=this.destination)||e.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var i;null==(i=this.mixNode)||i.resize(e,t)}startMix(){return Ab(this,null,(function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),PO&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),null==(e=this.manager)||e.changeInput(this)}))}addCameraSource(e,t,i){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error("There is already a cameraSource with the same ID: ".concat(e));let r,{mediaTrack:n}=t;if(!n)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,dx(this,pV).add("videoInputRemoved",(i=>{i.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())})),t.on("output-media-track-changed",(()=>{this.endedIds.delete(e),this.updateCameraSource(e,i,t.mediaTrack)})),r=16===BO&&n instanceof CanvasCaptureMediaStreamTrack?this.videoContext.createVideoImageSource(n.canvas,{name:"cameraCanvasSource",logger:this.log}):this.videoContext.createVideoTrackSource(n,"cameraNodeSource"),r.resize(t.settings.width,t.settings.height),r.shouldUpdate=!1,this._connectMix(r,i,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,r),this.setFpsAuto()}addScreenSource(e,t,i){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error("There is already a screenSource with the same ID: ".concat(e));let{mediaTrack:r}=t;if(!r)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(r,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,i),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:i="",font:r,color:n,layout:o}=e;if(this.textNodeMap.has(t))throw new Error("There is already a textSource with the same ID: ".concat(t));let s=this.videoContext.createTextSource({content:i,font:r,color:n});s.resize(o.width,o.height),this._connectMix(s,o),this.textNodeMap.set(t,s)}addImageSource(e,t,i){if(this.imageNodeMap.has(e))throw new Error("There is already a imageSource with the same ID: ".concat(e));let r=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});r.resize(t.width,t.height),this._connectMix(r,i),this.imageNodeMap.set(e,r)}addVideoSource(e,t,i){if(this.videoNodeMap.has(e))throw new Error("There is already a videoSource with the same ID: ".concat(e));let r=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});r.resize(t.videoWidth,t.videoHeight),r.shouldUpdate=!1,this._connectMix(r,i),this.videoNodeMap.set(e,r)}updateCameraSource(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=arguments.length>3?arguments[3]:void 0,n=this.cameraNodeMap.get(e);if(n){if(i){if(16===BO&&i instanceof CanvasCaptureMediaStreamTrack)if(n instanceof kB){let t=n.output;n.close(),n=this.videoContext.createVideoImageSource(i.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(t),this.cameraNodeMap.set(e,n)}else n.image=i.canvas;else if(n instanceof kB)n.replaceTrack(i);else{let t=n.output;n.close(),n=this.videoContext.createVideoTrackSource(i,"cameraNodeSource"),n.connect(t),this.cameraNodeMap.set(e,n)}let{width:t,height:r}=i.getSettings();t&&r&&n.resize(t,r)}r&&n.resize(r.width,r.height),(r||i)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let i=this.screenNodeMap.get(e);i&&this._changeMixLayout(i,t)}updateTextSource(e){let{id:t,content:i,font:r,color:n,layout:o}=e,s=this.textNodeMap.get(t);s&&(dw(i)||(s.content=i),dw(r)||(s.font=r),dw(n)||(s.color=n),s.resize(o.width,o.height),this._changeMixLayout(s,o))}updateImageSource(e,t,i){let r=this.imageNodeMap.get(e);r&&(i&&(r.image=i,r.resize(i.width,i.height)),this._changeMixLayout(r,t))}updateVideoSource(e,t,i){let r=this.videoNodeMap.get(e);if(r){if(i){let e=r.image;e instanceof HTMLVideoElement&&this.stopVideoElement(e),r.image=i,r.resize(i.videoWidth,i.videoHeight)}this._changeMixLayout(r,t)}}_connectMix(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"contain";if(!this.mixNode)return;let{mirror:r,rotation:n}=t;e.disconnect();let o=new FB(this.videoContext,this.log,r,n);o=e.connect(o),t.fillMode||(t.fillMode=i),o.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:i,rotation:r}=t,n=e.output||e;n instanceof FB&&(dw(i)||(n.mirror=i),dw(r)||(n.rotation=r),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let i=this.cameraNodeMap.get(e);i&&(i.output instanceof FB&&i.output.close(),i.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let i=this.screenNodeMap.get(e);i&&(i.output instanceof FB&&i.output.close(),i.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof FB&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof FB&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof FB&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(){arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),sx.clearTask(this._checkId),null==(e=this.videoContext)||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),ux(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}},HB=fM();if("undefined"!=typeof navigator&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:HB,exposeOrigin:!0,permittedOrigins:["*"]})}catch(EJ){}var WB=function(e){return Ab(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:MO?{max:e.width}:{ideal:e.width,max:e.width},height:MO?{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);_M.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(DO&&NO<74||MO||wN)&&_M.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(bM){_M.warn("screen applyConstraints failed: ".concat(bM))}e.captureElement&&(yield function(e,t){return Ab(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&lw(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==HB)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){_M.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 dw(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);_M.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},GB=class extends _B{constructor(e){super(e,2),Sb(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),Sb(this,"objectFit","contain"),Sb(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}get isShareCurrentTab(){var e,t;try{return HB===(null==(t=null==(e=this.mediaTrack)?void 0:e.getCaptureHandle())?void 0:t.handle)}catch(AM){return}}capture(e){return Ab(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:r,echoCancellation:n,noiseSuppression:o,audioTrack:s,videoTrack:a,captureElement:c,preferDisplaySurface:l}=e;return function*(){try{let e;return a||s?(e=new MediaStream,a&&e.addTrack(a),s&&e.addTrack(s)):(e=yield WB({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:r,echoCancellation:n,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),t.sourceTrack=e.getVideoTracks()[0]),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof Ub?e:new Ub({code:xb.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return Ab(this,null,(function*(){throw new Error("Method not implemented.")}))}};yb([xV((function(e){this.setContentHint(e.contentHint||"detail")}))],GB.prototype,"capture",1);var jB,JB=class extends uB{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}addAudioProcessor(e,t,i,r){this.pipeline.silentNode.setNode(i),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(r),this.enableTrackAEC(!1)}removeAudioProcessor(e,t,i,r){this.pipeline.aec.node===r&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};function KB(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,r=arguments.length>3?arguments[3]:void 0;return Ab(this,null,(function*(){let n=Qx();jB||(jB=Bx(n,URL.createObjectURL(new Blob(['registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});'],{type:"application/javascript"})))),yield jB;let o=n.sampleRate,s=new AudioWorkletNode(n,"dumper",{numberOfInputs:e.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:o,targetSampleRate:t}});return s.channelCountMode="explicit",s.channelCount=i,r&&s.port.postMessage({port:r},[r]),e.forEach(((e,t)=>e.connect(s,0,t))),new ReadableStream({start(e){s.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach((e=>e.disconnect(s))),s.port.close()}})}))}var qB=class extends iV{constructor(e){super(),this.room=e,Sb(this,"_localAudioTrack"),Sb(this,"_localScreenAudioTrack"),Sb(this,"log",_M.createLogger({id:"am"})),Sb(this,"denoiser"),Sb(this,"voiceChanger"),Sb(this,"mixChangedDebounce"),Sb(this,"audioProcessor"),Sb(this,"encodePipeline",[]),Sb(this,"decodePipeline",[]),Sb(this,"getPCMAbortCtrlMap",new Map),Sb(this,"audioFrameEventConfigMap",new Map),Sb(this,"audioReferenceMap",new Map),Sb(this,"isLocalAudioNeedAudioProcess",!1),Sb(this,"isScreenAudioNeedAudioProcess",!1),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.installEvent()}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return null==(e=this._localScreenAudioTrack)?void 0:e.pipeline}dump(e){var t,i;if(!this._localAudioTrack)return;let r=[],n=[];null!=(t=this._localAudioPipline)&&t.source.node&&(r.push(this._localAudioPipline.source.node),n.push("mic")),null!=(i=this._localAudioPipline)&&i.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),n.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),n.push("mix")),this.log.info("dump audio track ".concat(n,", duration: ").concat(e));let o=new AbortController,s=[],a=setTimeout((()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")}),1e3*e),c=()=>{for(let e=0;e<n.length;e++){let t=URL.createObjectURL(new Blob(s[e])),i=document.createElement("a");i.href=t,i.download="".concat(n[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(a),o.abort("download")},l=KB(r).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>s[t]=s[t]?s[t].concat(e[0]):[e[0]]))}}),o).catch((e=>c))));return{then:l.then.bind(l),download:c}}getPCM(e,t){var i,r,n;if("undefined"==typeof WritableStream)return void this.log.warn("getPCM failed: browser not support WritableStream");let{enable:o,sampleRate:s=48e3,channelCount:a=1,port:c}=(""===t?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!o)return;this.log.info("getPCM ".concat(t||"local"));let l,d,u=Math.floor(.04*s),h=new Float32Array(u),p=new Float32Array(u),m=0,_=new AbortController,f=""===t?null==(i=this._localAudioTrack)?void 0:i.mediaTrack:null==(n=null==(r=this.room)?void 0:r.remotePublishedUserMap.get(t))?void 0:n.remoteAudioTrack.mediaTrack;if(f)return KB([Qx().createMediaStreamSource(new MediaStream([f]))],s,a,c).then((i=>i.pipeTo(new WritableStream({write(i){i[0][0]&&(m+i[0][0].length>u?(h.set(i[0][0].subarray(0,u-m),m),l=i[0][0].subarray(u-m),i[0][1]&&(p.set(i[0][1].subarray(0,u-m),m),d=i[0][1].subarray(u-m)),m+=u-m):(l&&(h.set(l,m),m+=l.length,l=void 0),d&&(p.set(d,m),d=void 0),h.set(i[0][0],m),i[0][1]&&p.set(i[0][1],m),m+=i[0][0].length),m>=u&&(m=0,e({userId:t,sampleRate:s,channelCount:a,data:1===a?h:[h,p]}),h=new Float32Array(u),p=new Float32Array(u)))}}),_).catch((e=>this.log.warn("stop getPCM reason:".concat(e)))))),_;this.log.info("getPCM failed: ".concat(t||"local"," has no audio track"))}get hasScreenAudioTrack(){return!dw(this._localScreenAudioTrack)}get hasAudioTrack(){return!dw(this._localAudioTrack)}changeInput(e){return e instanceof JB?(this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach(((t,i)=>{e.mixAudioReference(t,i)}))),e.pipeline.connect(),this.mixOnChange()):e instanceof uB?(this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach(((t,i)=>{e.mixAudioReference(t,i)}))),e.pipeline.connect(),this.mixOnChange()):e instanceof QB?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}mixAudioReference(e,t){var i;null==(i=this._localAudioTrack)||i.mixAudioReference(e,t)}unMixAudioReference(e){var t;null==(t=this._localAudioTrack)||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var i;null==(i=this._localAudioTrack)||i.setAudioReferenceVolume(e,t)}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 JB?delete this._localScreenAudioTrack:e instanceof uB&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}addAudioProcessor(e,t,i,r){var n;this.audioProcessor=[e,t,i,r],this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&(this._localAudioTrack.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach(((e,t)=>{var i;null==(i=this._localAudioTrack)||i.mixAudioReference(e,t)}))),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&(null==(n=this._localScreenAudioTrack)||n.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach(((e,t)=>{var i;null==(i=this._localScreenAudioTrack)||i.mixAudioReference(e,t)})))}removeDenoiser(e){var t;return delete this.denoiser,null==(t=this._localAudioTrack)?void 0: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()}removeAudioProcessor(e,t,i,r){var n;delete this.audioProcessor,null==(n=this._localAudioTrack)||n.removeAudioProcessor(e,t,i,r)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach((e=>null==e?void 0:e.abort("destroy"))),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}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}handleLocalTrackStarted(e){let{room:t,userId:i}=e;var r;if(t!==this.room||this.getPCMAbortCtrlMap.get(i))return;let n=this.getPCM((e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)}),"");this.getPCMAbortCtrlMap.set(i,n),this.getPCMAbortCtrlMap.get(i)&&(null==(r=this._localAudioTrack)||r.on("input-media-track-changed",(()=>{let e=this.getPCMAbortCtrlMap.get(i);e&&(e.abort("inputMediaTrackChanged"),e=this.getPCM((e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)}),""),this.getPCMAbortCtrlMap.set(i,e))})))}handleLocalTrackStopped(e){let{room:t,userId:i}=e;if(t!==this.room)return;let r=this.getPCMAbortCtrlMap.get(i);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(i))}handleRemoteTrackStarted(e){let{room:t,userId:i}=e;if(t===this.room&&!this.getPCMAbortCtrlMap.get(i)){let e=this.room.audioManager.getPCM((e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)}),i);this.getPCMAbortCtrlMap.set(i,e)}}handleRemoteTrackStopped(e){let{room:t,userId:i}=e;if(t!==this.room)return;let r=this.getPCMAbortCtrlMap.get(i);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(i))}installEvent(){dM.on("113",this.handleLocalTrackStarted,this),dM.on("114",this.handleLocalTrackStopped,this),dM.on("115",this.handleRemoteTrackStarted,this),dM.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){dM.off("113",this.handleLocalTrackStarted),dM.off("114",this.handleLocalTrackStopped),dM.off("115",this.handleRemoteTrackStarted),dM.off("116",this.handleRemoteTrackStopped)}updateAudioReference(e){let{type:t,audioReference:i,refId:r,volume:n}=e;if("add"===t){if(this.audioReferenceMap.get(r)||!i||(this.audioReferenceMap.set(r,i),!this.audioProcessor))return;this.mixAudioReference(i,r)}else if("remove"===t)this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if("updateVolume"===t){if(!this.audioProcessor||dw(n))return;this.setAudioReferenceVolume(r,n)}}};function zB(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return UV(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];return new Promise(((n,s)=>{let a=setTimeout((()=>{let i=new Ub({code:xb.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});_M.warn(i),2===t?s(i):1===t&&n()}),1e3*e);i.apply(this,o).then(n,s).finally((()=>{clearTimeout(a)}))}))}))}var YB=class e extends bV{constructor(t,i,r){super({userId:i.userId,sdkAppId:t.sdkAppId,mediaType:r,room:t}),this.room=t,this.user=i,Sb(this,"tinyId"),Sb(this,"isRemote",!0),Sb(this,"jitterBufferDelay",0),Sb(this,"availableState"),Sb(this,"remotePublishState"),Sb(this,"_triggerCheckDecodeSubject",CU(xU(this,e.STATE_SUBSCRIBE))),this.tinyId=i.tinyId,this.availableState=new ex("".concat(i.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new ex("".concat(i.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),oU(mU(xU(this,ex.STATECHANGED),xU(this.remotePublishState,ex.STATECHANGED)),DF((()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing))),rB((e=>{this.availableState.state!==(e?ex.ON:ex.OFF)&&(this.availableState.state=e?ex.ON:ex.OFF),this.updatePlayingState(e)})));let n=oU(xU(this.player,ax.ERROR),tF((e=>e.code===MediaError.MEDIA_ERR_DECODE))),o=oU(MU(5e3),tF((()=>!(this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived)&&(!this.player.isPlaying&&!(this.kind===Sk.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1))))),s=oU(_U(n,o),nF(xU(this,ex.INIT)));oU(this._triggerCheckDecodeSubject,tF((()=>!this.ignoreDecodeError)),VF(s),rB((e=>{this.reportDecodeResult(!1,e)})))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)}))}get ignoreDecodeError(){var e,t;return((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===e.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===ex.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){var i,r;let n=this.kind===Sk.AUDIO;if(FP[e?"addSuccessEvent":"addFailedEvent"]({key:n?504700:514702}),!n){let t=(null==(i=this.room)?void 0:i.downlinkVideoCodec.toUpperCase())||"H264";FP[e?"addSuccessEvent":"addFailedEvent"]({key:xP["DECODE_".concat(t,"_RESULT")]}),e||this.log.warn("".concat(null==(r=this.room)?void 0:r.downlinkVideoCodec," decode failed"))}e||(FP.addEnum({key:n?504701:514703,value:nM()}),hx.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(tM()||sM()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===Sk.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?ex.ON:ex.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};Sb(YB,"STATE_SUBSCRIBE","subscribe"),yb([zB(5,1)],YB.prototype,"waitHasMediaTrack",1),yb([QL(ex.INIT,YB.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),dM.emit(hM.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),qV(521716,!1)],YB.prototype,"subscribe",1),yb([QL(YB.STATE_SUBSCRIBE,ex.INIT,{sync:!0,success(){this.log.info("unsubscribed"),dM.emit(hM.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],YB.prototype,"unsubscribe",1);var XB=YB,QB=class extends XB{constructor(e,t){super(e,t,1),Sb(this,"volume",0),Sb(this,"mediaType",1),Sb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}get dbVolume(){return cV.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}};var ZB=class extends XB{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),Sb(this,"mediaType",4),Sb(this,"source"),Sb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager,this.once("first-video-frame",(e=>{this.room.emit("first-video-frame",e)}))}play(e,t){return(pw(null==t?void 0:t.canvasRender)?t.canvasRender:17===BO)&&!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 PB({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new SB(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),UL()||(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;!hw(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)}},$B=class extends ZB{constructor(e,t){super(e,t,2),Sb(this,"mediaType",2),Sb(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},eH=new Map;function tH(e,t){let i=gb(fb({},t),{timestamp:Bb()});eH.has(e)?eH.get(e).push(i):eH.set(e,[i])}function iH(e,t,i,r){try{if(_w(e))for(let n=0;n<e.length;n++)rH.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else rH.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}catch(AM){throw _M.error(AM),AM}}function rH(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;if(dw(i)){if(t.required)throw new Ub({code:xb.INVALID_PARAMETER,message:bP({key:IP.INVALID_PARAMETER_REQUIRED,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(dw(t.defaultValue))return;i=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let r=0;r<t.type.length;r++)null===t.type[r]&&null===i&&(e=!0),lw(t.type[r])&&i instanceof t.type[r]&&(e=!0),uw(t.type[r])&&cw(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new Ub({code:xb.INVALID_PARAMETER,message:bP({key:IP.INVALID_PARAMETER_TYPE,data:{key:r,rule:{type:t.type.map((e=>Tw(e)?vw(e):uw(e)?e:cw(e)))},fnName:n,value:i},link:{className:o,fnName:n}})})}else if(!dw(t.type)&&cw(i)!==t.type)throw new Ub({code:xb.INVALID_PARAMETER,message:bP({key:IP.INVALID_PARAMETER_TYPE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!1===t.allowEmpty){let e=hw(i)&&(0===i||Number.isNaN(i)),s=uw(i)&&""===i.trim();if(e||s)throw new Ub({code:xb.INVALID_PARAMETER,message:bP({key:IP.INVALID_PARAMETER_EMPTY,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})})}if(t.notLessThanZero&&hw(i)&&i<0)throw new Ub({code:xb.INVALID_PARAMETER,message:bP({key:IP.CANNOT_LESS_THAN_ZERO,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!dw(t.min)&&hw(i)&&i<t.min)throw new Ub({code:xb.INVALID_PARAMETER,message:bP({key:IP.INVALID_PARAMETER_MIN,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!dw(t.max)&&hw(i)&&i>t.max)throw new Ub({code:xb.INVALID_PARAMETER,message:bP({key:IP.INVALID_PARAMETER_MAX,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(uw(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new Ub({code:xb.INVALID_PARAMETER,message:bP({key:IP.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})})}else if(lw(t.instanceOf)&&!(i instanceof t.instanceOf))throw new Ub({code:xb.INVALID_PARAMETER,message:bP({key:IP.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(t.values&&!t.values.includes(i))throw new Ub({code:xb.INVALID_PARAMETER,message:bP({key:IP.INVALID_PARAMETER_RANGE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});let{properties:s}=t;ow(s)&&mw(i)&&Object.keys(s).forEach((e=>{rH.call(this,{rule:s[e],value:i&&i[e],key:"".concat(r,".").concat(e),fnName:n,className:o})}));let{arrayItem:a}=t;ow(a)&&_w(i)&&i.forEach(((e,t)=>{rH.call(this,{rule:a,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),lw(t.validate)&&t.validate.call(this,i,r,n,o,this)}dM.on(hM.JOIN_SUCCESS,(e=>{let{room:t}=e;tH(t.userId,{eventId:32788})})),dM.on(hM.LEAVE_START,(e=>{let{room:t}=e;tH(t.userId,{eventId:32789})})),dM.on(hM.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),tH(t.room.userId,{eventId:e})}})),dM.on(hM.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),tH(t.room.userId,{eventId:e})}})),dM.on(hM.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Sk.AUDIO?tH(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):tH(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),dM.on(hM.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Sk.AUDIO?tH(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):tH(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),dM.on(hM.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&tH(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&tH(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&tH(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),dM.on(hM.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&tH(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&tH(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&tH(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),dM.on(hM.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&tH(t.room.userId,{eventId:t.kind===Sk.VIDEO?32780:32781})})),dM.on(hM.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&tH(t.room.userId,{eventId:t.kind===Sk.VIDEO?32782:32783})})),dM.on(hM.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&&tH(i.userId,{eventId:t})})),dM.on(hM.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:n,remoteUserId:o}=e,s=!!o;switch(n){case"CONNECTED":t="RECONNECTING"===r?s?32801:32798:s?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===r&&(t=s?32802:32799);break;case"RECONNECTING":t=s?32800:32797}t&&tH(i.userId,{eventId:t,remoteUserId:o})})),dM.on(hM.VIDEO_CODEC_IMPLEMENTATION_CHANGED,(e=>{let{implementation:t,userId:i,remoteUserId:r,codec:n,isHWCodec:o,prevImplementation:s,streamType:a}=e,c=o?1:0;s||(c=o?3:2);let l={H264:0,H265:1,VP8:2}[n.toUpperCase()],d={eventId:4004,param1:c,param2:l,streamType:a||2};r&&(d.remoteUserId=r,d.eventId=4005),tH(i,d),FP.addEnum({key:r?514701:513701,value:c}),FP.addEnum({key:r?514700:513700,value:l})})),dM.on(hM.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===Sk.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),tH(t.userId,e)}}));var nH=vb(Rb(),1),oH=class extends nH.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"userId";super(),this.mySelfId=e,this._log=t,this.key=i,Sb(this,"userMap",new Map),Sb(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find((e=>e.isRobot))}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:r,role:n}=e;if(this.userMap.has(t))return;let o={userId:i,tinyId:r,role:20===n?"anchor":"audience"};this.userMap.set(t,o),this.emit("1",o)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let r="peer leave [".concat(e,"]");dw(t)||(r+=":".concat(TD[t])),this._log.info(r);let n=this.remotePublishedUserMap.get(e);if(n){let t=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:t,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",i.userId)}setUserList(e){this.userMap.forEach((t=>{e.findIndex((e=>e[this.key]===t[this.key]))<0&&this.deleteUser(t[this.key],0)})),e.forEach((e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)}))}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach((t=>{let i=t[this.key];if(e.findIndex((e=>e[this.key]===t[this.key]))<0){this._log.info("remote [".concat(i,"] unpublish"));let e=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(i),this.emit("6",{prevMuteState:e,muteState:t.muteState,flag:0})}})),e.forEach((e=>{var t;let i=e[this.key];if(i===this.mySelfId)return;let{flag:r,userId:n,tinyId:o}=e,s=Dw(r,n),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==r&&(e.flag=r,this._log.info("remote publish updated: ".concat(JSON.stringify(e.muteState))),this.emit("6",{prevMuteState:a,muteState:s,flag:r}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(s))),this.addUser({userId:n,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:Dw(0,n),muteState:s,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function sH(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return UV(((e,n)=>{let o=new WeakMap;return dM.on(hM.ROOM_DESTROY,(e=>{let{room:t}=e;return o.delete(t)})),function(){let s=o.get(this);for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(s||(s={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,s)),0===s.timestamp?s.timestamp=Date.now():Date.now()-s.timestamp>1e3&&(s.timestamp=Date.now(),s.callCountInSecond=0,s.totalSizeInSecond=0),r&&(s.totalSizeInSecond+=r(...c)),0!==s.timestamp&&Date.now()-s.timestamp<1e3&&(s.callCountInSecond>=t||s.totalSizeInSecond>i))throw new Ub({code:xb.INVALID_OPERATION,message:bP({key:IP.CALL_FREQUENCY_LIMIT,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>i,name:n,timesInSecond:t,maxSizeInSecond:i}})});s.callCountInSecond++,e.call(this,...c)}}))}var aH,cH=!0,lH={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"},dH={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},uH=((aH=uH||{})[aH.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",aH[aH.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",aH[aH.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",aH[aH.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",aH[aH.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",aH[aH.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",aH[aH.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",aH[aH.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",aH[aH.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",aH[aH.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",aH[aH.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",aH[aH.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",aH[aH.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",aH[aH.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",aH[aH.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",aH[aH.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",aH[aH.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",aH[aH.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",aH[aH.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",aH[aH.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",aH[aH.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",aH[aH.INVALID_OPERATION=5100]="INVALID_OPERATION",aH[aH.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",aH[aH.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",aH[aH.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",aH[aH.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",aH[aH.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",aH[aH.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",aH[aH.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",aH[aH.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",aH[aH.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",aH[aH.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",aH[aH.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",aH[aH.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",aH[aH.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",aH[aH.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",aH[aH.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",aH[aH.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",aH[aH.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",aH[aH.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",aH[aH.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",aH[aH.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",aH[aH.DEVICE_ERROR=5300]="DEVICE_ERROR",aH[aH.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",aH[aH.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",aH[aH.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",aH[aH.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",aH[aH.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",aH[aH.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",aH[aH.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",aH[aH.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",aH[aH.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",aH[aH.SERVER_ERROR=5400]="SERVER_ERROR",aH[aH.NEED_TO_BUY=5401]="NEED_TO_BUY",aH[aH.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",aH[aH.OPERATION_FAILED=5500]="OPERATION_FAILED",aH[aH.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",aH[aH.REJOIN_FAILED=5502]="REJOIN_FAILED",aH[aH.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",aH[aH.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",aH[aH.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",aH[aH.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",aH[aH.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",aH[aH.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",aH[aH.OPERATION_ABORT=5998]="OPERATION_ABORT",aH[aH.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",aH);var hH=gb(fb({},AP),{INVALID_PARAMETER(e){let{fnName:t}=e;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(r,"(), received type: ").concat(cw(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(r,"(), received type: ").concat(cw(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_REQUIRED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_ROOM_ID_TYPE_MISMATCH(e){let{key:t}=e;return"The type of target roomId must match the current roomId. Current room is using '".concat(t,"', but received '").concat("strRoomId"===t?"roomId":"strRoomId","'.")},INVALID_ROOM_ID_DUPLICATE(e){let{key:t}=e;return"the target '".concat(t,"' must not be the same as the current '").concat(t,"'.")},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 or screen share 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=pH(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=pH(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=pH(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=pH(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=pH(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=pH(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=pH(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 pH(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var mH=class e extends Error{constructor(e){let{code:t,extraCode:i,message:r="",messageParams:n,fnName:o="",originError:s,data:a}=e;var c;let l;l=r||function(e){let t,{code:i,params:r,enableDocLink:n=!1}=e,s="",a=uH[i];try{t=hH[a]}catch(o){t=hH.UNKNOWN_ERROR}return lw(t)?s=t(r):uw(t)&&(s=t),r.fnName&&!s.includes(r.fnName)&&("."!==s[s.length-1]&&(s+="."),s+=" thrown from ".concat(r.fnName,"()")),n&&(s+=" doc:"),s}({code:t===dH.SERVER_ERROR?t:i||t,params:fb({fnName:o,error:s},n)}),super(l),Sb(this,"name","RtcError"),Sb(this,"code"),Sb(this,"extraCode"),Sb(this,"functionName"),Sb(this,"message"),Sb(this,"data"),Sb(this,"handler"),Sb(this,"originError"),this.name=uH[t],this.code=t,this.extraCode=i,this.functionName=o,this.originError=s,this.message=l,this.data=a,5302===this.extraCode&&null!=(c=this.originError)&&c.message.includes("system")&&(this.handler=()=>{let e=document.createElement("a");sO?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):aO&&(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 Ub){let{stack:o}=t,s={code:dH.UNKNOWN_ERROR,fnName:i,originError:t};switch(t.getCode()){case xb.INVALID_PARAMETER:s.code=dH.INVALID_PARAMETER,s.message=t.message;break;case xb.INVALID_OPERATION:s.code=dH.INVALID_OPERATION;break;case xb.NOT_SUPPORTED:case xb.NOT_SUPPORTED_H264:s.code=dH.ENV_NOT_SUPPORTED,t.getCode()===xb.NOT_SUPPORTED_H264&&(s.extraCode=t.message.includes(AP.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case xb.JOIN_ROOM_FAILED:s.messageParams={fnParams:r};case xb.SERVER_TIMEOUT:case xb.SWITCH_ROLE_FAILED:case xb.SWITCH_ROOM_FAILED:s.code=dH.SERVER_ERROR,s.extraCode=t.getExtraCode();break;case xb.API_CALL_ABORTED:s.code=dH.OPERATION_ABORT;break;case xb.DEVICE_NOT_FOUND:case xb.DEVICE_AUTO_RECOVER_FAILED:case xb.INITIALIZE_FAILED:s.code=5300,t.name&&(s.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 xb.VIDEO_ENCODE_FAILED:s.extraCode=5505;case xb.AUDIO_ENCODE_FAILED:s.extraCode=5506,s.code=dH.OPERATION_FAILED;break;case xb.UNKNOWN:break;default:s.code=dH.OPERATION_FAILED}n=new e(s),o&&(n.stack+=o.substr(o.indexOf("\n")))}else{if(t instanceof e)return t;n=new e({code:dH.UNKNOWN_ERROR,fnName:i,originError:t})}return n}};var _H=mH;function fH(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function gH(e){return e===lH.QOS_PREFERENCE_CLEAR?"detail":e===lH.QOS_PREFERENCE_SMOOTH?"motion":""}function EH(e,t){let i=t?vk:Tk;return uN(e)?fb(fb({},i),e):Ek[e]?Ek[e]:i}var TH={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:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},vH={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}}},yH={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(uw(e)&&!document.getElementById(e))throw new _H({code:dH.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},SH={name:"userId",required:!0,type:"string"},IH={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[lH.AUDIO_PROFILE_STANDARD,lH.AUDIO_PROFILE_STANDARD_STEREO,lH.AUDIO_PROFILE_HIGH,lH.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function AH(e,t){if(!e)throw new _H({code:dH.INVALID_OPERATION,extraCode:5101,fnName:t})}function RH(e,t,i){if(!e)throw new _H({code:dH.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}function CH(e,t,i){if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new _H({code:dH.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:i}})}function bH(e,t,i){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new _H({code:dH.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:i}})}function kH(e){var t;if(null==(t=null==e?void 0:e.option)||!t.small)return;if(!uL())return _M.warn("small stream is not supported"),void delete e.option.small;let i=EH(e.option.profile),r=EH(e.option.small,!0);return((e,t)=>e.width*e.height>=t.width*t.height&&e.frameRate>=t.frameRate&&e.bitrate>=t.bitrate)(i,r)?void 0:(_M.warn("small stream profile must be less than big stream profile. Big: ".concat(JSON.stringify(i),", Small: ").concat(JSON.stringify(r))),void delete e.option.small)}var DH={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 _H({code:dH.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(uw(e.roomId))throw new _H({code:dH.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});CH(e.roomId,i,t)}else{if(!e.strRoomId)throw new _H({code:dH.INVALID_PARAMETER,extraCode:5015,fnName:i});bH(e.strRoomId,i,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"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:yH,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:TH},validate(e){var t,i;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&qP())throw new _H({code:dH.ENV_NOT_SUPPORTED,extraCode:5201});null!=(i=null==e?void 0:e.option)&&i.small&&kH(e)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:gb(fb({},yH),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:TH},validate(e){var t;null!=(t=null==e?void 0:e.option)&&t.small&&kH(e)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:IH},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&qP())throw new _H({code:dH.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:IH}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:yH,publish:{type:"boolean"},option:vH},validate(e,t,i,r,n){var o;if(null==(o=null==e?void 0:e.option)||!o.videoTrack){if(qP())throw new _H({code:dH.ENV_NOT_SUPPORTED,extraCode:5201});if(!$P())throw new _H({code:dH.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:yH,publish:{type:"boolean"},option:vH}},muteRemoteAudio:[SH,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[SH,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:yH,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){AH(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(RH(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new _H({code:dH.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:gb(fb({},yH),{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){AH(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(RH(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new _H({code:dH.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&&dw(e.streamType))throw new _H({code:dH.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){AH(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(!kL)throw new _H({code:dH.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new _H({code:dH.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new _H({code:dH.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new _H({code:dH.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});AH(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 _H({code:dH.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 _H({code:dH.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new _H({code:dH.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(AH(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new _H({code:dH.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(e,t,i){if(AH(this._room.isJoined,i),this._room.useStringRoomId&&e.strRoomId===this._room.roomId||!this._room.useStringRoomId&&e.roomId===Number(this._room.roomId))throw new _H({code:dH.INVALID_PARAMETER,extraCode:5020,fnName:i,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId&&this._room.useStringRoomId||!e.roomId&&e.strRoomId&&!this._room.useStringRoomId)throw new _H({code:dH.INVALID_PARAMETER,extraCode:5019,fnName:i,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId)CH(e.roomId,i,t);else{if(!e.strRoomId)throw new _H({code:dH.INVALID_PARAMETER,extraCode:5015,fnName:i});bH(e.strRoomId,i,t)}},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},wH={TRTC:DH},NH=class extends Error{};function OH(e,t){let i=Mw(e);for(let r=0;r<t.length;r++)Ow(i[r],t[r]);return i}function MH(e){this._resolve=Promise.resolve(e)}function PH(e){this._reject=Promise.reject(e)}var LH=class e{constructor(t,i){this.instance=t,this.group=i,Sb(this,"started",!1),Sb(this,"ops",[]),Sb(this,"startSame",(()=>!0)),Sb(this,"mergeUpdate",OH);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 NH("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:MH,reject:PH};try{switch(this.state){case 1:if(0===e)throw new NH("already started");break;case 4:if(2===e)throw new NH("not started");break;default:return this.cacheOp(o)}}catch(CM){return Promise.reject(CM)}return this.ops.push(o),o.promise=t(...o.args).then(r,n)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new NH("already start");break;case 3:switch(e.type){case 2:throw new NH("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new NH("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new NH("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 NH("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new NH("start not allowed after update");case 0:throw new NH("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new NH("keep start")),new NH("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}};Sb(LH,"instances",new WeakMap);var xH=LH,VH=new WeakMap,UH=(e,t)=>{if(t instanceof NH){let{stack:i}=t;t=new _H({code:dH.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function FH(e,t){return UV(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let a=xH.get(this,"string"==typeof e?e:e.call(this,...o));return a?(t&&(a.startSame=t.bind(this)),a.action(0,i.bind(this),o).catch(UH.bind(null,r))):i.apply(this,o)}))}function BH(e,t){let{merge:i,debounce:r}=t||{};return UV(((t,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=xH.get(this,"string"==typeof e?e:e.call(this,...s));if(!c)return t.apply(this,s);if(i&&(c.mergeUpdate=i.bind(this)),r&&r.isNeedToDebounce.apply(this,s)){let{delay:e,getKey:i}=r;return new Promise(((r,o)=>{var a,l;let d=null==(a=VH.get(this))?void 0:a.get(i(...s));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout((()=>{if(3===c.state||4===c.state)return r();c.action(2,t.bind(this),s).catch(UH.bind(null,n)).then(r,o)}),e);VH.has(this)?null==(l=VH.get(this))||l.set(i(...s),{timeoutId:u,resolve:r}):VH.set(this,new Map([[i(...s),{timeoutId:u,resolve:r}]]))}))}return c.action(2,t.bind(this),s).catch(UH.bind(null,n))}))}function HH(e){return UV(((t,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let s="function"==typeof e?e.call(this,...n):e;if(s instanceof RegExp)return Promise.all(xH.gets(this,s).map((e=>e.action(3,(()=>Promise.resolve()),n)))).then((()=>t.call(this,...n)));let a=xH.get(this,s);return a?a.action(3,t.bind(this),n).catch(UH.bind(null,i)):t.apply(this,n)}))}var WH={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",PERMISSION_STATE_CHANGE:"permission-state-change"},GH=new Set([WH.ERROR,WH.AUTOPLAY_FAILED,WH.KICKED_OUT,WH.REMOTE_USER_ENTER,WH.REMOTE_USER_EXIT,WH.REMOTE_AUDIO_AVAILABLE,WH.REMOTE_AUDIO_UNAVAILABLE,WH.REMOTE_VIDEO_AVAILABLE,WH.REMOTE_VIDEO_UNAVAILABLE,WH.CONNECTION_STATE_CHANGED,WH.PUBLISH_STATE_CHANGED,WH.SCREEN_SHARE_STOPPED,WH.DEVICE_CHANGED,WH.FIRST_VIDEO_FRAME,WH.PERMISSION_STATE_CHANGE]),jH={};Tb(jH,{ScheduleRequestType:()=>QH,getAbilityConfig:()=>$H,getScheduleDomain:()=>eW,isNeedToSchedule:()=>KH,scheduleProxy:()=>YH,sendScheduleRequest:()=>zH,setIsNeedToSchedule:()=>qH,setScheduleProxy:()=>XH});var JH=null,KH=!0;function qH(e){pw(e)&&e!==KH&&(KH=e,_M.info("setIsNeedToSchedule ".concat(e)))}function zH(e){return Ab(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:n,userSig:o,version:s,frameWorkType:a,role:c,latencyLevel:l}=e;return function*(){if(!KH&&JH)return{isCached:!0,result:JH};let e={delta:0,count:[1,1],msg:[],detail:[]};try{let d=new FormData;d.append("userId",String(t)),d.append("sdkAppId",String(i)),d.append("isStrGroupId",String(r)),d.append("groupId",String(n)),d.append("sdkVersion",s),d.append("userSig",String(o));let u=yield $O();null!=u&&u.model&&d.append("model",String(null==u?void 0:u.model)),c&&d.append("role",String(c)),l&&d.append("latencyLevel",String(l)),a&&d.append("frameWorkType",String(a));let h=Aw(),p=yield function(e,t,i){return new Promise(((r,n)=>{let o=null;Iw([iW((e=>t.count[0]=e+1),(e=>{let{error:r,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[0]=r.message,o||(s>=1&&(a[0]=ZH(i,"config",Sk.MAIN,!0)),n())}))(ZH(i,"config",Sk.MAIN),e,{get timeout(){return 1e3*sw(2+t.count[0])}}),iW((e=>t.count[1]=e+1),(e=>{let{error:r,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[1]=r.message,o||(s>=2&&(a[0]=ZH(i,"config",Sk.BACKUP,!0)),n())}))(ZH(i,"config",Sk.BACKUP),e,{get timeout(){return 1e3*sw(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}(d,e,i);p.config&&(p.config.loggerDomain&&ek(p.config.loggerDomain),pw(p.config.scheduleCache)&&qH(!p.config.scheduleCache)),e.delta=Aw()-h;let m=function(e,t,i){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let n=performance.getEntriesByType("resource"),o=ZH(e,"config",Sk.MAIN),s=ZH(e,"config",Sk.BACKUP);for(let e of n)if(e.startTime>=i&&(e.name===o||e.name===s)&&e.transferSize>0){let i=e.name===o?Sk.MAIN:Sk.BACKUP,n=Math.round(e.duration),s=Math.round(e.domainLookupStart-e.startTime),a=e.redirectStart>0?Math.round(e.redirectEnd-e.redirectStart):0,c=e.fetchStart>0?Math.round(e.domainLookupStart-e.fetchStart):0,l=Math.round(e.domainLookupEnd-e.domainLookupStart),d=Math.round(e.requestStart-e.secureConnectionStart),u=Math.round(e.secureConnectionStart-e.connectStart),h=Math.round(e.responseStart-e.requestStart),p=Math.round(e.responseEnd-e.responseStart),m=[l,d,u,h,p];hx.uploadEvent({log:"stat-schedule-net:".concat(n,"(").concat(s,"(").concat(a,"->").concat(c,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=gb(fb({},r),{totalCost:n,local:s,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(o){_M.error("getScheduleDetailCost error",o)}return r}(Number(i),t,h);return JH=p,{isCached:!1,result:p,detailCost:m}}catch(d){let e=_w(d)?d[0]:d,t=hw(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),r=new Ub({code:xb.SCHEDULE_FAILED,extraCode:t,message:bP({key:IP.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw _M.error(i,t),r}}()}))}"undefined"!=typeof document&&document.head.insertAdjacentHTML("beforeend",Object.values(uD).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),dM.on("28",(()=>qH(!0))),dM.on("63",(()=>qH(!0))),dM.on("84",(()=>qH(!0))),dM.on("201",(e=>{"RECONNECTING"===e.state&&qH(!0)})),dM.on("202",(e=>{"RECONNECTING"===e.state&&qH(!0)}));var YH={main:"",backup:""};function XH(e){_w(e)?(YH.main=e[0],YH.backup=e[1]):YH.main=e}var QH=(e=>(e.CONFIG="config",e.TRTC_AUTO_CONF="trtcAutoConf",e.AUDIO_AI_AUTH="audioAiAuth",e))(QH||{});function ZH(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Sk.MAIN,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return"https://".concat(YH[i]||eW(e,i,r),"/api/v1/").concat(t)}function $H(e,t,i){let r=ZH(e,t),n=ZH(e,t,Sk.BACKUP),o=new URLSearchParams(i).toString();return Iw([fetch("".concat(r,"?").concat(o)).then((e=>e.json())),fetch("".concat(n,"?").concat(o)).then((e=>e.json()))])}function eW(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Sk.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=JD(e)?r?i===Sk.MAIN?uD.MAIN_OVERSEA_BACKUP:uD.BACKUP_OVERSEA:i===Sk.MAIN?uD.MAIN_OVERSEA:uD.BACKUP_OVERSEA:i===Sk.MAIN?uD.MAIN:uD.BACKUP,t}function tW(e,t,i){return new Promise(((r,n)=>{nN({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 iW=(e,t)=>hN({retryFunction:tW,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var rW=class{constructor(){Sb(this,"_log"),this._log=_M.createLogger({id:"fd"})}download(e,t){return Ab(this,null,(function*(){let{type:i="blob"}=t||{};e=Kw(e);try{let t,r=Aw();if(t=lw(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let n=Aw()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(n,"ms")),FP.addSuccessEvent({key:522700,cost:Aw()-r}),t.data}catch(AM){throw this._log.error("failed to download: ".concat(e,", error: ").concat(AM)),FP.addFailedEvent({key:522700,error:AM}),AM}}))}downloadWithFetch(e,t){return Ab(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){let e=new Error("network response was not ok: ".concat(r.status));throw e.status=r.status,e}return i="arraybuffer"===t?yield r.arrayBuffer():yield r.blob(),{data:i}}catch(Xk){throw Xk}}))}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=()=>{if(200===n.status||0===n.status&&n.response)i({data:n.response});else{let e=new Error("XHR failed, status: ".concat(n.status));e.status=n.status,r(e)}},n.onerror=r,n.send(null)}))}loadWasm(e,t){return Ab(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=Aw(),r=null,n=null;if(lw(WebAssembly.instantiateStreaming)&&!e.startsWith("data:application/octet-stream;base64,")&&!(e=>e.startsWith("file://"))(e)&&lw(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(Yb){n=Yb}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(Yb){n=Yb}if(r){let t=Aw()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),FP.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),FP.addFailedEvent({key:522701,error:n}),n}))}loadScript(e){this._log.info("loadScript ".concat(e));let t=Aw();return new Promise(((i,r)=>{let n=document.createElement("script");n.type="text/javascript",n.onload=()=>{this._log.info("loadedScript ".concat(e,", cost: ").concat(Aw()-t,"ms")),FP.addSuccessEvent({key:522702,cost:Aw()-t,split:1e3}),i(n)},n.onerror=t=>{this._log.error("failed to loadScript ".concat(e,", error: ").concat((null==t?void 0:t.message)||JSON.stringify(t))),FP.addFailedEvent({key:522702}),r(t)},n.crossOrigin="anonymous",n.src=e,document.head.append?document.head.append(n):document.getElementsByTagName("head")[0].appendChild(n)}))}};yb([mx({settings:{timeout:0,retries:3},onError(e,t,i){var r;404===(null==e?void 0:e.status)||null!=(r=null==e?void 0:e.message)&&r.includes("404")?(this._log.warn("download 404, stop retry"),i(e)):t()},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],rW.prototype,"download",1),yb([mx({settings:{timeout:3e3,retries:3},onRetrying(e){this._log.warn("loadScript retrying: ".concat(e))}})],rW.prototype,"loadScript",1);var nW=new rW;function oW(e){var t=this;let{TRTC:i,room:r,errorModule:n,assetsPath:o}=e;return{TRTC:i,LocalMixVideoTrack:BB,LocalVideoTrack:_B,LocalScreenTrack:GB,room:r,assetsPath:o,fileDownloader:nW,innerEmitter:dM,constants:jb,environment:mN,utils:fB,eventLogger:hx,log:this.room.getLogger(),loggerManager:_M,errorModule:n,kvStatManager:FP,rtcDectection:EM,trtc:this,rx:zV,enums:TM,schedule:jH,getDevices:_V,initVisionTaskRegistry:function(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"/mediapipe/vision.js";return Ab(t,null,(function*(){window.VisionTaskRegistry||(yield nW.loadScript("".concat(e,"/").concat(i).replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(e)).preloadModels([window.VisionTaskType.ImageSegmenter])}))},clearStarted:(e,t)=>{let i=e.getAlias(),r=xH.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:KB,createAudioNode:nV}}var sW=new WeakMap;function aW(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return UV(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{lW.call(this,t,n,i,this._name)}catch(AM){return Promise.reject(AM)}return e.apply(this,n)}))}function cW(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return UV(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{lW.call(this,t,n,i,this._name)}catch(AM){throw AM}return e.apply(this,n)}))}function lW(e,t,i,r){if(_w(e))for(let n=0;n<e.length;n++)dW.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else dW.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function dW(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function s(e){return{code:dH.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(dw(i)){if(t.required)throw new _H(s(5001));if(dw(t.defaultValue))return void(lw(t.validate)&&t.validate.call(this,i,r,n,o,this));i=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let r=0;r<t.type.length;r++)null===t.type[r]&&null===i&&(e=!0),lw(t.type[r])&&i instanceof t.type[r]&&(e=!0),uw(t.type[r])&&cw(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new _H({code:dH.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>Tw(e)?vw(e):uw(e)?e:cw(e)))},value:i}})}else if(!dw(t.type)&&cw(i)!==t.type)throw new _H(s(5002));if(!1===t.allowEmpty){let e=hw(i)&&(0===i||Number.isNaN(i)),t=uw(i)&&""===i.trim();if(e||t)throw new _H(s(5003))}if(t.notLessThanZero&&hw(i)&&i<0)throw new _H(s(5006));if(!dw(t.min)&&hw(i)&&i<t.min)throw new _H(s(5007));if(!dw(t.max)&&hw(i)&&i>t.max)throw new _H(s(5008));if(uw(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new _H(s(5004))}else if(lw(t.instanceOf)&&!(i instanceof t.instanceOf))throw new _H(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new _H(s(5005));let{properties:a}=t;ow(a)&&mw(i)&&Object.keys(a).forEach((e=>{dW.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;ow(c)&&_w(i)&&i.forEach(((e,t)=>{dW.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),lw(t.validate)&&t.validate.call(this,i,r,n,o,this)}function uW(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r,ignoreLog:n,ignoreErrorLog:o}=e;return UV(((e,s)=>function(){for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];var d,u,h;function p(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...c);if(c[e.argIndex]===t)return e.value}if(t===c||e in c)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(cw(t)):t instanceof MediaStreamTrack?qw(t):(JSON.stringify(t),t)}catch(n){return"type:".concat(cw(t))}}let m=this._log||_M;if(null!=n&&n(...c))return e.apply(this,c);c.length>0?m.info("".concat(s,"() ").concat(JSON.stringify(c,((e,t)=>p(e,t,["userSig","privateMapKey"]))))):m.info("".concat(s,"()"));let _=r?r(...c):OP[s],f=(null==o?void 0:o(...c))||!1;try{let i=e.apply(this,c),r=Aw();if(Ew(i)){let e="".concat(s.includes("Plugin")?"".concat((null==(u=(d=c[0]).getName)?void 0:u.call(d))||""," "):" ");return i.then((i=>(m.info("".concat(s,"() success ").concat(e).concat(t.call(this,...c))),FP.addSuccessEvent({key:_,cost:Aw()-r}),i))).catch((i=>{var r;let n=(i=_H.convertFrom.call(this,i,s,1===c.length?c[0]:c)).extraCode||i.code,o=null!=(r=i.message)&&r.includes(n)?"":" code:".concat(n);throw f||m.error("".concat(s,"() failed ").concat(e).concat(t.call(this,...c)," ").concat(i).concat(o," params: ").concat(JSON.stringify(c,p))),FP.addFailedEvent({key:_,error:i}),i}))}return FP.addSuccessEvent({key:_}),i}catch(kM){let t=(kM=_H.convertFrom.call(this,kM,s)).extraCode||kM.code,i=null!=(h=kM.message)&&h.includes(t)?"":" code:".concat(t);throw f||m.error("".concat(s,"() failed ").concat(kM).concat(i," params: ").concat(JSON.stringify(c,p))),FP.addFailedEvent({key:_,error:kM}),kM}}))}var hW,pW=e=>UV(((t,i)=>function(r,n){return Ab(this,null,(function*(){let o=this._plugins.get(r);if(!o)throw this._log.error("plugin ".concat(String(r)," is not found")),new _H({code:dH.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(lw(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new _H({code:dH.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return lW.call(this,o.getValidateRule(e),[n],i,"TRTC"),t.call(this,o,n)}))})),mW=0,_W=class e{constructor(e){this.core=e,Sb(this,"log"),Sb(this,"customAudioReferenceMap",new Map),Sb(this,"audioRefId",0),Sb(this,"audioContext",Qx()),Sb(this,"localAudioWorkletNode"),Sb(this,"screenAudioWorkletNode"),Sb(this,"mixNode"),Sb(this,"silentNode"),mW+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(mW)}),this.log.info("created id=".concat(this.getAlias()).concat(mW))}static getStartValidateRule(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&&!e.room.audioManager.hasScreenAudioTrack)throw new _H({code:dH.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return hW||(hW=this.doPreload(e)),hW}doPreload(e){return Ab(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield Bx(this.audioContext,i)}catch(AM){this.log.error("preload audioProcessor failed. ".concat(AM))}finally{URL.revokeObjectURL(i)}}))}getName(){return e.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return e.getStartValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return Ab(this,null,(function*(){let{room:t}=this.core,{sdkAppId:i,userId:r,assetsPath:n=this.core.assetsPath,audioReference:o,processLevel:s,enableDump:a,isLocalAudioNeedAudioProcess:c=!0,isScreenAudioNeedAudioProcess:l=!0}=e;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=c,this.core.room.audioManager.isScreenAudioNeedAudioProcess=l,!n)throw new _H({code:dH.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload("".concat(n,"/audioProcessor-wasm.js")),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let n=String(Date.now()).slice(0,-3),{auth:o,sign:s,status:a,message:c}=yield function(e){return Ab(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]:Sk.MAIN;return"https://".concat(YH[t]||eW(e,t),"/api/v1/audioAiAuth")}(t),"?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(r,"×tamp=").concat(n),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d=JD(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",u="Init RTCAudioProcessor failed.",h="";switch(s){case 1:h="Please check your params.";break;case 2:h="You need to buy packages. Refer to: ".concat(d);break;case 3:h="Server is invalid. Please contact our engineer. ";break;case 4:h="Your packages is not active. Refer to: ".concat(d);break;case 5:h="Your packages is expired. Refer to: ".concat(d);break;case 6:h="Your version is not supported."}return{auth:!1,status:l,message:a?"".concat(u," Reason: ").concat(a,". ").concat(h):"".concat(u,", ").concat(h)}}()}))}(gb(fb({},e),{timestamp:n}));if(!o)throw this.log.info("audioProcessor: ".concat(r," auth result: ").concat(o,". Message: ").concat(c)),new _H({code:dH.INVALID_PARAMETER,message:c});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",i,r,n,s,a,t),this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",i,r,n,s,a,t)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),this.localAudioWorkletNode.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),t.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode),dw(o)||o.forEach((e=>{this.customAudioReferenceMap.set(e,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:e,refId:"o-".concat(this.audioRefId++)})})),dw(s)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:s}}),dw(a)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:a}})}))}update(e){return Ab(this,null,(function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:t,enableDump:i,processLevel:r}=e;dw(t)||(this.customAudioReferenceMap.forEach(((e,t)=>{this.customAudioReferenceMap.delete(t),this.core.room.audioManager.updateAudioReference({type:"remove",refId:e})})),t.forEach((e=>{this.customAudioReferenceMap.set(e,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:e,refId:"o-".concat(this.audioRefId++)})}))),dw(r)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),dw(i)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:i}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:i}}))}))}stop(){return Ab(this,null,(function*(){if(!(this.localAudioWorkletNode&&this.mixNode&&this.silentNode&&this.screenAudioWorkletNode))return;let{room:e}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode)}))}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}initWorkletNode(e,t,i,r,n,o,s,a){e.port.postMessage({type:"init",data:{sdkAppId:String(i),userId:r,timestamp:n,sign:o,status:s}}),e.port.onmessage=e=>{var i;let{data:r}=e;switch(r.type){case"cost":let e=(null==r?void 0:r.value)>10?"info":"debug";return void this.log[e]("[".concat(t,"] avg cost: ").concat(r.value," max: ").concat(null==r?void 0:r.max,"(").concat(Wb(new Date(null==r?void 0:r.maxCostTimestamp)),") hist: ").concat(null==(i=null==r?void 0:r.hist)?void 0:i.join(" ")));case"log":return void this.log[r.logLevel]("[".concat(t,"] ").concat(r.value));case"dump":return void dM.emit("265",{room:a,data:r.value,type:"localAudio"===t?"dump":"dump-screen-audio"})}}}};Sb(_W,"updateValidateRule",{type:"object"}),Sb(_W,"stopValidateRule",{type:"object"}),Sb(_W,"Name","AudioProcessor");var fW=_W;var gW=0,EW=class{constructor(e,t){Sb(this,"player"),Sb(this,"publisher"),Sb(this,"mixInput"),this.mixInput=new tV(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&&(dw(e.volume)||(this.volume=e.volume),dw(e.loop)||(this.loop=e.loop),dw(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 TW(e,t){if(t&&"function"!=typeof t)throw new _H({code:dH.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var vW=class e{constructor(e){this.core=e,Sb(this,"log"),Sb(this,"mixedMusicMap",new Map),Sb(this,"cacheMusicMap",new Map),gW+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(gW)}),this.log.info("created id=".concat(this.getAlias()).concat(gW))}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 Ab(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 EW(e,t.audioManager),this.cacheMusicMap.set(i,n)),n.updateListener(e),n.updateSettings(e),yield n.play(),this.mixedMusicMap.set(i,n),n.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:n.mixInput.source.node,refId:"ax-".concat(i)}),this.log.info("start mix audio track ".concat(i," success.")),FP.addEnum({key:502700,value:3}),this.kvUpload(e)}))}update(e){return Ab(this,null,(function*(){let{id:t,operation:i,seekFrom:r,playbackRate:n}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let o=this.mixedMusicMap.get(t);o?(o.updateSettings(e),o.updateListener(e),dw(i)||o.setOperation(i),dw(r)||o.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return Ab(this,arguments,(function(e){var t=this;let{id:i}=e;return function*(){if(t.mixedMusicMap.has(i)){t.log.info("remove music source, music id: ".concat(i));let e=t.mixedMusicMap.get(i);null!=e&&e.mixInput.source.node&&t.core.room.audioManager.updateAudioReference({type:"remove",audioReference:e.mixInput.source.node,refId:"ax-".concat(i)}),null==e||e.stop(),t.mixedMusicMap.delete(i)}"*"===i&&t.destroyAllMusic()}()}))}kvUpload(e){let{track:t,loop:i,volume:r,playbackRate:n,operation:o,seekFrom:s,onTimeUpdate:a,onDurationChange:c,onEnded:l}=e;t&&FP.addCount({key:502711}),i&&FP.addCount({key:502703}),r&&FP.addCount({key:502704}),n&&FP.addCount({key:502705}),o&&FP.addCount({key:502706}),s&&FP.addCount({key:502707}),"function"!=typeof a&&FP.addCount({key:502709}),"function"!=typeof l&&FP.addCount({key:502710}),"function"!=typeof c&&FP.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>{null!=e&&e.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:e.mixInput.track,refId: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()}};Sb(vW,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(e,t,i){if(e.url&&"*"!==e.url){let t=e.url.split("?")[0],r=["mp3","ogg","wav","flac"],n=t.split(".").pop(),o=r.indexOf(n)>=0,s=t.startsWith("blob"),a=t.startsWith("data");if(!(o||s||a))throw new _H({code:dH.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new _H({code:dH.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});TW("onTimeUpdate",e.onTimeUpdate),TW("onEnded",e.onEnded),TW("onDurationChange",e.onDurationChange)}}),Sb(vW,"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){TW("onTimeUpdate",e.onTimeUpdate),TW("onEnded",e.onEnded),TW("onDurationChange",e.onDurationChange)}}),Sb(vW,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),Sb(vW,"Name","AudioMixer");var yW,SW=vW,IW=0,AW=class e{constructor(e){this.core=e,Sb(this,"log"),Sb(this,"audioContext",Qx()),Sb(this,"workletNode"),IW+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(IW)}),this.log.info("created id=".concat(this.getAlias()).concat(IW))}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 _H({code:dH.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return yW||(yW=this.doPreload(e)),yW}doPreload(e){return Ab(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield Bx(this.audioContext,i)}catch(AM){throw this.log.error("load worklet failed",AM),AM}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 Ab(this,null,(function*(){let{room:t,schedule:i}=this.core,{assetsPath:r=this.core.assetsPath}=e;if(!r)throw new _H({code:dH.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload("".concat(r,"/denoiser-wasm.js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:n,status:o,message:s}=yield function(e,t){return Ab(this,arguments,(function(e,t){let{sdkAppId:i,userId:r,userSig:o,timestamp:s}=t;return function*(){try{let{data:{errCode:t,errMsg:n,sign:a,status:c}}=yield e.getAbilityConfig(i,e.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:r,userSig:o,timestamp:s});if("1"===c)return{auth:!0,sign:a,status:c,message:n};let l=JD(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",d="Init RTCAIDenoiser failed.",u="";switch(t){case 1:u="Please check your params.";break;case 2:u="You need to buy packages. Refer to: ".concat(l);break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: ".concat(l);break;case 5:u="Your packages is expired. Refer to: ".concat(l);break;case 6:u="Your version is not supported."}return{auth:!1,status:c,message:n?"".concat(d," Reason: ").concat(n,". ").concat(u):"".concat(d,", ").concat(u)}}catch(n){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(n)}}}()}))}(i,gb(fb({},e),{timestamp:t}));if(!r)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(r,". Message: ").concat(s)),new _H({code:dH.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:n,status:o}}),this.workletNode.port.onmessage=e=>{var t;let{data:i}=e;if("cost"===i.type){let e=(null==i?void 0:i.max)>20?"warn":(null==i?void 0:i.max)>10?"info":"debug";this.log[e]("avg cost: ".concat(i.value," max: ").concat(null==i?void 0:i.max,"(").concat(Wb(new Date(null==i?void 0:i.maxCostTimestamp)),") hist: ").concat(null==(t=null==i?void 0:i.hist)?void 0:t.join(" ")))}else"log"===i.type&&this.log[i.logLevel]("".concat(i.value))}}this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})}))}update(){return Ab(this,null,(function*(){}))}stop(){return Ab(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)}};Sb(AW,"updateValidateRule",{type:"object"}),Sb(AW,"stopValidateRule",{type:"object"}),Sb(AW,"Name","AIDenoiser");var RW=AW;var CW=vb(Rb(),1),bW=class extends CW.EventEmitter{constructor(){super(),Sb(this,"observer"),Sb(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 Ab(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(zb){hx.uploadEvent({log:"stat-pressure-detector-start-failed",error:zb})}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&_M.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(Xk){hx.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:Xk})}}},kW=new bW;function DW(e){let[t,i]=e,r=i.byteLength,n=parseInt(String(r/255),10),o=r%255,s=[];s.push(0,0,0,1,6,t);for(let c=0;c<n;c++)s.push(255);s.push(o);let a=new DataView(i);return s.push(...new Uint8Array(a.buffer)),s.push(128),new hB(new DataView(new Uint8Array(s).buffer),!0)}function wW(e){return"empty"===e.type||0===e.data.byteLength}function NW(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}function OW(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 MW(e){let{frame:t,seiMessageList:i}=e;if(!i||0===i.length||0===t.data.byteLength)return t;let r=9-OW(t.data);if(r<=0)return t;let n=i.splice(0,r).reverse().map(DW),o=n.reduce(((e,t)=>e+t.dataView.byteLength),0),s=new ArrayBuffer(o+t.data.byteLength),a=new DataView(s),c=new DataView(t.data),l=0;for(let d=0;d<n.length;d++)for(let e=0;e<n[d].dataView.byteLength;e++)a.setInt8(l++,n[d].dataView.getInt8(e));for(let d=0;d<t.data.byteLength;d++)a.setInt8(l++,c.getInt8(d));return t.data=s,t}function PW(e){let{frame:t,onSEI:i}=e;try{let e=new DataView(t.data);if(wW(t)||!NW(e))return t;let r=[],n=0,o=-1,s=-1;for(let i=0;i<t.data.byteLength;i++){let a=e.getUint8(i);if(0===a)n++;else if(1===a){if(2===n||3===n){let a=i-n;if(-1===o?o=a:-1===s&&(s=a,r.push(new hB(new DataView(e.buffer.slice(o,s)))),o=a,s=-1),6!==e.getUint8(i+1)){t.data=e.buffer.slice(a);break}}n=0}else n=0}null==i||i(r.reverse())}catch(zb){}return t}var LW=0,xW=class e{constructor(e){this.core=e,Sb(this,"log"),Sb(this,"_seiMessageList",[]),Sb(this,"_smallSeiMessageList",[]),Sb(this,"_subStreamSeiMessageList",[]),LW++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(LW)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(LW)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:t,mediaType:i}=e;try{return MW({frame:t,seiMessageList:8===i?this._smallSeiMessageList:2===i?this._subStreamSeiMessageList:this._seiMessageList})}catch(Xk){this.log.warn(Xk)}return t}decode(e){let{frame:t,track:i}=e;return PW({frame:t,onSEI:e=>{e.forEach((e=>{this.core.trtc.emit(WH.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:CL?this.encode:MW,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:CL?this.decode:PW,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],o=!!i.small;i.toSubStream?this._subStreamSeiMessageList.push(n):(this._seiMessageList.push(n),o&&this._smallSeiMessageList.push(n)),null==(r=this.core.room.scriptTransformWorker)||r.postMessage({type:"sei",data:n,isMain:!i.toSubStream,small:o})}getName(){return e.Name}getAlias(){return"sei"}getGroup(){return"sei"}};Sb(xW,"autoStart",!0),Sb(xW,"Name","SEI");var VW=xW;function UW(e){let{frame:t,onDump:i}=e;return null==i||i(),t}function FW(e){let{frame:t,onDump:i}=e;return null==i||i(),t}var BW={"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=>{BW["".concat(e,"()")]={tips:"Call trtc.".concat(e),color:"blue",class:"blue",textColor:"#fff"}}));var HW,WW=0,GW=class e{constructor(e){this.core=e,Sb(this,"_core"),Sb(this,"log"),Sb(this,"dumpLocalVideoMap",{}),Sb(this,"dumpRemoteVideoMap",{}),Sb(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++WW)}),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 Ab(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(e){return Ab(this,arguments,(function(e){var t=this;let{forceOpen:i}=e;return function*(){dw(i)&&(i?(yield t.openDebugDiaLog(),t.addVideoProcessor()):(t.closeDebugDiaLog(),t.removeVideoProcessor()))}()}))}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return Ab(this,null,(function*(){var e;if(!this.dialog)try{if(HW)yield HW;else{let t=new URLSearchParams(location.search).get("trtcDebugDialogPath")||(null==(e=window.sessionStorage)?void 0:e.getItem("TRTC_DEBUG_DIALOG_PATH"))||"https://unpkg.com/".concat("trtc-sdk-v5","@").concat(Kb,"/assets/debug-dialog.js");HW=this._core.fileDownloader.loadScript(t),yield HW}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(zb){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(zb))}}))}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):UW,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):FW,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 UW({frame:t,onDump:()=>{if(!i)return;let e=2===i?"sub":"main",r=this.dumpLocalVideoMap[e];r&&(r.data.push(t.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>1e3*r.duration&&r.onDumpEnd())}})}decodeVideo(e){let{frame:t,track:i}=e;return FW({frame:t,onDump:()=>{if(!i)return;let e=this.dumpRemoteVideoMap["".concat(i.userId,"-").concat(i.streamType)];e&&(e.data.push(t.data.slice(0)),e.duration>0&&Date.now()-e.startTimestamp>1e3*e.duration&&e.onDumpEnd())}})}};Sb(GW,"Name","Debug"),Sb(GW,"autoStart",!0);var jW=GW,JW=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},KW=class{constructor(e,t,i){Sb(this,"trackDoneOB"),Sb(this,"startOB"),Sb(this,"stopOB"),Sb(this,"inputFrameCount",0),Sb(this,"decodedFrameCount",0),Sb(this,"type","auto"),Sb(this,"config"),Sb(this,"decoder"),Sb(this,"_decodeSink");let{kvStatManager:r,trtc:n}=e;this.config=i.config,this.trackDoneOB=xU(t,ex.INIT),this.stopOB=CU(),this.startOB=CU(),"auto"===i.type?this.type="webCodecs":this.type=i.type;let o=CU();oU(this.startOB,yU(0),LF((e=>{let i=this.pipe(t);return o.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),oU(i,nF(this.stopOB),rB((()=>{}),(i=>{t.log.error(i),r.addFailedEvent({key:JW(this.type),error:i}),e>4?this.startOB.error(i):this.startOB.next(e+1)}))),oU(i,rF(1),eB(zU))})),nF(this.stopOB),rB((()=>{t.player.setOutput(),o.next("STARTED")}),(e=>{o.next("FAILED")}),(()=>{r.addSuccessEvent({key:JW(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 pU()((t=>Ab(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(AM){e.log.error(AM),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"}))}},qW={type:"object"},zW=class e{constructor(e){this.core=e,Sb(this,"log"),Sb(this,"contextMap",new Map),Sb(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 qW}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 KW(this.core,r,e);return oU(n.trackDoneOB,rF(1),rB((()=>{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 KW(this.core,e.track,e))}}};Sb(zW,"Name","TRTCAudioDecoder");var YW=zW,XW=class{constructor(){Sb(this,"log"),this.log=_M.createLogger({id:"exp"})}call(e,t){return Ab(this,null,(function*(){return lw(this[e])?this[e](t):Promise.reject(new Ub({code:xb.INVALID_PARAMETER,message:bP({key:IP.API_NOT_EXIST,data:{name:e}})}))}))}enableAudioFrameEvent(e){return Ab(this,null,(function*(){let{trtcInstance:t,enable:i,userId:r,sampleRate:n=48e3,channelCount:o=1,port:s}=e,{audioManager:a}=t.room,{getPCMAbortCtrlMap:c,audioFrameEventConfigMap:l}=a;if(l.set(r,{enable:i,sampleRate:n,channelCount:o,port:s}),i)if("*"===r)t.room.remotePublishedUserMap.forEach((e=>{if(e.remoteAudioTrack.isAvailable){if(c.get(e.userId))return;let i=a.getPCM((e=>{t.emit(WH.AUDIO_FRAME,e)}),e.userId);c.set(e.userId,i)}}));else{if(c.get(r))return;let e=a.getPCM((e=>{t.emit(WH.AUDIO_FRAME,e)}),r);c.set(r,e)}else if("*"===r)t.room.remotePublishedUserMap.forEach((e=>{if(e.remoteAudioTrack.isSubscribed){let{userId:t}=e,i=c.get(t);null==i||i.abort("disable"),c.delete(t)}}));else{let e=c.get(r);null==e||e.abort("disable"),c.delete(r)}}))}};yb([function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return UV(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return iH.call(this,t,n,i,this._name),e.apply(this,n)}))}({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],XW.prototype,"enableAudioFrameEvent",1);var QW=new XW,ZW=vb(Rb(),1),$W=class extends ZW.EventEmitter{constructor(){super(),Sb(this,"states",{}),Sb(this,"permissionChangeHandler"),Sb(this,"log"),this.log=_M.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:null==(e=this.states.camera)?void 0:e.state,microphone:null==(t=this.states.microphone)?void 0:t.state})}}request(e){return Ab(this,null,(function*(){if(this.log.info("request ".concat(e.join(", "))),0===e.length)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach((e=>e.stop()))}))}get(e){return Ab(this,null,(function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info("get ".concat(e," permission state: ").concat(this.states[e].state)),this.states[e].state}catch(Xk){return this.log.error("get ".concat(e," permission failed, error: ").concat(Xk instanceof Error?Xk.message:Xk)),null}}))}destroy(){Object.values(this.states).forEach((e=>{null==e||e.removeEventListener("change",this.permissionChangeHandler)})),this.states={}}},eG=new $W,tG=0,iG=new Set,rG=null;qb("5.13.0-beta.14"),gM.checkStorage();var nG=class e extends Pb.EventEmitter{constructor(t,i){super(),Sb(this,"_room"),Sb(this,"_eventListened",new Set),Sb(this,"_localVideoTrack",null),Sb(this,"_localAudioTrack",null),Sb(this,"_localScreenTrack",null),Sb(this,"_localScreenAudioTrack",null),Sb(this,"_localVideoConfig",null),Sb(this,"_localScreenConfig",null),Sb(this,"_localAudioConfig",null),Sb(this,"_remoteVideoConfigMap",new Map),Sb(this,"_remoteAudioConfigMap",new Map),Sb(this,"_remoteAudioVolumeMap",new Map),Sb(this,"_remoteAudioMuteMap",new Map),Sb(this,"_mediaTrackMap",new WeakMap),Sb(this,"_log",_M.createLogger({id:"t".concat(++tG)})),Sb(this,"_plugins",new Map),Sb(this,"_networkQuality",null),Sb(this,"_speakerId"),Sb(this,"enterRoomParams"),Sb(this,"_enableAutoSwitchWhenRecapturing",!0),this._room=new t(fb({logger:this._log,frameWorkType:e.frameWorkType},i)),this._room.videoDecodeFallbackType=i.videoDecodeFallback,pw(i.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=i.enableAutoSwitchWhenRecapturing),this._log.info("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(SW,i.assetsPath),this._use(fW,i.assetsPath),this._use(RW,i.assetsPath),this._use(YW,i.assetsPath),this._use(jW),i.enableSEI&&kL&&this._use(VW),this._room.on("audio-volume",(e=>{var t,r;!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*(null!=(t=this._localAudioTrack.getInternalAudioLevelAfter3A())?t:this._localAudioTrack.getAudioLevel())),floatVolume:null!=(r=this._localAudioTrack.getInternalAudioLevelAfter3A())?r:this._localAudioTrack.getInternalAudioLevel()}),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(WH.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{this._log.error(new _H({code:dH.OPERATION_FAILED,extraCode:5504,message:e.message,originError:e}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:i}=e;e.emit=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{return i.apply(e,n)}catch(AM){let i=bP({key:IP.CATCH_HANDLER_ERROR,data:{name:t,event:n[0]},addDocLink:!1});return _M.warn("".concat(i,"\n\n").concat(AM.stack)),!1}}})(this,"trtc")}static create(e){}static _create(t,i){!function(){var e;if(cH){cH=!1,5!==_M.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(ok,"/en/index.html")),console.info("* Changelog: ".concat(ok,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),_M.info("TRTC Web SDK Version:",Kb),KO||_M.debug("Build Time:","2025-08-20 12:14:05");let t="UA: ".concat(navigator.userAgent," \nCPU core: ").concat(navigator.hardwareConcurrency,", GPU: ").concat(eM()),i=navigator.deviceMemory;i&&(t+=", minRAM: ".concat(i,"GB")),_M.info(t),_M.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),$O().then((e=>{e&&_M.info(ZO)}))}}();let r=new e(t,i||{});return iG.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){dx(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(WH.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(WH.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().finally((()=>{this.emit(WH.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().finally((()=>{this.emit(WH.ERROR,_H.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(WH.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e;let t=gb(fb({},e),{uplinkRTT:Math.min(e.uplinkRTT,ID),downlinkRTT:Math.min(e.downlinkRTT,ID)});this.emit(WH.NETWORK_QUALITY,t)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{dx(t,t).add("player-state-changed",(i=>{let r=gb(fb({},i),{userId:e.userId});t.kind===Sk.VIDEO&&(r.streamType=fH(t.streamType)),this.emit(t.kind===Sk.AUDIO?WH.AUDIO_PLAY_STATE_CHANGED:WH.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===xb.PLAY_NOT_ALLOWED&&this.emit(WH.AUTOPLAY_FAILED,{userId:t.userId,mediaType:t.strMediaType,resume:()=>t.player.resume()})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{ux(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:r}=i,n=t.audioAvailable,o=t.videoAvailable,{audioAvailable:s,videoAvailable:a}=i;s||this._remoteAudioConfigMap.delete(r),a||this._removeRemoteVideoConfig(r,"main"),i.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),o!==a&&(a?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(a?WH.REMOTE_VIDEO_AVAILABLE:WH.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),n!==s&&(s?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i}),this.emit(s?WH.REMOTE_AUDIO_AVAILABLE:WH.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?WH.REMOTE_VIDEO_AVAILABLE:WH.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))})).add("sei-message",(e=>{this.emit(WH.SEI_MESSAGE,gb(fb({},e),{streamType:fH(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(WH.ERROR,new _H({code:dH.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,i,r,n,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(r=this._networkQuality)?void 0:r.downlinkRTT)||0,ID),upLoss:(null==(n=this._networkQuality)?void 0:n.uplinkLoss)||0,downLoss:(null==(o=this._networkQuality)?void 0:o.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/dP},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)/dP,point2pointDelay:(e.msg_audio_status.uint32_audio_p2p_delay||0)+(e.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:e.msg_audio_status.uint32_audio_cache_ms||0},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],point2pointDelay:(e.uint32_video_p2p_delay||0)+(e.uint32_video_cache_ms||0),jitterBufferDelay:e.uint32_video_cache_ms||0,codec:e.uint32_video_codec})))})))};this.emit(WH.STATISTICS,l)})).add("custom-message",(e=>{this.emit(WH.CUSTOM_MESSAGE,e)})).add("layerData",(e=>this.emit(WH.LAYER_DATA,e))).add("first-video-frame",(e=>{this.emit(WH.FIRST_VIDEO_FRAME,gb(fb({},e),{streamType:fH(e.streamType)}))})).add("audio-frame",(e=>{this.emit(WH.AUDIO_FRAME,e)})),dx(this,pV).add("audioInputAdded",(e=>{this.emit(WH.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(WH.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(WH.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(WH.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>Ab(this,null,(function*(){if(this.emit(WH.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),rG&&rG.deviceId===fD){let e=(yield TV()).find((e=>e.deviceId===fD));e&&rG.groupId!==e.groupId&&(rG=e,this.emit(WH.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>Ab(this,null,(function*(){this.emit(WH.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield TV())[0];if(!t||!rG||rG.groupId===t.groupId)return;let i=rG.deviceId===e.deviceId,r=rG.deviceId===fD&&rG.deviceId===t.deviceId;(i||r)&&(rG=t,this.emit(WH.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})))),dx(this,eG).add("permission-state-change",(e=>{this.emit(WH.PERMISSION_STATE_CHANGE,e)}))}use(e){let t,i;"plugin"in e?(t=e.plugin,i=e.assetsPath):t=e,this._use(t,i)}_use(t,i){if(this._plugins.get(t.Name))return void this._log.warn("duplicate install plugin",t.Name);let r=new t(oW.call(this,{TRTC:e,room:this._room,assetsPath:i,errorModule:{RtcError:_H,ErrorCode:dH,CoreErrorCode:xb,ErrorCodeDictionary:uH}}));this._plugins.set(t.Name,r),r.__v_skip=!0,t.autoStart&&this.startPlugin(t.Name)}enterRoom(t){return Ab(this,null,(function*(){var i,r;this.enterRoomParams=t;let{scene:n="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:a=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!uw(t.proxy)&&t.proxy.turnServer&&(null==(r=(i=this._room).setTurnServer)||r.call(i,t.proxy.turnServer,t.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=a,pw(t.preferHW)&&(this._room.preferHW=t.preferHW),t.playoutDelay&&(this._room.playoutDelay=t.playoutDelay),t.jitterBufferDelay&&(this._room.jitterBufferDelay=t.jitterBufferDelay);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,useH265:t.useH265,keepAlive:t.keepAlive};t.strRoomId&&!t.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(c,n,e.frameWorkType),this._checkTrackToPublish(),kW.start()}))}exitRoom(){return Ab(this,null,(function*(){return yield this._exitRoom()}))}switchRoom(e){return Ab(this,null,(function*(){if(this.room.isSwitchRoomSupported())yield this._room.switchRoom(e);else{yield this.exitRoom();let t=fb(fb({},this.enterRoomParams),e);yield this.enterRoom(t)}}))}switchRole(e,t){return Ab(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(){ux(this),this.removeAllListeners(),this._room.destroy(),iG.delete(this),0===iG.size&&kW.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(),dM.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:i=!0,mute:r,option:n}=t,o=new uB(e._room.audioManager),s={},a={muted:!0};n&&(dw(n.microphoneId)?dw(n.audioTrack)||(s.customSource=n.audioTrack):s.deviceId=n.microphoneId,n&&hw(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),dw(n.profile)||(uw(n.profile)?gk[n.profile]&&o.setProfile(gk[n.profile]):o.setProfile(n.profile)),hw(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),dw(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),dw(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),dw(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl),pw(e._enableAutoSwitchWhenRecapturing)&&(o.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),o.on("5",(t=>{e.emit(WH.ERROR,new _H({code:dH.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(WH.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=_H.convertFrom(t.error)),e.emit(WH.PUBLISH_STATE_CHANGED,gb(fb({},t),{error:i}))})),o.on("6",(()=>{e.emit(WH.ERROR,new _H({code:dH.OPERATION_FAILED,extraCode:5506,message:"audio encode failed"}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),dw(r)||o.setMute(r),dx(o,o).add("player-state-changed",(t=>{e.emit(WH.AUDIO_PLAY_STATE_CHANGED,gb(fb({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localAudioTrack=o,e._localAudioConfig=gb(fb({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:a,track:o}),dM.emit("113",{userId:"",room:e.room})}()}))}updateLocalAudio(e){return Ab(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):dw(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),dw(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),dw(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!dw(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),dw(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Ow(this._localAudioConfig,e)}))}stopLocalAudio(){return Ab(this,null,(function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),dM.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),ux(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null,capture:!0};return function*(){var i;if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:r,publish:n=!0,capture:o=!0,mute:s,option:a}=t,c=new _B(e._room.videoManager),l={},d={};a&&(pw(a.avoidCropping)&&(c.avoidCropping=a.avoidCropping),a.cameraId?l.deviceId=a.cameraId:dw(a.useFrontCamera)?dw(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?Sk.FACING_MODE_USER:Sk.FACING_MODE_ENVIRONMENT,dw(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=gH(a.qosPreference)),dw(a.profile)||(uw(a.profile)?Ek[a.profile]&&c.setProfile(Ek[a.profile]):c.setProfile(a.profile)),dw(a.fillMode)||(d.objectFit=a.fillMode),dw(a.mirror)||(d.mirror=a.mirror),dw(a.small)||(dw(a.smallMode)||(e._room.smallMode=a.smallMode),pw(a.small)&&!1===a.small?c.stopSmall():c.updateSmallConfig(EH(a.small,!0))),dw(a.rotation)||c.setRotation(a.rotation),pw(e._enableAutoSwitchWhenRecapturing)&&(c.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),c.once("first-video-frame",(t=>{e.emit(WH.FIRST_VIDEO_FRAME,gb(fb({},t),{streamType:fH(t.streamType)}))})),c.on("5",(t=>{e.emit(WH.ERROR,new _H({code:dH.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),c.on("2",(t=>{e.emit(WH.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),c.on("4",(t=>{let i;t.error&&(i=_H.convertFrom(t.error)),e.emit(WH.PUBLISH_STATE_CHANGED,gb(fb({},t),{error:i}))})),c.on("6",(()=>{e.emit(WH.ERROR,new _H({code:dH.OPERATION_FAILED,extraCode:5505,message:"video encode failed"}))})),e._listenOutputTrackChanged(c),o?yield c.capture(l):null==(i=c.manager)||i.changeInput(c),dw(s)||(yield c.setMute(s)),dx(c,c).add("player-state-changed",(t=>{e.emit(WH.VIDEO_PLAY_STATE_CHANGED,gb(fb({},t),{userId:"",streamType:"main"}))})),n&&e._room.isJoined&&e._room.publish(c).catch((()=>{})),e._localVideoTrack=c,e._localVideoConfig=gb(fb({},t),{view:r,publish:n,capture:o}),yield e._updateVideoPlayOption({view:r,playOption:d,track:c})}()}))}updateLocalVideo(e){return Ab(this,null,(function*(){var t,i,r;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:n,publish:o,mute:s,capture:a,option:c}=e,l={};if(this._localVideoConfig.capture)!1!==a?null!=c&&c.cameraId?yield this._localVideoTrack.switchDevice(null==c?void 0:c.cameraId):dw(null==c?void 0:c.useFrontCamera)?dw(null==c?void 0:c.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(null==c?void 0:c.videoTrack)):yield this._localVideoTrack.switchDevice(null!=c&&c.useFrontCamera?Sk.FACING_MODE_USER:Sk.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(a){let e={};e.deviceId=(null==c?void 0:c.cameraId)||(null==(t=this._localVideoConfig.option)?void 0:t.cameraId),e.facingMode=null!=c&&c.useFrontCamera||null!=(i=this._localVideoConfig.option)&&i.useFrontCamera?Sk.FACING_MODE_USER:Sk.FACING_MODE_ENVIRONMENT,e.customSource=(null==c?void 0:c.videoTrack)||(null==(r=this._localVideoConfig.option)?void 0:r.videoTrack),yield this._localVideoTrack.capture(e)}c&&(dw(c.profile)||(uw(c.profile)?Ek[c.profile]&&this._localVideoTrack.setProfile(Ek[c.profile]):this._localVideoTrack.setProfile(c.profile),(!c.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(c.cameraId))&&dw(c.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),dw(c.fillMode)||(l.objectFit=c.fillMode),dw(c.mirror)||(l.mirror=c.mirror),dw(c.rotation)||this._localVideoTrack.setRotation(c.rotation),c.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(gH(c.qosPreference)),dw(c.small)||(pw(c.small)&&!c.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(EH(c.small,!0)))),this._room.isJoined&&dw(o)&&this._localVideoConfig.publish&&a&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._room.isJoined&&((null!=o?o:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch((()=>{})):this._room.unpublish(this._localVideoTrack).catch((()=>{}))),dw(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:n,playOption:l,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Ow(this._localVideoConfig,e)}))}stopLocalVideo(){return Ab(this,null,(function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),ux(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:i=null,publish:r=!0,muteSystemAudio:n,option:o}=t,s=new GB(e._room.videoManager);s.on("4",(t=>{let i;t.error&&(i=_H.convertFrom(t.error)),e.emit(WH.PUBLISH_STATE_CHANGED,gb(fb({},t),{error:i}))})),s.once("first-video-frame",(t=>{e.emit(WH.FIRST_VIDEO_FRAME,gb(fb({},t),{streamType:fH(t.streamType)}))})),e._listenOutputTrackChanged(s),"main"===t.streamType&&(s.mediaType=4);let a=null,c={},l={};o&&(dw(o.profile)||(uw(o.profile)?yk[o.profile]&&s.setProfile(yk[o.profile]):s.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),dw(o.fillMode)||(l.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface),o.qosPreference&&(c.contentHint=gH(o.qosPreference)));let d=yield s.capture(c);if(s.mediaTrack.addEventListener(Sk.ENDED,(()=>{e._stopScreenShare(),e.emit(WH.SCREEN_SHARE_STOPPED)})),d.getAudioTracks()[0]&&(a=new JB(e._room.audioManager),yield a.setInputMediaStreamTrack(d.getAudioTracks()[0]),pw(n)&&a.mediaTrack&&(a.mediaTrack.enabled=!n),e._speakerId&&a.setAudioOutput(e._speakerId)),dx(s,s).add("player-state-changed",(t=>{e.emit(WH.VIDEO_PLAY_STATE_CHANGED,gb(fb({},t),{userId:"",streamType:"sub"}))})),r&&e._room.isJoined){let t=[s];a&&(t.push(a),e._checkScreenAudioEchoCancellation(s,a)),e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=s,e._localScreenAudioTrack=a,e._localScreenConfig=gb(fb({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:l,track:s})}()}))}updateScreenShare(e){return Ab(this,null,(function*(){var t;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:i,publish:r,muteSystemAudio:n,option:o}=e,s={};if(o&&(dw(o.fillMode)||(s.objectFit=o.fillMode),o.qosPreference)){let e=gH(o.qosPreference);this._localScreenTrack.setContentHint(e)}if(this._room.isJoined&&!dw(r)){if(r&&!this._localScreenConfig.publish){let e=[this._localScreenTrack];this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._room.publish(...e).catch((()=>{}))}if(this._localScreenConfig.publish&&!r){let e=[this._localScreenTrack];this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._room.unpublish(...e).catch((()=>{}))}}null!=(t=this._localScreenAudioTrack)&&t.mediaTrack&&pw(n)&&(this._localScreenAudioTrack.mediaTrack.enabled=!n),yield this._updateVideoPlayOption({view:i,playOption:s,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Ow(this._localScreenConfig,e)}))}stopScreenShare(){return Ab(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return Ab(this,null,(function*(){let{view:t,userId:i,streamType:r,option:n}=e,o="".concat(i,"_").concat(r);if(this._remoteVideoConfigMap.has(o))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(r));let s=this._room.remotePublishedUserMap.get(i);if(!s)return;let a={},c="main"===r?s.remoteVideoTrack:s.remoteAuxiliaryTrack;c.on("decode-failed",(e=>{this.emit(WH.ERROR,new _H({code:dH.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))})),this._listenOutputTrackChanged(c),n&&(dw(n.fillMode)||(a.objectFit=n.fillMode),dw(n.mirror)||(a.mirror=n.mirror),dw(n.poster)||(a.poster=n.poster),a.canvasRender=n.canvasRender,"main"===r&&!dw(n.small)&&(!s.remoteVideoTrack.isSubscribing&&!s.remoteVideoTrack.isSubscribed&&s.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(o,{config:e}),n&&!dw(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return Ab(this,null,(function*(){var t,i;let{view:r,userId:n,streamType:o,option:s}=e,a="".concat(n,"_").concat(o),c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(n))return;let l={};s&&(dw(s.fillMode)||(l.objectFit=s.fillMode),dw(s.mirror)||(l.mirror=s.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);if("main"===o&&null!=u&&u.muteState.hasVideo&&(d=u.remoteVideoTrack),"sub"===o&&null!=u&&u.muteState.hasAuxiliary&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:h}=c;"main"===o&&s&&!dw(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:h}),Ow(h,e);let p=dw(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=dw(r)?h.view:r,_=dw(null==s?void 0:s.viewRoot)?null==(i=h.option)?void 0:i.viewRoot:s.viewRoot;this._observeView({remoteTrack:d,view:m,receiveWhenViewVisible:p,viewRoot:_})}))}stopRemoteVideo(e){return Ab(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ab(this,null,(function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:n,remoteAuxiliaryTrack:o}=r;"main"===e.streamType&&(n.stop(),t.hasVideo&&i.push(n)),"sub"===e.streamType&&(o.stop(),t.hasAuxiliary&&i.push(o))}for(let e of i)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.delete(e.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)}))}_removeRemoteVideoConfig(e,t){let i="".concat(e,"_").concat(t),r=this._remoteVideoConfigMap.get(i);r&&r.observer&&r.observer.disconnect(),this._remoteVideoConfigMap.delete(i)}muteRemoteAudio(e,t){return Ab(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(AM){throw this._remoteAudioMuteMap.delete(e),AM}}))}setRemoteAudioVolume(e,t){if("*"===e){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach(((e,i)=>this._remoteAudioVolumeMap.set(i,t)));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 Ab(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return Ab(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return Ab(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,i),this._eventListened.add(e),this.listeners(WH.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:e}=this.room.audioManager;e.get("")||e.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return 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{GH.has(e)&&this._log.debug("emit ".concat(e," ").concat(JSON.stringify(i)))}catch(AM){}return super.emit(e,...i)}off(t,i,r){if(this._log.debug("off",t),"*"===t?(this._eventListened.clear(),this.removeAllListeners()):super.off(t,i,r),(t===e.EVENT.AUDIO_FRAME||"*"===t)&&0===this.listeners(e.EVENT.AUDIO_FRAME).length){let{getPCMAbortCtrlMap:e}=this.room.audioManager;e.forEach((e=>{null==e||e.abort("off")})),e.clear()}return this}getAudioTrack(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},i=null,r="main",n=!1;if(uw(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 Ab(this,null,(function*(){(yield TV()).forEach((t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(WH.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),rG=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 Ab(this,null,(function*(){var t;let{userId:i}=e;if(this._remoteAudioConfigMap.has(i))return void this._log.warn("remote audio has already started. userId:".concat(i));let r=this._room.remotePublishedUserMap.get(i);if(!r)return;let n={},o=r.remoteAudioTrack;o.on("decode-failed",(e=>{this.emit(WH.ERROR,new _H({code:dH.OPERATION_FAILED,extraCode:5506,message:"audio decode failed"}))})),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId);try{let r=null!=(t=this._remoteAudioVolumeMap.get(i))?t:this._remoteAudioVolumeMap.get("*"),s=hw(r)?r:100;n.volume=s,this._remoteAudioConfigMap.set(i,e),yield this._room.subscribe(o),oU(xU(o,"decode-failed"),nF(xU(o,ex.INIT)),rB((()=>{this.startPlugin(YW.Name,{track:o,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})}))),yield this._updateAudioPlayOption({playOption:n,track:o}),dM.emit("115",{userId:i,room:this.room}),o.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:o.outMediaTrack,refId:"ra-".concat(i)})}catch(s){throw this._remoteAudioConfigMap.delete(i),s}this._emitTrackEvent(o)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ab(this,null,(function*(){let i=this._room.remotePublishedUserMap.get(e.userId);i&&(i.remoteAudioTrack.stop(),i.muteState.hasAudio&&t&&(yield this._room.unsubscribe(i.remoteAudioTrack)),this._mediaTrackMap.delete(i.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId)),dM.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:"ra-".concat(e.userId)})}))}_enableVideoDecodeFallback(e,t){let i,r=this._room.videoDecodeFallbackType;r&&this._plugins.has("TRTCVideoDecoder")&&(e.log.debug("remote video will fall back when decode failed",e.id),oU(xU(e,"decode-failed"),nF(xU(e,ex.INIT)),nB((()=>{"h265"!==this._room.downlinkVideoCodec&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})})),VF(xU(e,"decode-downgrade-state-changed")),rB((r=>{i=r.state,this.emit(WH.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,gb(fb({},r),{streamType:t,userId:e.userId}))}),(t=>{e.log.error("fallback",t)}),(()=>{"STARTED"===i&&e.log.info("fallback complete")}))))}_updateVideoPlayOption(e){return Ab(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),dw(t)&&n&&n.view&&!kw(i)){let e=Pw(n.view);e.length>0&&(yield r.play(e,i))}if(!dw(t)){let e=Pw(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return Ab(this,arguments,(function(e){var t=this;let{playOption:i={},track:r,prevConfig:n}=e;return function*(){if(!r.isPlayCalled)try{yield r.play(null,i)}catch(Yb){}if(dw(i.muted)||r.setPlayerMute(i.muted),dw(i.volume)||r.setAudioVolume(i.volume/100),r instanceof uB&&r.mediaTrack){let e=!1===i.muted&&!dw(i.volume)&&i.volume>0?"add":"remove";t.room.audioManager.updateAudioReference({type:e,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof QB){let e=i.muted?0:i.volume;if(dw(e))return;t.room.audioManager.updateAudioReference({type:"updateVolume",refId:"ra-".concat(r.userId),volume:i.volume})}}()}))}_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(WH.TRACK,{userId:i,streamType:fH(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),this._checkScreenAudioEchoCancellation(this._localScreenTrack,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(dw(i))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(fH(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||_w(i)&&0===i.length||!r)return null==s||s.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch((()=>{})));let a=o.visibleViewMap||new Map,c=-1;(!s||s.root!==n)&&(null==s||s.disconnect(),a.clear(),s=new IntersectionObserver((e=>{e.forEach((e=>{a.set(e.target,e.isIntersecting),t.log.info("view ".concat(e.target.id," is").concat(e.isIntersecting?"":" not"," visible"))})),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(Pw(i));a.forEach(((e,t)=>{l.has(t)||(s.unobserve(t),a.delete(t))})),l.forEach((e=>{a.set(e,!0),s.observe(e)})),s.takeRecords().forEach((e=>{a.set(e.target,e.isIntersecting)})),o.visibleViewMap=a,o.observer=s}_exitRoom(){return Ab(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(),function(e){let t=sW.get(e);t&&(t.forEach((e=>clearTimeout(e))),sW.delete(e))}(this),this._room.remotePublishedUserMap.forEach((e=>{ux(e.remoteAudioTrack),ux(e.remoteVideoTrack),ux(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return Ab(this,null,(function*(){var e,t;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&&(!1===(null==(t=this._localScreenAudioTrack.trackSettings)?void 0:t.echoCancellation)&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),ux(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_checkScreenAudioEchoCancellation(e,t){return Ab(this,null,(function*(){var i,r;if(!e||!t)return;let n=null==(i=e.trackSettings)?void 0:i.displaySurface;if(!1===(null==(r=t.trackSettings)?void 0:r.echoCancellation)&&("monitor"===n||"browser"===n&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(CM){this._log.warn("start audioProcessor plugin failed: ",CM)}}}))}_onLocalTrackCaptured(e){let{track:t}=e;"audio"===t.kind&&(!rG||mV(rG))&&(this._initActiveSpeaker(),dM.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return Ab(this,null,(function*(){if(rG&&!mV(rG))this.emit(WH.DEVICE_CHANGED,{type:"speaker",action:"active",device:rG});else{let e=yield TV();e[0]&&!mV(e[0])?(rG=e[0],this.emit(WH.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):dM.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:gb(fb({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),FP.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),FP.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return Ab(this,null,(function*(){return this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(t),")")),QW.call(e,fb({trtcInstance:this},t))}))}static setLogLevel(e,t){_M.setLogLevel(e),dw(t)||(t?_M.enableUploadLog():_M.disableUploadLog())}static isSupported(){return QP(e.frameWorkType)}static getPermissions(e){return Ab(this,arguments,(function(e){let{request:t=!0,types:i=["camera","microphone"]}=e;return function*(){t&&(yield eG.request(i).catch((e=>{var t;return _M.error("getPermissions request failed, error: ".concat(null!=(t=null==e?void 0:e.message)?t:e))})));let[e,r]=yield Promise.all([eG.get("camera"),eG.get("microphone")]);return{camera:e,microphone:r}}()}))}static getCameraList(){return gV(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return fV(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return TV(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(t){return Ab(this,null,(function*(){if(!CN||t!==lH.SPEAKER&&t!==lH.HEADSET)(yield TV()).forEach((e=>{e.deviceId===t&&(iG.forEach((i=>{i._setCurrentSpeaker(t),i.emit(WH.DEVICE_CHANGED,{type:"speaker",action:"active",device:e})})),rG=e)}));else{let i=yield e.getMicrophoneList(),r="";if(i.forEach((e=>{e.label===t&&(r=e.deviceId)})),!r)return;iG.forEach((e=>Ab(this,null,(function*(){e._localAudioTrack&&(yield e.updateLocalAudio({option:{microphoneId:r}}))}))))}}))}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:o,version:s,max:a}=e;switch(s&&(UP.version=s),t){case"count":UP.addCount({key:i,useUV:o});break;case"enum":UP.addEnum({key:i,value:r,useUV:o});break;case"number":UP.addNumber({key:i,value:r,split:n,max:a})}}};Sb(nG,"_loggerManager",_M),Sb(nG,"EVENT",WH),Sb(nG,"ERROR_CODE",dH),Sb(nG,"TYPE",lH),Sb(nG,"frameWorkType",30),yb([uW({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"}})})],nG.prototype,"use",1),yb([aW(wH.TRTC.enterRoom),FH("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})),UV((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),uW()],nG.prototype,"enterRoom",1),yb([uW()],nG.prototype,"exitRoom",1),yb([aW(wH.TRTC.switchRoom),uW(),jV()],nG.prototype,"switchRoom",1),yb([aW(wH.TRTC.switchRole),BH("room",{merge:(e,t)=>t}),uW()],nG.prototype,"switchRole",1),yb([uW()],nG.prototype,"destroy",1),yb([aW(wH.TRTC.startLocalAudio),FH("audio",((e,t)=>{let[i]=e,[r]=t;var n,o;return(null==(n=null==i?void 0:i.option)?void 0:n.microphoneId)===(null==(o=null==r?void 0:r.option)?void 0:o.microphoneId)})),uW()],nG.prototype,"startLocalAudio",1),yb([aW(wH.TRTC.updateLocalAudio),BH("audio",{debounce:{delay:200,getKey:()=>"".concat(tG,"-localAudio"),isNeedToDebounce:e=>{var t;return!dw(null==(t=e.option)?void 0:t.captureVolume)}}}),uW()],nG.prototype,"updateLocalAudio",1),yb([HH("audio"),uW()],nG.prototype,"stopLocalAudio",1),yb([aW(wH.TRTC.startLocalVideo),FH("video",((e,t)=>{let[i]=e,[r]=t;var n,o;return(null==(n=null==i?void 0:i.option)?void 0:n.cameraId)===(null==(o=null==r?void 0:r.option)?void 0:o.cameraId)})),uW()],nG.prototype,"startLocalVideo",1),yb([aW(wH.TRTC.updateLocalVideo),BH("video"),uW()],nG.prototype,"updateLocalVideo",1),yb([HH("video"),uW()],nG.prototype,"stopLocalVideo",1),yb([aW(wH.TRTC.startScreenShare),FH("screen",(()=>!0)),uW()],nG.prototype,"startScreenShare",1),yb([aW(wH.TRTC.updateScreenShare),BH("screen"),uW()],nG.prototype,"updateScreenShare",1),yb([uW()],nG.prototype,"stopScreenShare",1),yb([aW(wH.TRTC.startRemoteVideo),FH((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),uW({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],nG.prototype,"startRemoteVideo",1),yb([aW(wH.TRTC.updateRemoteVideo),BH((e=>"v".concat(e.userId).concat(e.streamType))),uW({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],nG.prototype,"updateRemoteVideo",1),yb([aW(wH.TRTC.stopRemoteVideo),UV((e=>function(t){return Ab(this,null,(function*(){if("*"===t.userId){let e=[];return this._room.remotePublishedUserMap.forEach((t=>{this._remoteVideoConfigMap.has("".concat(t.userId,"_main"))&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch((()=>{}))),this._remoteVideoConfigMap.has("".concat(t.userId,"_sub"))&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch((()=>{})))})),Promise.all(e)}return e.call(this,t)}))})),uW({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],nG.prototype,"stopRemoteVideo",1),yb([HH((e=>"v".concat(e.userId).concat(e.streamType)))],nG.prototype,"_stopRemoteVideo",1),yb([aW(...wH.TRTC.muteRemoteAudio),uW({getRemoteId:e=>e})],nG.prototype,"muteRemoteAudio",1),yb([cW(...wH.TRTC.setRemoteAudioVolume),function(e,t){return UV(((i,r)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let s=sW.get(this);s||(s=new Map,sW.set(this,s));let a=t(...n),c=s.get(a);if(!c||c<=0){i.apply(this,n);let t=setTimeout((()=>{var e;null==(e=sW.get(this))||e.delete(a)}),e);s.set(a,t)}else{clearTimeout(c);let t=window.setTimeout((()=>{var e;i.apply(this,n),null==(e=sW.get(this))||e.delete(a)}),e);s.set(a,t)}}))}(200,(e=>e)),uW({getRemoteId:e=>e})],nG.prototype,"setRemoteAudioVolume",1),yb([pW("start"),xV((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),FH(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),uW({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>MP[e.getName()],ignoreLog:e=>"Debug"===e.getName(),ignoreErrorLog:e=>"AudioProcessor"===e.getName()})],nG.prototype,"startPlugin",1),yb([pW("update"),BH(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),{merge:(e,t)=>(Ow(e[1],t[1]),e)}),uW({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>PP[e.getName()]})],nG.prototype,"updatePlugin",1),yb([pW("stop"),HH(((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i})),uW({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>LP[e.getName()]})],nG.prototype,"stopPlugin",1),yb([cW(...wH.TRTC.enableAudioVolumeEvaluation)],nG.prototype,"enableAudioVolumeEvaluation",1),yb([uW()],nG.prototype,"getVideoSnapshot",1),yb([uW()],nG.prototype,"_setCurrentSpeaker",1),yb([FH((e=>"a".concat(e.userId)),(()=>!0))],nG.prototype,"_startRemoteAudio",1),yb([UV((e=>function(t){return Ab(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(gb(fb({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),HH((e=>"a".concat(e.userId)))],nG.prototype,"_stopRemoteAudio",1),yb([HH("room")],nG.prototype,"_exitRoom",1),yb([HH("screen")],nG.prototype,"_stopScreenShare",1),yb([aW(...wH.TRTC.sendSEIMessage),sH({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}})],nG.prototype,"sendSEIMessage",1),yb([aW(wH.TRTC.sendCustomMessage),sH({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],nG.prototype,"sendCustomMessage",1),yb([aW(wH.TRTC.create)],nG,"_create",1);var oG=nG,sG=class{constructor(){Sb(this,"_set",new Set),dM.on(hM.LEAVE_SUCCESS,this.delete,this),dM.on(hM.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,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))}handleSwitchRoomSuccess(e){let{room:t,currentRoomId:i,targetRoomId:r}=e;"rtc"!==t.scene&&(this._set.delete(this.getKey(t.userId,i,t.sdkAppId,t.useStringRoomId)),this._set.add(this.getKey(t.userId,r,t.sdkAppId,t.useStringRoomId)))}};function aG(){return Ab(this,null,(function*(){let e,t;try{let t=yield fV();e=t&&t.length}catch(p){}try{let e=yield gV();t=e&&e.length}catch(p){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:s,isH265EncodeSupported:a,isH265DecodeSupported:c}=this.checkSystemResult.detail,l=EM.basis(),d={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:r,h264Decode:o,vp8Encode:n,vp8Decode:s,h265Encode:a,h265Decode:c},u={browser:l.browser,os:l.os,trtc:d,devices:i},h={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};hx.uploadEvent({log:"trtcstats-".concat(JSON.stringify(u)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(u))),hx.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(h)),userId:this.userId}),WL()}))}var cG=vb(Rb()),lG="1",dG="2",uG="3",hG="4",pG="5",mG="6",_G="7",fG={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,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161},gG=[fG.UPDATE_REMOTE_MUTE_STAT,fG.UPLINK_NETWORK_STATS,fG.USER_LIST_RES,fG.MUTE_RESULT,fG.SERVER_FIRST_PACKAGE_RECEIVED,fG.RECEIVE_CUSTOM_MSG],EG={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",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res"},TG="publish_change",vG="join",yG="leave",SG="quality_report",IG="mute_uplink",AG="publish",RG="publish_state_change",CG="unpublish",bG="subscribe",kG="unsubscribe",DG="subscribe_change",wG="start_publishing",NG="stop_publishing",OG="start_push_user_cdn",MG="stop_push_user_cdn",PG="start_mcu_mix",LG="stop_mcu_mix",xG="start_publish_cdn_stream",VG="update_publish_cdn_stream",UG="stop_publish_cdn_stream",FG="get_user_list",BG="change_role",HG="update_constraint_config",WG="rebuild_pc",GG="join/v2",jG="publish/v2",JG="subscribe/v3",KG="ability_status_report",qG="reconnect",zG="channel_msg",YG="switch_room",XG=new Set;var QG=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],ZG=class extends cG.default{constructor(e){var t,i,r;super(),Sb(this,"room"),Sb(this,"sdkAppId"),Sb(this,"userId"),Sb(this,"userSig"),Sb(this,"url"),Sb(this,"backupUrl"),Sb(this,"destroyed",!1),Sb(this,"_socketInUse"),Sb(this,"_socket"),Sb(this,"_backupSocket"),Sb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[]}),Sb(this,"_currentState","DISCONNECTED"),Sb(this,"_isReconnecting",!1),Sb(this,"_seq",0),Sb(this,"_log"),Sb(this,"_lastMessageTime",-1),Sb(this,"_connectStartTime",-1),Sb(this,"_stopConnectRetry"),Sb(this,"bytesSent",0),Sb(this,"bytesReceived",0),Sb(this,"keepAlive",!1),Sb(this,"signalDomainWhenUnifiedProxy"),Sb(this,"stopKeepAliveTimeout"),Sb(this,"rtt",0),this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let n=(null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0;null!=(r=this.room.joinParams)&&r.keepAlive&&!n&&(n=1),n-XG.size>0&&this.room.enableSPC&&(this.keepAlive=!0,XG.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=_M.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 race(){return this.room.enableSPC&&!this.room.proxy_ws}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);return QG.forEach((i=>{let r=t.get("trtc_".concat(i));r&&(e+="&".concat(i,"=").concat(encodeURIComponent(r)))})),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 isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;return function*(){if(e.isConnected)return Promise.resolve();e._log.info("connect to [".concat(e.url,", ").concat(e.backupUrl,"] ").concat(e.race?"race":"").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive))),e.emitConnectionStateChanged("CONNECTING"),e._connectStartTime=Aw();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 Iw(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?Sk.BACKUP:Sk.MAIN),e.emitConnectionStateChanged("CONNECTED")}()}))}connectWS(e){let{url:t,timeout:i,isMain:r}=e,n=new WebSocket(t);this.bindSocket(n),r?this._socket=n:this._backupSocket=n;let o=-1;return new Promise(((e,t)=>{n.onclose=t,n.onerror=t,n.onopen=()=>e(n),i&&(o=setTimeout((()=>{this.unbindAndCloseSocket(r?Sk.MAIN:Sk.BACKUP),t(new Ub({code:xb.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),i))})).finally((()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)}))}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===Sk.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(Xk){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(Xk){}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(pG,new Ub({code:xb.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(Sk.MAIN),this.unbindAndCloseSocket(Sk.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(pG,new Ub({code:xb.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Fw(e.data);let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values(fG),o=Object.keys(fG)[n.indexOf(i)],s=EG[o]||i;switch(gG.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case fG.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,r.svrTime&&function(e){Fb=e-(new Date).getTime();let t=new Date;t.setTime(e),_M.info("baseTime from server: ".concat(t," offset: ").concat(Fb))}(r.svrTime),this._log.info("ChannelSetup Success ".concat(Aw()-this._connectStartTime)),FP.addSuccessEvent({key:521701,cost:Aw()-this._connectStartTime}),this._connectStartTime=-1,this.emit(lG,{signalInfo:this._signalInfo});else{let e=new Ub({code:xb.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:bP({key:IP.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),FP.addFailedEvent({key:521701,error:e}),this.emit(pG,e)}break;case fG.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(s,{data:t});break;default:this.emit(String(s),{data:t})}}reGetSignalChannelUrl(){return Ab(this,null,(function*(){try{if(!this.room.joinParams)return;qH(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(zb){}}))}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?Sk.MAIN:Sk.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return Ab(this,null,(function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:i,relayInnerIp:r,relayPort:n}=this._signalInfo,{data:o}=yield this.sendWaitForResponse({command:qG,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:EG.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),FP.addSuccessEvent({key:521702,cost:Aw()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(FP.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(zb){this._log.error(zb),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+=Fw(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:o,enableLog:s=!0,addReceiveTime:a=!1}=e;return new Promise(((e,c)=>{let l=()=>{clearTimeout(d),c(new Ub({code:xb.API_CALL_ABORTED,message:"".concat(t," aborted due to connection closed")}))};this.once(_G,l);let d=setTimeout((()=>{this.off(n,u),this.off(_G,l);let e=new Ub({code:xb.API_CALL_TIMEOUT,message:bP({key:IP.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),c(e)}),r),u=t=>{t.data.seq===h&&(clearTimeout(d),this.off(n,u),this.off(_G,l),a&&(t.data.receiveTime=Date.now()),e(t))};this.on(n,u);let h=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,reject:r,error:n}=e;!this.room.isJoined||this.destroyed||n.code===xb.API_CALL_ABORTED?r(n):this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(uG,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),XG.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(Sk.MAIN),this.unbindAndCloseSocket(Sk.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(_G)}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(EG.JOIN_ROOM_RESULT,t)}),1e3*e);let t=e=>{0===e.data.code&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(EG.JOIN_ROOM_RESULT,t))};this.on(EG.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(dG,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(uG):"DISCONNECTED"===e&&this.emit(mG))}};yb([mx({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())}})],ZG.prototype,"connect",1);var $G=vb(Rb()),ej=0,tj=!1,ij=new Set,rj=!1,nj=class{constructor(e){Sb(this,"userId"),Sb(this,"tinyId"),Sb(this,"_sdpSemantics"),Sb(this,"_isUplink"),Sb(this,"_room"),Sb(this,"_log"),Sb(this,"_signalChannel"),Sb(this,"_isErrorObserved",!1),Sb(this,"_waitForPeerConnectionConnectedPromise"),Sb(this,"_waitForPeerConnectionConnectedPromiseReject",null),Sb(this,"_peerConnection",null),Sb(this,"_emitter",new $G.default),Sb(this,"_currentState","DISCONNECTED"),Sb(this,"_isReconnecting",!1),Sb(this,"_reconnectionCount",0),Sb(this,"_reconnectionTimer",-1),Sb(this,"_isFirstConnection",!0),Sb(this,"_prevTime",-1),Sb(this,"_localAddress"),Sb(this,"_remoteAddress"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=_M.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=Aw())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,FP.addSuccessEvent({key:521705,cost:Math.min(Aw()-this._prevTime,3e4)})):this._isReconnecting&&FP.addSuccessEvent({key:521706,cost:Aw()-this._prevTime}),this._prevTime=-1}catch(IM){throw this._isFirstConnection?(this._isFirstConnection=!1,FP.addFailedEvent({key:521705,error:IM})):this._isReconnecting&&this._reconnectionCount>=3&&FP.addFailedEvent({key:521706,error:IM}),IM}}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(),ij.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 Ub({code:xb.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Jk;let e=null;if(this._isUplink){if(!mL()||0===this._peerConnection.getSenders().length)return Jk;e=this._peerConnection.getSenders()[0].transport}else{if(!pL()||0===this._peerConnection.getReceivers().length)return Jk;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:Jk}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(e.target.connectionState,", ICE: ").concat(t,", DTLS: ").concat(i)),e.target.connectionState===Kk.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===Kk.FAILED||e.target.connectionState===Kk.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new Ub({message:r,code:xb.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===Kk.CONNECTED||e.target.connectionState===Kk.COMPLETED)&&(this.logSelectedCandidate(),hx.logSuccessEvent({userId:this._room.userId,eventType:Zk.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(ej=0,tj=!1,rj=!0,ij.add(this)):ij.delete(this),dM.emit(hM.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return Ab(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(nL(t)){let i=e.get(t.localCandidateId),r=e.get(t.remoteCandidateId);i&&(this._log.info("local candidate: ".concat(i.candidateType," ").concat(i.protocol,":").concat(i.ip||i.address,":").concat(i.port," ").concat(i.networkType||""," ").concat("relay"===i.candidateType?"relayProtocol:".concat(i.relayProtocol):"")),this._localAddress="".concat(i.ip||i.address,":").concat(i.port)),r&&(this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port)),this._remoteAddress="".concat(r.protocol,":").concat(r.ip||r.address));break}}))}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this._currentState)return e();this._waitForPeerConnectionConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new Ub({code:xb.API_CALL_ABORTED,message:bP({key:IP.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{dM.off(hM.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new Ub({code:xb.API_CALL_TIMEOUT,message:"connection timeout"});var i;ej+=1,i=this._signalChannel.isConnected,ej>2&&!tj&&0===ij.size&&i&&(this._log.warn("firewall restriction"),tj=!0,this._emitter.emit("firewall-restriction")),t(e)}),dD);dM.on(hM.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(uG,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Yk()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new Ub({code:this._isUplink?xb.UPLINK_RECONNECTION_FAILED:xb.DOWNLINK_RECONNECTION_FAILED,message:bP({key:this._isUplink?IP.UPLINK_RECONNECTION_FAILED:IP.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(uG,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)}};yb([qV(521712,!1)],nj.prototype,"setOffer",1),yb([qV(521713,!1)],nj.prototype,"setAnswer",1);var oj=vb(Mb()),sj=function(e){return oj.default.parse(e)},aj=function(e){return oj.default.write(e)};function cj(e){return Object.keys(e).filter((t=>e[t]))}var lj=class e extends nj{constructor(e){super(gb(fb({},e),{isUplink:!1})),Sb(this,"_flag",0),Sb(this,"isRobot",!1),Sb(this,"role","anchor"),Sb(this,"remoteAudioTrack"),Sb(this,"remoteVideoTrack"),Sb(this,"remoteAuxiliaryTrack"),Sb(this,"ssrc",{audio:0,video:0,auxiliary:0}),Sb(this,"_isSDPExchanging",!1),Sb(this,"_videoCodec"),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new QB(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new ZB(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new $B(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":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}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 Dw(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===Sk.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let t=e.streams[0],{track:i}=e,r=t.id===Pk?Sk.MAIN:Sk.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=Sk.AUDIO;i.kind===Sk.VIDEO&&(n=r===Sk.MAIN?Sk.VIDEO:Sk.AUXILIARY);let o=this.remoteAudioTrack;n===Sk.VIDEO?o=this.remoteVideoTrack:n===Sk.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}addRRTRLine(e){let t=e.split("\r\n"),i=new Map;t.forEach(((e,r)=>{/^a=rtcp-fb:/.test(e)&&t[r+1]&&!/^a=rtcp-fb:/.test(t[r+1])&&i.set(r+1,"".concat(e.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))}));let r=[...i];for(let n=0;n<r.length;n++){let[e,i]=r[n];t.splice(e+n,0,i)}return t.join("\r\n")}addSPSDescription(e){let t=sj(e);return t.media.forEach((e=>{e.type===Sk.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),aj(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=sj(e);return i.media.forEach((e=>{e.ext&&(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),aj(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return Ab(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===Kk.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===Kk.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(t," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else this.initialize(),yield this.connect(e)}catch(Yb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Yb.message," ").concat(JSON.stringify(this.muteState))),new Ub({code:xb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Yb}}))}unsubscribe(e){return Ab(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=fb({},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(cj(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=kG,n=EG.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=DG,n=EG.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 Ub({code:i.code,message:bP({key:IP.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(t),yield e.waitForPeerConnectionConnected()}catch(Xk){throw e.closePeerConnection(!0),Xk}}()}))}exchangeSDP(e){return Ab(this,null,(function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:i}=this._peerConnection.localDescription,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:bG,commandDesc:"exchange sdp",data:r,responseCommand:EG.SUBSCRIBE_RESULT,timeout:tD});if(!this._peerConnection){let e=new Ub({code:xb.INVALID_OPERATION,message:bP({key:IP.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(Xk){throw this._isSDPExchanging=!1,Xk}}))}createOffer(){return Ab(this,null,(function*(){let e={voiceActivityDetection:!1};fL()&&this._sdpSemantics===iD?(this._peerConnection.addTransceiver(Sk.AUDIO,{direction:Ik.RECVONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Ik.RECVONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Ik.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield XP();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=sj(e);return t.media.forEach((e=>{var t,i;if(e.type===Sk.VIDEO){let r=new Set;e.rtp.forEach((e=>{let{payload:t,codec:i}=e;return"H264"===i&&r.add(t)})),e.fmtp.forEach((e=>{let{payload:t,config:i}=e,n=i.match(/apt=(\d+)/);n&&n[1]&&r.has(Number(n[1]))&&r.add(t)}));let n=e=>{let{payload:t}=e;return!r.has(t)};e.rtp=e.rtp.filter(n),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=null==(i=e.payloads)?void 0:i.split(" ").filter((e=>!r.has(Number(e)))).join(" ")}})),aj(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=sj(e);return t.media.forEach((e=>{e.type===Sk.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),aj(t)}(t.sdp),this._sdpSemantics===iD&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)}))}onSubscribeResult(e){return Ab(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===nD)throw new Ub({code:xb.NOT_SUPPORTED_H264,message:bP({key:IP.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new Ub({code:t,message:bP({key:IP.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(CM){throw this._log.error(CM),CM}}))}updateSSRC(e){try{sj(e).media.forEach((e=>{if(e.ssrcs)if(e.type===Sk.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Pk)}));t&&(this.ssrc.audio=Number(t.id))}else{let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Pk)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Lk)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(Xk){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return Ab(this,null,(function*(){if(!(Ib(e.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(Xk){let t=aw(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}};yb([UV((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 Ub({code:xb.API_CALL_ABORTED,message:bP({key:IP.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],lj.prototype,"subscribe",1),yb([qV(521717,!1)],lj.prototype,"unsubscribe",1),yb([xV(nj.prototype.afterConnect),LV(nj.prototype.beforeConnect)],lj.prototype,"connect",1);var dj=lj,uj={voiceActivityDetection:!1},hj=class e extends nj{constructor(e){super(gb(fb({},e),{isUplink:!0})),Sb(this,"localMainAudioTrack",null),Sb(this,"localMainVideoTrack",null),Sb(this,"localAuxAudioTrack",null),Sb(this,"localAuxVideoTrack",null),Sb(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),Sb(this,"_isPublishingAux",!1),Sb(this,"_publishingLocalAudioTrack"),Sb(this,"_publishingLocalVideoTrack"),Sb(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),Sb(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(_L()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(i=o[2])||!i.track),n.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((e=>{e.track&&(e.track.kind===Sk.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return Ab(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(),fL()?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 Ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n,isAuxiliary:o}=e;return function*(){t._log.info("publish by transceiver");let e=new MediaStream,s=null==r?void 0:r.outMediaTrack,a=null==i?void 0:i.outMediaTrack;a&&e.addTrack(a),s&&e.addTrack(s);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||Sk.AUDIO,{direction:Ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?Sk.VIDEO:s||Sk.VIDEO,{direction:Ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||Sk.VIDEO,{direction:Ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||Sk.VIDEO,{direction:Ik.SENDONLY,streams:[e]}),yield t.connect();else{let e=[];if(a&&(c[0].sender.track||e.push(0),yield c[0].sender.replaceTrack(a),yield t.setBandwidth({bandwidth:(null==i?void 0:i.profile.bitrate)||40,type:Sk.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:Sk.VIDEO,videoType:o?Sk.AUXILIARY:Sk.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:Sk.VIDEO,videoType:Sk.SMALL}),e.push(2))}yield t.setTransceiverDirection(Ik.SENDONLY,e),yield t.doPublishChange(),null==r||r.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),null==r||r.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()}))}publishByAddTrack(e){return Ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n}=e;return function*(){t._log.info("publish by addtrack");let e=null==r?void 0:r.outMediaTrack,o=null==i?void 0:i.outMediaTrack;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return i&&o&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(r)));let s=new MediaStream;if(o&&s.addTrack(o),e&&s.addTrack(e),o&&t._peerConnection.addTrack(o,s),e&&(t._peerConnection.addTrack(e,s),n)){let e=new MediaStream;e.addTrack(n),t._peerConnection.addTrack(n,e)}yield t.connect()}()}))}enableSmall(e){return Ab(this,null,(function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(Ik.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Ik.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return Ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!_L())return i&&i.outMediaTrack&&!r&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):r&&r.outMediaTrack&&!i&&t.localMainAudioTrack?(yield t.removeTrack(r),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),void t.emitConnectionStateChangedEvent("DISCONNECTED",r));let e=r&&r===t.localAuxVideoTrack,n=null==r?void 0:r.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localAuxAudioTrack&&!t.localMainAudioTrack&&(yield o[0].replaceTrack(null),s.push(0))),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=gb(fb({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=gb(fb({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.setTransceiverDirection(Ik.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Ab(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:RG,data:t,responseCommand:EG.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:CG,commandDesc:"unpublish",responseCommand:EG.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===xb.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),IL){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:HG,data:this._mediaSettings,responseCommand:EG.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return Ab(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Sk.AUXILIARY:Sk.MAIN," stream")),fL()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return Ab(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Sk.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),1===n&&null!=(i=this.localMainVideoTrack)&&i.small&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Ik.INACTIVE&&(yield this.setTransceiverDirection(Ik.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return Ab(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;_L()&&this._peerConnection.getTransceivers().findIndex((e=>"stopped"===e.direction))>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let i=this._peerConnection.getSenders().find((e=>e.track&&e.track.kind===t.kind));if(i&&i.track){this._log.warn("sender already exists, remove sender first");let e=i.track;this.removeSender(i),yield this.updateOffer("remove",e)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===Sk.VIDEO&&e instanceof _B&&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===rD||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=sj(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===Sk.VIDEO)return!0;return!1}removeSender(e){let t=null;_L()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&lw(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return Ab(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?Sk.AUXILIARY:Sk.MAIN," stream")),fL()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return Ab(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Sk.AUDIO)yield i[0].sender.replaceTrack(null);else{let r=t?3:1;yield i[r].sender.replaceTrack(null),1===r&&e.small&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Ik.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return Ab(this,null,(function*(){if(!wN)return;let i=!1,r=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let n=this._peerConnection.getTransceivers();if(t.forEach((t=>{n[t].direction!==e&&(n[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this.setOffer(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(Ik.INACTIVE,"|").concat(Ik.RECVONLY,"|").concat(Ik.SENDONLY,")")))&&o++,t.includes(o)){if(e===Ik.INACTIVE&&i.includes("a=".concat(Ik.RECVONLY)))return r=!0,"a=".concat(e);if(e===Ik.SENDONLY&&i.includes("a=".concat(Ik.INACTIVE)))return r=!0,"a=".concat(Ik.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:s}))}))}removeTrackBySender(e){return Ab(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===Sk.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let t=this._peerConnection.getSenders().find((t=>t.track===e.outMediaTrack));t&&(this.removeSender(t),e.kind===Sk.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===Sk.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return Ab(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=fL()?e.kind===Sk.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?Sk.AUXILIARY:Sk.MAIN," stream")),e.kind===Sk.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===Sk.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack)),!0}))}updateOffer(e,t){return Ab(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(uj);wN&&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===Sk.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:r,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(n.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:TG,data:n,responseCommand:EG.UPDATE_OFFER_RESULT,timeout:eD,commandDesc:"update offer"}),{code:s,message:a}=o.data;0!==s&&this.checkPublishResultCode(s,a),yield this.acceptAnswer(o.data.data),i.sdp&&this.updateSSRC(i.sdp)}catch(AM){throw this._log.error(AM),AM}}))}setBandwidth(e){return Ab(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!yL())return o?r===Sk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(fL()){let t=0;r===Sk.VIDEO&&(t=n===Sk.SMALL?2:n===Sk.AUXILIARY?3:1),e=s[t]}else e=s.find((e=>e.track&&e.track.kind===r));if(e){let s=e.getParameters();(!s.encodings||0===s.encodings.length)&&(s.encodings=[{}]),s.encodings[0].maxBitrate=1e3*i;try{return yield e.setParameters(s),t._log.info("".concat(n||"").concat(r," bandwidth ").concat(i," kbps")),o}catch(a){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(a)),o)return r===Sk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";wN&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===Sk.SMALL?n=1:i===Sk.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(o+=1,o===n?"".concat(e,"b=").concat(r,":").concat(t,"\r\n"):e)))}updateAudioBandwidthRestriction(e,t){let i="AS";return wN&&(i="TIAS",t*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,"m=audio $1\r\nc=IN $2\r\nb=".concat(i,":").concat(t,"\r\n"))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return Ab(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(zb){throw this.closePeerConnection(!0),this.uninstallEvents(),zb}}))}exchangeSDP(){return Ab(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(zb){throw zb}}))}createOffer(){return Ab(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(uj);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(zb){throw zb}}))}doExchangeSDP(){let e={command:AG,responseCommand:EG.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof GB||this.localAuxVideoTrack instanceof GB,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=sj(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),aj(r)}acceptAnswer(e){return Ab(this,null,(function*(){var t,i,r,n,o;try{let s;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let e=(null==(t=this._publishingLocalVideoTrack)?void 0:t.profile.bitrate)||(null==(i=this.localMainVideoTrack)?void 0:i.profile.bitrate),o=(null==(r=this._publishingLocalAudioTrack)?void 0:r.profile.bitrate)||(null==(n=this.localMainAudioTrack)?void 0:n.profile.bitrate);if(e){let t=this._isPublishingAux?Sk.AUXILIARY:Sk.BIG;s=yield this.setBandwidth({bandwidth:e,type:Sk.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:Sk.AUDIO,sdp:s}))}if(s=this.removeVideoOrientation(e.sdp),null!=(o=this._publishingLocalVideoTrack)&&o.small){let{smallStreamConfig:e}=this._room;s=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:Sk.VIDEO,videoType:Sk.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this.setAnswer(a),this._log.debug("accepted answer: ".concat(s))}catch(s){throw this._log.error("failed to accept remote answer ".concat(s)),s}}))}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(IG,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return Ab(this,null,(function*(){if(!(Ib(e.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:CG,responseCommand:EG.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(Xk){let t=aw(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)&&dM.emit(hM.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{sj(e).media.forEach(((e,t)=>{if(e.type===Sk.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===rD&&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(Xk){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Sk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Sk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Sk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Sk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Sk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===nD?(this._log.error(AP.NOT_SUPPORTED_H264ENCODE),new Ub({code:xb.NOT_SUPPORTED_H264,message:bP({key:IP.NOT_SUPPORTED_H264ENCODE})})):new Ub({code:xb.UNKNOWN,message:bP({key:IP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:EG.PUBLISH_RESULT,code:e,message:t}})})}};yb([UV((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 Ub({code:xb.API_CALL_ABORTED,message:bP({key:IP.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],hj.prototype,"publish",1),yb([qV(521715,!1)],hj.prototype,"unpublish",1),yb([xV(nj.prototype.afterConnect),LV(nj.prototype.beforeConnect)],hj.prototype,"connect",1);var pj=hj,mj=class{constructor(e,t){this.room=e,Sb(this,"_log"),Sb(this,"_prevReportTime",0),Sb(this,"_prevReport",{}),Sb(this,"_prevStats",null),Sb(this,"_prevEncoderImplementation",""),Sb(this,"_prevAuxEncoderImpl",""),Sb(this,"_prevQualityLimitationReason",""),Sb(this,"_prevAuxQualityLimitationReason",""),Sb(this,"_prevDecoderImplementationMap",new Map),Sb(this,"_decodeMap",new Map),Sb(this,"totalBytesSent",0),Sb(this,"totalBytesReceived",0),Sb(this,"_spcStats",null),this._log=t}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return Ab(this,null,(function*(){var t;let i={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},r=e.getPeerConnection(),n=e.getSSRC();if(r)try{if((this._spcStats||(yield r.getStats())).forEach((t=>{var r,o,s;let a,c;if("outbound-rtp"===t.type)if((t.mediaType||t.kind)===Sk.VIDEO){if(t.ssrc===n.video?(a=Sk.VIDEO,c=e.localMainVideoTrack):t.ssrc===n.small?a=Sk.SMALL:t.ssrc===n.auxiliary&&(c=e.localAuxVideoTrack,a=Sk.AUXILIARY),!a)return;if(i[a].bytesSent=t.bytesSent,i[a].packetsSent=t.packetsSent,i[a].framesEncoded=t.framesEncoded,dw(t.keyFramesEncoded)||(i[a].keyFramesEncoded=t.keyFramesEncoded),dw(t.nackCount)||(i[a].nackCount=t.nackCount),dw(t.pliCount)||(i[a].pliCount=t.pliCount),dw(t.retransmittedPacketsSent)||(i[a].retransmittedPacketsSent=t.retransmittedPacketsSent),dw(t.totalEncodeTime)||(i[a].totalEncodeTime=t.totalEncodeTime),dw(t.totalPacketSendDelay)||(i[a].totalPacketSendDelay=t.totalPacketSendDelay),!dw(t.encoderImplementation)&&(a===Sk.VIDEO&&this._prevEncoderImplementation!==t.encoderImplementation||a===Sk.AUXILIARY&&this._prevAuxEncoderImpl!==t.encoderImplementation)){let i=2,r=this._prevEncoderImplementation;a===Sk.AUXILIARY&&(i=7,r=this._prevAuxEncoderImpl),dM.emit("262",{userId:e.userId,streamType:i,prevImplementation:r,implementation:t.encoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientEncoder}),this[a===Sk.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=t.encoderImplementation,this._log.info("".concat(a===Sk.AUXILIARY?"aux ":"","encoderImplementation change to ").concat(t.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(t.powerEfficientEncoder))}t.ssrc===n.video?!dw(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),dM.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&&!dw(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),dM.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(o=e.localAuxVideoTrack)?void 0:o.isQosClearFirst}),this._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else i.audio.bytesSent=t.bytesSent,i.audio.packetsSent=t.packetsSent;else"candidate-pair"===t.type?nL(t)&&(this.totalBytesSent=t.bytesSent,hw(t.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*t.currentRoundTripTime))):"media-source"===t.type&&(t.kind===Sk.AUDIO?(i.audio.audioLevel=t.audioLevel||0,i.audio.totalAudioEnergy=t.totalAudioEnergy||0,t.echoReturnLoss,t.totalSamplesDuration&&(i.audio.totalSamplesDuration=t.totalSamplesDuration)):t.kind===Sk.VIDEO&&(t.trackIdentifier===e.getVideoTrackId(Sk.VIDEO)?i.video.fpsCapture=t.framesPerSecond:t.trackIdentifier===e.getVideoTrackId(Sk.AUXILIARY)?i.auxiliary.fpsCapture=t.framesPerSecond:i.small.fpsCapture=t.framesPerSecond));if(!dw(t.audioLevel)&&null!=(s=e.localMainAudioTrack)&&s.mediaTrack&&t.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(i.audio.audioLevel=t.audioLevel||0),!dw(t.frameWidth)){let r=Sk.SMALL;t.trackIdentifier===e.getVideoTrackId(Sk.VIDEO)||t.ssrc===n.video?r=Sk.VIDEO:(t.trackIdentifier===e.getVideoTrackId(Sk.AUXILIARY)||t.ssrc===n.auxiliary)&&(r=Sk.AUXILIARY),i[r].frameWidth=t.frameWidth,i[r].frameHeight=t.frameHeight,i[r].framesSent=t.framesSent}})),e.localMainAudioTrack){let t=e.localMainAudioTrack.getInternalAudioLevel(),r=e.localMainAudioTrack.getInternalAudioLevelAfter3A();i.audio.audioCaptureEnergyAfter3a=r,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===Sk.AUDIO?(e.localMainAudioTrack&&(e.localMainAudioTrack.stat=i[t]),e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=i[t])):t===Sk.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=i[t]):t===Sk.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=i[t])}))}catch(Yb){this._log.warn("failed to getStats on sender connection ".concat(Yb))}return 0===i.rtt&&(i.rtt=(null==(t=this.room.networkQuality)?void 0:t.uplinkRTT)||0),i}))}getReceiverStats(e){return Ab(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,p2pDelay:0,codec:""},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""}},o=e.getPeerConnection();if(o)try{let{ssrc:r}=e,{muteState:s,subscribeState:a}=e;(this._spcStats||(yield o.getStats())).forEach((t=>{var i,o;if("codec"===t.type&&this._decodeMap.set(t.id,t),"inbound-rtp"===t.type){let c=(t.mediaType||t.kind)===Sk.AUDIO;if(c){if(t.ssrc!==r.audio||!s.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),t.silentConcealedSamples&&(n.audio.silentConcealedSamples=t.silentConcealedSamples);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(wN&&0===t.bytesReceived)return;let c;t.ssrc===r.video&&s.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,e.videoCodec=pP[null==(i=this._decodeMap.get(t.codecId))?void 0:i.mimeType.split("/")[1]]||"h264",n.video.codec=e.videoCodec,c=e.remoteVideoTrack,s.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,"(").concat(e.videoCodec,") HWDecoder: ").concat(t.powerEfficientDecoder)),dM.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&&s.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,c=e.remoteAuxiliaryTrack,n.auxiliary.p2pDelay=c.stat.end2EndDelay,n.hasAuxiliary=!0,n.video.codec=(null==(o=this._decodeMap.get(t.codecId))?void 0:o.mimeType.split("/")[1].toLowerCase())||"h264"),c&&(c.stat.packetsReceived=t.packetsReceived,c.stat.bytesReceived=t.bytesReceived,c.stat.packetsLost=t.packetsLost,c.stat.framesReceived=t.framesReceived,c.stat.framesDecoded=t.framesDecoded,t.jitterBufferDelay&&(c.stat.jitterBufferDelay=Math.floor(t.jitterBufferDelay/t.jitterBufferEmittedCount*1e3)),n.video.p2pDelay=c.stat.end2EndDelay)}t.jitterBufferDelay&&(c?(n.audio.totalJitter=t.jitterBufferDelay,n.audio.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.video&&s.hasVideo?(n.video.totalJitter=t.jitterBufferDelay,n.video.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.auxiliary&&s.hasAuxiliary&&(n.auxiliary.totalJitter=t.jitterBufferDelay,n.auxiliary.totalJitterCount=t.jitterBufferEmittedCount))}else"candidate-pair"===t.type&&nL(t)&&(this.totalBytesReceived=t.bytesReceived,hw(t.currentRoundTripTime)&&(n.rtt=Math.floor(1e3*t.currentRoundTripTime)));dw(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)),!dw(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),dw(null==(t=e.remoteVideoTrack.player.stat)?void 0:t.fps)||(n.video.fpsRender=e.remoteVideoTrack.player.stat.fps),dw(null==(i=e.remoteAuxiliaryTrack.player.stat)?void 0:i.fps)||(n.auxiliary.fpsRender=e.remoteAuxiliaryTrack.player.stat.fps)}catch(CM){this._log.warn("failed to getStats on receiver connection ".concat(CM))}return 0===n.rtt&&(n.rtt=(null==(r=this.room.networkQuality)?void 0:r.uplinkRTT)||0),n}))}getStats(e,t){return Ab(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=Aw(),n=yield e.getStats(),o=Aw();o-t>2e3&&this._log.warn("getStats cost ".concat(o-t,"ms"));let s=[],a=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec"]);n.forEach((e=>a.has(e.type)&&s.push(e))),this._spcStats=s}e&&(i=yield this.getSenderStats(e));for(let[e,n]of t){let e=yield this.getReceiverStats(n);r.push(e)}return{senderStats:i,receiverStats:r}}))}getDifferenceValue(e,t){if(DV(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r}=e;var n,o,s;if(!DV(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*dP,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*dP),t.senderStats.audio.audioCaptureEnergyAfter3a&&(e.uint32_audio_capture_energy_after3a=t.senderStats.audio.audioCaptureEnergyAfter3a*dP),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 a=null==(n=Qx())?void 0:n.playoutStats;a&&(i.msg_device_info.uint32_audio_play_cost=a.totalFramesDuration);let{statInterval:c}=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(xk)),n=i?i.duration:0,o={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.video.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.video.totalJitter,uint32_video_cache_ms_count:e.video.totalJitterCount,uint32_video_p2p_delay:e.video.p2pDelay,uint32_video_codec:e.video.codec};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=r.get("".concat(e.userId,"_").concat(Vk)),n=i?i.duration:0,o={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.auxiliary.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.auxiliary.totalJitter,uint32_video_cache_ms_count:e.auxiliary.totalJitterCount,uint32_video_p2p_delay:e.auxiliary.p2pDelay,uint32_video_codec:e.video.codec};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let l=this._prevReport,d=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&&l.msg_up_stream_info.msg_audio_status){let e=l.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/c),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}null!=(o=l.msg_device_info)&&o.uint32_audio_capture_cost?i.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(l.msg_device_info.uint32_audio_capture_cost,i.msg_device_info.uint32_audio_capture_cost)/c):delete i.msg_device_info.uint32_audio_capture_cost}let u=l.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=u.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 s=this.getDifferenceValue(r,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*s/c),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)/c),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_codec_fps)/c),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),dw(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),dw(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),dw(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),dw(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),dw(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/c)),dw(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/c))}));let h=l.msg_down_stream_info;i.msg_down_stream_info=i.msg_down_stream_info.filter((e=>h.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid))));let p=i.msg_down_stream_info;return p.forEach((e=>{let t=h.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(DV(e.msg_audio_status)||DV(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 s=this.getDifferenceValue(r.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*s/c),i.uint32_audio_total_bitrate=Math.round(8*s/c)}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,s=t.uint32_video_receive_fps,a=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/c);let d=this.getDifferenceValue(s,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/c),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(a,e.uint32_video_dec_fps)/c);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}))}})),null!=(s=l.msg_device_info)&&s.uint32_audio_play_cost?i.msg_device_info.uint32_audio_play_cost=2*Math.floor(this.getDifferenceValue(l.msg_device_info.uint32_audio_play_cost,i.msg_device_info.uint32_audio_play_cost)/c):delete i.msg_device_info.uint32_audio_play_cost,d&&t.receiverStats.forEach((e=>{if(e.audio.concealedSamples&&e.audio.totalSamplesReceived){let t=d.receiverStats.find((t=>t.userId===e.userId));if(t&&t.audio.concealedSamples&&t.audio.totalSamplesReceived){let i=(e.audio.silentConcealedSamples||0)-(t.audio.silentConcealedSamples||0),r=e.audio.concealedSamples-t.audio.concealedSamples,n=e.audio.totalSamplesReceived-t.audio.totalSamplesReceived,o=Math.floor((r-i)/n*1e3*c);if(o>1e3*c/5){let t=p.find((t=>t.msg_user_info.str_identifier===e.userId));t&&(t.msg_audio_status.uint32_audio_block_time=o)}}}})),i}getStatsReport(e){return Ab(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,uint32_audio_capture_energy_after3a:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield t.getStats(i,r);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:n}),t._prevReportTime=Date.now(),e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},_j=vb(Rb());function fj(e){return new Promise((t=>Ab(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(Yb){}clearTimeout(i);let o=function(e){let t={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let i=performance.getEntriesByType("resource").reverse();for(let r of i)if(r.name===e){let e=Math.round(r.duration),i=Math.max(Math.round(r.domainLookupStart-r.startTime),0),n=r.redirectStart>0?Math.max(Math.round(r.redirectEnd-r.redirectStart),0):0,o=r.fetchStart>0?Math.max(Math.round(r.domainLookupStart-r.fetchStart),0):0,s=Math.round(r.domainLookupEnd-r.domainLookupStart),a=Math.round(r.requestStart-r.secureConnectionStart),c=Math.round(r.secureConnectionStart-r.connectStart),l=Math.round(r.responseStart-r.requestStart),d=Math.round(r.responseEnd-(r.responseStart||r.startTime));t=gb(fb({},t),{totalCost:e,local:i,redirect:n,httpCache:o,dns:s,tcp:c,tls:a,request:l,response:d});break}}catch(i){}return t}(n);0===o.totalCost&&(o.totalCost=Date.now()-r),t(o)}))))}var gj=class e extends _j.default{constructor(e){let{signalChannel:t,room:i}=e;super(),Sb(this,"_room"),Sb(this,"_signalChannel"),Sb(this,"_log"),Sb(this,"uplinkRTT",0),Sb(this,"uplinkLoss",0),Sb(this,"downlinkRTT",0),Sb(this,"downlinkLoss",0),Sb(this,"pingResults",{}),Sb(this,"_downlinkPrevStatMap",new Map),Sb(this,"_downlinkLossAndRTTMap",new Map),Sb(this,"_interval",-1),Sb(this,"_uplinkNetworkQuality",0),Sb(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=_M.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(EG.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(dG,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,i;if(0!==e.data.code)return;let r=e.data.data;if(r.delay&&this.updateDelay(r.delay),this._room.signalChannel&&r.wsRtt&&(this._room.signalChannel.rtt=r.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);let n=null==(i=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:i.getPeerConnection();if(n&&this.isPeerConnectionDisconnected(n))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);let o=r.expectAudPkg+r.expectVidPkg,s=r.recvAudPkg+r.recvVidPkg,a=o-s;0===o&&0===s||(this.uplinkLoss=a<=0?0:Math.round(a/o*100),this.uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return Ab(this,null,(function*(){if(0===this._room.remotePublishedUserMap.size)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],t=e.filter((e=>{var t;return(null==(t=e.getPeerConnection())?void 0:t.connectionState)===Kk.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let n=0;n<t.length;n++){let e=t[n].getPeerConnection();if(!e)return;let{rtt:i,totalPacketsLost:r,totalPacketsReceived:o}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o});continue}let s=0,a=this._downlinkPrevStatMap.get(e),c=r-a.totalPacketsLost,l=o-a.totalPacketsReceived;s=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:s,userId:t[n].getUserId(),audioDelay:t[n].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[n].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach((e=>{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return 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 Ab(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!pL())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&&hw(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===Sk.AUDIO||e.mediaType===Sk.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return 0===t.rtt&&(t.rtt=this.uplinkRTT),t}catch(bM){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){"DISCONNECTED"===e.state?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):"CONNECTED"===e.state&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(e){let{state:t}=e;"DISCONNECTED"===t?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):"CONNECTED"===t&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==Kk.DISCONNECTED&&e.connectionState!==Kk.FAILED&&e.connectionState!==Kk.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){-1===this._interval?(this._log.debug("start network quality calculating"),this._interval=sx.run("ric",(()=>{var t;this.handleDownlinkNetworkQuality();let i=[...this._downlinkLossAndRTTMap.values()];dM.emit(hM.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=gb(fb({},n),{pingResults:this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold?this.pingResults:{}})),this.emit(e.EVENT_NETWORK_QUALITY,n);let o=Date.now();if(r&&(this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold)&&o-e.lastPingTime>1e3*r.interval){e.lastPingTime=Date.now();let t=r.domain.map((e=>fj(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=o,this.pingResults.data=e,e.forEach((e=>{FP.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&&(sx.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach((e=>{let{srcTinyId:i,videoDelay:r,audioDelay:n}=e,o=t.get(i);if(o){let e=this._room.remotePublishedUserMap.get(o);null==e||e.setDelay({videoDelay:r,audioDelay:n})}}))}};Sb(gj,"EVENT_NETWORK_QUALITY","0"),Sb(gj,"lastPingTime",0);var Ej=gj;var Tj=class{constructor(e){Sb(this,"_frameWorkType"),Sb(this,"_component"),Sb(this,"_language"),Sb(this,"connectionType"),Sb(this,"_room"),Sb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0}),Sb(this,"_keyPrefix"),Sb(this,"_log"),Sb(this,"_intervalId"),Sb(this,"_firstPublishedUserList"),Sb(this,"_networkQuality"),Sb(this,"_basicInfo"),Sb(this,"_pathJoinRoom"),Sb(this,"_pathLeaveRoom"),Sb(this,"_pathMainVideoMap"),Sb(this,"_pathMainAudioMap"),Sb(this,"_pathAuxiliaryMap"),Sb(this,"_remoteStreamStatMap"),Sb(this,"_localStreamStat"),Sb(this,"_eventMap",new Map),Sb(this,"_captureCostSum",0),Sb(this,"_captureCostCount",0),Sb(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=_M.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&lw(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];let o=t.apply(i,r);return Ew(o)?o.catch((e=>_M.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(Xk){_M.error("".concat(t.name,"() error observed ").concat(Xk))}}}({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:Kb,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,$O().then((e=>{this._basicInfo.string_os_version=sM(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),dM.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(hM.JOIN_START,this.handleJoinStart).addEvent(hM.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(hM.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(hM.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(hM.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(hM.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(hM.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(hM.JOIN_FAILED,this.handleJoinFailed).addEvent(hM.LEAVE_START,this.handleLeaveStart).addEvent(hM.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(hM.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(hM.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(hM.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(hM.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(hM.PUBLISH_START,this.handlePublishStart).addEvent(hM.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(hM.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(hM.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(hM.PLAY_TRACK_START,this.handlePlayStart).addEvent(hM.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(hM.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!t.isRemote||!this.hitTest(t.room)||"PLAYING"===i&&(r===Sk.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(hM.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(hM.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(hM.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(hM.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(hM.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(hM.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(hM.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let n=i.hasAudio||i.hasVideo||i.hasSmall,o=i.hasAuxiliary,s=r.hasAudio||r.hasVideo||r.hasSmall,a=r.hasAuxiliary;!n&&s&&this.handleRemoteStreamAdded(r.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")})).addEvent(hM.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)=>dM.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),sx.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&&(dw(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),dw(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),dw(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(e){let{room:t,detailCost:i}=e;if(this.hitTest(t)&&i){let{totalCost:e,local:t,dns:r,tcp:n,tls:o,request:s,response:a}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=r,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=o,this._pathJoinRoom.int32_schedule_request=s,this._pathJoinRoom.int32_schedule_response=a}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(e){let{room:t,error:i}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=i instanceof Ub?Number(i.getExtraCode()||i.getCode()):xb.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())}handleSwitchRoomStart(e){if(this.hitTest(e.room)){let e=Date.now();this.report().then((()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e}))}}handleSwitchRoomSuccess(e){let{room:t}=e;if(this.hitTest(t)&&0===this._pathJoinRoom.uint64_end_time){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed(e){let{room:t,error:i}=e;if(this.hitTest(t)){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,i&&(this._pathJoinRoom.int32_end_ret=i instanceof Ub?Number(i.getExtraCode()||i.getCode()):xb.UNKNOWN)}}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:gb(fb({},yj),{msg_user_info:new Sj({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};n.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(r,n)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:r,subscribeState:n}=e;if(!this.hitTest(t))return;let{userId:o,tinyId:s,role:a}=i,c=new Sj({userId:o,tinyId:s,role:"anchor"===a?20:21}),l=Date.now(),d="".concat(o,"_").concat(r),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=l),"main"===r?(i.muteState.hasVideo&&(n.video||n.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),i.muteState.hasAudio&&n.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):i.muteState.hasAuxiliary&&n.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l})}handleSubscribed(e){let{room:t,remotePublishedUser:i,streamType:r}=e;if(this.hitTest(t)){let e="".concat(i.userId,"_").concat(r),t=this._remoteStreamStatMap.get(e);t&&0===t.subscribedTime&&(t.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!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,FP.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:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(s)s.totalRTT+=t,s.totalLoss+=i,n&&(s.totalVideoDelay=(s.totalVideoDelay||0)+n,s.videoDelayCount=(s.videoDelayCount||0)+1),o&&(s.totalAudioDelay=(s.totalAudioDelay||0)+o,s.audioDelayCount=(s.audioDelayCount||0)+1),s.count++;else{let e,s,a,c;n&&(s=n,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_device_info:t,msg_up_stream_info:i,msg_down_stream_info:r}=e.report;if(i.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:t,uint32_video_width:r,uint32_video_height:n}=i.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=t,this._localStreamStat.totalVideoWidth+=r,this._localStreamStat.totalVideoHeight+=n,this._localStreamStat.videoCount++}if(i.msg_audio_status){let{uint32_audio_level:e}=i.msg_audio_status;Math.floor(e/dP*100)>0&&(this._localStreamStat.totalAudioLevel+=e/dP,this._localStreamStat.audioLevelCount++)}r.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:r}=e,n=t.str_identifier,o=this._room.remotePublishedUserMap.get(n);if(r.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,r="".concat(n,"_").concat(t?"main":"auxiliary"),s=this._remoteStreamStatMap.get(r);if(s&&(t&&null!=o&&o.remoteVideoTrack.isSubscribed||i&&null!=o&&o.remoteAuxiliaryTrack)){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*mb(10,6)))}})),!kw(i)){let e="".concat(n,"_main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&null!=o&&o.remoteAudioTrack.isSubscribed&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,o.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=o.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/dP*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/dP,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 Ub?i.getExtraCode()||i.getCode():xb.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&Ck))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Dk))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&kk))>=0}hitTest(e){return e===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach(((e,t)=>{let{userId:i}=e,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(r){let{totalLoss:t,count:i,audioDelayCount:n,videoDelayCount:o,totalAudioDelay:s,totalVideoDelay:a}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),n&&s&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(s/n),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/o))}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:n}=this._room;n&&(e.statsToReport.uint32_audio_play_time=n.getDuration(t,Sk.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,Sk.VIDEO)),e.statsToReport.uint32_video_render_first&&(e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,vj));let{badCaseDetector:o}=this._room,{dataFreeze:s,count:a}=o.getDataFreezeDuration(t),{renderFreeze:c}=o.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=a,e.statsToReport.uint32_video_block_time=Math.min(s,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),o.isBlackStream(t)&&0===e.statsToReport.uint32_video_avg_fps?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>vj&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+vj):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>vj&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+vj):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>vj&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+vj)}getReportData(){this._basicInfo.uint32_networkType=QD();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Sj({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Nw(this._signalInfo.relayIp),uint32_client_ip:Nw(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*mb(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:Nw(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return Gw(e),e}report(){return Ab(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(IM){this._log.warn(IM)}finally{this.isDestroyed&&(this._room=null)}}))}upload(e){return Ab(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=pM.enable?$w(e,2001,t):yield oN(e),r=i instanceof ArrayBuffer,n="".concat(KD(t,dk.KEY_POINT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i));let s=[this.uploadKVStat(FP),this.uploadKVStat(UP)];o||s.push(nN({url:n,body:i,priority:"low"})),yield Promise.all(s)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return Ab(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=gb(fb({},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=pM.enable?$w(t,2003,this._room.sdkAppId):yield oN(t),r=i instanceof ArrayBuffer,n="".concat(KD(+this._room.sdkAppId,dk.KV_STAT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i)),o||nN({url:n,body:i})}))}};yb([mx({settings:{timeout:500,retries:3}})],Tj.prototype,"upload",1);var vj=5e3,yj={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},Sj=class{constructor(e){Sb(this,"str_identifier"),Sb(this,"str_tinyid"),Sb(this,"uint32_role"),this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},Ij=Tj,Aj=class{constructor(){Sb(this,"_startTime"),Sb(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=Aw())}stop(){0===this._endTime&&(this._endTime=Aw())}getDuration(){return 0===this._endTime?Aw()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Rj=class{constructor(e){Sb(this,"_room",null),Sb(this,"_durationMap"),Sb(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(hM.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(hM.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(hM.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;var n;let{userId:o}=r;if(!this.hitTest(t))return;i.hasAudio&&!r.hasAudio&&this.stopDurationItem("".concat(o,"_main"),Sk.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_main"),Sk.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_auxiliary"),Sk.VIDEO);let s=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);s&&(!i.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,Sk.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,Sk.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,Sk.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>dM.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>dM.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 Aj,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===Sk.AUDIO?[n]:[],video:t===Sk.AUDIO?[]:[n]})}stopDurationItem(e,t){if(this._durationMap.has(e)){let i=this._durationMap.get(e)[t].find((e=>0===e.endTime));i&&i.stop()}}hitTest(e){return this._room===e}getDuration(e,t){return this._durationMap.has(e)?this._durationMap.get(e)[t].reduce(((e,t)=>e+t.getDuration()),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Cj=class{constructor(e){Sb(this,"_room"),Sb(this,"_renderFreezeMap",new Map),Sb(this,"_isVideoPlayingEventFiredMap",new Map),Sb(this,"_dataFreezeMap",new Map),Sb(this,"_monitorFreezeData",new Map),Sb(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(hM.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(hM.PLAY_TRACK_START,this.onPlayTrackStart).set(hM.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);this.stopDataFreeze({key:o,userId:n,type:i})})).set(hM.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(hM.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(t.isRemote&&t.room&&this.hitTest(t.room)&&n===Sk.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===Sk.MUTE?this.onVideoTrackMuted(t):r===Sk.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(hM.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>dM.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>dM.off(t,e,this))),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i),n=this._dataFreezeMap.get(r),o=new Aj;n?n.durationItemList.push(o):this._dataFreezeMap.set(r,{userId:t,type:i,durationItemList:[o],isFreezing(){let e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i);this.stopDataFreeze({key:r,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;this.hitTest(t)&&i.msg_down_stream_info.forEach((e=>{let t=this._room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);if(!t)return;let{userId:i,muteState:r}=t;e.msg_video_status.forEach((e=>{2===e.uint32_video_stream_type&&r.hasVideo&&!r.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"main"}),7===e.uint32_video_stream_type&&r.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"auxiliary"})}))}))}stopDataFreeze(e){let{key:t,userId:i,type:r}=e,n=this._dataFreezeMap.get(t);if(!n||!n.isFreezing())return;let o=n.durationItemList[n.durationItemList.length-1];o.stop();let s=o.getDuration();s>sD?this._monitorFreezeData.set(t,{userId:i,type:r,duration:s}):n.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return Ab(this,arguments,(function(e){var t=this;let{userId:i,fps:r,type:n}=e;return function*(){let e="".concat(i,"_").concat(n),o=t._renderFreezeMap.get(e);if(r<=2){let r=Aw();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:r,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(e,{userId:i,type:n,isFreeze:!0,freezeTimeline:[{startTime:r,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let e=o.freezeTimeline.pop();if(e){e.endTime=Aw();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room)||t.kind!==Sk.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()<sD&&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=Aw()-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()}},bj=vb(Rb(),1),kj=class{constructor(e,t,i,r){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:4/3;this.vbMode=e,this.faceDetectorHash=t,this.visionTaskRegistry=i,this.logger=r,Sb(this,"animationState"),Sb(this,"originalAspect"),Sb(this,"totalOffsetX",0),Sb(this,"totalOffsetY",0),Sb(this,"defaultScaleRatio",.1),Sb(this,"isRecovering",!1),Sb(this,"boundaryY",280),Sb(this,"lastActionTime",0),Sb(this,"restTime",400),this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=n||4/3}addEvent(e,t,i){let r=[{key:570704,error:null!=i?i:t?void 0:11},{key:570705,error:null!=i?i:t?void 0:22}][e-1];r&&(t?FP.addSuccessEvent({key:r.key}):FP.addFailedEvent({key:r.key,error:r.error}))}actionCentering(e){let t=Date.now();if(this.animation(),!this.faceDetectorHash||t-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:i,videoHeight:r}=e;this.animationState.debounceThreshold=i/30,this.animationState.movementThreshold=i/20,this.boundaryY=.6*r;try{let e=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(e.detections.length<=0)return void(1===this.vbMode&&this.recoverOriginal(i,r));let t=e.detections[0].boundingBox,n=t.originX,o=t.originY,s=t.width,a=t.height;1===this.vbMode?this.dualStageCropping(i,r,n,o,s,a):2===this.vbMode&&this.movingPortrait(i,r,n,o,s,a)}catch(bM){this.logger.error(bM)}this.lastActionTime=t}calculateBoundary(e,t,i,r){let n,o;return e>t/2?(n=t-i-r,o=i-n):(n=i,o=0),{min:n,offset:o}}calculateTargetPosition(e,t,i,r,n,o){let s,a,c=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.4,l=e+i/2,d=t+r/2,{min:u,offset:h}=this.calculateBoundary(l,n,e,i),{min:p,offset:m}=this.calculateBoundary(d,o,t,r);return s=2*u+i,a=2*p+r,s/a>this.originalAspect?(s=a*this.originalAspect,h=l-s/2):(a=s/this.originalAspect,m=d-a/2),i/n>c&&(h=0,m=0,s=n,a=o),h=Math.max(0,Math.min(h,n-s)),m=Math.max(0,Math.min(m,o-a)),{sx:h,sy:m,cropWidth:s,cropHeight:a,timestamp:Date.now()}}processFacePositionCrop(e,t,i){if(!this.animationState.current||!this.animationState.target){let e={sx:0,sy:0,cropWidth:t,cropHeight:i,timestamp:Date.now()};return this.animationState.current=e,void(this.animationState.target=e)}let r=this.positionDistance(this.animationState.target,e),n=this.positionDistance(this.animationState.current,e),o=this.animationState.current.cropWidth/t;r>this.animationState.debounceThreshold*o&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&n>this.animationState.movementThreshold*o&&(this.animationState.target=e,this.animationState.debounceTimer=setTimeout((()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0}),this.animationState.debounceTime))}processFacePositionPortrait(e){if(!this.animationState.current||!this.animationState.target)return this.animationState.current=fb({},e),void(this.animationState.target=fb({},e));let t=this.positionDistance(this.animationState.current,e),i=this.positionDistance(this.animationState.target,e);t>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&i>this.animationState.movementThreshold&&(this.animationState.current=e,this.animationState.debounceTimer=setTimeout((()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0}),this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let e=Date.now()-this.animationState.startTime,t=Math.min(e/this.animationState.duration,1),i=e=>e<.5?2*e*e:(4-2*e)*e-1;if(this.animationState.current&&this.animationState.target){let e=(this.animationState.target.sx-this.animationState.current.sx)*i(t);this.animationState.current.sx+=e,this.totalOffsetX+=e;let r=(this.animationState.target.sy-this.animationState.current.sy)*i(t);if(this.animationState.current.sy+=r,this.totalOffsetY+=r,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*i(t),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*i(t),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*i(t)),hw(this.animationState.current.scaleOffsetX)&&hw(this.animationState.target.scaleOffsetX)&&hw(this.animationState.current.scaleOffsetY)&&hw(this.animationState.target.scaleOffsetY)){let e=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*i(t);this.animationState.current.scaleOffsetX+=e;let r=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*i(t);this.animationState.current.scaleOffsetY+=r}}t>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(e,t){return Math.sqrt(mb(e.sx-t.sx,2)+mb(e.sy-t.sy,2))}recoverOriginal(e,t){this.animationState.target={sx:0,sy:0,cropWidth:e,cropHeight:t,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(e,t,i,r,n,o){let s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.3;if(this.isRecovering)return;let a=this.calculateTargetPosition(i,r,n,o,e,t);this.processFacePositionCrop(a,e,t),n*o/a.cropWidth/a.cropHeight>s&&this.recoverOriginal(e,t)}movingPortrait(e,t,i,r,n,o){var s,a,c,l,d,u,h,p,m,_,f,g;let E={sx:i+n/2+this.totalOffsetX,sy:r+o/2+this.totalOffsetY,cropWidth:e,cropHeight:t,scaleRatio:null!=(a=null==(s=this.animationState.current)?void 0:s.scaleRatio)?a:1,scaleOffsetX:null!=(l=null==(c=this.animationState.current)?void 0:c.scaleOffsetX)?l:0,scaleOffsetY:null!=(u=null==(d=this.animationState.current)?void 0:d.scaleOffsetY)?u:0,timestamp:Date.now()};this.animationState.target={sx:e/2,sy:r+o/2,cropWidth:e,cropHeight:t,scaleRatio:null!=(p=null==(h=this.animationState.target)?void 0:h.scaleRatio)?p:1,scaleOffsetX:null!=(_=null==(m=this.animationState.target)?void 0:m.scaleOffsetX)?_:0,scaleOffsetY:null!=(g=null==(f=this.animationState.target)?void 0:f.scaleOffsetY)?g:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(n*o/e/t/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=1-this.animationState.target.scaleRatio,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(E)}set aspectRatio(e){this.originalAspect=e}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}},Dj=class extends kB{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log}),Sb(this,"_bgTexture"),Sb(this,"_waterMarkTexture"),Sb(this,"_lastMaskTexture"),Sb(this,"_lastMaskFbo"),Sb(this,"_textureValid",!1),Sb(this,"_selfieTextureValid",!1),Sb(this,"_selfieSegmentationHash"),Sb(this,"wasm"),Sb(this,"predictReady"),Sb(this,"_color"),Sb(this,"_prePrograme"),Sb(this,"_segmentationMask"),Sb(this,"_weixin",!1),Sb(this,"_centerFace"),Sb(this,"_textureMatrixLocation"),Sb(this,"_offsetMatrixLocation"),Sb(this,"_colorLocation"),Sb(this,"_enableFaceCentering",!1),Sb(this,"_enableEffectOptimization",!1),Sb(this,"_mat4"),Sb(this,"_postProcessing"),Sb(this,"_onAbort"),Sb(this,"_visionTaskRegistry"),Sb(this,"resolvePreditReady"),this.init(t).catch((t=>{e.log.error(t),e.destroy(new Ub({code:xb.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(t.message||t)})),this.resolvePreditReady()}))}init(e){return Ab(this,null,(function*(){var t,i,r;this.predictReady=new Promise((e=>{this.resolvePreditReady=e}));let n=e.Wasm,o=this.context.ctx;if(e.color&&(this._color=e.color),e.mat4&&(this._mat4=e.mat4),e.postProcessing&&(this._postProcessing=e.postProcessing),this._enableFaceCentering=null!=(t=e.enableFaceCentering)&&t,this._enableEffectOptimization=null!=(i=e.enableEffectOptimization)&&i,this.wasm=new n.AllIn1(o),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.rotation=e.rotation||0,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"color"===e.bg?3:0,this._onAbort=e.onAbort,e.bg||this.resolvePreditReady(),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)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),o.uniform1i(o.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(o.uniform1i(o.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(o.uniform1i(o.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let s=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=o.getUniformLocation(this.program,"u_textureMatrix"),o.uniformMatrix4fv(this._textureMatrixLocation,!1,s),this._offsetMatrixLocation=o.getUniformLocation(this.program,"u_offsetMatrix"),o.uniformMatrix4fv(this._offsetMatrixLocation,!1,s),this._colorLocation=o.getUniformLocation(this.program,"u_color"),o.uniform1i(o.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(o.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(o.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),o.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),o.uniform1i(o.getUniformLocation(this._prePrograme,"mask"),1)}this._enableEffectOptimization&&(2===this.wasm.vbMode||3===this.wasm.vbMode)&&(null==(r=this._postProcessing)||r.init(o,this.positionBuffer,this.texCoordBuffer,4/3)),yield this.initVisionTasks(e)}))}initVisionTasks(e){return Ab(this,null,(function*(){if(e.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._visionTaskRegistry.video=this.image,this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let e=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!e)return;this._centerFace=new kj(this.wasm.vbMode,e,this._visionTaskRegistry,this.context.log)}catch(Xk){this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}}))}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let i=this.getMaskTexture(e);if(!i)return;let r=i;this._enableEffectOptimization&&this._postProcessing&&(2===this.wasm.vbMode||3===this.wasm.vbMode)&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,r=this._postProcessing.postProcessing(i)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,r||null),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),3===this.wasm.vbMode&&t.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),Yw(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),t.viewport(0,0,t.canvas.width,t.canvas.height),t.drawArrays(t.TRIANGLE_STRIP,0,4),e.close()}getMaskTexture(e){return e.confidenceMasks?e.confidenceMasks[0].getAsWebGLTexture():void 0}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){let t=this.context.ctx,{image:i}=this;this.tryVideoFrameCallback();let{videoWidth:r,videoHeight:n}=i;if(Yw(this.wasm.rotation)&&!this._visionTaskRegistry&&([r,n]=[n,r]),0===r||0===n||!this.available)return!1;i.width=r,i.height=n;let o=!1;if(this.totalFrames)this.useTexture(),o=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),o=this._textureValid,this._textureValid=!0}if(this.width===r&&this.height===n&&o?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,i):(this.resize(r,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,i)),this._weixin){if(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let e=this.getMaskTexture(this._segmentationMask);t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,e||null),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)}t.drawArrays(t.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,r,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,r,n,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let e=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);1===this.totalFrames&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(e)}}catch(s){this._onAbort&&this._onAbort(s)}return this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let e=this.context.ctx;this._centerFace.aspectRatio=e.canvas.width/e.canvas.height,this._centerFace.actionCentering(this.image);let{current:t,offset:i}=this._centerFace;if(t&&(1===this.wasm.vbMode&&this.drawImage(t.sx,t.sy,t.cropWidth,t.cropHeight),i&&2===this.wasm.vbMode)){if(!this._mat4)return;let r=this._mat4.create(),{scaleRatio:n=1,scaleOffsetX:o=0,scaleOffsetY:s=0}=t;this._mat4.fromTranslation(r,[-i.offsetX/e.canvas.width+o,s,0]),this._mat4.scale(r,r,[n,n,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,r)}}drawImage(e,t,i,r){let n=this.context.ctx;if(!this._mat4)return;let{width:o,height:s}=n.canvas,a=this._mat4.create();this._mat4.fromTranslation(a,[e/o,1-(t+r)/s,0]),this._mat4.scale(a,a,[i/o,r/s,1]),n.uniformMatrix4fv(this._textureMatrixLocation,!1,a)}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),this._postProcessing&&this._postProcessing.close(),null==(e=this.wasm)||e.close()}},wj=class extends TB{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 }"}),Sb(this,"yTextureRef"),Sb(this,"uTextureRef"),Sb(this,"vTextureRef"),Sb(this,"Y"),Sb(this,"U"),Sb(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)}},Nj=[e=>{e.codec="avc1.42e01f"},e=>{delete e.hardwareAcceleration}],Oj=(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")};var Mj=0,Pj=class{constructor(e){Sb(this,"id",Mj++),Sb(this,"trackDoneOB"),Sb(this,"startOB"),Sb(this,"stopOB"),Sb(this,"decoder"),Sb(this,"videoContext"),Sb(this,"gop",0),Sb(this,"gop_helper",0),Sb(this,"waitFirstKeyFrame",!0),Sb(this,"startTimestamp",0),Sb(this,"startTime",0),Sb(this,"startPerformanceTime",0),Sb(this,"inputFrameCount",0),Sb(this,"decodedFrameCount",0),Sb(this,"decodeFrameCount",0),Sb(this,"downgradeLevel",0),Sb(this,"lastDowngradeTime",0),Sb(this,"lastFrameDiff",0),Sb(this,"lastDecodeFrameTimestamp",0),Sb(this,"config"),Sb(this,"gop_before_configure",[]),Sb(this,"videoElement"),Sb(this,"type","wasm"),Sb(this,"goodType"),Sb(this,"renderer","2d"),Sb(this,"wasmOption"),Sb(this,"createDecoder"),Sb(this,"_decodeSink"),Sb(this,"isReported",!1),Sb(this,"track"),Sb(this,"stateChangeOB"),Sb(this,"failedReason");let{track:t,createDecoder:i}=e;if(this.stateChangeOB=CU(),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=xU(t.availableState,ex.OFF),this.stopOB=CU(),"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),oU(this.stateChangeOB,CF(((e,i)=>(e!==i&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:e,state:i}),i)),"INITIALIZED"),nF(this.stopOB),rB()),this.start()}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=oU(this.pipe(this.track),nF(this.stopOB),pU());oU(t,rB((()=>{this.track.stat.framesDecoded++}),(t=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(t," retryCount: ").concat(e)),FP.addFailedEvent({key:Oj(this.type,this.renderer),error:t}),e>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),FP.addFailedEvent({key:514704});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")),FP.addSuccessEvent({key:Oj(this.type,this.renderer)}),FP.addSuccessEvent({key:514704})}))),oU(t,rF(1),rB((()=>{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&&!zP()&&(this.renderer="2d"),this.wasmOption.yuvMode="webgl"===this.renderer}decode(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i,r;if(this.failedReason)return;this.inputFrameCount++;let n=new Uint8Array(e.data);if(0!==(o=n)[0]||0!==o[1]||0!==o[2]||1!==o[3]||n.length<5)return this.stateChangeOB.next("FAILED"),this.close("not h26x frame ".concat(n.subarray(0,5))),e;var o;let s=!1;switch(31&n[4]){case 5:case 7:s=!0}if("configured"!==(null==(i=this.decoder)?void 0:i.state))return this.track.log.debug("not configured ".concat(this.inputFrameCount)),s&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:e.data,timestamp:e.timestamp,type:e.type}),e;this.gop_before_configure.length>0&&!t&&(this.gop_before_configure.forEach((e=>this.decode(e,!0))),this.gop_before_configure=[]);let{timestamp:a}=e;if(s?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!s)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(n.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=a,this.startTime=Date.now(),this.startPerformanceTime=Aw()}switch(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.decodeFrameCount<10||this.decodeFrameCount%500==0)&&this.track.log.debug("decode ".concat(this.decodeFrameCount," gop: ").concat(this.gop," ").concat(a," ").concat(null==(r=e.getMetadata)?void 0:r.call(e).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=a,void this.decoder.decode({data:e.data,type:e.type,timestamp:this.lastDecodeFrameTimestamp})}return e}checkDowngradeByFrameDiff(){let e=this.downgradeLevel,t=this.decodeFrameCount-this.decodedFrameCount;t>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):t<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug("downgrade level ".concat(e," to ").concat(this.downgradeLevel," ").concat(this.decodeFrameCount," frameDiff: ").concat(t,", lastFrameDiff: ").concat(this.lastFrameDiff)),this.lastFrameDiff=t,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(e){let t=this.downgradeLevel;this.lastDecodeFrameTimestamp-e>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==t&&this.track.log.debug("downgrade level ".concat(t," to ").concat(this.downgradeLevel))}pipe(e){return t=>Ab(this,null,(function*(){this._decodeSink=t;let i,r=e.mediaTrack;t.defer((()=>{var t;r&&(e.player.setCanvas(),e.setInputMediaStreamTrack(r)),null==i||i.close(),null==(t=this.videoContext)||t.destroy(),delete this._decodeSink}));let{renderer:n,type:o}=this;e.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(o){case"wasm":i=this.createDecoder(o,this.wasmOption);break;case"webCodecs":for(let e=0;e<=Nj.length;e++){let{supported:i}=yield VideoDecoder.isConfigSupported(this.config);if(i)break;if(e===Nj.length)return void t.error(3);Nj[e](this.config)}i=this.createDecoder(o);break;default:throw new Error("not supported yet")}let r=0;if(i.on("videoFrame",(i=>{this.decodedFrameCount++,r++,(r<=10||r%500==0)&&e.log.debug("frame ".concat(r," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(i.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&("webCodecs"===this.type?this.checkDowngradeByFrameDiff():"wasm"===this.type&&this.checkDowngradeByTimestampDiff(i.timestamp)),t.next(i)})),i.on("error",(i=>{e.log.error(i),t.error("webCodecs"===o?4:8)})),yield i.initialize(this.videoElement),!this._decodeSink)return;if(i.configure(this.config),"wasm"===o&&"webgl"===n){this.videoContext=new MB({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(MB.UNAVAILABLE,(i=>{e.log.error(i),t.error(7)}));let r=new wj(this.videoContext);i.on("videoCodecInfo",(e=>r.resize(e.width,e.height))),i.on("videoFrame",(e=>{({y:r.Y,u:r.U,v:r.V}=e),1===this.downgradeLevel?this.decodedFrameCount%2==0&&r.render(this.decodedFrameCount):r.render(this.decodedFrameCount)})),e.source=r,e.player.setCanvas(this.videoContext._canvas,2)}else if("videoFrame"===n){e.player.setCanvas();let t=new MediaStreamTrackGenerator({kind:"video"}),r=t.writable.getWriter();e.setInputMediaStreamTrack(t),i.on("videoFrame",(e=>r.write(e)))}else{this.videoContext=new PB({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create({alpha:!1});let r=this.videoContext.createVideoImageSource();i.on("videoFrame",(i=>{try{r.image=i,r.update()}catch(n){delete this.goodType,e.log.error(n),t.error(11)}}));let n=new SB(this.videoContext,{name:"remotePlayer",logger:e.log});r.connect(n),e.source=r,e.player.setCanvas(this.videoContext._canvas,2)}this.decoder=i}catch(CM){e.log.error(CM),t.error("webCodecs"===o?2:6)}}))}},Lj=class extends bj.EventEmitter{constructor(e){super(),this.room=e,Sb(this,"videoContext"),Sb(this,"_glVideoContext"),Sb(this,"_2dVideoContext"),Sb(this,"destination"),Sb(this,"smallVideoContext"),Sb(this,"smallDestination"),Sb(this,"smallTrackSource"),Sb(this,"smallImageSource"),Sb(this,"_isMirror",!1),Sb(this,"_rotation",0),Sb(this,"cameraTrack"),Sb(this,"cameraNode"),Sb(this,"transformNode"),Sb(this,"mixNode"),Sb(this,"screenTrack"),Sb(this,"screenNode"),Sb(this,"selfModel",!1),Sb(this,"blurRadius",3),Sb(this,"arTrack"),Sb(this,"_enableFaceCentering",!1),Sb(this,"_enableEffectOptimization",!1),Sb(this,"onAbort"),Sb(this,"_color"),Sb(this,"Wasm"),Sb(this,"waterMarkNode"),Sb(this,"_waterMarkOption"),Sb(this,"watermarkImageList",[]),Sb(this,"_beautyParams"),Sb(this,"isUsingArTrack",!1),Sb(this,"mixTrack"),Sb(this,"_isMixScreen",!1),Sb(this,"_virtualBackground"),Sb(this,"_virtualBackgroundAbortCallback"),Sb(this,"virtualBackgroundInstance"),Sb(this,"_bgAssetPath"),Sb(this,"log",_M.createLogger({id:"vm"})),Sb(this,"_mat4"),Sb(this,"_postProcessing"),Sb(this,"_checkId",0),Sb(this,"_use2d",!1),Sb(this,"_autoSwitchRenderMode",!0),Sb(this,"encodePipeline",[]),Sb(this,"decodePipeline",[]),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new PB({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return(null==(e=this.room)?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return 0!==this._rotation}get _isTransform(){return this._isMirror||this._isRotate}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())}get cameraResolution(){var e;let{width:t,height:i}=(null==(e=this.cameraTrack)?void 0:e.settings)||{};return Yw(this._rotation)?{width:i,height:t}:{width:t,height:i}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new PB({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 MB({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on(MB.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(zb){this.emit("error",zb)}}initVirtualBackground(e,t,i){this.onAbort=e,this._mat4=t,this._postProcessing=i}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=sx.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(),sx.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(PO||this._isMixScreen||this._isTransform||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?FP.addFailedEvent({key:t,error:e}):FP.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 MB({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}setSmallVideo(e,t){if("api"!==this.smallMode)if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new RB(this.smallVideoContext,e,this.log),this.smallVideoContext.on(MB.UNAVAILABLE,(e=>{this.log.warn("small video context lost",e)}))}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:e,height:t}=this.cameraTrack.settings;this.smallTrackSource.resize(e,t),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let i=this.cameraTrack,{small:r,player:n}=i;PO&&n.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.log.info("set main output ".concat(o?o.label:"no output track")),this.setSmallVideo(r,e),i.setOutputMediaStreamTrack(o)}catch(AM){this.log.error("set main output failed",AM)}}update(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Ab(this,null,(function*(){var t;if(!this.cameraTrack||!this.initialTrack)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}),this.destination.on("render",(e=>{var t;null==(t=this.cameraTrack)||t.emit("render",e)}))),16===BO?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof kB?(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 kB?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);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new AB(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on("render",(e=>{var t;null==(t=this.cameraTrack)||t.emit("render",e)})));let{width:e,height:t}=this.cameraResolution,i=yield this.getWatermarkImage(e,t);this._waterMarkOption={x:0,y:0,width:i.width,height:i.height,image:i},this.cameraNode=new Dj(this.videoContext,{input:this.initialTrack,width:e,height:t,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=r.frameRate,this._use2d){let e=this.cameraNode;if(e.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new FB(this.videoContext,this.log,this._isMirror,this._rotation),e=e.connect(this.transformNode),e.disconnect(),this.log.info("start mirror ".concat(this._isMirror," rotate ").concat(this.rotation))),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new VB(this.videoContext,this.log),e.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;else if(this.waterMarkNode){let{width:e,height:t}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(e,t),e&&t&&this.waterMarkNode.resize(e,t)}null==(t=this.waterMarkNode)||t.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),e=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))}e.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext._canvas)}))}clearLastFrame(){var e;this.destination&&(null==(e=this.destination.ctx2d)||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var t,i,r,n,o;if(e instanceof GB)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof _B)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof ZB){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);let t=e.mediaTrack;return e.setOutputMediaStreamTrack(t)}if(e instanceof BB)return this.log.info("change mix input",null==(n=e.outMediaTrack)?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",null==(o=e.mediaTrack)?void 0:o.label)}removeInput(e){var t;e instanceof GB?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof _B?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof ZB?e.source&&e.source.context.destroy():e instanceof BB&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return Ab(this,null,(function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}))}getWatermarkImage(e,t){return Ab(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 Ub({code:xb.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort(((e,t)=>e.zIndex-t.zIndex)),this.watermarkImageList.forEach((e=>{let{image:t,x:i,y:n,width:o,height:s}=e;r.drawImage(t,i,n,o,s)})),Hw(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 Ab(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return Ab(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return Ab(this,null,(function*(){let t;try{t=yield Hw((null==e?void 0:e.imageElement)||e.imageUrl)}catch(c){throw new Ub({code:xb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:i=0,y:r=0,width:n=t.width,height:o=t.height,type:s="watermark",zIndex:a=2}=e;this.watermarkImageList.some((e=>e.type===s))?(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==s)),this.pushWaterMarkImageList({x:i,y:r,width:n,height:o,image:t,zIndex:a,type:s,imageUrl:e.imageUrl}),t=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:i,y:r,width:n,height:o,image:t,zIndex:a,type:s,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,((e,t)=>"imageUrl"===e?void 0:t)))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return Ab(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 Ab(this,null,(function*(){var e;null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:t,height:i}=this.cameraResolution,r=yield this.getWatermarkImage(t,i);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()}))}setVirtualBackground(e){return Ab(this,null,(function*(){var t,i,r;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 Hw(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=null!=(t=e.enableFaceCentering)?t:this._enableFaceCentering,this._enableEffectOptimization=null!=(i=e.enableEffectOptimization)?i:this._enableEffectOptimization,this._color=null!=(r=e.color)?r:[0,1,0]}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 Ub({code:xb.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._isTransform||(null==(t=this.transformNode)||t.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var t;this._rotation!==e&&(this._rotation=e,this._isTransform||(null==(t=this.transformNode)||t.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return Ab(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 Pj(e)}clear(){var e,t;null==(e=this.videoContext)||e.disconnect(),null==(t=this.destination)||t.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,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}};yb([VV((function(e){this.log.error("update failed",e)}))],Lj.prototype,"update",1);var xj=0,Vj=class extends ex{constructor(e){super("room"),Sb(this,"seq",++xj),Sb(this,"sdkAppId"),Sb(this,"userId"),Sb(this,"userSig"),Sb(this,"privateMapKey"),Sb(this,"latencyLevel"),Sb(this,"tinyId"),Sb(this,"scene"),Sb(this,"roomId"),Sb(this,"useStringRoomId"),Sb(this,"role","anchor"),Sb(this,"joinParams",null),Sb(this,"localPublishFlag",0),Sb(this,"localTracks",new Set),Sb(this,"enableAutoPlayDialog",!0),Sb(this,"autoReceiveAudio",!0),Sb(this,"autoReceiveVideo",!0),Sb(this,"proxy_ws"),Sb(this,"proxy_wt"),Sb(this,"proxy_unified"),Sb(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,isH265EncodeSupported:!0,isH265DecodeSupported:!0}}),Sb(this,"keyPointManager"),Sb(this,"audioManager"),Sb(this,"videoManager"),Sb(this,"callDurationCalculator"),Sb(this,"badCaseDetector"),Sb(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),Sb(this,"videoDecodeFallbackType"),Sb(this,"smallMode","canvas"),Sb(this,"_isUsingCachedSchedule",!1),Sb(this,"_log",_M.createLogger({id:"r".concat(this.seq)})),Sb(this,"_joinedTimestamp",0),Sb(this,"_sdkType"),Sb(this,"heartbeatReport"),Sb(this,"quality"),Sb(this,"enableSEI"),Sb(this,"isDestroyed",!1),this.useStringRoomId=!!e.useStringRoomId,pw(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),pw(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),pw(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new Ij({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Rj({room:this}),this.badCaseDetector=new Cj({room:this}),this.audioManager=new qB(this),this.videoManager=new Lj(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 Ab(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return Ab(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return Ab(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(uw(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(ow(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:r,scheduleProxy:n,unifiedProxy:o}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=o,o?(XH([o,o]),ek("https://".concat(o))):(r&&ek(r),n&&XH(n))}dM.once(hM.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:YH.main,sched_back_domain:YH.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return Ab(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return Ab(this,null,(function*(){var e;let t={rtt:(null==(e=this.quality)?void 0:e.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let i of this.quality.downlinkInfo)t.downlinksRTT[i.userId]=i.rtt;return t}))}getRemoteVideoStats(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"main";return function*(){let i={};return e.remotePublishedUserMap.forEach((e=>{let r="auxiliary"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;i[e.userId]=r.stat})),i}()}))}checkDestroy(){if(this.isDestroyed)throw new Ub({code:xb.INVALID_OPERATION,message:bP({key:IP.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(AP.INVALID_DESTROY),new Ub({code:xb.INVALID_OPERATION,message:bP({key:IP.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,dM.emit(hM.ROOM_DESTROY,{room:this})}schedule(e,t){return Ab(this,null,(function*(){var i,r,n,o;let s=Aw();try{let{isCached:a,result:c,detailCost:l}=yield zH({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Kb,userSig:this.userSig,role:"live"===this.scene?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=a,this._log.info("schedule cache:".concat(+a," ").concat(Vw(c,{keysToExclude:["username","credential"]}))),a&&dM.once(hM.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=fb(fb({},this.scheduleResult),c),hw(null==(i=c.config)?void 0:i.retryCount)&&zk(c.config.retryCount),uw(null==(r=c.config)?void 0:r.loggerDomain)&&ek(c.config.loggerDomain),this.videoDecodeFallbackType=(null==(n=c.config)?void 0:n.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=(null==(o=c.config)?void 0:o.smallMode)||this.smallMode,dM.emit(hM.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:l}),FP.addSuccessEvent({key:521700,cost:Aw()-s})}catch(yM){throw FP.addFailedEvent({key:521700,error:yM}),yM}}))}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}},Uj=vb(Rb()),Fj=vb(Mb());function Bj(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 Hj=(e,t,i)=>Ab(void 0,null,(function*(){var r;let n=sj(e),o={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};o.ice.ufrag=String(n.media[0].iceUfrag),o.ice.password=n.media[0].icePwd||"",n.fingerprint&&(o.dtls.hash=n.fingerprint.type,o.dtls.fingerprint=n.fingerprint.hash,o.dtls.setup=n.setup||""),n.media[0].fingerprint&&(o.dtls.hash=n.media[0].fingerprint.type,o.dtls.fingerprint=n.media[0].fingerprint.hash),o.dtls.setup=n.media[0].setup||"";let s=n.media[0],a=n.media[1];s.ext&&(o.audio.extensions=s.ext.map((e=>({id:e.value,uri:e.uri})))),a.ext&&(o.video.extensions=a.ext.map((e=>({id:e.value,uri:e.uri}))));let c={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channels:s.rtp[0].encoding,rtcpfb:[],rtx:0};null==(r=s.rtcpFb)||r.forEach((e=>{let{payload:t,type:i,subtype:r}=e;if(t===c.payload){let e={id:i,params:[]};r&&e.params.push(r),c.rtcpfb.push(e)}})),o.audio.codecs.push(c);let l=["h264","vp8","h265"];return t&&l.shift(),i&&l.pop(),o.video.codecs=[...Bj(a)].filter((e=>l.includes(e.codec.toLocaleLowerCase()))),o.video.decoders=(yield function(){return Ab(this,null,(function*(){let e=new RTCPeerConnection;e.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY});let t=yield e.createOffer();if(!t.sdp)return[];let i=Bj(sj(t.sdp).media[0]);return e.close(),i}))}()).filter((e=>["h264","vp8","h265"].includes(e.codec.toLocaleLowerCase()))),o})),Wj=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,o=sj(r),s={extmapAllowMixed:"extmap-allow-mixed",groups:o.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},a={candidates:t.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:o.media[0].port,protocol:o.media[0].protocol,type:Sk.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map((e=>({payload:t.audio.codecs[0].payload,type:e.id,subtype:e.params[0]}))),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};return s.media.push(a),[1,2,3].forEach((e=>{s.media.push(Gj({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),n&&s.media.push(o.media.find((e=>"dc"===e.mid))),aj(s)},Gj=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,isDownlink:o=!1}=e,s={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(t),payloads:"",port:n.media[0].port,protocol:n.media[0].protocol,type:Sk.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(o){let e=i.video.decoders;(!e||0===e.length)&&(e=i.video.codecs),(!e||0===e.length)&&(e=r.video.decoders),e.forEach((e=>{jj(s,e)}))}else{let e;e=i.useH265?i.video.codecs.findIndex((e=>"h265"===e.codec.toLowerCase())):i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264")));let t=i.video.codecs[e]||r.video.codecs[0];jj(s,t)}return s},jj=(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 Jj=(e,t,i)=>{let r=Fj.default.parse(e);return r.media.forEach(((e,n)=>{var o;if((e.type===Sk.AUDIO||e.type===Sk.VIDEO)&&(function(e){if(!e.rtcpFb)return;let t=[];e.rtcpFb.forEach(((i,r)=>{var n;t.push(i),e.rtcpFb&&(null==(n=e.rtcpFb[r+1])?void 0:n.payload)!==i.payload&&"rrtr"!==i.type&&t.push({payload:i.payload,type:"rrtr"})})),e.rtcpFb=t}(e),function(e){e.type===Sk.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===Sk.AUDIO&&e.fmtp&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))}(e),function(e){let t=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}(e),e.type===Sk.VIDEO))if(n<4)e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach((t=>jj(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=>jj(e,t)))}null!=(o=e.payloads)&&o.includes("datachannel")&&r.groups&&e.mid&&(r.groups[0].mids=r.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),Fj.default.write(r)},Kj=vb(Rb()),qj=class extends Kj.EventEmitter{constructor(e){super(),this.room=e,Sb(this,"mainFpsHealth",1),Sb(this,"mainBitrateHealth",1),Sb(this,"badMainBitrateHealthCount",0),Sb(this,"lastEmitBadHealthTime",0),Sb(this,"log"),!CN&&kO&&dM.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(){dM.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};Sb(qj,"EVENT_BAD_HEALTH","bad_health");var zj=qj;function Yj(e){let{seiMessageList:t,isAudio:i,isMain:r}=e;return new TransformStream({transform(e,n){let o=e;i?audioEncodePipeline.forEach((e=>{o=e({frame:o})})):videoEncodePipeline.forEach((e=>{o=e({frame:o,seiMessageList:t,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:o.data,userId:"",streamType:r?"main":"auxiliary"})}})})),n.enqueue(o)}})}function Xj(e,t,i){return new TransformStream({transform(r,n){let o=r;videoDecodePipeline.forEach((r=>{o=r({frame:o,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:o.data,userId:e,streamType:t})}})})),n.enqueue(o)}})}var Qj=(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))(Qj||{}),Zj=0,$j=!1,eJ=new Set,tJ=1,iJ=class extends Uj.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),Sb(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),Sb(this,"currentState","DISCONNECTED"),Sb(this,"_room"),Sb(this,"_signalChannel"),Sb(this,"_peerConnection",null),Sb(this,"_datachannel",null),Sb(this,"_enableCustomMessage"),Sb(this,"_log"),Sb(this,"_downlinkMIDMap",new Map),Sb(this,"_downlinkMIDUserIDMap",new Map),Sb(this,"_reconnectionTimer",-1),Sb(this,"reconnectionCount",0),Sb(this,"clientAbility"),Sb(this,"_serverAbility",null),Sb(this,"addDownlinkQueue",new Set),Sb(this,"removeDownlinkQueue",new Set),Sb(this,"_parsedAnswer",null),Sb(this,"_updateSDPPromise",null),Sb(this,"_waitForPCConnectedPromise"),Sb(this,"clearWaitForConnectedPromise"),Sb(this,"clearConnectTimeout"),Sb(this,"_isSDPLogged",!1),Sb(this,"enableInsertableStreams",!1),Sb(this,"insertableStreamsAbortMap",new Map),Sb(this,"receiverRemoteTrackMap",new WeakMap),Sb(this,"scriptTransformWorker"),Sb(this,"_isRelayTried",!1),Sb(this,"_rttOverCount",0),Sb(this,"originOffer",null),Sb(this,"autoSubscribedSsrcGroups",new Map),Sb(this,"autoSubscribedUserMap",new Map),Sb(this,"_h265DecodeFailed",!1),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=_M.createLogger({id:"spc".concat(tJ++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(CL?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 isH265EncodeSupported(){let e=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((e=>"h265"===e.codec.toLowerCase()))),e}get videoCodec(){var e,t,i;let r=null==(e=this._parsedAnswer)?void 0:e.media[1].rtp.find((e=>["h264","vp8","h265"].includes(e.codec.toLowerCase())));return r?r.codec.toLowerCase():null!=(t=this._serverAbility)&&t.useH265?"h265":null!=(i=this._serverAbility)&&i.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e,t,i;return null!=(e=this._serverAbility)&&e.useH265&&null!=(t=this._serverAbility)&&t.video.decoders.find((e=>"h265"===e.codec.toLowerCase()))&&!this._h265DecodeFailed?"h265":null!=(i=this._serverAbility)&&i.video.decoders.find((e=>"h264"===e.codec.toLowerCase()))?"h264":"vp8"}get isUsingH264(){return"h264"===this.videoCodec}get isUsingH265(){return"h265"===this.videoCodec}get isUsingVP8(){return"vp8"===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=sj(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&&!dw(e.ssrcs[0].id)){let n=Number(e.ssrcs[0].id),o=Number(null==(r=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:r.id);switch(t){case 0:i.audioSsrc=n;break;case 1:i.bigVideoSsrc=n,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=n,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=n,i.auxVideoRtxSsrc=o}}})),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(e){let{isAux:t}=e;this.useHWEncoder(!1,t?7:2)}initScriptTransformWorker(){bL&&(this.scriptTransformWorker=function(e){let t=[hB],i=[OW,wW,NW,DW,Yj,Xj],r="const videoEncodePipeline=[".concat(e.videoEncodePipeline.toString(),"];\n const videoDecodePipeline=[").concat(e.videoDecodePipeline.toString(),"];\n const audioEncodePipeline = [").concat(e.audioEncodePipeline.toString(),"];\n const audioDecodePipeline = [").concat(e.audioDecodePipeline.toString(),"];"),n="(()=>{".concat(t.map((e=>"const ".concat(e.name,"=(()=>").concat(e.toString(),")()"))).join("\n"),"\n").concat(i.map((e=>e.toString())).join("\n"),";(").concat((()=>{let e=[],t=[],i=[];self.onmessage=r=>{"sei"===r.data.type&&(r.data.isMain?(e.push(r.data.data),r.data.small&&i.push(r.data.data)):t.push(r.data.data))},self.onrtctransform=r=>{let{options:n}=r.transformer,o=n.isReceiver?Xj(n.userId,n.streamType,n.isAudio):Yj({isAudio:n.isAudio,seiMessageList:n.isMain?n.small?i:e:t,isMain:n.isMain});r.transformer.readable.pipeThrough(o).pipeTo(r.transformer.writable)}}),")();").concat(r,"})()"),o=new Blob([n],{type:"text/javascript"}),s=URL.createObjectURL(o),a=new Worker(s);return URL.revokeObjectURL(s),a}({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{"sei"===e.data.type&&this.emit("sei-message",e.data),"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){var t;let i={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=null==(t=this._peerConnection)?void 0:t.getConfiguration().encodedInsertableStreams;return lN(r)&&(i.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(i)),i}initialize(e){return Ab(this,null,(function*(){var t,i;let r;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(),FP.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):"failed"===e&&FP.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 nJ(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(Sk.AUDIO,{direction:Sk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_SENDONLY}),r=yield this._peerConnection.createOffer(),this.clientAbility=yield Hj(r.sdp,(null==(t=this._room.scheduleResult.config)?void 0:t.remove264FromSDP)||!1,(null==(i=this._room.scheduleResult.config)?void 0:i.remove265FromSDP)||!1),this.originOffer=r,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()))}),FP.addSuccessEvent({key:521707}),this.clientAbility}catch(Yb){throw FP.addFailedEvent({key:521707,error:Yb}),this._log.error("initialize failed ".concat(Yb," \noffer: ").concat(null==r?void 0:r.sdp)),Yb}}))}setIceServers(e){return Ab(this,null,(function*(){var t;if(this._peerConnection&&0!==e.length)try{if(this._log.info("setIceServers",JSON.stringify(e,((e,t)=>"username"===e||"credential"===e?"hided":t))),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),null!=(t=this._peerConnection)&&t.localDescription||!this.originOffer)return void this._log.warn("setIceServers already has localDescription or no origin Offer");yield this.setOffer(this.originOffer)}catch(AM){this._log.warn("setIceServers error ",AM)}}))}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(Xk){this._log.warn("setPriority error ",Xk)}}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Ab(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 o=Aw(),s={type:"answer",sdp:Wj({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(s),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||FP.addSuccessEvent({key:521703,cost:Aw()-o})}catch(CM){let i=CM instanceof Ub&&CM.code===xb.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(CM),e),this.reset(),!i&&!this.isReconnecting&&(FP.addFailedEvent({key:521703,error:CM}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),CM}}))}reconnect(){return Ab(this,null,(function*(){if(-1===this._reconnectionTimer){if(!this._signalChannel.isConnected)return this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(uG,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=fb({ability:t},e),r=yield this._signalChannel.sendWaitForResponse({command:WG,responseCommand:EG.REBUILD_PEER_CONNECTION_RES,data:i,enableLog:!1});if(0!==r.data.code)throw new Ub({code:r.data.code,message:r.data.message});yield this.connect(r.data.data.ability,!0),FP.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),dM.emit(hM.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(zb){if(!this.isReconnecting)return;if(null!=zb&&zb.message.includes("timeout")){let e=aw(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield jw(e,(e=>{this._reconnectionTimer=e})),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(null==zb?void 0:zb.code," ").concat(zb)),FP.addFailedEvent({key:521704,error:zb}),this.reconnectionCount>=Yk()&&this._log.warn("SDK has tried reconnect for ".concat(Yk()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")}))}getPeerConnection(){return this._peerConnection}startReconnection(){return Ab(this,null,(function*(){this.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(uG,this.reconnect,this),"RECONNECTING"===this.currentState&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===Kk.CLOSED&&this.startReconnection()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){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===Kk.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===Kk.FAILED||e.target.connectionState===Kk.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===Kk.CONNECTED||e.target.connectionState===Kk.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),dM.emit(hM.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 Jk;let e=null;return mL()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,pL()&&0!==this._peerConnection.getReceivers().length&&e?e.state:Jk):Jk}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(Qj.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return Ab(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(nL(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&&XD(t.networkType)),r&&this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port));break}}))}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this.currentState)return e();let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new Ub({code:xb.API_CALL_ABORTED,message:bP({key:IP.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{dM.off(hM.LEAVE_SUCCESS,r,this),this.off(Qj.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{n();let e=new Ub({code:xb.API_CALL_TIMEOUT,message:"connection timeout"});var i;Zj+=1,i=this._signalChannel.isConnected,Zj>2&&!$j&&0===eJ.size&&i&&(this._log.warn("firewall restriction"),$j=!0,this.emit(Qj.FIREWALL_RESTRICTION)),t(e)}),dD);this.clearConnectTimeout=()=>{n(),clearTimeout(o),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new Ub({code:xb.API_CALL_TIMEOUT,message:"connection timeout"}))},dM.on(hM.LEAVE_SUCCESS,r,this),this.on(Qj.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 Ab(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(Xk){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(Xk)),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=Sk.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=sj(this._peerConnection.remoteDescription.sdp));let o,s,a,c=this._parsedAnswer.media.filter((e=>{var t;return null==(t=e.ssrcs)?void 0:t.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(r)}))}));if(3===c.length)o=c[0],s=c[1],a=c[2];else if(3===n.length)o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[0]))),s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[1]))),a=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[2])));else if(0===n.length){this._peerConnection.addTransceiver(Sk.AUDIO,{direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY}),o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=Gj({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:sj(this._peerConnection.localDescription.sdp),isDownlink:!0});s=JSON.parse(JSON.stringify(e)),a=JSON.parse(JSON.stringify(e)),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a)}o.direction=Sk.TRANSCEIVER_DIRECTION_SENDONLY;let l="".concat(r,"-").concat(t.audio);o.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(l)},{id:t.audio,attribute:"msid",value:"".concat(l,"-").concat(Sk.MAIN," ").concat(l,"-audio")}],s.direction=Sk.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(Sk.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(Sk.MAIN," ").concat(l,"-bigvideo")}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=Sk.TRANSCEIVER_DIRECTION_SENDONLY;let d="".concat(l,"-aux");a.ssrcs=[{id:t.auxiliary,attribute:"cname",value:d},{id:t.auxiliary,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Sk.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(Sk.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Sk.VIDEO)}],a.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map((e=>e.mid)).join(" ")),this._downlinkMIDMap.set(i,[o.mid,s.mid,a.mid]),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(s.mid,i),this._downlinkMIDUserIDMap.set(a.mid,i)}removeDownlink(e){return Ab(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=sj(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 Ab(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(yL()){let e=this._peerConnection.getSenders().slice(0,4);for(let s=0;s<e.length;s++){let o,a=e[s];0===s&&t?o=t:1===s&&i?o=i:2===s&&r?o=r:3===s&&n&&(o=n),o&&(yield this.setSenderMaxBitrate(a,o))}let o=!1;i&&e[1].track&&(o=this.setStartBitrate(1,i)),n&&e[3].track&&(o=this.setStartBitrate(3,n)||o),o&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info("setBandwidth ".concat(JSON.stringify(e)))}catch(CM){this._log.error("failed to set bandwidth: ".concat(CM))}}))}setStartBitrate(e,t){var i,r;return!(null==(i=this._peerConnection)||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=sj(this._peerConnection.remoteDescription.sdp)),null==(r=this._parsedAnswer.media[e])||!r.fmtp[0]))&&(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),!0)}setSenderMaxBitrate(e,t){let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),"unlimited"===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,e.setParameters(i)}setBandwidthBySDP(e){let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=sj(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=sj(this._peerConnection.remoteDescription.sdp));let s=wN?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:wN?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:wN?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:wN?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:wN?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:s,limit:wN?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:wN?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:s,limit:wN?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:wN?1e3*n:n}]);let a={type:"offer",sdp:aj(o)};return this.updateSDP({localDescription:a})}setScaleResolutionDownBy(e,t,i){let r=e.getParameters();(!r.encodings||0===r.encodings.length)&&(r.encodings=[{}]);let n=r.encodings[0].scaleResolutionDownBy;if(dw(n)?1===t:t===n)return;let o="setScaleResolutionDownBy ".concat(i," ").concat(t);return n&&(o+=" prevScale: ".concat(n)),this._log.warn(o),r.encodings[0].scaleResolutionDownBy=t,e.setParameters(r)}setDegradationPreference(e,t,i){if(kO&&NO<83||RN&&UO(VO,"12.1")||wN&&ON<138)return;let r=e.getParameters(),n="balanced";if("motion"===t?n="maintain-framerate":"detail"===t&&(n="maintain-resolution"),r.degradationPreference===n)return;let o="setDegradationPreference ".concat(i," ").concat(n);return this._log.info(o),r.degradationPreference=n,e.setParameters(r).catch((e=>this._log.warn("".concat(o," failed: ").concat(e))))}updateSDP(){let{localDescription:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=aj(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,r)=>Ab(this,null,(function*(){var n,o;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,i()}catch(s){this._log.error(s),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection(null==(n=this._peerConnection.localDescription)?void 0:n.sdp)," \nnext offer: ").concat(this.filterSDPDirection(null==e?void 0:e.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection(null==(o=this._peerConnection.remoteDescription)?void 0:o.sdp)," \nnext answer: ").concat(this.filterSDPDirection(t))),this._log.warn("offer: ".concat(null==e?void 0:e.sdp)),this._log.warn("answer: ".concat(t)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map((e=>{let{mid:t,currentDirection:i,direction:r,stopped:n}=e;return{mid:t,currentDirection:i,direction:r,stopped:n}}))))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,r(s)}})))),this._updateSDPPromise}setTransceiverDirection(e,t){return Ab(this,null,(function*(){if(!wN||!this._peerConnection||!this._parsedAnswer)return;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let i=this._peerConnection.getTransceivers();t.forEach((t=>{i[t].direction!==e&&(i[t].direction=e)}));for(let r of t){let t=this._parsedAnswer.media[r].direction;e===Ik.INACTIVE&&t===Ik.RECVONLY&&(this._parsedAnswer.media[r].direction=e),e===Ik.SENDONLY&&t===Ik.INACTIVE&&(this._parsedAnswer.media[r].direction=Ik.RECVONLY)}yield this.updateSDP()}))}filterSDPDirection(){return sj(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((e=>e.direction))}setOffer(e){this._log.info("setting offer");let t=Jj(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 Ab(this,null,(function*(){if("h265"===e&&!this._parsedAnswer&&(this._parsedAnswer=sj(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach((i=>{var r;if(i.type===Sk.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=[],jj(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 Ab(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];dw(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===Sk.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=[],jj(t,n),i=!0)}})),i&&(this._log.warn("use ".concat(e?"hw":"sw"," encoder")),yield this.updateSDP())}))}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),null==(e=this.clearWaitForConnectedPromise)||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach((e=>aN(e.abort)&&e.abort("destroy"))),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map((e=>t[e]))}get isUsingRelay(){return"relay"===this._room.getIceTransportPolicy()}detectTCPAndUDP(e){let{uplinkRTT:t,downlinkRTT:i}=e;var r;if("CONNECTED"!==this.currentState||this._isRelayTried&&!this._room.forceRelay||0===this._room.getIceServers().length)return;let n=this._signalChannel.rtt,o=Math.max(t,i),{rttRatioThreshold:s,rttThreshold:a}=(null==(r=this._room.scheduleResult.config)?void 0:r.useTurnTcpInfo)||{};if(!(s&&a&&n&&o))return;let c=Math.floor(o/n),l=(this._isRelayTried||c>s)&&o>a;l?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(n," upRTT: ").concat(t," downRTT: ").concat(i," ratio: ").concat(c," over-count: ").concat(this._rttOverCount," isOver: ").concat(l," isRelayTried: ").concat(this._isRelayTried," force-relay: ").concat(this._room.forceRelay)),this.isUsingRelay||this._isRelayTried?this._room.forceRelay&&this.switchRelay(!1):(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0))):this._rttOverCount=0}switchRelay(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Ab(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")),FP.addSuccessEvent({key:r,cost:Date.now()-t})}catch(Yb){this._log.warn("switchRelay ".concat(i," failed"),Yb),FP.addFailedEvent({key:r,error:Yb}),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)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:HG,data:{videoDecCodec:"h264"},responseCommand:EG.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)}))}};yb([JV("reconnect")],iJ.prototype,"startReconnection",1),yb([KV((e=>e.userId))],iJ.prototype,"addDownlink",1),yb([KV((e=>e))],iJ.prototype,"removeDownlink",1),yb([jV(!0)],iJ.prototype,"updateSDP",1),yb([qV(521712,!1)],iJ.prototype,"setOffer",1),yb([qV(521713,!1)],iJ.prototype,"setAnswer",1);var rJ=class{constructor(e){Sb(this,"tag"),Sb(this,"len"),Sb(this,"data");let t=new DataView(e);this.tag=t.getUint16(),this.len=t.getUint16(2),this.data=new Uint8Array(e).slice(4,4+this.len).buffer}},nJ=class{constructor(e){Sb(this,"tinyId"),Sb(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new rJ(new Uint8Array(e).slice(i,i+2+2+n).buffer);r.push(o),i+=4+n}r.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},oJ=new Set;function sJ(){let e=Math.floor(4294967296*Math.random());return oJ.has(e)?sJ():(oJ.add(e),e)}var aJ=vb(Rb()),cJ=class extends aJ.default{constructor(e){super(),Sb(this,"userId"),Sb(this,"tinyId"),Sb(this,"_sdpSemantics"),Sb(this,"_isUplink"),Sb(this,"_room"),Sb(this,"_log"),Sb(this,"_currentState","DISCONNECTED"),Sb(this,"_prevTime",-1),Sb(this,"_blackSmallVideoDetectionId"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=_M.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&&(dM.emit(hM.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"))}},lJ=new class{constructor(){Sb(this,"worker"),Sb(this,"callbacks",new Map),Sb(this,"_log"),Sb(this,"sleep",{}),Sb(this,"heartbeatListenerCleaner",new Map),Sb(this,"userIdMap",new Map),this._log=_M.createLogger({id:"bvd"})}getWorker(){if(!this.worker){let e=new Blob(['\n const tracks=new Map;let canvas,ctx;const log=(...t)=>postMessage({type:"log",message:"[worker] "+t.join(" ")});function startDetection(e,t,a){if(!tracks.has(e)){const c={reader:a.getReader(),blackCount:0,timeoutId:null,intervalId:null};tracks.set(e,c),c.timeoutId=setTimeout(()=>stopDetection(e,"timeout"),t),c.intervalId=setInterval(async()=>{try{await isFrameBlack(e)?(c.blackCount++,postMessage({type:"blackCount",trackId:e,count:c.blackCount}),3<=c.blackCount&&(postMessage({type:"black",trackId:e}),stopDetection(e,"black"))):c.blackCount=0}catch(t){log("check black video error:",t.message),stopDetection(e,"error")}},1e3)}}function stopDetection(t,e){var a=tracks.get(t);a&&(a.timeoutId&&clearTimeout(a.timeoutId),a.intervalId&&clearInterval(a.intervalId),a.reader&&a.reader.cancel(),tracks.delete(t),postMessage({type:e,trackId:t}))}async function isFrameBlack(t){t=tracks.get(t);if(!t)return!1;var t=t.reader,{done:t,value:e}=await t.read();if(!e||t)return!1;canvas||(canvas=new OffscreenCanvas(e.codedWidth,e.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===e.codedWidth&&canvas.height===e.codedHeight||(canvas.width=e.codedWidth,canvas.height=e.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(e,0,0,canvas.width,canvas.height);t=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return e.close(),1===t}function getFrameBlackRatio(t){var e=t.data;let a=0;for(let t=0;t<100;t++){var c=4*Math.floor(Math.random()*(e.length/4)),[c,r,n,o]=[e[c],e[1+c],e[2+c],e[3+c]];0<o&&0===c&&0===r&&0===n&&a++}return a/100}self.onmessage=t=>{var{type:t,trackId:e,timeout:a,readable:c}=t.data;"addTrack"===t&&startDetection(e,a,c),"removeTrack"===t&&stopDetection(e)};\n '],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=e=>this._log.warn("worker error:",e.message,e.filename||"unknown",e.lineno||"unknown"),this.worker.onmessage=e=>{var t;let{type:i,trackId:r,message:n,count:o}=e.data;if("black"===i)null==(t=this.callbacks.get(r))||t();else if("log"===i)this._log.warn(n);else if("blackCount"===i){let e=this.userIdMap.get(r);this._log.warn("".concat(e||r," black count: ").concat(o))}}}return this.worker}start(e){let{track:t,isUplink:i,room:r,userId:n,onBlack:o}=e;if(this._log.debug("start detect black video",t.id),!zP()||!o||!t||"undefined"==typeof Worker)return void this._log.warn("black video detector not supported");let s=e=>{var r,o,s,a;let c;if(i)c=null==(o=null==(r=e.msg_up_stream_info)?void 0:r.msg_video_status)?void 0:o.filter((e=>3===e.uint32_video_stream_type))[0];else{let t=null==(s=e.msg_down_stream_info)?void 0:s.filter((e=>{var t;return(null==(t=e.msg_user_info)?void 0:t.str_identifier)===n}))[0];c=null==(a=null==t?void 0:t.msg_video_status)?void 0:a.filter((e=>3===e.uint32_video_stream_type))[0]}if(c){let e=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[t.id]&&this.sleep[t.id]>0)return void(this.sleep[t.id]-=1);e>0&&e<10&&(this.sleep[t.id]=30,this._log.info("track bitrate",e,"start check"),this.checkOnce(t,3e4))}};return r.on("heartbeat-report",s),this.heartbeatListenerCleaner.set(t.id,(()=>r.off("heartbeat-report",s))),this.callbacks.set(t.id,o),this.userIdMap.set(t.id,n),t.id}checkOnce(e,t){try{let i=this.getWorker();if(!i)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:e});i.postMessage({type:"addTrack",trackId:e.id,timeout:t,readable:r.readable},[r.readable])}catch(Xk){this._log.warn("check error:",Xk),this.stop(e.id)}}stop(e){if(e){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:e}),this.callbacks.delete(e),delete this.sleep[e];let t=this.heartbeatListenerCleaner.get(e);t&&t(),this.heartbeatListenerCleaner.delete(e),this.userIdMap.delete(e)}}destroy(){this.callbacks.forEach(((e,t)=>this.stop(t))),this.worker&&(this.worker.terminate(),this.worker=null)}},dJ=class extends cJ{constructor(e){super(gb(fb({},e),{isUplink:!0})),Sb(this,"localMainAudioTrack",null),Sb(this,"localMainVideoTrack",null),Sb(this,"localAuxAudioTrack",null),Sb(this,"localAuxVideoTrack",null),Sb(this,"_isPublishingAux",!1),Sb(this,"_publishingLocalAudioTrack"),Sb(this,"_publishingLocalVideoTrack"),Sb(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),Sb(this,"_flag",0),Sb(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc:r,smallVideoRtxSsrc:n,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:o||0,auxiliaryRtx:s||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];try{if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:i}=this,r=Object.keys(t).filter((e=>{if(t[e]!==i[e]&&t[e])switch(e){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1}));if(r.length>0){if(!e)return void(this._checkPublishStateTimeoutId=sx.run("timeout",(()=>this.checkPublishState(!0)),{delay:1e4,count:1}));FP.addCount({key:521e3}),r.forEach((e=>{this._log.warn("".concat(e," publish failed during call ").concat(sM()," ").concat(tM())),FP.addEnum({key:521719,value:uJ[e]})})),sx.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(Xk){this._log.warn("checkPublishState failed",Xk)}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(_L()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(i=o[2])||!i.track),n.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((e=>{e.track&&(e.track.kind===Sk.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}get publishingState(){let{publishState:e}=this,t=fb({},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&Dk),bigVideo:!!(this.flag&Ck),smallVideo:!!(this.flag&bk),auxVideo:!!(this.flag&kk)}}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 o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}onVideoEncodeFailed(e){if(!e||!e.isMediaTrackActive)return;let{videoCodec:t,singlePC:i}=this;if(!i)return;let r={h265:{supported:i.isH264EncodeSupported,target:"h264",log:"h265 encoder not working, switch to h264"},h264:{supported:i.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working, switch to vp8"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}}[t];this._log.warn(r.log),null!=r&&r.supported&&i.switchVideoEncoder(r.target)}publish(e){return Ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e,o,s,a,c,l,d;if(!t.singlePC)return;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 Ub({code:xb.NOT_SUPPORTED_H264,message:bP({key:IP.NOT_SUPPORTED_H264ENCODE})});t.singlePC.isUsingH264&&!t.singlePC.isH264EncodeSupported&&t.singlePC.isVP8EncodeSupported&&(t._log.warn("h264 encoder not supported"),yield t.singlePC.switchVideoEncoder("vp8")),CN&&115===bO()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(Tk))),r.setProfile(Tk),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:jG,responseCommand:EG.SPC_PUBLISH_RESULT,data:gb(fb({},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,yield t.singlePC.setDegradationPreference(t._peerConnection.getSenders()[n?3:1],r.contentHint,r.streamType);let{scaleResolutionDownBy:e}=r;yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[n?3:1],e,r.streamType)}i&&(t[n?"localAuxAudioTrack":"localMainAudioTrack"]=i),yield t.singlePC.setBandwidth({audio:(null==(e=t.localMainAudioTrack)?void 0:e.profile.bitrate)||(null==(o=t.localAuxAudioTrack)?void 0:o.profile.bitrate),bigVideo:null==(s=t.localMainVideoTrack)?void 0:s.profile.bitrate,smallVideo:null==(c=null==(a=t.localMainVideoTrack)?void 0:a.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),t.sendMediaSettings(),t.installTrackMuteEvents(i,r),(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(!fL())return;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[],d=(e,t,i)=>{var r;let n=a[t].sender.replaceTrack(i);l.push(t),null!=(r=this.singlePC)&&r.enableInsertableStreams&&n.then((()=>this.createEncodedStreams(a[t].sender,e))),this.initSenderTransform(a[t].sender,e),c.push(n)};s&&d(t.mediaType,0,s),o&&d(i.mediaType,n?3:1,o),null!=i&&i.small&&c.push(this.publishSmall(this._room.videoManager.smallMode,i));let u=this.singlePC.setTransceiverDirection(Ik.SENDONLY,l);return c.push(u),Promise.all(c)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var i,r;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let n=e.createEncodedStreams(),o=new AbortController;null==(i=this.singlePC)||i.addAbortController(e,o),(null!=(r=this.getTrackByMediaType(t))&&r.enableEncodeFrame?n.readable.pipeThrough(new TransformStream({transform:(e,i)=>{var r,n;let o=this.getTrackByMediaType(t);i.enqueue((null!=(r=this.singlePC)&&r.isUsingH264||null!=(n=this.singlePC)&&n.isUsingH265)&&o?o.encodeFrame(e,8===t):e)}}),o):n.readable).pipeTo(n.writable,o).catch((e=>{this._log.debug("encoded stream error",e),"destory"!==e&&this._log.warn(e)}))}initSenderTransform(e,t){if(!(this._peerConnection&&this.singlePC&&this.singlePC.scriptTransformWorker&&bL))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 Ab(this,null,(function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()}))}publishSmall(e){return Ab(this,arguments,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.localMainVideoTrack;return function*(){var r;if(!t.singlePC)return;if("canvas"===e&&!lL())return void t._log.warn("canvas mode small stream is not supported");let n=t._peerConnection.getTransceivers(),{sender:o}=n[2],s=yield t.doPublishSmall(e,i),a="canvas"===e?524700:524701;FP.addSuccessEvent({key:a}),s?(null!=(r=t.singlePC)&&r.enableInsertableStreams&&t.createEncodedStreams(o,8),t.initSenderTransform(o,8),yield t.singlePC.setTransceiverDirection(Ik.SENDONLY,[2]),t.updateMediaSettings(),yield t.doPublishChange(),t._blackSmallVideoDetectionId=lJ.start({track:o.track,room:t._room,isUplink:!0,userId:t.userId,onBlack:()=>{t._log.warn("small video is black");let i="canvas"===e?524700:524701;FP.addFailedEvent({key:i,error:10002}),lJ.stop(t._blackSmallVideoDetectionId),t._blackSmallVideoDetectionId=void 0}})):FP.addFailedEvent({key:a,error:10001})}()}))}doPublishSmall(e){return Ab(this,arguments,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.localMainVideoTrack;return function*(){if(!t.singlePC)return null;t._log.info("publish small",e);let r=t._peerConnection.getTransceivers(),{sender:n}=r[2];if("canvas"===e&&t._room.videoManager.smallTrack)return yield n.replaceTrack(t._room.videoManager.smallTrack),"canvas";if("api"===e&&null!=i&&i.outMediaTrack&&null!=i&&i.small){yield n.replaceTrack(null==i?void 0:i.outMediaTrack);let e=n.getParameters(),r=zw(null==i?void 0:i.profile,null==i?void 0:i.small);return t._log.info("small scaleResolutionDownBy",r),e.encodings[0].scaleResolutionDownBy=r,n.setParameters(e),"api"}return t._log.warn("small track can not be enabled, smallMode: ".concat(t._room.videoManager.smallMode,", smallTrack: ").concat(!!t._room.videoManager.smallTrack,", bigVideoTrack: ").concat(!(null==i||!i.outMediaTrack))),null}()}))}unpublishSmall(){return Ab(this,null,(function*(){this.singlePC&&(this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Ik.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),lJ.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return Ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){var e;yield null==(e=t.singlePC)?void 0:e.waitForPeerConnectionConnected();let n=r&&r===t.localAuxVideoTrack||i&&i===t.localAuxAudioTrack,o=null==r?void 0:r.outMediaTrack,s=t._peerConnection.getSenders(),a=[];i&&(n?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localMainAudioTrack&&!t.localAuxAudioTrack&&(yield s[0].replaceTrack(null),a.push(0))),o&&(n?(yield s[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=gb(fb({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),a.push(3)):(yield s[1].replaceTrack(null),yield s[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=gb(fb({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),a.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.singlePC.setTransceiverDirection(Ik.INACTIVE,a),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 Ab(this,null,(function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:RG,data:t,responseCommand:EG.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:CG,commandDesc:"unpublish",responseCommand:EG.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===xb.API_CALL_TIMEOUT||e.getCode()===xb.API_CALL_ABORTED)return Promise.resolve();throw e}))}updateMediaSettings(){var e,t;this._mediaSettings.videoCodec=(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264",this._mediaSettings.videoDecCodec=(null==(t=this.singlePC)?void 0:t.downlinkVideoCodec)||"h264";let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),IL){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(),{scaleResolutionDownBy:t}=r;this._mediaSettings.videoWidth=e.width/t||0,this._mediaSettings.videoHeight=e.height/t||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(),{scaleResolutionDownBy:t}=n;this._mediaSettings.auxVideoWidth=e.width/t||0,this._mediaSettings.auxVideoHeight=e.height/t||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:HG,data:this._mediaSettings,responseCommand:EG.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return Ab(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Sk.AUXILIARY:Sk.MAIN," stream")),_L()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return Ab(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Sk.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),1===n&&null!=(i=this.localMainVideoTrack)&&i.small&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Ik.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Ik.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return Ab(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?Sk.AUXILIARY:Sk.MAIN," stream")),_L()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return Ab(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Sk.AUDIO)yield i[0].sender.replaceTrack(null);else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._room.videoManager.hasSmall&&(yield i[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(Ik.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}replaceTrack(e){return Ab(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?Sk.AUXILIARY:Sk.MAIN," stream")),r.kind===Sk.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===Sk.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0}))}setBandwidth(e){return Ab(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===Sk.AUDIO?e.audio=i:"big"===n?e.bigVideo=i:"small"===n?e.smallVideo=i:e.auxVideo=i,yield t.singlePC.setBandwidth(e)}}()}))}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:IG,responseCommand:EG.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&dM.emit(hM.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Sk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Sk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Sk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Sk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Sk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===nD?(this._log.error(AP.NOT_SUPPORTED_H264ENCODE),new Ub({code:xb.NOT_SUPPORTED_H264,message:bP({key:IP.NOT_SUPPORTED_H264ENCODE})})):new Ub({code:xb.UNKNOWN,message:bP({key:IP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:EG.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return Ab(this,null,(function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))}))}};yb([xV((function(e){let{localVideoTrack:t}=e;null==t||t.once("6",this.onVideoEncodeFailed,this)}))],dJ.prototype,"publish",1),yb([xV((function(e){let{localVideoTrack:t}=e;null==t||t.off("6",this.onVideoEncodeFailed,this)}))],dJ.prototype,"unpublish",1);var uJ=(e=>(e[e.audio=1]="audio",e[e.bigVideo=2]="bigVideo",e[e.smallVideo=3]="smallVideo",e[e.auxVideo=4]="auxVideo",e))(uJ||{}),hJ=dJ;function pJ(e){return Object.keys(e).filter((t=>e[t]))}var mJ=class extends cJ{constructor(e){super(gb(fb({},e),{isUplink:!1})),Sb(this,"_flag",0),Sb(this,"isRobot",!1),Sb(this,"role","anchor"),Sb(this,"remoteAudioTrack"),Sb(this,"remoteVideoTrack"),Sb(this,"remoteAuxiliaryTrack"),Sb(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),Sb(this,"jitterBufferTimeoutId",-1),Sb(this,"_videoCodec"),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new QB(this._room,this),this.remoteVideoTrack=new ZB(this._room,this),this.remoteAuxiliaryTrack=new $B(this._room,this),this.initialize()}get videoCodec(){var e;return this._videoCodec||(null==(e=this.singlePC)?void 0:e.downlinkVideoCodec)||"h264"}set videoCodec(e){this._videoCodec=e}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 Dw(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===Sk.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){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),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,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:o}=e;if(!r.id.includes(this.tinyId))return;let s=r.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(s," ").concat(n.kind));let a=Sk.AUDIO;n.kind===Sk.VIDEO&&(a=s===Sk.MAIN?Sk.VIDEO:Sk.AUXILIARY);let c=this.remoteAudioTrack;a===Sk.VIDEO?c=this.remoteVideoTrack:a===Sk.AUXILIARY&&(c=this.remoteAuxiliaryTrack),null==(t=this.singlePC)||t.receiverRemoteTrackMap.set(o,c),null!=(i=this.singlePC)&&i.scriptTransformWorker&&this.initReceiverTransform(o,s,n.kind===Sk.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(o),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,n;let o=null==(i=this.singlePC)?void 0:i.receiverRemoteTrackMap.get(e);return o&&("video"!==o.kind||null!=(r=this.singlePC)&&r.isUsingH264||null!=(n=this.singlePC)&&n.isUsingH265)?o.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 Ab(this,null,(function*(){var i,r;try{let n=!0;if(this._log.info("subscribe ".concat(t," ").concat(pJ(e))),this.hasSSRC){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else{if(null!=(i=this.singlePC)&&i.autoSubscribedUserMap.size){let e=this.singlePC.autoSubscribedUserMap.get(this.userId);if(e){this.singlePC.autoSubscribedUserMap.delete(this.userId);let t=null==(r=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))?void 0:r[e.groupIndex];t&&(this.ssrc={audio:t.audioSsrc,video:t.bigVideoSsrc,videoRtx:t.bigVideoRtxSsrc,auxiliary:t.auxVideoSsrc,auxiliaryRtx:t.auxVideoRtxSsrc},n=!1)}}yield this.doSubscribe(e,n),this.checkTrackEnded(e)}if(e.smallVideo){let{user:e,mediaTrack:t}=this.remoteVideoTrack;FP.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=lJ.start({track:t,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,e),FP.addFailedEvent({key:524702}),lJ.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})}else lJ.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}catch(Yb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Yb.message," ").concat(JSON.stringify(this.muteState))),new Ub({code:xb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Yb}}))}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"),kO&&NO<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return Ab(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=fb({},t.subscribeState);i.forEach((e=>{switch(e.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1}}));let o="subscribe_change";Object.values(n).find((e=>!0===e))||(o="unsubscribe"),t._log.info("".concat("unsubscribe"===o?o:"subscribe"," ").concat(r," [").concat(pJ(n),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,n),"main"===r&&(lJ.stop(t._blackSmallVideoDetectionId),t._blackSmallVideoDetectionId=void 0),"unsubscribe"===o&&(yield t.removeDownlink())}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=kG,n=EG.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=DG,n=EG.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 Ub({code:i.code,message:bP({key:IP.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(){return Ab(this,null,(function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())}))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected();try{if(i||!e.hasSSRC){let i={audioSsrc:sJ(),bigVideoSsrc:sJ(),bigVideoRtxSsrc:sJ(),auxVideoSsrc:sJ(),auxVideoRtxSsrc:sJ()},{audioSsrc:n,bigVideoSsrc:o,bigVideoRtxSsrc:s,auxVideoSsrc:a,auxVideoRtxSsrc:c}=i;e.ssrc={audio:n,video:o,videoRtx:s,auxiliary:a,auxiliaryRtx:c},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let r=yield e._signalChannel.sendWaitForResponseWithRetry({command:JG,responseCommand:EG.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&&-10036!==r.data.code)throw new Ub({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{if(!FL)return;let{main:t,aux:i}=e._room.jitterBufferDelay||{},{jitterDelay:r=t,jitterDelayAux:n=i}=e._room.scheduleResult.config||{};(hw(r)||hw(n))&&e.setJitterBufferDelay({mainDelay:r,auxDelay:n})}}}()}))}removeDownlink(){return Ab(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(!FL||!this.singlePC||!this._peerConnection||cN(t)&&cN(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return hw(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),hw(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,cN(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||cN(t)&&e.track===this.remoteAudioTrack.outMediaTrack;if(n&&cN(i)||!n&&cN(t))return;let o=n?i||0:t,s=(e.jitterBufferTarget||0)+100;s>o||(e.jitterBufferTarget=s,this._log.debug("set ".concat(n?"aux ":"").concat(null==(r=null==e?void 0:e.track)?void 0:r.kind," jitterBuffer delay ").concat(s," -> ").concat(o)))})),!r.find((e=>{let r=e.track===this.remoteAuxiliaryTrack.outMediaTrack?i||0:t;return e.jitterBufferTarget<r})))return this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i," done")),n();this.jitterBufferTimeoutId=setTimeout((()=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:n})}),1e3)}catch(Yb){this._log.warn("set jitterBuffer delay error: ".concat(Yb)),clearTimeout(this.jitterBufferTimeoutId),n()}}get audioReceiver(){var e;return(null==(e=this.singlePC)?void 0:e.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){"h265"===this._room.downlinkVideoCodec&&this._room.requestRemoteFallbackToH264()}};yb([jV(),UV((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 Ub({code:xb.API_CALL_ABORTED,message:bP({key:IP.CONNECTION_ABORTED,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],mJ.prototype,"subscribe",1),yb([jV()],mJ.prototype,"unsubscribe",1),yb([KV((()=>"jitter"))],mJ.prototype,"setJitterBufferDelay",1);var _J=mJ;var fJ=vb(Rb());var gJ=class e extends fJ.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,Sb(this,"log"),Sb(this,"cmdIdSeqMap",new Map),Sb(this,"messageMap",new Map),this.log=_M.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(EG.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(zG,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),jw(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 o=null==r?void 0:r.cachedMessageMap.get(n.seq+1);o&&this.emitMessage(o.message)}};Sb(gJ,"SEQ_INTERVAL",300);var EJ,TJ=gJ,{isString:vJ,isUndefined:yJ,getNetworkType:SJ,isEmpty:IJ}=Gb,AJ=class extends Vj{constructor(e){super(e),Sb(this,"_businessInfo"),Sb(this,"userManager"),Sb(this,"_version"),Sb(this,"_heartbeat",-1),Sb(this,"_lastHeartBeatTime",-1),Sb(this,"_stats"),Sb(this,"_joinTimeout",-1),Sb(this,"_firstPublishedList",null),Sb(this,"_joinReject",null),Sb(this,"_isRelayChanged",!1),Sb(this,"sdpSemantics"),Sb(this,"signalChannel",null),Sb(this,"uplinkConnection",null),Sb(this,"singlePC",null),Sb(this,"enableSPC",gL),Sb(this,"_changeBigSmallRecords",new Map),Sb(this,"networkQuality"),Sb(this,"_iceTransportPolicy"),Sb(this,"forceRelay",!1),Sb(this,"_turnServers",[]),Sb(this,"_iceServersFromJoin"),Sb(this,"_syncUserListInterval",-1),Sb(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),Sb(this,"enableSEI",!1),Sb(this,"_enableAudioVolumeEvaluation",!1),Sb(this,"_audioVolumeIntervalId",0),Sb(this,"_enableMultiAuxStream",!1),Sb(this,"_pureAudioPushMode",!1),Sb(this,"_customMessageManager"),Sb(this,"preferHW",!1),Sb(this,"healthDetector"),Sb(this,"playoutDelay"),Sb(this,"jitterBufferDelay"),Sb(this,"_updateAudioLevelTaskId",-1),this._stats=new mj(this,this._log),this.userManager=new oH(this.userId,this._log),this._version=Kb,this.sdpSemantics=rD,yJ(e.sdpSemantics)?EM.isUnifiedPlanDefault()&&(this.sdpSemantics=iD):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(SJ())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!yJ(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&gL,!yJ(e.enableSPC)&&gL&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new zj(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])))}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264"}get downlinkVideoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.downlinkVideoCodec)||"h264"}join(e,t,i){return Ab(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",(e=>{this.emit("peer-join",e)})),this.userManager.on("2",(e=>{this.closeDownLinkConnection(e,"remote user exitRoom"),this.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(e=>{var t=((e,t)=>{var i={};for(var r in e)ub.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&lb)for(var r of lb(e))t.indexOf(r)<0&&hb.call(e,r)&&(i[r]=e[r]);return i})(e,[]);dM.emit(hM.REMOTE_PUBLISH_STATE_CHANGED,fb({room:this},t)),this.emit("remote-publish-state-changed",fb({},t))})),this.joinParams=e,new Promise(((t,i)=>Ab(this,null,(function*(){var r,n;this._joinReject=i;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(o){if(!(o instanceof Ub&&o.code===xb.SPC_INITIALIZED_FAILED))return i(o);null==(r=this.signalChannel)||r.destroy(),yield this.initialize()}let s=Aw();yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),FP.addSuccessEvent({key:521708,cost:Aw()-s}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(yM){FP.addFailedEvent({key:521708,error:yM}),i(yM)}this._joinReject=null}))))}))}initSinglePC(){return Ab(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new iJ({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(zb){throw this.fallbackToMPC(),new Ub({code:xb.SPC_INITIALIZED_FAILED,message:null==zb?void 0:zb.message})}}}))}doJoin(e,t){return new Promise(((i,r)=>Ab(this,null,(function*(){var n,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(pG,(e=>{this.clearJoinTimeout(),dM.emit(hM.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)})),pw(null==(o=null==(n=this.scheduleResult)?void 0:n.config)?void 0:o.singlePC)&&gL&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);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:aM(),netType:QD(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;null!=(s=this.scheduleResult.config)&&s.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{r(new Ub({code:xb.JOIN_ROOM_FAILED,message:bP({key:IP.JOIN_ROOM_TIMEOUT})}))}),c),dM.emit(hM.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?GG:vG,a),this.signalChannel.once(EG.JOIN_ROOM_RESULT,(t=>Ab(this,null,(function*(){this.clearJoinTimeout();let{code:n,message:o,data:s,tinyId:a}=t.data;dM.emit(hM.JOIN_RECEIVED_CMD_RES,{room:this,code:n}),0===n?(this._log.info("Join room success, start heartbeat"),a&&(this.tinyId=a),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=s.publishers,this._iceServersFromJoin=s.iceServer?[s.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then((()=>{var t;null==(t=this.singlePC)||t.connect(gb(fb({},s.ability),{useVp8:s.ability.useVp8||!!e.useVp8,useH265:s.ability.useH265||!!e.useH265})).catch((()=>{}))})),i()):(this._log.error("Join room failed result: ".concat(n," error: ").concat(o)),r(new Ub({code:xb.JOIN_ROOM_FAILED,extraCode:n,message:bP({key:IP.JOIN_ROOM_FAILED,data:{error:o,code:n}})})))}))))}))))}reJoin(){return Ab(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then((t=>(e=t,t))))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(gb(fb({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),hx.logSuccessEvent({userId:this.userId,eventType:Zk.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(Qj.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof hJ&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(Qj.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof pj&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(zb){this._log.warn("reJoin fail ".concat(zb)),this.reset(),hx.logFailedEvent({userId:this.userId,eventType:Zk.REJOIN,error:zb}),this.emit("error",new Ub({code:xb.JOIN_ROOM_FAILED,message:bP({key:IP.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return Ab(this,null,(function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this.signalChannel||function(e){let t=[...XG.values()].find((t=>t.room.userId===e&&!t.room.isJoined));return t||null}(this.userId),n=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId&&r.room===this);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):(r&&r.close(),this.signalChannel=new ZG({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:t,backupUrl:i,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?e:void 0}),this._customMessageManager=new TJ(this,this.signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this.networkQuality||(this.networkQuality=new Ej({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Ej.EVENT_NETWORK_QUALITY,(e=>{var t;this.emit("network-quality",e),null==(t=this.singlePC)||t.detectTCPAndUDP(e)}))),dx(this,this.signalChannel).add(dG,(e=>{dM.emit(hM.SIGNAL_CONNECTION_STATE_CHANGED,fb({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(hG,(e=>{this.reset(),this.emit("error",e)})).add(EG.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})).add(EG.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(EG.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(EG.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(hx.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})})).add(EG.SEND_SWITCH_ROOM_SUBED_REQ,(e=>{if(!this.singlePC)return;let{subList:t}=e.data.data;t.forEach((e=>{this.singlePC.autoSubscribedUserMap.set(e.userId,e)}))})).add(EG.FALLBACK_CODEC,(e=>Ab(this,null,(function*(){var t,i,r,n,o;let s=e.data.data;this._log.warn("fallback codec enableH265Enc: ".concat(null==(t=s.videoControlInfo)?void 0:t.enableH265Enc)),0===(null==(i=s.videoControlInfo)?void 0:i.enableH265Enc)&&"h265"===(null==(r=this.singlePC)?void 0:r.videoCodec)&&(FP.addCount({key:513e3}),yield null==(n=this.singlePC)?void 0:n.switchVideoEncoder("h264"),yield null==(o=this.uplinkConnection)?void 0:o.sendMediaSettings())})))),this.signalChannel.once(lG,(e=>{this.tinyId=e.signalInfo.tinyId,dM.emit(hM.JOIN_SIGNAL_CONNECTION_END,{room:this})})),dM.emit(hM.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&dM.emit(hM.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this.signalChannel=e,e||ux(this)}leave(){return Ab(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(Xk){}this._log.info("leave() => leaving room"),dM.emit(hM.LEAVE_SEND_CMD,{room:this}),null==(e=this.signalChannel)||e.send(yG)}))}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=sx.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),sx.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return Ab(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});this.badCaseDetector.resetMonitor();let r=null!=(e=this.signalChannel)&&e.isConnected?function(e){if(eH.has(e)){let t=eH.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 eH.delete(e),t}return[]}(this.userId):[],n=gb(fb({str_sdk_version:Jb,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:fb({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:QD()},i.msg_device_info)});if(this.heartbeatReport=n,dM.emit(hM.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(SG,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",gb(fb({},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!==Mk)).map((e=>{let{userId:t,srcTinyId:i,flag:r}=e;t===this.userId&&(this.uplinkConnection&&(this.uplinkConnection.flag=r),this.localPublishFlag!==r&&(this.localPublishFlag=r,this.emit("local-publish-flag-changed",r)));let n=this.remotePublishedUserMap.get(t);return n&&this.checkSubscribeBigSmallVideo(n),{userId:t,tinyId:i,flag:r}}));e.data.mixRobotList.forEach((e=>{let{userId:i,srcTinyId:r,flag:n,mixUserList:o}=e;t.unshift({userId:i,tinyId:r,flag:n,isRobot:!0,mixUserList:o})})),e.data.fakeMixUser&&(e.data.fakeMixUser.tinyId=e.data.fakeMixUser.srcTinyId,t.push(e.data.fakeMixUser)),dM.emit(hM.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),t.find((e=>e.userId===this.userId))||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),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().catch((()=>{})),this.uplinkConnection.close(e),this.uplinkConnection instanceof pj&&(this.uplinkConnection=null)),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r,isRobot:n}=e,o=new(this.singlePC?_J:dj)({userId:t,tinyId:i,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:n});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,t),this.emit("remote-published",o)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",(e=>{let i=e.getCode();i!==xb.ICE_TRANSPORT_ERROR&&(i===xb.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",gb(fb({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=sx.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){sx.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:FG,responseCommand:EG.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 bP({key:IP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:EG.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||!rj)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?(null==(e=this.singlePC.getPeerConnection())?void 0:e.connectionState)===Kk.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof nj&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===Kk.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return Ab(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),hx.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,null==(e=this.singlePC)||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new pj({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 dj({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 Ub({code:xb.INVALID_OPERATION,message:bP({key:IP.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),sx.clearTask(this._audioVolumeIntervalId))}switchRole(e){return Ab(this,null,(function*(){this.role!==e&&("audience"===e&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))}))}doSwitchRole(e){let t={command:BG,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:EG.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 Ub({code:xb.SWITCH_ROLE_FAILED,message:bP({key:IP.SWITCH_ROLE_FAILED,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof Ub&&e.getCode()===xb.API_CALL_TIMEOUT&&(e=new Ub({code:xb.SWITCH_ROLE_FAILED,message:bP({key:IP.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e}))}publish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Ab(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof uB&&(t instanceof JB?i.audio=t:e.audio=t),t instanceof _B&&(t instanceof GB&&2===t.mediaType?i.video=t:e.video=t)}));let r=IJ(e),n=IJ(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new hJ({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new pj({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",gb(fb({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==xb.ICE_TRANSPORT_ERROR&&(t===xb.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})));let o=t.map((e=>e.kind)).join(",");r||(this._log.info("publish() => main ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:e.audio,localVideoTrack:e.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info("publish() => aux ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:i.audio,localVideoTrack:i.video,isAuxiliary:!0}),this._log.info("aux is published"))}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Ab(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let e={},i={};t.forEach((t=>{!t.mediaTrack||!t.isPublished||(t instanceof uB&&(t instanceof JB?i.audio=t:e.audio=t),t instanceof _B&&(t instanceof GB&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");IJ(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),IJ(i)||(this._log.info("unpublish() => aux ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(bM){}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&&vL()?this.uplinkConnection.replaceTrack(e).then((t=>{t&&dM.emit(hM.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return Ab(this,null,(function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return Ab(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:Sk.VIDEO,videoType:Sk.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)}))}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Ab(this,null,(function*(){if(t=t.filter((e=>!e.isSubscribed)),0===t.length)return;let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let r=t.find((e=>2===e.mediaType))?"auxiliary":"main";try{let n=fb({},i.subscribeState);t.forEach((e=>{switch(e.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0}}));let o=this._changeBigSmallRecords.get(e);o&&o.options.smallVideo&&i.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),dM.emit(hM.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(cj(n),"] prev: [").concat(cj(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());dM.emit(hM.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(Yb){let i=Yb instanceof Ub?Yb.getCode():xb.UNKNOWN,n=Yb;throw Yb instanceof Ub?i===xb.REMOTE_STREAM_NOT_EXIST&&(n=new Ub({code:xb.API_CALL_ABORTED,message:bP({key:IP.API_CALL_ABORTED,data:{message:Yb.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new Ub({code:i,message:bP({key:IP.SUBSCRIBE_FAILED,data:{message:Yb.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 Ab(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(Yb){this._log.warn("unsubscribe() => failed ".concat(Yb))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),dM.emit(hM.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 sx.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),dM.emit(hM.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&sx.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=sx.run("intervalInWorker",(()=>{var i;cV.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];null==(i=this.remotePublishedUserMap)||i.forEach((e=>{if(e.muteState.hasAudio){!cV.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,floatVolume:e.remoteAudioTrack.getInternalAudioLevel()})}})),this.emit("audio-volume",r)}),{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return Ab(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=sx.run("intervalInWorker",(()=>Ab(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack)return void this.stopUpdateAudioLevelFromSenderStat();let e=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:t}=this.uplinkConnection;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"),sx.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(!SL||!i)return;let r=null==(t=i.getSynchronizationSources()[0])?void 0:t.audioLevel;hw(r)?e.remoteAudioTrack.volume=Math.min(2*r,1):i.getStats().then((t=>{t.forEach((t=>{"inbound-rtp"===t.type&&hw(t.audioLevel)&&(e.remoteAudioTrack.volume=t.audioLevel)}))}))}getLocalAudioStats(){return Ab(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 Ab(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 Ab(this,null,(function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let i=yield this._stats.getReceiverStats(t);e.downlinksRTT[i.userId]=i.rtt}return e}))}getRemoteVideoStats(e){return Ab(this,null,(function*(){let t={};for(let[i,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 Ab(this,null,(function*(){let e={};for(let[t,i]of this.remotePublishedUserMap)i.muteState.hasAudio&&(e[t]=i.remoteAudioTrack.stat);return e}))}setTurnServer(e,t){this._log.info("set turn server: ".concat(JSON.stringify(e)," ").concat(t||""));let i=[];Array.isArray(e)?e.forEach((e=>i.push(Gb.getTurnServer(e)))):Gb.isPlainObject(e)&&i.push(Gb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:PG,data:e,timeout:5e3,responseCommand:EG.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e}))}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:LG,data:e,timeout:5e3,responseCommand:EG.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e}))}sendStartPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?wG:OG,data:e,timeout:5e3,responseCommand:t?EG.START_PUBLISH_TENCENT_CDN_RES:EG.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e}))}sendStopPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?NG:MG,data:e,timeout:5e3,responseCommand:t?EG.STOP_PUBLISH_TENCENT_CDN_RES:EG.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e}))}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:xG,data:e,timeout:5e3,responseCommand:EG.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e}))}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:VG,data:e,timeout:5e3,responseCommand:EG.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e}))}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:UG,data:e,timeout:5e3,responseCommand:EG.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e}))}sendAbilityStatus(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:KG,data:e,timeout:5e3,responseCommand:EG.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch((e=>{}))}getIceServers(e){var t,i;return this._turnServers.length>0?this._turnServers:null!=(t=this.scheduleResult.iceServers)&&t.length?this.scheduleResult.iceServers:null!=e&&e.length?e:null!=(i=this._iceServersFromJoin)&&i.length?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=Gb.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 Ab(this,null,(function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:r,hasVideo:n}}=e;if(!r&&!n||!t.video&&!t.smallVideo)return;let o=this._changeBigSmallRecords.get(i);if(!o||o.isSubscribing||o.reSubscribeCount<=0)return;let{options:s,reSubscribeCount:a}=o;if(s.video&&t.video||s.smallVideo&&t.smallVideo&&r)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:s.video,smallVideo:s.smallVideo};try{if(!r&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;o.isSubscribing=!0,o.reSubscribeCount=a-1,yield e.subscribe(c,"main"),e.remoteVideoTrack.setMediaType(c.smallVideo?8:4),this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video successfully. count ").concat(vD-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=vD}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(vD-o.reSubscribeCount,". reason: ").concat(l)),o.isSubscribing=!1,0===o.reSubscribeCount&&this._changeBigSmallRecords.delete(i)}}))}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:vD};this._changeBigSmallRecords.set(t.userId,i),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big")),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});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(vJ(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!yJ(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new Ub({code:xb.INVALID_PARAMETER,message:bP({key:IP.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(!yJ(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new Ub({code:xb.INVALID_PARAMETER,message:bP({key:IP.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!yJ(e.userDefinePushArgs)){if(!(vJ(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new Ub({code:xb.INVALID_PARAMETER,message:bP({key:IP.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}IJ(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){return Ab(this,null,(function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&CL)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 Ub({code:xb.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}switchRoom(e){return Ab(this,null,(function*(){var t,i;if(!this.signalChannel)return;let{roomId:r,strRoomId:n,userSig:o,privateMapKey:s}=e,a=(null==(t=this.scheduleResult.config)?void 0:t.autoSubscribeCount)||(null==e?void 0:e.autoSubscribeCount)||1,c=String(this.useStringRoomId?n:r),l=[];for(let e=0;e<a;e++)l.push({audioSsrc:sJ(),bigVideoSsrc:sJ(),bigVideoRtxSsrc:sJ(),auxVideoSsrc:sJ(),auxVideoRtxSsrc:sJ()});let d={currRoomId:this.roomId,targetRoomId:c,useStringRoomId:this.useStringRoomId,ability:null==(i=this.singlePC)?void 0:i.clientAbility,userSig:null!=o?o:this.userSig,privateMapKey:null!=s?s:this.privateMapKey,subscribe:l};this.singlePC&&(this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(c,l));let u=this.roomId;this.roomId=this.useStringRoomId?n:String(r),dM.emit(hM.SWITCH_ROOM_START,{room:this});let h=yield this.signalChannel.sendWaitForResponse({command:YG,responseCommand:EG.SEND_SWITCH_ROOM_RES,data:d}),{code:p,message:m}=h.data;if(0!==p){this._log.error("switch room failed. result: ".concat(p," error: ").concat(m)),this.roomId=u,this.singlePC&&this.singlePC.autoSubscribedSsrcGroups.clear();let e=new Ub({code:xb.SWITCH_ROOM_FAILED,extraCode:p,message:m});throw dM.emit(hM.SWITCH_ROOM_FAILED,{room:this,error:e}),e}yJ(o)||(this.userSig=o),yJ(s)||(this.privateMapKey=s),dM.emit(hM.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:u,targetRoomId:c})}))}isSwitchRoomSupported(){var e;let t="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return!0!==(null==(e=this.scheduleResult.config)?void 0:e.switchRoom)?(this._log.warn("".concat(t," Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.")),!1):"live"!==this.scene?(this._log.warn("".concat(t," Reason: the scene is not 'live'.")),!1):"audience"!==this.role?(this._log.warn("".concat(t," Reason: the role is not 'audience'.")),!1):!!this.singlePC||(this._log.warn("".concat(t," Reason: is not using single peerConnection.")),!1)}requestRemoteFallbackToH264(){var e;null==(e=this.singlePC)||e.requestRemoteFallbackToH264()}};return yb([QL(["left",ex.INIT],"joined"),mx({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"),qH(!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())}}),UV((e=>{let t=new sG;return function(i,r,n){return Ab(this,null,(function*(){let o=String(i.roomId||i.strRoomId);if(this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.userSig=i.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,i.privateMapKey=i.privateMapKey||"",this.isJoined)throw new Ub({code:xb.INVALID_OPERATION,message:bP({key:IP.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new Ub({code:xb.INVALID_OPERATION,message:bP({key:IP.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:o}),this.role=21===i.role?"audience":"anchor",this._log.info("Join() => joining room: ".concat(o," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),dM.emit(hM.JOIN_START,{room:this,roomId:o,params:i});let s=Gb.getEnv();s||(s=uk.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Ak.OLD_CLOUD_LADDER)?s=uk.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Ak.WEBRTC)&&(s=uk.WEBRTC))),hx.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),EM.checkSystemRequirementsInternal(n).then((e=>{this.checkSystemResult=e,aG.call(this)}));try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Gb.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=Gb.performanceNow(),dM.emit(hM.JOIN_SUCCESS,{room:this}),30===n&&!i.component&&hx.uploadEvent({log:"stat-conv-".concat(Number(KO),"-").concat(location.hostname),userId:this.userId}),t}catch(CM){throw t.delete({room:this,roomId:o}),dM.emit(hM.JOIN_FAILED,{room:this,error:CM}),CM}}))}}))],AJ.prototype,"join",1),yb([QL("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),UV((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Ab(this,null,(function*(){dM.emit(hM.LEAVE_START,{room:this}),yield e.call(this,...i),dM.emit(hM.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),JV("leave room"),_x({fnName:"publish",validateArgs:!1}),_x({fnName:"unsubscribe",validateArgs:!1})],AJ.prototype,"leave",1),yb([jV(),UV((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Ab(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"ready"===e.state)),!i.length))return;dM.emit("61",{room:this});let t=e.apply(this,i);return Promise.all(i.map((e=>e.publish(this,t))))}))})),mx({settings:{retries:Yk,timeout:e=>aw(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),dM.emit(hM.PUBLISH_FAILED,{room:this}))}})],AJ.prototype,"publish",1),yb([_x({fnName:"publish"}),(EJ="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=WV.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 Ub({code:xb.API_CALL_ABORTED,message:EJ})),!1)}));n.queue=e}return r.apply(this,t)},i}),jV(),UV((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})),xV((function(){var e,t;0===this.localTracks.size&&mL()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((e=>e.track&&e.replaceTrack(null))))}))],AJ.prototype,"unpublish",1),yb([VV((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e})),KV((e=>e.userId))],AJ.prototype,"replaceTrack",1),yb([KV((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),zB(),UV((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})),mx({settings:{retries:Yk,timeout:e=>aw(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),dM.emit(hM.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],AJ.prototype,"subscribe",1),yb([_x({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")}))}}),KV((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],AJ.prototype,"unsubscribe",1),oG.create=oG._create.bind(oG,AJ),VL(30),oG}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TRTC=t()}(this,(function(){function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r=function(e){return e&&e.Math===Math&&e},n=r("object"==typeof globalThis&&globalThis)||r("object"==typeof window&&window)||r("object"==typeof self&&self)||r("object"==typeof t&&t)||r("object"==typeof t&&t)||function(){return this}()||Function("return this")(),o={},s=function(e){try{return!!e()}catch(t){return!0}},a=!s((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})),c=!s((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),l=c,d=Function.prototype.call,u=l?d.bind(d):function(){return d.apply(d,arguments)},h={},p={}.propertyIsEnumerable,m=Object.getOwnPropertyDescriptor,_=m&&!p.call({1:2},1);h.f=_?function(e){var t=m(this,e);return!!t&&t.enumerable}:p;var f,g,E=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},T=c,v=Function.prototype,y=v.call,S=T&&v.bind.bind(y,y),I=T?S:function(e){return function(){return y.apply(e,arguments)}},A=I,R=A({}.toString),C=A("".slice),b=function(e){return C(R(e),8,-1)},k=s,D=b,w=Object,N=I("".split),O=k((function(){return!w("z").propertyIsEnumerable(0)}))?function(e){return"String"===D(e)?N(e,""):w(e)}:w,M=function(e){return null==e},P=M,L=TypeError,x=function(e){if(P(e))throw new L("Can't call method on "+e);return e},V=O,U=x,F=function(e){return V(U(e))},B="object"==typeof document&&document.all,H=void 0===B&&void 0!==B?function(e){return"function"==typeof e||e===B}:function(e){return"function"==typeof e},W=H,G=function(e){return"object"==typeof e?null!==e:W(e)},j=n,J=H,K=function(e,t){return arguments.length<2?(i=j[e],J(i)?i:void 0):j[e]&&j[e][t];var i},q=I({}.isPrototypeOf),z=n.navigator,Y=z&&z.userAgent,X=Y?String(Y):"",Q=n,Z=X,$=Q.process,ee=Q.Deno,te=$&&$.versions||ee&&ee.version,ie=te&&te.v8;ie&&(g=(f=ie.split("."))[0]>0&&f[0]<4?1:+(f[0]+f[1])),!g&&Z&&(!(f=Z.match(/Edge\/(\d+)/))||f[1]>=74)&&(f=Z.match(/Chrome\/(\d+)/))&&(g=+f[1]);var re=g,ne=re,oe=s,se=n.String,ae=!!Object.getOwnPropertySymbols&&!oe((function(){var e=Symbol("symbol detection");return!se(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),ce=ae&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,le=K,de=H,ue=q,he=Object,pe=ce?function(e){return"symbol"==typeof e}:function(e){var t=le("Symbol");return de(t)&&ue(t.prototype,he(e))},me=String,_e=function(e){try{return me(e)}catch(t){return"Object"}},fe=H,ge=_e,Ee=TypeError,Te=function(e){if(fe(e))return e;throw new Ee(ge(e)+" is not a function")},ve=Te,ye=M,Se=function(e,t){var i=e[t];return ye(i)?void 0:ve(i)},Ie=u,Ae=H,Re=G,Ce=TypeError,be={exports:{}},ke=n,De=Object.defineProperty,we=function(e,t){try{De(ke,e,{value:t,configurable:!0,writable:!0})}catch(i){ke[e]=t}return t},Ne=n,Oe=we,Me="__core-js_shared__",Pe=be.exports=Ne[Me]||Oe(Me,{});(Pe.versions||(Pe.versions=[])).push({version:"3.40.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.40.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Le=be.exports,xe=Le,Ve=function(e,t){return xe[e]||(xe[e]=t||{})},Ue=x,Fe=Object,Be=function(e){return Fe(Ue(e))},He=Be,We=I({}.hasOwnProperty),Ge=Object.hasOwn||function(e,t){return We(He(e),t)},je=I,Je=0,Ke=Math.random(),qe=je(1..toString),ze=function(e){return"Symbol("+(void 0===e?"":e)+")_"+qe(++Je+Ke,36)},Ye=Ve,Xe=Ge,Qe=ze,Ze=ae,$e=ce,et=n.Symbol,tt=Ye("wks"),it=$e?et.for||et:et&&et.withoutSetter||Qe,rt=function(e){return Xe(tt,e)||(tt[e]=Ze&&Xe(et,e)?et[e]:it("Symbol."+e)),tt[e]},nt=u,ot=G,st=pe,at=Se,ct=function(e,t){var i,r;if("string"===t&&Ae(i=e.toString)&&!Re(r=Ie(i,e)))return r;if(Ae(i=e.valueOf)&&!Re(r=Ie(i,e)))return r;if("string"!==t&&Ae(i=e.toString)&&!Re(r=Ie(i,e)))return r;throw new Ce("Can't convert object to primitive value")},lt=TypeError,dt=rt("toPrimitive"),ut=function(e,t){if(!ot(e)||st(e))return e;var i,r=at(e,dt);if(r){if(void 0===t&&(t="default"),i=nt(r,e,t),!ot(i)||st(i))return i;throw new lt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ct(e,t)},ht=ut,pt=pe,mt=function(e){var t=ht(e,"string");return pt(t)?t:t+""},_t=G,ft=n.document,gt=_t(ft)&&_t(ft.createElement),Et=function(e){return gt?ft.createElement(e):{}},Tt=Et,vt=!a&&!s((function(){return 7!==Object.defineProperty(Tt("div"),"a",{get:function(){return 7}}).a})),yt=a,St=u,It=h,At=E,Rt=F,Ct=mt,bt=Ge,kt=vt,Dt=Object.getOwnPropertyDescriptor;o.f=yt?Dt:function(e,t){if(e=Rt(e),t=Ct(t),kt)try{return Dt(e,t)}catch(i){}if(bt(e,t))return At(!St(It.f,e,t),e[t])};var wt={},Nt=a&&s((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Ot=G,Mt=String,Pt=TypeError,Lt=function(e){if(Ot(e))return e;throw new Pt(Mt(e)+" is not an object")},xt=a,Vt=vt,Ut=Nt,Ft=Lt,Bt=mt,Ht=TypeError,Wt=Object.defineProperty,Gt=Object.getOwnPropertyDescriptor,jt="enumerable",Jt="configurable",Kt="writable";wt.f=xt?Ut?function(e,t,i){if(Ft(e),t=Bt(t),Ft(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Kt in i&&!i[Kt]){var r=Gt(e,t);r&&r[Kt]&&(e[t]=i.value,i={configurable:Jt in i?i[Jt]:r[Jt],enumerable:jt in i?i[jt]:r[jt],writable:!1})}return Wt(e,t,i)}:Wt:function(e,t,i){if(Ft(e),t=Bt(t),Ft(i),Vt)try{return Wt(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Ht("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var qt=wt,zt=E,Yt=a?function(e,t,i){return qt.f(e,t,zt(1,i))}:function(e,t,i){return e[t]=i,e},Xt={exports:{}},Qt=a,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=H,ni=Le,oi=I(Function.toString);ri(ni.inspectSource)||(ni.inspectSource=function(e){return oi(e)});var si,ai,ci,li=ni.inspectSource,di=H,ui=n.WeakMap,hi=di(ui)&&/native code/.test(String(ui)),pi=ze,mi=Ve("keys"),_i=function(e){return mi[e]||(mi[e]=pi(e))},fi={},gi=hi,Ei=n,Ti=G,vi=Yt,yi=Ge,Si=Le,Ii=_i,Ai=fi,Ri="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,si=function(e,t){if(ki.has(e))throw new Ci(Ri);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");Ai[Di]=!0,si=function(e,t){if(yi(e,Di))throw new Ci(Ri);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 wi={set:si,get:ai,has:ci,enforce:function(e){return ci(e)?ai(e):si(e,{})},getterFor:function(e){return function(t){var i;if(!Ti(t)||(i=ai(t)).type!==e)throw new Ci("Incompatible receiver, "+e+" required");return i}}},Ni=I,Oi=s,Mi=H,Pi=Ge,Li=a,xi=ii.CONFIGURABLE,Vi=li,Ui=wi.enforce,Fi=wi.get,Bi=String,Hi=Object.defineProperty,Wi=Ni("".slice),Gi=Ni("".replace),ji=Ni([].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("===Wi(Bi(t),0,7)&&(t="["+Gi(Bi(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Pi(e,"name")||xi&&e.name!==t)&&(Li?Hi(e,"name",{value:t,configurable:!0}):e.name=t),Ji&&i&&Pi(i,"arity")&&e.length!==i.arity&&Hi(e,"length",{value:i.arity});try{i&&Pi(i,"constructor")&&i.constructor?Li&&Hi(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var r=Ui(e);return Pi(r,"source")||(r.source=ji(Ki,"string"==typeof t?t:"")),e};Function.prototype.toString=qi((function(){return Mi(this)&&Fi(this).source||Vi(this)}),"toString");var zi=Xt.exports,Yi=H,Xi=wt,Qi=zi,Zi=we,$i=function(e,t,i,r){r||(r={});var n=r.enumerable,o=void 0!==r.name?r.name:t;if(Yi(i)&&Qi(i,o,r),r.global)n?e[t]=i:Zi(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch(s){}n?e[t]=i:Xi.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},er={},tr=Math.ceil,ir=Math.floor,rr=Math.trunc||function(e){var t=+e;return(t>0?ir:tr)(t)},nr=rr,or=function(e){var t=+e;return t!=t||0===t?0:nr(t)},sr=or,ar=Math.max,cr=Math.min,lr=function(e,t){var i=sr(e);return i<0?ar(i+t,0):cr(i,t)},dr=or,ur=Math.min,hr=function(e){var t=dr(e);return t>0?ur(t,9007199254740991):0},pr=hr,mr=function(e){return pr(e.length)},_r=F,fr=lr,gr=mr,Er=function(e){return function(t,i,r){var n=_r(t),o=gr(n);if(0===o)return!e&&-1;var s,a=fr(r,o);if(e&&i!=i){for(;o>a;)if((s=n[a++])!=s)return!0}else for(;o>a;a++)if((e||a in n)&&n[a]===i)return e||a||0;return!e&&-1}},Tr={includes:Er(!0),indexOf:Er(!1)},vr=Ge,yr=F,Sr=Tr.indexOf,Ir=fi,Ar=I([].push),Rr=function(e,t){var i,r=yr(e),n=0,o=[];for(i in r)!vr(Ir,i)&&vr(r,i)&&Ar(o,i);for(;t.length>n;)vr(r,i=t[n++])&&(~Sr(o,i)||Ar(o,i));return o},Cr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],br=Rr,kr=Cr.concat("length","prototype");er.f=Object.getOwnPropertyNames||function(e){return br(e,kr)};var Dr={};Dr.f=Object.getOwnPropertySymbols;var wr=K,Nr=er,Or=Dr,Mr=Lt,Pr=I([].concat),Lr=wr("Reflect","ownKeys")||function(e){var t=Nr.f(Mr(e)),i=Or.f;return i?Pr(t,i(e)):t},xr=Ge,Vr=Lr,Ur=o,Fr=wt,Br=function(e,t,i){for(var r=Vr(t),n=Fr.f,o=Ur.f,s=0;s<r.length;s++){var a=r[s];xr(e,a)||i&&xr(i,a)||n(e,a,o(t,a))}},Hr=s,Wr=H,Gr=/#|\.prototype\./,jr=function(e,t){var i=Kr[Jr(e)];return i===zr||i!==qr&&(Wr(t)?Hr(t):!!t)},Jr=jr.normalize=function(e){return String(e).replace(Gr,".").toLowerCase()},Kr=jr.data={},qr=jr.NATIVE="N",zr=jr.POLYFILL="P",Yr=jr,Xr=n,Qr=o.f,Zr=Yt,$r=$i,en=we,tn=Br,rn=Yr,nn=function(e,t){var i,r,n,o,s,a=e.target,c=e.global,l=e.stat;if(i=c?Xr:l?Xr[a]||en(a,{}):Xr[a]&&Xr[a].prototype)for(r in t){if(o=t[r],n=e.dontCallGetSet?(s=Qr(i,r))&&s.value:i[r],!rn(c?r:a+(l?".":"#")+r,e.forced)&&void 0!==n){if(typeof o==typeof n)continue;tn(o,n)}(e.sham||n&&n.sham)&&Zr(o,"sham",!0),$r(i,r,o,e)}},on={};on[rt("toStringTag")]="z";var sn="[object z]"===String(on),an=H,cn=b,ln=rt("toStringTag"),dn=Object,un="Arguments"===cn(function(){return arguments}()),hn=sn?cn:function(e){var t,i,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(i){}}(t=dn(e),ln))?i:un?cn(t):"Object"===(r=cn(t))&&an(t.callee)?"Arguments":r},pn=hn,mn=String,_n=function(e){if("Symbol"===pn(e))throw new TypeError("Cannot convert a Symbol value to a string");return mn(e)},fn=zi,gn=wt,En=function(e,t,i){return i.get&&fn(i.get,t,{getter:!0}),i.set&&fn(i.set,t,{setter:!0}),gn.f(e,t,i)},Tn=nn,vn=a,yn=I,Sn=Ge,In=H,An=q,Rn=_n,Cn=En,bn=Br,kn=n.Symbol,Dn=kn&&kn.prototype;if(vn&&In(kn)&&(!("description"in Dn)||void 0!==kn().description)){var wn={},Nn=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:Rn(arguments[0]),t=An(Dn,this)?new kn(e):void 0===e?kn():kn(e);return""===e&&(wn[t]=!0),t};bn(Nn,kn),Nn.prototype=Dn,Dn.constructor=Nn;var On="Symbol(description detection)"===String(kn("description detection")),Mn=yn(Dn.valueOf),Pn=yn(Dn.toString),Ln=/^Symbol\((.*)\)[^)]+$/,xn=yn("".replace),Vn=yn("".slice);Cn(Dn,"description",{configurable:!0,get:function(){var e=Mn(this);if(Sn(wn,e))return"";var t=Pn(e),i=On?Vn(t,7,-1):xn(t,Ln,"$1");return""===i?void 0:i}}),Tn({global:!0,constructor:!0,forced:!0},{Symbol:Nn})}var Un={},Fn=Rr,Bn=Cr,Hn=Object.keys||function(e){return Fn(e,Bn)},Wn=a,Gn=Nt,jn=wt,Jn=Lt,Kn=F,qn=Hn;Un.f=Wn&&!Gn?Object.defineProperties:function(e,t){Jn(e);for(var i,r=Kn(t),n=qn(t),o=n.length,s=0;o>s;)jn.f(e,i=n[s++],r[i]);return e};var zn,Yn=K("document","documentElement"),Xn=Lt,Qn=Un,Zn=Cr,$n=fi,eo=Yn,to=Et,io="prototype",ro="script",no=_i("IE_PROTO"),oo=function(){},so=function(e){return"<"+ro+">"+e+"</"+ro+">"},ao=function(e){e.write(so("")),e.close();var t=e.parentWindow.Object;return e=null,t},co=function(){try{zn=new ActiveXObject("htmlfile")}catch(n){}var e,t,i;co="undefined"!=typeof document?document.domain&&zn?ao(zn):(t=to("iframe"),i="java"+ro+":",t.style.display="none",eo.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(so("document.F=Object")),e.close(),e.F):ao(zn);for(var r=Zn.length;r--;)delete co[io][Zn[r]];return co()};$n[no]=!0;var lo=Object.create||function(e,t){var i;return null!==e?(oo[io]=Xn(e),i=new oo,oo[io]=null,i[no]=e):i=co(),void 0===t?i:Qn.f(i,t)},uo=rt,ho=lo,po=wt.f,mo=uo("unscopables"),_o=Array.prototype;void 0===_o[mo]&&po(_o,mo,{configurable:!0,value:ho(null)});var fo=function(e){_o[mo][e]=!0},go=Tr.includes,Eo=fo;nn({target:"Array",proto:!0,forced:s((function(){return!Array(1).includes()}))},{includes:function(e){return go(this,e,arguments.length>1?arguments[1]:void 0)}}),Eo("includes");var To,vo,yo,So={},Io=!s((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Ao=Ge,Ro=H,Co=Be,bo=Io,ko=_i("IE_PROTO"),Do=Object,wo=Do.prototype,No=bo?Do.getPrototypeOf:function(e){var t=Co(e);if(Ao(t,ko))return t[ko];var i=t.constructor;return Ro(i)&&t instanceof i?i.prototype:t instanceof Do?wo:null},Oo=s,Mo=H,Po=G,Lo=No,xo=$i,Vo=rt("iterator"),Uo=!1;[].keys&&("next"in(yo=[].keys())?(vo=Lo(Lo(yo)))!==Object.prototype&&(To=vo):Uo=!0);var Fo=!Po(To)||Oo((function(){var e={};return To[Vo].call(e)!==e}));Fo&&(To={}),Mo(To[Vo])||xo(To,Vo,(function(){return this}));var Bo={IteratorPrototype:To,BUGGY_SAFARI_ITERATORS:Uo},Ho=wt.f,Wo=Ge,Go=rt("toStringTag"),jo=function(e,t,i){e&&!i&&(e=e.prototype),e&&!Wo(e,Go)&&Ho(e,Go,{configurable:!0,value:t})},Jo=Bo.IteratorPrototype,Ko=lo,qo=E,zo=jo,Yo=So,Xo=function(){return this},Qo=function(e,t,i,r){var n=t+" Iterator";return e.prototype=Ko(Jo,{next:qo(+!r,i)}),zo(e,n,!1),Yo[n]=Xo,e},Zo=I,$o=Te,es=G,ts=function(e){return es(e)||null===e},is=String,rs=TypeError,ns=function(e,t,i){try{return Zo($o(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},os=G,ss=x,as=function(e){if(ts(e))return e;throw new rs("Can't set "+is(e)+" as a prototype")},cs=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=ns(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return ss(i),as(r),os(i)?(t?e(i,r):i.__proto__=r,i):i}}():void 0),ls=nn,ds=u,us=H,hs=Qo,ps=No,ms=cs,_s=jo,fs=Yt,gs=$i,Es=So,Ts=ii.PROPER,vs=ii.CONFIGURABLE,ys=Bo.IteratorPrototype,Ss=Bo.BUGGY_SAFARI_ITERATORS,Is=rt("iterator"),As="keys",Rs="values",Cs="entries",bs=function(){return this},ks=function(e,t,i,r,n,o,s){hs(i,t,r);var a,c,l,d=function(e){if(e===n&&_)return _;if(!Ss&&e&&e in p)return p[e];switch(e){case As:case Rs:case Cs:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[Is]||p["@@iterator"]||n&&p[n],_=!Ss&&m||d(n),f="Array"===t&&p.entries||m;if(f&&(a=ps(f.call(new e)))!==Object.prototype&&a.next&&(ps(a)!==ys&&(ms?ms(a,ys):us(a[Is])||gs(a,Is,bs)),_s(a,u,!0)),Ts&&n===Rs&&m&&m.name!==Rs&&(vs?fs(p,"name",Rs):(h=!0,_=function(){return ds(m,this)})),n)if(c={values:d(Rs),keys:o?_:d(As),entries:d(Cs)},s)for(l in c)(Ss||h||!(l in p))&&gs(p,l,c[l]);else ls({target:t,proto:!0,forced:Ss||h},c);return p[Is]!==_&&gs(p,Is,_,{name:n}),Es[t]=_,c},Ds=function(e,t){return{value:e,done:t}},ws=F,Ns=fo,Os=So,Ms=wi,Ps=wt.f,Ls=ks,xs=Ds,Vs=a,Us="Array Iterator",Fs=Ms.set,Bs=Ms.getterFor(Us),Hs=Ls(Array,"Array",(function(e,t){Fs(this,{type:Us,target:ws(e),index:0,kind:t})}),(function(){var e=Bs(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,xs(void 0,!0);switch(e.kind){case"keys":return xs(i,!1);case"values":return xs(t[i],!1)}return xs([i,t[i]],!1)}),"values"),Ws=Os.Arguments=Os.Array;if(Ns("keys"),Ns("values"),Ns("entries"),Vs&&"values"!==Ws.name)try{Ps(Ws,"name",{value:"values"})}catch(bJ){}var Gs=Te,js=Be,Js=O,Ks=mr,qs=TypeError,zs="Reduce of empty array with no initial value",Ys=function(e){return function(t,i,r,n){var o=js(t),s=Js(o),a=Ks(o);if(Gs(i),0===a&&r<2)throw new qs(zs);var c=e?a-1:0,l=e?-1:1;if(r<2)for(;;){if(c in s){n=s[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw new qs(zs)}for(;e?c>=0:a>c;c+=l)c in s&&(n=i(n,s[c],c,o));return n}},Xs={left:Ys(!1),right:Ys(!0)},Qs=s,Zs=function(e,t){var i=[][e];return!!i&&Qs((function(){i.call(null,t||function(){return 1},1)}))},$s=n,ea=X,ta=b,ia=function(e){return ea.slice(0,e.length)===e},ra=ia("Bun/")?"BUN":ia("Cloudflare-Workers")?"CLOUDFLARE":ia("Deno/")?"DENO":ia("Node.js/")?"NODE":$s.Bun&&"string"==typeof Bun.version?"BUN":$s.Deno&&"object"==typeof Deno.version?"DENO":"process"===ta($s.process)?"NODE":$s.window&&$s.document?"BROWSER":"REST",na="NODE"===ra,oa=Xs.left;nn({target:"Array",proto:!0,forced:!na&&re>79&&re<83||!Zs("reduce")},{reduce:function(e){var t=arguments.length;return oa(this,e,t,t>1?arguments[1]:void 0)}});var sa=Xs.right;nn({target:"Array",proto:!0,forced:!na&&re>79&&re<83||!Zs("reduceRight")},{reduceRight:function(e){return sa(this,e,arguments.length,arguments.length>1?arguments[1]:void 0)}});var aa=b,ca=Array.isArray||function(e){return"Array"===aa(e)},la=nn,da=ca,ua=I([].reverse),ha=[1,2];la({target:"Array",proto:!0,forced:String(ha)===String(ha.reverse())},{reverse:function(){return da(this)&&(this.length=this.length),ua(this)}});var pa=_e,ma=TypeError,_a=I([].slice),fa=_a,ga=Math.floor,Ea=function(e,t){var i=e.length;if(i<8)for(var r,n,o=1;o<i;){for(n=o,r=e[o];n&&t(e[n-1],r)>0;)e[n]=e[--n];n!==o++&&(e[n]=r)}else for(var s=ga(i/2),a=Ea(fa(e,0,s),t),c=Ea(fa(e,s),t),l=a.length,d=c.length,u=0,h=0;u<l||h<d;)e[u+h]=u<l&&h<d?t(a[u],c[h])<=0?a[u++]:c[h++]:u<l?a[u++]:c[h++];return e},Ta=Ea,va=X.match(/firefox\/(\d+)/i),ya=!!va&&+va[1],Sa=/MSIE|Trident/.test(X),Ia=X.match(/AppleWebKit\/(\d+)\./),Aa=!!Ia&&+Ia[1],Ra=nn,Ca=I,ba=Te,ka=Be,Da=mr,wa=function(e,t){if(!delete e[t])throw new ma("Cannot delete property "+pa(t)+" of "+pa(e))},Na=_n,Oa=s,Ma=Ta,Pa=Zs,La=ya,xa=Sa,Va=re,Ua=Aa,Fa=[],Ba=Ca(Fa.sort),Ha=Ca(Fa.push),Wa=Oa((function(){Fa.sort(void 0)})),Ga=Oa((function(){Fa.sort(null)})),ja=Pa("sort"),Ja=!Oa((function(){if(Va)return Va<70;if(!(La&&La>3)){if(xa)return!0;if(Ua)return Ua<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++)Fa.push({k:t+r,v:i})}for(Fa.sort((function(e,t){return t.v-e.v})),r=0;r<Fa.length;r++)t=Fa[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));Ra({target:"Array",proto:!0,forced:Wa||!Ga||!ja||!Ja},{sort:function(e){void 0!==e&&ba(e);var t=ka(this);if(Ja)return void 0===e?Ba(t):Ba(t,e);var i,r,n=[],o=Da(t);for(r=0;r<o;r++)r in t&&Ha(n,t[r]);for(Ma(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=Da(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)wa(t,r++);return t}});var Ka="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,qa=$i,za=function(e,t,i){for(var r in t)qa(e,r,t[r],i);return e},Ya=q,Xa=TypeError,Qa=function(e,t){if(Ya(t,e))return e;throw new Xa("Incorrect invocation")},Za=or,$a=hr,ec=RangeError,tc=function(e){if(void 0===e)return 0;var t=Za(e),i=$a(t);if(t!==i)throw new ec("Wrong length or index");return i},ic=Math.sign||function(e){var t=+e;return 0===t||t!=t?t:t<0?-1:1},rc=4503599627370496,nc=ic,oc=function(e){return e+rc-rc},sc=Math.abs,ac=function(e,t,i,r){var n=+e,o=sc(n),s=nc(n);if(o<r)return s*oc(o/r/t)*r*t;var a=(1+t/2220446049250313e-31)*o,c=a-(a-o);return c>i||c!=c?Infinity*s:s*c},cc=Math.fround||function(e){return ac(e,1.1920928955078125e-7,34028234663852886e22,11754943508222875e-54)},lc=Array,dc=Math.abs,uc=Math.pow,hc=Math.floor,pc=Math.log,mc=Math.LN2,_c={pack:function(e,t,i){var r,n,o,s=lc(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?uc(2,-24)-uc(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=dc(e))!=e||Infinity===e?(n=e!=e?1:0,r=c):(r=hc(pc(e)/mc),e*(o=uc(2,-r))<1&&(r--,o*=2),(e+=r+l>=1?d/o:d*uc(2,1-l))*o>=2&&(r++,o/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*o-1)*uc(2,t),r+=l):(n=e*uc(2,l-1)*uc(2,t),r=0));t>=8;)s[h++]=255&n,n/=256,t-=8;for(r=r<<t|n,a+=t;a>0;)s[h++]=255&r,r/=256,a-=8;return s[h-1]|=128*u,s},unpack:function(e,t){var i,r=e.length,n=8*r-t-1,o=(1<<n)-1,s=o>>1,a=n-7,c=r-1,l=e[c--],d=127&l;for(l>>=7;a>0;)d=256*d+e[c--],a-=8;for(i=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)i=256*i+e[c--],a-=8;if(0===d)d=1-s;else{if(d===o)return i?NaN:l?-Infinity:Infinity;i+=uc(2,t),d-=s}return(l?-1:1)*i*uc(2,d-t)}},fc=Be,gc=lr,Ec=mr,Tc=function(e){for(var t=fc(this),i=Ec(t),r=arguments.length,n=gc(r>1?arguments[1]:void 0,i),o=r>2?arguments[2]:void 0,s=void 0===o?i:gc(o,i);s>n;)t[n++]=e;return t},vc=H,yc=G,Sc=cs,Ic=function(e,t,i){var r,n;return Sc&&vc(r=t.constructor)&&r!==i&&yc(n=r.prototype)&&n!==i.prototype&&Sc(e,n),e},Ac=n,Rc=I,Cc=a,bc=Ka,kc=Yt,Dc=En,wc=za,Nc=s,Oc=Qa,Mc=or,Pc=hr,Lc=tc,xc=cc,Vc=_c,Uc=No,Fc=cs,Bc=Tc,Hc=_a,Wc=Ic,Gc=Br,jc=jo,Jc=wi,Kc=ii.PROPER,qc=ii.CONFIGURABLE,zc="ArrayBuffer",Yc="DataView",Xc="prototype",Qc="Wrong index",Zc=Jc.getterFor(zc),$c=Jc.getterFor(Yc),el=Jc.set,tl=Ac[zc],il=tl,rl=il&&il[Xc],nl=Ac[Yc],ol=nl&&nl[Xc],sl=Object.prototype,al=Ac.Array,cl=Ac.RangeError,ll=Rc(Bc),dl=Rc([].reverse),ul=Vc.pack,hl=Vc.unpack,pl=function(e){return[255&e]},ml=function(e){return[255&e,e>>8&255]},_l=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},fl=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},gl=function(e){return ul(xc(e),23,4)},El=function(e){return ul(e,52,8)},Tl=function(e,t,i){Dc(e[Xc],t,{configurable:!0,get:function(){return i(this)[t]}})},vl=function(e,t,i,r){var n=$c(e),o=Lc(i),s=!!r;if(o+t>n.byteLength)throw new cl(Qc);var a=n.bytes,c=o+n.byteOffset,l=Hc(a,c,c+t);return s?l:dl(l)},yl=function(e,t,i,r,n,o){var s=$c(e),a=Lc(i),c=r(+n),l=!!o;if(a+t>s.byteLength)throw new cl(Qc);for(var d=s.bytes,u=a+s.byteOffset,h=0;h<t;h++)d[u+h]=c[l?h:t-h-1]};if(bc){var Sl=Kc&&tl.name!==zc;Nc((function(){tl(1)}))&&Nc((function(){new tl(-1)}))&&!Nc((function(){return new tl,new tl(1.5),new tl(NaN),1!==tl.length||Sl&&!qc}))?Sl&&qc&&kc(tl,"name",zc):((il=function(e){return Oc(this,rl),Wc(new tl(Lc(e)),this,il)})[Xc]=rl,rl.constructor=il,Gc(il,tl)),Fc&&Uc(ol)!==sl&&Fc(ol,sl);var Il=new nl(new il(2)),Al=Rc(ol.setInt8);Il.setInt8(0,2147483648),Il.setInt8(1,2147483649),!Il.getInt8(0)&&Il.getInt8(1)||wc(ol,{setInt8:function(e,t){Al(this,e,t<<24>>24)},setUint8:function(e,t){Al(this,e,t<<24>>24)}},{unsafe:!0})}else rl=(il=function(e){Oc(this,rl);var t=Lc(e);el(this,{type:zc,bytes:ll(al(t),0),byteLength:t}),Cc||(this.byteLength=t,this.detached=!1)})[Xc],ol=(nl=function(e,t,i){Oc(this,ol),Oc(e,rl);var r=Zc(e),n=r.byteLength,o=Mc(t);if(o<0||o>n)throw new cl("Wrong offset");if(o+(i=void 0===i?n-o:Pc(i))>n)throw new cl("Wrong length");el(this,{type:Yc,buffer:e,byteLength:i,byteOffset:o,bytes:r.bytes}),Cc||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[Xc],Cc&&(Tl(il,"byteLength",Zc),Tl(nl,"buffer",$c),Tl(nl,"byteLength",$c),Tl(nl,"byteOffset",$c)),wc(ol,{getInt8:function(e){return vl(this,1,e)[0]<<24>>24},getUint8:function(e){return vl(this,1,e)[0]},getInt16:function(e){var t=vl(this,2,e,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=vl(this,2,e,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return fl(vl(this,4,e,arguments.length>1&&arguments[1]))},getUint32:function(e){return fl(vl(this,4,e,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(e){return hl(vl(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return hl(vl(this,8,e,arguments.length>1&&arguments[1]),52)},setInt8:function(e,t){yl(this,1,e,pl,t)},setUint8:function(e,t){yl(this,1,e,pl,t)},setInt16:function(e,t){yl(this,2,e,ml,t,arguments.length>2&&arguments[2])},setUint16:function(e,t){yl(this,2,e,ml,t,arguments.length>2&&arguments[2])},setInt32:function(e,t){yl(this,4,e,_l,t,arguments.length>2&&arguments[2])},setUint32:function(e,t){yl(this,4,e,_l,t,arguments.length>2&&arguments[2])},setFloat32:function(e,t){yl(this,4,e,gl,t,arguments.length>2&&arguments[2])},setFloat64:function(e,t){yl(this,8,e,El,t,arguments.length>2&&arguments[2])}});jc(il,zc),jc(nl,Yc);var Rl={ArrayBuffer:il,DataView:nl},Cl=K,bl=En,kl=a,Dl=rt("species"),wl=function(e){var t=Cl(e);kl&&t&&!t[Dl]&&bl(t,Dl,{configurable:!0,get:function(){return this}})},Nl=wl,Ol="ArrayBuffer",Ml=Rl[Ol];nn({global:!0,constructor:!0,forced:n[Ol]!==Ml},{ArrayBuffer:Ml}),Nl(Ol);var Pl=b,Ll=I,xl=function(e){if("Function"===Pl(e))return Ll(e)},Vl=nn,Ul=xl,Fl=s,Bl=Lt,Hl=lr,Wl=hr,Gl=Rl.ArrayBuffer,jl=Rl.DataView,Jl=jl.prototype,Kl=Ul(Gl.prototype.slice),ql=Ul(Jl.getUint8),zl=Ul(Jl.setUint8);Vl({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:Fl((function(){return!new Gl(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(Kl&&void 0===t)return Kl(Bl(this),e);for(var i=Bl(this).byteLength,r=Hl(e,i),n=Hl(void 0===t?i:t,i),o=new Gl(Wl(n-r)),s=new jl(this),a=new jl(o),c=0;r<n;)zl(a,c++,ql(s,r++));return o}});var Yl=I,Xl=s,Ql=H,Zl=hn,$l=li,ed=function(){},td=K("Reflect","construct"),id=/^\s*(?:class|function)\b/,rd=Yl(id.exec),nd=!id.test(ed),od=function(e){if(!Ql(e))return!1;try{return td(ed,[],e),!0}catch(bJ){return!1}},sd=function(e){if(!Ql(e))return!1;switch(Zl(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return nd||!!rd(id,$l(e))}catch(bJ){return!0}};sd.sham=!0;var ad,cd,ld,dd,ud=!td||Xl((function(){var e;return od(od.call)||!od(Object)||!od((function(){e=!0}))||e}))?sd:od,hd=ud,pd=_e,md=TypeError,_d=function(e){if(hd(e))return e;throw new md(pd(e)+" is not a constructor")},fd=Lt,gd=_d,Ed=M,Td=rt("species"),vd=function(e,t){var i,r=fd(e).constructor;return void 0===r||Ed(i=fd(r)[Td])?t:gd(i)},yd=c,Sd=Function.prototype,Id=Sd.apply,Ad=Sd.call,Rd="object"==typeof Reflect&&Reflect.apply||(yd?Ad.bind(Id):function(){return Ad.apply(Id,arguments)}),Cd=Te,bd=c,kd=xl(xl.bind),Dd=function(e,t){return Cd(e),void 0===t?e:bd?kd(e,t):function(){return e.apply(t,arguments)}},wd=TypeError,Nd=function(e,t){if(e<t)throw new wd("Not enough arguments");return e},Od=/(?:ipad|iphone|ipod).*applewebkit/i.test(X),Md=n,Pd=Rd,Ld=Dd,xd=H,Vd=Ge,Ud=s,Fd=Yn,Bd=_a,Hd=Et,Wd=Nd,Gd=Od,jd=na,Jd=Md.setImmediate,Kd=Md.clearImmediate,qd=Md.process,zd=Md.Dispatch,Yd=Md.Function,Xd=Md.MessageChannel,Qd=Md.String,Zd=0,$d={},eu="onreadystatechange";Ud((function(){ad=Md.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){Md.postMessage(Qd(e),ad.protocol+"//"+ad.host)};Jd&&Kd||(Jd=function(e){Wd(arguments.length,1);var t=xd(e)?e:Yd(e),i=Bd(arguments,1);return $d[++Zd]=function(){Pd(t,void 0,i)},cd(Zd),Zd},Kd=function(e){delete $d[e]},jd?cd=function(e){qd.nextTick(iu(e))}:zd&&zd.now?cd=function(e){zd.now(iu(e))}:Xd&&!Gd?(dd=(ld=new Xd).port2,ld.port1.onmessage=ru,cd=Ld(dd.postMessage,dd)):Md.addEventListener&&xd(Md.postMessage)&&!Md.importScripts&&ad&&"file:"!==ad.protocol&&!Ud(nu)?(cd=nu,Md.addEventListener("message",ru,!1)):cd=eu in Hd("script")?function(e){Fd.appendChild(Hd("script"))[eu]=function(){Fd.removeChild(this),tu(e)}}:function(e){setTimeout(iu(e),0)});var ou={set:Jd,clear:Kd},su=n,au=a,cu=Object.getOwnPropertyDescriptor,lu=function(e){if(!au)return su[e];var t=cu(su,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(X)&&"undefined"!=typeof Pebble,Eu=/web0s(?!.*chrome)/i.test(X),Tu=n,vu=lu,yu=Dd,Su=ou.set,Iu=fu,Au=Od,Ru=gu,Cu=Eu,bu=na,ku=Tu.MutationObserver||Tu.WebKitMutationObserver,Du=Tu.document,wu=Tu.process,Nu=Tu.Promise,Ou=vu("queueMicrotask");if(!Ou){var Mu=new Iu,Pu=function(){var e,t;for(bu&&(e=wu.domain)&&e.exit();t=Mu.get();)try{t()}catch(bJ){throw Mu.head&&uu(),bJ}e&&e.enter()};Au||bu||Cu||!ku||!Du?!Ru&&Nu&&Nu.resolve?((mu=Nu.resolve(void 0)).constructor=Nu,_u=yu(mu.then,mu),uu=function(){_u(Pu)}):bu?uu=function(){wu.nextTick(Pu)}:(Su=yu(Su,Tu),uu=function(){Su(Pu)}):(hu=!0,pu=Du.createTextNode(""),new ku(Pu).observe(pu,{characterData:!0}),uu=function(){pu.data=hu=!hu}),Ou=function(e){Mu.head||uu(),Mu.add(e)}}var Lu=Ou,xu=function(e){try{return{error:!1,value:e()}}catch(bJ){return{error:!0,value:bJ}}},Vu=n.Promise,Uu=n,Fu=Vu,Bu=H,Hu=Yr,Wu=li,Gu=rt,ju=ra,Ju=re;Fu&&Fu.prototype;var Ku=Gu("species"),qu=!1,zu=Bu(Uu.PromiseRejectionEvent),Yu=Hu("Promise",(function(){var e=Wu(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=Te,$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=nn,oh=na,sh=n,ah=u,ch=$i,lh=cs,dh=jo,uh=wl,hh=Te,ph=H,mh=G,_h=Qa,fh=vd,gh=ou.set,Eh=Lu,Th=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(bJ){}},vh=xu,yh=fu,Sh=wi,Ih=Vu,Ah=Qu,Rh="Promise",Ch=Xu.CONSTRUCTOR,bh=Xu.REJECTION_EVENT,kh=Xu.SUBCLASSING,Dh=Sh.getterFor(Rh),wh=Sh.set,Nh=Ih&&Ih.prototype,Oh=Ih,Mh=Nh,Ph=sh.TypeError,Lh=sh.document,xh=sh.process,Vh=Ah.f,Uh=Vh,Fh=!!(Lh&&Lh.createEvent&&sh.dispatchEvent),Bh="unhandledrejection",Hh=function(e){var t;return!(!mh(e)||!ph(t=e.then))&&t},Wh=function(e,t){var i,r,n,o=t.value,s=1===t.state,a=s?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{a?(s||(2===t.rejection&&qh(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),n=!0)),i===e.promise?l(new Ph("Promise-chain cycle")):(r=Hh(i))?ah(r,i,c,l):c(i)):l(o)}catch(bJ){d&&!n&&d.exit(),l(bJ)}},Gh=function(e,t){e.notified||(e.notified=!0,Eh((function(){for(var i,r=e.reactions;i=r.get();)Wh(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),sh.dispatchEvent(r)):r={promise:t,reason:i},!bh&&(n=sh["on"+e])?n(r):e===Bh&&Th("Unhandled promise rejection",i)},Jh=function(e){ah(gh,sh,(function(){var t,i=e.facade,r=e.value;if(Kh(e)&&(t=vh((function(){oh?xh.emit("unhandledRejection",r,i):jh(Bh,i,r)})),e.rejection=oh||Kh(e)?2:1,t.error))throw t.value}))},Kh=function(e){return 1!==e.rejection&&!e.parent},qh=function(e){ah(gh,sh,(function(){var t=e.facade;oh?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,Gh(e,!0))},Xh=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new Ph("Promise can't be resolved itself");var r=Hh(t);r?Eh((function(){var i={done:!1};try{ah(r,t,zh(Xh,i,e),zh(Yh,i,e))}catch(bJ){Yh(i,bJ,e)}})):(e.value=t,e.state=1,Gh(e,!1))}catch(bJ){Yh({done:!1},bJ,e)}}};if(Ch&&(Mh=(Oh=function(e){_h(this,Mh),hh(e),ah(th,this);var t=Dh(this);try{e(zh(Xh,t),zh(Yh,t))}catch(bJ){Yh(t,bJ)}}).prototype,(th=function(e){wh(this,{type:Rh,done:!1,notified:!1,parent:!1,reactions:new yh,rejection:!1,state:0,value:null})}).prototype=ch(Mh,"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=oh?xh.domain:void 0,0===i.state?i.reactions.add(r):Eh((function(){Wh(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)},Ah.f=Vh=function(e){return e===Oh||undefined===e?new ih(e):Uh(e)},ph(Ih)&&Nh!==Object.prototype)){rh=Nh.then,kh||ch(Nh,"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 Nh.constructor}catch(bJ){}lh&&lh(Nh,Mh)}nh({global:!0,constructor:!0,wrap:!0,forced:Ch},{Promise:Oh}),dh(Oh,Rh,!1),uh(Rh);var Qh=So,Zh=rt("iterator"),$h=Array.prototype,ep=function(e){return void 0!==e&&(Qh.Array===e||$h[Zh]===e)},tp=hn,ip=Se,rp=M,np=So,op=rt("iterator"),sp=function(e){if(!rp(e))return ip(e,op)||ip(e,"@@iterator")||np[tp(e)]},ap=u,cp=Te,lp=Lt,dp=_e,up=sp,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=u,_p=Lt,fp=Se,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(bJ){n=!0,r=bJ}if("throw"===t)throw i;if(n)throw r;return _p(r),i},Ep=Dd,Tp=u,vp=Lt,yp=_e,Sp=ep,Ip=mr,Ap=q,Rp=pp,Cp=sp,bp=gp,kp=TypeError,Dp=function(e,t){this.stopped=e,this.result=t},wp=Dp.prototype,Np=function(e,t,i){var r,n,o,s,a,c,l,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),_=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(o=0,s=Ip(e);s>o;o++)if((a=g(e[o]))&&Ap(wp,a))return a;return new Dp(!1)}r=Rp(e,n)}for(c=h?e.next:r.next;!(l=Tp(c,r)).done;){try{a=g(l.value)}catch(bJ){bp(r,"throw",bJ)}if("object"==typeof a&&a&&Ap(wp,a))return a}return new Dp(!1)},Op=rt("iterator"),Mp=!1;try{var Pp=0,Lp={next:function(){return{done:!!Pp++}},return:function(){Mp=!0}};Lp[Op]=function(){return this},Array.from(Lp,(function(){throw 2}))}catch(bJ){}var xp=function(e,t){try{if(!t&&!Mp)return!1}catch(bJ){return!1}var i=!1;try{var r={};r[Op]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(bJ){}return i},Vp=Vu,Up=Xu.CONSTRUCTOR||!xp((function(e){Vp.all(e).then(void 0,(function(){}))})),Fp=u,Bp=Te,Hp=Qu,Wp=xu,Gp=Np;nn({target:"Promise",stat:!0,forced:Up},{all:function(e){var t=this,i=Hp.f(t),r=i.resolve,n=i.reject,o=Wp((function(){var i=Bp(t.resolve),o=[],s=0,a=1;Gp(e,(function(e){var c=s++,l=!1;a++,Fp(i,t,e).then((function(e){l||(l=!0,o[c]=e,--a||r(o))}),n)})),--a||r(o)}));return o.error&&n(o.value),i.promise}});var jp=nn,Jp=Xu.CONSTRUCTOR,Kp=Vu,qp=K,zp=H,Yp=$i,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=u,$p=Te,em=Qu,tm=xu,im=Np;nn({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;nn({target:"Promise",stat:!0,forced:Xu.CONSTRUCTOR},{reject:function(e){var t=rm.f(this);return(0,t.reject)(e),t.promise}});var nm=Lt,om=G,sm=Qu,am=function(e,t){if(nm(e),om(t)&&t.constructor===e)return t;var i=sm.f(e);return(0,i.resolve)(t),i.promise},cm=nn,lm=Xu.CONSTRUCTOR,dm=am;K("Promise"),cm({target:"Promise",stat:!0,forced:lm},{resolve:function(e){return dm(this,e)}});var um=nn,hm=Vu,pm=s,mm=K,_m=H,fm=vd,gm=am,Em=$i,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=b,Im=rt("match"),Am=function(e){var t;return ym(e)&&(void 0!==(t=e[Im])?!!t:"RegExp"===Sm(e))},Rm=Lt,Cm=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},bm=u,km=Ge,Dm=q,wm=Cm,Nm=RegExp.prototype,Om=function(e){var t=e.flags;return void 0!==t||"flags"in Nm||km(e,"flags")||!Dm(Nm,e)?t:bm(wm,e)},Mm=s,Pm=n.RegExp,Lm=Mm((function(){var e=Pm("a","y");return e.lastIndex=2,null!==e.exec("abcd")})),xm=Lm||Mm((function(){return!Pm("a","y").sticky})),Vm=Lm||Mm((function(){var e=Pm("^r","gy");return e.lastIndex=2,null!==e.exec("str")})),Um={BROKEN_CARET:Vm,MISSED_STICKY:xm,UNSUPPORTED_Y:Lm},Fm=wt.f,Bm=s,Hm=n.RegExp,Wm=Bm((function(){var e=Hm(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)})),Gm=s,jm=n.RegExp,Jm=Gm((function(){var e=jm("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Km=a,qm=n,zm=I,Ym=Yr,Xm=Ic,Qm=Yt,Zm=lo,$m=er.f,e_=q,t_=Am,i_=_n,r_=Om,n_=Um,o_=function(e,t,i){i in e||Fm(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},s_=$i,a_=s,c_=Ge,l_=wi.enforce,d_=wl,u_=Wm,h_=Jm,p_=rt("match"),m_=qm.RegExp,__=m_.prototype,f_=qm.SyntaxError,g_=zm(__.exec),E_=zm("".charAt),T_=zm("".replace),v_=zm("".indexOf),y_=zm("".slice),S_=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,I_=/a/g,A_=/a/g,R_=new m_(I_)!==I_,C_=n_.MISSED_STICKY,b_=n_.UNSUPPORTED_Y,k_=Km&&(!R_||C_||u_||h_||a_((function(){return A_[p_]=!1,m_(I_)!==I_||m_(A_)===A_||"/a/i"!==String(m_(I_,"i"))})));if(Ym("RegExp",k_)){for(var D_=function(e,t){var i,r,n,o,s,a,c=e_(__,this),l=t_(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===D_)return e;if((l||e_(__,e))&&(e=e.source,d&&(t=r_(h))),e=void 0===e?"":i_(e),t=void 0===t?"":i_(t),h=e,u_&&"dotAll"in I_&&(r=!!t&&v_(t,"s")>-1)&&(t=T_(t,/s/g,"")),i=t,C_&&"sticky"in I_&&(n=!!t&&v_(t,"y")>-1)&&b_&&(t=T_(t,/y/g,"")),h_&&(o=function(e){for(var t,i=e.length,r=0,n="",o=[],s=Zm(null),a=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=E_(e,r)))t+=E_(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:if(n+=t,"?:"===y_(e,r+1,r+3))continue;g_(S_,y_(e,r+1))&&(r+=2,c=!0),l++;continue;case">"===t&&c:if(""===d||c_(s,d))throw new f_("Invalid capture group name");s[d]=!0,o[o.length]=[d,l],c=!1,d="";continue}c?d+=t:n+=t}return[n,o]}(e),e=o[0],u=o[1]),s=Xm(m_(e,t),c?this:__,D_),(r||n||u.length)&&(a=l_(s),r&&(a.dotAll=!0,a.raw=D_(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=E_(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+E_(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Qm(s,"source",""===h?"(?:)":h)}catch(bJ){}return s},w_=$m(m_),N_=0;w_.length>N_;)o_(D_,m_,w_[N_++]);__.constructor=D_,D_.prototype=__,s_(qm,"RegExp",D_,{constructor:!0})}d_("RegExp");var O_=u,M_=I,P_=_n,L_=Cm,x_=Um,V_=lo,U_=wi.get,F_=Wm,B_=Jm,H_=Ve("native-string-replace",String.prototype.replace),W_=RegExp.prototype.exec,G_=W_,j_=M_("".charAt),J_=M_("".indexOf),K_=M_("".replace),q_=M_("".slice),z_=function(){var e=/a/,t=/b*/g;return O_(W_,e,"a"),O_(W_,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Y_=x_.BROKEN_CARET,X_=void 0!==/()??/.exec("")[1];(z_||X_||Y_||F_||B_)&&(G_=function(e){var t,i,r,n,o,s,a,c=this,l=U_(c),d=P_(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=O_(G_,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Y_&&c.sticky,m=O_(L_,c),_=c.source,f=0,g=d;if(p&&(m=K_(m,"y",""),-1===J_(m,"g")&&(m+="g"),g=q_(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==j_(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),X_&&(i=new RegExp("^"+_+"$(?!\\s)",m)),z_&&(r=c.lastIndex),n=O_(W_,p?i:c,g),p?n?(n.input=q_(n.input,f),n[0]=q_(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:z_&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),X_&&n&&n.length>1&&O_(H_,n[0],i,(function(){for(o=1;o<arguments.length-2;o++)void 0===arguments[o]&&(n[o]=void 0)})),n&&h)for(n.groups=s=V_(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=n[a[1]];return n});var Q_=G_;nn({target:"RegExp",proto:!0,forced:/./.exec!==Q_},{exec:Q_});var Z_=or,$_=_n,ef=x,tf=RangeError,rf=I,nf=hr,of=_n,sf=function(e){var t=$_(ef(this)),i="",r=Z_(e);if(r<0||Infinity===r)throw new tf("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},af=x,cf=rf(sf),lf=rf("".slice),df=Math.ceil,uf=function(e){return function(t,i,r){var n,o,s=of(af(t)),a=nf(i),c=s.length,l=void 0===r?" ":of(r);return a<=c||""===l?s:((o=cf(l,df((n=a-c)/l.length))).length>n&&(o=lf(o,0,n)),e?s+o:o+s)}},hf={start:uf(!1),end:uf(!0)},pf=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(X),mf=hf.start;nn({target:"String",proto:!0,forced:pf},{padStart:function(e){return mf(this,e,arguments.length>1?arguments[1]:void 0)}});var _f=u,ff=$i,gf=Q_,Ef=s,Tf=rt,vf=Yt,yf=Tf("species"),Sf=RegExp.prototype,If=I,Af=or,Rf=_n,Cf=x,bf=If("".charAt),kf=If("".charCodeAt),Df=If("".slice),wf=function(e){return function(t,i){var r,n,o=Rf(Cf(t)),s=Af(i),a=o.length;return s<0||s>=a?e?"":void 0:(r=kf(o,s))<55296||r>56319||s+1===a||(n=kf(o,s+1))<56320||n>57343?e?bf(o,s):r:e?Df(o,s,s+2):n-56320+(r-55296<<10)+65536}},Nf={codeAt:wf(!1),charAt:wf(!0)},Of=Nf.charAt,Mf=I,Pf=Be,Lf=Math.floor,xf=Mf("".charAt),Vf=Mf("".replace),Uf=Mf("".slice),Ff=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Bf=/\$([$&'`]|\d{1,2})/g,Hf=function(e,t,i,r,n,o){var s=i+e.length,a=r.length,c=Bf;return void 0!==n&&(n=Pf(n),c=Ff),Vf(o,c,(function(o,c){var l;switch(xf(c,0)){case"$":return"$";case"&":return e;case"`":return Uf(t,0,i);case"'":return Uf(t,s);case"<":l=n[Uf(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Lf(d/10);return 0===u?o:u<=a?void 0===r[u-1]?xf(c,1):r[u-1]+xf(c,1):o}l=r[d-1]}return void 0===l?"":l}))},Wf=u,Gf=Lt,jf=H,Jf=b,Kf=Q_,qf=TypeError,zf=Rd,Yf=u,Xf=I,Qf=function(e,t,i,r){var n=Tf(e),o=!Ef((function(){var t={};return t[n]=function(){return 7},7!==""[e](t)})),s=o&&!Ef((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[yf]=function(){return i},i.flags="",i[n]=/./[n]),i.exec=function(){return t=!0,null},i[n](""),!t}));if(!o||!s||i){var a=/./[n],c=t(n,""[e],(function(e,t,i,r,n){var s=t.exec;return s===gf||s===Sf.exec?o&&!n?{done:!0,value:_f(a,t,i,r)}:{done:!0,value:_f(e,i,t,r)}:{done:!1}}));ff(String.prototype,e,c[0]),ff(Sf,n,c[1])}r&&vf(Sf[n],"sham",!0)},Zf=s,$f=Lt,eg=H,tg=M,ig=or,rg=hr,ng=_n,og=x,sg=function(e,t,i){return t+(i?Of(e,t).length:1)},ag=Se,cg=Hf,lg=function(e,t){var i=e.exec;if(jf(i)){var r=Wf(i,e,t);return null!==r&&Gf(r),r}if("RegExp"===Jf(e))return Wf(Kf,e,t);throw new qf("RegExp#exec called on incompatible receiver")},dg=rt("replace"),ug=Math.max,hg=Math.min,pg=Xf([].concat),mg=Xf([].push),_g=Xf("".indexOf),fg=Xf("".slice),gg="$0"==="a".replace(/./,"$0"),Eg=!!/./[dg]&&""===/./[dg]("a","$0"),Tg=!Zf((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));Qf("replace",(function(e,t,i){var r=Eg?"$":"$0";return[function(e,i){var r=og(this),n=tg(e)?void 0:ag(e,dg);return n?Yf(n,e,r,i):Yf(t,ng(r),e,i)},function(e,n){var o=$f(this),s=ng(e);if("string"==typeof n&&-1===_g(n,r)&&-1===_g(n,"$<")){var a=i(t,o,s,n);if(a.done)return a.value}var c=eg(n);c||(n=ng(n));var l,d=o.global;d&&(l=o.unicode,o.lastIndex=0);for(var u,h=[];null!==(u=lg(o,s))&&(mg(h,u),d);){""===ng(u[0])&&(o.lastIndex=sg(s,rg(o.lastIndex),l))}for(var p,m="",_=0,f=0;f<h.length;f++){for(var g,E=ng((u=h[f])[0]),T=ug(hg(ig(u.index),s.length),0),v=[],y=1;y<u.length;y++)mg(v,void 0===(p=u[y])?p:String(p));var S=u.groups;if(c){var I=pg([E],v,T,s);void 0!==S&&mg(I,S),g=ng(zf(n,void 0,I))}else g=cg(E,s,T,v,S,n);T>=_&&(m+=fg(s,_,T)+g,_=T+E.length)}return m+fg(s,_)}]}),!Tg||!gg||Eg);var vg="\t\n\v\f\r \u2028\u2029\ufeff",yg=x,Sg=_n,Ig=vg,Ag=I("".replace),Rg=RegExp("^["+Ig+"]+"),Cg=RegExp("(^|[^"+Ig+"])["+Ig+"]+$"),bg=function(e){return function(t){var i=Sg(yg(t));return 1&e&&(i=Ag(i,Rg,"")),2&e&&(i=Ag(i,Cg,"$1")),i}},kg={start:bg(1),end:bg(2),trim:bg(3)},Dg=ii.PROPER,wg=s,Ng=vg,Og=kg.trim;nn({target:"String",proto:!0,forced:function(e){return wg((function(){return!!Ng[e]()||"
"!=="
"[e]()||Dg&&Ng[e].name!==e}))}("trim")},{trim:function(){return Og(this)}});var Mg,Pg,Lg,xg={exports:{}},Vg=Ka,Ug=a,Fg=n,Bg=H,Hg=G,Wg=Ge,Gg=hn,jg=_e,Jg=Yt,Kg=$i,qg=En,zg=q,Yg=No,Xg=cs,Qg=rt,Zg=ze,$g=wi.enforce,eE=wi.get,tE=Fg.Int8Array,iE=tE&&tE.prototype,rE=Fg.Uint8ClampedArray,nE=rE&&rE.prototype,oE=tE&&Yg(tE),sE=iE&&Yg(iE),aE=Object.prototype,cE=Fg.TypeError,lE=Qg("toStringTag"),dE=Zg("TYPED_ARRAY_TAG"),uE="TypedArrayConstructor",hE=Vg&&!!Xg&&"Opera"!==Gg(Fg.opera),pE=!1,mE={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},_E={BigInt64Array:8,BigUint64Array:8},fE=function(e){var t=Yg(e);if(Hg(t)){var i=eE(t);return i&&Wg(i,uE)?i[uE]:fE(t)}},gE=function(e){if(!Hg(e))return!1;var t=Gg(e);return Wg(mE,t)||Wg(_E,t)};for(Mg in mE)(Lg=(Pg=Fg[Mg])&&Pg.prototype)?$g(Lg)[uE]=Pg:hE=!1;for(Mg in _E)(Lg=(Pg=Fg[Mg])&&Pg.prototype)&&($g(Lg)[uE]=Pg);if((!hE||!Bg(oE)||oE===Function.prototype)&&(oE=function(){throw new cE("Incorrect invocation")},hE))for(Mg in mE)Fg[Mg]&&Xg(Fg[Mg],oE);if((!hE||!sE||sE===aE)&&(sE=oE.prototype,hE))for(Mg in mE)Fg[Mg]&&Xg(Fg[Mg].prototype,sE);if(hE&&Yg(nE)!==sE&&Xg(nE,sE),Ug&&!Wg(sE,lE))for(Mg in pE=!0,qg(sE,lE,{configurable:!0,get:function(){return Hg(this)?this[dE]:void 0}}),mE)Fg[Mg]&&Jg(Fg[Mg],dE,Mg);var EE={NATIVE_ARRAY_BUFFER_VIEWS:hE,TYPED_ARRAY_TAG:pE&&dE,aTypedArray:function(e){if(gE(e))return e;throw new cE("Target is not a typed array")},aTypedArrayConstructor:function(e){if(Bg(e)&&(!Xg||zg(oE,e)))return e;throw new cE(jg(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(Ug){if(i)for(var n in mE){var o=Fg[n];if(o&&Wg(o.prototype,e))try{delete o.prototype[e]}catch(bJ){try{o.prototype[e]=t}catch(s){}}}sE[e]&&!i||Kg(sE,e,i?t:hE&&iE[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(Ug){if(Xg){if(i)for(r in mE)if((n=Fg[r])&&Wg(n,e))try{delete n[e]}catch(bJ){}if(oE[e]&&!i)return;try{return Kg(oE,e,i?t:hE&&oE[e]||t)}catch(bJ){}}for(r in mE)!(n=Fg[r])||n[e]&&!i||Kg(n,e,t)}},getTypedArrayConstructor:fE,isView:function(e){if(!Hg(e))return!1;var t=Gg(e);return"DataView"===t||Wg(mE,t)||Wg(_E,t)},isTypedArray:gE,TypedArray:oE,TypedArrayPrototype:sE},TE=n,vE=s,yE=xp,SE=EE.NATIVE_ARRAY_BUFFER_VIEWS,IE=TE.ArrayBuffer,AE=TE.Int8Array,RE=!SE||!vE((function(){AE(1)}))||!vE((function(){new AE(-1)}))||!yE((function(e){new AE,new AE(null),new AE(1.5),new AE(e)}),!0)||vE((function(){return 1!==new AE(new IE(2),1,void 0).length})),CE=G,bE=Math.floor,kE=Number.isInteger||function(e){return!CE(e)&&isFinite(e)&&bE(e)===e},DE=or,wE=RangeError,NE=function(e){var t=DE(e);if(t<0)throw new wE("The argument can't be less than 0");return t},OE=RangeError,ME=function(e,t){var i=NE(e);if(i%t)throw new OE("Wrong offset");return i},PE=Math.round,LE=hn,xE=ut,VE=TypeError,UE=function(e){var t=xE(e,"number");if("number"==typeof t)throw new VE("Can't convert number to bigint");return BigInt(t)},FE=Dd,BE=u,HE=_d,WE=Be,GE=mr,jE=pp,JE=sp,KE=ep,qE=function(e){var t=LE(e);return"BigInt64Array"===t||"BigUint64Array"===t},zE=EE.aTypedArrayConstructor,YE=UE,XE=function(e){var t,i,r,n,o,s,a,c,l=HE(this),d=WE(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=JE(d);if(m&&!KE(m))for(c=(a=jE(d,m)).next,d=[];!(s=BE(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=FE(h,arguments[2])),i=GE(d),r=new(zE(l))(i),n=qE(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?YE(o):+o;return r},QE=ca,ZE=ud,$E=G,eT=rt("species"),tT=Array,iT=function(e){var t;return QE(e)&&(t=e.constructor,(ZE(t)&&(t===tT||QE(t.prototype))||$E(t)&&null===(t=t[eT]))&&(t=void 0)),void 0===t?tT:t},rT=Dd,nT=O,oT=Be,sT=mr,aT=function(e,t){return new(iT(e))(0===t?0:t)},cT=I([].push),lT=function(e){var t=1===e,i=2===e,r=3===e,n=4===e,o=6===e,s=7===e,a=5===e||o;return function(c,l,d,u){for(var h,p,m=oT(c),_=nT(m),f=sT(_),g=rT(l,d),E=0,T=u||aT,v=t?T(c,f):i||s?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:cT(v,h)}else switch(e){case 4:return!1;case 7:cT(v,h)}return o?-1:r||n?n:v}},dT={forEach:lT(0),map:lT(1),filter:lT(2),some:lT(3),every:lT(4),find:lT(5),findIndex:lT(6),filterReject:lT(7)},uT=mr,hT=nn,pT=n,mT=u,_T=a,fT=RE,gT=EE,ET=Rl,TT=Qa,vT=E,yT=Yt,ST=kE,IT=hr,AT=tc,RT=ME,CT=function(e){var t=PE(e);return t<0?0:t>255?255:255&t},bT=mt,kT=Ge,DT=hn,wT=G,NT=pe,OT=lo,MT=q,PT=cs,LT=er.f,xT=XE,VT=dT.forEach,UT=wl,FT=En,BT=wt,HT=o,WT=function(e,t,i){for(var r=0,n=arguments.length>2?i:uT(t),o=new e(n);n>r;)o[r]=t[r++];return o},GT=Ic,jT=wi.get,JT=wi.set,KT=wi.enforce,qT=BT.f,zT=HT.f,YT=pT.RangeError,XT=ET.ArrayBuffer,QT=XT.prototype,ZT=ET.DataView,$T=gT.NATIVE_ARRAY_BUFFER_VIEWS,ev=gT.TYPED_ARRAY_TAG,tv=gT.TypedArray,iv=gT.TypedArrayPrototype,rv=gT.isTypedArray,nv="BYTES_PER_ELEMENT",ov="Wrong length",sv=function(e,t){FT(e,t,{configurable:!0,get:function(){return jT(this)[t]}})},av=function(e){var t;return MT(QT,e)||"ArrayBuffer"===(t=DT(e))||"SharedArrayBuffer"===t},cv=function(e,t){return rv(e)&&!NT(t)&&t in e&&ST(+t)&&t>=0},lv=function(e,t){return t=bT(t),cv(e,t)?vT(2,e[t]):zT(e,t)},dv=function(e,t,i){return t=bT(t),!(cv(e,t)&&wT(i)&&kT(i,"value"))||kT(i,"get")||kT(i,"set")||i.configurable||kT(i,"writable")&&!i.writable||kT(i,"enumerable")&&!i.enumerable?qT(e,t,i):(e[t]=i.value,e)};_T?($T||(HT.f=lv,BT.f=dv,sv(iv,"buffer"),sv(iv,"byteOffset"),sv(iv,"byteLength"),sv(iv,"length")),hT({target:"Object",stat:!0,forced:!$T},{getOwnPropertyDescriptor:lv,defineProperty:dv}),xg.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=pT[n],c=a,l=c&&c.prototype,d={},u=function(e,t){qT(e,t,{get:function(){return function(e,t){var i=jT(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=jT(e);o.view[s](t*r+o.byteOffset,i?CT(n):n,!0)}(this,t,e)},enumerable:!0})};$T?fT&&(c=t((function(e,t,i,n){return TT(e,l),GT(wT(t)?av(t)?void 0!==n?new a(t,RT(i,r),n):void 0!==i?new a(t,RT(i,r)):new a(t):rv(t)?WT(c,t):mT(xT,c,t):new a(AT(t)),e,c)})),PT&&PT(c,tv),VT(LT(a),(function(e){e in c||yT(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,n){TT(e,l);var o,s,a,d=0,h=0;if(wT(t)){if(!av(t))return rv(t)?WT(c,t):mT(xT,c,t);o=t,h=RT(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw new YT(ov);if((s=p-h)<0)throw new YT(ov)}else if((s=IT(n)*r)+h>p)throw new YT(ov);a=s/r}else a=AT(t),o=new XT(s=a*r);for(JT(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new ZT(o)});d<a;)u(e,d++)})),PT&&PT(c,tv),l=c.prototype=OT(iv)),l.constructor!==c&&yT(l,"constructor",c),KT(l).TypedArrayConstructor=c,ev&&yT(l,ev,n);var h=c!==a;d[n]=c,hT({global:!0,constructor:!0,forced:h,sham:!$T},d),nv in c||yT(c,nv,r),nv in l||yT(l,nv,r),UT(n)}):xg.exports=function(){};var uv=xg.exports;uv("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}})),uv("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var hv=Tc,pv=UE,mv=hn,_v=u,fv=s,gv=EE.aTypedArray,Ev=EE.exportTypedArrayMethod,Tv=I("".slice);Ev("fill",(function(e){var t=arguments.length;gv(this);var i="Big"===Tv(mv(this),0,3)?pv(e):+e;return _v(hv,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),fv((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e}))),(0,EE.exportTypedArrayStaticMethod)("from",XE,RE);var vv=n,yv=u,Sv=EE,Iv=mr,Av=ME,Rv=Be,Cv=s,bv=vv.RangeError,kv=vv.Int8Array,Dv=kv&&kv.prototype,wv=Dv&&Dv.set,Nv=Sv.aTypedArray,Ov=Sv.exportTypedArrayMethod,Mv=!Cv((function(){var e=new Uint8ClampedArray(2);return yv(wv,e,{length:1,0:3},1),3!==e[1]})),Pv=Mv&&Sv.NATIVE_ARRAY_BUFFER_VIEWS&&Cv((function(){var e=new kv(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));Ov("set",(function(e){Nv(this);var t=Av(arguments.length>1?arguments[1]:void 0,1),i=Rv(e);if(Mv)return yv(wv,this,i,t);var r=this.length,n=Iv(i),o=0;if(n+t>r)throw new bv("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!Mv||Pv);var Lv=xl,xv=s,Vv=Te,Uv=Ta,Fv=ya,Bv=Sa,Hv=re,Wv=Aa,Gv=EE.aTypedArray,jv=EE.exportTypedArrayMethod,Jv=n.Uint16Array,Kv=Jv&&Lv(Jv.prototype.sort),qv=!(!Kv||xv((function(){Kv(new Jv(2),null)}))&&xv((function(){Kv(new Jv(2),{})}))),zv=!!Kv&&!xv((function(){if(Hv)return Hv<74;if(Fv)return Fv<67;if(Bv)return!0;if(Wv)return Wv<602;var e,t,i=new Jv(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(Kv(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));jv("sort",(function(e){return void 0!==e&&Vv(e),zv?Kv(this,e):Uv(Gv(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))}),!zv||qv);var Yv=nn,Xv=u,Qv=I,Zv=x,$v=H,ey=M,ty=Am,iy=_n,ry=Se,ny=Om,oy=Hf,sy=rt("replace"),ay=TypeError,cy=Qv("".indexOf);Qv("".replace);var ly=Qv("".slice),dy=Math.max;Yv({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,n,o,s,a,c,l,d,u=Zv(this),h=0,p="";if(!ey(e)){if(ty(e)&&(i=iy(Zv(ny(e))),!~cy(i,"g")))throw new ay("`.replaceAll` does not allow non-global regexes");if(r=ry(e,sy))return Xv(r,e,u,t)}for(n=iy(u),o=iy(e),(s=$v(t))||(t=iy(t)),a=o.length,c=dy(1,a),l=cy(n,o);-1!==l;)d=s?iy(t(o,l,n)):oy(o,n,l,[],void 0,t),p+=ly(n,h,l)+d,h=l+a,l=l+c>n.length?-1:cy(n,o,l+c);return h<n.length&&(p+=ly(n,h)),p}});var uy={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},hy=Et("span").classList,py=hy&&hy.constructor&&hy.constructor.prototype,my=py===Object.prototype?void 0:py,_y=dT.forEach,fy=Zs("forEach")?[].forEach:function(e){return _y(this,e,arguments.length>1?arguments[1]:void 0)},gy=n,Ey=uy,Ty=my,vy=fy,yy=Yt,Sy=function(e){if(e&&e.forEach!==vy)try{yy(e,"forEach",vy)}catch(bJ){e.forEach=vy}};for(var Iy in Ey)Ey[Iy]&&Sy(gy[Iy]&&gy[Iy].prototype);Sy(Ty);var Ay=n,Ry=uy,Cy=my,by=Hs,ky=Yt,Dy=jo,wy=rt("iterator"),Ny=by.values,Oy=function(e,t){if(e){if(e[wy]!==Ny)try{ky(e,wy,Ny)}catch(bJ){e[wy]=Ny}if(Dy(e,t,!0),Ry[t])for(var i in by)if(e[i]!==by[i])try{ky(e,i,by[i])}catch(bJ){e[i]=by[i]}}};for(var My in Ry)Oy(Ay[My]&&Ay[My].prototype,My);Oy(Cy,"DOMTokenList");var Py=Nf.charAt,Ly=_n,xy=wi,Vy=ks,Uy=Ds,Fy="String Iterator",By=xy.set,Hy=xy.getterFor(Fy);Vy(String,"String",(function(e){By(this,{type:Fy,string:Ly(e),index:0})}),(function(){var e,t=Hy(this),i=t.string,r=t.index;return r>=i.length?Uy(void 0,!0):(e=Py(i,r),t.index+=e.length,Uy(e,!1))}));var Wy=s,Gy=a,jy=rt("iterator"),Jy=!Wy((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&&!Gy||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[jy]||"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=a,qy=I,zy=u,Yy=s,Xy=Hn,Qy=Dr,Zy=h,$y=Be,eS=O,tS=Object.assign,iS=Object.defineProperty,rS=qy([].concat),nS=!tS||Yy((function(){if(Ky&&1!==tS({b:1},tS(iS({},"a",{enumerable:!0,get:function(){iS(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!==tS({},e)[i]||Xy(tS({},t)).join("")!==r}))?function(e,t){for(var i=$y(e),r=arguments.length,n=1,o=Qy.f,s=Zy.f;r>n;)for(var a,c=eS(arguments[n++]),l=o?rS(Xy(c),o(c)):Xy(c),d=l.length,u=0;d>u;)a=l[u++],Ky&&!zy(s,c,a)||(i[a]=c[a]);return i}:tS,oS=Lt,sS=gp,aS=a,cS=wt,lS=E,dS=Dd,uS=u,hS=Be,pS=function(e,t,i,r){try{return r?t(oS(i)[0],i[1]):t(i)}catch(bJ){sS(e,"throw",bJ)}},mS=ep,_S=ud,fS=mr,gS=function(e,t,i){aS?cS.f(e,t,lS(0,i)):e[t]=i},ES=pp,TS=sp,vS=Array,yS=I,SS=2147483647,IS=/[^\0-\u007E]/,AS=/[.\u3002\uFF0E\uFF61]/g,RS="Overflow: input needs wider integers to process",CS=RangeError,bS=yS(AS.exec),kS=Math.floor,DS=String.fromCharCode,wS=yS("".charCodeAt),NS=yS([].join),OS=yS([].push),MS=yS("".replace),PS=yS("".split),LS=yS("".toLowerCase),xS=function(e){return e+22+75*(e<26)},VS=function(e,t,i){var r=0;for(e=i?kS(e/700):e>>1,e+=kS(e/t);e>455;)e=kS(e/35),r+=36;return kS(r+36*e/(e+38))},US=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=wS(e,i++);if(n>=55296&&n<=56319&&i<r){var o=wS(e,i++);56320==(64512&o)?OS(t,((1023&n)<<10)+(1023&o)+65536):(OS(t,n),i--)}else OS(t,n)}return t}(e);var i,r,n=e.length,o=128,s=0,a=72;for(i=0;i<e.length;i++)(r=e[i])<128&&OS(t,DS(r));var c=t.length,l=c;for(c&&OS(t,"-");l<n;){var d=SS;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>kS((SS-s)/u))throw new CS(RS);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++s>SS)throw new CS(RS);if(r===o){for(var h=s,p=36;;){var m=p<=a?1:p>=a+26?26:p-a;if(h<m)break;var _=h-m,f=36-m;OS(t,DS(xS(m+_%f))),h=kS(_/f),p+=36}OS(t,DS(xS(h))),a=VS(s,u,l===c),s=0,l++}}s++,o++}return NS(t,"")},FS=nn,BS=I,HS=lr,WS=RangeError,GS=String.fromCharCode,jS=String.fromCodePoint,JS=BS([].join);FS({target:"String",stat:!0,arity:1,forced:!!jS&&1!==jS.length},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,n=0;r>n;){if(t=+arguments[n++],HS(t,1114111)!==t)throw new WS(t+" is not a valid code point");i[n]=t<65536?GS(t):GS(55296+((t-=65536)>>10),t%1024+56320)}return JS(i,"")}});var KS=nn,qS=n,zS=lu,YS=K,XS=u,QS=I,ZS=a,$S=Jy,eI=$i,tI=En,iI=za,rI=jo,nI=Qo,oI=wi,sI=Qa,aI=H,cI=Ge,lI=Dd,dI=hn,uI=Lt,hI=G,pI=_n,mI=lo,_I=E,fI=pp,gI=sp,EI=Ds,TI=Nd,vI=Ta,yI=rt("iterator"),SI="URLSearchParams",II=SI+"Iterator",AI=oI.set,RI=oI.getterFor(SI),CI=oI.getterFor(II),bI=zS("fetch"),kI=zS("Request"),DI=zS("Headers"),wI=kI&&kI.prototype,NI=DI&&DI.prototype,OI=qS.TypeError,MI=qS.encodeURIComponent,PI=String.fromCharCode,LI=YS("String","fromCodePoint"),xI=parseInt,VI=QS("".charAt),UI=QS([].join),FI=QS([].push),BI=QS("".replace),HI=QS([].shift),WI=QS([].splice),GI=QS("".split),jI=QS("".slice),JI=QS(/./.exec),KI=/\+/g,qI=/^[0-9a-f]+$/i,zI=function(e,t){var i=jI(e,t,t+2);return JI(qI,i)?xI(i,16):NaN},YI=function(e){for(var t=0,i=128;i>0&&e&i;i>>=1)t++;return t},XI=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},QI=function(e){for(var t=(e=BI(e,KI," ")).length,i="",r=0;r<t;){var n=VI(e,r);if("%"===n){if("%"===VI(e,r+1)||r+3>t){i+="%",r++;continue}var o=zI(e,r+1);if(o!=o){i+=n,r++;continue}r+=2;var s=YI(o);if(0===s)n=PI(o);else{if(1===s||s>4){i+="�",r++;continue}for(var a=[o],c=1;c<s&&!(++r+3>t||"%"!==VI(e,r));){var l=zI(e,r+1);if(l!=l){r+=3;break}if(l>191||l<128)break;FI(a,l),r+=2,c++}if(a.length!==s){i+="�";continue}var d=XI(a);null===d?i+="�":n=LI(d)}}i+=n,r++}return i},ZI=/[!'()~]|%20/g,$I={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},eA=function(e){return $I[e]},tA=function(e){return BI(MI(e),ZI,eA)},iA=nI((function(e,t){AI(this,{type:II,target:RI(e).entries,index:0,kind:t})}),SI,(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),rA=function(e){this.entries=[],this.url=null,void 0!==e&&(hI(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===VI(e,0)?jI(e,1):e:pI(e)))};rA.prototype={type:SI,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,s,a,c=this.entries,l=gI(e);if(l)for(i=(t=fI(e,l)).next;!(r=XS(i,t)).done;){if(o=(n=fI(uI(r.value))).next,(s=XS(o,n)).done||(a=XS(o,n)).done||!XS(o,n).done)throw new OI("Expected sequence with length 2");FI(c,{key:pI(s.value),value:pI(a.value)})}else for(var d in e)cI(e,d)&&FI(c,{key:d,value:pI(e[d])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,n=GI(e,"&"),o=0;o<n.length;)(t=n[o++]).length&&(i=GI(t,"="),FI(r,{key:QI(HI(i)),value:QI(UI(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],FI(i,tA(e.key)+"="+tA(e.value));return UI(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var nA=function(){sI(this,oA);var e=AI(this,new rA(arguments.length>0?arguments[0]:void 0));ZS||(this.size=e.entries.length)},oA=nA.prototype;if(iI(oA,{append:function(e,t){var i=RI(this);TI(arguments.length,2),FI(i.entries,{key:pI(e),value:pI(t)}),ZS||this.length++,i.updateURL()},delete:function(e){for(var t=RI(this),i=TI(arguments.length,1),r=t.entries,n=pI(e),o=i<2?void 0:arguments[1],s=void 0===o?o:pI(o),a=0;a<r.length;){var c=r[a];if(c.key!==n||void 0!==s&&c.value!==s)a++;else if(WI(r,a,1),void 0!==s)break}ZS||(this.size=r.length),t.updateURL()},get:function(e){var t=RI(this).entries;TI(arguments.length,1);for(var i=pI(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=RI(this).entries;TI(arguments.length,1);for(var i=pI(e),r=[],n=0;n<t.length;n++)t[n].key===i&&FI(r,t[n].value);return r},has:function(e){for(var t=RI(this).entries,i=TI(arguments.length,1),r=pI(e),n=i<2?void 0:arguments[1],o=void 0===n?n:pI(n),s=0;s<t.length;){var a=t[s++];if(a.key===r&&(void 0===o||a.value===o))return!0}return!1},set:function(e,t){var i=RI(this);TI(arguments.length,1);for(var r,n=i.entries,o=!1,s=pI(e),a=pI(t),c=0;c<n.length;c++)(r=n[c]).key===s&&(o?WI(n,c--,1):(o=!0,r.value=a));o||FI(n,{key:s,value:a}),ZS||(this.size=n.length),i.updateURL()},sort:function(){var e=RI(this);vI(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=RI(this).entries,r=lI(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 iA(this,"keys")},values:function(){return new iA(this,"values")},entries:function(){return new iA(this,"entries")}},{enumerable:!0}),eI(oA,yI,oA.entries,{name:"entries"}),eI(oA,"toString",(function(){return RI(this).serialize()}),{enumerable:!0}),ZS&&tI(oA,"size",{get:function(){return RI(this).entries.length},configurable:!0,enumerable:!0}),rI(nA,SI),KS({global:!0,constructor:!0,forced:!$S},{URLSearchParams:nA}),!$S&&aI(DI)){var sA=QS(NI.has),aA=QS(NI.set),cA=function(e){if(hI(e)){var t,i=e.body;if(dI(i)===SI)return t=e.headers?new DI(e.headers):new DI,sA(t,"content-type")||aA(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),mI(e,{body:_I(0,pI(i)),headers:_I(0,t)})}return e};if(aI(bI)&&KS({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return bI(e,arguments.length>1?cA(arguments[1]):{})}}),aI(kI)){var lA=function(e){return sI(this,wI),new kI(e,arguments.length>1?cA(arguments[1]):{})};wI.constructor=lA,lA.prototype=wI,KS({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:lA})}}var dA,uA=nn,hA=a,pA=Jy,mA=n,_A=Dd,fA=I,gA=$i,EA=En,TA=Qa,vA=Ge,yA=nS,SA=function(e){var t=hS(e),i=_S(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=dS(n,r>2?arguments[2]:void 0));var s,a,c,l,d,u,h=TS(t),p=0;if(!h||this===vS&&mS(h))for(s=fS(t),a=i?new this(s):vS(s);s>p;p++)u=o?n(t[p],p):t[p],gS(a,p,u);else for(a=i?new this:[],d=(l=ES(t,h)).next;!(c=uS(d,l)).done;p++)u=o?pS(l,n,[c.value,p],!0):c.value,gS(a,p,u);return a.length=p,a},IA=_a,AA=Nf.codeAt,RA=function(e){var t,i,r=[],n=PS(MS(LS(e),AS,"."),".");for(t=0;t<n.length;t++)i=n[t],OS(r,bS(IS,i)?"xn--"+US(i):i);return NS(r,".")},CA=_n,bA=jo,kA=Nd,DA={URLSearchParams:nA,getState:RI},wA=wi,NA=wA.set,OA=wA.getterFor("URL"),MA=DA.URLSearchParams,PA=DA.getState,LA=mA.URL,xA=mA.TypeError,VA=mA.parseInt,UA=Math.floor,FA=Math.pow,BA=fA("".charAt),HA=fA(/./.exec),WA=fA([].join),GA=fA(1..toString),jA=fA([].pop),JA=fA([].push),KA=fA("".replace),qA=fA([].shift),zA=fA("".split),YA=fA("".slice),XA=fA("".toLowerCase),QA=fA([].unshift),ZA="Invalid scheme",$A="Invalid host",eR="Invalid port",tR=/[a-z]/i,iR=/[\d+-.a-z]/i,rR=/\d/,nR=/^0x/i,oR=/^[0-7]+$/,sR=/^\d+$/,aR=/^[\da-f]+$/i,cR=/[\0\t\n\r #%/:<>?@[\\\]^|]/,lR=/[\0\t\n\r #/:<>?@[\\\]^|]/,dR=/^[\u0000-\u0020]+/,uR=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,hR=/[\t\n\r]/g,pR=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)QA(t,e%256),e=UA(e/256);return WA(t,".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,i=1,r=null,n=0,o=0;o<8;o++)0!==e[o]?(n>i&&(t=r,i=n),r=null,n=0):(null===r&&(r=o),++n);return n>i?r:t}(e),i=0;i<8;i++)n&&0===e[i]||(n&&(n=!1),r===i?(t+=i?":":"::",n=!0):(t+=GA(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},mR={},_R=yA({},mR,{" ":1,'"':1,"<":1,">":1,"`":1}),fR=yA({},_R,{"#":1,"?":1,"{":1,"}":1}),gR=yA({},fR,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),ER=function(e,t){var i=AA(e,0);return i>32&&i<127&&!vA(t,e)?e:encodeURIComponent(e)},TR={ftp:21,file:null,http:80,https:443,ws:80,wss:443},vR=function(e,t){var i;return 2===e.length&&HA(tR,BA(e,0))&&(":"===(i=BA(e,1))||!t&&"|"===i)},yR=function(e){var t;return e.length>1&&vR(YA(e,0,2))&&(2===e.length||"/"===(t=BA(e,2))||"\\"===t||"?"===t||"#"===t)},SR=function(e){return"."===e||"%2e"===XA(e)},IR={},AR={},RR={},CR={},bR={},kR={},DR={},wR={},NR={},OR={},MR={},PR={},LR={},xR={},VR={},UR={},FR={},BR={},HR={},WR={},GR={},jR=function(e,t,i){var r,n,o,s=CA(e);if(t){if(n=this.parse(s))throw new xA(n);this.searchParams=null}else{if(void 0!==i&&(r=new jR(i,!0)),n=this.parse(s,null,r))throw new xA(n);(o=PA(new MA)).bindURL(this),this.searchParams=o}};jR.prototype={type:"URL",parse:function(e,t,i){var r,n,o,s,a,c=this,l=t||IR,d=0,u="",h=!1,p=!1,m=!1;for(e=CA(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=KA(e,dR,""),e=KA(e,uR,"$1")),e=KA(e,hR,""),r=SA(e);d<=r.length;){switch(n=r[d],l){case IR:if(!n||!HA(tR,n)){if(t)return ZA;l=RR;continue}u+=XA(n),l=AR;break;case AR:if(n&&(HA(iR,n)||"+"===n||"-"===n||"."===n))u+=XA(n);else{if(":"!==n){if(t)return ZA;u="",l=RR,d=0;continue}if(t&&(c.isSpecial()!==vA(TR,u)||"file"===u&&(c.includesCredentials()||null!==c.port)||"file"===c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&TR[c.scheme]===c.port&&(c.port=null));u="","file"===c.scheme?l=xR:c.isSpecial()&&i&&i.scheme===c.scheme?l=CR:c.isSpecial()?l=wR:"/"===r[d+1]?(l=bR,d++):(c.cannotBeABaseURL=!0,JA(c.path,""),l=HR)}break;case RR:if(!i||i.cannotBeABaseURL&&"#"!==n)return ZA;if(i.cannotBeABaseURL&&"#"===n){c.scheme=i.scheme,c.path=IA(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=GR;break}l="file"===i.scheme?xR:kR;continue;case CR:if("/"!==n||"/"!==r[d+1]){l=kR;continue}l=NR,d++;break;case bR:if("/"===n){l=OR;break}l=BR;continue;case kR:if(c.scheme=i.scheme,n===dA)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=IA(i.path),c.query=i.query;else if("/"===n||"\\"===n&&c.isSpecial())l=DR;else if("?"===n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=IA(i.path),c.query="",l=WR;else{if("#"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=IA(i.path),c.path.length--,l=BR;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=IA(i.path),c.query=i.query,c.fragment="",l=GR}break;case DR:if(!c.isSpecial()||"/"!==n&&"\\"!==n){if("/"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=BR;continue}l=OR}else l=NR;break;case wR:if(l=NR,"/"!==n||"/"!==BA(u,d+1))continue;d++;break;case NR:if("/"!==n&&"\\"!==n){l=OR;continue}break;case OR:if("@"===n){h&&(u="%40"+u),h=!0,o=SA(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!==f||m){var g=ER(f,gR);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n===dA||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(h&&""===u)return"Invalid authority";d-=SA(u).length+1,u="",l=MR}else u+=n;break;case MR:case PR:if(t&&"file"===c.scheme){l=UR;continue}if(":"!==n||p){if(n===dA||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(c.isSpecial()&&""===u)return $A;if(t&&""===u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=FR,t)return;continue}"["===n?p=!0:"]"===n&&(p=!1),u+=n}else{if(""===u)return $A;if(s=c.parseHost(u))return s;if(u="",l=LR,t===PR)return}break;case LR:if(!HA(rR,n)){if(n===dA||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()||t){if(""!==u){var E=VA(u,10);if(E>65535)return eR;c.port=c.isSpecial()&&E===TR[c.scheme]?null:E,u=""}if(t)return;l=FR;continue}return eR}u+=n;break;case xR:if(c.scheme="file","/"===n||"\\"===n)l=VR;else{if(!i||"file"!==i.scheme){l=BR;continue}switch(n){case dA:c.host=i.host,c.path=IA(i.path),c.query=i.query;break;case"?":c.host=i.host,c.path=IA(i.path),c.query="",l=WR;break;case"#":c.host=i.host,c.path=IA(i.path),c.query=i.query,c.fragment="",l=GR;break;default:yR(WA(IA(r,d),""))||(c.host=i.host,c.path=IA(i.path),c.shortenPath()),l=BR;continue}}break;case VR:if("/"===n||"\\"===n){l=UR;break}i&&"file"===i.scheme&&!yR(WA(IA(r,d),""))&&(vR(i.path[0],!0)?JA(c.path,i.path[0]):c.host=i.host),l=BR;continue;case UR:if(n===dA||"/"===n||"\\"===n||"?"===n||"#"===n){if(!t&&vR(u))l=BR;else if(""===u){if(c.host="",t)return;l=FR}else{if(s=c.parseHost(u))return s;if("localhost"===c.host&&(c.host=""),t)return;u="",l=FR}continue}u+=n;break;case FR:if(c.isSpecial()){if(l=BR,"/"!==n&&"\\"!==n)continue}else if(t||"?"!==n)if(t||"#"!==n){if(n!==dA&&(l=BR,"/"!==n))continue}else c.fragment="",l=GR;else c.query="",l=WR;break;case BR:if(n===dA||"/"===n||"\\"===n&&c.isSpecial()||!t&&("?"===n||"#"===n)){if(".."===(a=XA(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"===n||"\\"===n&&c.isSpecial()||JA(c.path,"")):SR(u)?"/"===n||"\\"===n&&c.isSpecial()||JA(c.path,""):("file"===c.scheme&&!c.path.length&&vR(u)&&(c.host&&(c.host=""),u=BA(u,0)+":"),JA(c.path,u)),u="","file"===c.scheme&&(n===dA||"?"===n||"#"===n))for(;c.path.length>1&&""===c.path[0];)qA(c.path);"?"===n?(c.query="",l=WR):"#"===n&&(c.fragment="",l=GR)}else u+=ER(n,fR);break;case HR:"?"===n?(c.query="",l=WR):"#"===n?(c.fragment="",l=GR):n!==dA&&(c.path[0]+=ER(n,mR));break;case WR:t||"#"!==n?n!==dA&&("'"===n&&c.isSpecial()?c.query+="%27":c.query+="#"===n?"%23":ER(n,mR)):(c.fragment="",l=GR);break;case GR:n!==dA&&(c.fragment+=ER(n,_R))}d++}},parseHost:function(e){var t,i,r;if("["===BA(e,0)){if("]"!==BA(e,e.length-1))return $A;if(t=function(e){var t,i,r,n,o,s,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return BA(e,u)};if(":"===h()){if(":"!==BA(e,1))return;u+=2,d=++l}for(;h();){if(8===l)return;if(":"!==h()){for(t=i=0;i<4&&HA(aR,h());)t=16*t+VA(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(!HA(rR,h()))return;for(;HA(rR,h());){if(o=VA(h(),10),null===n)n=o;else{if(0===n)return;n=10*n+o}if(n>255)return;u++}c[l]=256*c[l]+n,2!=++r&&4!==r||l++}if(4!==r)return;break}if(":"===h()){if(u++,!h())return}else if(h())return;c[l++]=t}else{if(null!==d)return;u++,d=++l}}if(null!==d)for(s=l-d,l=7;0!==l&&s>0;)a=c[l],c[l--]=c[d+s-1],c[d+--s]=a;else if(8!==l)return;return c}(YA(e,1,-1)),!t)return $A;this.host=t}else if(this.isSpecial()){if(e=RA(e),HA(cR,e))return $A;if(t=function(e){var t,i,r,n,o,s,a,c=zA(e,".");if(c.length&&""===c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],r=0;r<t;r++){if(""===(n=c[r]))return e;if(o=10,n.length>1&&"0"===BA(n,0)&&(o=HA(nR,n)?16:8,n=YA(n,8===o?1:2)),""===n)s=0;else{if(!HA(10===o?sR:8===o?oR:aR,n))return e;s=VA(n,o)}JA(i,s)}for(r=0;r<t;r++)if(s=i[r],r===t-1){if(s>=FA(256,5-t))return null}else if(s>255)return null;for(a=jA(i),r=0;r<i.length;r++)a+=i[r]*FA(256,3-r);return a}(e),null===t)return $A;this.host=t}else{if(HA(lR,e))return $A;for(t="",i=SA(e),r=0;r<i.length;r++)t+=ER(i[r],mR);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return vA(TR,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&vR(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,r=e.password,n=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,l=t+":";return null!==n?(l+="//",e.includesCredentials()&&(l+=i+(r?":"+r:"")+"@"),l+=pR(n),null!==o&&(l+=":"+o)):"file"===t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+WA(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw new xA(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new JR(e.path[0]).origin}catch(bJ){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+pR(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(CA(e)+":",IR)},getUsername:function(){return this.username},setUsername:function(e){var t=SA(CA(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=ER(t[i],gR)}},getPassword:function(){return this.password},setPassword:function(e){var t=SA(CA(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=ER(t[i],gR)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?pR(e):pR(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,MR)},getHostname:function(){var e=this.host;return null===e?"":pR(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,PR)},getPort:function(){var e=this.port;return null===e?"":CA(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=CA(e))?this.port=null:this.parse(e,LR))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+WA(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,FR))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=CA(e))?this.query=null:("?"===BA(e,0)&&(e=YA(e,1)),this.query="",this.parse(e,WR)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=CA(e))?("#"===BA(e,0)&&(e=YA(e,1)),this.fragment="",this.parse(e,GR)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var JR=function(e){var t=TA(this,KR),i=kA(arguments.length,1)>1?arguments[1]:void 0,r=NA(t,new jR(e,!1,i));hA||(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())},KR=JR.prototype,qR=function(e,t){return{get:function(){return OA(this)[e]()},set:t&&function(e){return OA(this)[t](e)},configurable:!0,enumerable:!0}};if(hA&&(EA(KR,"href",qR("serialize","setHref")),EA(KR,"origin",qR("getOrigin")),EA(KR,"protocol",qR("getProtocol","setProtocol")),EA(KR,"username",qR("getUsername","setUsername")),EA(KR,"password",qR("getPassword","setPassword")),EA(KR,"host",qR("getHost","setHost")),EA(KR,"hostname",qR("getHostname","setHostname")),EA(KR,"port",qR("getPort","setPort")),EA(KR,"pathname",qR("getPathname","setPathname")),EA(KR,"search",qR("getSearch","setSearch")),EA(KR,"searchParams",qR("getSearchParams")),EA(KR,"hash",qR("getHash","setHash"))),gA(KR,"toJSON",(function(){return OA(this).serialize()}),{enumerable:!0}),gA(KR,"toString",(function(){return OA(this).serialize()}),{enumerable:!0}),LA){var zR=LA.createObjectURL,YR=LA.revokeObjectURL;zR&&gA(JR,"createObjectURL",_A(zR,LA)),YR&&gA(JR,"revokeObjectURL",_A(YR,LA))}bA(JR,"URL"),uA({global:!0,constructor:!0,forced:!pA,sham:!hA},{URL:JR});var XR=u;nn({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return XR(URL.prototype.toString,this)}});let QR=!0,ZR=!0;function $R(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function eC(e,t,i){if(!e.RTCPeerConnection)return;const r=e.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return n.apply(this,arguments);const o=e=>{const t=i(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,o),n.apply(this,[e,o])};const o=r.removeEventListener;r.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.apply(this,arguments);const r=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,r])},Object.defineProperty(r,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function tC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(QR=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function iC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ZR=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function rC(){if("object"==typeof window){if(QR)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function nC(e,t){ZR&&console.warn(e+" is deprecated, please use "+t+" instead.")}function oC(e){return"[object Object]"===Object.prototype.toString.call(e)}function sC(e){return oC(e)?Object.keys(e).reduce((function(t,i){const r=oC(e[i]),n=r?sC(e[i]):e[i],o=r&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[i]:n})}),{}):e}function aC(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?aC(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{aC(e,e.get(t),i)}))})))}function cC(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((i=>{i.type===r&&i.trackId===t.id&&aC(e,i,n)}))})),n}const lC=rC;function dC(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const r=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const r="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==r.ideal){t.optional=t.optional||[];let e={};"number"==typeof r.ideal?(e[n("min",i)]=r.ideal,t.optional.push(e),e={},e[n("max",i)]=r.ideal,t.optional.push(e)):(e[n("",i)]=r.ideal,t.optional.push(e))}void 0!==r.exact&&"number"!=typeof r.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",i)]=r.exact):["min","max"].forEach((e=>{void 0!==r[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,i)]=r[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=r(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{i=i.filter((e=>"videoinput"===e.kind));let s=i.find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=r(e.video),lC("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return lC("chrome: "+JSON.stringify(e)),n(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,r){n(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{r&&r(o(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function uC(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function hC(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 eC(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function pC(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 mC(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,r]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const r=function(e){i(o(n(e)))};return t.apply(this,[r,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(o(n(t)))},i])})).then(i,r)}}function _C(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=>cC(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}),eC(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>cC(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 fC(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 gC(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return fC(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}r.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const r=[].slice.call(arguments,1);if(1!==r.length||!r[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const n=this._streams[i.id];if(n)n.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const r=new e.MediaStream([t]);this._streams[i.id]=r,this._reverseStreams[r.id]=i,this.addStream(r)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=r[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function 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){eC(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var vC=Object.freeze({__proto__:null,shimMediaStream:uC,shimOnTrack:hC,shimGetSendersWithDtmf:pC,shimGetStats:mC,shimSenderReceiverGetStats:_C,shimAddTrackRemoveTrackWithNative:fC,shimAddTrackRemoveTrack:gC,shimPeerConnection:EC,fixNegotiationNeeded:TC,shimGetUserMedia:dC,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const r=i.video&&i.video.width,n=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},r&&(i.video.mandatory.maxWidth=r),n&&(i.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function yC(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){nC("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},r&&r.prototype.getSettings){const t=r.prototype.getSettings;r.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(r&&r.prototype.applyConstraints){const t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function SC(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function IC(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,o]=arguments;return r.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(zb){if("TypeError"!==zb.name)throw zb;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,o)}}function AC(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function RC(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}),eC(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){nC("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function bC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function kC(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 DC(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 wC(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 NC(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 OC=Object.freeze({__proto__:null,shimOnTrack:SC,shimPeerConnection:IC,shimSenderGetStats:AC,shimReceiverGetStats:RC,shimRemoveStream:CC,shimRTCDataChannel:bC,shimAddTransceiver:kC,shimGetParameters:DC,shimCreateOffer:wC,shimCreateAnswer:NC,shimGetUserMedia:yC,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function MC(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function PC(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function LC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,i){const r=n.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r};t.setLocalDescription=a,a=function(e,t,i){const r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.setRemoteDescription=a,a=function(e,t,i){const r=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.addIceCandidate=a}function xC(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(VC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function VC(e){return e&&void 0!==e.video?Object.assign({},e,{video:sC(e.video)}):e}function UC(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?(nC("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 FC(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 BC(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 HC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var WC=Object.freeze({__proto__:null,shimLocalStreamsAPI:MC,shimRemoteStreamsAPI:PC,shimCallbacksAPI:LC,shimGetUserMedia:xC,shimConstraints:VC,shimRTCIceServerUrls:UC,shimTrackEventTransceiver:FC,shimCreateOfferLegacy:BC,shimAudioContext:HC}),GC={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let r=8;r<t.length;r+=2)switch(t[r]){case"raddr":i.relatedAddress=t[r+1];break;case"rport":i.relatedPort=parseInt(t[r+1],10);break;case"tcptype":i.tcpType=t[r+1];break;case"ufrag":i.ufrag=t[r+1],i.usernameFragment=t[r+1];break;default:void 0===i[t[r]]&&(i[t[r]]=t[r+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const r=e.substring(e.indexOf(" ")+1).split(";");for(let n=0;n<r.length;n++)i=r[n].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const r=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+i+" "+r.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substring(t+1,r),i.value=e.substring(r+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const r=t.matchPrefix(e+i,"a=ice-ufrag:")[0],n=t.matchPrefix(e+i,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substring(12),password:n.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(" ");i.profile=r[2];for(let o=3;o<r.length;o++){const n=r[o],s=t.matchPrefix(e,"a=rtpmap:"+n+" ")[0];if(s){const r=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+n+" ");switch(r.parameters=o.length?t.parseFmtp(o[0]):{},r.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+n+" ").map(t.parseRtcpFb),i.codecs.push(r),r.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(r.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const n=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{n.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let r="";r+="m="+e+" ",r+=i.codecs.length>0?"9":"0",r+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{r+=t.writeRtpMap(e),r+=t.writeFmtp(e),r+=t.writeRtcpFb(e)}));let n=0;return i.codecs.forEach((e=>{e.maxptime>n&&(n=e.maxptime)})),n>0&&(r+="a=maxptime:"+n+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{r+=t.writeExtmap(e)})),r},t.parseRtpEncodingParameters=function(e){const i=[],r=t.parseRtpParameters(e),n=-1!==r.fecMechanisms.indexOf("RED"),o=-1!==r.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===a&&(c=l[0][1]),r.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),n&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=d}))),i},t.parseRtcpParameters=function(e){const i={},r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=n.length>0,i.compound=0===n.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const r=t.matchPrefix(e,"a=msid:");if(1===r.length)return i=r[0].substring(7).split(" "),{stream:i[0],track:i[1]};const n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return n.length>0?(i=n[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),r=t.matchPrefix(e,"a=max-message-size:");let n;r.length>0&&(n=parseInt(r[0].substring(19),10)),isNaN(n)&&(n=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:n};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,r){let n;const o=void 0!==i?i:2;n=e||t.generateSessionId();return"v=0\r\no="+(r||"thisisadapterortc")+" "+n+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const r=t.splitLines(e);for(let t=0;t<r.length;t++)switch(r[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(GC);var jC=GC.exports,JC=i(jC),KC=e({__proto__:null,default:JC},[jC]);function qC(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=JC.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,eC(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function zC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||eC(e,"icecandidate",(e=>{if(e.candidate){const t=JC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function YC(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=JC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=JC.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=JC.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?r=parseInt(n[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(r=2147483637),r}(arguments[0],e);let n;n=0===i&&0===r?Number.POSITIVE_INFINITY:0===i||0===r?Math.max(i,r):Math.min(i,r);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>n}),this._sctp=o}return i.apply(this,arguments)}}function XC(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},eC(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function QC(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 ZC(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 $C(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 eb(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 tb=Object.freeze({__proto__:null,shimRTCIceCandidate:qC,shimRTCIceCandidateRelayProtocol:zC,shimMaxMessageSize:YC,shimSendThrowTypeError:XC,shimConnectionState:QC,removeExtmapAllowMixed:ZC,shimAddIceCandidateNullOrEmpty:$C,shimParameterlessSetLocalDescription:eb});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=rC,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=$R(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=$R(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=$R(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:tb,extractVersion:$R,disableLog:tC,disableWarnings:iC,sdp:KC};switch(r.browser){case"chrome":if(!vC||!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=vC,$C(e,r),eb(e),dC(e,r),uC(e),EC(e,r),hC(e),gC(e,r),pC(e),mC(e),_C(e),TC(e,r),qC(e),zC(e),QC(e),YC(e,r),XC(e),ZC(e,r);break;case"firefox":if(!OC||!IC||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=OC,$C(e,r),eb(e),yC(e,r),IC(e,r),SC(e),CC(e),AC(e),RC(e),bC(e),kC(e),DC(e),wC(e),NC(e),qC(e),QC(e),YC(e,r),XC(e);break;case"safari":if(!WC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=WC,$C(e,r),eb(e),UC(e),BC(e),LC(e),MC(e),PC(e),FC(e),xC(e),HC(e),qC(e),zC(e),YC(e,r),XC(e),ZC(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var ib,rb=Object.create,nb=Object.defineProperty,ob=Object.defineProperties,sb=Object.getOwnPropertyDescriptor,ab=Object.getOwnPropertyDescriptors,cb=Object.getOwnPropertyNames,lb=Object.getOwnPropertySymbols,db=Object.getPrototypeOf,ub=Object.prototype.hasOwnProperty,hb=Object.prototype.propertyIsEnumerable,pb=Reflect.get,mb=Math.pow,_b=(e,t,i)=>t in e?nb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,fb=(e,t)=>{for(var i in t||(t={}))ub.call(t,i)&&_b(e,i,t[i]);if(lb)for(var i of lb(t))hb.call(t,i)&&_b(e,i,t[i]);return e},gb=(e,t)=>ob(e,ab(t)),Eb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Tb=(e,t)=>{for(var i in t)nb(e,i,{get:t[i],enumerable:!0})},vb=(e,t,i)=>(i=null!=e?rb(db(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of cb(t))!ub.call(e,n)&&n!==i&&nb(e,n,{get:()=>t[n],enumerable:!(r=sb(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:nb(i,"default",{value:e,enumerable:!0}),e)),yb=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?sb(t,i):t,s=e.length-1;s>=0;s--)(n=e[s])&&(o=(r?n(t,i,o):n(o))||o);return r&&o&&nb(t,i,o),o},Sb=(e,t,i)=>_b(e,"symbol"!=typeof t?t+"":t,i),Ib=(e,t,i)=>pb(db(e),i,t),Ab=(e,t,i)=>new Promise(((r,n)=>{var o=e=>{try{a(i.next(e))}catch(yM){n(yM)}},s=e=>{try{a(i.throw(e))}catch(yM){n(yM)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),Rb=Eb(((e,t)=>{var i=Object.prototype.hasOwnProperty,r="~";function n(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,i,n,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new o(i,n||e,s),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function c(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),c.prototype.eventNames=function(){var e,t,n=[];if(0===this._eventsCount)return n;for(t in e=this._events)i.call(e,t)&&n.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},c.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,o=i.length,s=new Array(o);n<o;n++)s[n]=i[n].fn;return s},c.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},c.prototype.emit=function(e,t,i,n,o,s){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,d=this._events[a],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,n),!0;case 5:return d.fn.call(d.context,t,i,n,o),!0;case 6:return d.fn.call(d.context,t,i,n,o,s),!0}for(l=1,c=new Array(u-1);l<u;l++)c[l-1]=arguments[l];d.fn.apply(d.context,c)}else{var h,p=d.length;for(l=0;l<p;l++)switch(d[l].once&&this.removeListener(e,d[l].fn,void 0,!0),u){case 1:d[l].fn.call(d[l].context);break;case 2:d[l].fn.call(d[l].context,t);break;case 3:d[l].fn.call(d[l].context,t,i);break;case 4:d[l].fn.call(d[l].context,t,i,n);break;default:if(!c)for(h=1,c=new Array(u-1);h<u;h++)c[h-1]=arguments[h];d[l].fn.apply(d[l].context,c)}}return!0},c.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},c.prototype.removeListener=function(e,t,i,n){var o=r?r+e:e;if(!this._events[o])return this;if(!t)return a(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!n||s.once)&&(!i||s.context===i)&&a(this,o);else{for(var c=0,l=[],d=s.length;c<d;c++)(s[c].fn!==t||n&&!s[c].once||i&&s[c].context!==i)&&l.push(s[c]);l.length?this._events[o]=1===l.length?l[0]:l:a(this,o)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new n,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,void 0!==t&&(t.exports=c)})),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")}))}))})),bb=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 o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=Cb(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),kb=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""}}))},o=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||s,n=t.innerOrder||a,c=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),Db=Eb((e=>{var t=bb(),i=kb(),r=Cb();e.grammar=r,e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),wb=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")}))}))})),Nb=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 o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=wb(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),Ob=Eb(((e,t)=>{var i=wb(),r=/%[sdv%]/g,n=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},o=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||s,n=t.innerOrder||a,c=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),Mb=Eb((e=>{var t=Nb(),i=Ob();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),Pb=vb(Rb()),Lb=((ib=Lb||{})[ib.INVALID_PARAMETER=4096]="INVALID_PARAMETER",ib[ib.INVALID_OPERATION=4097]="INVALID_OPERATION",ib[ib.NOT_SUPPORTED=4098]="NOT_SUPPORTED",ib[ib.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",ib[ib.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",ib[ib.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",ib[ib.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",ib[ib.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",ib[ib.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",ib[ib.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",ib[ib.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",ib[ib.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",ib[ib.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",ib[ib.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",ib[ib.CLIENT_BANNED=16448]="CLIENT_BANNED",ib[ib.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",ib[ib.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",ib[ib.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",ib[ib.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",ib[ib.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",ib[ib.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",ib[ib.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",ib[ib.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",ib[ib.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",ib[ib.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",ib[ib.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",ib[ib.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",ib[ib.API_CALL_ABORTED=16461]="API_CALL_ABORTED",ib[ib.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",ib[ib.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",ib[ib.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",ib[ib.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",ib[ib.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",ib[ib.UNKNOWN=65535]="UNKNOWN",ib),xb=Lb,Vb=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=xb.UNKNOWN,extraCode:n=0,constraint:o}=e,s="<".concat(function(e){for(let t in xb)if(xb[t]===e)return t;return"UNKNOWN"}(r)," 0x").concat(r.toString(16),">"),a="".concat(i).concat(o?" constraint: ".concat(o):"").concat(null!=i&&i.includes(s)?"":" ".concat(s));super(a),Sb(this,"code"),Sb(this,"extraCode"),Sb(this,"message"),Sb(this,"originMessage"),Sb(this,"name"),Sb(this,"constraint"),this.code=r,this.extraCode=n,this.name=t,this.message=a,this.constraint=o,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},Ub=Vb,Fb=((new Date).getTime(),0),Bb=function(){return(new Date).getTime()+Fb},Hb=function(){let e=new Date;return e.setTime(Bb()),e.toLocaleString()},Wb=function(e){let t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),"".concat(e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(t)},Gb={};Tb(Gb,{REPORT_TYPE:()=>Zw,buildSSOPackage:()=>$w,bytes2ms:()=>$D,calculateScaleResolutionDownNumber:()=>zw,convertObjectNumberToInt:()=>Gw,copyProperties:()=>ZD,deepClone:()=>Mw,deepCloneBasic:()=>Qw,deepMerge:()=>Ow,delay:()=>jw,fibonacci:()=>sw,formatedTime:()=>xw,getConstructorName:()=>vw,getContainerFromElement:()=>Lw,getEnv:()=>jD,getInternalVersion:()=>Cw,getLoggerUrl:()=>KD,getMediaStreamTrackInfo:()=>qw,getMuteStateFromFlag:()=>Dw,getNetworkType:()=>zD,getNumNetworkType:()=>QD,getReconnectionTimeout:()=>aw,getStringByteLength:()=>Fw,getTurnServer:()=>ww,getUint32Version:()=>Ww,getValueType:()=>cw,getViewListFromView:()=>Pw,glog:()=>rw,ipv4ToUint32:()=>Nw,isArray:()=>_w,isAudioWorkletSupported:()=>yw,isBoolean:()=>pw,isConstructor:()=>Tw,isEmpty:()=>kw,isFunction:()=>lw,isLangChinese:()=>nw,isMediaStreamTrack:()=>fw,isNumber:()=>hw,isObject:()=>mw,isOverseaSdkAppId:()=>JD,isPlainObject:()=>ow,isPortrait:()=>Bw,isPromise:()=>Ew,isRemoteTrack:()=>gw,isRotate90Or270:()=>Yw,isSetSinkIdSupported:()=>Sw,isString:()=>uw,isUndefined:()=>dw,loadImage:()=>Hw,loadVideo:()=>Xw,ms2bytes:()=>tw,ms2samples:()=>iw,normalizeUrl:()=>Kw,performanceNow:()=>Aw,promiseAny:()=>Iw,samples2ms:()=>ew,setNetworkType:()=>XD,stringify:()=>Vw,stringifyIncludeValue:()=>Uw,throttlePromise:()=>Jw});var jb={};Tb(jb,{AUDIO_MUTE_BIT:()=>wk,AUDIO_STAT_BIT:()=>Dk,AUX_STAT_BIT:()=>kk,AUX_STREAM_MSID:()=>Lk,BACKEND_ENV:()=>Ak,BASE_DOC_URL:()=>ok,BASE_HOST:()=>tk,CAPABILITIES_KEYS:()=>SD,CLASS_NAME:()=>pD,CLOUD_CONSOLE_URL:()=>nk,CROSS_ROOM_BIT:()=>Mk,DATA_FREEZE_TIMING:()=>sD,DOC_URL:()=>sk,DTLS_STATE_UNKNOWN:()=>Jk,ENV_NAME:()=>uk,EXCHANGE_SDP_TIMEOUT:()=>tD,IS_WORKER:()=>Xb,IS_WORKLET:()=>Qb,KIBANA_EVENT:()=>Zk,LOCAL_STREAM_PUBLISH_STATE:()=>oD,LOGGER_CMD_TYPE:()=>dk,LOGGER_DOMAIN:()=>ak,LOGGER_DOMAIN_OVERSEA:()=>ck,LOG_LEVEL:()=>hk,LOG_LEVEL_NAME:()=>ED,MAIN_STREAM_MSID:()=>Pk,MAX_RTT:()=>ID,MICROPHONE_COMMUNICATIONS:()=>gD,MICROPHONE_DEFAULT:()=>_D,MUTE_ALL_BIT:()=>Ok,NAME:()=>Sk,NETWORK_TYPE:()=>_k,NOT_SUPPORTED_H264:()=>nD,PAUSED_RETRY_COUNT:()=>mD,PEERCONNECTION_CONNECTING_TIMEOUT:()=>dD,PEER_CONNECTION_STATE:()=>Kk,PEER_LEAVE_REASON:()=>TD,RECOVER_CAPTURE_INTERVAL:()=>yD,REMOTE_STREAM_TYPE_AUX:()=>Vk,REMOTE_STREAM_TYPE_MAIN:()=>xk,RENDER_FREEZE_TIMING:()=>aD,SCHEDULE_DOMAIN:()=>uD,SCHEDULE_TIMEOUT:()=>hD,SDP_SEMANTICS_PLAN_B:()=>rD,SDP_SEMANTICS_UNIFIED_PLAN:()=>iD,SECOND_HOST:()=>ik,SIGNAL_PING_PONG_INTERVAL:()=>mk,SIGNAL_PING_TIMEOUT:()=>pk,SIGNAL_RECONNECTION_COUNT:()=>Qk,SMALL_STAT_BIT:()=>bk,SPEAKER_DEFAULT:()=>fD,STORAGE_EXPIRES_TIME:()=>fk,STREAM_TYPE_BIG:()=>cD,STREAM_TYPE_SMALL:()=>lD,SUBSCRIBE_SMALL_RETRY_COUNT:()=>vD,SYNC_USER_LIST_INTERVAL:()=>$k,Scene:()=>Rk,THIRD_HOST:()=>rk,TRANSPORT_DIRECTION:()=>Ik,TRTC_ERROR_ASSISTANCE:()=>lk,TRTC_QUALITY_BAD:()=>Wk,TRTC_QUALITY_DISCONNECTED:()=>jk,TRTC_QUALITY_EXCELLENT:()=>Fk,TRTC_QUALITY_GOOD:()=>Bk,TRTC_QUALITY_POOR:()=>Hk,TRTC_QUALITY_UNKNOWN:()=>Uk,TRTC_QUALITY_VERY_BAD:()=>Gk,UPDATE_OFFER_TIMEOUT:()=>eD,VIDEO_MUTE_BIT:()=>Nk,VIDEO_STAT_BIT:()=>Ck,audioProfileMap:()=>gk,defaultBigVideoProfile:()=>Tk,defaultSmallVideoProfile:()=>vk,getRetryCount:()=>Yk,getScriptDir:()=>Zb,innerVersion:()=>Jb,loggerProxy:()=>$b,screenProfileMap:()=>yk,setLoggerProxy:()=>ek,setRetryCount:()=>zk,setVersion:()=>qb,version:()=>Kb,videoProfileMap:()=>Ek});var Jb="4.15.00.1600",Kb="5.0.0";function qb(e){Kb=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));Jb="".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 zb,Yb,Xb="undefined"!=typeof importScripts,Qb="undefined"!=typeof registerProcessor,Zb=()=>{let e=Xb?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},$b="",ek=e=>$b=e,tk="web.sdk.qcloud.com",ik="web.sdk.tencent.cn",rk="web.sdk.cloud.tencent.cn",nk="https://console.cloud.tencent.com/trtc",ok="https://".concat(tk,"/trtc/webrtc/v5/doc"),sk="".concat(ok,"/zh-cn/"),ak="https://yun.tim.qq.com",ck="https://apisgp.my-imcloud.com",lk="trtc_error_assistance",dk={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},uk={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},hk=((Yb=hk||{})[Yb.TRACE=0]="TRACE",Yb[Yb.DEBUG=1]="DEBUG",Yb[Yb.INFO=2]="INFO",Yb[Yb.WARN=3]="WARN",Yb[Yb.ERROR=4]="ERROR",Yb[Yb.NONE=5]="NONE",Yb),pk=18e3,mk=2e3,_k={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},fk=6048e5,gk={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=Ek["480p_2"],vk=Ek["120p_2"],yk={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},Sk={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",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",RESIZE:"resize"},Ik={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Ak={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Rk=((zb=Rk||{}).LIVE="live",zb.RTC="rtc",zb),Ck=1,bk=2,kk=4,Dk=8,wk=64,Nk=16,Ok=112,Mk=128,Pk="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Lk="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",xk=Sk.MAIN,Vk=Sk.AUXILIARY,Uk=0,Fk=1,Bk=2,Hk=3,Wk=4,Gk=5,jk=6,Jk="unknown",Kk={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},qk=1/0;function zk(e){qk=e}function Yk(){return qk}var Xk,Qk=30,Zk={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"},$k=1e4,eD=1e4,tD=1e4,iD="unified-plan",rD="plan-b",nD=1028,oD=((Xk=oD||{})[Xk.UNPUBLISH=-1]="UNPUBLISH",Xk[Xk.PUBLISHING=0]="PUBLISHING",Xk[Xk.PUBLISHED=1]="PUBLISHED",Xk),sD=500,aD=1e3,cD=Sk.BIG,lD=Sk.SMALL,dD=1e4,uD={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"},hD=2e3,pD={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},mD=5,_D="default",fD=_D,gD="communications",ED=Object.keys(hk),TD=["normal leave","timeout leave","kick","role change"],vD=10,yD=2e3,SD=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],ID=1e4,AD=function(e,t,i,r){return new(i||(i=Promise))((function(n,o){function s(e){try{c(r.next(e))}catch(t){o(t)}}function a(e){try{c(r.throw(e))}catch(t){o(t)}}function c(e){e.done?n(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(s,a)}c((r=r.apply(e,t||[])).next())}))},RD=Symbol(32),CD=Symbol(16),bD=Symbol(8),kD=class{constructor(e){this.g=e,this.consumed=0,e&&(this.need=e.next().value)}setG(e){this.g=e,this.demand(e.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(e,t){return t&&this.consume(),this.need=e,this.flush()}read(e){return AD(this,void 0,void 0,(function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise(((t,i)=>{var r;this.reject=i,this.resolve=e=>{delete this.lastReadPromise,delete this.resolve,delete this.need,t(e)},this.demand(e,!0)||null===(r=this.pull)||void 0===r||r.call(this,e)}))}))}readU32(){return this.read(RD)}readU16(){return this.read(CD)}readU8(){return this.read(bD)}close(){var e;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),null===(e=this.reject)||void 0===e||e.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let e=null,t=this.buffer.subarray(this.consumed),i=0,r=e=>t.length<(i=e);if("number"==typeof this.need){if(r(this.need))return;e=t.subarray(0,i)}else if(this.need===RD){if(r(4))return;e=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===CD){if(r(2))return;e=t[0]<<8|t[1]}else if(this.need===bD){if(r(1))return;e=t[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(t.subarray(0,i)),e=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(t.subarray(0,i)),e=this.need}return this.consumed+=i,this.g?this.demand(this.g.next(e).value,!0):this.resolve&&this.resolve(e),e}write(e){if(e instanceof Uint8Array?this.malloc(e.length).set(e):"buffer"in e?this.malloc(e.byteLength).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):this.malloc(e.byteLength).set(new Uint8Array(e)),!this.g&&!this.resolve)return new Promise((e=>this.pull=e));this.flush()}writeU32(e){this.malloc(4).set([e>>24&255,e>>16&255,e>>8&255,255&e]),this.flush()}writeU16(e){this.malloc(2).set([e>>8&255,255&e]),this.flush()}writeU8(e){this.malloc(1)[0]=e,this.flush()}malloc(e){if(this.buffer){let t=this.buffer.length,i=t+e;if(i<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,i);else{let e=new Uint8Array(i);e.set(this.buffer),this.buffer=e}return this.buffer.subarray(t,i)}return this.buffer=new Uint8Array(e),this.buffer}};kD.U32=RD,kD.U16=CD,kD.U8=bD;var DD=128;function wD(e){let t=new kD;for(;e>=128;)t.malloc(1)[0]=255&e|DD,e>>>=7;return t.malloc(1)[0]=255&e,t.buffer||new Uint8Array(0)}function ND(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=new kD,r=t<<3;switch(typeof e){case"boolean":let n=i.malloc(2);n[0]=r,n[1]=e?1:0;break;case"number":i.malloc(1)[0]=r,i.write(wD(e));break;case"string":i.malloc(1)[0]=2|r;let o=(new TextEncoder).encode(e);i.write(wD(o.length));let s=i.malloc(o.length);for(let e=0;e<o.length;e++)s[e]=o[e];break;case"object":let a=new kD;if(Array.isArray(e))for(let t=0;t<e.length;t++){let i=ND(e[t],t+1);i&&a.write(i)}else{let t=1;for(let i in e){let r=ND(e[i],t++);r&&a.write(r)}}0===t?a.buffer&&i.write(a.buffer):(i.malloc(1)[0]=2|r,a.buffer&&(i.write(wD(a.buffer.length)),i.write(a.buffer)))}return i.buffer||new Uint8Array(0)}var OD=class{constructor(){Sb(this,"buffer"),this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(e){this.buffer.push(e>>>24&255),this.buffer.push(e>>>16&255),this.buffer.push(e>>>8&255),this.buffer.push(255&e)}writeInt16(e){this.buffer.push(e>>>8&255),this.buffer.push(255&e)}writeByte(e){this.buffer.push(255&e)}writeBytes(e){for(let t=0;t<e.length;t++)this.buffer.push(e[t])}};function MD(e,t,i){e[i]=t>>>24&255,e[i+1]=t>>>16&255,e[i+2]=t>>>8&255,e[i+3]=255&t}function PD(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function LD(e,t){return e[t]}function xD(e,t,i){return(new TextDecoder).decode(function(e,t,i){return e.slice(t,t+i)}(e,t,i))}var VD=0,UD=2654435769,FD=16,BD=2,HD=7;function WD(e,t){let i=new OD,r=function(e,t,i){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"AVQualityReportSvc.C2S";return{version:arguments.length>4&&void 0!==arguments[4]?arguments[4]:2e3,encryption:arguments.length>5&&void 0!==arguments[5]?arguments[5]:2,d2:"",d2Len:0,uinType:arguments.length>6&&void 0!==arguments[6]?arguments[6]:30,uin:"",uinLen:0,reqHead:{seqNumber:i,appId:e,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:r,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:t}}(t,e,VD);VD=VD+1&2147483647,i.writeInt32(0),i.writeInt32(r.version),i.writeByte(r.encryption);let n=(new TextEncoder).encode(r.d2);i.writeInt32(n.length+4),n&&i.writeBytes(n),i.writeByte(r.uinType);let o=(new TextEncoder).encode(r.uin);i.writeInt32(o.length+4),o.length&&i.writeBytes(o);let s=new OD;s.writeInt32(0),s.writeInt32(r.reqHead.seqNumber),s.writeInt32(r.reqHead.appId),s.writeByte(r.reqHead.appId>>>24&255),s.writeByte(r.reqHead.appId>>>16&255),s.writeByte(r.reqHead.appId>>>8&255),s.writeByte(255&r.reqHead.appId);for(let E=4;E<16;E++)s.writeByte(0);let a=(new TextEncoder).encode(r.reqHead.a2);s.writeInt32(a.length+4),a.length&&s.writeBytes(a);let c=(new TextEncoder).encode(r.reqHead.serviceCmd);s.writeInt32(c.length+4),c.length&&s.writeBytes(c);let l=(new TextEncoder).encode(r.reqHead.cookie);s.writeInt32(l.length+4),l.length&&s.writeBytes(l);let d=(new TextEncoder).encode(r.reqHead.imei);s.writeInt32(d.length+4),d.length&&s.writeBytes(d);let u=(new TextEncoder).encode(r.reqHead.ksid);s.writeInt32(u.length+4),u.length&&s.writeBytes(u);let h=(new TextEncoder).encode(r.reqHead.clientVersionInfo);s.writeInt16(h.length+2),h.length&&s.writeBytes(h);let p=s.length;s.data[0]=p>>>24&255,s.data[1]=p>>>16&255,s.data[2]=p>>>8&255,s.data[3]=255&p,uw(e)&&(e=(new TextEncoder).encode(e)),s.writeInt32(e.length+4),e.length&&s.writeBytes(e);let m=new Uint8Array(s.data),_=null;1===r.encryption?_=(new TextEncoder).encode(r.uin):2===r.encryption&&(_=new Uint8Array(16)),_&&(m=function(e,t){let i=e.length,r=(i+1+BD+HD)%8;r&&(r=8-r);let n=i+1+BD+HD+r,o=new Uint8Array(n),s=0,a=new Uint8Array(8),c=new Uint8Array(8),l=new Uint8Array(8),d=0;a[0]=248&Math.floor(256*Math.random())|r,d=1;for(let h=0;h<r;h++)a[d]=255&Math.floor(256*Math.random()),d+=1;for(let h=0;h<BD;)if(d<8&&(a[d]=255&Math.floor(256*Math.random()),d+=1,h+=1),8===d){GD(a,t,c,l,o,s),s+=8,d=0;for(let e=0;e<8;e++)l[e]=o[s-8+e]}let u=0;for(;u<i;)if(d<8&&(a[d]=e[u],d+=1,u+=1),8===d){GD(a,t,c,l,o,s),s+=8,d=0;for(let e=0;e<8;e++)l[e]=o[s-8+e]}for(let h=0;h<HD;)if(d<8&&(a[d]=0,d+=1,h+=1),8===d){GD(a,t,c,l,o,s),s+=8,d=0;for(let e=0;e<8;e++)l[e]=o[s-8+e]}return o}(m,_)),i.writeBytes(m);let f=new Uint8Array(i.data),g=f.length;return f[0]=g>>>24&255,f[1]=g>>>16&255,f[2]=g>>>8&255,f[3]=255&g,f}function GD(e,t,i,r,n,o){for(let s=0;s<8;s++)e[s]^=r[s];!function(e,t,i,r){let n=PD(e,0),o=PD(e,4),s=[];for(let c=0;c<4;c++)s[c]=PD(t,4*c);let a=0;for(let c=0;c<FD;c++)a+=UD,a>>>=0,n+=(o<<4)+s[0]^o+a^(o>>>5)+s[1],n>>>=0,o+=(n<<4)+s[2]^n+a^(n>>>5)+s[3],o>>>=0;MD(i,n,r),MD(i,o,r+4)}(e,t,n,o);for(let s=0;s<8;s++)n[o+s]^=i[s];for(let s=0;s<8;s++)i[s]=e[s]}var jD=function(){return new URLSearchParams(location.search).get("trtc_env")||""},JD=e=>Number(e)<14e8,KD=function(e,t){let i;i=$b||(JD(e)?ck:ak);let r=Math.floor(Math.random()*mb(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},qD="unknown";function zD(){if("unknown"!==qD)return qD;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&&(qD=YD(r,n)),qD}function YD(e,t){if(_k[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function XD(e){qD=YD(e)}function QD(){return _k[zD()]}function ZD(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 $D(e){return ew(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function ew(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function tw(e){return 4*iw(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function iw(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var rw="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},nw=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},ow=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 sw(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:sw(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function aw(e){return e>8?3e4:1e3*sw(e)}function cw(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var lw=e=>"function"==typeof e,dw=e=>void 0===e,uw=e=>"string"==typeof e,hw=e=>"number"==typeof e,pw=e=>"boolean"==typeof e,mw=e=>"object"===cw(e),_w=e=>"array"===cw(e),fw=e=>cw(e)==="MediaStreamTrack".toLowerCase(),gw=e=>e.isRemote,Ew=e=>"promise"===cw(e),Tw=e=>lw(e)&&e.prototype.constructor===e,vw=e=>Tw(e)?e.prototype.constructor.name:"",yw="undefined"!=typeof AudioWorkletNode,Sw="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype;function Iw(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 Aw(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var Rw=e=>+e<10?"0".concat(e):e,Cw=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=Rw(i[1])+Rw(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},bw=Object.prototype.hasOwnProperty;function kw(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(ow(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(bw.call(e,t))return!1;return!0}return!1}function Dw(e,t){return{userId:t,hasAudio:!!(e&Dk),hasVideo:!!(e&Ck),hasAuxiliary:!!(e&kk),hasSmall:!!(e&bk),audioMuted:!!(e&wk),videoMuted:!!(e&Nk),audioAvailable:!(!(e&Dk)||e&wk),videoAvailable:!(!(e&Ck)||e&Nk)}}function ww(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!dw(e.username)&&!dw(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",dw(e.credentialType)||(t.credentialType=e.credentialType)),t}function Nw(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!uw(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 Ow=function(e,t,i,r){if(!mw(e)||!mw(t))return 0;let n,o=0,s=Object.keys(t);for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(dw(t[n])||i&&i.includes(n)))if(mw(e[n])&&mw(t[n]))o+=Ow(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=Mw(t[n]),o+=1)}return o};function Mw(e){if(_w(e)){let t=[];return e.forEach(((e,i)=>{t[i]=Mw(e)})),t}if(mw(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=Mw(e[i])})),t}return e}var Pw=e=>{let t=[];if(_w(e))t=[...e];else if(uw(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},Lw=e=>uw(e)?document.getElementById(e):e,xw=()=>(e=>{let t=e=>e<10?"0".concat(e):"".concat(e),i=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),o=t(e.getHours()),s=t(e.getMinutes()),a=t(e.getSeconds());return"".concat(i,"/").concat(r,"/").concat(n," ").concat(o,":").concat(s,":").concat(a)})(new Date);function Vw(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(_w(e))return"[".concat(e.map((e=>Vw(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!ow(e)||!_w(i)&&!_w(r))return JSON.stringify(e);let t={},n=new Set(i),o=new Set(r);return Object.keys(e).forEach((s=>{(0===o.size&&n.has(s)||0===n.size&&!o.has(s))&&(t[s]=ow(e[s])||_w(e[s])?JSON.parse(Vw(e[s],{keysToExclude:r,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(Xk){return"{}"}}function Uw(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)})),Vw(e,{keysToInclude:i})}function Fw(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Bw=()=>{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},Hw=e=>Ab(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(uw(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 Ub({code:xb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}}))})),Ww=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},Gw=e=>(Object.keys(e).forEach((t=>{hw(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(ow(e[t])||_w(e[t]))&&Gw(e[t])})),e);function jw(e,t){return new Promise((i=>{let r=setTimeout(i,e);t&&t(r)}))}function Jw(e,t){let i=null;return function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return i||(i=e.apply(t||this,n),i.finally((()=>i=null)),i)}}function Kw(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function qw(e){var t;try{let{width:i,height:r,frameRate:n,sampleRate:o,sampleSize:s,channelCount:a}=null==(t=e.getSettings)?void 0:t.call(e),c=e.kind===Sk.AUDIO?"".concat(o,"x").concat(s,"@").concat(a):"".concat(i,"x").concat(r,"@").concat(n),l=e.stats?" stats: ".concat(JSON.stringify(e.stats).replaceAll('"',"")):"";return"".concat(e.id," ").concat(e.readyState," muted:").concat(e.muted," ").concat(e.kind," ").concat(e.label," ").concat(c).concat(l)}catch(zb){return""}}function zw(e,t){return e.width*e.height==t.width*t.height?1:Bw()&&t.width>t.height&&e.height>t.width?Math.max(e.width/t.height,e.height/t.width,1):Math.max(e.width/t.width,e.height/t.height,1)}function Yw(e){return 90===e||270===e}function Xw(e){return Ab(this,null,(function*(){return new Promise(((t,i)=>{let r=document.createElement("video");r.crossOrigin="anonymous",r.src=e,r.muted=!0,r.loop=!0,r.playsInline=!0,r.play().then((()=>t(r))),r.onerror=()=>{i(r.error)}}))}))}function Qw(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new WeakMap;if("object"!=typeof e||null===e)return e;if(t.has(e))return t.get(e);if(Array.isArray(e)){let i=[];return t.set(e,i),e.forEach(((e,r)=>{i[r]=Qw(e,t)})),i}if("[object Object]"===Object.prototype.toString.call(e)){let i={};return t.set(e,i),Reflect.ownKeys(e).forEach((r=>{i[r]=Qw(e[r],t)})),i}return e}var Zw=(e=>(e[e.END_REPORT=2001]="END_REPORT",e[e.LOG=2002]="LOG",e[e.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",e))(Zw||{});function $w(e,t,i,r){try{let n=function(e,t,i,r){let n={data:e,random:Math.floor(2147483648*Math.random()),sdkAppId:i};return dw(r)||(n=gb(fb({},n),{gzip:+r})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:t,bytes_report_data:JSON.stringify(n)}}}(e,t,i,r);return WD(ND(n),i)}catch(AM){return JSON.stringify(e)}}function eN(e){let t=function(e){try{let t={},i=0;t.totalLength=PD(e,i),i+=4,t.version=PD(e,i),i+=4,t.encryption=LD(e,i),i+=1,t.uinType=LD(e,i),i+=1,t.uinLength=PD(e,i),i+=4,t.uin=t.uinLength>4?xD(e,i,t.uinLength-4):"",i+=t.uinLength-4;let r=e.slice(i);if(2===t.encryption){e=function(e,t){let i=0,r=new Uint8Array(8).fill(0),n=new Uint8Array(e.slice(0,8)),o=tN(n,t),s=7&o[0],a=e.length-1-s-BD-HD,c=new Uint8Array(a),l=0,d=r,u=e.slice(0,8);i=8;let h=1;h+=s;for(let m=1;m<=BD;)if(h<8)h++,m++;else if(8===h){let r=iN(e,i,d,u,o,t);d=r.ivPreCrypt,u=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,h=0}let p=a;for(;p>0;)if(h<8)c[l++]=o[h]^d[h],h++,p--;else if(8===h){let r=iN(e,i,d,u,o,t);d=r.ivPreCrypt,u=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,h=0}for(let m=1;m<=HD;)if(h<8)o[h],d[h],h++,m++;else if(8===h){if(i>=e.length)break;let r=iN(e,i,d,u,o,t);if(!r.success)break;d=r.ivPreCrypt,u=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,h=0}return c}(r,new Uint8Array(16).fill(0)),t.decrypted=!0,i=0}else e=r,i=0;return t.rspHeadLength=PD(e,i),i+=4,t.seqNo=PD(e,i),i+=4,t.retCode=PD(e,i),i+=4,t.retStrLength=PD(e,i),i+=4,t.retStr=t.retStrLength?xD(e,i,t.retStrLength-4):"",i+=t.retStrLength-4,t.serviceCmdLength=PD(e,i),i+=4,t.serviceCmd=t.serviceCmdLength?xD(e,i,t.serviceCmdLength-4):"",i+=t.serviceCmdLength-4,t.cookieLength=PD(e,i),i+=4,t.cookie=t.cookieLength?xD(e,i,t.cookieLength-4):"",i+=t.cookieLength-4,t.flag=PD(e,i),i+=4,t.busiBuffLength=PD(e,i),i+=4,t.busiBuff=t.busiBuffLength?xD(e,i,t.busiBuffLength-4):"",i+=t.busiBuffLength-4,t}catch(t){}}(e);return null==t?void 0:t.busiBuff}function tN(e,t){let i=e[0]<<24|e[1]<<16|e[2]<<8|e[3],r=e[4]<<24|e[5]<<16|e[6]<<8|e[7];i>>>=0,r>>>=0;let n=UD*FD>>>0;for(let o=0;o<FD;o++)r-=(i<<4)+t[2]^i+n^(i>>>5)+t[3],r>>>=0,i-=(r<<4)+t[0]^r+n^(r>>>5)+t[1],i>>>=0,n-=UD,n>>>=0;return new Uint8Array([i>>>24&255,i>>>16&255,i>>>8&255,255&i,r>>>24&255,r>>>16&255,r>>>8&255,255&r])}function iN(e,t,i,r,n,o){if(t+8>e.length)return{success:!1};let s=new Uint8Array(r),a=e.slice(t,t+8),c=new Uint8Array(8);for(let l=0;l<8;l++)c[l]=n[l]^a[l];return{success:!0,ivPreCrypt:s,ivCurCrypt:a,debiBuf:tN(c,o),bufPos:t+8}}var rN="undefined"!=typeof TextDecoder?new TextDecoder:void 0;function nN(e){let{url:t,body:i,method:r="POST",timeout:n,priority:o}=e;return new Promise(((e,s)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:o}).then((e=>e.clone().json().then((e=>({data:e})),(()=>e.arrayBuffer().then((e=>({data:eN(new Uint8Array(e))||(rN?rN.decode(e):e)}))))))).then(e,s);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(bM){e({data:a.response})}else s({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=n||5e3,a.open(r,t,!0),a.send(i)}))}function oN(e){return Ab(this,null,(function*(){let t=Aw(),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 _M.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(Aw()-t,"ms")),r}catch(Xk){return i}}))}var sN=Object.prototype.hasOwnProperty,aN=e=>"function"==typeof e,cN=e=>void 0===e,lN=e=>"boolean"==typeof e,dN=e=>e.isRemote,uN=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)};var hN=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:n,onRetryFailed:o,onRetrySuccess:s,context:a}=e;return function(){for(var e=arguments.length,c=new Array(e),l=0;l<e;l++)c[l]=arguments[l];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,_=(e,i)=>Ab(this,null,(function*(){let l=a||this;try{let i=yield t.apply(l,c);h>0&&s&&s.call(this,h),h=0,e(i)}catch(wP){let s=()=>{clearTimeout(p),h=0,m=2,i(wP)},a=()=>{2!==m&&h<(aN(d)?d():d)?(h++,m=1,aN(n)&&n.call(this,h,s),p=window.setTimeout((()=>{p=-1,_(e,i)}),aN(u)?u(h):u)):(s(),aN(o)&&o.call(this,wP))};aN(r)?r.call(this,{error:wP,retry:a,reject:i,retryFuncArgs:c,retriedCount:h}):a()}}));return new Promise(_)}},pN=class{constructor(e){Sb(this,"userId"),Sb(this,"remoteUserId"),Sb(this,"id"),Sb(this,"sdkAppId"),Sb(this,"type"),Sb(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!lN(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):"","]")),_M.log(e,t,cN(this.userId)||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(uN(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(sN.call(e,t))return!1;return!0}return!1}(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:()=>NO,CHROME_VERSION:()=>OO,EDGE_VERSION:()=>PN,EDG_MAJOR_VERSION:()=>VN,EDG_VERSION:()=>xN,FIREFOX_MAJOR_VERSION:()=>ON,FIREFOX_VERSION:()=>NN,HUAWEI_VERSION:()=>EO,IE_VERSION:()=>zN,IOS_MAIN_VERSION:()=>BO,IOS_VERSION:()=>VO,IPADQQB_VERSION:()=>oO,IS_ANDROID:()=>CN,IS_ANDROID_WEBVIEW:()=>xO,IS_ANY_SAFARI:()=>PO,IS_CHROME:()=>DO,IS_CHROME_OS:()=>lO,IS_CHROMIUM_BASE:()=>kO,IS_DESKTOP_IOS_CHROME:()=>JO,IS_EDG:()=>LN,IS_EDGE:()=>MN,IS_ELECTRON:()=>hO,IS_FIREFOX:()=>wN,IS_HEADLESS_CHROME:()=>wO,IS_HONOR:()=>gO,IS_HUAWEI:()=>fO,IS_HUAWEIBROWSER:()=>_O,IS_IE:()=>qN,IS_IE8:()=>KN,IS_IOS:()=>RN,IS_IOS_13_OR_14:()=>GO,IS_IOS_15_1:()=>WO,IS_IOS_CHROME:()=>jO,IS_IPAD:()=>yN,IS_IPADQQB:()=>nO,IS_IPAD_PRO:()=>SN,IS_IPHONE:()=>IN,IS_IPOD:()=>AN,IS_LINUX:()=>cO,IS_LOCAL:()=>KO,IS_MAC:()=>aO,IS_MACQQB:()=>iO,IS_MIBROWSER:()=>pO,IS_MQQB:()=>ZN,IS_NATIVE_ANDROID:()=>DN,IS_OLD_ANDROID:()=>kN,IS_OPENHARMONY:()=>RO,IS_OPPOBROWSER:()=>yO,IS_SAFARI:()=>MO,IS_SAFARI_15_1:()=>HO,IS_SAMSUNGBROWSER:()=>TO,IS_SOGOU:()=>BN,IS_SOGOUM:()=>UN,IS_TBS:()=>WN,IS_UCBROWSER:()=>uO,IS_VIVOBROWSER:()=>IO,IS_WECHAT:()=>YN,IS_WIN:()=>sO,IS_WQQB:()=>eO,IS_WX:()=>dO,IS_X5MQQB:()=>QN,IS_XWEB:()=>jN,MACQQB_VERSION:()=>rO,MI_VERSION:()=>mO,MQQB_VERSION:()=>$N,OPENHARMONY_VERSION:()=>CO,OPPO_VERSION:()=>SO,SAFARI_VERSION:()=>LO,SAMSUNG_VERSION:()=>vO,SOGOUM_VERSION:()=>FN,SOGOU_VERSION:()=>HN,TBS_VERSION:()=>GN,UA_DATA_STRING:()=>ZO,USER_AGENT:()=>_N,VIVO_VERSION:()=>AO,WECHAT_VERSION:()=>XN,WQQB_VERSION:()=>tO,XWEB_VERSION:()=>JN,browserInfo:()=>zO,getBrowserCoreNumber:()=>oM,getBrowserInfo:()=>YO,getChromeMajorVersion:()=>bO,getDeviceModel:()=>tM,getGPUInfo:()=>eM,getOSName:()=>rM,getOSNumber:()=>nM,getOSString:()=>sM,getOSType:()=>cM,getTerminalType:()=>aM,getUserAgentData:()=>$O,isLocalStorageEnabled:()=>qO,isMobile:()=>QO,isVersionLargerThan:()=>FO,isVersionSmallerThan:()=>UO});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,AN=fN("iPod"),RN=IN||yN||AN||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,wN=fN("Firefox"),NN=gN("Firefox"),ON=EN("Firefox"),MN=fN("Edge"),PN=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"),WN=fN("TBS"),GN=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=!WN&&fN("MQQBrowser")&&fN("COVC"),ZN=!WN&&fN("MQQBrowser")&&!fN("COVC"),$N=ZN||QN?gN("MQQBrowser"):"",eO=!WN&&fN(" QQBrowser"),tO=gN(" QQBrowser"),iO=!WN&&fN("QQBrowserLite"),rO=gN("QQBrowserLite"),nO=!WN&&fN("MQBHD"),oO=gN("MQBHD"),sO=fN("Windows"),aO=!RN&&fN("MAC OS X"),cO=!CN&&fN("Linux"),lO=fN("CrOS"),dO=fN("MicroMessenger"),uO=fN("UCBrowser"),hO=fN("Electron"),pO=fN("MiuiBrowser"),mO=gN("MiuiBrowser"),_O=fN("HuaweiBrowser"),fO=fN("Huawei")||fN("HUAWEI"),gO=fN("Honor")||fN("HONOR"),EO=gN("HuaweiBrowser"),TO=fN("SamsungBrowser"),vO=gN("SamsungBrowser"),yO=fN("HeyTapBrowser"),SO=gN("HeyTapBrowser"),IO=fN("VivoBrowser"),AO=gN("VivoBrowser"),RO=fN("OpenHarmony"),CO=gN("OpenHarmony"),bO=()=>EN("Chrome"),kO=fN("Chrome"),DO=!MN&&!BN&&!UN&&!WN&&!jN&&!LN&&!eO&&!pO&&!_O&&!TO&&!yO&&!IO&&kO,wO=fN("HeadlessChrome"),NO=bO(),OO=gN("Chrome"),MO=!kO&&!ZN&&!QN&&!iO&&!nO&&fN("Safari"),PO=MO||RN,LO=gN("Version"),xO=/Android.*(wv|.0.0.0)/.test(_N),VO=(()=>{if(SN)return LO;if(RN){let e=_N.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})();function UO(e,t){let i=e.split(".").map((e=>Number(e))),r=t.split(".").map((e=>Number(e)));for(let n=0;n<Math.max(i.length,r.length);n++){let e=i[n]||0,t=r[n]||0;if(e<t)return!0;if(e>t)return!1}return!1}function FO(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=e.split(".").map((e=>Number(e))),n=t.split(".").map((e=>Number(e)));for(let o=0;o<Math.max(r.length,n.length);o++){let e=r[o]||0,t=n[o]||0;if(e>t)return!0;if(e<t)return!1}return i}var BO=Number(VO.split(".")[0]),HO="15.1"===LO,WO="15.1"===VO,GO=(()=>{let e=Number(VO.split(".")[0]);return 14===e||13===e})(),jO=fN("CriOS"),JO=jO&&"11.1.1"===LO,KO="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),qO=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(IM){e=!1}return e}})(),zO=YO();function YO(){let e=new Map([[wN,["Firefox",NN]],[LN,["Edg",xN]],[DO,["Chrome",OO]],[MO,["Safari",LO]],[WN,["TBS",GN]],[jN,["XWEB",JN]],[YN&&IN,["WeChat",XN]],[eO,["QQ(Win)",tO]],[ZN,["QQ(Mobile)",$N]],[QN,["QQ(Mobile X5)",$N]],[iO,["QQ(Mac)",rO]],[nO,["QQ(iPad)",oO]],[pO,["MI",mO]],[_O,["HW",EO]],[TO,["Samsung",vO]],[yO,["OPPO",SO]],[IO,["VIVO",AO]],[MN,["EDGE",PN]],[UN,["SogouMobile",FN]],[BN,["Sogou",HN]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var XO=null;function QO(){return XO&&"boolean"==typeof XO.mobile?XO.mobile:CN||RN||IN||yN||RO}var ZO="";function $O(){return Ab(this,null,(function*(){if(XO)return XO;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(XO=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!ZO&&(ZO="UAData: ".concat(XO.platform,"/").concat(XO.platformVersion),XO.architecture&&XO.bitness&&(ZO+=" ".concat(XO.architecture,"/").concat(XO.bitness)),XO.mobile&&(ZO+=" mobile"),XO.model&&(ZO+=" model: ".concat(XO.model.replace(/\s+/g,"/"))),XO.fullVersionList&&(ZO+=" ".concat(XO.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),XO}catch(vJ){return null}}))}function eM(){try{let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"";let i=t.getExtension("WEBGL_debug_renderer_info");if(i){let e=t.getParameter(i.UNMASKED_VENDOR_WEBGL),r=t.getParameter(i.UNMASKED_RENDERER_WEBGL);return"".concat(e," ").concat(r)}return""}catch(vJ){return""}}function tM(){return(null==XO?void 0:XO.model)||""}var iM=new Map([[CN,"Android"],[RN,"iOS"],[sO,"Windows"],[aO,"MacOS"],[cO,"Linux"],[lO,"ChromeOS"]]),rM=function(){return iM.get(!0)?iM.get(!0):XO?XO.platform:"unknown"};function nM(){return sO?1:CN?2:aO?3:RN?4:cO?5:lO?6:RO?7:0}function oM(){return kO?1:MO?2:wN?3:0}var sM=()=>{let e=rM();return e+="/".concat(zO.name,"/").concat(MO?zO.version:zO.version.split(".")[0]),null!=XO&&XO.platformVersion&&(e+="/".concat(XO.platformVersion)),null!=XO&&XO.architecture&&(e+="/".concat(XO.architecture)),e};function aM(){return CN?4:IN?2:yN?3:aO?12:sO?5:cO?13:RO?22:1}function cM(){return CN?"Android":IN?"iPhone":yN?"iPad":aO?"Mac":sO?"Windows":cO?"Linux":"unknown"}var lM,dM=new(vb(Rb(),1).default),uM=((lM=uM||{}).ROOM_DESTROY="1",lM.JOIN_START="21",lM.JOIN_SCHEDULE_SUCCESS="22",lM.JOIN_SIGNAL_CONNECTION_START="23",lM.JOIN_SIGNAL_CONNECTION_END="24",lM.JOIN_SEND_CMD="25",lM.JOIN_RECEIVED_CMD_RES="26",lM.JOIN_SUCCESS="27",lM.JOIN_FAILED="28",lM.LEAVE_START="51",lM.LEAVE_SEND_CMD="52",lM.LEAVE_SUCCESS="53",lM.PUBLISH_START="61",lM.SEND_FIRST_VIDEO_FRAME="62",lM.PUBLISH_FAILED="63",lM.SUBSCRIBE_START="81",lM.SUBSCRIBE_SUCCESS="82",lM.SUBSCRIBE_FAILED="84",lM.UNSUBSCRIBE_SUCCESS="83",lM.LOCAL_TRACK_CAPTURE_START="101",lM.LOCAL_TRACK_CAPTURE_SUCCESS="102",lM.LOCAL_TRACK_CAPTURE_FAILED="103",lM.LOCAL_TRACK_PUBLISHED="104",lM.LOCAL_TRACK_UNPUBLISHED="105",lM.LOCAL_TRACK_REPLACED="106",lM.SWITCH_DEVICE_SUCCESS="107",lM.TRACK_MUTED="108",lM.TRACK_UNMUTED="109",lM.REMOTE_TRACK_SUBSCRIBED="110",lM.REMOTE_TRACK_UNSUBSCRIBED="111",lM.LOCAL_TRACK_RECAPTURE="112",lM.LOCAL_AUDIO_STARTED="113",lM.LOCAL_AUDIO_STOPPED="114",lM.REMOTE_AUDIO_STARTED="115",lM.REMOTE_AUDIO_STOPPED="116",lM.PLAY_TRACK_START="151",lM.PLAYER_STATE_CHANGED="152",lM.VIDEO_LOADED_DATA="153",lM.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",lM.AUDIO_CONTEXT_LONG_SUSPENDED="155",lM.SIGNAL_CONNECTION_STATE_CHANGED="201",lM.PEER_CONNECTION_STATE_CHANGED="202",lM.SINGLE_CONNECTION_STAT="203",lM.SPC_RECONNECTED="204",lM.HEARTBEAT_REPORT="251",lM.RECEIVED_PUBLISHED_USER_LIST="252",lM.REMOTE_PUBLISH_STATE_CHANGED="253",lM.AUDIO_LEVEL_INTERVAL="260",lM.NETWORK_QUALITY="261",lM.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",lM.QUALITY_LIMITATION_CHANGED="263",lM.LOG="264",lM.AUDIO_PROCESSOR_DEBUG="265",lM.SSO_SWITCH="266",lM.SWITCH_ROOM_START="401",lM.SWITCH_ROOM_SUCCESS="407",lM.SWITCH_ROOM_FAILED="408",lM),hM=uM,pM=new class{constructor(){Sb(this,"enable",!1),Sb(this,"ssoFailCount",0),dM.on("22",(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.sso&&dM.emit("266",{enable:!0})})),dM.on("266",(e=>{let{enable:t}=e;this.enable=t}))}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&dM.emit("266",{enable:!1})}},mM=class e{constructor(){Sb(this,"_isEnableUploadLog",!0),Sb(this,"_localJoinedUser",new Map),Sb(this,"_queue",[]),Sb(this,"_timeoutId",-1),Sb(this,"_logLevel",1),Sb(this,"_logLevelToUpload",2),!Xb&&!Qb&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){dM.on(hM.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.logLevelToUpload&&hk[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),dM.on(hM.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),dM.once(hM.JOIN_FAILED,(()=>{this.startUpload()})),dM.on(hM.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(uw(i.userId)&&hw(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 Ab(this,null,(function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;e<t.length;e++){let{userId:i,sdkAppId:r,logs:n}=t[e],o={timestamp:Hb(),sdkAppId:String(r),userId:i,version:Kb,log:n.map((e=>e.log)).join("\n")},s=JSON.stringify(o),a=pM.enable?$w(o,2002,r):s;yield this.uploadLogWithRetry(a,r,a instanceof Uint8Array,s),n.forEach((e=>e.uploaded=!0))}}catch(AM){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t,i,r){return hN({retryFunction:()=>nN({url:KD(t,dk.LOG),body:e,timeout:5e3,priority:"low"}).then((e=>{i&&"ok"!==e.data&&(pM.handleUploadFailed(),this.uploadLogWithRetry(r,t,!1,r))})),settings:{retries:3,timeout:2e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;return t.setTime(Bb()),"[".concat(Wb(t),"] <").concat(hk[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){dw(hk[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(uw(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(zb){return""}}log(t,i){let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0;var s;i.unshift(this.getPrefix(t));let a={log:i.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:t,userId:n,sdkAppId:o,forAllJoinedClients:r};if(dM.emit(hM.LOG,{log:a}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(a),t<this._logLevel)return;let c=(null==(s=hk[t])?void 0:s.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;hk[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};Sb(mM,"PRINT_LOG_TAG",!(RN||CN||wO));var _M=new mM,fM=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)}))},gM=new class{constructor(){Sb(this,"_prefix","TRTC"),Sb(this,"_queue",new Map)}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){qO()&&(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(AM){return!1}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(qO())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(IM){_M.warn(IM)}}getItem(e){if(!qO())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(zb){_M.warn(zb)}}setItem(e,t){if(qO())try{let i={expiresIn:Date.now()+fk,value:t};this._queue.set(this.getRealKey(e),i)}catch(Xk){_M.warn(Xk)}}deleteItem(e){if(!qO())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(zb){return _M.warn(zb),!1}}clear(){if(qO())try{localStorage.clear()}catch(IM){_M.warn(IM)}}},EM={};Tb(EM,{HTTPS_API:()=>nL,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>CL,IS_GET_CAPABILITIES_SUPPORTED:()=>RL,IS_GET_SETTINGS_SUPPORTED:()=>AL,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>IL,IS_INSERTABLE_STREAM_SUPPORTED:()=>bL,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>BL,IS_RTC_RTP_SENDER_SUPPORTED:()=>vL,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>kL,IS_SEI_SUPPORTED:()=>DL,IS_SPC_SUPPORTED:()=>EL,basis:()=>LL,capabilityCheck:()=>UL,checkSystemRequirementsInternal:()=>ZP,decodeSupportStatus:()=>QP,detectVideoCodecCapabilities:()=>GL,detectVideoDecoderCapabilities:()=>JL,detectVideoEncoderCapabilities:()=>jL,encodeSupportStatus:()=>XP,getBrowserInfo:()=>GP,getDisplayResolution:()=>sL,isAddTransceiverSupported:()=>gL,isBrowserSupported:()=>jP,isCanvasCaptureStreamAPISupported:()=>lL,isCanvasSmallStreamSupported:()=>dL,isGetReceiversSupported:()=>mL,isGetSendersSupported:()=>_L,isGetTransceiversSupported:()=>fL,isGetUserMediaSupported:()=>aL,isMediaDevicesSupported:()=>KP,isMediaSessionSupported:()=>OL,isMediaStreamTrackProcessorSupported:()=>YP,isReplaceTrackSupported:()=>yL,isRequestVideoFrameCallbackSupported:()=>FL,isSIMDSupported:()=>PL,isScaleResolutionDownBySupported:()=>uL,isScreenCaptureApiAvailable:()=>eL,isSelectedCandidatePair:()=>oL,isSetParametersSupported:()=>SL,isSetSinkIdSupported:()=>tL,isSmallStreamSupported:()=>hL,isStopTransceiverSupported:()=>TL,isTRTCSupported:()=>$P,isUnifiedPlanDefault:()=>pL,isUsedInHttpProtocol:()=>zP,isWebAudioSupported:()=>cL,isWebCodecSupported:()=>NL,isWebCodecsSupported:()=>JP,isWebRTCSupported:()=>wL,isWebTransportSupported:()=>ML});var TM={};Tb(TM,{AUDIO_LEVEL_SCALE:()=>uP,AudioCodecPipelineType:()=>fP,AudioDecoderDowngradeState:()=>KM,AudioPlayerMode:()=>cP,AudioType:()=>ZM,BASIC_TYPE:()=>pP,BannedReason:()=>lP,CONNECTION_CLOSED_REASON:()=>MM,CheckPermissionType:()=>SP,ClientEvent:()=>PM,CodecType:()=>gP,ConnectionEvent:()=>OM,ConnectionState:()=>JM,DECODE_FAILED_ERROR_CODE:()=>EP,DeviceType:()=>IP,FacingMode:()=>sP,FrameWorkType:()=>NM,LeaveReason:()=>dP,LocalTrackEvent:()=>xM,MULTI_VIDEO_DATA_TYPE:()=>iP,MediaType:()=>XM,MediaTypeLabel:()=>QM,MonitorEventId:()=>rP,MutedFlag:()=>HM,NetworkQualityValue:()=>nP,PlayerState:()=>VM,ReceiveMode:()=>oP,RemoteStreamType:()=>tP,RemoteTrackEvent:()=>BM,RoomEvent:()=>UM,SMALL_MODE:()=>yP,SceneNumber:()=>WM,StreamEvent:()=>LM,StreamType:()=>eP,SubscribeMediaType:()=>hP,TIMER_TYPE:()=>vP,TRACK_ACTION:()=>YM,TRACK_KIND:()=>zM,TrackEvent:()=>FM,UserRole:()=>jM,UserRoleNumber:()=>GM,VideoCodec:()=>mP,VideoCodecPipelineType:()=>_P,VideoContentHint:()=>TP,VideoDecoderDowngradeState:()=>qM,VideoPlayerMode:()=>aP,VideoType:()=>$M});var vM,yM,SM,IM,AM,RM,CM,bM,kM,DM,wM,NM=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(NM||{}),OM=((wM=OM||{}).TRACK_ADDED="track-added",wM.TRACK_UPDATED="track-updated",wM.TRACK_SUBSCRIBED="track-subscribed",wM.STREAM_ADDED="stream-added",wM.STREAM_REMOVED="stream-removed",wM.STREAM_UPDATED="stream-updated",wM.STREAM_PUBLISHED="stream-published",wM.STREAM_SUBSCRIBED="stream-subscribed",wM.STREAM_UNSUBSCRIBED="stream-unsubscribed",wM.STATE_CHANGED="state-changed",wM.ERROR="error",wM.CONNECTION_STATE_CHANGED="connection-state-changed",wM.FIREWALL_RESTRICTION="firewall-restriction",wM.SEI_MESSAGE="sei-message",wM.CLOSED="closed",wM),MM=(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))(MM||{}),PM=((DM=PM||{}).STREAM_ADDED="stream-added",DM.STREAM_REMOVED="stream-removed",DM.STREAM_UPDATED="stream-updated",DM.STREAM_SUBSCRIBED="stream-subscribed",DM.CONNECTION_STATE_CHANGED="connection-state-changed",DM.PEER_JOIN="peer-join",DM.PEER_LEAVE="peer-leave",DM.MUTE_AUDIO="mute-audio",DM.MUTE_VIDEO="mute-video",DM.UNMUTE_AUDIO="unmute-audio",DM.UNMUTE_VIDEO="unmute-video",DM.CLIENT_BANNED="client-banned",DM.NETWORK_QUALITY="network-quality",DM.AUDIO_VOLUME="audio-volume",DM.SEI_MESSAGE="sei-message",DM.ERROR="error",DM),LM=((kM=LM||{}).PLAYER_STATE_CHANGED="player-state-changed",kM.SCREEN_SHARING_STOPPED="screen-sharing-stopped",kM.CONNECTION_STATE_CHANGED="connection-state-changed",kM.DEVICE_AUTO_RECOVERED="device-auto-recovered",kM.ERROR="error",kM),xM=((bM=xM||{}).DEVICE_AUTO_RECOVERED="1",bM.DEVICE_RECOVER_FAILED="5",bM.DEVICE_CHANGED="2",bM.ERROR="3",bM.PUBLISH_STATE_CHANGED="4",bM.ENCODE_FAILED="6",bM.TRACK_ENDED="7",bM.RENDER="render",bM),VM=(e=>(e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e))(VM||{}),UM=((CM=UM||{}).PEER_JOIN="peer-join",CM.PEER_LEAVE="peer-leave",CM.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",CM.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",CM.BANNED="banned",CM.NETWORK_QUALITY="network-quality",CM.AUDIO_VOLUME="audio-volume",CM.SEI_MESSAGE="sei-message",CM.ERROR="error",CM.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",CM.REMOTE_PUBLISHED="remote-published",CM.REMOTE_UNPUBLISHED="remote-unpublished",CM.FIREWALL_RESTRICTION="firewall-restriction",CM.HEARTBEAT_REPORT="heartbeat-report",CM.CUSTOM_MESSAGE="custom-message",CM.LAYER_DATA="layerData",CM.FIRST_VIDEO_FRAME="first-video-frame",CM.DUMP="dump",CM.AUDIO_FRAME="audio-frame",CM.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",CM.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",CM),FM=(e=>(e.PLAYER_STATE_CHANGED="player-state-changed",e.MUTE="mute",e.UNMUTE="unmute",e.ERROR="error",e.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",e.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",e.FIRST_VIDEO_FRAME="first-video-frame",e.VIDEO_SIZE_CHANGED="video-size-changed",e))(FM||{}),BM=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(BM||{}),HM=((RM=HM||{})[RM.VIDEO=1]="VIDEO",RM[RM.SMALL=2]="SMALL",RM[RM.AUX=4]="AUX",RM[RM.AUDIO=8]="AUDIO",RM[RM.VIDEO_MUTE=16]="VIDEO_MUTE",RM[RM.AUX_MUTE=32]="AUX_MUTE",RM[RM.AUDIO_MUTE=64]="AUDIO_MUTE",RM),WM=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(WM||{}),GM=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(GM||{}),jM=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(jM||{}),JM=(e=>(e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e))(JM||{}),KM=((AM=KM||{}).INITIALIZED="INITIALIZED",AM.STARTING="STARTING",AM.STARTED="STARTED",AM.FAILED="FAILED",AM),qM=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(qM||{}),zM=(e=>(e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e))(zM||{}),YM=(e=>(e.ADD="add",e.REMOVE="remove",e))(YM||{}),XM=(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))(XM||{}),QM={1:"audio",2:"auxVideo",4:"video"},ZM=((IM=ZM||{})[IM.opus=111]="opus",IM),$M=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))($M||{}),eP=(e=>(e.Big="big",e.Small="small",e))(eP||{}),tP=(e=>(e.Main="main",e.Aux="auxiliary",e))(tP||{}),iP=(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))(iP||{}),rP=((SM=rP||{})[SM.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",SM[SM.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",SM[SM.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",SM[SM.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",SM[SM.MUTE_AUDIO=32772]="MUTE_AUDIO",SM[SM.MUTE_VIDEO=32773]="MUTE_VIDEO",SM[SM.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",SM[SM.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",SM[SM.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",SM[SM.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",SM[SM.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",SM[SM.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",SM[SM.SWITCH_CAMERA=32780]="SWITCH_CAMERA",SM[SM.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",SM[SM.REPLACE_VIDEO=32782]="REPLACE_VIDEO",SM[SM.REPLACE_AUDIO=32783]="REPLACE_AUDIO",SM[SM.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",SM[SM.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",SM[SM.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",SM[SM.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",SM[SM.JOIN=32788]="JOIN",SM[SM.LEAVE=32789]="LEAVE",SM[SM.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",SM[SM.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",SM[SM.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",SM[SM.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",SM[SM.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",SM[SM.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",SM[SM.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",SM[SM.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",SM[SM.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",SM[SM.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",SM[SM.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",SM[SM.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",SM[SM.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",SM[SM.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",SM[SM.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",SM[SM.PUBLISH_AUX=32805]="PUBLISH_AUX",SM[SM.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",SM[SM.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",SM[SM.VIDEO_ENCODER=4004]="VIDEO_ENCODER",SM[SM.VIDEO_DECODER=4005]="VIDEO_DECODER",SM),nP=(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))(nP||{}),oP=(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))(oP||{}),sP=(e=>(e.user="user",e.environment="environment",e))(sP||{}),aP=(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))(aP||{}),cP=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(cP||{}),lP=(e=>(e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e))(lP||{}),dP=((yM=dP||{})[yM.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",yM[yM.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",yM[yM.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",yM[yM.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",yM[yM.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",yM[yM.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",yM[yM.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",yM[yM.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",yM[yM.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",yM),uP=1e8,hP=class{constructor(){Sb(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)}},pP=(e=>(e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e))(pP||{}),mP=(e=>(e.H264="h264",e.H265="h265",e.VP8="vp8",e.VP9="vp9",e.AV1="av1",e))(mP||{}),_P=(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))(_P||{}),fP=(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))(fP||{}),gP=(e=>(e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e))(gP||{}),EP=((vM=EP||{})[vM.SUCCESS=0]="SUCCESS",vM[vM.FAILED=1]="FAILED",vM[vM.WEBCODEC_INIT=2]="WEBCODEC_INIT",vM[vM.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",vM[vM.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",vM[vM.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",vM[vM.WASM_INIT=6]="WASM_INIT",vM[vM.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",vM[vM.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",vM[vM.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",vM[vM.TEST=10]="TEST",vM[vM.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",vM),TP=(e=>(e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e))(TP||{}),vP=(e=>(e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e))(vP||{}),yP=(e=>(e.CANVAS="canvas",e.API="api",e))(yP||{}),SP=(e=>(e[e.NONE=0]="NONE",e[e.MICROPHONE=1]="MICROPHONE",e[e.CAMERA=2]="CAMERA",e[e.BOTH=3]="BOTH",e))(SP||{}),IP=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(IP||{}),AP={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"},RP={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(r,"(), received type: ").concat(cw(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(r,"(), received type: ").concat(cw(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,"()")},CP=(e,t)=>t?"".concat(ok,"/").concat(e,"/").concat(t):"".concat(ok,"/").concat(e,"/index.html"),bP=()=>{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(lk);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 kP(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",s="",a="";lw(RP[t])?o=RP[t](i):uw(RP[t])&&(o=RP[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=bP();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(lw(l[t])?a=l[t](i):uw(l[t])&&(a=l[t]));let d=o;return nw()&&(c&&c[t]&&(lw(c[t])?s=c[t](i):uw(c[t])&&(s=c[t])),s&&(d=n?"".concat(s,"\n请查看文档: ").concat(CP("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(CP("en",a),"\n")),d}var DP,wP,NP=vb(Db(),1),OP=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];Sb(this,"countMap",new Map),Sb(this,"distributionMap",new Map),Sb(this,"version"),Sb(this,"log",_M.createLogger({id:"kv"})),e&&(dM.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===Sk.AUDIO?501700:511700,cost:i})})),dM.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===Sk.AUDIO?501700:511700,error:i})})),dM.on("266",(e=>{let{enable:t}=e;this.log.info("".concat(t?"enable":"disable"," sso")),t?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:Ww(this.version||Kb),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,uint32_count:i}})),stats_distribution:[...this.distributionMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,distribution_items:[...i.entries()].map((e=>{let[t,i]=e;return{uint32_item_key:t,uint32_item_value:i}}))}}))};return this.countMap.clear(),this.distributionMap.clear(),e}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){let t=+String(e).slice(-3);return t>=700&&t<799}isErrorCodeKey(e){let t=+String(e).slice(-3);return t>=600&&t<699}isCountKey(e){let t=+String(e).slice(-3);return t>=0&&t<599}isNumberKey(e){let t=+String(e).slice(-3);return t>=800&&t<899}addCount(e){let{key:t,useUV:i=!1}=e;this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}addEnum(e){let{key:t,value:i,useUV:r=!0}=e;var n;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=(null==(n=this.distributionMap)?void 0:n.get(t))||new Map;o.set(i,(o.get(i)||0)+1),this.distributionMap.set(t,o)}addNumber(e){let{key:t,value:i,split:r=100,useUV:n=!1,max:o=5e3}=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;i>o&&(i=o),this.countMap.set(t,(this.countMap.get(t)||0)+1);let a=(null==(s=this.distributionMap)?void 0:s.get(t))||new Map,c=0;if(hw(r))c=Math.floor(i/r);else for(let l=r.length-1;l>0;l--)if(i>r[l]){c=l;break}a.set(c,(a.get(c)||0)+1),this.distributionMap.set(t,a)}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=xb.UNKNOWN;i&&(hw(i)?r=i:(!dw(i.extraCode)||!dw(i.code))&&(r=i.extraCode||i.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:Math.abs(r),useUV:!1})}},MP=((DP=MP||{})[DP.enterRoom=500700]="enterRoom",DP[DP.exitRoom=500701]="exitRoom",DP[DP.switchRole=500702]="switchRole",DP[DP.destroy=500703]="destroy",DP[DP.startLocalAudio=500704]="startLocalAudio",DP[DP.updateLocalAudio=500705]="updateLocalAudio",DP[DP.stopLocalAudio=500706]="stopLocalAudio",DP[DP.startLocalVideo=500707]="startLocalVideo",DP[DP.updateLocalVideo=500708]="updateLocalVideo",DP[DP.stopLocalVideo=500709]="stopLocalVideo",DP[DP.startScreenShare=500710]="startScreenShare",DP[DP.updateScreenShare=500711]="updateScreenShare",DP[DP.stopScreenShare=500712]="stopScreenShare",DP[DP.startRemoteVideo=500713]="startRemoteVideo",DP[DP.updateRemoteVideo=500714]="updateRemoteVideo",DP[DP.stopRemoteVideo=500715]="stopRemoteVideo",DP[DP.muteRemoteAudio=500716]="muteRemoteAudio",DP[DP.setRemoteAudioVolume=500717]="setRemoteAudioVolume",DP[DP.use=500718]="use",DP[DP.switchRoom=500719]="switchRoom",DP[DP.sendSEIMessage=5e5]="sendSEIMessage",DP[DP.sendCustomMessage=500001]="sendCustomMessage",DP),PP=(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[e.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",e[e.VideoMixer=594700]="VideoMixer",e[e.AudioProcessor=595700]="AudioProcessor",e))(PP||{}),LP=(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[e.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",e[e.VideoMixer=594701]="VideoMixer",e[e.AudioProcessor=595701]="AudioProcessor",e))(LP||{}),xP=(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[e.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",e[e.VideoMixer=594702]="VideoMixer",e[e.AudioProcessor=595702]="AudioProcessor",e))(xP||{}),VP=((wP=VP||{})[wP.DECODER_TYPE=514700]="DECODER_TYPE",wP[wP.DECODER_HW_SW=514701]="DECODER_HW_SW",wP[wP.DECODE_RESULT=514702]="DECODE_RESULT",wP[wP.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",wP[wP.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",wP[wP.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",wP[wP.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",wP[wP.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",wP[wP.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",wP[wP.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",wP[wP.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",wP[wP.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",wP[wP.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",wP[wP.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",wP[wP.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",wP[wP.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",wP[wP.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",wP),UP=new OP(!0),FP=new OP(!1),BP=UP,HP={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},WP=new Map([[wN,["Firefox",NN]],[LN,["Edg",xN]],[DO,["Chrome",OO]],[MO,["Safari",LO]],[WN,["TBS",GN]],[jN,["XWEB",JN]],[YN&&IN,["WeChat",XN]],[eO,["QQ(Win)",tO]],[ZN,["QQ(Mobile)",$N]],[QN,["QQ(Mobile X5)",$N]],[iO,["QQ(Mac)",rO]],[nO,["QQ(iPad)",oO]],[pO,["MI",mO]],[_O,["HW",EO]],[TO,["Samsung",vO]],[yO,["OPPO",SO]],[IO,["VIVO",AO]],[MN,["EDGE",PN]],[UN,["SogouMobile",FN]],[BN,["Sogou",HN]]]);function GP(){let e=WP.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var jP=function(){return!(uO||MN||LN&&VN<80||wN&&ON<56)},JP=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every((e=>e in window))},KP=function(){if(!navigator.mediaDevices)return zP()||_M.error(RP.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},qP=!1;function zP(){return"http:"===location.protocol&&!KO&&(qP||_M.error(kP({key:AP.NOT_SUPPORTED_HTTP})),qP=!0,!0)}var YP=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},XP=function(){return Ab(this,null,(function*(){var e,t,i;if(HP.detail.isH264EncodeSupported&&HP.detail.isVp8EncodeSupported)return{isH264EncodeSupported:HP.detail.isH264EncodeSupported,isVp8EncodeSupported:HP.detail.isVp8EncodeSupported,isH265EncodeSupported:HP.detail.isH265EncodeSupported};let r,n=!1,o=!1,s=!1;try{let a=new RTCPeerConnection,c=document.createElement(Sk.CANVAS);c.getContext("2d");let l=c.captureStream(0);return a.addTrack(l.getVideoTracks()[0],l),r=yield a.createOffer(),n=-1!==(null==(e=r.sdp)?void 0:e.toLowerCase().indexOf("h264")),o=-1!==(null==(t=r.sdp)?void 0:t.toLowerCase().indexOf("vp8")),s=-1!==(null==(i=r.sdp)?void 0:i.toLowerCase().indexOf("h265")),a.close(),{isH264EncodeSupported:n,isVp8EncodeSupported:o,isH265EncodeSupported:s}}catch(RM){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}}))},QP=function(){return Ab(this,null,(function*(){var e;if(HP.detail.isH264DecodeSupported&&HP.detail.isVp8DecodeSupported)return{isH264DecodeSupported:HP.detail.isH264DecodeSupported,isVp8DecodeSupported:HP.detail.isVp8DecodeSupported,isH265DecodeSupported:HP.detail.isH265DecodeSupported};let t,i=!1,r=!1;try{let n=new RTCPeerConnection;gL()?(n.addTransceiver(Sk.VIDEO,{direction:"recvonly"}),t=yield n.createOffer()):t=yield n.createOffer({offerToReceiveVideo:!0}),-1!==t.sdp.toLowerCase().indexOf("h264")&&(i=!0),-1!==t.sdp.toLowerCase().indexOf("vp8")&&(r=!0);let o=-1!==(null==(e=t.sdp)?void 0:e.toLowerCase().indexOf("h265"));return n.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:r,isH265DecodeSupported:o}}catch(AM){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}}))};var ZP=Jw((e=>Ab(void 0,null,(function*(){let t=Date.now(),i=wL(),r=KP(),n=JP();if(HP.detail.isWebRTCSupported=i,HP.detail.isMediaDevicesSupported=r,HP.detail.isWebCodecsSupported=n,HP.detail.isScreenShareSupported=eL(),HP.detail.isSmallStreamSupported=hL(),37===e)return Object.assign(HP.detail,yield function(){return Ab(this,null,(function*(){return rL||(rL=new Promise((e=>Ab(this,null,(function*(){let t={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!JP())return void e(t);let i=null,r=null,n=null,o=()=>{n&&clearTimeout(n),i=null,r=null};try{i=document.createElement("canvas"),r=i.getContext("2d"),i.width=320,i.height=240;let s=0,a=()=>{!r||!i||(r.fillStyle="hsl(".concat(s%360,", 50%, 50%)"),r.fillRect(0,0,i.width,i.height),r.fillStyle="white",r.font="20px Arial",r.fillText("Frame ".concat(s),10,30),s++)};n=setTimeout((()=>{o(),e(t)}),5e3);let c=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(c.map((e=>Ab(this,null,(function*(){let t,r={type:e.type,encodeSupported:!1,decodeSupported:!1};try{t=yield new Promise(((t,n)=>Ab(this,null,(function*(){try{let o=new VideoEncoder({output:e=>{t(e),r.encodeSupported=!0},error:n});o.configure(e.encodeConfig),a();let s=new VideoFrame(i,{timestamp:0});o.encode(s,{keyFrame:!0}),s.close(),yield o.flush(),o.close()}catch(wM){n(wM)}}))))}catch(p){return _M.warn("".concat(e.type," encoder error:"),p),r}try{yield new Promise(((i,n)=>Ab(this,null,(function*(){try{let o=new VideoDecoder({output:e=>{r.decodeSupported=!0,i(0),e.close()},error:n});o.configure(e.decodeConfig),o.decode(t),yield o.flush(),o.close()}catch(wM){n(wM)}}))))}catch(p){_M.warn("".concat(e.type," decoder error:"),p)}return r})))))).forEach((e=>{"h264"===e.type?(t.isH264EncodeSupported=e.encodeSupported,t.isH264DecodeSupported=e.decodeSupported):"vp8"===e.type&&(t.isVp8EncodeSupported=e.encodeSupported,t.isVp8DecodeSupported=e.decodeSupported)})),o(),e(t)}catch(s){o(),_M.warn("detectWebCodecsSupported failed:",s),e(t)}})))),rL)}))}()),HP.detail.isBrowserSupported=n,HP.result=r&&n,HP.result||_M.error("".concat(navigator.userAgent," ").concat(Uw(HP.detail,!1))),VL(e),BP.addNumber({key:523800,value:Date.now()-t}),HP;if(HP.result&&HP.detail.isH264EncodeSupported&&HP.detail.isVp8EncodeSupported&&HP.detail.isH265EncodeSupported&&HP.detail.isH264DecodeSupported&&HP.detail.isVp8DecodeSupported&&HP.detail.isH265DecodeSupported)return HP;let o=jP(),{encode:s,decode:a}=yield function(){return Ab(this,null,(function*(){let[e,t]=yield Promise.all([XP(),QP()]);return{encode:{h264:e.isH264EncodeSupported,vp8:e.isVp8EncodeSupported,h265:e.isH265EncodeSupported},decode:{h264:t.isH264DecodeSupported,vp8:t.isVp8DecodeSupported,h265:t.isH265DecodeSupported}}}))}(),{h264:c,vp8:l}=s,{h264:d}=a,{h265:u}=s,{vp8:h,h265:p}=a;if(!c||!l){let e=yield XP();_M.warn("detect encode again h264:".concat(c," vp8:").concat(l," result: ").concat(JSON.stringify(e))),c=e.isH264EncodeSupported,l=e.isVp8EncodeSupported}if(c&&d&&CN&&kO&&!jN&&!WN){let{encode:e,decode:t}=yield function(){return Ab(this,null,(function*(){return iL||(iL=new Promise((e=>Ab(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{let r=document.createElement("canvas"),n=r.getContext("2d");r.width=320,r.height=240;let o=setInterval((()=>{n.fillText("test",Math.floor(320*Math.random()),Math.floor(240*Math.random()))}),66),s=-1,a=-1;i=()=>{clearInterval(s),clearInterval(o),clearTimeout(a),l.close(),d.close(),c.getTracks().forEach((e=>e.stop()))},a=setTimeout((()=>{i(),e(t)}),2e3);let c=r.captureStream(),l=new RTCPeerConnection({}),d=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",(e=>d.addIceCandidate(e.candidate))),d.addEventListener("icecandidate",(e=>l.addIceCandidate(e.candidate))),l.addTrack(c.getVideoTracks()[0],c);let u=yield l.createOffer();yield l.setLocalDescription(u),yield d.setRemoteDescription(u);let h=yield d.createAnswer(),p=NP.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=NP.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval((()=>Ab(this,null,(function*(){t.encode&&t.decode&&(i(),e(t));let[r,n]=yield Promise.all([l.getSenders()[0].getStats(),d.getReceivers()[0].getStats()]);t.encode||r.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===Sk.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===Sk.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(r){i(),_M.warn("detectH264Supported failed",r),e({encode:!0,decode:!0})}})))).then((e=>(e.encode||(e.decode=!0),(!e.encode||!e.decode)&&_M.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(ZO)),e))),iL)}))}();c=e,d=t}return HP.result=o&&i&&r&&(c||l)&&(d||h),HP.detail.isBrowserSupported=o,HP.detail.isWebRTCSupported=i,HP.detail.isH264EncodeSupported=c,HP.detail.isVp8EncodeSupported=l,HP.detail.isH265EncodeSupported=u,HP.detail.isH264DecodeSupported=d,HP.detail.isVp8DecodeSupported=h,HP.detail.isH265DecodeSupported=p,HP.result||_M.error("".concat(navigator.userAgent," ").concat(Uw(HP.detail,!1))),VL(),BP.addNumber({key:523800,value:Date.now()-t}),HP})))),$P=function(){return HP.result},eL=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},tL="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype,iL=null;var rL=null;var nL=(e,t,i)=>{"http:"===location.protocol&&!KO&&(e[t]=()=>{throw new Ub({code:xb.INVALID_OPERATION,message:RP.NOT_SUPPORTED_HTTP})})},oL=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(pw(e.selected)&&!e.selected)};function sL(){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 aL(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function cL(){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 lL(){return"captureStream"in HTMLCanvasElement.prototype}function dL(){return!(YN||RN||NO&&NO<63)&&!(!jP()||!lL())}function uL(){return!(NO<74||MN||BO<11||ON<46)}function hL(){return dL()||uL()}var pL=function(){if(dw(window.RTCRtpTransceiver)||!gL()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:iD}),e.addTransceiver(Sk.AUDIO),t=!0}catch(zb){}return null==e||e.close(),t};function mL(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function _L(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function fL(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function gL(){return!(11===BO&&!JO)&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var EL=!(!gL()||kO&&NO<86);function TL(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var vL="RTCRtpSender"in window;function yL(){return vL&&"replaceTrack"in window.RTCRtpSender.prototype}function SL(){return vL&&"setParameters"in window.RTCRtpSender.prototype&&_L()}var IL="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,AL=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,RL=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,CL="undefined"!=typeof InputDeviceInfo&&"getCapabilities"in InputDeviceInfo.prototype,bL=vL&&"createEncodedStreams"in window.RTCRtpSender.prototype&&bO()>=86,kL="RTCRtpScriptTransform"in window,DL=vL&&(bL||kL),wL=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function NL(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return dw(window.AudioDecoder)||(e.AudioDecoder=!0),dw(window.AudioEncoder)||(e.AudioEncoder=!0),dw(window.VideoDecoder)||(e.VideoDecoder=!0),dw(window.VideoEncoder)||(e.VideoEncoder=!0),dw(window.ImageDecoder)||(e.ImageDecoder=!0),e}function OL(){return"mediaSession"in navigator&&!dw(navigator.mediaSession.setActionHandler)}function ML(){return!dw(window.WebTransport)}function PL(){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 LL(){let e={browser:"".concat(zO.name,"/").concat(zO.version),os:rM(),displayResolution:sL(),isScreenShareSupported:eL(),isWebRTCSupported:wL(),isGetUserMediaSupported:aL(),isWebAudioSupported:cL(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:NL(),isMediaSessionSupported:OL(),isWebTransportSupported:ML()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var xL="checkResult";function VL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30;gM.setItem(xL+e,{ua:navigator.userAgent,checkResult:HP})}function UL(e){zP();let t=gM.getItem(xL+e);t&&t.ua===navigator.userAgent&&t.checkResult&&function(e,t){return!!mw(e)&&Object.keys(t).every((t=>t in e))}(t.checkResult.detail,HP.detail)&&(HP=t.checkResult),ZP(e)}function FL(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var BL="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function HL(e){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[e]}var WL=!1;function GL(){return Ab(this,null,(function*(){var e;try{if(WL||null==(e=null==navigator?void 0:navigator.mediaCapabilities)||!e.encodingInfo)return;let t=nM(),i=oM();if(0===t||0===i)return;WL=!0;let r=["H264","VP8","VP9","AV1","H265"],[n,o]=yield Promise.all([jL(r),JL(r)]);n&&Object.keys(n).forEach((e=>{let r=HL(e.toLowerCase());BP.addEnum({key:513707,value:+"".concat(r).concat(+n[e].supported).concat(+n[e].powerEfficient).concat(t).concat(i),useUV:!1})})),o&&Object.keys(o).forEach((e=>{let r=HL(e.toLowerCase());BP.addEnum({key:514713,value:+"".concat(r).concat(+o[e].supported).concat(+o[e].powerEfficient).concat(t).concat(i),useUV:!1})}))}catch(IM){_M.info("detectVideoCodecCapabilities failed",IM)}}))}function jL(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1920,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1080,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:30,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:3e3;return Ab(this,null,(function*(){let o={};try{for(let s of e){let e=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:"video/".concat(s),width:t,height:i,bitrate:n,framerate:r}});o[s]=e}}catch(Yb){}return o}))}function JL(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1920,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1080,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:30,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:3e3;return Ab(this,null,(function*(){let o={};try{for(let s of e){let e=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:"video/".concat(s),width:t,height:i,bitrate:n,framerate:r}});o[s]=e}}catch(Yb){}return o}))}var KL=vb(Rb(),1),qL=Symbol("instance"),zL=Symbol("cacheResult"),YL=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,ex.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},XL=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var QL=new Map;function ZL(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,n,o)=>{let s=i.action||n;if(!i.context){let i=QL.get(r)||[];QL.has(r)||QL.set(r,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let r=this;for(var n=arguments.length,o=new Array(n),c=0;c<n;c++)o[c]=arguments[c];if(i.context&&(r=tx.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return i.sync?r[zL]:Promise.resolve(r[zL]);r.state instanceof YL&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof YL&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new XL(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e.join("|")))):e!==r.state&&(l=new XL(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e)));let d=e=>{if(i.fail&&i.fail.call(this,e),i.sync){if(i.ignoreError)return e;throw e}return i.ignoreError?Promise.resolve(e):Promise.reject(e)};if(l)return d(l);let u=r.state,h=new YL(u,t,s);ex.call(r,h);let p=e=>{var n;return r[zL]=e,h.aborted||(ex.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[zL])),e},m=e=>(ex.call(r,u,e),d(e));try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(p).catch(m):i.sync?p(e):Promise.resolve(p(e))}catch(DM){return m(new XL(r._state,"".concat(r.name," ").concat(s," from ").concat(e," to ").concat(t," failed: ").concat(DM),DM instanceof Error?DM:new Error(String(DM))))}}}}var $L="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 ex(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(tx.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var tx=class e extends KL.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[qL];n?this.name=n.name+"-"+n.count++:r[qL]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=QL.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);QL.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?r.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:o})})):n.push({to:i,action:o})})),r.forEach((e=>{let{from:t,to:r,action:n}=e;o.add(t),o.add(r),o.add(n+"ing"),i.add("".concat(t," --\x3e ").concat(n,"ing : ").concat(n)),i.add("".concat(n,"ing --\x3e ").concat(r," : ").concat(n," 🟢")),i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🔴"))})),n.forEach((e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(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]:{};$L(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){ex.call(this,e)}};tx.STATECHANGED="stateChanged",tx.UPDATEAFSM="updateAFSM",tx.INIT="[*]",tx.ON="on",tx.OFF="off",tx.instances=new Map,tx.instances2=new WeakMap;var ix="undefined"!=typeof window,rx=ix&&window.requestIdleCallback||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},nx=ix&&window.cancelIdleCallback||function(e){clearTimeout(e)},ox=ix&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),sx=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=fb("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=gb(fb({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&&(e.isBreakLoop(r)?(null==(i=e.sharedWorker)||i.postMessage({type:"stop",taskId:r.taskID}),e.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),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=Aw(),n=()=>{if(i=Aw()-r,i>=t.delay&&(r=Aw()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!e.isBreakLoop(t))return t.ricID=rx(n,{timeout:t.delay})};return t.ricID=rx(n,{timeout:t.delay})}static raf(t){let i,r=Aw(),n=()=>document.hidden&&t.backgroundTask?(i=Aw()-r,r=Aw(),t.callback(),t.loopCount+=1,e.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(n,t.delay-Math.floor(i%t.delay))):(i=Aw()-r,i>=t.delay&&(r=Aw()-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=Aw()-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:o}=this.taskMap.get(e);return t&&clearInterval(t),i&&clearTimeout(i),r&&ox&&ox(r),n&&nx(n),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.hasTask(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};Sb(sx,"taskMap",new Map),Sb(sx,"currentTaskID",1),Sb(sx,"sharedWorker",null),Sb(sx,"workerTasks",new Map);var ax=sx;Sk.SEI_MESSAGE;var cx={LOADED_DATA:Sk.LOADEDDATA,LOADED_META_DATA:Sk.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",RESIZE:Sk.RESIZE},lx={};Tb(lx,{create:()=>ux,remove:()=>hx});var dx=new WeakMap;function ux(e,t){dx.has(e)||dx.set(e,[]);let i=dx.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 hx(e){let t=dx.get(e);t&&(t.forEach((e=>e())),dx.delete(e))}var px=new class{constructor(){Sb(this,"_roomIdMap",new Map),Sb(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:Kb,env:uk.QCLOUD,browserVersion:zO.name+zO.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){KO||!_M.isAbleToUpload||this._configs.env===uk.QCLOUD&&this.uploadEventToKibana(gb(fb({},e),{result:"success"}))}logFailedEvent(e){if(KO||!_M.isAbleToUpload)return;let{eventType:t,code:i,error:r,userId:n}=e,o={roomId:this._roomIdMap.get(n||this._configs.userId),userId:n,eventType:t,result:"failed",code:i||(null==r?void 0:r.extraCode)||(null==r?void 0:r.code)||xb.UNKNOWN};this._configs.env===uk.QCLOUD&&this.uploadEventToKibana(gb(fb({},o),{error:r}))}uploadEventToKibana(e){let t="stat-".concat(e.eventType,"-").concat(e.result);("delta-join"===e.eventType||"delta-leave"===e.eventType||"delta-publish"===e.eventType)&&(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}uploadEvent(e){let{log:t,userId:i,error:r}=e,n={timestamp:Hb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:Kb,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+="\n".concat(r.stack)));let o=pM.enable?$w(n,2002,Number(this._configs.sdkAppId)):JSON.stringify(n);this.sendRequest(KD(this._configs.sdkAppId,dk.LOG),o)}sendRequest(e,t){setTimeout((()=>nN({url:e,body:t,priority:"low"}).catch((()=>{}))),2e3)}},mx=new WeakMap;function _x(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,s){let a=hN({retryFunction:s.value,settings:t,onError(t){let{error:r,retry:n,reject:s,retryFuncArgs:a}=t;var c;i?i.call(this,r,(()=>{var t;null!=(t=mx.get(e))&&t.has(o)?n():s(r)}),s,a):null!=(c=mx.get(e))&&c.has(o)?n():s(r)},onRetrying(t,i){var n;aN(r)&&r.call(this,t,i),null!=(n=mx.get(e))&&n.has(o)&&(mx.get(e).get(o).stopRetry=i)},onRetryFailed:n});return s.value=function(){let t=mx.get(e);for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return t?t.set(o,{args:r}):mx.set(e,new Map([[o,{args:r}]])),a.apply(this,r).finally((()=>{var t;return null==(t=mx.get(e))?void 0:t.delete(o)}))},s}}function fx(e){let{fnName:t,callback:i,validateArgs:r=!0}=e;return function(e,n,o){let s=o.value;return o.value=function(){for(var n,o,a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(null!=(n=mx.get(e))&&n.has(t)){let{stopRetry:n,args:s}=mx.get(e).get(t),a=!0;if(r)for(let e of s)if(!c.find((t=>t===e))){a=!1;break}a&&(i&&i.apply(this,c),n&&n(),null==(o=mx.get(e))||o.delete(t))}return s.apply(this,c)},o}}var gx=class extends tx{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,Sb(this,"id"),Sb(this,"element",null),Sb(this,"track"),Sb(this,"url"),Sb(this,"attr"),Sb(this,"mode"),Sb(this,"muted"),Sb(this,"_log"),Sb(this,"_pausedRetryCount"),Sb(this,"_isElementPlayingFired",!1),Sb(this,"_interval"),Sb(this,"_delayDestroyTimeoutId",0),Sb(this,"_playSuccessResolve"),Sb(this,"_isReplayByRecreateMediaStreamCalled",!1),Sb(this,"isInAutoPlayFailedState",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=mD,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){var e;return"PLAYING"===this._state&&!1===(null==(e=this.element)?void 0:e.paused)}get isPaused(){var e;return"PAUSED"===this._state||!0===(null==(e=this.element)?void 0:e.paused)}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,null!==e&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return Ab(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(zb){let t=kP({key:AP.PLAY_FAILED,data:{media:this.kind,error:zb}});if(this._log.warn(zb),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new Ub({code:xb.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&&!PO?this._delayDestroyTimeoutId||(this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout((()=>this.destroyElement()),3*e)):this.destroyElement(),this.handleStopped(Sk.ENDED),this._interval>0&&ax.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():WO?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 ux(this.element,this.element).add(Sk.PLAYING,e).add(Sk.ENDED,e).add(Sk.PAUSE,e).add(Sk.ERROR,e).add(Sk.LOADEDDATA,e).add(Sk.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==lx||lx.create(e,e).add(Sk.ENDED,t).add(Sk.MUTE,t).add(Sk.UNMUTE,t),e.readyState===Sk.ENDED&&this.handleTrackEvent({type:Sk.ENDED}),e.muted&&this.handleTrackEvent({type:Sk.MUTE})}}bindAutoPlayEvent(){dM.on(hM.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;e&&hx(e)}unbindEvents(){this.element&&hx(this.element),this.unbindTrackEvents(),dM.off(hM.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case Sk.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(Sk.PLAYING),this._interval&&(ax.clearTask(this._interval),this._interval=-1);break;case Sk.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(Sk.ENDED);break;case Sk.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(Sk.PAUSE),RN&&(this._interval=ax.run("timeout",(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case Sk.ERROR:if(this.element&&this.element.error){this.handlePaused(Sk.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)),px.uploadEvent({log:"stat-".concat(this.kind,"-").concat(Zk.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),gO||fO?this.emit(cx.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case Sk.LOADEDDATA:this.kind===Sk.VIDEO&&this.emit(cx.LOADED_DATA);break;case Sk.LOADEDMETADATA:this.kind===Sk.VIDEO&&this.emit(cx.LOADED_META_DATA)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),px.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),BP.addSuccessEvent({key:this.kind===Sk.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),px.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),BP.addFailedEvent({key:this.kind===Sk.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(cx.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,i)=>{jw(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)}),jw(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){return Ab(this,null,(function*(){switch(e.type){case Sk.ENDED:this.handleStopped(Sk.ENDED);break;case Sk.MUTE:this.handlePaused(Sk.MUTE);break;case Sk.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&(this._log.warn("track unmuted and element is paused, resume"),yield this.resume()),!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(Sk.UNMUTE))}}))}handlePlaying(e){var t;this._log.debug("handlePlaying",e),null==(t=this._playSuccessResolve)||t.call(this,e),this.emit(cx.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this._log.debug("handlePaused",e),this.emit(cx.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this._log.debug("handleStopped",e),this.emit(cx.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};yb([_x({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],gx.prototype,"doReplayByRecreateMediaStream",1),yb([ZL([],"PLAYING",{sync:!0})],gx.prototype,"handlePlaying",1),yb([ZL("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],gx.prototype,"handlePaused",1),yb([ZL([],"STOPPED",{sync:!0})],gx.prototype,"handleStopped",1);var Ex,Tx="trtc_autoplay",vx="".concat(Tx,"_mask"),yx="".concat(Tx,"_wrapper"),Sx="".concat(Tx,"_header"),Ix="".concat(Tx,"_content"),Ax="".concat(Tx,"_action_wrapper"),Rx="".concat(Tx,"_question"),Cx="".concat(Tx,"_collapse"),bx="".concat(Tx,"_action_confirm"),kx="".concat(Tx,"_detail"),Dx="#2473E8",wx="dialog",Nx="".concat(wx,"-show"),Ox="".concat(wx,"-1"),Mx="".concat(wx,"-2"),Px=!1,Lx=()=>!!document.querySelector(".".concat(yx)),xx="".concat(ok,"/").concat(nw()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),Vx="<br><a href='".concat(xx,"' target='_blank'>").concat(nw()?"其他方案?":"Any other solution?","</a>"),Ux="".concat(nw()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(Vx):"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(Vx)),Fx=class{constructor(){if(Sb(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),Sb(this,"_dialogNode",null),Sb(this,"_bodyPosition",""),Sb(this,"_showDetail",!1),Sb(this,"_isCollapseClicked",!1),Sb(this,"_isQuestionClicked",!1),nw()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Px){let e=document.createElement("style");e.innerHTML=".".concat(vx,"{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(vx," div:not(.").concat(Ax,"){display:block !important;}.").concat(yx,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(yx," a{color:").concat(Dx,";}.").concat(Sx,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(Ix,"{margin:8px 0;}.").concat(Ax,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(Cx,"{margin-right:auto;cursor:pointer}.").concat(Rx,"{height:100%;line-height:16px;cursor:pointer;}.").concat(bx,"{margin-left:8px;color:#fff;background:").concat(Dx,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(bx,":hover{opacity:0.9;}.").concat(Cx,",.").concat(bx,",.").concat(Ix,",.").concat(Rx,"{font-size:14px;}@media screen and (max-width:750px){.").concat(yx,"{width:80vw;}}"),document.head.appendChild(e),Px=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(vx,"\"><div class='").concat(yx,"'><div class='").concat(Sx,"'>").concat(location.host,"</div><div class='").concat(Ix,"'>").concat(this.content,"</div><div class='").concat(kx,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(Ux,"</div><div class='").concat(Ax,"'></div></div></div>").trim();let t=document.createElement("button");t.className=bx,t.innerText=nw()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=Rx,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=Cx,r.innerText="".concat(nw()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(Ax));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){Lx()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(yx)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",_M.info("show autoplay dialog"),px.uploadEvent({log:Nx}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){_M.warn("confirm clicked, try resume stream"),dM.emit(hM.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(kx));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||px.uploadEvent({log:Ox}),this._isCollapseClicked=!0}onQuestionClick(){window.open(xx,"_blank"),this._isQuestionClicked||px.uploadEvent({log:Mx}),this._isQuestionClicked=!0}},Bx=class extends gx{constructor(e){super(e,Sk.VIDEO),Sb(this,"stat",{}),Sb(this,"_calculateTimeout",-1),Sb(this,"viewMirror",!1),Sb(this,"objectFit"),Sb(this,"container"),Sb(this,"canvas"),Sb(this,"_preSize",{width:0,height:0}),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,dw(e.viewMirror)||(this.viewMirror=e.viewMirror),dw(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return!("PLAYING"!==this._state||this.element&&this.element.paused)&&("live"===(null==(e=this.track)?void 0:e.readyState)&&!this.track.muted)}initializeElement(){var e;let t=document.createElement(Sk.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.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(Sk.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(Sk.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(Sk.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===Sk.MUTE&&null!=(t=this.stat)&&t.fps&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var t,i,r,n,o,s,a,c;if(2===this.mode)return;super.handleElementEvent(e);let l=e.type;if(l===Sk.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id)),this.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=mD,this._log.info("view container ".concat(null==(i=this.container)?void 0:i.id," is recreated"))),this._pausedRetryCount>0&&!Lx()&&(this._log.info("[".concat(mD-this._pausedRetryCount+1,"/").concat(mD,"] ").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;l===Sk.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):l===Sk.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}l===Sk.RESIZE&&(this._preSize.height!==(null==(r=this.element)?void 0:r.videoHeight)||this._preSize.width!==(null==(n=this.element)?void 0:n.videoWidth))&&(this._log.info("video size changed to ".concat(null==(o=this.element)?void 0:o.videoWidth,"x").concat(null==(s=this.element)?void 0:s.videoHeight)),this._preSize.height=(null==(a=this.element)?void 0:a.videoHeight)||0,this._preSize.width=(null==(c=this.element)?void 0:c.videoWidth)||0,this.emit(cx.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;var i,r,n,o;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==(o=this.container)||o.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(cx.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(FL()&&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(zb){this._log.warn("init stat failed",zb)}}};function Hx(e,t){return Ab(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),_M.info("worklet addModule success")}catch(zb){throw _M.info("worklet addModule catch error. ".concat(zb.message)),zb}}))}"undefined"!=typeof AudioContext?Ex=AudioContext:"undefined"!=typeof webkitAudioContext?Ex=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(Ex=mozAudioContext);var Wx,Gx=1500,jx=-1,Jx=0,Kx=-1,qx=!1;!function e(){try{if(Wx)return;(Wx=new Ex({sampleRate:48e3})).onstatechange=()=>{_M.info("context state: ".concat(Wx.state).concat("running"!==Wx.state?" visibilityState: ".concat(document.visibilityState):"")),zx()},clearTimeout(jx)}catch(vJ){_M.error("initAudioContext failed: ".concat(vJ," typeof AudioContextClass: ").concat(typeof Ex)),jx=setTimeout(e,1e3)}}();var zx=()=>{"suspended"===Wx.state?(Jx=Aw(),-1===Kx&&(Kx=setTimeout((()=>{"suspended"===Wx.state&&(qx=!0,dM.emit("155",{isSuspended:!0}))}),Gx)),Qx(),document.addEventListener("click",zx)):"interrupted"===Wx.state?Qx():(Jx&&(BP.addNumber({key:507800,value:Aw()-Jx,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Jx=0),-1!==Kx&&(clearTimeout(Kx),Kx=-1,qx&&(qx=!1,dM.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",zx),document.removeEventListener("click",zx))},Yx=0,Xx=-1;function Qx(){return new Promise(((e,t)=>{if("running"===Wx.state)return e();Date.now()-Yx<1e3?(clearTimeout(Xx),Xx=setTimeout((()=>{Yx=Date.now(),Wx.resume().then(e,t)}),1e3)):(clearTimeout(Xx),Yx=Date.now(),Wx.resume().then(e,t))})).catch((e=>{_M.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",zx)}))}document.addEventListener("click",zx);var Zx=e=>Wx,$x=class{constructor(e){this.name=e,Sb(this,"node"),Sb(this,"node2"),Sb(this,"pre",new Set),Sb(this,"next",new Set),Sb(this,"context"),Sb(this,"connectedNodes",new Set),Sb(this,"nextInputChannelMap",new Map),Sb(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(e){this._channelCount=e,this.setChannelCount(this.node,e),this.setChannelCount(this.node2,e),this.next.forEach((t=>t.channelCount=e))}setChannelCount(e,t){!e||e instanceof ScriptProcessorNode||(e.channelCountMode="explicit",e.channelCount=t||this.channelCount||1)}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.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(Xk){_M.error(Xk)}}setNode(e,t){var i;if(!this.node)try{null==(i=this.context)||i.addMixWeight(),this.node=e,this.setChannelCount(this.node),t&&(this.node2=t,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),BP.addSuccessEvent({key:502701})}catch(AM){_M.error(AM),BP.addFailedEvent({key:502701,error:AM})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),BP.addSuccessEvent({key:502702})}catch(zb){_M.error(zb),BP.addFailedEvent({key:502702,error:zb})}}preNodeReconnect(){this.pre.forEach((e=>{e.node?e.reconnect():e.preNodeReconnect()}))}connectNext(e){this.next.forEach((t=>{let i=this.nextInputChannelMap.get(t);e._connect(t.node,i)||t.connectNext(e)}))}_connect(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return!(!this.node||!e)&&((this.node2||this.node).connect(e,0,t),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(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return this.next.add(e),e.pre.add(this),this.nextInputChannelMap.set(e,t),e}},eV=class extends $x{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,Sb(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}},tV=class{constructor(){Sb(this,"source",new $x),Sb(this,"gain",new $x),Sb(this,"destination",new $x)}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(Zx().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.replaceNode(oV(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}},iV=class extends tV{constructor(e){super(),this.context=e,Sb(this,"aec",new $x("aec")),Sb(this,"mixNode",new $x("mixNode")),Sb(this,"silentNode",new $x("silentNode")),Sb(this,"denoiser",new $x("denoiser")),Sb(this,"voiceChanger",new $x("voiceChanger")),this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.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.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.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()}},rV=class{constructor(){Sb(this,"audioContext",Zx()),Sb(this,"destination",this.audioContext.createMediaStreamDestination()),Sb(this,"inputs",new Set),Sb(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]}},nV=new WeakMap;function oV(e){let t=nV.get(e);if(t)return t;let i=Zx();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return nV.set(e,t),t}var sV=class e{constructor(e){Sb(this,"_volume",0),Sb(this,"_volumeDb",0),Sb(this,"_log"),Sb(this,"_scriptProcessorNode",null),Sb(this,"_audioWorkletNode",null),Sb(this,"_interval",200),Sb(this,"ready",this.preload());let{log:t}=e;this._log=t,dM.on(hM.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=Hx(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(IM){this._log.error("volumeMeter init audio worklet error: ".concat(IM)),px.logFailedEvent({userId:this._log.userId,eventType:Zk.LOAD_WORKLET,error:IM}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Zx().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(IM){this._log.error("volumeMeter init script processor error: ".concat(IM))}}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,dM.off(hM.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})}};Sb(sV,"lastMessageTime",0),Sb(sV,"audioContext",Zx()),Sb(sV,"workletReady");var aV=sV,cV=class extends $x{constructor(e){super(),Sb(this,"_volumeMeter"),this._volumeMeter=new aV(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return Ab(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()}}},lV=aV,dV=vb(Rb(),1),uV=e=>t=>t.deviceId===e,hV=class{constructor(e,t){Sb(this,"kind"),Sb(this,"type"),Sb(this,"devices",[]),this.kind=e,this.type=t}update(e,t){let i=e.filter((e=>e.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase())));1===this.devices.length&&_V(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(uV(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");_M.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(uV(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");_M.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},pV=class extends dV.EventEmitter{constructor(){super(),Sb(this,"audioInputs",new hV(Sk.AUDIO,"Input")),Sb(this,"videoInputs",new hV(Sk.VIDEO,"Input")),Sb(this,"audioOutputs",new hV(Sk.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||ax.run("interval",(()=>{this.update()}),{delay:1e4}))}init(){fV().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield fV(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},mV=Qb||Xb?null:new pV;function _V(e){return e.deviceId===e.groupId&&""===e.groupId}function fV(){return Ab(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(zP()||!KP())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{_V(e)&&(e.kind===Sk.AUDIO_INPUT?i.audio=!0:e.kind===Sk.VIDEO_INPUT&&(i.video=!0))})),2===e&&(i.audio=!1),1===e&&(i.video=!1),i.audio||i.video){let e;try{e=yield navigator.mediaDevices.getUserMedia(i),i.audio&&Qx()}catch(AM){_M.debug("capture before getDevices failed: ",AM)}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&&yV.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function gV(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return mV.update(e?1:0).then((e=>e.audioInputs.devices))}function EV(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return mV.update(e?2:0).then((e=>e.videoInputs.devices))}var TV=!1;function vV(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Ab(this,null,(function*(){return(RN||MO)&&(e=!1),mV.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var yV=new Set;function SV(e,t){return Ab(this,null,(function*(){let i=(yield gV()).find((e=>e.deviceId===_D));return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t}))}var IV,AV=class extends tV{constructor(e){super(),this.log=e,Sb(this,"volumeMeter"),Sb(this,"volumeMeterAfter3A"),Sb(this,"volumeDestination"),Sb(this,"analyser",new eV),this.volumeMeter=new cV({log:this.log}),this.volumeMeterAfter3A=new cV({log:this.log}),this.volumeDestination=new $x,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},RV=class e extends gx{constructor(e){super(e,Sk.AUDIO),Sb(this,"_outputDeviceId"),Sb(this,"_volume",1),Sb(this,"_destination",Zx().createMediaStreamDestination()),Sb(this,"pipeline"),Sb(this,"volumeMeterMode","worklet"),this.mode=0,this.pipeline=new AV(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(("15.2"===VO||"15.3"===VO||"15.4"===VO)&&this.muted)return void this._log.info("audioElement is muted.");let t=IV||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,hw(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),t===IV&&(IV=void 0),this.bindElementEvents()}play(t){return Ab(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(),this.pipeline.volumeMeterAfter3A.init()):"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(Zx().createAnalyser()),function(){Ab(this,null,(function*(){try{TV||(TV=!0,_M.info("speakers:".concat((yield vV()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(e){}}))}(),Ib(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 Ab(this,null,(function*(){var t,i;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield null==(i=(t=this.element).setSinkId)?void 0:i.call(t,e))}))}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()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},CV=class extends RV{setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(cx.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)}},bV=class extends RV{constructor(e){super(e),Sb(this,"_sourceElement"),Sb(this,"_output",new $x),this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Zx().destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,i,r;(null==(i=null==(t=this.element)?void 0:t.error)?void 0:i.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(cx.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=(null==(r=e.getSettings())?void 0:r.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?this.element?(this._log.info("set element volume: ".concat(e)),this.element.volume=e):this._log.info("set element volume: no element"):RN||(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),hx(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&&PO&&(IV=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},kV=class extends tx{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:o=(1===r?bV:Bx)}=e;var s;super(),Sb(this,"id",fM()),Sb(this,"userId",""),Sb(this,"isRemote"),Sb(this,"mediaType"),Sb(this,"room"),Sb(this,"user"),Sb(this,"_log"),Sb(this,"_inputTrack"),Sb(this,"_outputTrack"),Sb(this,"isPlayCalled"),Sb(this,"container",null),Sb(this,"player"),Sb(this,"subVideoPlayerMap"),Sb(this,"muted",!1),Sb(this,"abortCtrl"),Sb(this,"objectFit","cover"),Sb(this,"mirror"),Sb(this,"rotation"),Sb(this,"isScreen",!1),Sb(this,"manager"),Sb(this,"trackSettings"),Sb(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=_M.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=n||this.room)?void 0:s.userId,remoteUserId:this instanceof dB?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof dB}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(cx.PLAYER_STATE_CHANGED,(e=>{dM.emit(hM.PLAYER_STATE_CHANGED,fb({track:this},e)),this.emit("player-state-changed",e)})),this.kind===Sk.VIDEO&&(this.player.on(cx.LOADED_DATA,(()=>{this.emitFirstVideoFrameEvent(cx.LOADED_DATA),dM.emit(hM.VIDEO_LOADED_DATA,{track:this})})),this.player.on(cx.LOADED_META_DATA,(()=>{this.emitFirstVideoFrameEvent(cx.LOADED_META_DATA)})),this.player.on(cx.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))})),this.player.on(cx.RESIZE,(e=>{this.emit("video-size-changed",fb({userId:this.userId,streamType:2===this.mediaType?"auxiliary":"main"},e))}))),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(cx.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||_M}get kind(){return 1===this.mediaType?Sk.AUDIO:Sk.VIDEO}get strMediaType(){return 4===this.mediaType?Sk.VIDEO:2===this.mediaType?Sk.SCREEN:Sk.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&(!this.mediaTrack.muted&&"live"===this.mediaTrack.readyState&&this.mediaTrack.enabled)}play(e,t){return Ab(this,null,(function*(){let i=_w(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!dw(t.muted)&&this.setPlayerMute(t.muted),t&&!dw(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof Bx&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),_w(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!dw(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===Sk.VIDEO)&&this.setPlayerMute(!0),t&&!dw(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof Bx&&(this.player.setObjectFit(this.objectFit),t&&!dw(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof Bx&&this.player.setContainer(i)),dM.emit(hM.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),_w(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(kM){throw this.handleAutoPlayFailed(kM),kM}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==Sk.VIDEO||dw(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(pw(this.mirror))return i.setViewMirror(this.mirror),void(!this.isRemote&&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 Ab(this,null,(function*(){if(!this._outputTrack||this.kind===Sk.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,i)=>{var r;e.find((e=>i===e))||(t.stop(),null==(r=this.subVideoPlayerMap)||r.delete(i))}));for(let[r,n]of e.entries()){let e=this.subVideoPlayerMap.get(n);e?t&&(dw(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new Bx({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 Ab(this,null,(function*(){var e;this.isPlayCalled&&(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),dM.emit(e?hM.TRACK_MUTED:hM.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){ux(e,e).add(Sk.MUTE,this.onTrackMuted).add(Sk.UNMUTE,this.onTrackUnmuted).add(Sk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Sk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){hx(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 Fx;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 Bx?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var t,i,r;if(this.isFirstVideoFrameEmitted)return;let n=null==(t=this.mediaTrack)?void 0:t.getSettings(),o=(null==n?void 0:n.width)||(null==(i=this.player.element)?void 0:i.videoWidth)||0,s=(null==n?void 0:n.height)||(null==(r=this.player.element)?void 0:r.videoHeight)||0;e===cx.RESIZE&&!o&&!s||e===cx.LOADED_META_DATA&&!o&&!s||(e===cx.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,Yw(this.rotation)&&([o,s]=[s,o]),this.emit("first-video-frame",{width:o,height:s,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"))}};yb([ZL([],tx.INIT,{sync:!0})],kV.prototype,"close",1);var DV=Object.prototype.hasOwnProperty;var wV=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(ow(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(DV.call(e,t))return!1;return!0}return!1},NV=hN({retryFunction:function(e){return Ab(this,null,(function*(){let t=function(e){return{audio:MV(e),video:PV(e)}}(e);_M.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId","groupId"];t.audio&&(i=yield gV(),_M.info("microphones: ".concat(Vw(i.map((e=>gb(fb({},e),{groupId:e.groupId.substring(0,8)}))),{keysToInclude:n})))),t.video&&(r=yield EV(),_M.info("cameras: ".concat(Vw(r,{keysToInclude:n}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return RL&&e.getTracks().forEach((e=>{_M.info("".concat(e.kind," capabilities: ").concat(Vw(e.getCapabilities(),{keysToInclude:SD})))})),t.audio&&Qx(),e}catch(kM){let{message:n}=kM;throw"NotFoundError"===kM.name&&(e.video&&r&&0===r.length&&(n=kP({key:AP.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(n=kP({key:AP.MICROPHONE_NOT_FOUND}))),new Ub({code:xb.INITIALIZE_FAILED,name:kM.name,message:n,constraint:kM.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,retryFuncArgs:n,retriedCount:o}=e,s=o+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===s?(n[0].video&&(n[0].maxResolution=!1,(!MO||n[0].width*n[0].height<=2073600)&&n[0].frameRate&&(n[0].frameRate=n[0].frameRate>10?10:5)),n[0].retryWhenExactFailed&&n[0].useExactDeviceId&&(n[0].useExactDeviceId=!1)):2===s?n[0].useDeviceIdOnly=!0:3===s&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&OV(n[0].microphoneId,!1),n[0].cameraId&&OV(n[0].cameraId,!0)},onRetrying:e=>{_M.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{px.logFailedEvent({eventType:Zk.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{px.logSuccessEvent({eventType:Zk.GET_USER_MEDIA_RETRY}),px.uploadEvent({log:"stat-".concat(Zk.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function OV(e,t){return Ab(this,null,(function*(){let i=(t?yield EV():yield gV()).find((t=>t.deviceId===e));i&&lw(i.getCapabilities)&&_M.warn(Vw(i.getCapabilities(),{keysToInclude:SD}))}))}function MV(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!wV(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(hw(e.channelCount)&&(t.channelCount=e.channelCount),pw(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),pw(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),pw(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!wV(t)||t)}function PV(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&&!wV(i)?i:(e.width&&(i.width={ideal:e.width},t&&!wN&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!wN&&(i.height.max=e.height)),wN&&aO&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!wV(i)||i)}var LV=NV;function xV(e){return FV(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Ab(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function VV(e){return FV(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Ab(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function UV(e){return FV(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Ab(this,null,(function*(){try{return yield t.apply(this,r)}catch(AM){e.call(this,AM)}}))}))}function FV(e){return function(t,i,r){return r.value=e(r.value,i),r}}var BV=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&_M.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{_M.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),HV=0,WV=class{constructor(){Sb(this,"log",_M.createLogger({id:"fq".concat(++HV)})),Sb(this,"isRunning",!1),Sb(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=fb({},e),o=new Promise(((e,t)=>{n.resolve=e,n.reject=t}));return n.promise=o,t?this.length<=1?this.queue.push(n):null==(r=null==(i=this.lastQueueItem)?void 0:i.promise)||r.then(n.resolve,n.reject):this.queue.push(n),this.log.debug("push ".concat(this.length)),this.isRunning||this.callNext(),o}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length)),e}callNext(){if(this.isRunning||0===this.length)return;this.log.debug("callNext ",this.length);let{fn:e,args:t,context:i,resolve:r,reject:n}=this.queue[0];this.isRunning=!0,e.apply(i,t).then(r,n).finally((()=>{this.isRunning=!1,this.shift(),this.callNext()}))}},GV=new WeakMap,jV=new WeakMap;function JV(){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=GV.get(this)||new WV;for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return GV.set(this,t),t.push({fn:n,args:r,context:this},e)},r}}function KV(e){return function(t,i,r){let n=r.value;return r.value=function(){var t,i,r;let o=[];for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return null==(i=null==(t=GV.get(this))?void 0:t.queue)||i.forEach((e=>o.push(e))),null==(r=jV.get(this))||r.forEach((e=>null==e?void 0:e.queue.forEach((e=>o.push(e))))),o.forEach((t=>{t.reject(new Ub({code:xb.API_CALL_ABORTED,message:e}))})),GV.delete(this),jV.delete(this),n.apply(this,a)},r}}function qV(e){return function(t,i,r){let n=r.value,o=t=>e(...t);return r.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=jV.get(this)||new Map,s=r.get(o(t))||new WV;return r.set(o(t),s),jV.set(this,r),s.push({fn:n,args:t,context:this})},r}}function zV(e,t){return FV(((i,r)=>function(){let r=e;try{for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let e=i.apply(this,o),a=Aw();return Ew(e)?e.then((e=>(t?BP.addSuccessEvent({key:r,cost:Aw()-a}):BP.addSuccessEvent({key:r}),e))).catch((e=>{throw BP.addFailedEvent({key:r,error:e}),e})):(BP.addSuccessEvent({key:r}),e)}catch(Yb){throw BP.addFailedEvent({key:r,error:Yb}),Yb}}))}var YV={};function XV(){}Tb(YV,{Events:()=>uU,Inspect:()=>iU,LastSink:()=>rU,Sink:()=>nU,Subscribe:()=>oU,TimeoutError:()=>hU,audit:()=>fF,bindCallback:()=>JU,bindNodeCallback:()=>KU,buffer:()=>RU,bufferCount:()=>AU,bufferTime:()=>$F,call:()=>QV,catchError:()=>tB,combineLatest:()=>vU,concat:()=>gU,concatMap:()=>HF,concatMapTo:()=>WF,count:()=>ZU,create:()=>aU,debounce:()=>TF,debounceTime:()=>vF,defer:()=>kU,delay:()=>eB,deliver:()=>cU,dispose:()=>$V,elementAt:()=>yF,empty:()=>YU,every:()=>CF,exhaustMap:()=>YF,exhaustMapTo:()=>XF,filter:()=>iF,find:()=>SF,findIndex:()=>IF,first:()=>AF,fromAnimationFrame:()=>GU,fromArray:()=>OU,fromEvent:()=>VU,fromEventPattern:()=>xU,fromFetch:()=>FU,fromIterable:()=>BU,fromPromise:()=>UU,fromReadableStream:()=>WU,fromReader:()=>HU,groupBy:()=>QF,identity:()=>ZV,ignoreElements:()=>rF,iif:()=>TU,inspect:()=>eU,interval:()=>MU,last:()=>RF,map:()=>wF,mapTo:()=>NF,max:()=>$U,merge:()=>_U,mergeMap:()=>JF,mergeMapTo:()=>KF,min:()=>eF,never:()=>qU,nothing:()=>XV,of:()=>NU,pairwise:()=>kF,pipe:()=>sU,race:()=>fU,range:()=>jU,reduce:()=>QU,retry:()=>aB,scan:()=>bF,share:()=>mU,shareReplay:()=>EU,skip:()=>cF,skipUntil:()=>lF,skipWhile:()=>dF,startWith:()=>SU,subject:()=>bU,subscribe:()=>nB,sum:()=>tF,switchMap:()=>xF,switchMapTo:()=>UF,take:()=>nF,takeLast:()=>aF,takeUntil:()=>oF,takeWhile:()=>sF,tap:()=>oB,throttle:()=>mF,throwError:()=>zU,timeInterval:()=>ZF,timeout:()=>sB,timer:()=>PU,toPromise:()=>iB,toReadableStream:()=>rB,withLatestFrom:()=>IU,zip:()=>yU});var QV=e=>e(),ZV=e=>e;function $V(){this.dispose()}var eU=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,tU=1,iU=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new dU(e,this,this.streamId++);return uU.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},rU=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=XV,this.error=XV,this.next=XV,this.dispose=XV,this.subscribe=XV,this.doDefer()}subscribe(e){return e instanceof iU?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(QV),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}},nU=class extends rU{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)}},oU=class extends rU{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:XV,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:XV,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:XV;if(super(),this._next=t,this._error=i,this._complete=r,this.then=XV,e instanceof iU){let n={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{uU.defer(n,0)})),uU.create(n),uU.pipe(n),this.sourceId=n.id,this.subscribe(e),uU.subscribe({id:n.id,end:!0}),t==XV?this._next=e=>uU.next(n,0,e):this.next=e=>{uU.next(n,0,e),t(e)},r==XV?this._complete=()=>uU.complete(n,0):this.complete=()=>{this.dispose(),uU.complete(n,0),r()},i==XV?this._error=e=>uU.complete(n,0,e):this.error=e=>{this.dispose(),uU.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 sU(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 aU(e,t,i){if(eU()){let r=Object.defineProperties(Object.setPrototypeOf(e,iU.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}});uU.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof iU&&uU.addSource(r,t)}return r}return e}function cU(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 iU){let n=aU((t=>{let o=new e(t,...r);o.sourceId=n.id,o.subscribe(i)}),t,arguments);return n.source=i,uU.pipe(n),n}return t=>i(new e(t,...r))}}}function lU(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var dU=class extends nU{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{uU.defer(this.source,this.id)}))}next(e){uU.next(this.source,this.id,e),this.sink.next(e)}complete(){uU.complete(this.source,this.id),this.sink.complete()}error(e){uU.complete(this.source,this.id,e),this.sink.error(e)}},uU={addSource(e,t){lU("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){lU("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;lU("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){lU("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){lU("defer",{id:e.id,streamId:t})},pipe(e){lU("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){lU("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=tU++),lU("create",{name:e.toString(),id:e.id})}},hU=class extends Error{constructor(e){super("timeout after ".concat(e,"ms")),this.timeout=e}},pU=class extends rU{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 mU(){return e=>{let t=new pU(e);if(e instanceof iU){let i=aU((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,uU.pipe(i),i}return aU(t.add.bind(t),"share",arguments)}}function _U(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return aU((e=>{let i=new nU(e),r=t.length;i.complete=()=>{0==--r&&e.complete()},t.forEach(i.bindSubscribe)}),"merge",arguments)}function fU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return aU((e=>{let i=new Map;t.forEach((t=>{let r=new nU(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 gU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return aU((e=>{let i=0,r=t.length,n=new nU(e);n.complete=()=>{i<r&&!n.disposed?(n.doDefer(),n.subscribe(t[i++])):e.complete()},n.complete()}),"concat",arguments)}function EU(e){return t=>{let i=new pU(t),r=[];return i.next=function(t){r.push(t),r.length>e&&r.shift(),this.sinks.forEach((e=>e.next(t)))},aU((e=>{e.defer((()=>i.remove(e))),r.forEach((t=>e.next(t))),i.add(e)}),"shareReplay",arguments)}}function TU(e,t,i){return aU((r=>e()?t(r):i(r)),"iif",arguments)}function vU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return aU((e=>{let i=t.length,r=i,n=i,o=new Array(i),s=()=>{0==--n&&e.complete()};t.forEach(((t,i)=>{let n=new nU(e);n.next=t=>{0==--r?(n.next=t=>{o[i]=t,e.next(o)},n.next(t)):o[i]=t},n.complete=s,n.subscribe(t)}))}),"combineLatest",arguments)}function yU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return aU((e=>{let i=t.length,r=i,n=new Array(i),o=()=>{0==--r&&e.complete()};t.forEach(((t,i)=>{let r=new nU(e),s=[];n[i]=s,r.next=t=>{s.push(t),n.every((e=>e.length))&&e.next(n.map((e=>e.shift())))},r.complete=o,r.subscribe(t)}))}),"zip",arguments)}function SU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>aU((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 IU=cU(class extends nU{constructor(e){super(e);let t=new nU(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=XV,t.subscribe(vU(...r))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},"withLatestFrom"),AU=cU(class extends nU{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"),RU=cU(class extends nU{constructor(e,t){super(e),this.buffer=[];let i=new nU(e);i.next=t=>{e.next(this.buffer),this.buffer=[]},i.complete=XV,i.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),CU=function(e,t,i,r){return new(i||(i=Promise))((function(n,o){function s(e){try{c(r.next(e))}catch(t){o(t)}}function a(e){try{c(r.throw(e))}catch(t){o(t)}}function c(e){e.done?n(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(s,a)}c((r=r.apply(e,t||[])).next())}))};function bU(e){let t=arguments,i=mU()(aU((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=XV,i.complete=XV,i.error=XV,i}function kU(e){return aU((t=>t.subscribe(e())),"defer",arguments)}var DU=e=>t=>{setTimeout((()=>e(t)))},wU=e=>DU((t=>{for(let i=0;!t.disposed&&i<e.length;i++)t.next(e[i]);t.complete()}));function NU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return aU(wU(t),"of",arguments)}function OU(e){return aU(wU(e),"fromArray",arguments)}function MU(e){return aU((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}function PU(e,t){return aU((i=>{let r=0,n=setTimeout((()=>{if(i.removeDefer(o),i.next(r++),t){let e=setInterval((()=>i.next(r++)),t);i.defer((()=>{clearInterval(e)}))}else i.complete()}),e),o=()=>{clearTimeout(n)};i.defer(o)}),"timer",arguments)}function LU(e,t){return i=>{let r=e=>i.next(e);i.defer((()=>t(r))),e(r)}}function xU(e,t){return aU(LU(e,t),"fromEventPattern",arguments)}function VU(e,t){if("on"in e&&"off"in e)return aU(LU((i=>e.on(t,i)),(i=>e.off(t,i))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return aU(LU((i=>e.addListener(t,i)),(i=>e.removeListener(t,i))),"fromEvent",arguments);if("addEventListener"in e)return aU(LU((i=>e.addEventListener(t,i)),(i=>e.removeEventListener(t,i))),"fromEvent",arguments);throw"target is not a EventDispachter"}function UU(e){return aU((t=>{e.then(t.next.bind(t),t.error.bind(t))}),"fromPromise",arguments)}function FU(e,t){return aU(kU((()=>UU(fetch(e,t)))),"fromFetch",arguments)}function BU(e){return aU(DU((t=>{try{for(let i of e){if(t.disposed)return;t.next(i)}t.complete()}catch(zb){t.error(zb)}})),"fromIterable",arguments)}function HU(e){let t=i=>CU(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 aU((e=>{t(e)}),"fromReader",arguments)}function WU(e){return aU((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 GU(){return aU((e=>{let t=requestAnimationFrame((function i(r){e.disposed||(e.next(r),t=requestAnimationFrame(i))}));e.defer((()=>cancelAnimationFrame(t)))}),"fromAnimationFrame",arguments)}function jU(e,t){return aU((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 JU(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 aU((i=>{let n=r.concat((e=>(i.next(e),i.complete())));e.apply(t,n)}),"bindCallback",arguments)}function KU(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 aU((i=>{let n=r.concat(((e,t)=>e?i.error(e):(i.next(t),i.complete())));e.apply(t,n)}),"bindNodeCallback",arguments)}function qU(){return aU((()=>{}),"never",arguments)}function zU(e){return aU((t=>t.error(e)),"throwError",arguments)}function YU(){return aU((e=>e.complete()),"empty",arguments)}var XU=class extends nU{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)}},QU=cU(XU,"reduce"),ZU=e=>cU(XU,"count")(((t,i)=>e(i)?t+1:t),0),$U=()=>cU(XU,"max")(Math.max),eF=()=>cU(XU,"min")(Math.min),tF=()=>cU(XU,"sum")(((e,t)=>e+t),0),iF=cU(class extends nU{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"),rF=cU(class extends nU{next(e){}},"ignoreElements"),nF=cU(class extends nU{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&this.complete()}},"take"),oF=cU(class extends nU{constructor(e,t){super(e);let i=new nU(e);i.next=()=>e.complete(),i.complete=$V,i.subscribe(t)}},"takeUntil"),sF=cU(class extends nU{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):this.complete()}},"takeWhile"),aF=e=>QU(((t,i)=>(t.push(i),t.length>e&&t.shift(),t)),[]),cF=cU(class extends nU{constructor(e,t){super(e),this.count=t}next(e){0==--this.count&&(this.next=super.next)}},"skip"),lF=cU(class extends nU{constructor(e,t){super(e),e.next=XV;let i=new nU(e);i.next=()=>{i.dispose(),e.resetNext()},i.complete=$V,i.subscribe(t)}},"skipUntil"),dF=cU(class extends nU{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),uF={leading:!0,trailing:!1},hF=class extends nU{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)}},pF=class extends nU{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:uF;super(e),this.durationSelector=t,this.config=i,this._throttle=new hF(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=XV,this._throttle.complete(),super.complete()}},mF=cU(pF,"throttle"),_F={leading:!1,trailing:!0},fF=e=>cU(pF,"audit")(e,_F),gF=class extends nU{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},EF=class extends nU{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new gF(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()}},TF=cU(EF,"debounce"),vF=e=>cU(EF,"debounceTime")((t=>PU(e))),yF=cU(class extends nU{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"),SF=e=>t=>nF(1)(dF((t=>!e(t)))(t)),IF=cU(class extends nU{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"),AF=cU(class extends nU{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"),RF=cU(class extends nU{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"),CF=cU(class extends nU{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"),bF=cU(class extends nU{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"),kF=cU(class extends nU{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},"pairwise"),DF=class extends nU{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},wF=cU(DF,"map"),NF=e=>cU(DF,"mapTo")((t=>e)),OF=class extends nU{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()}},MF=class extends nU{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()}},PF=class extends OF{},LF=class extends MF{next(e){this.subInner(e,PF),this.next=e=>{this.currentSink.dispose(),this.subInner(e,PF)}}},xF=cU(LF,"switchMap");function VF(e){return(t,i)=>e((()=>t),i)}var UF=VF(cU(LF,"switchMapTo")),FF=class extends OF{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},BF=class extends MF{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(),FF),this.disposed&&0===this.sources.length&&this.currentSink.resetComplete()}tryComplete(){0===this.sources.length&&this.currentSink.resetComplete(),this.dispose()}},HF=cU(BF,"concatMap"),WF=VF(cU(BF,"concatMapTo")),GF=class extends OF{tryComplete(){this.context.inners.delete(this),super.dispose(),0===this.context.inners.size&&this.context.resetComplete()}},jF=class extends MF{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,GF),this.inners.add(this.currentSink)}tryComplete(){1===this.inners.size?this.inners.forEach((e=>e.resetComplete())):this.dispose()}},JF=cU(jF,"mergeMap"),KF=VF(cU(jF,"mergeMapTo")),qF=class extends OF{dispose(){this.context.resetNext(),super.dispose()}},zF=class extends MF{next(e){this.next=XV,this.subInner(e,qF)}},YF=cU(zF,"exhaustMap"),XF=VF(cU(zF,"exhaustMapTo")),QF=cU(class extends nU{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=bU(),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"),ZF=cU(class extends nU{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"),$F=cU(class extends nU{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"),eB=cU(class extends nU{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"),tB=cU(class extends nU{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),iB=()=>e=>new Promise(((t,i)=>{let r;new oU(e,(e=>r=e),i,(()=>t(r)))})),rB=()=>e=>{let t;return new ReadableStream({start(i){t=new oU(e,i.enqueue.bind(i),i.error.bind(i),i.close.bind(i))},cancel(){t.dispose()}})},nB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:XV,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:XV,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:XV;return r=>new oU(r,e,t,i)},oB=cU(class extends nU{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"),sB=cU(class extends nU{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout((()=>this.error(new hU(this.timeout))),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),aB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0;return t=>{if(t instanceof iU){let i=aU((r=>{let n=e,o=new nU(r);o.error=e=>{n-- >0?o.subscribe(t):r.error(e)},o.sourceId=i.id,o.subscribe(t)}),"retry",[e]);return i.source=t,uU.pipe(i),i}return i=>{let r=e,n=new nU(i);n.error=e=>{r-- >0?t(n):i.error(e)},t(n)}}},cB=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(cB||{}),lB=class e extends kV{constructor(e,t){super({mediaType:e,PlayerClass:t}),Sb(this,"isRemote",!1),Sb(this,"deviceId"),Sb(this,"groupId",""),Sb(this,"label",""),Sb(this,"sourceTrack"),Sb(this,"enableAutoSwitchWhenRecapturing",!0),Sb(this,"_isRecapturing",!1),Sb(this,"_lastRecaptureTime",0),Sb(this,"_onMuteTimeoutId",-1),Sb(this,"_encodeCheckTimeoutId",-1),Sb(this,"recaptureMode",0),Sb(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return"publishing"===this.state.toString()}get isPublished(){return"publish"===this.state}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){ux(e,e).add(Sk.MUTE,this.onTrackMuted).add(Sk.UNMUTE,this.onTrackUnmuted).add(Sk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Sk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){hx(e)}setStateToReady(){}capture(e){return Ab(this,null,(function*(){var t;try{let i,r=Aw();dM.emit(hM.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.sourceTrack)||t.stop(),i=yield LV(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.sourceTrack=n,this.updateDeviceIdInUse(),this.listenDeviceChange()),dM.emit(hM.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Aw()-r}),i}catch(AM){throw dM.emit(hM.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:AM}),this.log.error("getUserMedia error observed ".concat(AM)),AM}}))}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return null==(t=this.room)?void 0:t.replaceTrack(this)}get hasFlag(){var e,t;let i=Dw((null==(e=this.room)?void 0:e.localPublishFlag)||0,(null==(t=this.room)?void 0:t.userId)||"");return 4===this.mediaType&&i.hasVideo||1===this.mediaType&&i.hasAudio||2===this.mediaType&&i.hasAuxiliary}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),Promise.all([t,new Promise(((t,i)=>Ab(this,null,(function*(){var r,n;this.hasFlag?t():sU(VU(e,"local-publish-flag-changed"),iF((()=>this.hasFlag)),oF(_U(VU(this,tx.INIT),VU(this,"ready"))),nB(t)),!(((null==(n=null==(r=this.room)?void 0:r.networkQuality)?void 0:n.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout((()=>{var e,t,r,n,o,s;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===Sk.AUDIO,t=this.stat.bytesSent>0;if(BP[t?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),!e){let e={H264:513704,H265:513705,VP8:513706}[(null==(n=null==(r=this.room)?void 0:r.videoCodec)?void 0:n.toUpperCase())||"H264"];e&&BP[t?"addSuccessEvent":"addFailedEvent"]({key:e})}t||(BP.addEnum({key:e?503701:513703,value:nM()}),px.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(tM()||sM()),userId:this.userId}),this.log.warn(e?"encode failed":"".concat(null==(s=null==(o=this.room)?void 0:o.videoCodec)?void 0:s.toUpperCase()," encode failed")),this.emit("6",this),i(new Ub({message:"".concat(this.strMediaType," encode failed"),code:e?xb.AUDIO_ENCODE_FAILED:xb.VIDEO_ENCODE_FAILED})))}}),5e3))}))))])}unpublish(){this.room&&this.room.localTracks.delete(this),dM.emit(hM.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return Ab(this,null,(function*(){if(this.sourceTrack&&AL){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:i}=this.sourceTrack;(yield function(e){return Ab(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==Sk.AUDIO||t!==_D||(yield SV(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),fV().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.sourceTrack||this.kind===Sk.AUDIO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("麦克风"))return!0;let i="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(Sk.AUDIO_INPUT);return!!yV.has(i)}(this.sourceTrack)||this.kind===Sk.VIDEO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let i="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(Sk.VIDEO_INPUT);return!!yV.has(i)}(this.sourceTrack)||this._isRecapturing||e&&aO&&MO)}onTrackMuted(){if(super.onTrackMuted(),BV(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<yD)return void setTimeout((()=>this.onTrackMuted()),yD);this._onMuteTimeoutId=setTimeout((()=>Ab(this,null,(function*(){var e;if(null!=(e=this.sourceTrack)&&e.muted){if((RN||CN)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return Ab(this,null,(function*(){if(Ib(e.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&0===this.recaptureMode){if(Date.now()-this._lastRecaptureTime<yD)return void setTimeout((()=>this.onTrackEnded()),yD);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return Ab(this,null,(function*(){var t;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying"),null==(t=this.sourceTrack)||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 gV():yield EV()).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}),dM.emit(hM.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),dM.emit(hM.LOCAL_TRACK_RECAPTURE,{track:this,error:e})}))}))}getRecoverCaptureDeviceId(){return Ab(this,null,(function*(){let e=this instanceof fB;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(uB.get(t)||0)+1;if(uB.set(t,i),i>=3&&this.enableAutoSwitchWhenRecapturing){let r=e?(yield EV()).find((e=>!uB.has(e.deviceId))):(yield gV()).find((e=>!uB.has(e.deviceId)));r&&(this.log.warn("".concat(t," capture fail ").concat(i," times, change new ").concat(r.deviceId)),t=r.deviceId)}}return t}))}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),null==(e=this.manager)||e.removeInput(this)}close(){super.close(),this.stopCapture()}};yb([ZL(tx.INIT,"ready",{ignoreError:!0,sync:!0})],lB.prototype,"setStateToReady",1),yb([JV()],lB.prototype,"capture",1),yb([ZL("ready","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),dM.emit(hM.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(e){let t="error";if(e.cause instanceof Ub){let i=e.cause;i.message.includes("timeout")?t="timeout":i.code===xb.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),zV(521714,!1)],lB.prototype,"publish",1),yb([FV((e=>function(){return Ab(this,null,(function*(){let t="publish"===this.state?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)}))})),ZL([],"ready",{sync:!0})],lB.prototype,"unpublish",1);var dB=lB,uB=new Map;dM.on(hM.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&uB.delete(e.track.deviceId)}));var hB=class e extends dB{constructor(e){super(1,CV),Sb(this,"mediaType",1),Sb(this,"volume",0),Sb(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),Sb(this,"playerMuted",!0),Sb(this,"pipeline"),Sb(this,"earMonitorGainNode",new $x),Sb(this,"_output",new $x),Sb(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),Sb(this,"mixedAudioReferenceMap",new Map),Sb(this,"isAudioContextLongSuspended",!1),this.manager=e,this.pipeline=new iV(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),dM.on(hM.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return lV.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}getInternalAudioLevelAfter3A(){if(this.pipeline.aec.node||this.pipeline.denoiser.node)return this.player.getInternalAudioLevelAfter3A()}setInputMediaStreamTrack(t){return Ab(this,null,(function*(){let i=this.trackSettings||{};BP.addEnum({key:501701,value:i.channelCount||0,useUV:!1}),BP.addEnum({key:501702,value:i.sampleRate||0,useUV:!1}),BP.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.source.channelCount=n||1,this.pipeline.replaceSource(t),yield Ib(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 Ab(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource){if(e!==_D)return;if(yield SV(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),dM.emit(hM.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(Xk){throw this.log.error("switch microphone failed ".concat(Xk)),this.deviceId&&this.recapture(this.deviceId),Xk}}}))}listenDeviceChange(){mV&&!mV.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&mV.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return Ab(this,null,(function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(cB[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){rH(this.userId,{eventId:2003,param1:6,streamType:1});let e=yield gV();e[0]?this.recapture(e[0].deviceId):t=!0}t&&mV.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){1===this.recaptureMode&&e.deviceId!==this.deviceId||(mV.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}update3A(e){return Ab(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:n}=e;return function*(){let e=t.sourceTrack||t.mediaTrack;if(!e)return;let o=e.getConstraints(),s=!1;!dw(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,o.echoCancellation=i,s=!0),!dw(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,o.noiseSuppression=r,s=!0),!dw(n)&&n!==t.profile.autoGainControl&&(t.profile.autoGainControl=n,o.autoGainControl=n,s=!0),s&&(wN||MO?yield e.applyConstraints(o).catch((e=>t._log.warn("update3A failed: ",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&&BP.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),RN&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Zx().createGain()),this._output.setNode(Zx().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!MO&&!RN)return this.update3A({echoCancellation:e})}addDenoiser(e){var t;NO<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(BP.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1))}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info("mixAudioReference() => ".concat(t));let i=oV(e),r=new $x,n=Zx().createGain();n.gain.value=1;let o=new $x;r.pipeTo(o).pipeTo(this.pipeline.mixNode),r.setNode(i),o.setNode(n),this.mixedAudioReferenceMap.set(t,[r,o])}unMixAudioReference(e){let[t,i]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info("unMixAudioReference() => ".concat(e)),t.deleteNode(),null==i||i.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[i,r]=this.mixedAudioReferenceMap.get(e)||[];null!=r&&r.node&&(r.node.gain.value=t/100,this.log.info("setAudioReferenceVolume() => ".concat(e," ").concat(r.node.gain.value)))}addAudioProcessor(e,t,i){this.pipeline.silentNode.setNode(i),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach((e=>{let[t,i]=e;t.deleteNode(),i.deleteNode()})),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),mV.off("audioInputAdded",this.handleMicrophoneAdded,this),mV.off("audioInputRemoved",this.handleMicrophoneRemoved,this),dM.off(hM.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(t){return Ab(this,null,(function*(){try{yield Ib(e.prototype,this,"recapture").call(this,t)}catch(Xk){let r=(yield gV()).find((e=>e.deviceId!==t));if(!r)throw Xk;yield Ib(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))}handleAudioContextLongSuspended(e){let{isSuspended:t}=e;if(this.pipeline.isProcessEnabled)if(t){this.isAudioContextLongSuspended=!0,this.log.warn("context has suspended for ".concat(1.5," seconds, change to source audio").concat(PO?"":", non-Safari"));let e=this.sourceTrack||this.mediaTrack;e&&this.setOutputMediaStreamTrack(e)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}},pB=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,i=[],r=0;for(let o=e;o<=t;o++){let e=this.dataView.getInt8(o);switch(e){case 0:case 1:case 2:case 3:2===r&&(i.push(3),r=0),0==e?r++:r=0,i.push(e);break;default:r=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],r=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:r++,i.push(this.dataView.getInt8(o));break;case 3:2!==r&&i.push(this.dataView.getInt8(o)),r=0;break;default:i.push(this.dataView.getInt8(o)),r=0}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}get isSEI(){return 6===this.dataView.getUint8(4)}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let n=6;n<this.dataView.buffer.byteLength;n++){let i=this.dataView.getUint8(n);if(t++,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),r=new DataView(i);for(let n=0;n<i.byteLength;n++,t++)r.setInt8(n,this.dataView.getInt8(t));return r}},mB=class{constructor(){Sb(this,"_seiMessageList",[]),Sb(this,"_smallSeiMessageList",[]),Sb(this,"_seiPayloadType",243)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),r=t%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let s=0;s<i;s++)n.push(255);n.push(r);let o=new DataView(e);return n.push(...new Uint8Array(o.buffer)),n.push(128),new pB(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),o=new ArrayBuffer(n+e.data.byteLength),s=new DataView(o),a=new DataView(e.data),c=0;for(let e=0;e<r.length;e++)for(let t=0;t<r[e].dataView.byteLength;t++)s.setInt8(c++,r[e].dataView.getInt8(t));for(let i=0;i<e.data.byteLength;i++)s.setInt8(c++,a.getInt8(i));return e.data=o,r.length}return 0}},_B=class e extends dB{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,Bx),Sb(this,"profile",fb({},Tk)),Sb(this,"avoidCropping",!1),Sb(this,"_scaleResolutionDownBy"),Sb(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0}),Sb(this,"small"),Sb(this,"isNeedToSetBandwidth"),Sb(this,"muteImage"),Sb(this,"manager"),Sb(this,"_seiCodec",new mB),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(gb(fb({},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(AL&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return(null==(e=this._inputTrack)?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}setMute(t){return Ab(this,null,(function*(){var i,r,n;if(uw(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,Ib(e.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield null==(n=this.manager)?void 0:n.deleteWatermark("mute"),this.muteImage=void 0),Ib(e.prototype,this,"setMute").call(this,t)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:r=!0,customSource:n,retryWhenExactFailed:o=!0}=e;return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:o,customSource:n})}setProfile(e){let t=this.fallbackProfile(e);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(gb(fb({},this.profile),{width:1920,height:1080})))}applyProfile(){return Ab(this,null,(function*(){var e;if(!this.mediaTrack)return;let{width:t=0,height:i=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=t*i,n=this.settings,o=n.height!==this.profile.height||n.width!==this.profile.width||n.frameRate!==this.profile.frameRate;if(o&&(16===BO&&this.deviceId?yield this.recapture(this.deviceId):(yield null==(e=this.sourceTrack||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;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),i=e*t;return o&&i&&r&&i===r?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:Sk.VIDEO,videoType:Sk.BIG})}}))}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return AL&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:zw(this.settings,this.profile)}isAllowed2k4k(e){var t;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||1===(null==(t=this.room.scheduleResult.trtcAutoConf)?void 0:t["2k4k"])}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return Ab(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};if("user"===e||"environment"===e){t.facingMode=e;try{if((fO||RO)&&"environment"===e&&CL){let e=(yield EV(!0)).map((e=>{var t;return gb(fb({},e),{capabilities:null==(t=e.getCapabilities)?void 0:t.call(e)})})).filter((e=>{var t,i;return null==(i=null==(t=e.capabilities)?void 0:t.facingMode)?void 0:i.includes("environment")})),i=e[0];e.forEach((e=>{var t,r,n,o;let{capabilities:s}=e;(null!=(t=s.width)&&t.max&&null!=(r=s.height)&&r.max?s.width.max*s.height.max:0)>(null!=(n=i.capabilities.width)&&n.max&&null!=(o=i.capabilities.height)&&o.max?i.capabilities.width.max*i.capabilities.height.max:0)&&(i=e)})),null!=i&&i.capabilities&&(delete t.facingMode,this._log.info("switch to max res camera",i),t.deviceId=i.deviceId)}}catch(AM){this._log.warn("get max res camera failed",AM)}}else t.deviceId=e;this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),dM.emit(hM.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(Xk){throw this.log.error("switch camera failed ".concat(Xk)),this.deviceId&&this.recapture(this.deviceId),Xk}}))}updateSmallConfig(e){var t,i;this._log.info("update small stream config: ".concat(JSON.stringify(e)));let r=!this.small;this.small=this.fallbackProfile(e,!0),null==(t=this.manager)||t.update(),r&&(null==(i=this.room)||i.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=e.width>e.height,r=fb({},e);return e.width*e.height<=19200&&CN&&kO&&(this.log.warn("".concat(t?"small ":"","resolution is ").concat(e.width,"*").concat(e.height,", fallback to 240*180 for android chrome")),r.width=i?240:180,r.height=i?180:240,r.bitrate=Math.max(e.bitrate,150)),e.width*e.height>921600&&GO&&(r.width=i?1280:720,r.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),UO(VO,"14.3")&&FO(VO,"14.0",!0)&&this.on("7",(()=>{let e=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=e?640:480,this.profile.height=e?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>230400&&(this.profile.width=e?640:360,this.profile.height=e?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))})),!t&&this.avoidCropping&&(kO||wN)&&!QO()&&e.width*e.height<=230400&&e.width/e.height==16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn("capture 720p, scale: ".concat(this._scaleResolutionDownBy))),r}stopSmall(){var e,t;this.small&&(delete this.small,null==(e=this.manager)||e.update(),null==(t=this.room)||t.enableSmall(!1))}listenDeviceChange(){mV&&!mV.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&mV.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return Ab(this,null,(function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(cB[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){rH(this.userId,{eventId:2003,param1:7,streamType:2});let e=yield EV();e[0]?this.recapture(e[0].deviceId):t=!0}t&&mV.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return Ab(this,null,(function*(){1===this.recaptureMode&&e.deviceId!==this.deviceId||(mV.off("videoInputAdded",this.handleCameraAdded,this),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 dw(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){mV.off("videoInputAdded",this.handleCameraAdded,this),mV.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return Ab(this,null,(function*(){try{yield Ib(e.prototype,this,"recapture").call(this,t)}catch(Xk){let r=(yield EV()).find((e=>e.deviceId!==t));if(!r)throw Xk;yield Ib(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))}setRotation(e){this.manager&&(this.isScreen||dw(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};yb([VV((function(e){this.setContentHint(e.contentHint||"motion")}))],_B.prototype,"capture",1);var fB=_B,gB={};Tb(gB,{REPORT_TYPE:()=>Zw,buildSSOPackage:()=>$w,bytes2ms:()=>$D,calculateScaleResolutionDownNumber:()=>zw,convertObjectNumberToInt:()=>Gw,copyProperties:()=>ZD,deepClone:()=>Mw,deepCloneBasic:()=>Qw,deepMerge:()=>Ow,delay:()=>jw,fibonacci:()=>sw,formatedTime:()=>xw,getConstructorName:()=>vw,getContainerFromElement:()=>Lw,getEnv:()=>jD,getInternalVersion:()=>Cw,getLoggerUrl:()=>KD,getMediaStreamTrackInfo:()=>qw,getMuteStateFromFlag:()=>Dw,getNetworkType:()=>zD,getNumNetworkType:()=>QD,getReconnectionTimeout:()=>aw,getStringByteLength:()=>Fw,getTurnServer:()=>ww,getUint32Version:()=>Ww,getValueType:()=>cw,getViewListFromView:()=>Pw,glog:()=>rw,ipv4ToUint32:()=>Nw,isArray:()=>_w,isAudioWorkletSupported:()=>yw,isBoolean:()=>pw,isConstructor:()=>Tw,isEmpty:()=>kw,isFunction:()=>lw,isLangChinese:()=>nw,isMediaStreamTrack:()=>fw,isNumber:()=>hw,isObject:()=>mw,isOverseaSdkAppId:()=>JD,isPlainObject:()=>ow,isPortrait:()=>Bw,isPromise:()=>Ew,isRemoteTrack:()=>gw,isRotate90Or270:()=>Yw,isSetSinkIdSupported:()=>Sw,isString:()=>uw,isUndefined:()=>dw,loadImage:()=>Hw,loadVideo:()=>Xw,ms2bytes:()=>tw,ms2samples:()=>iw,normalizeUrl:()=>Kw,performanceNow:()=>Aw,promiseAny:()=>Iw,samples2ms:()=>ew,setNetworkType:()=>XD,stringify:()=>Vw,stringifyIncludeValue:()=>Uw,throttlePromise:()=>Jw});var EB=[-1,-1,1,-1,-1,1,1,1],TB=[0,0,1,0,0,1,1,1],vB=class e extends tx{constructor(e,t){if(super(),this.context=e,Sb(this,"name"),Sb(this,"input"),Sb(this,"output"),Sb(this,"texture"),Sb(this,"ctx2d",null),Sb(this,"fbo"),Sb(this,"width",0),Sb(this,"height",0),Sb(this,"x",0),Sb(this,"y",0),Sb(this,"program"),Sb(this,"vertexShader"),Sb(this,"fragmentShader"),Sb(this,"totalFrames",0),Sb(this,"dropFrames",0),Sb(this,"matchInputSize",!0),Sb(this,"texCoordBuffer"),Sb(this,"positionBuffer"),Sb(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),Sb(this,"cost",0),Sb(this,"_canvas",null),Sb(this,"_image"),Sb(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 xB)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==BO?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(TB),this.positionBuffer=this.createBuffer(EB),!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(AM){this.context.destroy(new Ub({code:xb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(AM.message||AM)}))}}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 LB&&this.render(e)||this.context instanceof xB&&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 LB){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(t,i,r,n,o,s,a,c,l){let d=!(dw(s)||dw(a)||dw(c)||dw(l));return!(!this.ctx2d||!t)&&(t instanceof ImageData?(d?this.ctx2d.putImageData(t,i,r,s,a,c,l):this.ctx2d.putImageData(t,i,r),this.emit(e.RENDER,this.ctx2d.canvas)):(d?this.ctx2d.drawImage(t,s,a,c,l,i,r,n,o):this.ctx2d.drawImage(t,i,r,n,o),this.emit(e.RENDER,t)),"undefined"!=typeof VideoFrame&&t instanceof VideoFrame&&t.close(),!0)}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var e;let{totalFrames:t,x:i,y:r,width:n,height:o,name:s,cost:a}=this,c=Date.now(),l=(t-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:t,x:i,y:r,width:n,height:o,timestamp:c,fps:l,name:s,cost:a},fb({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,i=t.createTexture();return this.useTextures(i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};Sb(vB,"RENDER","render"),yb([ZL(tx.INIT,"connected",{sync:!0})],vB.prototype,"connect",1),yb([ZL("connected",tx.INIT,{ignoreError:!0,sync:!0})],vB.prototype,"disconnect",1),yb([ZL([],"closed",{sync:!0})],vB.prototype,"close",1);var yB=vB,SB=sU(MU(250),wF((()=>performance.now())),mU()),IB=[0,1,1,1,0,0,1,0],AB=class extends yB{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),Sb(this,"_intervalId",0),Sb(this,"_sequence",0),Sb(this,"checkGLError",!1),Sb(this,"checkVisibilityChange"),e instanceof xB?this.ctx2d=e.ctx||null:e.available&&null!=t&&t.mirrorUpAndDown&&this.setTexBuffer(IB)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),ax.clearTask(this._intervalId),this._intervalId=ax.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(ax.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof LB){let e=this.context.ctx.getError();e&&this.context.destroy(new Ub({code:xb.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(),this.emit(yB.RENDER,this.context._canvas),!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;this._intervalId&&(ax.clearTask(this._intervalId),this._intervalId=0,1===e&&(this.log.info("".concat(this.name," use requestVideoFrameCallback")),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),ax.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),ax.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},RB=class extends AB{constructor(e,t){super(e,t),Sb(this,"_videoTrack"),Sb(this,"_muteOb"),Sb(this,"_closedOb",VU(this,"closed")),Sb(this,"_subscription"),Sb(this,"_canvasContainer"),Number(LO)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=VU(this._videoTrack,"mute"),sU(VU(this._videoTrack,"ended"),oF(this._closedOb),nB((()=>{this.context.destroy(new Ub({code:xb.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){var e;this._subscription=sU(this._muteOb,oF(this._closedOb),UF((e=5e3,t=>{let i=performance.now();sU(SB,dF((t=>t-i<e)),nF(1))(t)})),iF((()=>{var e;return!(null==(e=this._videoTrack)||!e.muted||document.hidden)})),nB((()=>{this.context.destroy(new Ub({code:xb.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()}},CB=class extends RB{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},bB=class extends RB{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))}},kB=class extends yB{constructor(e,t){super(e,fb({name:"imageSource"},t)),Sb(this,"_lastImage"),Sb(this,"_totalFrames",0),Sb(this,"_autoResize",!1),Sb(this,"_canvasRendered"),Sb(this,"videoCallbackId",0),Sb(this,"waitingFirstFrame",!0),Sb(this,"shouldUpdate",!0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===BO&&(this._canvasRendered=bU(),sU(this._canvasRendered,SU(this._image),xF((e=>e instanceof HTMLCanvasElement?VU(e,"rendered"):YU())),oF(VU(this,"closed")),nB((()=>{this.update()}))))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),FL()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback(((e,t)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=t.presentedFrames,this.update(1))})))}_render(e,t){var i;let{width:r,height:n}=this,{image:o}=this;if(o instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),({videoWidth:r,videoHeight:n}=o),!r||!n)return!1;o.width=r,o.height=n}else if(o instanceof HTMLImageElement||o instanceof ImageData||o instanceof ImageBitmap){if(({width:r,height:n}=o),o!==this._lastImage)this._lastImage=o;else if(r===this.width&&n===this.height)return!0}else o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas?(({width:r,height:n}=o),this._lastImage=o):"undefined"!=typeof VideoFrame&&o instanceof VideoFrame&&(({displayWidth:r,displayHeight:n}=o),null==(i=this._lastImage)||i.close(),this._lastImage=o);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,o)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,o)}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)}},DB=class extends kB{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",sU(VU(this._player,cx.PLAYER_STATE_CHANGED),oF(VU(this,"closed")),iF((e=>{let{state:t}=e;return"PLAYING"===t})),nB((()=>{this.tryVideoFrameCallback()})))}get image(){return this._player.element}},wB=class extends DB{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,t,i){super(e,new Bx({id:i.name,track:t,muted:!0,container:null,objectFit:"contain",log:i.logger}),i),this.name="videoTrackSource",this._player.play()}replaceTrack(e){this.waitingFirstFrame=!0,this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},NB=class extends yB{constructor(e,t,i){super(e,gb(fb({name:"textSource"},i),{create2d:!0})),Sb(this,"hasChange",!0),Sb(this,"content",""),this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return(null==(e=this.ctx2d)?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return(null==(e=this.ctx2d)?void 0:e.fillStyle)||""}render2d(e){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:i,font:r}=this;super.resize(e,t),this.color=i,this.font=r}drawMultilineText(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1.2;if(!this.ctx2d)return;let r=this.ctx2d.measureText(this.content);t+=r.fontBoundingBoxAscent||r.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),o=(n?parseInt(n[1],10):16)*i,s=this.content.split("\n");for(let a=0;a<s.length;a++)this.ctx2d.fillText(s[a],e,t+a*o)}},OB=class extends tx{constructor(e){super(),Sb(this,"frameRate"),Sb(this,"_canvas"),Sb(this,"log"),Sb(this,"hasAlpha",!1),Sb(this,"name"),Sb(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 wB(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new RB(this,e)}createVideoImageSource(e,t){return new kB(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new DB(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new NB(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};Sb(OB,"_ids",0);var MB={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},PB=class extends OB{constructor(){super(...arguments),Sb(this,"defaultProgam"),Sb(this,"defaultVShader"),Sb(this,"defaultFShader"),Sb(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(OB._ids++)),this.ctx=this._canvas.getContext("webgl2",MB),!this.ctx)throw new Ub({code:xb.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 Ub({code:xb.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}))}destroy(e){let t="";return e&&(t=e.message,this.error=e,BP.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}};Sb(PB,"UNAVAILABLE","unavailable"),yb([ZL(tx.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),BP.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),BP.addSuccessEvent({key:512700})}})],PB.prototype,"create",1),yb([ZL("created",tx.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(PB.UNAVAILABLE,e),this.removeAllListeners()}})],PB.prototype,"destroy",1);var LB=PB,xB=class extends OB{constructor(){super(...arguments),Sb(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(OB._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new Ub({code:xb.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",(()=>{this.log.error("2d context lost")})),this._canvas.addEventListener("contextrestored",(()=>{this.log.warn("2d context restored")}))}destroy(e){let t="";e&&(t=e.message,this.error=e,BP.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(),BP.addSuccessEvent({key:512703})}};function VB(e,t,i,r,n){arguments.length>5&&void 0!==arguments[5]&&arguments[5]&&([i,r]=[r,i]);let o={sWidth:e,sHeight:t,dWidth:i,dHeight:r,sx:0,sy:0,dx:0,dy:0};if(0===e||0===t)return o;switch(n){case void 0:case"fill":break;case"contain":{let n=Math.min(i/e,r/t);o.dWidth=e*n,o.dHeight=t*n,o.dx=(i-o.dWidth)/2,o.dy=(r-o.dHeight)/2;break}case"cover":{let n=Math.max(i/e,r/t),s=i/n,a=r/n;o.sx=(e-s)/2,o.sy=(t-a)/2,o.sWidth=s,o.sHeight=a;break}}return o}yb([ZL(tx.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),BP.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),BP.addSuccessEvent({key:512701})}})],xB.prototype,"create",1),yb([ZL("created",tx.INIT,{ignoreError:!0,sync:!0})],xB.prototype,"destroy",1);var UB=class{constructor(e,t){this.node=e,this.layout=t,Sb(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},FB=class extends yB{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),Sb(this,"inputs",[]),Sb(this,"backgroundColor","black")}addInput(e,t){let i=0,r=this.inputs.length;for(;i<r;){let e=Math.floor((i+r)/2);if(this.inputs[e].layout.zIndex<t.zIndex)i=e+1;else{if(!(this.inputs[e].layout.zIndex>t.zIndex))throw new Error("input already exists at zIndex ".concat(t.zIndex));r=e}}let n=new UB(e,t);this.inputs.splice(i,0,n)}changeInputLayout(e,t){let i=this.inputs.findIndex((t=>t.node===e));if(i<0)return;let{x:r,y:n,width:o,height:s,zIndex:a,fillMode:c,rotation:l,hidden:d}=t;if(!dw(a)&&this.inputs.some((t=>t.layout.zIndex===a&&t.node!==e)))throw new Error("input already exists at zIndex ".concat(t.zIndex));let u=this.inputs[i];dw(r)||(u.layout.x=r),dw(n)||(u.layout.y=n),dw(o)||(u.layout.width=o),dw(s)||(u.layout.height=s),dw(l)||(u.layout.rotation=l),dw(d)||(u.layout.hidden=d),c&&(u.layout.fillMode=c),!dw(a)&&a!==u.layout.zIndex&&(u.layout.zIndex=a,this.inputs.sort(((e,t)=>e.layout.zIndex-t.layout.zIndex)))}hasInput(e){return this.inputs.some((t=>t.node===e))}hasNoInput(){return 0===this.inputs.length}resize(e,t){if(!this.matchInputSize)return void super.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 LB&&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.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter((t=>t.node!==e)),0===this.inputs.length&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce(((t,i)=>i.node.requestFrame(e)||t),!1)&&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.forEach((t=>t.node.requestFrame(e))),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];if(t.hidden)continue;let i=VB(t.node.width,t.node.height,t.width,t.height,t.fillMode,Yw(t.rotation));this.draw2d(t.node.image,t.x+i.dx,t.y+i.dy,i.dWidth,i.dHeight,i.sx,i.sy,i.sWidth,i.sHeight)}return!0}return!1}debugLayout(e,t,i,r){let n=arguments.length>4&&void 0!==arguments[4]&&arguments[4];this.ctx2d&&(n&&([i,r]=[r,i]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,i,r),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:i,width:r,height:n,name:o}=this,s=Date.now(),a=(e-this.lastInfo.totalFrames)/((s-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:i,width:r,height:n,timestamp:s,fps:a,name:o},fb({parent:this.inputs.filter((e=>e)).map((e=>e.node.getInfo()))},this.lastInfo)}removeAllInputs(){this.inputs.forEach((e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof LB)try{null==(t=this.context.ctx)||t.deleteBuffer(e.positionBuffer)}catch(AM){}}))}close(){super.close(),this.removeAllInputs()}},BB=[1,0,0,0,1,1,0,1],HB=class extends yB{constructor(e,t,i,r){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t}),Sb(this,"mirror",!1),Sb(this,"rotation",0),i&&(this.mirror=i),r&&(this.rotation=r),e instanceof LB)try{this.setTexBuffer(BB)}catch(Yb){e.destroy(new Ub({code:xb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(Yb.message||Yb)}))}}draw2d(e,t,i,r,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),90===this.rotation?(this.ctx2d.translate(r,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/r,r/n)):180===this.rotation?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):270===this.rotation&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/r,r/n));let o=super.draw2d(e,t,i,r,n);return this.ctx2d.restore(),o}return!1}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}resize(e,t){Yw(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}},WB=class extends dB{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,Bx),Sb(this,"inputLocalVideoTracks",new Map),Sb(this,"inputLocalScreenTracks",new Map),Sb(this,"cameraNodeMap",new Map),Sb(this,"screenNodeMap",new Map),Sb(this,"textNodeMap",new Map),Sb(this,"imageNodeMap",new Map),Sb(this,"videoNodeMap",new Map),Sb(this,"endedIds",new Set),Sb(this,"videoContext"),Sb(this,"mixNode"),Sb(this,"destination"),Sb(this,"manager"),Sb(this,"stat"),Sb(this,"_checkId",0),Sb(this,"autoSetFps",!0),this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(yB.RENDER,(e=>{this.emit("render",e)})),this.mixNode=new FB(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=ax.run("interval",(()=>{this.destination&&this.log.debug(this.destination.getInfo())}),{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new xB({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout((()=>{var e;return null==(e=this.destination)?void 0:e.start(this.videoContext.frameRate)}),500)}setFpsAuto(){var e;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let t=null,i=0,r=!0;for(let[n,o]of this.inputLocalVideoTracks)if(o.profile.frameRate>i){if(this.endedIds.has(n)){let e=this.cameraNodeMap.get(n);e&&e.image.cancelVideoFrameCallback(e.videoCallbackId);continue}i=o.profile.frameRate,t=n}for(let[n,o]of this.inputLocalScreenTracks)if(o.profile.frameRate>i){if(this.endedIds.has(n)){let e=this.screenNodeMap.get(n);e&&e.image.cancelVideoFrameCallback(e.videoCallbackId);continue}i=o.profile.frameRate,t=n,r=!1}if(null!==t){let e=r?this.cameraNodeMap.get(t):this.screenNodeMap.get(t);e&&(e.shouldUpdate=!0,e.tryVideoFrameCallback()),this.log.info("set mix fps: ",i)}else null==(e=this.destination)||e.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var i;null==(i=this.mixNode)||i.resize(e,t)}startMix(){return Ab(this,null,(function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),PO&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),null==(e=this.manager)||e.changeInput(this)}))}addCameraSource(e,t,i){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error("There is already a cameraSource with the same ID: ".concat(e));let r,{mediaTrack:n}=t;if(!n)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,ux(this,mV).add("videoInputRemoved",(i=>{i.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())})),t.on("output-media-track-changed",(()=>{this.endedIds.delete(e),this.updateCameraSource(e,i,t.mediaTrack)})),r=16===BO&&n instanceof CanvasCaptureMediaStreamTrack?this.videoContext.createVideoImageSource(n.canvas,{name:"cameraCanvasSource",logger:this.log}):this.videoContext.createVideoTrackSource(n,"cameraNodeSource"),r.resize(t.settings.width,t.settings.height),r.shouldUpdate=!1,this._connectMix(r,i,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,r),this.setFpsAuto()}addScreenSource(e,t,i){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error("There is already a screenSource with the same ID: ".concat(e));let{mediaTrack:r}=t;if(!r)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(r,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,i),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:i="",font:r,color:n,layout:o}=e;if(this.textNodeMap.has(t))throw new Error("There is already a textSource with the same ID: ".concat(t));let s=this.videoContext.createTextSource({content:i,font:r,color:n});s.resize(o.width,o.height),this._connectMix(s,o),this.textNodeMap.set(t,s)}addImageSource(e,t,i){if(this.imageNodeMap.has(e))throw new Error("There is already a imageSource with the same ID: ".concat(e));let r=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});r.resize(t.width,t.height),this._connectMix(r,i),this.imageNodeMap.set(e,r)}addVideoSource(e,t,i){if(this.videoNodeMap.has(e))throw new Error("There is already a videoSource with the same ID: ".concat(e));let r=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});r.resize(t.videoWidth,t.videoHeight),r.shouldUpdate=!1,this._connectMix(r,i),this.videoNodeMap.set(e,r)}updateCameraSource(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=arguments.length>3?arguments[3]:void 0,n=this.cameraNodeMap.get(e);if(n){if(i){if(16===BO&&i instanceof CanvasCaptureMediaStreamTrack)if(n instanceof wB){let t=n.output;n.close(),n=this.videoContext.createVideoImageSource(i.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(t),this.cameraNodeMap.set(e,n)}else n.image=i.canvas;else if(n instanceof wB)n.replaceTrack(i);else{let t=n.output;n.close(),n=this.videoContext.createVideoTrackSource(i,"cameraNodeSource"),n.connect(t),this.cameraNodeMap.set(e,n)}let{width:t,height:r}=i.getSettings();t&&r&&n.resize(t,r)}r&&n.resize(r.width,r.height),(r||i)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let i=this.screenNodeMap.get(e);i&&this._changeMixLayout(i,t)}updateTextSource(e){let{id:t,content:i,font:r,color:n,layout:o}=e,s=this.textNodeMap.get(t);s&&(dw(i)||(s.content=i),dw(r)||(s.font=r),dw(n)||(s.color=n),s.resize(o.width,o.height),this._changeMixLayout(s,o))}updateImageSource(e,t,i){let r=this.imageNodeMap.get(e);r&&(i&&(r.image=i,r.resize(i.width,i.height)),this._changeMixLayout(r,t))}updateVideoSource(e,t,i){let r=this.videoNodeMap.get(e);if(r){if(i){let e=r.image;e instanceof HTMLVideoElement&&this.stopVideoElement(e),r.image=i,r.resize(i.videoWidth,i.videoHeight)}this._changeMixLayout(r,t)}}_connectMix(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"contain";if(!this.mixNode)return;let{mirror:r,rotation:n}=t;e.disconnect();let o=new HB(this.videoContext,this.log,r,n);o=e.connect(o),t.fillMode||(t.fillMode=i),o.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:i,rotation:r}=t,n=e.output||e;n instanceof HB&&(dw(i)||(n.mirror=i),dw(r)||(n.rotation=r),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let i=this.cameraNodeMap.get(e);i&&(i.output instanceof HB&&i.output.close(),i.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let i=this.screenNodeMap.get(e);i&&(i.output instanceof HB&&i.output.close(),i.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof HB&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof HB&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof HB&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(){arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),ax.clearTask(this._checkId),null==(e=this.videoContext)||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),hx(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}},GB=fM();if("undefined"!=typeof navigator&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:GB,exposeOrigin:!0,permittedOrigins:["*"]})}catch(vJ){}var jB=function(e){return Ab(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:MO?{max:e.width}:{ideal:e.width,max:e.width},height:MO?{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);_M.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(DO&&NO<74||MO||wN)&&_M.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(kM){_M.warn("screen applyConstraints failed: ".concat(kM))}e.captureElement&&(yield function(e,t){return Ab(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&lw(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==GB)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){_M.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 dw(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);_M.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},JB=class extends fB{constructor(e){super(e,2),Sb(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),Sb(this,"objectFit","contain"),Sb(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}get isShareCurrentTab(){var e,t;try{return GB===(null==(t=null==(e=this.mediaTrack)?void 0:e.getCaptureHandle())?void 0:t.handle)}catch(AM){return}}capture(e){return Ab(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:r,echoCancellation:n,noiseSuppression:o,audioTrack:s,videoTrack:a,captureElement:c,preferDisplaySurface:l}=e;return function*(){try{let e;return a||s?(e=new MediaStream,a&&e.addTrack(a),s&&e.addTrack(s)):(e=yield jB({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:r,echoCancellation:n,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),t.sourceTrack=e.getVideoTracks()[0]),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof Ub?e:new Ub({code:xb.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return Ab(this,null,(function*(){throw new Error("Method not implemented.")}))}};yb([VV((function(e){this.setContentHint(e.contentHint||"detail")}))],JB.prototype,"capture",1);var KB,qB=class extends hB{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}addAudioProcessor(e,t,i){this.pipeline.silentNode.setNode(i),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e),this.enableTrackAEC(!1)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};function zB(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,r=arguments.length>3?arguments[3]:void 0;return Ab(this,null,(function*(){let n=Zx();KB||(KB=Hx(n,URL.createObjectURL(new Blob(['registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});'],{type:"application/javascript"})))),yield KB;let o=n.sampleRate,s=new AudioWorkletNode(n,"dumper",{numberOfInputs:e.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:o,targetSampleRate:t}});return s.channelCountMode="explicit",s.channelCount=i,r&&s.port.postMessage({port:r},[r]),e.forEach(((e,t)=>e.connect(s,0,t))),new ReadableStream({start(e){s.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach((e=>e.disconnect(s))),s.port.close()}})}))}var YB=class extends rV{constructor(e){super(),this.room=e,Sb(this,"_localAudioTrack"),Sb(this,"_localScreenAudioTrack"),Sb(this,"log",_M.createLogger({id:"am"})),Sb(this,"denoiser"),Sb(this,"voiceChanger"),Sb(this,"mixChangedDebounce"),Sb(this,"audioProcessor"),Sb(this,"encodePipeline",[]),Sb(this,"decodePipeline",[]),Sb(this,"getPCMAbortCtrlMap",new Map),Sb(this,"audioFrameEventConfigMap",new Map),Sb(this,"audioReferenceMap",new Map),Sb(this,"isLocalAudioNeedAudioProcess",!1),Sb(this,"isScreenAudioNeedAudioProcess",!1),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.installEvent()}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return null==(e=this._localScreenAudioTrack)?void 0:e.pipeline}dump(e){var t,i;if(!this._localAudioTrack)return;let r=[],n=[];null!=(t=this._localAudioPipline)&&t.source.node&&(r.push(this._localAudioPipline.source.node),n.push("mic")),null!=(i=this._localAudioPipline)&&i.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),n.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),n.push("mix")),this.log.info("dump audio track ".concat(n,", duration: ").concat(e));let o=new AbortController,s=[],a=setTimeout((()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")}),1e3*e),c=()=>{for(let e=0;e<n.length;e++){let t=URL.createObjectURL(new Blob(s[e])),i=document.createElement("a");i.href=t,i.download="".concat(n[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(a),o.abort("download")},l=zB(r).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>s[t]=s[t]?s[t].concat(e[0]):[e[0]]))}}),o).catch((e=>c))));return{then:l.then.bind(l),download:c}}getPCM(e,t){var i,r,n;if("undefined"==typeof WritableStream)return void this.log.warn("getPCM failed: browser not support WritableStream");let{enable:o,sampleRate:s=48e3,channelCount:a=1,port:c}=(""===t?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!o)return;this.log.info("getPCM ".concat(t||"local"));let l,d,u=Math.floor(.04*s),h=new Float32Array(u),p=new Float32Array(u),m=0,_=new AbortController,f=""===t?null==(i=this._localAudioTrack)?void 0:i.mediaTrack:null==(n=null==(r=this.room)?void 0:r.remotePublishedUserMap.get(t))?void 0:n.remoteAudioTrack.mediaTrack;if(f)return zB([Zx().createMediaStreamSource(new MediaStream([f]))],s,a,c).then((i=>i.pipeTo(new WritableStream({write(i){i[0][0]&&(m+i[0][0].length>u?(h.set(i[0][0].subarray(0,u-m),m),l=i[0][0].subarray(u-m),i[0][1]&&(p.set(i[0][1].subarray(0,u-m),m),d=i[0][1].subarray(u-m)),m+=u-m):(l&&(h.set(l,m),m+=l.length,l=void 0),d&&(p.set(d,m),d=void 0),h.set(i[0][0],m),i[0][1]&&p.set(i[0][1],m),m+=i[0][0].length),m>=u&&(m=0,e({userId:t,sampleRate:s,channelCount:a,data:1===a?h:[h,p]}),h=new Float32Array(u),p=new Float32Array(u)))}}),_).catch((e=>this.log.warn("stop getPCM reason:".concat(e)))))),_;this.log.info("getPCM failed: ".concat(t||"local"," has no audio track"))}get hasScreenAudioTrack(){return!dw(this._localScreenAudioTrack)}get hasAudioTrack(){return!dw(this._localAudioTrack)}changeInput(e){var t,i;return e instanceof qB?(this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&null!=(t=this.audioProcessor)&&t.screenAudioWorkletNode&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach(((t,i)=>{e.mixAudioReference(t,i)}))),e.pipeline.connect(),this.mixOnChange()):e instanceof hB?(this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&null!=(i=this.audioProcessor)&&i.localAudioWorkletNode&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach(((t,i)=>{e.mixAudioReference(t,i)}))),e.pipeline.connect(),this.mixOnChange()):e instanceof $B?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}mixAudioReference(e,t){var i;null==(i=this._localAudioTrack)||i.mixAudioReference(e,t)}unMixAudioReference(e){var t;null==(t=this._localAudioTrack)||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var i;null==(i=this._localAudioTrack)||i.setAudioReferenceVolume(e,t)}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 qB?delete this._localScreenAudioTrack:e instanceof hB&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}addAudioProcessor(e,t,i,r){var n;this.audioProcessor={localAudioWorkletNode:i,mixNode:e,silentNode:t,screenAudioWorkletNode:r},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&i&&(this._localAudioTrack.addAudioProcessor(i,e,t),this.audioReferenceMap.forEach(((e,t)=>{var i;null==(i=this._localAudioTrack)||i.mixAudioReference(e,t)}))),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&r&&(null==(n=this._localScreenAudioTrack)||n.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach(((e,t)=>{var i;null==(i=this._localScreenAudioTrack)||i.mixAudioReference(e,t)})))}removeDenoiser(e){var t;return delete this.denoiser,null==(t=this._localAudioTrack)?void 0: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()}removeAudioProcessor(e,t){var i,r;delete this.audioProcessor,null==(i=this._localAudioTrack)||i.removeAudioProcessor(e),null==(r=this._localScreenAudioTrack)||r.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach((e=>null==e?void 0:e.abort("destroy"))),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}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}handleLocalTrackStarted(e){let{room:t,userId:i}=e;var r;if(t!==this.room||this.getPCMAbortCtrlMap.get(i))return;let n=this.getPCM((e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)}),"");this.getPCMAbortCtrlMap.set(i,n),this.getPCMAbortCtrlMap.get(i)&&(null==(r=this._localAudioTrack)||r.on("input-media-track-changed",(()=>{let e=this.getPCMAbortCtrlMap.get(i);e&&(e.abort("inputMediaTrackChanged"),e=this.getPCM((e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)}),""),this.getPCMAbortCtrlMap.set(i,e))})))}handleLocalTrackStopped(e){let{room:t,userId:i}=e;if(t!==this.room)return;let r=this.getPCMAbortCtrlMap.get(i);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(i))}handleRemoteTrackStarted(e){let{room:t,userId:i}=e;if(t===this.room&&!this.getPCMAbortCtrlMap.get(i)){let e=this.room.audioManager.getPCM((e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)}),i);this.getPCMAbortCtrlMap.set(i,e)}}handleRemoteTrackStopped(e){let{room:t,userId:i}=e;if(t!==this.room)return;let r=this.getPCMAbortCtrlMap.get(i);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(i))}installEvent(){dM.on("113",this.handleLocalTrackStarted,this),dM.on("114",this.handleLocalTrackStopped,this),dM.on("115",this.handleRemoteTrackStarted,this),dM.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){dM.off("113",this.handleLocalTrackStarted),dM.off("114",this.handleLocalTrackStopped),dM.off("115",this.handleRemoteTrackStarted),dM.off("116",this.handleRemoteTrackStopped)}updateAudioReference(e){let{type:t,audioReference:i,refId:r,volume:n}=e;if("add"===t){if(this.audioReferenceMap.get(r)||!i||(this.audioReferenceMap.set(r,i),!this.audioProcessor))return;this.mixAudioReference(i,r)}else if("remove"===t)this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if("updateVolume"===t){if(!this.audioProcessor||dw(n))return;this.setAudioReferenceVolume(r,n)}}};function XB(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return FV(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];return new Promise(((n,s)=>{let a=setTimeout((()=>{let i=new Ub({code:xb.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});_M.warn(i),2===t?s(i):1===t&&n()}),1e3*e);i.apply(this,o).then(n,s).finally((()=>{clearTimeout(a)}))}))}))}var QB=class e extends kV{constructor(t,i,r){super({userId:i.userId,sdkAppId:t.sdkAppId,mediaType:r,room:t}),this.room=t,this.user=i,Sb(this,"tinyId"),Sb(this,"isRemote",!0),Sb(this,"jitterBufferDelay",0),Sb(this,"availableState"),Sb(this,"remotePublishState"),Sb(this,"_triggerCheckDecodeSubject",bU(VU(this,e.STATE_SUBSCRIBE))),this.tinyId=i.tinyId,this.availableState=new tx("".concat(i.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new tx("".concat(i.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),sU(_U(VU(this,tx.STATECHANGED),VU(this.remotePublishState,tx.STATECHANGED)),wF((()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing))),nB((e=>{this.availableState.state!==(e?tx.ON:tx.OFF)&&(this.availableState.state=e?tx.ON:tx.OFF),this.updatePlayingState(e)})));let n=sU(VU(this.player,cx.ERROR),iF((e=>e.code===MediaError.MEDIA_ERR_DECODE))),o=sU(PU(5e3),iF((()=>!(this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived)&&(!this.player.isPlaying&&!(this.kind===Sk.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1))))),s=sU(fU(n,o),oF(VU(this,tx.INIT)));sU(this._triggerCheckDecodeSubject,iF((()=>!this.ignoreDecodeError)),UF(s),nB((e=>{this.reportDecodeResult(!1,e)})))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)}))}get ignoreDecodeError(){var e,t;return((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===e.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===tx.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){var i,r;let n=this.kind===Sk.AUDIO;if(BP[e?"addSuccessEvent":"addFailedEvent"]({key:n?504700:514702}),!n){let t=(null==(i=this.room)?void 0:i.downlinkVideoCodec.toUpperCase())||"H264";BP[e?"addSuccessEvent":"addFailedEvent"]({key:VP["DECODE_".concat(t,"_RESULT")]}),e||this.log.warn("".concat(null==(r=this.room)?void 0:r.downlinkVideoCodec," decode failed"))}e||(BP.addEnum({key:n?504701:514703,value:nM()}),px.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(tM()||sM()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===Sk.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?tx.ON:tx.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};Sb(QB,"STATE_SUBSCRIBE","subscribe"),yb([XB(5,1)],QB.prototype,"waitHasMediaTrack",1),yb([ZL(tx.INIT,QB.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),dM.emit(hM.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),zV(521716,!1)],QB.prototype,"subscribe",1),yb([ZL(QB.STATE_SUBSCRIBE,tx.INIT,{sync:!0,success(){this.log.info("unsubscribed"),dM.emit(hM.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],QB.prototype,"unsubscribe",1);var ZB=QB,$B=class extends ZB{constructor(e,t){super(e,t,1),Sb(this,"volume",0),Sb(this,"mediaType",1),Sb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}get dbVolume(){return lV.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}};var eH=class extends ZB{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),Sb(this,"mediaType",4),Sb(this,"source"),Sb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager,this.once("first-video-frame",(e=>{this.room.emit("first-video-frame",e)}))}play(e,t){return(pw(null==t?void 0:t.canvasRender)?t.canvasRender:17===BO)&&!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 xB({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new AB(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),FL()||(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;!hw(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)}},tH=class extends eH{constructor(e,t){super(e,t,2),Sb(this,"mediaType",2),Sb(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},iH=new Map;function rH(e,t){let i=gb(fb({},t),{timestamp:Bb()});iH.has(e)?iH.get(e).push(i):iH.set(e,[i])}function nH(e,t,i,r){try{if(_w(e))for(let n=0;n<e.length;n++)oH.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else oH.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}catch(AM){throw _M.error(AM),AM}}function oH(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;if(dw(i)){if(t.required)throw new Ub({code:xb.INVALID_PARAMETER,message:kP({key:AP.INVALID_PARAMETER_REQUIRED,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(dw(t.defaultValue))return;i=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let r=0;r<t.type.length;r++)null===t.type[r]&&null===i&&(e=!0),lw(t.type[r])&&i instanceof t.type[r]&&(e=!0),uw(t.type[r])&&cw(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new Ub({code:xb.INVALID_PARAMETER,message:kP({key:AP.INVALID_PARAMETER_TYPE,data:{key:r,rule:{type:t.type.map((e=>Tw(e)?vw(e):uw(e)?e:cw(e)))},fnName:n,value:i},link:{className:o,fnName:n}})})}else if(!dw(t.type)&&cw(i)!==t.type)throw new Ub({code:xb.INVALID_PARAMETER,message:kP({key:AP.INVALID_PARAMETER_TYPE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!1===t.allowEmpty){let e=hw(i)&&(0===i||Number.isNaN(i)),s=uw(i)&&""===i.trim();if(e||s)throw new Ub({code:xb.INVALID_PARAMETER,message:kP({key:AP.INVALID_PARAMETER_EMPTY,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})})}if(t.notLessThanZero&&hw(i)&&i<0)throw new Ub({code:xb.INVALID_PARAMETER,message:kP({key:AP.CANNOT_LESS_THAN_ZERO,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!dw(t.min)&&hw(i)&&i<t.min)throw new Ub({code:xb.INVALID_PARAMETER,message:kP({key:AP.INVALID_PARAMETER_MIN,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!dw(t.max)&&hw(i)&&i>t.max)throw new Ub({code:xb.INVALID_PARAMETER,message:kP({key:AP.INVALID_PARAMETER_MAX,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(uw(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new Ub({code:xb.INVALID_PARAMETER,message:kP({key:AP.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})})}else if(lw(t.instanceOf)&&!(i instanceof t.instanceOf))throw new Ub({code:xb.INVALID_PARAMETER,message:kP({key:AP.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(t.values&&!t.values.includes(i))throw new Ub({code:xb.INVALID_PARAMETER,message:kP({key:AP.INVALID_PARAMETER_RANGE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});let{properties:s}=t;ow(s)&&mw(i)&&Object.keys(s).forEach((e=>{oH.call(this,{rule:s[e],value:i&&i[e],key:"".concat(r,".").concat(e),fnName:n,className:o})}));let{arrayItem:a}=t;ow(a)&&_w(i)&&i.forEach(((e,t)=>{oH.call(this,{rule:a,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),lw(t.validate)&&t.validate.call(this,i,r,n,o,this)}dM.on(hM.JOIN_SUCCESS,(e=>{let{room:t}=e;rH(t.userId,{eventId:32788})})),dM.on(hM.LEAVE_START,(e=>{let{room:t}=e;rH(t.userId,{eventId:32789})})),dM.on(hM.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),rH(t.room.userId,{eventId:e})}})),dM.on(hM.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),rH(t.room.userId,{eventId:e})}})),dM.on(hM.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Sk.AUDIO?rH(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):rH(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),dM.on(hM.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Sk.AUDIO?rH(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):rH(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),dM.on(hM.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&rH(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&rH(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&rH(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),dM.on(hM.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&rH(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&rH(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&rH(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),dM.on(hM.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&rH(t.room.userId,{eventId:t.kind===Sk.VIDEO?32780:32781})})),dM.on(hM.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&rH(t.room.userId,{eventId:t.kind===Sk.VIDEO?32782:32783})})),dM.on(hM.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&&rH(i.userId,{eventId:t})})),dM.on(hM.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:n,remoteUserId:o}=e,s=!!o;switch(n){case"CONNECTED":t="RECONNECTING"===r?s?32801:32798:s?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===r&&(t=s?32802:32799);break;case"RECONNECTING":t=s?32800:32797}t&&rH(i.userId,{eventId:t,remoteUserId:o})})),dM.on(hM.VIDEO_CODEC_IMPLEMENTATION_CHANGED,(e=>{let{implementation:t,userId:i,remoteUserId:r,codec:n,isHWCodec:o,prevImplementation:s,streamType:a}=e,c=o?1:0;s||(c=o?3:2);let l={H264:0,H265:1,VP8:2}[n.toUpperCase()],d={eventId:4004,param1:c,param2:l,streamType:a||2};r&&(d.remoteUserId=r,d.eventId=4005),rH(i,d),BP.addEnum({key:r?514701:513701,value:c}),BP.addEnum({key:r?514700:513700,value:l})})),dM.on(hM.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===Sk.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),rH(t.userId,e)}}));var sH=vb(Rb(),1),aH=class extends sH.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"userId";super(),this.mySelfId=e,this._log=t,this.key=i,Sb(this,"userMap",new Map),Sb(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find((e=>e.isRobot))}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:r,role:n}=e;if(this.userMap.has(t))return;let o={userId:i,tinyId:r,role:20===n?"anchor":"audience"};this.userMap.set(t,o),this.emit("1",o)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let r="peer leave [".concat(e,"]");dw(t)||(r+=":".concat(TD[t])),this._log.info(r);let n=this.remotePublishedUserMap.get(e);if(n){let t=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:t,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",i.userId)}setUserList(e){this.userMap.forEach((t=>{e.findIndex((e=>e[this.key]===t[this.key]))<0&&this.deleteUser(t[this.key],0)})),e.forEach((e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)}))}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach((t=>{let i=t[this.key];if(e.findIndex((e=>e[this.key]===t[this.key]))<0){this._log.info("remote [".concat(i,"] unpublish"));let e=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(i),this.emit("6",{prevMuteState:e,muteState:t.muteState,flag:0})}})),e.forEach((e=>{var t;let i=e[this.key];if(i===this.mySelfId)return;let{flag:r,userId:n,tinyId:o}=e,s=Dw(r,n),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==r&&(e.flag=r,this._log.info("remote publish updated: ".concat(JSON.stringify(e.muteState))),this.emit("6",{prevMuteState:a,muteState:s,flag:r}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(s))),this.addUser({userId:n,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:Dw(0,n),muteState:s,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function cH(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return FV(((e,n)=>{let o=new WeakMap;return dM.on(hM.ROOM_DESTROY,(e=>{let{room:t}=e;return o.delete(t)})),function(){let s=o.get(this);for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(s||(s={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,s)),0===s.timestamp?s.timestamp=Date.now():Date.now()-s.timestamp>1e3&&(s.timestamp=Date.now(),s.callCountInSecond=0,s.totalSizeInSecond=0),r&&(s.totalSizeInSecond+=r(...c)),0!==s.timestamp&&Date.now()-s.timestamp<1e3&&(s.callCountInSecond>=t||s.totalSizeInSecond>i))throw new Ub({code:xb.INVALID_OPERATION,message:kP({key:AP.CALL_FREQUENCY_LIMIT,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>i,name:n,timesInSecond:t,maxSizeInSecond:i}})});s.callCountInSecond++,e.call(this,...c)}}))}var lH,dH=!0,uH={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"},hH={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},pH=((lH=pH||{})[lH.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",lH[lH.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",lH[lH.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",lH[lH.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",lH[lH.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",lH[lH.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",lH[lH.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",lH[lH.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",lH[lH.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",lH[lH.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",lH[lH.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",lH[lH.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",lH[lH.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",lH[lH.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",lH[lH.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",lH[lH.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",lH[lH.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",lH[lH.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",lH[lH.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",lH[lH.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",lH[lH.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",lH[lH.INVALID_OPERATION=5100]="INVALID_OPERATION",lH[lH.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",lH[lH.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",lH[lH.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",lH[lH.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",lH[lH.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",lH[lH.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",lH[lH.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",lH[lH.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",lH[lH.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",lH[lH.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",lH[lH.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",lH[lH.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",lH[lH.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",lH[lH.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",lH[lH.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",lH[lH.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",lH[lH.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",lH[lH.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",lH[lH.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",lH[lH.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",lH[lH.DEVICE_ERROR=5300]="DEVICE_ERROR",lH[lH.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",lH[lH.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",lH[lH.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",lH[lH.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",lH[lH.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",lH[lH.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",lH[lH.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",lH[lH.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",lH[lH.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",lH[lH.SERVER_ERROR=5400]="SERVER_ERROR",lH[lH.NEED_TO_BUY=5401]="NEED_TO_BUY",lH[lH.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",lH[lH.OPERATION_FAILED=5500]="OPERATION_FAILED",lH[lH.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",lH[lH.REJOIN_FAILED=5502]="REJOIN_FAILED",lH[lH.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",lH[lH.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",lH[lH.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",lH[lH.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",lH[lH.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",lH[lH.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",lH[lH.OPERATION_ABORT=5998]="OPERATION_ABORT",lH[lH.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",lH);var mH=gb(fb({},RP),{INVALID_PARAMETER(e){let{fnName:t}=e;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(r,"(), received type: ").concat(cw(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(r,"(), received type: ").concat(cw(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_REQUIRED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_ROOM_ID_TYPE_MISMATCH(e){let{key:t}=e;return"The type of target roomId must match the current roomId. Current room is using '".concat(t,"', but received '").concat("strRoomId"===t?"roomId":"strRoomId","'.")},INVALID_ROOM_ID_DUPLICATE(e){let{key:t}=e;return"the target '".concat(t,"' must not be the same as the current '").concat(t,"'.")},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 or screen share 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=_H(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=_H(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=_H(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=_H(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=_H(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=_H(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=_H(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 _H(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var fH=class e extends Error{constructor(e){let{code:t,extraCode:i,message:r="",messageParams:n,fnName:o="",originError:s,data:a}=e;var c;let l;l=r||function(e){let t,{code:i,params:r,enableDocLink:n=!1}=e,s="",a=pH[i];try{t=mH[a]}catch(o){t=mH.UNKNOWN_ERROR}return lw(t)?s=t(r):uw(t)&&(s=t),r.fnName&&!s.includes(r.fnName)&&("."!==s[s.length-1]&&(s+="."),s+=" thrown from ".concat(r.fnName,"()")),n&&(s+=" doc:"),s}({code:t===hH.SERVER_ERROR?t:i||t,params:fb({fnName:o,error:s},n)}),super(l),Sb(this,"name","RtcError"),Sb(this,"code"),Sb(this,"extraCode"),Sb(this,"functionName"),Sb(this,"message"),Sb(this,"data"),Sb(this,"handler"),Sb(this,"originError"),this.name=pH[t],this.code=t,this.extraCode=i,this.functionName=o,this.originError=s,this.message=l,this.data=a,5302===this.extraCode&&null!=(c=this.originError)&&c.message.includes("system")&&(this.handler=()=>{let e=document.createElement("a");sO?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):aO&&(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 Ub){let{stack:o}=t,s={code:hH.UNKNOWN_ERROR,fnName:i,originError:t};switch(t.getCode()){case xb.INVALID_PARAMETER:s.code=hH.INVALID_PARAMETER,s.message=t.message;break;case xb.INVALID_OPERATION:s.code=hH.INVALID_OPERATION;break;case xb.NOT_SUPPORTED:case xb.NOT_SUPPORTED_H264:s.code=hH.ENV_NOT_SUPPORTED,t.getCode()===xb.NOT_SUPPORTED_H264&&(s.extraCode=t.message.includes(RP.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case xb.JOIN_ROOM_FAILED:s.messageParams={fnParams:r};case xb.SERVER_TIMEOUT:case xb.SWITCH_ROLE_FAILED:case xb.SWITCH_ROOM_FAILED:s.code=hH.SERVER_ERROR,s.extraCode=t.getExtraCode();break;case xb.API_CALL_ABORTED:s.code=hH.OPERATION_ABORT;break;case xb.DEVICE_NOT_FOUND:case xb.DEVICE_AUTO_RECOVER_FAILED:case xb.INITIALIZE_FAILED:s.code=5300,t.name&&(s.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 xb.VIDEO_ENCODE_FAILED:s.extraCode=5505;case xb.AUDIO_ENCODE_FAILED:s.extraCode=5506,s.code=hH.OPERATION_FAILED;break;case xb.UNKNOWN:break;default:s.code=hH.OPERATION_FAILED}n=new e(s),o&&(n.stack+=o.substr(o.indexOf("\n")))}else{if(t instanceof e)return t;n=new e({code:hH.UNKNOWN_ERROR,fnName:i,originError:t})}return n}};var gH=fH;function EH(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function TH(e){return e===uH.QOS_PREFERENCE_CLEAR?"detail":e===uH.QOS_PREFERENCE_SMOOTH?"motion":""}function vH(e,t){let i=t?vk:Tk;return uN(e)?fb(fb({},i),e):Ek[e]?Ek[e]:i}var yH={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:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},SH={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}}},IH={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(uw(e)&&!document.getElementById(e))throw new gH({code:hH.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},AH={name:"userId",required:!0,type:"string"},RH={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[uH.AUDIO_PROFILE_STANDARD,uH.AUDIO_PROFILE_STANDARD_STEREO,uH.AUDIO_PROFILE_HIGH,uH.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function CH(e,t){if(!e)throw new gH({code:hH.INVALID_OPERATION,extraCode:5101,fnName:t})}function bH(e,t,i){if(!e)throw new gH({code:hH.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}function kH(e,t,i){if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new gH({code:hH.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:i}})}function DH(e,t,i){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new gH({code:hH.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:i}})}function wH(e){var t;if(null==(t=null==e?void 0:e.option)||!t.small)return;if(!hL())return _M.warn("small stream is not supported"),void delete e.option.small;let i=vH(e.option.profile),r=vH(e.option.small,!0);return((e,t)=>e.width*e.height>=t.width*t.height&&e.frameRate>=t.frameRate&&e.bitrate>=t.bitrate)(i,r)?void 0:(_M.warn("small stream profile must be less than big stream profile. Big: ".concat(JSON.stringify(i),", Small: ").concat(JSON.stringify(r))),void delete e.option.small)}var NH={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 gH({code:hH.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(uw(e.roomId))throw new gH({code:hH.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});kH(e.roomId,i,t)}else{if(!e.strRoomId)throw new gH({code:hH.INVALID_PARAMETER,extraCode:5015,fnName:i});DH(e.strRoomId,i,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"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:IH,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:yH},validate(e){var t,i;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&zP())throw new gH({code:hH.ENV_NOT_SUPPORTED,extraCode:5201});null!=(i=null==e?void 0:e.option)&&i.small&&wH(e)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:gb(fb({},IH),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:yH},validate(e){var t;null!=(t=null==e?void 0:e.option)&&t.small&&wH(e)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:RH},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&zP())throw new gH({code:hH.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:RH}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:IH,publish:{type:"boolean"},option:SH},validate(e,t,i,r,n){var o;if(null==(o=null==e?void 0:e.option)||!o.videoTrack){if(zP())throw new gH({code:hH.ENV_NOT_SUPPORTED,extraCode:5201});if(!eL())throw new gH({code:hH.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:IH,publish:{type:"boolean"},option:SH}},muteRemoteAudio:[AH,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[AH,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:IH,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){CH(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(bH(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new gH({code:hH.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:gb(fb({},IH),{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){CH(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(bH(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new gH({code:hH.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&&dw(e.streamType))throw new gH({code:hH.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){CH(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(!DL)throw new gH({code:hH.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new gH({code:hH.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new gH({code:hH.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new gH({code:hH.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});CH(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 gH({code:hH.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 gH({code:hH.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new gH({code:hH.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(CH(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new gH({code:hH.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(e,t,i){if(CH(this._room.isJoined,i),this._room.useStringRoomId&&e.strRoomId===this._room.roomId||!this._room.useStringRoomId&&e.roomId===Number(this._room.roomId))throw new gH({code:hH.INVALID_PARAMETER,extraCode:5020,fnName:i,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId&&this._room.useStringRoomId||!e.roomId&&e.strRoomId&&!this._room.useStringRoomId)throw new gH({code:hH.INVALID_PARAMETER,extraCode:5019,fnName:i,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId)kH(e.roomId,i,t);else{if(!e.strRoomId)throw new gH({code:hH.INVALID_PARAMETER,extraCode:5015,fnName:i});DH(e.strRoomId,i,t)}},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},OH={TRTC:NH},MH=class extends Error{};function PH(e,t){let i=Mw(e);for(let r=0;r<t.length;r++)Ow(i[r],t[r]);return i}function LH(e){this._resolve=Promise.resolve(e)}function xH(e){this._reject=Promise.reject(e)}var VH=class e{constructor(t,i){this.instance=t,this.group=i,Sb(this,"started",!1),Sb(this,"ops",[]),Sb(this,"startSame",(()=>!0)),Sb(this,"mergeUpdate",PH);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 MH("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:LH,reject:xH};try{switch(this.state){case 1:if(0===e)throw new MH("already started");break;case 4:if(2===e)throw new MH("not started");break;default:return this.cacheOp(o)}}catch(RM){return Promise.reject(RM)}return this.ops.push(o),o.promise=t(...o.args).then(r,n)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new MH("already start");break;case 3:switch(e.type){case 2:throw new MH("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new MH("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new MH("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 MH("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new MH("start not allowed after update");case 0:throw new MH("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new MH("keep start")),new MH("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}};Sb(VH,"instances",new WeakMap);var UH=VH,FH=new WeakMap,BH=(e,t)=>{if(t instanceof MH){let{stack:i}=t;t=new gH({code:hH.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function HH(e,t){return FV(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let a=UH.get(this,"string"==typeof e?e:e.call(this,...o));return a?(t&&(a.startSame=t.bind(this)),a.action(0,i.bind(this),o).catch(BH.bind(null,r))):i.apply(this,o)}))}function WH(e,t){let{merge:i,debounce:r}=t||{};return FV(((t,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=UH.get(this,"string"==typeof e?e:e.call(this,...s));if(!c)return t.apply(this,s);if(i&&(c.mergeUpdate=i.bind(this)),r&&r.isNeedToDebounce.apply(this,s)){let{delay:e,getKey:i}=r;return new Promise(((r,o)=>{var a,l;let d=null==(a=FH.get(this))?void 0:a.get(i(...s));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout((()=>{if(3===c.state||4===c.state)return r();c.action(2,t.bind(this),s).catch(BH.bind(null,n)).then(r,o)}),e);FH.has(this)?null==(l=FH.get(this))||l.set(i(...s),{timeoutId:u,resolve:r}):FH.set(this,new Map([[i(...s),{timeoutId:u,resolve:r}]]))}))}return c.action(2,t.bind(this),s).catch(BH.bind(null,n))}))}function GH(e){return FV(((t,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let s="function"==typeof e?e.call(this,...n):e;if(s instanceof RegExp)return Promise.all(UH.gets(this,s).map((e=>e.action(3,(()=>Promise.resolve()),n)))).then((()=>t.call(this,...n)));let a=UH.get(this,s);return a?a.action(3,t.bind(this),n).catch(BH.bind(null,i)):t.apply(this,n)}))}var jH={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",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},JH=new Set([jH.ERROR,jH.AUTOPLAY_FAILED,jH.KICKED_OUT,jH.REMOTE_USER_ENTER,jH.REMOTE_USER_EXIT,jH.REMOTE_AUDIO_AVAILABLE,jH.REMOTE_AUDIO_UNAVAILABLE,jH.REMOTE_VIDEO_AVAILABLE,jH.REMOTE_VIDEO_UNAVAILABLE,jH.CONNECTION_STATE_CHANGED,jH.PUBLISH_STATE_CHANGED,jH.SCREEN_SHARE_STOPPED,jH.DEVICE_CHANGED,jH.FIRST_VIDEO_FRAME,jH.PERMISSION_STATE_CHANGE,jH.VIDEO_SIZE_CHANGED]),KH={};Tb(KH,{ScheduleRequestType:()=>$H,getAbilityConfig:()=>tW,getScheduleDomain:()=>iW,isNeedToSchedule:()=>zH,scheduleProxy:()=>QH,sendScheduleRequest:()=>XH,setIsNeedToSchedule:()=>YH,setScheduleProxy:()=>ZH});var qH=null,zH=!0;function YH(e){pw(e)&&e!==zH&&(zH=e,_M.info("setIsNeedToSchedule ".concat(e)))}function XH(e){return Ab(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:n,userSig:o,version:s,frameWorkType:a,role:c,latencyLevel:l}=e;return function*(){if(!zH&&qH)return{isCached:!0,result:qH};let e={delta:0,count:[1,1],msg:[],detail:[]};try{let d=new FormData;d.append("userId",String(t)),d.append("sdkAppId",String(i)),d.append("isStrGroupId",String(r)),d.append("groupId",String(n)),d.append("sdkVersion",s),d.append("userSig",String(o));let u=yield $O();null!=u&&u.model&&d.append("model",String(null==u?void 0:u.model)),c&&d.append("role",String(c)),l&&d.append("latencyLevel",String(l)),a&&d.append("frameWorkType",String(a));let h=Aw(),p=yield function(e,t,i){return new Promise(((r,n)=>{let o=null;Iw([nW((e=>t.count[0]=e+1),(e=>{let{error:r,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[0]=r.message,o||(s>=1&&(a[0]=eW(i,"config",Sk.MAIN,!0)),n())}))(eW(i,"config",Sk.MAIN),e,{get timeout(){return 1e3*sw(2+t.count[0])}}),nW((e=>t.count[1]=e+1),(e=>{let{error:r,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[1]=r.message,o||(s>=2&&(a[0]=eW(i,"config",Sk.BACKUP,!0)),n())}))(eW(i,"config",Sk.BACKUP),e,{get timeout(){return 1e3*sw(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}(d,e,i);p.config&&(p.config.loggerDomain&&ek(p.config.loggerDomain),pw(p.config.scheduleCache)&&YH(!p.config.scheduleCache)),e.delta=Aw()-h;let m=function(e,t,i){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let n=performance.getEntriesByType("resource"),o=eW(e,"config",Sk.MAIN),s=eW(e,"config",Sk.BACKUP);for(let e of n)if(e.startTime>=i&&(e.name===o||e.name===s)&&e.transferSize>0){let i=e.name===o?Sk.MAIN:Sk.BACKUP,n=Math.round(e.duration),s=Math.round(e.domainLookupStart-e.startTime),a=e.redirectStart>0?Math.round(e.redirectEnd-e.redirectStart):0,c=e.fetchStart>0?Math.round(e.domainLookupStart-e.fetchStart):0,l=Math.round(e.domainLookupEnd-e.domainLookupStart),d=Math.round(e.requestStart-e.secureConnectionStart),u=Math.round(e.secureConnectionStart-e.connectStart),h=Math.round(e.responseStart-e.requestStart),p=Math.round(e.responseEnd-e.responseStart),m=[l,d,u,h,p];px.uploadEvent({log:"stat-schedule-net:".concat(n,"(").concat(s,"(").concat(a,"->").concat(c,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=gb(fb({},r),{totalCost:n,local:s,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(o){_M.error("getScheduleDetailCost error",o)}return r}(Number(i),t,h);return qH=p,{isCached:!1,result:p,detailCost:m}}catch(d){let e=_w(d)?d[0]:d,t=hw(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),r=new Ub({code:xb.SCHEDULE_FAILED,extraCode:t,message:kP({key:AP.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw _M.error(i,t),r}}()}))}"undefined"!=typeof document&&document.head.insertAdjacentHTML("beforeend",Object.values(uD).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),dM.on("28",(()=>YH(!0))),dM.on("63",(()=>YH(!0))),dM.on("84",(()=>YH(!0))),dM.on("201",(e=>{"RECONNECTING"===e.state&&YH(!0)})),dM.on("202",(e=>{"RECONNECTING"===e.state&&YH(!0)}));var QH={main:"",backup:""};function ZH(e){_w(e)?(QH.main=e[0],QH.backup=e[1]):QH.main=e}var $H=(e=>(e.CONFIG="config",e.TRTC_AUTO_CONF="trtcAutoConf",e.AUDIO_AI_AUTH="audioAiAuth",e))($H||{});function eW(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Sk.MAIN,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return"https://".concat(QH[i]||iW(e,i,r),"/api/v1/").concat(t)}function tW(e,t,i){let r=eW(e,t),n=eW(e,t,Sk.BACKUP),o=new URLSearchParams(i).toString(),s=fetch("".concat(r,"?").concat(o)).then((e=>e.json())),a=fetch("".concat(n,"?").concat(o)).then((e=>e.json()));return Iw([s,a])}function iW(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Sk.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=JD(e)?r?i===Sk.MAIN?uD.MAIN_OVERSEA_BACKUP:uD.BACKUP_OVERSEA:i===Sk.MAIN?uD.MAIN_OVERSEA:uD.BACKUP_OVERSEA:i===Sk.MAIN?uD.MAIN:uD.BACKUP,t}function rW(e,t,i){return new Promise(((r,n)=>{nN({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 nW=(e,t)=>hN({retryFunction:rW,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var oW=class{constructor(){Sb(this,"_log"),this._log=_M.createLogger({id:"fd"})}download(e,t){return Ab(this,null,(function*(){let{type:i="blob"}=t||{};e=Kw(e);try{let t,r=Aw();if(t=lw(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let n=Aw()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(n,"ms")),BP.addSuccessEvent({key:522700,cost:Aw()-r}),t.data}catch(AM){throw this._log.error("failed to download: ".concat(e,", error: ").concat(AM)),BP.addFailedEvent({key:522700,error:AM}),AM}}))}downloadWithFetch(e,t){return Ab(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){let e=new Error("network response was not ok: ".concat(r.status));throw e.status=r.status,e}return i="arraybuffer"===t?yield r.arrayBuffer():yield r.blob(),{data:i}}catch(Xk){throw Xk}}))}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=()=>{if(200===n.status||0===n.status&&n.response)i({data:n.response});else{let e=new Error("XHR failed, status: ".concat(n.status));e.status=n.status,r(e)}},n.onerror=r,n.send(null)}))}loadWasm(e,t){return Ab(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=Aw(),r=null,n=null;if(lw(WebAssembly.instantiateStreaming)&&!e.startsWith("data:application/octet-stream;base64,")&&!(e=>e.startsWith("file://"))(e)&&lw(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(Yb){n=Yb}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(Yb){n=Yb}if(r){let t=Aw()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),BP.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),BP.addFailedEvent({key:522701,error:n}),n}))}loadScript(e){this._log.info("loadScript ".concat(e));let t=Aw();return new Promise(((i,r)=>{let n=document.createElement("script");n.type="text/javascript",n.onload=()=>{this._log.info("loadedScript ".concat(e,", cost: ").concat(Aw()-t,"ms")),BP.addSuccessEvent({key:522702,cost:Aw()-t,split:1e3}),i(n)},n.onerror=t=>{this._log.error("failed to loadScript ".concat(e,", error: ").concat((null==t?void 0:t.message)||JSON.stringify(t))),BP.addFailedEvent({key:522702}),r(t)},n.crossOrigin="anonymous",n.src=e,document.head.append?document.head.append(n):document.getElementsByTagName("head")[0].appendChild(n)}))}};yb([_x({settings:{timeout:0,retries:3},onError(e,t,i){var r;404===(null==e?void 0:e.status)||null!=(r=null==e?void 0:e.message)&&r.includes("404")?(this._log.warn("download 404, stop retry"),i(e)):t()},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],oW.prototype,"download",1),yb([_x({settings:{timeout:3e3,retries:3},onRetrying(e){this._log.warn("loadScript retrying: ".concat(e))}})],oW.prototype,"loadScript",1);var sW=new oW;function aW(e){var t=this;let{TRTC:i,room:r,errorModule:n,assetsPath:o}=e;return{TRTC:i,LocalMixVideoTrack:WB,LocalVideoTrack:fB,LocalScreenTrack:JB,room:r,assetsPath:o,fileDownloader:sW,innerEmitter:dM,constants:jb,environment:mN,utils:gB,eventLogger:px,log:this.room.getLogger(),loggerManager:_M,errorModule:n,kvStatManager:BP,rtcDectection:EM,trtc:this,rx:YV,enums:TM,schedule:KH,getDevices:fV,initVisionTaskRegistry:function(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"/mediapipe/vision.js";return Ab(t,null,(function*(){window.VisionTaskRegistry||(yield sW.loadScript("".concat(e,"/").concat(i).replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(e)).preloadModels([window.VisionTaskType.ImageSegmenter])}))},clearStarted:(e,t)=>{let i=e.getAlias(),r=UH.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:zB,createAudioNode:oV}}var cW=new WeakMap;function lW(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return FV(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{uW.call(this,t,n,i,this._name)}catch(AM){return Promise.reject(AM)}return e.apply(this,n)}))}function dW(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return FV(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{uW.call(this,t,n,i,this._name)}catch(AM){throw AM}return e.apply(this,n)}))}function uW(e,t,i,r){if(_w(e))for(let n=0;n<e.length;n++)hW.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else hW.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function hW(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function s(e){return{code:hH.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(dw(i)){if(t.required)throw new gH(s(5001));if(dw(t.defaultValue))return void(lw(t.validate)&&t.validate.call(this,i,r,n,o,this));i=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let r=0;r<t.type.length;r++)null===t.type[r]&&null===i&&(e=!0),lw(t.type[r])&&i instanceof t.type[r]&&(e=!0),uw(t.type[r])&&cw(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new gH({code:hH.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>Tw(e)?vw(e):uw(e)?e:cw(e)))},value:i}})}else if(!dw(t.type)&&cw(i)!==t.type)throw new gH(s(5002));if(!1===t.allowEmpty){let e=hw(i)&&(0===i||Number.isNaN(i)),t=uw(i)&&""===i.trim();if(e||t)throw new gH(s(5003))}if(t.notLessThanZero&&hw(i)&&i<0)throw new gH(s(5006));if(!dw(t.min)&&hw(i)&&i<t.min)throw new gH(s(5007));if(!dw(t.max)&&hw(i)&&i>t.max)throw new gH(s(5008));if(uw(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new gH(s(5004))}else if(lw(t.instanceOf)&&!(i instanceof t.instanceOf))throw new gH(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new gH(s(5005));let{properties:a}=t;ow(a)&&mw(i)&&Object.keys(a).forEach((e=>{hW.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;ow(c)&&_w(i)&&i.forEach(((e,t)=>{hW.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),lw(t.validate)&&t.validate.call(this,i,r,n,o,this)}function pW(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r,ignoreLog:n,ignoreErrorLog:o}=e;return FV(((e,s)=>function(){for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];var d,u,h;function p(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...c);if(c[e.argIndex]===t)return e.value}if(t===c||e in c)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(cw(t)):t instanceof MediaStreamTrack?qw(t):(JSON.stringify(t),t)}catch(n){return"type:".concat(cw(t))}}let m=this._log||_M;if(null!=n&&n(...c))return e.apply(this,c);c.length>0?m.info("".concat(s,"() ").concat(JSON.stringify(c,((e,t)=>p(e,t,["userSig","privateMapKey"]))))):m.info("".concat(s,"()"));let _=r?r(...c):MP[s],f=(null==o?void 0:o(...c))||!1;try{let i=e.apply(this,c),r=Aw();if(Ew(i)){let e="".concat(s.includes("Plugin")?"".concat((null==(u=(d=c[0]).getName)?void 0:u.call(d))||""," "):" ");return i.then((i=>(m.info("".concat(s,"() success ").concat(e).concat(t.call(this,...c))),BP.addSuccessEvent({key:_,cost:Aw()-r}),i))).catch((i=>{var r;let n=(i=gH.convertFrom.call(this,i,s,1===c.length?c[0]:c)).extraCode||i.code,o=null!=(r=i.message)&&r.includes(n)?"":" code:".concat(n);throw f||m.error("".concat(s,"() failed ").concat(e).concat(t.call(this,...c)," ").concat(i).concat(o," params: ").concat(JSON.stringify(c,p))),BP.addFailedEvent({key:_,error:i}),i}))}return BP.addSuccessEvent({key:_}),i}catch(DM){let t=(DM=gH.convertFrom.call(this,DM,s)).extraCode||DM.code,i=null!=(h=DM.message)&&h.includes(t)?"":" code:".concat(t);throw f||m.error("".concat(s,"() failed ").concat(DM).concat(i," params: ").concat(JSON.stringify(c,p))),BP.addFailedEvent({key:_,error:DM}),DM}}))}var mW,_W=e=>FV(((t,i)=>function(r,n){return Ab(this,null,(function*(){let o=this._plugins.get(r);if(!o)throw this._log.error("plugin ".concat(String(r)," is not found")),new gH({code:hH.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(lw(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new gH({code:hH.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return uW.call(this,o.getValidateRule(e),[n],i,"TRTC"),t.call(this,o,n)}))})),fW=0,gW=class e{constructor(e){this.core=e,Sb(this,"log"),Sb(this,"customAudioReferenceMap",new Map),Sb(this,"audioRefId",0),Sb(this,"audioContext",Zx()),Sb(this,"localAudioWorkletNode"),Sb(this,"screenAudioWorkletNode"),Sb(this,"mixNode"),Sb(this,"silentNode"),fW+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(fW)}),this.log.info("created id=".concat(this.getAlias()).concat(fW)),this.installEvent()}static getStartValidateRule(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&&!e.room.audioManager.hasScreenAudioTrack)throw new gH({code:hH.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return mW||(mW=this.doPreload(e)),mW}doPreload(e){return Ab(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield Hx(this.audioContext,i)}catch(AM){this.log.error("preload audioProcessor failed. ".concat(AM))}finally{URL.revokeObjectURL(i)}}))}getName(){return e.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return e.getStartValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return Ab(this,null,(function*(){var t,i,r,n;let{room:o}=this.core,{sdkAppId:s,userId:a,userSig:c,assetsPath:l=this.core.assetsPath,audioReference:d,processLevel:u,enableDump:h,isLocalAudioNeedAudioProcess:p=!0,isScreenAudioNeedAudioProcess:m=!1}=e;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=p,this.core.room.audioManager.isScreenAudioNeedAudioProcess=m,!l)throw new gH({code:hH.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload("".concat(l,"/audioProcessor-wasm.js")),p&&!this.localAudioWorkletNode){let{sign:e,status:t,timestamp:i}=yield this.getAuthData(s,a,c);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",s,a,i,e,t,o)}if(m&&!this.screenAudioWorkletNode){let{sign:e,status:t,timestamp:i}=yield this.getAuthData(s,a,c);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",s,a,i,e,t,o)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),null==(t=this.localAudioWorkletNode)||t.port.postMessage({type:"enable"}),null==(i=this.screenAudioWorkletNode)||i.port.postMessage({type:"enable"}),o.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),dw(d)||d.forEach((e=>{this.customAudioReferenceMap.set(e,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:e,refId:"o-".concat(this.audioRefId++)})})),dw(u)||null==(r=this.localAudioWorkletNode)||r.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:u}}),dw(h)||null==(n=this.localAudioWorkletNode)||n.port.postMessage({type:"dump",data:{enable:h}})}))}update(e){return Ab(this,null,(function*(){var t,i,r;let{audioReference:n,enableDump:o,processLevel:s}=e;dw(n)||(this.customAudioReferenceMap.forEach(((e,t)=>{this.customAudioReferenceMap.delete(t),this.core.room.audioManager.updateAudioReference({type:"remove",refId:e})})),n.forEach((e=>{this.customAudioReferenceMap.set(e,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:e,refId:"o-".concat(this.audioRefId++)})}))),dw(s)||null==(t=this.localAudioWorkletNode)||t.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:s}}),dw(o)||(null==(i=this.localAudioWorkletNode)||i.port.postMessage({type:"dump",data:{enable:o}}),null==(r=this.screenAudioWorkletNode)||r.port.postMessage({type:"dump",data:{enable:o}}))}))}stop(){return Ab(this,null,(function*(){var e,t;let{room:i}=this.core;null==(e=this.localAudioWorkletNode)||e.port.postMessage({type:"disable"}),null==(t=this.screenAudioWorkletNode)||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)}))}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(e,t,i){return Ab(this,null,(function*(){let r=String(Date.now()).slice(0,-3),{auth:n,sign:o,status:s,message:a}=yield function(e){return Ab(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]:Sk.MAIN;return"https://".concat(QH[t]||iW(e,t),"/api/v1/audioAiAuth")}(t),"?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(r,"×tamp=").concat(n),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d=JD(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",u="Init RTCAudioProcessor failed.",h="";switch(s){case 1:h="Please check your params.";break;case 2:h="You need to buy packages. Refer to: ".concat(d);break;case 3:h="Server is invalid. Please contact our engineer. ";break;case 4:h="Your packages is not active. Refer to: ".concat(d);break;case 5:h="Your packages is expired. Refer to: ".concat(d);break;case 6:h="Your version is not supported."}return{auth:!1,status:l,message:a?"".concat(u," Reason: ").concat(a,". ").concat(h):"".concat(u,", ").concat(h)}}()}))}({sdkAppId:e,userSig:i,userId:t,timestamp:r});if(!n)throw this.log.info("audioProcessor: ".concat(t," auth result: ").concat(n,". Message: ").concat(a)),new gH({code:hH.INVALID_PARAMETER,message:a});return{sign:o,status:s,timestamp:r}}))}initWorkletNode(e,t,i,r,n,o,s,a){e.port.postMessage({type:"init",data:{sdkAppId:String(i),userId:r,timestamp:n,sign:o,status:s}}),e.port.onmessage=e=>{var i;let{data:r}=e;switch(r.type){case"cost":let e=(null==r?void 0:r.value)>10?"info":"debug";return void this.log[e]("".concat("localAudio"===t?"":"[".concat(t,"] "),"avg cost: ").concat(r.value," max: ").concat(null==r?void 0:r.max,"(").concat(Wb(new Date(null==r?void 0:r.maxCostTimestamp)),") hist: ").concat(null==(i=null==r?void 0:r.hist)?void 0:i.join(" ")));case"log":return void this.log[r.logLevel]("".concat("localAudio"===t?"":"[".concat(t,"] ")).concat(r.value));case"dump":return void dM.emit("265",{room:a,data:r.value,type:"localAudio"===t?"dump":"dump-screen-audio"})}}}handleLocalAudioStarted(e){return Ab(this,null,(function*(){var t;if(this.hitTest(e.room)&&!0===(null==(t=this.core.room.scheduleResult.config)?void 0:t.audioProcessor))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(Xk){this.log.warn("audio processor auto start failed, error: ".concat(Xk))}}))}handleLocalAudioStopped(e){return Ab(this,null,(function*(){var t;!this.hitTest(e.room)||!0!==(null==(t=this.core.room.scheduleResult.config)?void 0:t.audioProcessor)||(yield this.core.trtc.stopPlugin("AudioProcessor"))}))}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(e){return e===this.core.room}};Sb(gW,"updateValidateRule",{type:"object"}),Sb(gW,"stopValidateRule",{type:"object"}),Sb(gW,"Name","AudioProcessor");var EW=gW;var TW=0,vW=class{constructor(e,t){Sb(this,"player"),Sb(this,"publisher"),Sb(this,"mixInput"),this.mixInput=new iV(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&&(dw(e.volume)||(this.volume=e.volume),dw(e.loop)||(this.loop=e.loop),dw(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 yW(e,t){if(t&&"function"!=typeof t)throw new gH({code:hH.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var SW=class e{constructor(e){this.core=e,Sb(this,"log"),Sb(this,"mixedMusicMap",new Map),Sb(this,"cacheMusicMap",new Map),TW+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(TW)}),this.log.info("created id=".concat(this.getAlias()).concat(TW))}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 Ab(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 vW(e,t.audioManager),this.cacheMusicMap.set(i,n)),n.updateListener(e),n.updateSettings(e),yield n.play(),this.mixedMusicMap.set(i,n),n.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:n.mixInput.source.node,refId:"ax-".concat(i)}),this.log.info("start mix audio track ".concat(i," success.")),BP.addEnum({key:502700,value:3}),this.kvUpload(e)}))}update(e){return Ab(this,null,(function*(){let{id:t,operation:i,seekFrom:r,playbackRate:n}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let o=this.mixedMusicMap.get(t);o?(o.updateSettings(e),o.updateListener(e),dw(i)||o.setOperation(i),dw(r)||o.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return Ab(this,arguments,(function(e){var t=this;let{id:i}=e;return function*(){if(t.mixedMusicMap.has(i)){t.log.info("remove music source, music id: ".concat(i));let e=t.mixedMusicMap.get(i);null!=e&&e.mixInput.source.node&&t.core.room.audioManager.updateAudioReference({type:"remove",audioReference:e.mixInput.source.node,refId:"ax-".concat(i)}),null==e||e.stop(),t.mixedMusicMap.delete(i)}"*"===i&&t.destroyAllMusic()}()}))}kvUpload(e){let{track:t,loop:i,volume:r,playbackRate:n,operation:o,seekFrom:s,onTimeUpdate:a,onDurationChange:c,onEnded:l}=e;t&&BP.addCount({key:502711}),i&&BP.addCount({key:502703}),r&&BP.addCount({key:502704}),n&&BP.addCount({key:502705}),o&&BP.addCount({key:502706}),s&&BP.addCount({key:502707}),"function"!=typeof a&&BP.addCount({key:502709}),"function"!=typeof l&&BP.addCount({key:502710}),"function"!=typeof c&&BP.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>{null!=e&&e.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:e.mixInput.track,refId: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()}};Sb(SW,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(e,t,i){if(e.url&&"*"!==e.url){let t=e.url.split("?")[0],r=["mp3","ogg","wav","flac"],n=t.split(".").pop(),o=r.indexOf(n)>=0,s=t.startsWith("blob"),a=t.startsWith("data");if(!(o||s||a))throw new gH({code:hH.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new gH({code:hH.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});yW("onTimeUpdate",e.onTimeUpdate),yW("onEnded",e.onEnded),yW("onDurationChange",e.onDurationChange)}}),Sb(SW,"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){yW("onTimeUpdate",e.onTimeUpdate),yW("onEnded",e.onEnded),yW("onDurationChange",e.onDurationChange)}}),Sb(SW,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),Sb(SW,"Name","AudioMixer");var IW,AW=SW,RW=0,CW=class e{constructor(e){this.core=e,Sb(this,"log"),Sb(this,"audioContext",Zx()),Sb(this,"workletNode"),RW+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(RW)}),this.log.info("created id=".concat(this.getAlias()).concat(RW))}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 gH({code:hH.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return IW||(IW=this.doPreload(e)),IW}doPreload(e){return Ab(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield Hx(this.audioContext,i)}catch(AM){throw this.log.error("load worklet failed",AM),AM}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 Ab(this,null,(function*(){let{room:t,schedule:i}=this.core,{assetsPath:r=this.core.assetsPath}=e;if(!r)throw new gH({code:hH.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload("".concat(r,"/denoiser-wasm.js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:n,status:o,message:s}=yield function(e,t){return Ab(this,arguments,(function(e,t){let{sdkAppId:i,userId:r,userSig:o,timestamp:s}=t;return function*(){try{let{data:{errCode:t,errMsg:n,sign:a,status:c}}=yield e.getAbilityConfig(i,e.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:r,userSig:o,timestamp:s});if("1"===c)return{auth:!0,sign:a,status:c,message:n};let l=JD(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",d="Init RTCAIDenoiser failed.",u="";switch(t){case 1:u="Please check your params.";break;case 2:u="You need to buy packages. Refer to: ".concat(l);break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: ".concat(l);break;case 5:u="Your packages is expired. Refer to: ".concat(l);break;case 6:u="Your version is not supported."}return{auth:!1,status:c,message:n?"".concat(d," Reason: ").concat(n,". ").concat(u):"".concat(d,", ").concat(u)}}catch(n){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(n)}}}()}))}(i,gb(fb({},e),{timestamp:t}));if(!r)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(r,". Message: ").concat(s)),new gH({code:hH.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:n,status:o}}),this.workletNode.port.onmessage=e=>{var t;let{data:i}=e;if("cost"===i.type){let e=(null==i?void 0:i.max)>20?"warn":(null==i?void 0:i.max)>10?"info":"debug";this.log[e]("avg cost: ".concat(i.value," max: ").concat(null==i?void 0:i.max,"(").concat(Wb(new Date(null==i?void 0:i.maxCostTimestamp)),") hist: ").concat(null==(t=null==i?void 0:i.hist)?void 0:t.join(" ")))}else"log"===i.type&&this.log[i.logLevel]("".concat(i.value))}}this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})}))}update(){return Ab(this,null,(function*(){}))}stop(){return Ab(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)}};Sb(CW,"updateValidateRule",{type:"object"}),Sb(CW,"stopValidateRule",{type:"object"}),Sb(CW,"Name","AIDenoiser");var bW=CW;var kW=vb(Rb(),1),DW=class extends kW.EventEmitter{constructor(){super(),Sb(this,"observer"),Sb(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 Ab(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(zb){px.uploadEvent({log:"stat-pressure-detector-start-failed",error:zb})}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&_M.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(Xk){px.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:Xk})}}},wW=new DW;function NW(e){let[t,i]=e,r=i.byteLength,n=parseInt(String(r/255),10),o=r%255,s=[];s.push(0,0,0,1,6,t);for(let c=0;c<n;c++)s.push(255);s.push(o);let a=new DataView(i);return s.push(...new Uint8Array(a.buffer)),s.push(128),new pB(new DataView(new Uint8Array(s).buffer),!0)}function OW(e){return"empty"===e.type||0===e.data.byteLength}function MW(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}function PW(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 LW(e){let{frame:t,seiMessageList:i}=e;if(!i||0===i.length||0===t.data.byteLength)return t;let r=9-PW(t.data);if(r<=0)return t;let n=i.splice(0,r).reverse().map(NW),o=n.reduce(((e,t)=>e+t.dataView.byteLength),0),s=new ArrayBuffer(o+t.data.byteLength),a=new DataView(s),c=new DataView(t.data),l=0;for(let d=0;d<n.length;d++)for(let e=0;e<n[d].dataView.byteLength;e++)a.setInt8(l++,n[d].dataView.getInt8(e));for(let d=0;d<t.data.byteLength;d++)a.setInt8(l++,c.getInt8(d));return t.data=s,t}function xW(e){let{frame:t,onSEI:i}=e;try{let e=new DataView(t.data);if(OW(t)||!MW(e))return t;let r=[],n=0,o=-1,s=-1;for(let i=0;i<t.data.byteLength;i++){let a=e.getUint8(i);if(0===a)n++;else if(1===a){if(2===n||3===n){let a=i-n;if(-1===o?o=a:-1===s&&(s=a,r.push(new pB(new DataView(e.buffer.slice(o,s)))),o=a,s=-1),6!==e.getUint8(i+1)){t.data=e.buffer.slice(a);break}}n=0}else n=0}null==i||i(r.reverse())}catch(zb){}return t}var VW=0,UW=class e{constructor(e){this.core=e,Sb(this,"log"),Sb(this,"_seiMessageList",[]),Sb(this,"_smallSeiMessageList",[]),Sb(this,"_subStreamSeiMessageList",[]),VW++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(VW)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(VW)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:t,mediaType:i}=e;try{return LW({frame:t,seiMessageList:8===i?this._smallSeiMessageList:2===i?this._subStreamSeiMessageList:this._seiMessageList})}catch(Xk){this.log.warn(Xk)}return t}decode(e){let{frame:t,track:i}=e;return xW({frame:t,onSEI:e=>{e.forEach((e=>{this.core.trtc.emit(jH.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:bL?this.encode:LW,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:bL?this.decode:xW,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],o=!!i.small;i.toSubStream?this._subStreamSeiMessageList.push(n):(this._seiMessageList.push(n),o&&this._smallSeiMessageList.push(n)),null==(r=this.core.room.scriptTransformWorker)||r.postMessage({type:"sei",data:n,isMain:!i.toSubStream,small:o})}getName(){return e.Name}getAlias(){return"sei"}getGroup(){return"sei"}};Sb(UW,"autoStart",!0),Sb(UW,"Name","SEI");var FW=UW;function BW(e){let{frame:t,onDump:i}=e;return null==i||i(),t}function HW(e){let{frame:t,onDump:i}=e;return null==i||i(),t}var WW={"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=>{WW["".concat(e,"()")]={tips:"Call trtc.".concat(e),color:"blue",class:"blue",textColor:"#fff"}}));var GW,jW=0,JW=class e{constructor(e){this.core=e,Sb(this,"_core"),Sb(this,"log"),Sb(this,"dumpLocalVideoMap",{}),Sb(this,"dumpRemoteVideoMap",{}),Sb(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++jW)}),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 Ab(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(e){return Ab(this,arguments,(function(e){var t=this;let{visible:i}=e;return function*(){i?(yield t.openDebugDiaLog(),t.addVideoProcessor()):(t.closeDebugDiaLog(),t.removeVideoProcessor())}()}))}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return Ab(this,null,(function*(){var e;if(!this.dialog)try{if(GW)yield GW;else{let t=new URLSearchParams(location.search).get("trtcDebugDialogPath")||(null==(e=window.sessionStorage)?void 0:e.getItem("TRTC_DEBUG_DIALOG_PATH"))||"https://unpkg.com/".concat("trtc-sdk-v5","@").concat(Kb,"/assets/debug-dialog.js");GW=this._core.fileDownloader.loadScript(t),yield GW}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(zb){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(zb))}}))}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):BW,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):HW,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 BW({frame:t,onDump:()=>{if(!i)return;let e=2===i?"sub":"main",r=this.dumpLocalVideoMap[e];r&&(r.data.push(t.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>1e3*r.duration&&r.onDumpEnd())}})}decodeVideo(e){let{frame:t,track:i}=e;return HW({frame:t,onDump:()=>{if(!i)return;let e=this.dumpRemoteVideoMap["".concat(i.userId,"-").concat(i.streamType)];e&&(e.data.push(t.data.slice(0)),e.duration>0&&Date.now()-e.startTimestamp>1e3*e.duration&&e.onDumpEnd())}})}};Sb(JW,"Name","Debug"),Sb(JW,"autoStart",!0);var KW=JW,qW=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},zW=class{constructor(e,t,i){Sb(this,"trackDoneOB"),Sb(this,"startOB"),Sb(this,"stopOB"),Sb(this,"inputFrameCount",0),Sb(this,"decodedFrameCount",0),Sb(this,"type","auto"),Sb(this,"config"),Sb(this,"decoder"),Sb(this,"_decodeSink");let{kvStatManager:r,trtc:n}=e;this.config=i.config,this.trackDoneOB=VU(t,tx.INIT),this.stopOB=bU(),this.startOB=bU(),"auto"===i.type?this.type="webCodecs":this.type=i.type;let o=bU();sU(this.startOB,SU(0),xF((e=>{let i=this.pipe(t);return o.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),sU(i,oF(this.stopOB),nB((()=>{}),(i=>{t.log.error(i),r.addFailedEvent({key:qW(this.type),error:i}),e>4?this.startOB.error(i):this.startOB.next(e+1)}))),sU(i,nF(1),tB(YU))})),oF(this.stopOB),nB((()=>{t.player.setOutput(),o.next("STARTED")}),(e=>{o.next("FAILED")}),(()=>{r.addSuccessEvent({key:qW(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 mU()((t=>Ab(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(AM){e.log.error(AM),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"}))}},YW={type:"object"},XW=class e{constructor(e){this.core=e,Sb(this,"log"),Sb(this,"contextMap",new Map),Sb(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 YW}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 zW(this.core,r,e);return sU(n.trackDoneOB,nF(1),nB((()=>{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 zW(this.core,e.track,e))}}};Sb(XW,"Name","TRTCAudioDecoder");var QW=XW,ZW=class{constructor(){Sb(this,"log"),this.log=_M.createLogger({id:"exp"})}call(e,t){return Ab(this,null,(function*(){return lw(this[e])?this[e](t):Promise.reject(new Ub({code:xb.INVALID_PARAMETER,message:kP({key:AP.API_NOT_EXIST,data:{name:e}})}))}))}enableAudioFrameEvent(e){return Ab(this,null,(function*(){let{trtcInstance:t,enable:i,userId:r,sampleRate:n=48e3,channelCount:o=1,port:s}=e,{audioManager:a}=t.room,{getPCMAbortCtrlMap:c,audioFrameEventConfigMap:l}=a;if(l.set(r,{enable:i,sampleRate:n,channelCount:o,port:s}),i)if("*"===r)t.room.remotePublishedUserMap.forEach((e=>{if(e.remoteAudioTrack.isAvailable){if(c.get(e.userId))return;let i=a.getPCM((e=>{t.emit(jH.AUDIO_FRAME,e)}),e.userId);c.set(e.userId,i)}}));else{if(c.get(r))return;let e=a.getPCM((e=>{t.emit(jH.AUDIO_FRAME,e)}),r);c.set(r,e)}else if("*"===r)t.room.remotePublishedUserMap.forEach((e=>{if(e.remoteAudioTrack.isSubscribed){let{userId:t}=e,i=c.get(t);null==i||i.abort("disable"),c.delete(t)}}));else{let e=c.get(r);null==e||e.abort("disable"),c.delete(r)}}))}};yb([function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return FV(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return nH.call(this,t,n,i,this._name),e.apply(this,n)}))}({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],ZW.prototype,"enableAudioFrameEvent",1);var $W=new ZW,eG=vb(Rb(),1),tG=class extends eG.EventEmitter{constructor(){super(),Sb(this,"states",{}),Sb(this,"permissionChangeHandler"),Sb(this,"log"),this.log=_M.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:null==(e=this.states.camera)?void 0:e.state,microphone:null==(t=this.states.microphone)?void 0:t.state})}}request(e){return Ab(this,null,(function*(){if(this.log.info("request ".concat(e.join(", "))),0===e.length)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach((e=>e.stop()))}))}get(e){return Ab(this,null,(function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info("get ".concat(e," permission state: ").concat(this.states[e].state)),this.states[e].state}catch(Xk){return this.log.error("get ".concat(e," permission failed, error: ").concat(Xk instanceof Error?Xk.message:Xk)),null}}))}destroy(){Object.values(this.states).forEach((e=>{null==e||e.removeEventListener("change",this.permissionChangeHandler)})),this.states={}}},iG=new tG,rG=0,nG=new Set,oG=null;qb("5.13.0-beta.16"),gM.checkStorage();var sG=class e extends Pb.EventEmitter{constructor(t,i){super(),Sb(this,"_room"),Sb(this,"_eventListened",new Set),Sb(this,"_localVideoTrack",null),Sb(this,"_localAudioTrack",null),Sb(this,"_localScreenTrack",null),Sb(this,"_localScreenAudioTrack",null),Sb(this,"_localVideoConfig",null),Sb(this,"_localScreenConfig",null),Sb(this,"_localAudioConfig",null),Sb(this,"_remoteVideoConfigMap",new Map),Sb(this,"_remoteAudioConfigMap",new Map),Sb(this,"_remoteAudioVolumeMap",new Map),Sb(this,"_remoteAudioMuteMap",new Map),Sb(this,"_mediaTrackMap",new WeakMap),Sb(this,"_log",_M.createLogger({id:"t".concat(++rG)})),Sb(this,"_plugins",new Map),Sb(this,"_networkQuality",null),Sb(this,"_speakerId"),Sb(this,"enterRoomParams"),Sb(this,"_enableAutoSwitchWhenRecapturing",!0),this._room=new t(fb({logger:this._log,frameWorkType:e.frameWorkType},i)),this._room.videoDecodeFallbackType=i.videoDecodeFallback,pw(i.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=i.enableAutoSwitchWhenRecapturing),this._log.info("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(AW,i.assetsPath),this._use(EW,i.assetsPath),this._use(bW,i.assetsPath),this._use(QW,i.assetsPath),this._use(KW),i.enableSEI&&DL&&this._use(FW),this._room.on("audio-volume",(e=>{var t,r;!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*(null!=(t=this._localAudioTrack.getInternalAudioLevelAfter3A())?t:this._localAudioTrack.getAudioLevel())),floatVolume:null!=(r=this._localAudioTrack.getInternalAudioLevelAfter3A())?r:this._localAudioTrack.getInternalAudioLevel()}),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(jH.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{this._log.error(new gH({code:hH.OPERATION_FAILED,extraCode:5504,message:e.message,originError:e}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:i}=e;e.emit=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{return i.apply(e,n)}catch(AM){let i=kP({key:AP.CATCH_HANDLER_ERROR,data:{name:t,event:n[0]},addDocLink:!1});return _M.warn("".concat(i,"\n\n").concat(AM.stack)),!1}}})(this,"trtc")}static create(e){}static _create(t,i){!function(){var e;if(dH){dH=!1,5!==_M.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(ok,"/en/index.html")),console.info("* Changelog: ".concat(ok,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),_M.info("TRTC Web SDK Version:",Kb),KO||_M.debug("Build Time:","2025-08-25 16:21:27");let t="UA: ".concat(navigator.userAgent," \nCPU core: ").concat(navigator.hardwareConcurrency,", GPU: ").concat(eM()),i=navigator.deviceMemory;i&&(t+=", minRAM: ".concat(i,"GB")),_M.info(t),_M.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),$O().then((e=>{e&&_M.info(ZO)}))}}();let r=new e(t,i||{});return nG.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){ux(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(jH.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(jH.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().finally((()=>{this.emit(jH.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().finally((()=>{this.emit(jH.ERROR,gH.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(jH.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e;let t=gb(fb({},e),{uplinkRTT:Math.min(e.uplinkRTT,ID),downlinkRTT:Math.min(e.downlinkRTT,ID)});this.emit(jH.NETWORK_QUALITY,t)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{ux(t,t).add("player-state-changed",(i=>{let r=gb(fb({},i),{userId:e.userId});t.kind===Sk.VIDEO&&(r.streamType=EH(t.streamType)),this.emit(t.kind===Sk.AUDIO?jH.AUDIO_PLAY_STATE_CHANGED:jH.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===xb.PLAY_NOT_ALLOWED&&this.emit(jH.AUTOPLAY_FAILED,{userId:t.userId,mediaType:t.strMediaType,resume:()=>t.player.resume()})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{hx(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:r}=i,n=t.audioAvailable,o=t.videoAvailable,{audioAvailable:s,videoAvailable:a}=i;s||this._remoteAudioConfigMap.delete(r),a||this._removeRemoteVideoConfig(r,"main"),i.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),o!==a&&(a?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(a?jH.REMOTE_VIDEO_AVAILABLE:jH.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),n!==s&&(s?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i}),this.emit(s?jH.REMOTE_AUDIO_AVAILABLE:jH.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?jH.REMOTE_VIDEO_AVAILABLE:jH.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))})).add("sei-message",(e=>{this.emit(jH.SEI_MESSAGE,gb(fb({},e),{streamType:EH(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(jH.ERROR,new gH({code:hH.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,i,r,n,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(r=this._networkQuality)?void 0:r.downlinkRTT)||0,ID),upLoss:(null==(n=this._networkQuality)?void 0:n.uplinkLoss)||0,downLoss:(null==(o=this._networkQuality)?void 0:o.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/uP},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)/uP,point2pointDelay:(e.msg_audio_status.uint32_audio_p2p_delay||0)+(e.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:e.msg_audio_status.uint32_audio_cache_ms||0},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],point2pointDelay:(e.uint32_video_p2p_delay||0)+(e.uint32_video_cache_ms||0),jitterBufferDelay:e.uint32_video_cache_ms||0,codec:e.uint32_video_codec})))})))};this.emit(jH.STATISTICS,l)})).add("custom-message",(e=>{this.emit(jH.CUSTOM_MESSAGE,e)})).add("layerData",(e=>this.emit(jH.LAYER_DATA,e))).add("first-video-frame",(e=>{this.emit(jH.FIRST_VIDEO_FRAME,gb(fb({},e),{streamType:EH(e.streamType)}))})).add("audio-frame",(e=>{this.emit(jH.AUDIO_FRAME,e)})),ux(this,mV).add("audioInputAdded",(e=>{this.emit(jH.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(jH.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(jH.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(jH.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>Ab(this,null,(function*(){if(this.emit(jH.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),oG&&oG.deviceId===fD){let e=(yield vV()).find((e=>e.deviceId===fD));e&&oG.groupId!==e.groupId&&(oG=e,this.emit(jH.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>Ab(this,null,(function*(){this.emit(jH.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield vV())[0];if(!t||!oG||oG.groupId===t.groupId)return;let i=oG.deviceId===e.deviceId,r=oG.deviceId===fD&&oG.deviceId===t.deviceId;(i||r)&&(oG=t,this.emit(jH.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})))),ux(this,iG).add("permission-state-change",(e=>{this.emit(jH.PERMISSION_STATE_CHANGE,e)}))}use(e){let t,i;"plugin"in e?(t=e.plugin,i=e.assetsPath):t=e,this._use(t,i)}_use(t,i){if(this._plugins.get(t.Name))return void this._log.warn("duplicate install plugin",t.Name);let r=new t(aW.call(this,{TRTC:e,room:this._room,assetsPath:i,errorModule:{RtcError:gH,ErrorCode:hH,CoreErrorCode:xb,ErrorCodeDictionary:pH}}));this._plugins.set(t.Name,r),r.__v_skip=!0,t.autoStart&&this.startPlugin(t.Name)}enterRoom(t){return Ab(this,null,(function*(){var i,r;this.enterRoomParams=t;let{scene:n="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:a=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!uw(t.proxy)&&t.proxy.turnServer&&(null==(r=(i=this._room).setTurnServer)||r.call(i,t.proxy.turnServer,t.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=a,pw(t.preferHW)&&(this._room.preferHW=t.preferHW),t.playoutDelay&&(this._room.playoutDelay=t.playoutDelay),t.jitterBufferDelay&&(this._room.jitterBufferDelay=t.jitterBufferDelay);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,useH265:t.useH265,keepAlive:t.keepAlive};t.strRoomId&&!t.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(c,n,e.frameWorkType),this._checkTrackToPublish(),wW.start()}))}exitRoom(){return Ab(this,null,(function*(){return yield this._exitRoom()}))}switchRoom(e){return Ab(this,null,(function*(){if(this.room.isSwitchRoomSupported())try{yield this._room.switchRoom(e)}catch(Xk){if(!(Xk instanceof Vb)||Xk.code!==xb.API_CALL_TIMEOUT&&Xk.code!==xb.SWITCH_ROOM_FAILED)throw Xk;this._log.warn("switchRoom ".concat(Xk.code===xb.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(e)}else yield this._rejoinRoom(e)}))}_rejoinRoom(e){return Ab(this,null,(function*(){yield this.exitRoom();let t=fb(fb({},this.enterRoomParams),e);yield this.enterRoom(t)}))}switchRole(e,t){return Ab(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(){hx(this),this.removeAllListeners(),this._room.destroy(),nG.delete(this),0===nG.size&&wW.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(),dM.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:i=!0,mute:r,option:n}=t,o=new hB(e._room.audioManager),s={},a={muted:!0};n&&(dw(n.microphoneId)?dw(n.audioTrack)||(s.customSource=n.audioTrack):s.deviceId=n.microphoneId,n&&hw(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),dw(n.profile)||(uw(n.profile)?gk[n.profile]&&o.setProfile(gk[n.profile]):o.setProfile(n.profile)),hw(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),dw(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),dw(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),dw(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl),pw(e._enableAutoSwitchWhenRecapturing)&&(o.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),o.on("5",(t=>{e.emit(jH.ERROR,new gH({code:hH.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(jH.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=gH.convertFrom(t.error)),e.emit(jH.PUBLISH_STATE_CHANGED,gb(fb({},t),{error:i}))})),o.on("6",(()=>{e.emit(jH.ERROR,new gH({code:hH.OPERATION_FAILED,extraCode:5506,message:"audio encode failed"}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),dw(r)||o.setMute(r),ux(o,o).add("player-state-changed",(t=>{e.emit(jH.AUDIO_PLAY_STATE_CHANGED,gb(fb({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localAudioTrack=o,e._localAudioConfig=gb(fb({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:a,track:o}),dM.emit("113",{userId:"",room:e.room})}()}))}updateLocalAudio(e){return Ab(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):dw(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),dw(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),dw(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!dw(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),dw(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Ow(this._localAudioConfig,e)}))}stopLocalAudio(){return Ab(this,null,(function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),dM.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),hx(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null,capture:!0};return function*(){var i;if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:r,publish:n=!0,capture:o=!0,mute:s,option:a}=t,c=new fB(e._room.videoManager),l={},d={};a&&(pw(a.avoidCropping)&&(c.avoidCropping=a.avoidCropping),a.cameraId?l.deviceId=a.cameraId:dw(a.useFrontCamera)?dw(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?Sk.FACING_MODE_USER:Sk.FACING_MODE_ENVIRONMENT,dw(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=TH(a.qosPreference)),dw(a.profile)||(uw(a.profile)?Ek[a.profile]&&c.setProfile(Ek[a.profile]):c.setProfile(a.profile)),dw(a.fillMode)||(d.objectFit=a.fillMode),dw(a.mirror)||(d.mirror=a.mirror),dw(a.small)||(dw(a.smallMode)||(e._room.smallMode=a.smallMode),pw(a.small)&&!1===a.small?c.stopSmall():c.updateSmallConfig(vH(a.small,!0))),dw(a.rotation)||c.setRotation(a.rotation),pw(e._enableAutoSwitchWhenRecapturing)&&(c.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),c.once("first-video-frame",(t=>{e.emit(jH.FIRST_VIDEO_FRAME,gb(fb({},t),{streamType:EH(t.streamType)}))})),c.on("5",(t=>{e.emit(jH.ERROR,new gH({code:hH.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),c.on("2",(t=>{e.emit(jH.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),c.on("4",(t=>{let i;t.error&&(i=gH.convertFrom(t.error)),e.emit(jH.PUBLISH_STATE_CHANGED,gb(fb({},t),{error:i}))})),c.on("6",(()=>{e.emit(jH.ERROR,new gH({code:hH.OPERATION_FAILED,extraCode:5505,message:"video encode failed"}))})),e._listenOutputTrackChanged(c),o?yield c.capture(l):null==(i=c.manager)||i.changeInput(c),dw(s)||(yield c.setMute(s)),ux(c,c).add("player-state-changed",(t=>{e.emit(jH.VIDEO_PLAY_STATE_CHANGED,gb(fb({},t),{userId:"",streamType:"main"}))})).add("video-size-changed",(t=>{e.emit(jH.VIDEO_SIZE_CHANGED,gb(fb({},t),{streamType:EH(t.streamType)}))})),n&&e._room.isJoined&&e._room.publish(c).catch((()=>{})),e._localVideoTrack=c,e._localVideoConfig=gb(fb({},t),{view:r,publish:n,capture:o}),yield e._updateVideoPlayOption({view:r,playOption:d,track:c})}()}))}updateLocalVideo(e){return Ab(this,null,(function*(){var t,i,r;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:n,publish:o,mute:s,capture:a,option:c}=e,l={};if(this._localVideoConfig.capture)!1!==a?null!=c&&c.cameraId?yield this._localVideoTrack.switchDevice(null==c?void 0:c.cameraId):dw(null==c?void 0:c.useFrontCamera)?dw(null==c?void 0:c.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(null==c?void 0:c.videoTrack)):yield this._localVideoTrack.switchDevice(null!=c&&c.useFrontCamera?Sk.FACING_MODE_USER:Sk.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(a){let e={};e.deviceId=(null==c?void 0:c.cameraId)||(null==(t=this._localVideoConfig.option)?void 0:t.cameraId),e.facingMode=null!=c&&c.useFrontCamera||null!=(i=this._localVideoConfig.option)&&i.useFrontCamera?Sk.FACING_MODE_USER:Sk.FACING_MODE_ENVIRONMENT,e.customSource=(null==c?void 0:c.videoTrack)||(null==(r=this._localVideoConfig.option)?void 0:r.videoTrack),yield this._localVideoTrack.capture(e)}c&&(dw(c.profile)||(uw(c.profile)?Ek[c.profile]&&this._localVideoTrack.setProfile(Ek[c.profile]):this._localVideoTrack.setProfile(c.profile),(!c.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(c.cameraId))&&dw(c.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),dw(c.fillMode)||(l.objectFit=c.fillMode),dw(c.mirror)||(l.mirror=c.mirror),dw(c.rotation)||this._localVideoTrack.setRotation(c.rotation),c.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(TH(c.qosPreference)),dw(c.small)||(pw(c.small)&&!c.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(vH(c.small,!0)))),this._room.isJoined&&dw(o)&&this._localVideoConfig.publish&&a&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._room.isJoined&&((null!=o?o:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch((()=>{})):this._room.unpublish(this._localVideoTrack).catch((()=>{}))),dw(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:n,playOption:l,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Ow(this._localVideoConfig,e)}))}stopLocalVideo(){return Ab(this,null,(function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),hx(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){var i,r;if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:n=null,publish:o=!0,muteSystemAudio:s,option:a}=t,c=new JB(e._room.videoManager);c.on("4",(t=>{let i;t.error&&(i=gH.convertFrom(t.error)),e.emit(jH.PUBLISH_STATE_CHANGED,gb(fb({},t),{error:i}))})),c.once("first-video-frame",(t=>{e.emit(jH.FIRST_VIDEO_FRAME,gb(fb({},t),{streamType:EH(t.streamType)}))})),e._listenOutputTrackChanged(c),"main"===t.streamType&&(c.mediaType=4);let l=null,d={},u={};a&&(dw(a.profile)||(uw(a.profile)?yk[a.profile]&&c.setProfile(yk[a.profile]):c.setProfile(a.profile)),a.systemAudio&&(d.systemAudio=!0,d.echoCancellation=a.echoCancellation,d.noiseSuppression=a.noiseSuppression,d.autoGainControl=a.autoGainControl),dw(a.fillMode)||(u.objectFit=a.fillMode),a.videoTrack&&(d.videoTrack=a.videoTrack),a.audioTrack&&(d.audioTrack=a.audioTrack),a.captureElement&&(d.captureElement=a.captureElement),a.preferDisplaySurface&&(d.preferDisplaySurface=a.preferDisplaySurface),a.qosPreference&&(d.contentHint=TH(a.qosPreference)));let h=yield c.capture(d);if(c.mediaTrack.addEventListener(Sk.ENDED,(()=>{e._stopScreenShare(),e.emit(jH.SCREEN_SHARE_STOPPED)})),h.getAudioTracks()[0]){l=new qB(e._room.audioManager);let n=h.getAudioTracks()[0];null!=(i=t.option)&&i.systemAudio&&!(null!=(r=t.option)&&r.audioTrack)&&(l.sourceTrack=n),yield l.setInputMediaStreamTrack(n),pw(s)&&l.mediaTrack&&(l.mediaTrack.enabled=!s),e._speakerId&&l.setAudioOutput(e._speakerId)}if(ux(c,c).add("player-state-changed",(t=>{e.emit(jH.VIDEO_PLAY_STATE_CHANGED,gb(fb({},t),{userId:"",streamType:"sub"}))})),o&&e._room.isJoined){let t=[c];l&&(t.push(l),e._checkScreenAudioEchoCancellation(c,l)),e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=c,e._localScreenAudioTrack=l,e._localScreenConfig=gb(fb({},t),{view:n,publish:o}),yield e._updateVideoPlayOption({view:n,playOption:u,track:c})}()}))}updateScreenShare(e){return Ab(this,null,(function*(){var t;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:i,publish:r,muteSystemAudio:n,option:o}=e,s={};if(o&&(dw(o.fillMode)||(s.objectFit=o.fillMode),o.qosPreference)){let e=TH(o.qosPreference);this._localScreenTrack.setContentHint(e)}if(this._room.isJoined&&!dw(r)){if(r&&!this._localScreenConfig.publish){let e=[this._localScreenTrack];this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._room.publish(...e).catch((()=>{}))}if(this._localScreenConfig.publish&&!r){let e=[this._localScreenTrack];this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._room.unpublish(...e).catch((()=>{}))}}null!=(t=this._localScreenAudioTrack)&&t.mediaTrack&&pw(n)&&(this._localScreenAudioTrack.mediaTrack.enabled=!n),yield this._updateVideoPlayOption({view:i,playOption:s,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Ow(this._localScreenConfig,e)}))}stopScreenShare(){return Ab(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return Ab(this,null,(function*(){let{view:t,userId:i,streamType:r,option:n}=e,o="".concat(i,"_").concat(r);if(this._remoteVideoConfigMap.has(o))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(r));let s=this._room.remotePublishedUserMap.get(i);if(!s)return;let a={},c="main"===r?s.remoteVideoTrack:s.remoteAuxiliaryTrack;c.on("decode-failed",(e=>{this.emit(jH.ERROR,new gH({code:hH.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))})),c.on("video-size-changed",(e=>{this.emit(jH.VIDEO_SIZE_CHANGED,gb(fb({},e),{streamType:EH(e.streamType)}))})),this._listenOutputTrackChanged(c),n&&(dw(n.fillMode)||(a.objectFit=n.fillMode),dw(n.mirror)||(a.mirror=n.mirror),dw(n.poster)||(a.poster=n.poster),a.canvasRender=n.canvasRender,"main"===r&&!dw(n.small)&&(!s.remoteVideoTrack.isSubscribing&&!s.remoteVideoTrack.isSubscribed&&s.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(o,{config:e}),n&&!dw(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return Ab(this,null,(function*(){var t,i;let{view:r,userId:n,streamType:o,option:s}=e,a="".concat(n,"_").concat(o),c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(n))return;let l={};s&&(dw(s.fillMode)||(l.objectFit=s.fillMode),dw(s.mirror)||(l.mirror=s.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);if("main"===o&&null!=u&&u.muteState.hasVideo&&(d=u.remoteVideoTrack),"sub"===o&&null!=u&&u.muteState.hasAuxiliary&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:h}=c;"main"===o&&s&&!dw(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:h}),Ow(h,e);let p=dw(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=dw(r)?h.view:r,_=dw(null==s?void 0:s.viewRoot)?null==(i=h.option)?void 0:i.viewRoot:s.viewRoot;this._observeView({remoteTrack:d,view:m,receiveWhenViewVisible:p,viewRoot:_})}))}stopRemoteVideo(e){return Ab(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ab(this,null,(function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:n,remoteAuxiliaryTrack:o}=r;"main"===e.streamType&&(n.stop(),t.hasVideo&&i.push(n)),"sub"===e.streamType&&(o.stop(),t.hasAuxiliary&&i.push(o))}for(let e of i)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.delete(e.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)}))}_removeRemoteVideoConfig(e,t){let i="".concat(e,"_").concat(t),r=this._remoteVideoConfigMap.get(i);r&&r.observer&&r.observer.disconnect(),this._remoteVideoConfigMap.delete(i)}muteRemoteAudio(e,t){return Ab(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(AM){throw AM.code!==hH.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),AM}}))}setRemoteAudioVolume(e,t){if("*"===e){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach(((e,i)=>this._remoteAudioVolumeMap.set(i,t)));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 Ab(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return Ab(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return Ab(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,i),this._eventListened.add(e),this.listeners(jH.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:e}=this.room.audioManager;e.get("")||e.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return 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{JH.has(e)&&this._log.debug("emit ".concat(e," ").concat(JSON.stringify(i)))}catch(AM){}return super.emit(e,...i)}off(t,i,r){if(this._log.debug("off",t),"*"===t?(this._eventListened.clear(),this.removeAllListeners()):super.off(t,i,r),(t===e.EVENT.AUDIO_FRAME||"*"===t)&&0===this.listeners(e.EVENT.AUDIO_FRAME).length){let{getPCMAbortCtrlMap:e}=this.room.audioManager;e.forEach((e=>{null==e||e.abort("off")})),e.clear()}return this}getAudioTrack(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},i=null,r="main",n=!1;if(uw(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 Ab(this,null,(function*(){(yield vV()).forEach((t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(jH.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),oG=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 Ab(this,null,(function*(){var t;let{userId:i}=e;if(this._remoteAudioConfigMap.has(i))return void this._log.warn("remote audio has already started. userId:".concat(i));let r=this._room.remotePublishedUserMap.get(i);if(!r)return;let n={},o=r.remoteAudioTrack;o.on("decode-failed",(e=>{this.emit(jH.ERROR,new gH({code:hH.OPERATION_FAILED,extraCode:5506,message:"audio decode failed"}))})),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId);try{let r=null!=(t=this._remoteAudioVolumeMap.get(i))?t:this._remoteAudioVolumeMap.get("*"),s=hw(r)?r:100;n.volume=s,this._remoteAudioConfigMap.set(i,e),yield this._room.subscribe(o),sU(VU(o,"decode-failed"),oF(VU(o,tx.INIT)),nB((()=>{this.startPlugin(QW.Name,{track:o,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})}))),yield this._updateAudioPlayOption({playOption:n,track:o}),dM.emit("115",{userId:i,room:this.room}),o.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:o.outMediaTrack,refId:"ra-".concat(i)})}catch(bM){throw this._remoteAudioConfigMap.delete(i),bM}this._emitTrackEvent(o)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ab(this,null,(function*(){let i=this._room.remotePublishedUserMap.get(e.userId);i&&(i.remoteAudioTrack.stop(),i.muteState.hasAudio&&t&&(yield this._room.unsubscribe(i.remoteAudioTrack)),this._mediaTrackMap.delete(i.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId)),dM.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:"ra-".concat(e.userId)})}))}_enableVideoDecodeFallback(e,t){let i,r=this._room.videoDecodeFallbackType;r&&this._plugins.has("TRTCVideoDecoder")&&(e.log.debug("remote video will fall back when decode failed",e.id),sU(VU(e,"decode-failed"),oF(VU(e,tx.INIT)),oB((()=>{"h265"!==this._room.downlinkVideoCodec&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})})),UF(VU(e,"decode-downgrade-state-changed")),nB((r=>{i=r.state,this.emit(jH.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,gb(fb({},r),{streamType:t,userId:e.userId}))}),(t=>{e.log.error("fallback",t)}),(()=>{"STARTED"===i&&e.log.info("fallback complete")}))))}_updateVideoPlayOption(e){return Ab(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),dw(t)&&n&&n.view&&!kw(i)){let e=Pw(n.view);e.length>0&&(yield r.play(e,i))}if(!dw(t)){let e=Pw(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return Ab(this,arguments,(function(e){var t=this;let{playOption:i={},track:r,prevConfig:n}=e;return function*(){if(!r.isPlayCalled)try{yield r.play(null,i)}catch(Yb){}if(dw(i.muted)||r.setPlayerMute(i.muted),dw(i.volume)||r.setAudioVolume(i.volume/100),r instanceof hB&&r.mediaTrack){let e=!1===i.muted&&!dw(i.volume)&&i.volume>0?"add":"remove";t.room.audioManager.updateAudioReference({type:e,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof $B){let e=i.muted?0:i.volume;if(dw(e))return;t.room.audioManager.updateAudioReference({type:"updateVolume",refId:"ra-".concat(r.userId),volume:i.volume})}}()}))}_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(jH.TRACK,{userId:i,streamType:EH(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),this._checkScreenAudioEchoCancellation(this._localScreenTrack,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(dw(i))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(EH(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||_w(i)&&0===i.length||!r)return null==s||s.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch((()=>{})));let a=o.visibleViewMap||new Map,c=-1;(!s||s.root!==n)&&(null==s||s.disconnect(),a.clear(),s=new IntersectionObserver((e=>{e.forEach((e=>{a.set(e.target,e.isIntersecting),t.log.info("view ".concat(e.target.id," is").concat(e.isIntersecting?"":" not"," visible"))})),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(Pw(i));a.forEach(((e,t)=>{l.has(t)||(s.unobserve(t),a.delete(t))})),l.forEach((e=>{a.set(e,!0),s.observe(e)})),s.takeRecords().forEach((e=>{a.set(e.target,e.isIntersecting)})),o.visibleViewMap=a,o.observer=s}_exitRoom(){return Ab(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(),function(e){let t=cW.get(e);t&&(t.forEach((e=>clearTimeout(e))),cW.delete(e))}(this),this._room.remotePublishedUserMap.forEach((e=>{hx(e.remoteAudioTrack),hx(e.remoteVideoTrack),hx(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return Ab(this,null,(function*(){var e,t;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&&(!1===(null==(t=this._localScreenAudioTrack.trackSettings)?void 0:t.echoCancellation)&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),hx(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_checkScreenAudioEchoCancellation(e,t){return Ab(this,null,(function*(){var i,r;if(!e||!t)return;let n=null==(i=e.trackSettings)?void 0:i.displaySurface;if(!1===(null==(r=t.trackSettings)?void 0:r.echoCancellation)&&("monitor"===n||"browser"===n&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(RM){this._log.warn("start audioProcessor plugin failed: ",RM)}}}))}_onLocalTrackCaptured(e){let{track:t}=e;"audio"===t.kind&&(!oG||_V(oG))&&(this._initActiveSpeaker(),dM.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return Ab(this,null,(function*(){if(oG&&!_V(oG))this.emit(jH.DEVICE_CHANGED,{type:"speaker",action:"active",device:oG});else{let e=yield vV();e[0]&&!_V(e[0])?(oG=e[0],this.emit(jH.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):dM.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:gb(fb({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),BP.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),BP.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return Ab(this,null,(function*(){return this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(t),")")),$W.call(e,fb({trtcInstance:this},t))}))}static setLogLevel(e,t){_M.setLogLevel(e),dw(t)||(t?_M.enableUploadLog():_M.disableUploadLog())}static isSupported(){return ZP(e.frameWorkType)}static getPermissions(e){return Ab(this,arguments,(function(e){let{request:t=!0,types:i=["camera","microphone"]}=e;return function*(){t&&(yield iG.request(i).catch((e=>{var t;return _M.error("getPermissions request failed, error: ".concat(null!=(t=null==e?void 0:e.message)?t:e))})));let[e,r]=yield Promise.all([iG.get("camera"),iG.get("microphone")]);return{camera:e,microphone:r}}()}))}static getCameraList(){return EV(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return gV(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return vV(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(t){return Ab(this,null,(function*(){if(!CN||t!==uH.SPEAKER&&t!==uH.HEADSET)(yield vV()).forEach((e=>{e.deviceId===t&&(nG.forEach((i=>{i._setCurrentSpeaker(t),i.emit(jH.DEVICE_CHANGED,{type:"speaker",action:"active",device:e})})),oG=e)}));else{let i=yield e.getMicrophoneList(),r="";if(i.forEach((e=>{e.label===t&&(r=e.deviceId)})),!r)return;nG.forEach((e=>Ab(this,null,(function*(){e._localAudioTrack&&(yield e.updateLocalAudio({option:{microphoneId:r}}))}))))}}))}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:o,version:s,max:a}=e;switch(s&&(FP.version=s),t){case"count":FP.addCount({key:i,useUV:o});break;case"enum":FP.addEnum({key:i,value:r,useUV:o});break;case"number":FP.addNumber({key:i,value:r,split:n,max:a})}}};Sb(sG,"_loggerManager",_M),Sb(sG,"EVENT",jH),Sb(sG,"ERROR_CODE",hH),Sb(sG,"TYPE",uH),Sb(sG,"frameWorkType",30),yb([pW({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"}})})],sG.prototype,"use",1),yb([lW(OH.TRTC.enterRoom),HH("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})),FV((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),pW()],sG.prototype,"enterRoom",1),yb([pW()],sG.prototype,"exitRoom",1),yb([lW(OH.TRTC.switchRoom),pW(),JV()],sG.prototype,"switchRoom",1),yb([lW(OH.TRTC.switchRole),WH("room",{merge:(e,t)=>t}),pW()],sG.prototype,"switchRole",1),yb([pW()],sG.prototype,"destroy",1),yb([lW(OH.TRTC.startLocalAudio),HH("audio",((e,t)=>{let[i]=e,[r]=t;var n,o;return(null==(n=null==i?void 0:i.option)?void 0:n.microphoneId)===(null==(o=null==r?void 0:r.option)?void 0:o.microphoneId)})),pW()],sG.prototype,"startLocalAudio",1),yb([lW(OH.TRTC.updateLocalAudio),WH("audio",{debounce:{delay:200,getKey:()=>"".concat(rG,"-localAudio"),isNeedToDebounce:e=>{var t;return!dw(null==(t=e.option)?void 0:t.captureVolume)}}}),pW()],sG.prototype,"updateLocalAudio",1),yb([GH("audio"),pW()],sG.prototype,"stopLocalAudio",1),yb([lW(OH.TRTC.startLocalVideo),HH("video",((e,t)=>{let[i]=e,[r]=t;var n,o;return(null==(n=null==i?void 0:i.option)?void 0:n.cameraId)===(null==(o=null==r?void 0:r.option)?void 0:o.cameraId)})),pW()],sG.prototype,"startLocalVideo",1),yb([lW(OH.TRTC.updateLocalVideo),WH("video"),pW()],sG.prototype,"updateLocalVideo",1),yb([GH("video"),pW()],sG.prototype,"stopLocalVideo",1),yb([lW(OH.TRTC.startScreenShare),HH("screen",(()=>!0)),pW()],sG.prototype,"startScreenShare",1),yb([lW(OH.TRTC.updateScreenShare),WH("screen"),pW()],sG.prototype,"updateScreenShare",1),yb([pW()],sG.prototype,"stopScreenShare",1),yb([lW(OH.TRTC.startRemoteVideo),HH((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),pW({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],sG.prototype,"startRemoteVideo",1),yb([lW(OH.TRTC.updateRemoteVideo),WH((e=>"v".concat(e.userId).concat(e.streamType))),pW({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],sG.prototype,"updateRemoteVideo",1),yb([lW(OH.TRTC.stopRemoteVideo),FV((e=>function(t){return Ab(this,null,(function*(){if("*"===t.userId){let e=[];return this._room.remotePublishedUserMap.forEach((t=>{this._remoteVideoConfigMap.has("".concat(t.userId,"_main"))&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch((()=>{}))),this._remoteVideoConfigMap.has("".concat(t.userId,"_sub"))&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch((()=>{})))})),Promise.all(e)}return e.call(this,t)}))})),pW({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],sG.prototype,"stopRemoteVideo",1),yb([GH((e=>"v".concat(e.userId).concat(e.streamType)))],sG.prototype,"_stopRemoteVideo",1),yb([lW(...OH.TRTC.muteRemoteAudio),pW({getRemoteId:e=>e})],sG.prototype,"muteRemoteAudio",1),yb([dW(...OH.TRTC.setRemoteAudioVolume),function(e,t){return FV(((i,r)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let s=cW.get(this);s||(s=new Map,cW.set(this,s));let a=t(...n),c=s.get(a);if(!c||c<=0){i.apply(this,n);let t=setTimeout((()=>{var e;null==(e=cW.get(this))||e.delete(a)}),e);s.set(a,t)}else{clearTimeout(c);let t=window.setTimeout((()=>{var e;i.apply(this,n),null==(e=cW.get(this))||e.delete(a)}),e);s.set(a,t)}}))}(200,(e=>e)),pW({getRemoteId:e=>e})],sG.prototype,"setRemoteAudioVolume",1),yb([_W("start"),VV((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),HH(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),pW({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>PP[e.getName()],ignoreLog:e=>"Debug"===e.getName(),ignoreErrorLog:e=>"AudioProcessor"===e.getName()})],sG.prototype,"startPlugin",1),yb([_W("update"),WH(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),{merge:(e,t)=>(Ow(e[1],t[1]),e)}),pW({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>LP[e.getName()]})],sG.prototype,"updatePlugin",1),yb([_W("stop"),GH(((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i})),pW({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>xP[e.getName()]})],sG.prototype,"stopPlugin",1),yb([dW(...OH.TRTC.enableAudioVolumeEvaluation)],sG.prototype,"enableAudioVolumeEvaluation",1),yb([pW()],sG.prototype,"getVideoSnapshot",1),yb([pW()],sG.prototype,"_setCurrentSpeaker",1),yb([HH((e=>"a".concat(e.userId)),(()=>!0))],sG.prototype,"_startRemoteAudio",1),yb([FV((e=>function(t){return Ab(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(gb(fb({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),GH((e=>"a".concat(e.userId)))],sG.prototype,"_stopRemoteAudio",1),yb([GH("room")],sG.prototype,"_exitRoom",1),yb([GH("screen")],sG.prototype,"_stopScreenShare",1),yb([lW(...OH.TRTC.sendSEIMessage),cH({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}})],sG.prototype,"sendSEIMessage",1),yb([lW(OH.TRTC.sendCustomMessage),cH({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],sG.prototype,"sendCustomMessage",1),yb([lW(OH.TRTC.create)],sG,"_create",1);var aG=sG,cG=class{constructor(){Sb(this,"_set",new Set),dM.on(hM.LEAVE_SUCCESS,this.delete,this),dM.on(hM.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,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))}handleSwitchRoomSuccess(e){let{room:t,currentRoomId:i,targetRoomId:r}=e;"rtc"!==t.scene&&(this._set.delete(this.getKey(t.userId,i,t.sdkAppId,t.useStringRoomId)),this._set.add(this.getKey(t.userId,r,t.sdkAppId,t.useStringRoomId)))}};function lG(){return Ab(this,null,(function*(){let e,t;try{let t=yield gV();e=t&&t.length}catch(p){}try{let e=yield EV();t=e&&e.length}catch(p){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:s,isH265EncodeSupported:a,isH265DecodeSupported:c}=this.checkSystemResult.detail,l=EM.basis(),d={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:r,h264Decode:o,vp8Encode:n,vp8Decode:s,h265Encode:a,h265Decode:c},u={browser:l.browser,os:l.os,trtc:d,devices:i},h={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};px.uploadEvent({log:"trtcstats-".concat(JSON.stringify(u)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(u))),px.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(h)),userId:this.userId}),GL()}))}var dG=vb(Rb()),uG="1",hG="2",pG="3",mG="4",_G="5",fG="6",gG="7",EG={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,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161},TG=[EG.UPDATE_REMOTE_MUTE_STAT,EG.UPLINK_NETWORK_STATS,EG.USER_LIST_RES,EG.MUTE_RESULT,EG.SERVER_FIRST_PACKAGE_RECEIVED,EG.RECEIVE_CUSTOM_MSG],vG={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",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res"},yG="publish_change",SG="join",IG="leave",AG="quality_report",RG="mute_uplink",CG="publish",bG="publish_state_change",kG="unpublish",DG="subscribe",wG="unsubscribe",NG="subscribe_change",OG="start_publishing",MG="stop_publishing",PG="start_push_user_cdn",LG="stop_push_user_cdn",xG="start_mcu_mix",VG="stop_mcu_mix",UG="start_publish_cdn_stream",FG="update_publish_cdn_stream",BG="stop_publish_cdn_stream",HG="get_user_list",WG="change_role",GG="update_constraint_config",jG="rebuild_pc",JG="join/v2",KG="publish/v2",qG="subscribe/v3",zG="ability_status_report",YG="reconnect",XG="channel_msg",QG="switch_room",ZG=new Set;var $G=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],ej=class extends dG.default{constructor(e){var t,i,r;super(),Sb(this,"room"),Sb(this,"sdkAppId"),Sb(this,"userId"),Sb(this,"userSig"),Sb(this,"url"),Sb(this,"backupUrl"),Sb(this,"destroyed",!1),Sb(this,"_socketInUse"),Sb(this,"_socket"),Sb(this,"_backupSocket"),Sb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[]}),Sb(this,"_currentState","DISCONNECTED"),Sb(this,"_isReconnecting",!1),Sb(this,"_seq",0),Sb(this,"_log"),Sb(this,"_lastMessageTime",-1),Sb(this,"_connectStartTime",-1),Sb(this,"_stopConnectRetry"),Sb(this,"bytesSent",0),Sb(this,"bytesReceived",0),Sb(this,"keepAlive",!1),Sb(this,"signalDomainWhenUnifiedProxy"),Sb(this,"stopKeepAliveTimeout"),Sb(this,"rtt",0),this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let n=(null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0;null!=(r=this.room.joinParams)&&r.keepAlive&&!n&&(n=1),n-ZG.size>0&&this.room.enableSPC&&(this.keepAlive=!0,ZG.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=_M.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 race(){return this.room.enableSPC&&!this.room.proxy_ws}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);return $G.forEach((i=>{let r=t.get("trtc_".concat(i));r&&(e+="&".concat(i,"=").concat(encodeURIComponent(r)))})),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 isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;return function*(){if(e.isConnected)return Promise.resolve();e._log.info("connect to [".concat(e.url,", ").concat(e.backupUrl,"] ").concat(e.race?"race":"").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive))),e.emitConnectionStateChanged("CONNECTING"),e._connectStartTime=Aw();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 Iw(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?Sk.BACKUP:Sk.MAIN),e.emitConnectionStateChanged("CONNECTED")}()}))}connectWS(e){let{url:t,timeout:i,isMain:r}=e,n=new WebSocket(t);this.bindSocket(n),r?this._socket=n:this._backupSocket=n;let o=-1;return new Promise(((e,t)=>{n.onclose=t,n.onerror=t,n.onopen=()=>e(n),i&&(o=setTimeout((()=>{this.unbindAndCloseSocket(r?Sk.MAIN:Sk.BACKUP),t(new Ub({code:xb.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),i))})).finally((()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)}))}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===Sk.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(Xk){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(Xk){}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(_G,new Ub({code:xb.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(Sk.MAIN),this.unbindAndCloseSocket(Sk.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(_G,new Ub({code:xb.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Fw(e.data);let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values(EG),o=Object.keys(EG)[n.indexOf(i)],s=vG[o]||i;switch(TG.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case EG.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,r.svrTime&&function(e){Fb=e-(new Date).getTime();let t=new Date;t.setTime(e),_M.info("baseTime from server: ".concat(t," offset: ").concat(Fb))}(r.svrTime),this._log.info("ChannelSetup Success ".concat(Aw()-this._connectStartTime)),BP.addSuccessEvent({key:521701,cost:Aw()-this._connectStartTime}),this._connectStartTime=-1,this.emit(uG,{signalInfo:this._signalInfo});else{let e=new Ub({code:xb.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:kP({key:AP.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),BP.addFailedEvent({key:521701,error:e}),this.emit(_G,e)}break;case EG.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(s,{data:t});break;default:this.emit(String(s),{data:t})}}reGetSignalChannelUrl(){return Ab(this,null,(function*(){try{if(!this.room.joinParams)return;YH(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(zb){}}))}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?Sk.MAIN:Sk.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return Ab(this,null,(function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:i,relayInnerIp:r,relayPort:n}=this._signalInfo,{data:o}=yield this.sendWaitForResponse({command:YG,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:vG.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),BP.addSuccessEvent({key:521702,cost:Aw()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(BP.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(zb){this._log.error(zb),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+=Fw(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:o,enableLog:s=!0,addReceiveTime:a=!1}=e;return new Promise(((e,c)=>{let l=()=>{clearTimeout(d),c(new Ub({code:xb.API_CALL_ABORTED,message:"".concat(t," aborted due to connection closed")}))};this.once(gG,l);let d=setTimeout((()=>{this.off(n,u),this.off(gG,l);let e=new Ub({code:xb.API_CALL_TIMEOUT,message:kP({key:AP.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),c(e)}),r),u=t=>{t.data.seq===h&&(clearTimeout(d),this.off(n,u),this.off(gG,l),a&&(t.data.receiveTime=Date.now()),e(t))};this.on(n,u);let h=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,reject:r,error:n}=e;!this.room.isJoined||this.destroyed||n.code===xb.API_CALL_ABORTED?r(n):this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(pG,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),ZG.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(Sk.MAIN),this.unbindAndCloseSocket(Sk.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(gG)}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(vG.JOIN_ROOM_RESULT,t)}),1e3*e);let t=e=>{0===e.data.code&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(vG.JOIN_ROOM_RESULT,t))};this.on(vG.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(hG,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(pG):"DISCONNECTED"===e&&this.emit(fG))}};yb([_x({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())}})],ej.prototype,"connect",1);var tj=vb(Rb()),ij=0,rj=!1,nj=new Set,oj=!1,sj=class{constructor(e){Sb(this,"userId"),Sb(this,"tinyId"),Sb(this,"_sdpSemantics"),Sb(this,"_isUplink"),Sb(this,"_room"),Sb(this,"_log"),Sb(this,"_signalChannel"),Sb(this,"_isErrorObserved",!1),Sb(this,"_waitForPeerConnectionConnectedPromise"),Sb(this,"_waitForPeerConnectionConnectedPromiseReject",null),Sb(this,"_peerConnection",null),Sb(this,"_emitter",new tj.default),Sb(this,"_currentState","DISCONNECTED"),Sb(this,"_isReconnecting",!1),Sb(this,"_reconnectionCount",0),Sb(this,"_reconnectionTimer",-1),Sb(this,"_isFirstConnection",!0),Sb(this,"_prevTime",-1),Sb(this,"_localAddress"),Sb(this,"_remoteAddress"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=_M.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=Aw())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,BP.addSuccessEvent({key:521705,cost:Math.min(Aw()-this._prevTime,3e4)})):this._isReconnecting&&BP.addSuccessEvent({key:521706,cost:Aw()-this._prevTime}),this._prevTime=-1}catch(IM){throw this._isFirstConnection?(this._isFirstConnection=!1,BP.addFailedEvent({key:521705,error:IM})):this._isReconnecting&&this._reconnectionCount>=3&&BP.addFailedEvent({key:521706,error:IM}),IM}}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(),nj.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 Ub({code:xb.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Jk;let e=null;if(this._isUplink){if(!_L()||0===this._peerConnection.getSenders().length)return Jk;e=this._peerConnection.getSenders()[0].transport}else{if(!mL()||0===this._peerConnection.getReceivers().length)return Jk;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:Jk}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(e.target.connectionState,", ICE: ").concat(t,", DTLS: ").concat(i)),e.target.connectionState===Kk.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===Kk.FAILED||e.target.connectionState===Kk.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new Ub({message:r,code:xb.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===Kk.CONNECTED||e.target.connectionState===Kk.COMPLETED)&&(this.logSelectedCandidate(),px.logSuccessEvent({userId:this._room.userId,eventType:Zk.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(ij=0,rj=!1,oj=!0,nj.add(this)):nj.delete(this),dM.emit(hM.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return Ab(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(oL(t)){let i=e.get(t.localCandidateId),r=e.get(t.remoteCandidateId);i&&(this._log.info("local candidate: ".concat(i.candidateType," ").concat(i.protocol,":").concat(i.ip||i.address,":").concat(i.port," ").concat(i.networkType||""," ").concat("relay"===i.candidateType?"relayProtocol:".concat(i.relayProtocol):"")),this._localAddress="".concat(i.ip||i.address,":").concat(i.port)),r&&(this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port)),this._remoteAddress="".concat(r.protocol,":").concat(r.ip||r.address));break}}))}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this._currentState)return e();this._waitForPeerConnectionConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new Ub({code:xb.API_CALL_ABORTED,message:kP({key:AP.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{dM.off(hM.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new Ub({code:xb.API_CALL_TIMEOUT,message:"connection timeout"});var i;ij+=1,i=this._signalChannel.isConnected,ij>2&&!rj&&0===nj.size&&i&&(this._log.warn("firewall restriction"),rj=!0,this._emitter.emit("firewall-restriction")),t(e)}),dD);dM.on(hM.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(pG,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Yk()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new Ub({code:this._isUplink?xb.UPLINK_RECONNECTION_FAILED:xb.DOWNLINK_RECONNECTION_FAILED,message:kP({key:this._isUplink?AP.UPLINK_RECONNECTION_FAILED:AP.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(pG,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)}};yb([zV(521712,!1)],sj.prototype,"setOffer",1),yb([zV(521713,!1)],sj.prototype,"setAnswer",1);var aj=vb(Mb()),cj=function(e){return aj.default.parse(e)},lj=function(e){return aj.default.write(e)};function dj(e){return Object.keys(e).filter((t=>e[t]))}var uj=class e extends sj{constructor(e){super(gb(fb({},e),{isUplink:!1})),Sb(this,"_flag",0),Sb(this,"isRobot",!1),Sb(this,"role","anchor"),Sb(this,"remoteAudioTrack"),Sb(this,"remoteVideoTrack"),Sb(this,"remoteAuxiliaryTrack"),Sb(this,"ssrc",{audio:0,video:0,auxiliary:0}),Sb(this,"_isSDPExchanging",!1),Sb(this,"_videoCodec"),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new $B(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new eH(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new tH(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":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}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 Dw(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===Sk.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let t=e.streams[0],{track:i}=e,r=t.id===Pk?Sk.MAIN:Sk.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=Sk.AUDIO;i.kind===Sk.VIDEO&&(n=r===Sk.MAIN?Sk.VIDEO:Sk.AUXILIARY);let o=this.remoteAudioTrack;n===Sk.VIDEO?o=this.remoteVideoTrack:n===Sk.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}addRRTRLine(e){let t=e.split("\r\n"),i=new Map;t.forEach(((e,r)=>{/^a=rtcp-fb:/.test(e)&&t[r+1]&&!/^a=rtcp-fb:/.test(t[r+1])&&i.set(r+1,"".concat(e.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))}));let r=[...i];for(let n=0;n<r.length;n++){let[e,i]=r[n];t.splice(e+n,0,i)}return t.join("\r\n")}addSPSDescription(e){let t=cj(e);return t.media.forEach((e=>{e.type===Sk.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),lj(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=cj(e);return i.media.forEach((e=>{e.ext&&(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),lj(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return Ab(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===Kk.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===Kk.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(t," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else this.initialize(),yield this.connect(e)}catch(Yb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Yb.message," ").concat(JSON.stringify(this.muteState))),new Ub({code:xb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Yb}}))}unsubscribe(e){return Ab(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=fb({},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(dj(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=wG,n=vG.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=NG,n=vG.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 Ub({code:i.code,message:kP({key:AP.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(t),yield e.waitForPeerConnectionConnected()}catch(Xk){throw e.closePeerConnection(!0),Xk}}()}))}exchangeSDP(e){return Ab(this,null,(function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:i}=this._peerConnection.localDescription,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:DG,commandDesc:"exchange sdp",data:r,responseCommand:vG.SUBSCRIBE_RESULT,timeout:tD});if(!this._peerConnection){let e=new Ub({code:xb.INVALID_OPERATION,message:kP({key:AP.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(Xk){throw this._isSDPExchanging=!1,Xk}}))}createOffer(){return Ab(this,null,(function*(){let e={voiceActivityDetection:!1};gL()&&this._sdpSemantics===iD?(this._peerConnection.addTransceiver(Sk.AUDIO,{direction:Ik.RECVONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Ik.RECVONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Ik.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield QP();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=cj(e);return t.media.forEach((e=>{var t,i;if(e.type===Sk.VIDEO){let r=new Set;e.rtp.forEach((e=>{let{payload:t,codec:i}=e;return"H264"===i&&r.add(t)})),e.fmtp.forEach((e=>{let{payload:t,config:i}=e,n=i.match(/apt=(\d+)/);n&&n[1]&&r.has(Number(n[1]))&&r.add(t)}));let n=e=>{let{payload:t}=e;return!r.has(t)};e.rtp=e.rtp.filter(n),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=null==(i=e.payloads)?void 0:i.split(" ").filter((e=>!r.has(Number(e)))).join(" ")}})),lj(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=cj(e);return t.media.forEach((e=>{e.type===Sk.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),lj(t)}(t.sdp),this._sdpSemantics===iD&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)}))}onSubscribeResult(e){return Ab(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===nD)throw new Ub({code:xb.NOT_SUPPORTED_H264,message:kP({key:AP.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new Ub({code:t,message:kP({key:AP.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(RM){throw this._log.error(RM),RM}}))}updateSSRC(e){try{cj(e).media.forEach((e=>{if(e.ssrcs)if(e.type===Sk.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Pk)}));t&&(this.ssrc.audio=Number(t.id))}else{let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Pk)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Lk)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(Xk){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return Ab(this,null,(function*(){if(!(Ib(e.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(Xk){let t=aw(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}};yb([FV((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 Ub({code:xb.API_CALL_ABORTED,message:kP({key:AP.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],uj.prototype,"subscribe",1),yb([zV(521717,!1)],uj.prototype,"unsubscribe",1),yb([VV(sj.prototype.afterConnect),xV(sj.prototype.beforeConnect)],uj.prototype,"connect",1);var hj=uj,pj={voiceActivityDetection:!1},mj=class e extends sj{constructor(e){super(gb(fb({},e),{isUplink:!0})),Sb(this,"localMainAudioTrack",null),Sb(this,"localMainVideoTrack",null),Sb(this,"localAuxAudioTrack",null),Sb(this,"localAuxVideoTrack",null),Sb(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),Sb(this,"_isPublishingAux",!1),Sb(this,"_publishingLocalAudioTrack"),Sb(this,"_publishingLocalVideoTrack"),Sb(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),Sb(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(fL()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(i=o[2])||!i.track),n.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((e=>{e.track&&(e.track.kind===Sk.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return Ab(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(),gL()?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 Ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n,isAuxiliary:o}=e;return function*(){t._log.info("publish by transceiver");let e=new MediaStream,s=null==r?void 0:r.outMediaTrack,a=null==i?void 0:i.outMediaTrack;a&&e.addTrack(a),s&&e.addTrack(s);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||Sk.AUDIO,{direction:Ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?Sk.VIDEO:s||Sk.VIDEO,{direction:Ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||Sk.VIDEO,{direction:Ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||Sk.VIDEO,{direction:Ik.SENDONLY,streams:[e]}),yield t.connect();else{let e=[];if(a&&(c[0].sender.track||e.push(0),yield c[0].sender.replaceTrack(a),yield t.setBandwidth({bandwidth:(null==i?void 0:i.profile.bitrate)||40,type:Sk.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:Sk.VIDEO,videoType:o?Sk.AUXILIARY:Sk.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:Sk.VIDEO,videoType:Sk.SMALL}),e.push(2))}yield t.setTransceiverDirection(Ik.SENDONLY,e),yield t.doPublishChange(),null==r||r.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),null==r||r.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()}))}publishByAddTrack(e){return Ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n}=e;return function*(){t._log.info("publish by addtrack");let e=null==r?void 0:r.outMediaTrack,o=null==i?void 0:i.outMediaTrack;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return i&&o&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(r)));let s=new MediaStream;if(o&&s.addTrack(o),e&&s.addTrack(e),o&&t._peerConnection.addTrack(o,s),e&&(t._peerConnection.addTrack(e,s),n)){let e=new MediaStream;e.addTrack(n),t._peerConnection.addTrack(n,e)}yield t.connect()}()}))}enableSmall(e){return Ab(this,null,(function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(Ik.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Ik.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return Ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!fL())return i&&i.outMediaTrack&&!r&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):r&&r.outMediaTrack&&!i&&t.localMainAudioTrack?(yield t.removeTrack(r),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),void t.emitConnectionStateChangedEvent("DISCONNECTED",r));let e=r&&r===t.localAuxVideoTrack,n=null==r?void 0:r.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localAuxAudioTrack&&!t.localMainAudioTrack&&(yield o[0].replaceTrack(null),s.push(0))),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=gb(fb({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=gb(fb({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.setTransceiverDirection(Ik.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Ab(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:bG,data:t,responseCommand:vG.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:kG,commandDesc:"unpublish",responseCommand:vG.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===xb.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),AL){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:GG,data:this._mediaSettings,responseCommand:vG.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return Ab(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Sk.AUXILIARY:Sk.MAIN," stream")),gL()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return Ab(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Sk.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),1===n&&null!=(i=this.localMainVideoTrack)&&i.small&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Ik.INACTIVE&&(yield this.setTransceiverDirection(Ik.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return Ab(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;fL()&&this._peerConnection.getTransceivers().findIndex((e=>"stopped"===e.direction))>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let i=this._peerConnection.getSenders().find((e=>e.track&&e.track.kind===t.kind));if(i&&i.track){this._log.warn("sender already exists, remove sender first");let e=i.track;this.removeSender(i),yield this.updateOffer("remove",e)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===Sk.VIDEO&&e instanceof fB&&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===rD||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=cj(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===Sk.VIDEO)return!0;return!1}removeSender(e){let t=null;fL()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&lw(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return Ab(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?Sk.AUXILIARY:Sk.MAIN," stream")),gL()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return Ab(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Sk.AUDIO)yield i[0].sender.replaceTrack(null);else{let r=t?3:1;yield i[r].sender.replaceTrack(null),1===r&&e.small&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Ik.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return Ab(this,null,(function*(){if(!wN)return;let i=!1,r=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let n=this._peerConnection.getTransceivers();if(t.forEach((t=>{n[t].direction!==e&&(n[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this.setOffer(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(Ik.INACTIVE,"|").concat(Ik.RECVONLY,"|").concat(Ik.SENDONLY,")")))&&o++,t.includes(o)){if(e===Ik.INACTIVE&&i.includes("a=".concat(Ik.RECVONLY)))return r=!0,"a=".concat(e);if(e===Ik.SENDONLY&&i.includes("a=".concat(Ik.INACTIVE)))return r=!0,"a=".concat(Ik.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:s}))}))}removeTrackBySender(e){return Ab(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===Sk.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let t=this._peerConnection.getSenders().find((t=>t.track===e.outMediaTrack));t&&(this.removeSender(t),e.kind===Sk.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===Sk.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return Ab(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=gL()?e.kind===Sk.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?Sk.AUXILIARY:Sk.MAIN," stream")),e.kind===Sk.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===Sk.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack)),!0}))}updateOffer(e,t){return Ab(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(pj);wN&&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===Sk.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:r,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(n.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:yG,data:n,responseCommand:vG.UPDATE_OFFER_RESULT,timeout:eD,commandDesc:"update offer"}),{code:s,message:a}=o.data;0!==s&&this.checkPublishResultCode(s,a),yield this.acceptAnswer(o.data.data),i.sdp&&this.updateSSRC(i.sdp)}catch(AM){throw this._log.error(AM),AM}}))}setBandwidth(e){return Ab(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!SL())return o?r===Sk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(gL()){let t=0;r===Sk.VIDEO&&(t=n===Sk.SMALL?2:n===Sk.AUXILIARY?3:1),e=s[t]}else e=s.find((e=>e.track&&e.track.kind===r));if(e){let s=e.getParameters();(!s.encodings||0===s.encodings.length)&&(s.encodings=[{}]),s.encodings[0].maxBitrate=1e3*i;try{return yield e.setParameters(s),t._log.info("".concat(n||"").concat(r," bandwidth ").concat(i," kbps")),o}catch(a){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(a)),o)return r===Sk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";wN&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===Sk.SMALL?n=1:i===Sk.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(o+=1,o===n?"".concat(e,"b=").concat(r,":").concat(t,"\r\n"):e))),e}updateAudioBandwidthRestriction(e,t){let i="AS";return wN&&(i="TIAS",t*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,"m=audio $1\r\nc=IN $2\r\nb=".concat(i,":").concat(t,"\r\n"))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return Ab(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(zb){throw this.closePeerConnection(!0),this.uninstallEvents(),zb}}))}exchangeSDP(){return Ab(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(zb){throw zb}}))}createOffer(){return Ab(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(pj);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(zb){throw zb}}))}doExchangeSDP(){let e={command:CG,responseCommand:vG.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof JB||this.localAuxVideoTrack instanceof JB,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=cj(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),lj(r)}acceptAnswer(e){return Ab(this,null,(function*(){var t,i,r,n,o;try{let s;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let e=(null==(t=this._publishingLocalVideoTrack)?void 0:t.profile.bitrate)||(null==(i=this.localMainVideoTrack)?void 0:i.profile.bitrate),o=(null==(r=this._publishingLocalAudioTrack)?void 0:r.profile.bitrate)||(null==(n=this.localMainAudioTrack)?void 0:n.profile.bitrate);if(e){let t=this._isPublishingAux?Sk.AUXILIARY:Sk.BIG;s=yield this.setBandwidth({bandwidth:e,type:Sk.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:Sk.AUDIO,sdp:s}))}if(s=this.removeVideoOrientation(e.sdp),null!=(o=this._publishingLocalVideoTrack)&&o.small){let{smallStreamConfig:e}=this._room;s=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:Sk.VIDEO,videoType:Sk.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this.setAnswer(a),this._log.debug("accepted answer: ".concat(s))}catch(bM){throw this._log.error("failed to accept remote answer ".concat(bM)),bM}}))}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(RG,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return Ab(this,null,(function*(){if(!(Ib(e.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:kG,responseCommand:vG.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(Xk){let t=aw(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)&&dM.emit(hM.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{cj(e).media.forEach(((e,t)=>{if(e.type===Sk.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===rD&&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(Xk){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Sk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Sk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Sk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Sk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Sk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===nD?(this._log.error(RP.NOT_SUPPORTED_H264ENCODE),new Ub({code:xb.NOT_SUPPORTED_H264,message:kP({key:AP.NOT_SUPPORTED_H264ENCODE})})):new Ub({code:xb.UNKNOWN,message:kP({key:AP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:vG.PUBLISH_RESULT,code:e,message:t}})})}};yb([FV((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 Ub({code:xb.API_CALL_ABORTED,message:kP({key:AP.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],mj.prototype,"publish",1),yb([zV(521715,!1)],mj.prototype,"unpublish",1),yb([VV(sj.prototype.afterConnect),xV(sj.prototype.beforeConnect)],mj.prototype,"connect",1);var _j=mj,fj=class{constructor(e,t){this.room=e,Sb(this,"_log"),Sb(this,"_prevReportTime",0),Sb(this,"_prevReport",{}),Sb(this,"_prevStats",null),Sb(this,"_prevEncoderImplementation",""),Sb(this,"_prevAuxEncoderImpl",""),Sb(this,"_prevQualityLimitationReason",""),Sb(this,"_prevAuxQualityLimitationReason",""),Sb(this,"_prevDecoderImplementationMap",new Map),Sb(this,"_decodeMap",new Map),Sb(this,"totalBytesSent",0),Sb(this,"totalBytesReceived",0),Sb(this,"_spcStats",null),this._log=t}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return Ab(this,null,(function*(){var t;let i={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},r=e.getPeerConnection(),n=e.getSSRC();if(r)try{if((this._spcStats||(yield r.getStats())).forEach((t=>{var r,o,s;let a,c;if("outbound-rtp"===t.type)if((t.mediaType||t.kind)===Sk.VIDEO){if(t.ssrc===n.video?(a=Sk.VIDEO,c=e.localMainVideoTrack):t.ssrc===n.small?a=Sk.SMALL:t.ssrc===n.auxiliary&&(c=e.localAuxVideoTrack,a=Sk.AUXILIARY),!a)return;if(i[a].bytesSent=t.bytesSent,i[a].packetsSent=t.packetsSent,i[a].framesEncoded=t.framesEncoded,dw(t.keyFramesEncoded)||(i[a].keyFramesEncoded=t.keyFramesEncoded),dw(t.nackCount)||(i[a].nackCount=t.nackCount),dw(t.pliCount)||(i[a].pliCount=t.pliCount),dw(t.retransmittedPacketsSent)||(i[a].retransmittedPacketsSent=t.retransmittedPacketsSent),dw(t.totalEncodeTime)||(i[a].totalEncodeTime=t.totalEncodeTime),dw(t.totalPacketSendDelay)||(i[a].totalPacketSendDelay=t.totalPacketSendDelay),!dw(t.encoderImplementation)&&(a===Sk.VIDEO&&this._prevEncoderImplementation!==t.encoderImplementation||a===Sk.AUXILIARY&&this._prevAuxEncoderImpl!==t.encoderImplementation)){let i=2,r=this._prevEncoderImplementation;a===Sk.AUXILIARY&&(i=7,r=this._prevAuxEncoderImpl),dM.emit("262",{userId:e.userId,streamType:i,prevImplementation:r,implementation:t.encoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientEncoder}),this[a===Sk.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=t.encoderImplementation,this._log.info("".concat(a===Sk.AUXILIARY?"aux ":"","encoderImplementation change to ").concat(t.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(t.powerEfficientEncoder))}t.ssrc===n.video?!dw(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),dM.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&&!dw(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),dM.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(o=e.localAuxVideoTrack)?void 0:o.isQosClearFirst}),this._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else i.audio.bytesSent=t.bytesSent,i.audio.packetsSent=t.packetsSent;else"candidate-pair"===t.type?oL(t)&&(this.totalBytesSent=t.bytesSent,hw(t.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*t.currentRoundTripTime))):"media-source"===t.type&&(t.kind===Sk.AUDIO?(i.audio.audioLevel=t.audioLevel||0,i.audio.totalAudioEnergy=t.totalAudioEnergy||0,t.echoReturnLoss,t.totalSamplesDuration&&(i.audio.totalSamplesDuration=t.totalSamplesDuration)):t.kind===Sk.VIDEO&&(t.trackIdentifier===e.getVideoTrackId(Sk.VIDEO)?i.video.fpsCapture=t.framesPerSecond:t.trackIdentifier===e.getVideoTrackId(Sk.AUXILIARY)?i.auxiliary.fpsCapture=t.framesPerSecond:i.small.fpsCapture=t.framesPerSecond));if(!dw(t.audioLevel)&&null!=(s=e.localMainAudioTrack)&&s.mediaTrack&&t.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(i.audio.audioLevel=t.audioLevel||0),!dw(t.frameWidth)){let r=Sk.SMALL;t.trackIdentifier===e.getVideoTrackId(Sk.VIDEO)||t.ssrc===n.video?r=Sk.VIDEO:(t.trackIdentifier===e.getVideoTrackId(Sk.AUXILIARY)||t.ssrc===n.auxiliary)&&(r=Sk.AUXILIARY),i[r].frameWidth=t.frameWidth,i[r].frameHeight=t.frameHeight,i[r].framesSent=t.framesSent}})),e.localMainAudioTrack){let t=e.localMainAudioTrack.getInternalAudioLevel(),r=e.localMainAudioTrack.getInternalAudioLevelAfter3A();i.audio.audioCaptureEnergyAfter3a=r,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===Sk.AUDIO?(e.localMainAudioTrack&&(e.localMainAudioTrack.stat=i[t]),e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=i[t])):t===Sk.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=i[t]):t===Sk.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=i[t])}))}catch(Yb){this._log.warn("failed to getStats on sender connection ".concat(Yb))}return 0===i.rtt&&(i.rtt=(null==(t=this.room.networkQuality)?void 0:t.uplinkRTT)||0),i}))}getReceiverStats(e){return Ab(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,p2pDelay:0,codec:""},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""}},o=e.getPeerConnection();if(o)try{let{ssrc:r}=e,{muteState:s,subscribeState:a}=e;(this._spcStats||(yield o.getStats())).forEach((t=>{var i,o;if("codec"===t.type&&this._decodeMap.set(t.id,t),"inbound-rtp"===t.type){let c=(t.mediaType||t.kind)===Sk.AUDIO;if(c){if(t.ssrc!==r.audio||!s.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),t.silentConcealedSamples&&(n.audio.silentConcealedSamples=t.silentConcealedSamples);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(wN&&0===t.bytesReceived)return;let c;t.ssrc===r.video&&s.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,e.videoCodec=mP[null==(i=this._decodeMap.get(t.codecId))?void 0:i.mimeType.split("/")[1]]||"h264",n.video.codec=e.videoCodec,c=e.remoteVideoTrack,s.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,"(").concat(e.videoCodec,") HWDecoder: ").concat(t.powerEfficientDecoder)),dM.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&&s.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,c=e.remoteAuxiliaryTrack,n.auxiliary.p2pDelay=c.stat.end2EndDelay,n.hasAuxiliary=!0,n.video.codec=(null==(o=this._decodeMap.get(t.codecId))?void 0:o.mimeType.split("/")[1].toLowerCase())||"h264"),c&&(c.stat.packetsReceived=t.packetsReceived,c.stat.bytesReceived=t.bytesReceived,c.stat.packetsLost=t.packetsLost,c.stat.framesReceived=t.framesReceived,c.stat.framesDecoded=t.framesDecoded,t.jitterBufferDelay&&(c.stat.jitterBufferDelay=Math.floor(t.jitterBufferDelay/t.jitterBufferEmittedCount*1e3)),n.video.p2pDelay=c.stat.end2EndDelay)}t.jitterBufferDelay&&(c?(n.audio.totalJitter=t.jitterBufferDelay,n.audio.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.video&&s.hasVideo?(n.video.totalJitter=t.jitterBufferDelay,n.video.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.auxiliary&&s.hasAuxiliary&&(n.auxiliary.totalJitter=t.jitterBufferDelay,n.auxiliary.totalJitterCount=t.jitterBufferEmittedCount))}else"candidate-pair"===t.type&&oL(t)&&(this.totalBytesReceived=t.bytesReceived,hw(t.currentRoundTripTime)&&(n.rtt=Math.floor(1e3*t.currentRoundTripTime)));dw(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)),!dw(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),dw(null==(t=e.remoteVideoTrack.player.stat)?void 0:t.fps)||(n.video.fpsRender=e.remoteVideoTrack.player.stat.fps),dw(null==(i=e.remoteAuxiliaryTrack.player.stat)?void 0:i.fps)||(n.auxiliary.fpsRender=e.remoteAuxiliaryTrack.player.stat.fps)}catch(RM){this._log.warn("failed to getStats on receiver connection ".concat(RM))}return 0===n.rtt&&(n.rtt=(null==(r=this.room.networkQuality)?void 0:r.uplinkRTT)||0),n}))}getStats(e,t){return Ab(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=Aw(),n=yield e.getStats(),o=Aw();o-t>2e3&&this._log.warn("getStats cost ".concat(o-t,"ms"));let s=[],a=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec"]);n.forEach((e=>a.has(e.type)&&s.push(e))),this._spcStats=s}e&&(i=yield this.getSenderStats(e));for(let[e,n]of t){let e=yield this.getReceiverStats(n);r.push(e)}return{senderStats:i,receiverStats:r}}))}getDifferenceValue(e,t){if(wV(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r}=e;var n,o,s;if(!wV(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*uP,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*uP),t.senderStats.audio.audioCaptureEnergyAfter3a&&(e.uint32_audio_capture_energy_after3a=t.senderStats.audio.audioCaptureEnergyAfter3a*uP),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 a=null==(n=Zx())?void 0:n.playoutStats;a&&(i.msg_device_info.uint32_audio_play_cost=a.totalFramesDuration);let{statInterval:c}=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(xk)),n=i?i.duration:0,o={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.video.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.video.totalJitter,uint32_video_cache_ms_count:e.video.totalJitterCount,uint32_video_p2p_delay:e.video.p2pDelay,uint32_video_codec:e.video.codec};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=r.get("".concat(e.userId,"_").concat(Vk)),n=i?i.duration:0,o={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.auxiliary.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.auxiliary.totalJitter,uint32_video_cache_ms_count:e.auxiliary.totalJitterCount,uint32_video_p2p_delay:e.auxiliary.p2pDelay,uint32_video_codec:e.video.codec};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let l=this._prevReport,d=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&&l.msg_up_stream_info.msg_audio_status){let e=l.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/c),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}null!=(o=l.msg_device_info)&&o.uint32_audio_capture_cost?i.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(l.msg_device_info.uint32_audio_capture_cost,i.msg_device_info.uint32_audio_capture_cost)/c):delete i.msg_device_info.uint32_audio_capture_cost}let u=l.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=u.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 s=this.getDifferenceValue(r,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*s/c),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)/c),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_codec_fps)/c),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),dw(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),dw(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),dw(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),dw(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),dw(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/c)),dw(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/c))}));let h=l.msg_down_stream_info;i.msg_down_stream_info=i.msg_down_stream_info.filter((e=>h.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid))));let p=i.msg_down_stream_info;return p.forEach((e=>{let t=h.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(wV(e.msg_audio_status)||wV(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 s=this.getDifferenceValue(r.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*s/c),i.uint32_audio_total_bitrate=Math.round(8*s/c)}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,s=t.uint32_video_receive_fps,a=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/c);let d=this.getDifferenceValue(s,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/c),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(a,e.uint32_video_dec_fps)/c);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}))}})),null!=(s=l.msg_device_info)&&s.uint32_audio_play_cost?i.msg_device_info.uint32_audio_play_cost=2*Math.floor(this.getDifferenceValue(l.msg_device_info.uint32_audio_play_cost,i.msg_device_info.uint32_audio_play_cost)/c):delete i.msg_device_info.uint32_audio_play_cost,d&&t.receiverStats.forEach((e=>{if(e.audio.concealedSamples&&e.audio.totalSamplesReceived){let t=d.receiverStats.find((t=>t.userId===e.userId));if(t&&t.audio.concealedSamples&&t.audio.totalSamplesReceived){let i=(e.audio.silentConcealedSamples||0)-(t.audio.silentConcealedSamples||0),r=e.audio.concealedSamples-t.audio.concealedSamples,n=e.audio.totalSamplesReceived-t.audio.totalSamplesReceived,o=Math.floor((r-i)/n*1e3*c);if(o>1e3*c/5){let t=p.find((t=>t.msg_user_info.str_identifier===e.userId));t&&(t.msg_audio_status.uint32_audio_block_time=o)}}}})),i}getStatsReport(e){return Ab(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,uint32_audio_capture_energy_after3a:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield t.getStats(i,r);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:n}),t._prevReportTime=Date.now(),e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},gj=vb(Rb());function Ej(e){return new Promise((t=>Ab(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(Yb){}clearTimeout(i);let o=function(e){let t={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let i=performance.getEntriesByType("resource").reverse();for(let r of i)if(r.name===e){let e=Math.round(r.duration),i=Math.max(Math.round(r.domainLookupStart-r.startTime),0),n=r.redirectStart>0?Math.max(Math.round(r.redirectEnd-r.redirectStart),0):0,o=r.fetchStart>0?Math.max(Math.round(r.domainLookupStart-r.fetchStart),0):0,s=Math.round(r.domainLookupEnd-r.domainLookupStart),a=Math.round(r.requestStart-r.secureConnectionStart),c=Math.round(r.secureConnectionStart-r.connectStart),l=Math.round(r.responseStart-r.requestStart),d=Math.round(r.responseEnd-(r.responseStart||r.startTime));t=gb(fb({},t),{totalCost:e,local:i,redirect:n,httpCache:o,dns:s,tcp:c,tls:a,request:l,response:d});break}}catch(i){}return t}(n);0===o.totalCost&&(o.totalCost=Date.now()-r),t(o)}))))}var Tj=class e extends gj.default{constructor(e){let{signalChannel:t,room:i}=e;super(),Sb(this,"_room"),Sb(this,"_signalChannel"),Sb(this,"_log"),Sb(this,"uplinkRTT",0),Sb(this,"uplinkLoss",0),Sb(this,"downlinkRTT",0),Sb(this,"downlinkLoss",0),Sb(this,"pingResults",{}),Sb(this,"_downlinkPrevStatMap",new Map),Sb(this,"_downlinkLossAndRTTMap",new Map),Sb(this,"_interval",-1),Sb(this,"_uplinkNetworkQuality",0),Sb(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=_M.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(vG.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(hG,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,i;if(0!==e.data.code)return;let r=e.data.data;if(r.delay&&this.updateDelay(r.delay),this._room.signalChannel&&r.wsRtt&&(this._room.signalChannel.rtt=r.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);let n=null==(i=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:i.getPeerConnection();if(n&&this.isPeerConnectionDisconnected(n))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);let o=r.expectAudPkg+r.expectVidPkg,s=r.recvAudPkg+r.recvVidPkg,a=o-s;0===o&&0===s||(this.uplinkLoss=a<=0?0:Math.round(a/o*100),this.uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return Ab(this,null,(function*(){if(0===this._room.remotePublishedUserMap.size)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],t=e.filter((e=>{var t;return(null==(t=e.getPeerConnection())?void 0:t.connectionState)===Kk.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let n=0;n<t.length;n++){let e=t[n].getPeerConnection();if(!e)return;let{rtt:i,totalPacketsLost:r,totalPacketsReceived:o}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o});continue}let s=0,a=this._downlinkPrevStatMap.get(e),c=r-a.totalPacketsLost,l=o-a.totalPacketsReceived;s=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:s,userId:t[n].getUserId(),audioDelay:t[n].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[n].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach((e=>{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return 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 Ab(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!mL())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&&hw(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===Sk.AUDIO||e.mediaType===Sk.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return 0===t.rtt&&(t.rtt=this.uplinkRTT),t}catch(kM){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){"DISCONNECTED"===e.state?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):"CONNECTED"===e.state&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(e){let{state:t}=e;"DISCONNECTED"===t?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):"CONNECTED"===t&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==Kk.DISCONNECTED&&e.connectionState!==Kk.FAILED&&e.connectionState!==Kk.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){-1===this._interval?(this._log.debug("start network quality calculating"),this._interval=ax.run("ric",(()=>{var t;this.handleDownlinkNetworkQuality();let i=[...this._downlinkLossAndRTTMap.values()];dM.emit(hM.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=gb(fb({},n),{pingResults:this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold?this.pingResults:{}})),this.emit(e.EVENT_NETWORK_QUALITY,n);let o=Date.now();if(r&&(this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold)&&o-e.lastPingTime>1e3*r.interval){e.lastPingTime=Date.now();let t=r.domain.map((e=>Ej(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=o,this.pingResults.data=e,e.forEach((e=>{BP.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&&(ax.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach((e=>{let{srcTinyId:i,videoDelay:r,audioDelay:n}=e,o=t.get(i);if(o){let e=this._room.remotePublishedUserMap.get(o);null==e||e.setDelay({videoDelay:r,audioDelay:n})}}))}};Sb(Tj,"EVENT_NETWORK_QUALITY","0"),Sb(Tj,"lastPingTime",0);var vj=Tj;var yj=class{constructor(e){Sb(this,"_frameWorkType"),Sb(this,"_component"),Sb(this,"_language"),Sb(this,"connectionType"),Sb(this,"_room"),Sb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0}),Sb(this,"_keyPrefix"),Sb(this,"_log"),Sb(this,"_intervalId"),Sb(this,"_firstPublishedUserList"),Sb(this,"_networkQuality"),Sb(this,"_basicInfo"),Sb(this,"_pathJoinRoom"),Sb(this,"_pathLeaveRoom"),Sb(this,"_pathMainVideoMap"),Sb(this,"_pathMainAudioMap"),Sb(this,"_pathAuxiliaryMap"),Sb(this,"_remoteStreamStatMap"),Sb(this,"_localStreamStat"),Sb(this,"_eventMap",new Map),Sb(this,"_captureCostSum",0),Sb(this,"_captureCostCount",0),Sb(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=_M.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&lw(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];let o=t.apply(i,r);return Ew(o)?o.catch((e=>_M.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(Xk){_M.error("".concat(t.name,"() error observed ").concat(Xk))}}}({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:Kb,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,$O().then((e=>{this._basicInfo.string_os_version=sM(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),dM.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(hM.JOIN_START,this.handleJoinStart).addEvent(hM.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(hM.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(hM.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(hM.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(hM.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(hM.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(hM.JOIN_FAILED,this.handleJoinFailed).addEvent(hM.LEAVE_START,this.handleLeaveStart).addEvent(hM.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(hM.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(hM.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(hM.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(hM.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(hM.PUBLISH_START,this.handlePublishStart).addEvent(hM.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(hM.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(hM.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(hM.PLAY_TRACK_START,this.handlePlayStart).addEvent(hM.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(hM.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!t.isRemote||!this.hitTest(t.room)||"PLAYING"===i&&(r===Sk.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(hM.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(hM.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(hM.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(hM.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(hM.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(hM.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(hM.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let n=i.hasAudio||i.hasVideo||i.hasSmall,o=i.hasAuxiliary,s=r.hasAudio||r.hasVideo||r.hasSmall,a=r.hasAuxiliary;!n&&s&&this.handleRemoteStreamAdded(r.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")})).addEvent(hM.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)=>dM.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),ax.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&&(dw(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),dw(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),dw(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(e){let{room:t,detailCost:i}=e;if(this.hitTest(t)&&i){let{totalCost:e,local:t,dns:r,tcp:n,tls:o,request:s,response:a}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=r,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=o,this._pathJoinRoom.int32_schedule_request=s,this._pathJoinRoom.int32_schedule_response=a}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(e){let{room:t,error:i}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=i instanceof Ub?Number(i.getExtraCode()||i.getCode()):xb.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())}handleSwitchRoomStart(e){if(this.hitTest(e.room)){let e=Date.now();this.report().then((()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e}))}}handleSwitchRoomSuccess(e){let{room:t}=e;if(this.hitTest(t)&&0===this._pathJoinRoom.uint64_end_time){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed(e){let{room:t,error:i}=e;if(this.hitTest(t)){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,i&&(this._pathJoinRoom.int32_end_ret=i instanceof Ub?Number(i.getExtraCode()||i.getCode()):xb.UNKNOWN)}}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:gb(fb({},Ij),{msg_user_info:new Aj({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};n.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(r,n)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:r,subscribeState:n}=e;if(!this.hitTest(t))return;let{userId:o,tinyId:s,role:a}=i,c=new Aj({userId:o,tinyId:s,role:"anchor"===a?20:21}),l=Date.now(),d="".concat(o,"_").concat(r),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=l),"main"===r?(i.muteState.hasVideo&&(n.video||n.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),i.muteState.hasAudio&&n.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):i.muteState.hasAuxiliary&&n.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l})}handleSubscribed(e){let{room:t,remotePublishedUser:i,streamType:r}=e;if(this.hitTest(t)){let e="".concat(i.userId,"_").concat(r),t=this._remoteStreamStatMap.get(e);t&&0===t.subscribedTime&&(t.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!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,BP.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:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(s)s.totalRTT+=t,s.totalLoss+=i,n&&(s.totalVideoDelay=(s.totalVideoDelay||0)+n,s.videoDelayCount=(s.videoDelayCount||0)+1),o&&(s.totalAudioDelay=(s.totalAudioDelay||0)+o,s.audioDelayCount=(s.audioDelayCount||0)+1),s.count++;else{let e,s,a,c;n&&(s=n,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_device_info:t,msg_up_stream_info:i,msg_down_stream_info:r}=e.report;if(i.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:t,uint32_video_width:r,uint32_video_height:n}=i.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=t,this._localStreamStat.totalVideoWidth+=r,this._localStreamStat.totalVideoHeight+=n,this._localStreamStat.videoCount++}if(i.msg_audio_status){let{uint32_audio_level:e}=i.msg_audio_status;Math.floor(e/uP*100)>0&&(this._localStreamStat.totalAudioLevel+=e/uP,this._localStreamStat.audioLevelCount++)}r.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:r}=e,n=t.str_identifier,o=this._room.remotePublishedUserMap.get(n);if(r.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,r="".concat(n,"_").concat(t?"main":"auxiliary"),s=this._remoteStreamStatMap.get(r);if(s&&(t&&null!=o&&o.remoteVideoTrack.isSubscribed||i&&null!=o&&o.remoteAuxiliaryTrack)){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*mb(10,6)))}})),!kw(i)){let e="".concat(n,"_main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&null!=o&&o.remoteAudioTrack.isSubscribed&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,o.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=o.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/uP*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/uP,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 Ub?i.getExtraCode()||i.getCode():xb.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&Ck))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Dk))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&kk))>=0}hitTest(e){return e===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach(((e,t)=>{let{userId:i}=e,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(r){let{totalLoss:t,count:i,audioDelayCount:n,videoDelayCount:o,totalAudioDelay:s,totalVideoDelay:a}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),n&&s&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(s/n),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/o))}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:n}=this._room;n&&(e.statsToReport.uint32_audio_play_time=n.getDuration(t,Sk.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,Sk.VIDEO)),e.statsToReport.uint32_video_render_first&&(e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,Sj));let{badCaseDetector:o}=this._room,{dataFreeze:s,count:a}=o.getDataFreezeDuration(t),{renderFreeze:c}=o.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=a,e.statsToReport.uint32_video_block_time=Math.min(s,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),o.isBlackStream(t)&&0===e.statsToReport.uint32_video_avg_fps?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>Sj&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+Sj):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>Sj&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+Sj):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Sj&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Sj)}getReportData(){this._basicInfo.uint32_networkType=QD();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Aj({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Nw(this._signalInfo.relayIp),uint32_client_ip:Nw(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*mb(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:Nw(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return Gw(e),e}report(){return Ab(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(IM){this._log.warn(IM)}finally{this.isDestroyed&&(this._room=null)}}))}upload(e){return Ab(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=pM.enable?$w(e,2001,t):yield oN(e),r=i instanceof ArrayBuffer,n="".concat(KD(t,dk.KEY_POINT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i));let s=[this.uploadKVStat(BP),this.uploadKVStat(FP)];o||s.push(nN({url:n,body:i,priority:"low"})),yield Promise.all(s)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return Ab(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=gb(fb({},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=pM.enable?$w(t,2003,this._room.sdkAppId):yield oN(t),r=i instanceof ArrayBuffer,n="".concat(KD(+this._room.sdkAppId,dk.KV_STAT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i)),o||nN({url:n,body:i})}))}};yb([_x({settings:{timeout:500,retries:3}})],yj.prototype,"upload",1);var Sj=5e3,Ij={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},Aj=class{constructor(e){Sb(this,"str_identifier"),Sb(this,"str_tinyid"),Sb(this,"uint32_role"),this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},Rj=yj,Cj=class{constructor(){Sb(this,"_startTime"),Sb(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=Aw())}stop(){0===this._endTime&&(this._endTime=Aw())}getDuration(){return 0===this._endTime?Aw()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},bj=class{constructor(e){Sb(this,"_room",null),Sb(this,"_durationMap"),Sb(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(hM.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(hM.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(hM.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;var n;let{userId:o}=r;if(!this.hitTest(t))return;i.hasAudio&&!r.hasAudio&&this.stopDurationItem("".concat(o,"_main"),Sk.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_main"),Sk.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_auxiliary"),Sk.VIDEO);let s=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);s&&(!i.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,Sk.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,Sk.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,Sk.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>dM.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>dM.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 Cj,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===Sk.AUDIO?[n]:[],video:t===Sk.AUDIO?[]:[n]})}stopDurationItem(e,t){if(this._durationMap.has(e)){let i=this._durationMap.get(e)[t].find((e=>0===e.endTime));i&&i.stop()}}hitTest(e){return this._room===e}getDuration(e,t){return this._durationMap.has(e)?this._durationMap.get(e)[t].reduce(((e,t)=>e+t.getDuration()),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},kj=class{constructor(e){Sb(this,"_room"),Sb(this,"_renderFreezeMap",new Map),Sb(this,"_isVideoPlayingEventFiredMap",new Map),Sb(this,"_dataFreezeMap",new Map),Sb(this,"_monitorFreezeData",new Map),Sb(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(hM.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(hM.PLAY_TRACK_START,this.onPlayTrackStart).set(hM.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);this.stopDataFreeze({key:o,userId:n,type:i})})).set(hM.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(hM.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(t.isRemote&&t.room&&this.hitTest(t.room)&&n===Sk.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===Sk.MUTE?this.onVideoTrackMuted(t):r===Sk.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(hM.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>dM.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>dM.off(t,e,this))),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i),n=this._dataFreezeMap.get(r),o=new Cj;n?n.durationItemList.push(o):this._dataFreezeMap.set(r,{userId:t,type:i,durationItemList:[o],isFreezing(){let e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i);this.stopDataFreeze({key:r,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;this.hitTest(t)&&i.msg_down_stream_info.forEach((e=>{let t=this._room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);if(!t)return;let{userId:i,muteState:r}=t;e.msg_video_status.forEach((e=>{2===e.uint32_video_stream_type&&r.hasVideo&&!r.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"main"}),7===e.uint32_video_stream_type&&r.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"auxiliary"})}))}))}stopDataFreeze(e){let{key:t,userId:i,type:r}=e,n=this._dataFreezeMap.get(t);if(!n||!n.isFreezing())return;let o=n.durationItemList[n.durationItemList.length-1];o.stop();let s=o.getDuration();s>sD?this._monitorFreezeData.set(t,{userId:i,type:r,duration:s}):n.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return Ab(this,arguments,(function(e){var t=this;let{userId:i,fps:r,type:n}=e;return function*(){let e="".concat(i,"_").concat(n),o=t._renderFreezeMap.get(e);if(r<=2){let r=Aw();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:r,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(e,{userId:i,type:n,isFreeze:!0,freezeTimeline:[{startTime:r,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let e=o.freezeTimeline.pop();if(e){e.endTime=Aw();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room)||t.kind!==Sk.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()<sD&&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=Aw()-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()}},Dj=vb(Rb(),1),wj=class{constructor(e,t,i,r){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:4/3;this.vbMode=e,this.faceDetectorHash=t,this.visionTaskRegistry=i,this.logger=r,Sb(this,"animationState"),Sb(this,"originalAspect"),Sb(this,"totalOffsetX",0),Sb(this,"totalOffsetY",0),Sb(this,"defaultScaleRatio",.1),Sb(this,"isRecovering",!1),Sb(this,"boundaryY",280),Sb(this,"lastActionTime",0),Sb(this,"restTime",400),this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=n||4/3}addEvent(e,t,i){let r=[{key:570704,error:null!=i?i:t?void 0:11},{key:570705,error:null!=i?i:t?void 0:22}][e-1];r&&(t?BP.addSuccessEvent({key:r.key}):BP.addFailedEvent({key:r.key,error:r.error}))}actionCentering(e){let t=Date.now();if(this.animation(),!this.faceDetectorHash||t-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:i,videoHeight:r}=e;this.animationState.debounceThreshold=i/30,this.animationState.movementThreshold=i/20,this.boundaryY=.6*r;try{let e=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(e.detections.length<=0)return void(1===this.vbMode&&this.recoverOriginal(i,r));let t=e.detections[0].boundingBox,n=t.originX,o=t.originY,s=t.width,a=t.height;1===this.vbMode?this.dualStageCropping(i,r,n,o,s,a):2===this.vbMode&&this.movingPortrait(i,r,n,o,s,a)}catch(kM){this.logger.error(kM)}this.lastActionTime=t}calculateBoundary(e,t,i,r){let n,o;return e>t/2?(n=t-i-r,o=i-n):(n=i,o=0),{min:n,offset:o}}calculateTargetPosition(e,t,i,r,n,o){let s,a,c=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.4,l=e+i/2,d=t+r/2,{min:u,offset:h}=this.calculateBoundary(l,n,e,i),{min:p,offset:m}=this.calculateBoundary(d,o,t,r);return s=2*u+i,a=2*p+r,s/a>this.originalAspect?(s=a*this.originalAspect,h=l-s/2):(a=s/this.originalAspect,m=d-a/2),i/n>c&&(h=0,m=0,s=n,a=o),h=Math.max(0,Math.min(h,n-s)),m=Math.max(0,Math.min(m,o-a)),{sx:h,sy:m,cropWidth:s,cropHeight:a,timestamp:Date.now()}}processFacePositionCrop(e,t,i){if(!this.animationState.current||!this.animationState.target){let e={sx:0,sy:0,cropWidth:t,cropHeight:i,timestamp:Date.now()};return this.animationState.current=e,void(this.animationState.target=e)}let r=this.positionDistance(this.animationState.target,e),n=this.positionDistance(this.animationState.current,e),o=this.animationState.current.cropWidth/t;r>this.animationState.debounceThreshold*o&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&n>this.animationState.movementThreshold*o&&(this.animationState.target=e,this.animationState.debounceTimer=setTimeout((()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0}),this.animationState.debounceTime))}processFacePositionPortrait(e){if(!this.animationState.current||!this.animationState.target)return this.animationState.current=fb({},e),void(this.animationState.target=fb({},e));let t=this.positionDistance(this.animationState.current,e),i=this.positionDistance(this.animationState.target,e);t>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&i>this.animationState.movementThreshold&&(this.animationState.current=e,this.animationState.debounceTimer=setTimeout((()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0}),this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let e=Date.now()-this.animationState.startTime,t=Math.min(e/this.animationState.duration,1),i=e=>e<.5?2*e*e:(4-2*e)*e-1;if(this.animationState.current&&this.animationState.target){let e=(this.animationState.target.sx-this.animationState.current.sx)*i(t);this.animationState.current.sx+=e,this.totalOffsetX+=e;let r=(this.animationState.target.sy-this.animationState.current.sy)*i(t);if(this.animationState.current.sy+=r,this.totalOffsetY+=r,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*i(t),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*i(t),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*i(t)),hw(this.animationState.current.scaleOffsetX)&&hw(this.animationState.target.scaleOffsetX)&&hw(this.animationState.current.scaleOffsetY)&&hw(this.animationState.target.scaleOffsetY)){let e=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*i(t);this.animationState.current.scaleOffsetX+=e;let r=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*i(t);this.animationState.current.scaleOffsetY+=r}}t>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(e,t){return Math.sqrt(mb(e.sx-t.sx,2)+mb(e.sy-t.sy,2))}recoverOriginal(e,t){this.animationState.target={sx:0,sy:0,cropWidth:e,cropHeight:t,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(e,t,i,r,n,o){let s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.3;if(this.isRecovering)return;let a=this.calculateTargetPosition(i,r,n,o,e,t);this.processFacePositionCrop(a,e,t),n*o/a.cropWidth/a.cropHeight>s&&this.recoverOriginal(e,t)}movingPortrait(e,t,i,r,n,o){var s,a,c,l,d,u,h,p,m,_,f,g;let E={sx:i+n/2+this.totalOffsetX,sy:r+o/2+this.totalOffsetY,cropWidth:e,cropHeight:t,scaleRatio:null!=(a=null==(s=this.animationState.current)?void 0:s.scaleRatio)?a:1,scaleOffsetX:null!=(l=null==(c=this.animationState.current)?void 0:c.scaleOffsetX)?l:0,scaleOffsetY:null!=(u=null==(d=this.animationState.current)?void 0:d.scaleOffsetY)?u:0,timestamp:Date.now()};this.animationState.target={sx:e/2,sy:r+o/2,cropWidth:e,cropHeight:t,scaleRatio:null!=(p=null==(h=this.animationState.target)?void 0:h.scaleRatio)?p:1,scaleOffsetX:null!=(_=null==(m=this.animationState.target)?void 0:m.scaleOffsetX)?_:0,scaleOffsetY:null!=(g=null==(f=this.animationState.target)?void 0:f.scaleOffsetY)?g:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(n*o/e/t/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=1-this.animationState.target.scaleRatio,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(E)}set aspectRatio(e){this.originalAspect=e}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}},Nj=class extends wB{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log}),Sb(this,"_bgTexture"),Sb(this,"_waterMarkTexture"),Sb(this,"_lastMaskTexture"),Sb(this,"_lastMaskFbo"),Sb(this,"_textureValid",!1),Sb(this,"_selfieTextureValid",!1),Sb(this,"_selfieSegmentationHash"),Sb(this,"wasm"),Sb(this,"predictReady"),Sb(this,"_color"),Sb(this,"_prePrograme"),Sb(this,"_segmentationMask"),Sb(this,"_weixin",!1),Sb(this,"_centerFace"),Sb(this,"_textureMatrixLocation"),Sb(this,"_offsetMatrixLocation"),Sb(this,"_colorLocation"),Sb(this,"_enableFaceCentering",!1),Sb(this,"_enableEffectOptimization",!1),Sb(this,"_mat4"),Sb(this,"_postProcessing"),Sb(this,"_onAbort"),Sb(this,"_visionTaskRegistry"),Sb(this,"resolvePreditReady"),this.init(t).catch((t=>{e.log.error(t),e.destroy(new Ub({code:xb.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(t.message||t)})),this.resolvePreditReady()}))}init(e){return Ab(this,null,(function*(){var t,i,r;this.predictReady=new Promise((e=>{this.resolvePreditReady=e}));let n=e.Wasm,o=this.context.ctx;if(e.color&&(this._color=e.color),e.mat4&&(this._mat4=e.mat4),e.postProcessing&&(this._postProcessing=e.postProcessing),this._enableFaceCentering=null!=(t=e.enableFaceCentering)&&t,this._enableEffectOptimization=null!=(i=e.enableEffectOptimization)&&i,this.wasm=new n.AllIn1(o),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.rotation=e.rotation||0,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"color"===e.bg?3:0,this._onAbort=e.onAbort,e.bg||this.resolvePreditReady(),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)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),o.uniform1i(o.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(o.uniform1i(o.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(o.uniform1i(o.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let s=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=o.getUniformLocation(this.program,"u_textureMatrix"),o.uniformMatrix4fv(this._textureMatrixLocation,!1,s),this._offsetMatrixLocation=o.getUniformLocation(this.program,"u_offsetMatrix"),o.uniformMatrix4fv(this._offsetMatrixLocation,!1,s),this._colorLocation=o.getUniformLocation(this.program,"u_color"),o.uniform1i(o.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(o.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(o.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),o.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),o.uniform1i(o.getUniformLocation(this._prePrograme,"mask"),1)}this._enableEffectOptimization&&(2===this.wasm.vbMode||3===this.wasm.vbMode)&&(null==(r=this._postProcessing)||r.init(o,this.positionBuffer,this.texCoordBuffer,4/3)),yield this.initVisionTasks(e)}))}initVisionTasks(e){return Ab(this,null,(function*(){if(e.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._visionTaskRegistry.video=this.image,this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let e=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!e)return;this._centerFace=new wj(this.wasm.vbMode,e,this._visionTaskRegistry,this.context.log)}catch(Xk){this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}}))}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let i=this.getMaskTexture(e);if(!i)return;let r=i;this._enableEffectOptimization&&this._postProcessing&&(2===this.wasm.vbMode||3===this.wasm.vbMode)&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,r=this._postProcessing.postProcessing(i)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,r||null),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),3===this.wasm.vbMode&&t.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),Yw(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),t.viewport(0,0,t.canvas.width,t.canvas.height),t.drawArrays(t.TRIANGLE_STRIP,0,4),e.close()}getMaskTexture(e){return e.confidenceMasks?e.confidenceMasks[0].getAsWebGLTexture():void 0}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){let t=this.context.ctx,{image:i}=this;this.tryVideoFrameCallback();let{videoWidth:r,videoHeight:n}=i;if(Yw(this.wasm.rotation)&&!this._visionTaskRegistry&&([r,n]=[n,r]),0===r||0===n||!this.available)return!1;i.width=r,i.height=n;let o=!1;if(this.totalFrames)this.useTexture(),o=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),o=this._textureValid,this._textureValid=!0}if(this.width===r&&this.height===n&&o?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,i):(this.resize(r,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,i)),this._weixin){if(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let e=this.getMaskTexture(this._segmentationMask);t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,e||null),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)}t.drawArrays(t.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,r,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,r,n,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let e=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);1===this.totalFrames&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(e)}}catch(bM){this._onAbort&&this._onAbort(bM)}return this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let e=this.context.ctx;this._centerFace.aspectRatio=e.canvas.width/e.canvas.height,this._centerFace.actionCentering(this.image);let{current:t,offset:i}=this._centerFace;if(t&&(1===this.wasm.vbMode&&this.drawImage(t.sx,t.sy,t.cropWidth,t.cropHeight),i&&2===this.wasm.vbMode)){if(!this._mat4)return;let r=this._mat4.create(),{scaleRatio:n=1,scaleOffsetX:o=0,scaleOffsetY:s=0}=t;this._mat4.fromTranslation(r,[-i.offsetX/e.canvas.width+o,s,0]),this._mat4.scale(r,r,[n,n,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,r)}}drawImage(e,t,i,r){let n=this.context.ctx;if(!this._mat4)return;let{width:o,height:s}=n.canvas,a=this._mat4.create();this._mat4.fromTranslation(a,[e/o,1-(t+r)/s,0]),this._mat4.scale(a,a,[i/o,r/s,1]),n.uniformMatrix4fv(this._textureMatrixLocation,!1,a)}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),this._postProcessing&&this._postProcessing.close(),null==(e=this.wasm)||e.close()}},Oj=class extends yB{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 }"}),Sb(this,"yTextureRef"),Sb(this,"uTextureRef"),Sb(this,"vTextureRef"),Sb(this,"Y"),Sb(this,"U"),Sb(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)}},Mj=[e=>{e.codec="avc1.42e01f"},e=>{delete e.hardwareAcceleration}],Pj=(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")};var Lj=0,xj=class{constructor(e){Sb(this,"id",Lj++),Sb(this,"trackDoneOB"),Sb(this,"startOB"),Sb(this,"stopOB"),Sb(this,"decoder"),Sb(this,"videoContext"),Sb(this,"gop",0),Sb(this,"gop_helper",0),Sb(this,"waitFirstKeyFrame",!0),Sb(this,"startTimestamp",0),Sb(this,"startTime",0),Sb(this,"startPerformanceTime",0),Sb(this,"inputFrameCount",0),Sb(this,"decodedFrameCount",0),Sb(this,"decodeFrameCount",0),Sb(this,"downgradeLevel",0),Sb(this,"lastDowngradeTime",0),Sb(this,"lastFrameDiff",0),Sb(this,"lastDecodeFrameTimestamp",0),Sb(this,"config"),Sb(this,"gop_before_configure",[]),Sb(this,"videoElement"),Sb(this,"type","wasm"),Sb(this,"goodType"),Sb(this,"renderer","2d"),Sb(this,"wasmOption"),Sb(this,"createDecoder"),Sb(this,"_decodeSink"),Sb(this,"isReported",!1),Sb(this,"track"),Sb(this,"stateChangeOB"),Sb(this,"failedReason");let{track:t,createDecoder:i}=e;if(this.stateChangeOB=bU(),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=VU(t.availableState,tx.OFF),this.stopOB=bU(),"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),sU(this.stateChangeOB,bF(((e,i)=>(e!==i&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:e,state:i}),i)),"INITIALIZED"),oF(this.stopOB),nB()),this.start()}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=sU(this.pipe(this.track),oF(this.stopOB),mU());sU(t,nB((()=>{this.track.stat.framesDecoded++}),(t=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(t," retryCount: ").concat(e)),BP.addFailedEvent({key:Pj(this.type,this.renderer),error:t}),e>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),BP.addFailedEvent({key:514704});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")),BP.addSuccessEvent({key:Pj(this.type,this.renderer)}),BP.addSuccessEvent({key:514704})}))),sU(t,nF(1),nB((()=>{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&&!YP()&&(this.renderer="2d"),this.wasmOption.yuvMode="webgl"===this.renderer}decode(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i,r;if(this.failedReason)return;this.inputFrameCount++;let n=new Uint8Array(e.data);if(0!==(o=n)[0]||0!==o[1]||0!==o[2]||1!==o[3]||n.length<5)return this.stateChangeOB.next("FAILED"),this.close("not h26x frame ".concat(n.subarray(0,5))),e;var o;let s=!1;switch(31&n[4]){case 5:case 7:s=!0}if("configured"!==(null==(i=this.decoder)?void 0:i.state))return this.track.log.debug("not configured ".concat(this.inputFrameCount)),s&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:e.data,timestamp:e.timestamp,type:e.type}),e;this.gop_before_configure.length>0&&!t&&(this.gop_before_configure.forEach((e=>this.decode(e,!0))),this.gop_before_configure=[]);let{timestamp:a}=e;if(s?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!s)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(n.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=a,this.startTime=Date.now(),this.startPerformanceTime=Aw()}switch(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.decodeFrameCount<10||this.decodeFrameCount%500==0)&&this.track.log.debug("decode ".concat(this.decodeFrameCount," gop: ").concat(this.gop," ").concat(a," ").concat(null==(r=e.getMetadata)?void 0:r.call(e).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=a,void this.decoder.decode({data:e.data,type:e.type,timestamp:this.lastDecodeFrameTimestamp})}return e}checkDowngradeByFrameDiff(){let e=this.downgradeLevel,t=this.decodeFrameCount-this.decodedFrameCount;t>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):t<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug("downgrade level ".concat(e," to ").concat(this.downgradeLevel," ").concat(this.decodeFrameCount," frameDiff: ").concat(t,", lastFrameDiff: ").concat(this.lastFrameDiff)),this.lastFrameDiff=t,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(e){let t=this.downgradeLevel;this.lastDecodeFrameTimestamp-e>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==t&&this.track.log.debug("downgrade level ".concat(t," to ").concat(this.downgradeLevel))}pipe(e){return t=>Ab(this,null,(function*(){this._decodeSink=t;let i,r=e.mediaTrack;t.defer((()=>{var t;r&&(e.player.setCanvas(),e.setInputMediaStreamTrack(r)),null==i||i.close(),null==(t=this.videoContext)||t.destroy(),delete this._decodeSink}));let{renderer:n,type:o}=this;e.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(o){case"wasm":i=this.createDecoder(o,this.wasmOption);break;case"webCodecs":for(let e=0;e<=Mj.length;e++){let{supported:i}=yield VideoDecoder.isConfigSupported(this.config);if(i)break;if(e===Mj.length)return void t.error(3);Mj[e](this.config)}i=this.createDecoder(o);break;default:throw new Error("not supported yet")}let r=0;if(i.on("videoFrame",(i=>{this.decodedFrameCount++,r++,(r<=10||r%500==0)&&e.log.debug("frame ".concat(r," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(i.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&("webCodecs"===this.type?this.checkDowngradeByFrameDiff():"wasm"===this.type&&this.checkDowngradeByTimestampDiff(i.timestamp)),t.next(i)})),i.on("error",(i=>{e.log.error(i),t.error("webCodecs"===o?4:8)})),yield i.initialize(this.videoElement),!this._decodeSink)return;if(i.configure(this.config),"wasm"===o&&"webgl"===n){this.videoContext=new LB({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(LB.UNAVAILABLE,(i=>{e.log.error(i),t.error(7)}));let r=new Oj(this.videoContext);i.on("videoCodecInfo",(e=>r.resize(e.width,e.height))),i.on("videoFrame",(e=>{({y:r.Y,u:r.U,v:r.V}=e),1===this.downgradeLevel?this.decodedFrameCount%2==0&&r.render(this.decodedFrameCount):r.render(this.decodedFrameCount)})),e.source=r,e.player.setCanvas(this.videoContext._canvas,2)}else if("videoFrame"===n){e.player.setCanvas();let t=new MediaStreamTrackGenerator({kind:"video"}),r=t.writable.getWriter();e.setInputMediaStreamTrack(t),i.on("videoFrame",(e=>r.write(e)))}else{this.videoContext=new xB({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create({alpha:!1});let r=this.videoContext.createVideoImageSource();i.on("videoFrame",(i=>{try{r.image=i,r.update()}catch(n){delete this.goodType,e.log.error(n),t.error(11)}}));let n=new AB(this.videoContext,{name:"remotePlayer",logger:e.log});r.connect(n),e.source=r,e.player.setCanvas(this.videoContext._canvas,2)}this.decoder=i}catch(RM){e.log.error(RM),t.error("webCodecs"===o?2:6)}}))}},Vj=class extends Dj.EventEmitter{constructor(e){super(),this.room=e,Sb(this,"videoContext"),Sb(this,"_glVideoContext"),Sb(this,"_2dVideoContext"),Sb(this,"destination"),Sb(this,"smallVideoContext"),Sb(this,"smallDestination"),Sb(this,"smallTrackSource"),Sb(this,"smallImageSource"),Sb(this,"_isMirror",!1),Sb(this,"_rotation",0),Sb(this,"cameraTrack"),Sb(this,"cameraNode"),Sb(this,"transformNode"),Sb(this,"mixNode"),Sb(this,"screenTrack"),Sb(this,"screenNode"),Sb(this,"selfModel",!1),Sb(this,"blurRadius",3),Sb(this,"arTrack"),Sb(this,"_enableFaceCentering",!1),Sb(this,"_enableEffectOptimization",!1),Sb(this,"onAbort"),Sb(this,"_color"),Sb(this,"Wasm"),Sb(this,"waterMarkNode"),Sb(this,"_waterMarkOption"),Sb(this,"watermarkImageList",[]),Sb(this,"_beautyParams"),Sb(this,"isUsingArTrack",!1),Sb(this,"mixTrack"),Sb(this,"_isMixScreen",!1),Sb(this,"_virtualBackground"),Sb(this,"_virtualBackgroundAbortCallback"),Sb(this,"virtualBackgroundInstance"),Sb(this,"_bgAssetPath"),Sb(this,"log",_M.createLogger({id:"vm"})),Sb(this,"_mat4"),Sb(this,"_postProcessing"),Sb(this,"_checkId",0),Sb(this,"_use2d",!1),Sb(this,"_autoSwitchRenderMode",!0),Sb(this,"encodePipeline",[]),Sb(this,"decodePipeline",[]),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new xB({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return(null==(e=this.room)?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return 0!==this._rotation}get _isTransform(){return this._isMirror||this._isRotate}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())}get cameraResolution(){var e;let{width:t,height:i}=(null==(e=this.cameraTrack)?void 0:e.settings)||{};return Yw(this._rotation)?{width:i,height:t}:{width:t,height:i}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new xB({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 LB({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on(LB.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(zb){this.emit("error",zb)}}initVirtualBackground(e,t,i){this.onAbort=e,this._mat4=t,this._postProcessing=i}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=ax.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(),ax.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(PO||this._isMixScreen||this._isTransform||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?BP.addFailedEvent({key:t,error:e}):BP.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 LB({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}setSmallVideo(e,t){if("api"!==this.smallMode)if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new bB(this.smallVideoContext,e,this.log),this.smallVideoContext.on(LB.UNAVAILABLE,(e=>{this.log.warn("small video context lost",e)}))}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:e,height:t}=this.cameraTrack.settings;this.smallTrackSource.resize(e,t),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let i=this.cameraTrack,{small:r,player:n}=i;PO&&n.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.log.info("set main output ".concat(o?o.label:"no output track")),this.setSmallVideo(r,e),i.setOutputMediaStreamTrack(o)}catch(AM){this.log.error("set main output failed",AM)}}update(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Ab(this,null,(function*(){var t;if(!this.cameraTrack||!this.initialTrack)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}),this.destination.on(yB.RENDER,(e=>{var t;null==(t=this.cameraTrack)||t.emit("render",e)}))),16===BO?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof wB?(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 wB?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);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new CB(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(yB.RENDER,(e=>{var t;null==(t=this.cameraTrack)||t.emit("render",e)})));let{width:e,height:t}=this.cameraResolution,i=yield this.getWatermarkImage(e,t);this._waterMarkOption={x:0,y:0,width:i.width,height:i.height,image:i},this.cameraNode=new Nj(this.videoContext,{input:this.initialTrack,width:e,height:t,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=r.frameRate,this._use2d){let e=this.cameraNode;if(e.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new HB(this.videoContext,this.log,this._isMirror,this._rotation),e=e.connect(this.transformNode),e.disconnect(),this.log.info("start mirror ".concat(this._isMirror," rotate ").concat(this.rotation))),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new FB(this.videoContext,this.log),e.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;else if(this.waterMarkNode){let{width:e,height:t}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(e,t),e&&t&&this.waterMarkNode.resize(e,t)}null==(t=this.waterMarkNode)||t.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),e=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))}e.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext._canvas)}))}clearLastFrame(){var e;this.destination&&(null==(e=this.destination.ctx2d)||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var t,i,r,n,o;if(e instanceof JB)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof fB)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof eH){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);let t=e.mediaTrack;return e.setOutputMediaStreamTrack(t)}if(e instanceof WB)return this.log.info("change mix input",null==(n=e.outMediaTrack)?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",null==(o=e.mediaTrack)?void 0:o.label)}removeInput(e){var t;e instanceof JB?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof fB?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof eH?e.source&&e.source.context.destroy():e instanceof WB&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return Ab(this,null,(function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}))}getWatermarkImage(e,t){return Ab(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 Ub({code:xb.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort(((e,t)=>e.zIndex-t.zIndex)),this.watermarkImageList.forEach((e=>{let{image:t,x:i,y:n,width:o,height:s}=e;r.drawImage(t,i,n,o,s)})),Hw(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 Ab(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return Ab(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return Ab(this,null,(function*(){let t;try{t=yield Hw((null==e?void 0:e.imageElement)||e.imageUrl)}catch(c){throw new Ub({code:xb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:i=0,y:r=0,width:n=t.width,height:o=t.height,type:s="watermark",zIndex:a=2}=e;this.watermarkImageList.some((e=>e.type===s))?(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==s)),this.pushWaterMarkImageList({x:i,y:r,width:n,height:o,image:t,zIndex:a,type:s,imageUrl:e.imageUrl}),t=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:i,y:r,width:n,height:o,image:t,zIndex:a,type:s,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,((e,t)=>"imageUrl"===e?void 0:t)))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return Ab(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 Ab(this,null,(function*(){var e;null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:t,height:i}=this.cameraResolution,r=yield this.getWatermarkImage(t,i);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()}))}setVirtualBackground(e){return Ab(this,null,(function*(){var t,i,r;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 Hw(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=null!=(t=e.enableFaceCentering)?t:this._enableFaceCentering,this._enableEffectOptimization=null!=(i=e.enableEffectOptimization)?i:this._enableEffectOptimization,this._color=null!=(r=e.color)?r:[0,1,0]}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 Ub({code:xb.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._isTransform||(null==(t=this.transformNode)||t.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var t;this._rotation!==e&&(this._rotation=e,this._isTransform||(null==(t=this.transformNode)||t.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return Ab(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 xj(e)}clear(){var e,t;null==(e=this.videoContext)||e.disconnect(),null==(t=this.destination)||t.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,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}};yb([UV((function(e){this.log.error("update failed",e)}))],Vj.prototype,"update",1);var Uj=0,Fj=class extends tx{constructor(e){super("room"),Sb(this,"seq",++Uj),Sb(this,"sdkAppId"),Sb(this,"userId"),Sb(this,"userSig"),Sb(this,"privateMapKey"),Sb(this,"latencyLevel"),Sb(this,"tinyId"),Sb(this,"scene"),Sb(this,"roomId"),Sb(this,"useStringRoomId"),Sb(this,"role","anchor"),Sb(this,"joinParams",null),Sb(this,"localPublishFlag",0),Sb(this,"localTracks",new Set),Sb(this,"enableAutoPlayDialog",!0),Sb(this,"autoReceiveAudio",!0),Sb(this,"autoReceiveVideo",!0),Sb(this,"proxy_ws"),Sb(this,"proxy_wt"),Sb(this,"proxy_unified"),Sb(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,isH265EncodeSupported:!0,isH265DecodeSupported:!0}}),Sb(this,"keyPointManager"),Sb(this,"audioManager"),Sb(this,"videoManager"),Sb(this,"callDurationCalculator"),Sb(this,"badCaseDetector"),Sb(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),Sb(this,"videoDecodeFallbackType"),Sb(this,"smallMode","canvas"),Sb(this,"_isUsingCachedSchedule",!1),Sb(this,"_log",_M.createLogger({id:"r".concat(this.seq)})),Sb(this,"_joinedTimestamp",0),Sb(this,"_sdkType"),Sb(this,"heartbeatReport"),Sb(this,"quality"),Sb(this,"enableSEI"),Sb(this,"isDestroyed",!1),this.useStringRoomId=!!e.useStringRoomId,pw(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),pw(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),pw(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new Rj({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new bj({room:this}),this.badCaseDetector=new kj({room:this}),this.audioManager=new YB(this),this.videoManager=new Vj(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 Ab(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return Ab(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return Ab(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(uw(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(ow(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:r,scheduleProxy:n,unifiedProxy:o}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=o,o?(ZH([o,o]),ek("https://".concat(o))):(r&&ek(r),n&&ZH(n))}dM.once(hM.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:QH.main,sched_back_domain:QH.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return Ab(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return Ab(this,null,(function*(){var e;let t={rtt:(null==(e=this.quality)?void 0:e.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let i of this.quality.downlinkInfo)t.downlinksRTT[i.userId]=i.rtt;return t}))}getRemoteVideoStats(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"main";return function*(){let i={};return e.remotePublishedUserMap.forEach((e=>{let r="auxiliary"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;i[e.userId]=r.stat})),i}()}))}checkDestroy(){if(this.isDestroyed)throw new Ub({code:xb.INVALID_OPERATION,message:kP({key:AP.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(RP.INVALID_DESTROY),new Ub({code:xb.INVALID_OPERATION,message:kP({key:AP.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,dM.emit(hM.ROOM_DESTROY,{room:this})}schedule(e,t){return Ab(this,null,(function*(){var i,r,n,o;let s=Aw();try{let{isCached:a,result:c,detailCost:l}=yield XH({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Kb,userSig:this.userSig,role:"live"===this.scene?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=a,this._log.info("schedule cache:".concat(+a," ").concat(Vw(c,{keysToExclude:["username","credential"]}))),a&&dM.once(hM.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=fb(fb({},this.scheduleResult),c),hw(null==(i=c.config)?void 0:i.retryCount)&&zk(c.config.retryCount),uw(null==(r=c.config)?void 0:r.loggerDomain)&&ek(c.config.loggerDomain),this.videoDecodeFallbackType=(null==(n=c.config)?void 0:n.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=(null==(o=c.config)?void 0:o.smallMode)||this.smallMode,dM.emit(hM.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:l}),BP.addSuccessEvent({key:521700,cost:Aw()-s})}catch(yM){throw BP.addFailedEvent({key:521700,error:yM}),yM}}))}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}},Bj=vb(Rb()),Hj=vb(Mb());function Wj(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 Gj=(e,t,i)=>Ab(void 0,null,(function*(){var r;let n=cj(e),o={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};o.ice.ufrag=String(n.media[0].iceUfrag),o.ice.password=n.media[0].icePwd||"",n.fingerprint&&(o.dtls.hash=n.fingerprint.type,o.dtls.fingerprint=n.fingerprint.hash,o.dtls.setup=n.setup||""),n.media[0].fingerprint&&(o.dtls.hash=n.media[0].fingerprint.type,o.dtls.fingerprint=n.media[0].fingerprint.hash),o.dtls.setup=n.media[0].setup||"";let s=n.media[0],a=n.media[1];s.ext&&(o.audio.extensions=s.ext.map((e=>({id:e.value,uri:e.uri})))),a.ext&&(o.video.extensions=a.ext.map((e=>({id:e.value,uri:e.uri}))));let c={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channels:s.rtp[0].encoding,rtcpfb:[],rtx:0};null==(r=s.rtcpFb)||r.forEach((e=>{let{payload:t,type:i,subtype:r}=e;if(t===c.payload){let e={id:i,params:[]};r&&e.params.push(r),c.rtcpfb.push(e)}})),o.audio.codecs.push(c);let l=["h264","vp8","h265"];return t&&l.shift(),i&&l.pop(),o.video.codecs=[...Wj(a)].filter((e=>l.includes(e.codec.toLocaleLowerCase()))),o.video.decoders=(yield function(){return Ab(this,null,(function*(){let e=new RTCPeerConnection;e.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY});let t=yield e.createOffer();if(!t.sdp)return[];let i=Wj(cj(t.sdp).media[0]);return e.close(),i}))}()).filter((e=>["h264","vp8","h265"].includes(e.codec.toLocaleLowerCase()))),o})),jj=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,o=cj(r),s={extmapAllowMixed:"extmap-allow-mixed",groups:o.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},a={candidates:t.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:o.media[0].port,protocol:o.media[0].protocol,type:Sk.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map((e=>({payload:t.audio.codecs[0].payload,type:e.id,subtype:e.params[0]}))),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};return s.media.push(a),[1,2,3].forEach((e=>{s.media.push(Jj({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),n&&s.media.push(o.media.find((e=>"dc"===e.mid))),lj(s)},Jj=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,isDownlink:o=!1}=e,s={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(t),payloads:"",port:n.media[0].port,protocol:n.media[0].protocol,type:Sk.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(o){let e=i.video.decoders;(!e||0===e.length)&&(e=i.video.codecs),(!e||0===e.length)&&(e=r.video.decoders),e.forEach((e=>{Kj(s,e)}))}else{let e;e=i.useH265?i.video.codecs.findIndex((e=>"h265"===e.codec.toLowerCase())):i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264")));let t=i.video.codecs[e]||r.video.codecs[0];Kj(s,t)}return s},Kj=(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 qj=(e,t,i)=>{let r=Hj.default.parse(e);return r.media.forEach(((e,n)=>{var o;if((e.type===Sk.AUDIO||e.type===Sk.VIDEO)&&(function(e){if(!e.rtcpFb)return;let t=[];e.rtcpFb.forEach(((i,r)=>{var n;t.push(i),e.rtcpFb&&(null==(n=e.rtcpFb[r+1])?void 0:n.payload)!==i.payload&&"rrtr"!==i.type&&t.push({payload:i.payload,type:"rrtr"})})),e.rtcpFb=t}(e),function(e){e.type===Sk.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===Sk.AUDIO&&e.fmtp&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))}(e),function(e){let t=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}(e),e.type===Sk.VIDEO))if(n<4)e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach((t=>Kj(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=>Kj(e,t)))}null!=(o=e.payloads)&&o.includes("datachannel")&&r.groups&&e.mid&&(r.groups[0].mids=r.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),Hj.default.write(r)},zj=vb(Rb()),Yj=class extends zj.EventEmitter{constructor(e){super(),this.room=e,Sb(this,"mainFpsHealth",1),Sb(this,"mainBitrateHealth",1),Sb(this,"badMainBitrateHealthCount",0),Sb(this,"lastEmitBadHealthTime",0),Sb(this,"log"),!CN&&kO&&dM.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(){dM.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};Sb(Yj,"EVENT_BAD_HEALTH","bad_health");var Xj=Yj;function Qj(e){let{seiMessageList:t,isAudio:i,isMain:r}=e;return new TransformStream({transform(e,n){let o=e;i?audioEncodePipeline.forEach((e=>{o=e({frame:o})})):videoEncodePipeline.forEach((e=>{o=e({frame:o,seiMessageList:t,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:o.data,userId:"",streamType:r?"main":"auxiliary"})}})})),n.enqueue(o)}})}function Zj(e,t,i){return new TransformStream({transform(r,n){let o=r;videoDecodePipeline.forEach((r=>{o=r({frame:o,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:o.data,userId:e,streamType:t})}})})),n.enqueue(o)}})}var $j=(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))($j||{}),eJ=0,tJ=!1,iJ=new Set,rJ=1,nJ=class extends Bj.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),Sb(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),Sb(this,"currentState","DISCONNECTED"),Sb(this,"_room"),Sb(this,"_signalChannel"),Sb(this,"_peerConnection",null),Sb(this,"_datachannel",null),Sb(this,"_enableCustomMessage"),Sb(this,"_log"),Sb(this,"_downlinkMIDMap",new Map),Sb(this,"_downlinkMIDUserIDMap",new Map),Sb(this,"_reconnectionTimer",-1),Sb(this,"reconnectionCount",0),Sb(this,"clientAbility"),Sb(this,"_serverAbility",null),Sb(this,"addDownlinkQueue",new Set),Sb(this,"removeDownlinkQueue",new Set),Sb(this,"_parsedAnswer",null),Sb(this,"_updateSDPPromise",null),Sb(this,"_waitForPCConnectedPromise"),Sb(this,"clearWaitForConnectedPromise"),Sb(this,"clearConnectTimeout"),Sb(this,"_isSDPLogged",!1),Sb(this,"enableInsertableStreams",!1),Sb(this,"insertableStreamsAbortMap",new Map),Sb(this,"receiverRemoteTrackMap",new WeakMap),Sb(this,"scriptTransformWorker"),Sb(this,"_isRelayTried",!1),Sb(this,"_rttOverCount",0),Sb(this,"originOffer",null),Sb(this,"autoSubscribedSsrcGroups",new Map),Sb(this,"autoSubscribedUserMap",new Map),Sb(this,"_h265DecodeFailed",!1),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=_M.createLogger({id:"spc".concat(rJ++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(bL?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 isH265EncodeSupported(){let e=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((e=>"h265"===e.codec.toLowerCase()))),e}get videoCodec(){var e,t,i;let r=null==(e=this._parsedAnswer)?void 0:e.media[1].rtp.find((e=>["h264","vp8","h265"].includes(e.codec.toLowerCase())));return r?r.codec.toLowerCase():null!=(t=this._serverAbility)&&t.useH265?"h265":null!=(i=this._serverAbility)&&i.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e,t,i;return null!=(e=this._serverAbility)&&e.useH265&&null!=(t=this._serverAbility)&&t.video.decoders.find((e=>"h265"===e.codec.toLowerCase()))&&!this._h265DecodeFailed?"h265":null!=(i=this._serverAbility)&&i.video.decoders.find((e=>"h264"===e.codec.toLowerCase()))?"h264":"vp8"}get isUsingH264(){return"h264"===this.videoCodec}get isUsingH265(){return"h265"===this.videoCodec}get isUsingVP8(){return"vp8"===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=cj(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&&!dw(e.ssrcs[0].id)){let n=Number(e.ssrcs[0].id),o=Number(null==(r=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:r.id);switch(t){case 0:i.audioSsrc=n;break;case 1:i.bigVideoSsrc=n,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=n,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=n,i.auxVideoRtxSsrc=o}}})),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(e){let{isAux:t}=e;this.useHWEncoder(!1,t?7:2)}initScriptTransformWorker(){kL&&(this.scriptTransformWorker=function(e){let t=[pB],i=[PW,OW,MW,NW,Qj,Zj],r="const videoEncodePipeline=[".concat(e.videoEncodePipeline.toString(),"];\n const videoDecodePipeline=[").concat(e.videoDecodePipeline.toString(),"];\n const audioEncodePipeline = [").concat(e.audioEncodePipeline.toString(),"];\n const audioDecodePipeline = [").concat(e.audioDecodePipeline.toString(),"];"),n="(()=>{".concat(t.map((e=>"const ".concat(e.name,"=(()=>").concat(e.toString(),")()"))).join("\n"),"\n").concat(i.map((e=>e.toString())).join("\n"),";(").concat((()=>{let e=[],t=[],i=[];self.onmessage=r=>{"sei"===r.data.type&&(r.data.isMain?(e.push(r.data.data),r.data.small&&i.push(r.data.data)):t.push(r.data.data))},self.onrtctransform=r=>{let{options:n}=r.transformer,o=n.isReceiver?Zj(n.userId,n.streamType,n.isAudio):Qj({isAudio:n.isAudio,seiMessageList:n.isMain?n.small?i:e:t,isMain:n.isMain});r.transformer.readable.pipeThrough(o).pipeTo(r.transformer.writable)}}),")();").concat(r,"})()"),o=new Blob([n],{type:"text/javascript"}),s=URL.createObjectURL(o),a=new Worker(s);return URL.revokeObjectURL(s),a}({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{"sei"===e.data.type&&this.emit("sei-message",e.data),"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){var t;let i={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=null==(t=this._peerConnection)?void 0:t.getConfiguration().encodedInsertableStreams;return lN(r)&&(i.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(i)),i}initialize(e){return Ab(this,null,(function*(){var t,i;let r;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(),BP.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):"failed"===e&&BP.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 sJ(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(Sk.AUDIO,{direction:Sk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_SENDONLY}),r=yield this._peerConnection.createOffer(),this.clientAbility=yield Gj(r.sdp,(null==(t=this._room.scheduleResult.config)?void 0:t.remove264FromSDP)||!1,(null==(i=this._room.scheduleResult.config)?void 0:i.remove265FromSDP)||!1),this.originOffer=r,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()))}),BP.addSuccessEvent({key:521707}),this.clientAbility}catch(Yb){throw BP.addFailedEvent({key:521707,error:Yb}),this._log.error("initialize failed ".concat(Yb," \noffer: ").concat(null==r?void 0:r.sdp)),Yb}}))}setIceServers(e){return Ab(this,null,(function*(){var t;if(this._peerConnection&&0!==e.length)try{if(this._log.info("setIceServers",JSON.stringify(e,((e,t)=>"username"===e||"credential"===e?"hided":t))),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),null!=(t=this._peerConnection)&&t.localDescription||!this.originOffer)return void this._log.warn("setIceServers already has localDescription or no origin Offer");yield this.setOffer(this.originOffer)}catch(AM){this._log.warn("setIceServers error ",AM)}}))}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(Xk){this._log.warn("setPriority error ",Xk)}}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Ab(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 o=Aw(),s={type:"answer",sdp:jj({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(s),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||BP.addSuccessEvent({key:521703,cost:Aw()-o})}catch(RM){let i=RM instanceof Ub&&RM.code===xb.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(RM),e),this.reset(),!i&&!this.isReconnecting&&(BP.addFailedEvent({key:521703,error:RM}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),RM}}))}reconnect(){return Ab(this,null,(function*(){if(-1===this._reconnectionTimer){if(!this._signalChannel.isConnected)return this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(pG,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=fb({ability:t},e),r=yield this._signalChannel.sendWaitForResponse({command:jG,responseCommand:vG.REBUILD_PEER_CONNECTION_RES,data:i,enableLog:!1});if(0!==r.data.code)throw new Ub({code:r.data.code,message:r.data.message});yield this.connect(r.data.data.ability,!0),BP.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),dM.emit(hM.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(zb){if(!this.isReconnecting)return;if(null!=zb&&zb.message.includes("timeout")){let e=aw(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield jw(e,(e=>{this._reconnectionTimer=e})),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(null==zb?void 0:zb.code," ").concat(zb)),BP.addFailedEvent({key:521704,error:zb}),this.reconnectionCount>=Yk()&&this._log.warn("SDK has tried reconnect for ".concat(Yk()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")}))}getPeerConnection(){return this._peerConnection}startReconnection(){return Ab(this,null,(function*(){this.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(pG,this.reconnect,this),"RECONNECTING"===this.currentState&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===Kk.CLOSED&&this.startReconnection()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){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===Kk.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===Kk.FAILED||e.target.connectionState===Kk.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===Kk.CONNECTED||e.target.connectionState===Kk.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),dM.emit(hM.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 Jk;let e=null;return _L()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,mL()&&0!==this._peerConnection.getReceivers().length&&e?e.state:Jk):Jk}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit($j.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return Ab(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(oL(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&&XD(t.networkType)),r&&this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port));break}}))}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this.currentState)return e();let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new Ub({code:xb.API_CALL_ABORTED,message:kP({key:AP.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{dM.off(hM.LEAVE_SUCCESS,r,this),this.off($j.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{n();let e=new Ub({code:xb.API_CALL_TIMEOUT,message:"connection timeout"});var i;eJ+=1,i=this._signalChannel.isConnected,eJ>2&&!tJ&&0===iJ.size&&i&&(this._log.warn("firewall restriction"),tJ=!0,this.emit($j.FIREWALL_RESTRICTION)),t(e)}),dD);this.clearConnectTimeout=()=>{n(),clearTimeout(o),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new Ub({code:xb.API_CALL_TIMEOUT,message:"connection timeout"}))},dM.on(hM.LEAVE_SUCCESS,r,this),this.on($j.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 Ab(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(Xk){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(Xk)),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=Sk.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=cj(this._peerConnection.remoteDescription.sdp));let o,s,a,c=this._parsedAnswer.media.filter((e=>{var t;return null==(t=e.ssrcs)?void 0:t.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(r)}))}));if(3===c.length)o=c[0],s=c[1],a=c[2];else if(3===n.length)o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[0]))),s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[1]))),a=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[2])));else if(0===n.length){this._peerConnection.addTransceiver(Sk.AUDIO,{direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY}),o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=Jj({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:cj(this._peerConnection.localDescription.sdp),isDownlink:!0});s=JSON.parse(JSON.stringify(e)),a=JSON.parse(JSON.stringify(e)),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a)}o.direction=Sk.TRANSCEIVER_DIRECTION_SENDONLY;let l="".concat(r,"-").concat(t.audio);o.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(l)},{id:t.audio,attribute:"msid",value:"".concat(l,"-").concat(Sk.MAIN," ").concat(l,"-audio")}],s.direction=Sk.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(Sk.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(Sk.MAIN," ").concat(l,"-bigvideo")}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=Sk.TRANSCEIVER_DIRECTION_SENDONLY;let d="".concat(l,"-aux");a.ssrcs=[{id:t.auxiliary,attribute:"cname",value:d},{id:t.auxiliary,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Sk.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(Sk.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Sk.VIDEO)}],a.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map((e=>e.mid)).join(" ")),this._downlinkMIDMap.set(i,[o.mid,s.mid,a.mid]),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(s.mid,i),this._downlinkMIDUserIDMap.set(a.mid,i)}removeDownlink(e){return Ab(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=cj(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 Ab(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(SL()){let e=this._peerConnection.getSenders().slice(0,4);for(let s=0;s<e.length;s++){let o,a=e[s];0===s&&t?o=t:1===s&&i?o=i:2===s&&r?o=r:3===s&&n&&(o=n),o&&(yield this.setSenderMaxBitrate(a,o))}let o=!1;i&&e[1].track&&(o=this.setStartBitrate(1,i)),n&&e[3].track&&(o=this.setStartBitrate(3,n)||o),o&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info("setBandwidth ".concat(JSON.stringify(e)))}catch(RM){this._log.error("failed to set bandwidth: ".concat(RM))}}))}setStartBitrate(e,t){var i,r;return!(null==(i=this._peerConnection)||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=cj(this._peerConnection.remoteDescription.sdp)),null==(r=this._parsedAnswer.media[e])||!r.fmtp[0]))&&(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),!0)}setSenderMaxBitrate(e,t){let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),"unlimited"===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,e.setParameters(i)}setBandwidthBySDP(e){let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=cj(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=cj(this._peerConnection.remoteDescription.sdp));let s=wN?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:wN?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:wN?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:wN?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:wN?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:s,limit:wN?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:wN?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:s,limit:wN?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:wN?1e3*n:n}]);let a={type:"offer",sdp:lj(o)};return this.updateSDP({localDescription:a})}setScaleResolutionDownBy(e,t,i){let r=e.getParameters();(!r.encodings||0===r.encodings.length)&&(r.encodings=[{}]);let n=r.encodings[0].scaleResolutionDownBy;if(dw(n)?1===t:t===n)return;let o="setScaleResolutionDownBy ".concat(i," ").concat(t);return n&&(o+=" prevScale: ".concat(n)),this._log.warn(o),r.encodings[0].scaleResolutionDownBy=t,e.setParameters(r)}setDegradationPreference(e,t,i){if(kO&&NO<83||RN&&UO(VO,"12.1")||wN&&ON<138)return;let r=e.getParameters(),n="balanced";if("motion"===t?n="maintain-framerate":"detail"===t&&(n="maintain-resolution"),r.degradationPreference===n)return;let o="setDegradationPreference ".concat(i," ").concat(n);return this._log.info(o),r.degradationPreference=n,e.setParameters(r).catch((e=>this._log.warn("".concat(o," failed: ").concat(e))))}updateSDP(){let{localDescription:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=lj(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,r)=>Ab(this,null,(function*(){var n,o;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,i()}catch(bM){this._log.error(bM),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection(null==(n=this._peerConnection.localDescription)?void 0:n.sdp)," \nnext offer: ").concat(this.filterSDPDirection(null==e?void 0:e.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection(null==(o=this._peerConnection.remoteDescription)?void 0:o.sdp)," \nnext answer: ").concat(this.filterSDPDirection(t))),this._log.warn("offer: ".concat(null==e?void 0:e.sdp)),this._log.warn("answer: ".concat(t)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map((e=>{let{mid:t,currentDirection:i,direction:r,stopped:n}=e;return{mid:t,currentDirection:i,direction:r,stopped:n}}))))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,r(bM)}})))),this._updateSDPPromise}setTransceiverDirection(e,t){return Ab(this,null,(function*(){if(!wN||!this._peerConnection||!this._parsedAnswer)return;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let i=this._peerConnection.getTransceivers();t.forEach((t=>{i[t].direction!==e&&(i[t].direction=e)}));for(let r of t){let t=this._parsedAnswer.media[r].direction;e===Ik.INACTIVE&&t===Ik.RECVONLY&&(this._parsedAnswer.media[r].direction=e),e===Ik.SENDONLY&&t===Ik.INACTIVE&&(this._parsedAnswer.media[r].direction=Ik.RECVONLY)}yield this.updateSDP()}))}filterSDPDirection(){return cj(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((e=>e.direction))}setOffer(e){this._log.info("setting offer");let t=qj(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 Ab(this,null,(function*(){if("h265"===e&&!this._parsedAnswer&&(this._parsedAnswer=cj(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach((i=>{var r;if(i.type===Sk.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=[],Kj(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 Ab(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];dw(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===Sk.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=[],Kj(t,n),i=!0)}})),i&&(this._log.warn("use ".concat(e?"hw":"sw"," encoder")),yield this.updateSDP())}))}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),null==(e=this.clearWaitForConnectedPromise)||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach((e=>aN(e.abort)&&e.abort("destroy"))),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map((e=>t[e]))}get isUsingRelay(){return"relay"===this._room.getIceTransportPolicy()}detectTCPAndUDP(e){let{uplinkRTT:t,downlinkRTT:i}=e;var r;if("CONNECTED"!==this.currentState||this._isRelayTried&&!this._room.forceRelay||0===this._room.getIceServers().length)return;let n=this._signalChannel.rtt,o=Math.max(t,i),{rttRatioThreshold:s,rttThreshold:a}=(null==(r=this._room.scheduleResult.config)?void 0:r.useTurnTcpInfo)||{};if(!(s&&a&&n&&o))return;let c=Math.floor(o/n),l=(this._isRelayTried||c>s)&&o>a;l?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(n," upRTT: ").concat(t," downRTT: ").concat(i," ratio: ").concat(c," over-count: ").concat(this._rttOverCount," isOver: ").concat(l," isRelayTried: ").concat(this._isRelayTried," force-relay: ").concat(this._room.forceRelay)),this.isUsingRelay||this._isRelayTried?this._room.forceRelay&&this.switchRelay(!1):(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0))):this._rttOverCount=0}switchRelay(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Ab(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")),BP.addSuccessEvent({key:r,cost:Date.now()-t})}catch(Yb){this._log.warn("switchRelay ".concat(i," failed"),Yb),BP.addFailedEvent({key:r,error:Yb}),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)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:GG,data:{videoDecCodec:"h264"},responseCommand:vG.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)}))}};yb([KV("reconnect")],nJ.prototype,"startReconnection",1),yb([qV((e=>e.userId))],nJ.prototype,"addDownlink",1),yb([qV((e=>e))],nJ.prototype,"removeDownlink",1),yb([JV(!0)],nJ.prototype,"updateSDP",1),yb([zV(521712,!1)],nJ.prototype,"setOffer",1),yb([zV(521713,!1)],nJ.prototype,"setAnswer",1);var oJ=class{constructor(e){Sb(this,"tag"),Sb(this,"len"),Sb(this,"data");let t=new DataView(e);this.tag=t.getUint16(),this.len=t.getUint16(2),this.data=new Uint8Array(e).slice(4,4+this.len).buffer}},sJ=class{constructor(e){Sb(this,"tinyId"),Sb(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new oJ(new Uint8Array(e).slice(i,i+2+2+n).buffer);r.push(o),i+=4+n}r.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},aJ=new Set;function cJ(){let e=Math.floor(4294967296*Math.random());return aJ.has(e)?cJ():(aJ.add(e),e)}var lJ=vb(Rb()),dJ=class extends lJ.default{constructor(e){super(),Sb(this,"userId"),Sb(this,"tinyId"),Sb(this,"_sdpSemantics"),Sb(this,"_isUplink"),Sb(this,"_room"),Sb(this,"_log"),Sb(this,"_currentState","DISCONNECTED"),Sb(this,"_prevTime",-1),Sb(this,"_blackSmallVideoDetectionId"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=_M.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&&(dM.emit(hM.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"))}},uJ=new class{constructor(){Sb(this,"worker"),Sb(this,"callbacks",new Map),Sb(this,"_log"),Sb(this,"sleep",{}),Sb(this,"heartbeatListenerCleaner",new Map),Sb(this,"userIdMap",new Map),this._log=_M.createLogger({id:"bvd"})}getWorker(){if(!this.worker){let e=new Blob(['\n const tracks=new Map;let canvas,ctx;const log=(...t)=>postMessage({type:"log",message:"[worker] "+t.join(" ")});function startDetection(e,t,a){if(!tracks.has(e)){const c={reader:a.getReader(),blackCount:0,timeoutId:null,intervalId:null};tracks.set(e,c),c.timeoutId=setTimeout(()=>stopDetection(e,"timeout"),t),c.intervalId=setInterval(async()=>{try{await isFrameBlack(e)?(c.blackCount++,postMessage({type:"blackCount",trackId:e,count:c.blackCount}),3<=c.blackCount&&(postMessage({type:"black",trackId:e}),stopDetection(e,"black"))):c.blackCount=0}catch(t){log("check black video error:",t.message),stopDetection(e,"error")}},1e3)}}function stopDetection(t,e){var a=tracks.get(t);a&&(a.timeoutId&&clearTimeout(a.timeoutId),a.intervalId&&clearInterval(a.intervalId),a.reader&&a.reader.cancel(),tracks.delete(t),postMessage({type:e,trackId:t}))}async function isFrameBlack(t){t=tracks.get(t);if(!t)return!1;var t=t.reader,{done:t,value:e}=await t.read();if(!e||t)return!1;canvas||(canvas=new OffscreenCanvas(e.codedWidth,e.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===e.codedWidth&&canvas.height===e.codedHeight||(canvas.width=e.codedWidth,canvas.height=e.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(e,0,0,canvas.width,canvas.height);t=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return e.close(),1===t}function getFrameBlackRatio(t){var e=t.data;let a=0;for(let t=0;t<100;t++){var c=4*Math.floor(Math.random()*(e.length/4)),[c,r,n,o]=[e[c],e[1+c],e[2+c],e[3+c]];0<o&&0===c&&0===r&&0===n&&a++}return a/100}self.onmessage=t=>{var{type:t,trackId:e,timeout:a,readable:c}=t.data;"addTrack"===t&&startDetection(e,a,c),"removeTrack"===t&&stopDetection(e)};\n '],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=e=>this._log.warn("worker error:",e.message,e.filename||"unknown",e.lineno||"unknown"),this.worker.onmessage=e=>{var t;let{type:i,trackId:r,message:n,count:o}=e.data;if("black"===i)null==(t=this.callbacks.get(r))||t();else if("log"===i)this._log.warn(n);else if("blackCount"===i){let e=this.userIdMap.get(r);this._log.warn("".concat(e||r," black count: ").concat(o))}}}return this.worker}start(e){let{track:t,isUplink:i,room:r,userId:n,onBlack:o}=e;if(this._log.debug("start detect black video",t.id),!YP()||!o||!t||"undefined"==typeof Worker)return void this._log.warn("black video detector not supported");let s=e=>{var r,o,s,a;let c;if(i)c=null==(o=null==(r=e.msg_up_stream_info)?void 0:r.msg_video_status)?void 0:o.filter((e=>3===e.uint32_video_stream_type))[0];else{let t=null==(s=e.msg_down_stream_info)?void 0:s.filter((e=>{var t;return(null==(t=e.msg_user_info)?void 0:t.str_identifier)===n}))[0];c=null==(a=null==t?void 0:t.msg_video_status)?void 0:a.filter((e=>3===e.uint32_video_stream_type))[0]}if(c){let e=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[t.id]&&this.sleep[t.id]>0)return void(this.sleep[t.id]-=1);e>0&&e<10&&(this.sleep[t.id]=30,this._log.info("track bitrate",e,"start check"),this.checkOnce(t,3e4))}};return r.on("heartbeat-report",s),this.heartbeatListenerCleaner.set(t.id,(()=>r.off("heartbeat-report",s))),this.callbacks.set(t.id,o),this.userIdMap.set(t.id,n),t.id}checkOnce(e,t){try{let i=this.getWorker();if(!i)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:e});i.postMessage({type:"addTrack",trackId:e.id,timeout:t,readable:r.readable},[r.readable])}catch(Xk){this._log.warn("check error:",Xk),this.stop(e.id)}}stop(e){if(e){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:e}),this.callbacks.delete(e),delete this.sleep[e];let t=this.heartbeatListenerCleaner.get(e);t&&t(),this.heartbeatListenerCleaner.delete(e),this.userIdMap.delete(e)}}destroy(){this.callbacks.forEach(((e,t)=>this.stop(t))),this.worker&&(this.worker.terminate(),this.worker=null)}},hJ=class extends dJ{constructor(e){super(gb(fb({},e),{isUplink:!0})),Sb(this,"localMainAudioTrack",null),Sb(this,"localMainVideoTrack",null),Sb(this,"localAuxAudioTrack",null),Sb(this,"localAuxVideoTrack",null),Sb(this,"_isPublishingAux",!1),Sb(this,"_publishingLocalAudioTrack"),Sb(this,"_publishingLocalVideoTrack"),Sb(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),Sb(this,"_flag",0),Sb(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc:r,smallVideoRtxSsrc:n,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:o||0,auxiliaryRtx:s||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];try{if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:i}=this,r=Object.keys(t).filter((e=>{if(t[e]!==i[e]&&t[e])switch(e){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1}));if(r.length>0){if(!e)return void(this._checkPublishStateTimeoutId=ax.run("timeout",(()=>this.checkPublishState(!0)),{delay:1e4,count:1}));BP.addCount({key:521e3}),r.forEach((e=>{this._log.warn("".concat(e," publish failed during call ").concat(sM()," ").concat(tM())),BP.addEnum({key:521719,value:pJ[e]})})),ax.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(Xk){this._log.warn("checkPublishState failed",Xk)}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(fL()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(i=o[2])||!i.track),n.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((e=>{e.track&&(e.track.kind===Sk.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}get publishingState(){let{publishState:e}=this,t=fb({},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&Dk),bigVideo:!!(this.flag&Ck),smallVideo:!!(this.flag&bk),auxVideo:!!(this.flag&kk)}}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 o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}onVideoEncodeFailed(e){if(!e||!e.isMediaTrackActive)return;let{videoCodec:t,singlePC:i}=this;if(!i)return;let r={h265:{supported:i.isH264EncodeSupported,target:"h264",log:"h265 encoder not working, switch to h264"},h264:{supported:i.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working, switch to vp8"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}}[t];this._log.warn(r.log),null!=r&&r.supported&&i.switchVideoEncoder(r.target)}publish(e){return Ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e,o,s,a,c,l,d;if(!t.singlePC)return;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 Ub({code:xb.NOT_SUPPORTED_H264,message:kP({key:AP.NOT_SUPPORTED_H264ENCODE})});t.singlePC.isUsingH264&&!t.singlePC.isH264EncodeSupported&&t.singlePC.isVP8EncodeSupported&&(t._log.warn("h264 encoder not supported"),yield t.singlePC.switchVideoEncoder("vp8")),CN&&115===bO()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(Tk))),r.setProfile(Tk),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:KG,responseCommand:vG.SPC_PUBLISH_RESULT,data:gb(fb({},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,yield t.singlePC.setDegradationPreference(t._peerConnection.getSenders()[n?3:1],r.contentHint,r.streamType);let{scaleResolutionDownBy:e}=r;yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[n?3:1],e,r.streamType)}i&&(t[n?"localAuxAudioTrack":"localMainAudioTrack"]=i),yield t.singlePC.setBandwidth({audio:(null==(e=t.localMainAudioTrack)?void 0:e.profile.bitrate)||(null==(o=t.localAuxAudioTrack)?void 0:o.profile.bitrate),bigVideo:null==(s=t.localMainVideoTrack)?void 0:s.profile.bitrate,smallVideo:null==(c=null==(a=t.localMainVideoTrack)?void 0:a.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),t.sendMediaSettings(),t.installTrackMuteEvents(i,r),(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(!gL())return;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[],d=(e,t,i)=>{var r;let n=a[t].sender.replaceTrack(i);l.push(t),null!=(r=this.singlePC)&&r.enableInsertableStreams&&n.then((()=>this.createEncodedStreams(a[t].sender,e))),this.initSenderTransform(a[t].sender,e),c.push(n)};s&&d(t.mediaType,0,s),o&&d(i.mediaType,n?3:1,o),null!=i&&i.small&&c.push(this.publishSmall(this._room.videoManager.smallMode,i));let u=this.singlePC.setTransceiverDirection(Ik.SENDONLY,l);return c.push(u),Promise.all(c)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var i,r;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let n=e.createEncodedStreams(),o=new AbortController;null==(i=this.singlePC)||i.addAbortController(e,o),(null!=(r=this.getTrackByMediaType(t))&&r.enableEncodeFrame?n.readable.pipeThrough(new TransformStream({transform:(e,i)=>{var r,n;let o=this.getTrackByMediaType(t);i.enqueue((null!=(r=this.singlePC)&&r.isUsingH264||null!=(n=this.singlePC)&&n.isUsingH265)&&o?o.encodeFrame(e,8===t):e)}}),o):n.readable).pipeTo(n.writable,o).catch((e=>{this._log.debug("encoded stream error",e),"destory"!==e&&this._log.warn(e)}))}initSenderTransform(e,t){if(!(this._peerConnection&&this.singlePC&&this.singlePC.scriptTransformWorker&&kL))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 Ab(this,null,(function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()}))}publishSmall(e){return Ab(this,arguments,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.localMainVideoTrack;return function*(){var r;if(!t.singlePC)return;if("canvas"===e&&!dL())return void t._log.warn("canvas mode small stream is not supported");let n=t._peerConnection.getTransceivers(),{sender:o}=n[2],s=yield t.doPublishSmall(e,i),a="canvas"===e?524700:524701;BP.addSuccessEvent({key:a}),s?(null!=(r=t.singlePC)&&r.enableInsertableStreams&&t.createEncodedStreams(o,8),t.initSenderTransform(o,8),yield t.singlePC.setTransceiverDirection(Ik.SENDONLY,[2]),t.updateMediaSettings(),yield t.doPublishChange(),t._blackSmallVideoDetectionId=uJ.start({track:o.track,room:t._room,isUplink:!0,userId:t.userId,onBlack:()=>{t._log.warn("small video is black");let i="canvas"===e?524700:524701;BP.addFailedEvent({key:i,error:10002}),uJ.stop(t._blackSmallVideoDetectionId),t._blackSmallVideoDetectionId=void 0}})):BP.addFailedEvent({key:a,error:10001})}()}))}doPublishSmall(e){return Ab(this,arguments,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.localMainVideoTrack;return function*(){if(!t.singlePC)return null;t._log.info("publish small",e);let r=t._peerConnection.getTransceivers(),{sender:n}=r[2];if("canvas"===e&&t._room.videoManager.smallTrack)return yield n.replaceTrack(t._room.videoManager.smallTrack),"canvas";if("api"===e&&null!=i&&i.outMediaTrack&&null!=i&&i.small){yield n.replaceTrack(null==i?void 0:i.outMediaTrack);let e=n.getParameters(),r=zw(null==i?void 0:i.profile,null==i?void 0:i.small);return t._log.info("small scaleResolutionDownBy",r),e.encodings[0].scaleResolutionDownBy=r,n.setParameters(e),"api"}return t._log.warn("small track can not be enabled, smallMode: ".concat(t._room.videoManager.smallMode,", smallTrack: ").concat(!!t._room.videoManager.smallTrack,", bigVideoTrack: ").concat(!(null==i||!i.outMediaTrack))),null}()}))}unpublishSmall(){return Ab(this,null,(function*(){this.singlePC&&(this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Ik.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),uJ.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return Ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){var e;yield null==(e=t.singlePC)?void 0:e.waitForPeerConnectionConnected();let n=r&&r===t.localAuxVideoTrack||i&&i===t.localAuxAudioTrack,o=null==r?void 0:r.outMediaTrack,s=t._peerConnection.getSenders(),a=[];i&&(n?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localMainAudioTrack&&!t.localAuxAudioTrack&&(yield s[0].replaceTrack(null),a.push(0))),o&&(n?(yield s[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=gb(fb({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),a.push(3)):(yield s[1].replaceTrack(null),yield s[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=gb(fb({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),a.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.singlePC.setTransceiverDirection(Ik.INACTIVE,a),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 Ab(this,null,(function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:bG,data:t,responseCommand:vG.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:kG,commandDesc:"unpublish",responseCommand:vG.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===xb.API_CALL_TIMEOUT||e.getCode()===xb.API_CALL_ABORTED)return Promise.resolve();throw e}))}updateMediaSettings(){var e,t;this._mediaSettings.videoCodec=(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264",this._mediaSettings.videoDecCodec=(null==(t=this.singlePC)?void 0:t.downlinkVideoCodec)||"h264";let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),AL){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(),{scaleResolutionDownBy:t}=r;this._mediaSettings.videoWidth=e.width/t||0,this._mediaSettings.videoHeight=e.height/t||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(),{scaleResolutionDownBy:t}=n;this._mediaSettings.auxVideoWidth=e.width/t||0,this._mediaSettings.auxVideoHeight=e.height/t||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:GG,data:this._mediaSettings,responseCommand:vG.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return Ab(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Sk.AUXILIARY:Sk.MAIN," stream")),fL()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return Ab(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Sk.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),1===n&&null!=(i=this.localMainVideoTrack)&&i.small&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Ik.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Ik.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return Ab(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?Sk.AUXILIARY:Sk.MAIN," stream")),fL()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return Ab(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Sk.AUDIO)yield i[0].sender.replaceTrack(null);else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._room.videoManager.hasSmall&&(yield i[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(Ik.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}replaceTrack(e){return Ab(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?Sk.AUXILIARY:Sk.MAIN," stream")),r.kind===Sk.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===Sk.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0}))}setBandwidth(e){return Ab(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===Sk.AUDIO?e.audio=i:"big"===n?e.bigVideo=i:"small"===n?e.smallVideo=i:e.auxVideo=i,yield t.singlePC.setBandwidth(e)}}()}))}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:RG,responseCommand:vG.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&dM.emit(hM.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Sk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Sk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Sk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Sk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Sk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===nD?(this._log.error(RP.NOT_SUPPORTED_H264ENCODE),new Ub({code:xb.NOT_SUPPORTED_H264,message:kP({key:AP.NOT_SUPPORTED_H264ENCODE})})):new Ub({code:xb.UNKNOWN,message:kP({key:AP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:vG.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return Ab(this,null,(function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))}))}};yb([VV((function(e){let{localVideoTrack:t}=e;null==t||t.once("6",this.onVideoEncodeFailed,this)}))],hJ.prototype,"publish",1),yb([VV((function(e){let{localVideoTrack:t}=e;null==t||t.off("6",this.onVideoEncodeFailed,this)}))],hJ.prototype,"unpublish",1);var pJ=(e=>(e[e.audio=1]="audio",e[e.bigVideo=2]="bigVideo",e[e.smallVideo=3]="smallVideo",e[e.auxVideo=4]="auxVideo",e))(pJ||{}),mJ=hJ;function _J(e){return Object.keys(e).filter((t=>e[t]))}var fJ=class extends dJ{constructor(e){super(gb(fb({},e),{isUplink:!1})),Sb(this,"_flag",0),Sb(this,"isRobot",!1),Sb(this,"role","anchor"),Sb(this,"remoteAudioTrack"),Sb(this,"remoteVideoTrack"),Sb(this,"remoteAuxiliaryTrack"),Sb(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),Sb(this,"jitterBufferTimeoutId",-1),Sb(this,"_videoCodec"),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new $B(this._room,this),this.remoteVideoTrack=new eH(this._room,this),this.remoteAuxiliaryTrack=new tH(this._room,this),this.initialize()}get videoCodec(){var e;return this._videoCodec||(null==(e=this.singlePC)?void 0:e.downlinkVideoCodec)||"h264"}set videoCodec(e){this._videoCodec=e}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 Dw(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===Sk.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){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),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,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:o}=e;if(!r.id.includes(this.tinyId))return;let s=r.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(s," ").concat(n.kind));let a=Sk.AUDIO;n.kind===Sk.VIDEO&&(a=s===Sk.MAIN?Sk.VIDEO:Sk.AUXILIARY);let c=this.remoteAudioTrack;a===Sk.VIDEO?c=this.remoteVideoTrack:a===Sk.AUXILIARY&&(c=this.remoteAuxiliaryTrack),null==(t=this.singlePC)||t.receiverRemoteTrackMap.set(o,c),null!=(i=this.singlePC)&&i.scriptTransformWorker&&this.initReceiverTransform(o,s,n.kind===Sk.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(o),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,n;let o=null==(i=this.singlePC)?void 0:i.receiverRemoteTrackMap.get(e);return o&&("video"!==o.kind||null!=(r=this.singlePC)&&r.isUsingH264||null!=(n=this.singlePC)&&n.isUsingH265)?o.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 Ab(this,null,(function*(){var i,r;try{let n=!0;if(this._log.info("subscribe ".concat(t," ").concat(_J(e))),this.hasSSRC){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else{if(yield this._room.switchRoomSubedReq,null!=(i=this.singlePC)&&i.autoSubscribedUserMap.size){let e=this.singlePC.autoSubscribedUserMap.get(this.userId);if(e){this.singlePC.autoSubscribedUserMap.delete(this.userId);let t=null==(r=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))?void 0:r[e.groupIndex];t&&(this.ssrc={audio:t.audioSsrc,video:t.bigVideoSsrc,videoRtx:t.bigVideoRtxSsrc,auxiliary:t.auxVideoSsrc,auxiliaryRtx:t.auxVideoRtxSsrc},n=!1)}}yield this.doSubscribe(e,n),this.checkTrackEnded(e)}if(e.smallVideo){let{user:e,mediaTrack:t}=this.remoteVideoTrack;BP.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=uJ.start({track:t,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,e),BP.addFailedEvent({key:524702}),uJ.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})}else uJ.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}catch(Yb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Yb.message," ").concat(JSON.stringify(this.muteState))),new Ub({code:xb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Yb}}))}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"),kO&&NO<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return Ab(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=fb({},t.subscribeState);i.forEach((e=>{switch(e.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1}}));let o="subscribe_change";Object.values(n).find((e=>!0===e))||(o="unsubscribe"),t._log.info("".concat("unsubscribe"===o?o:"subscribe"," ").concat(r," [").concat(_J(n),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,n),"main"===r&&(uJ.stop(t._blackSmallVideoDetectionId),t._blackSmallVideoDetectionId=void 0),"unsubscribe"===o&&(yield t.removeDownlink())}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=wG,n=vG.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=NG,n=vG.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 Ub({code:i.code,message:kP({key:AP.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(){return Ab(this,null,(function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())}))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return Ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected();try{if(i||!e.hasSSRC){let i={audioSsrc:cJ(),bigVideoSsrc:cJ(),bigVideoRtxSsrc:cJ(),auxVideoSsrc:cJ(),auxVideoRtxSsrc:cJ()},{audioSsrc:n,bigVideoSsrc:o,bigVideoRtxSsrc:s,auxVideoSsrc:a,auxVideoRtxSsrc:c}=i;e.ssrc={audio:n,video:o,videoRtx:s,auxiliary:a,auxiliaryRtx:c},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let r=yield e._signalChannel.sendWaitForResponseWithRetry({command:qG,responseCommand:vG.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&&-10036!==r.data.code)throw new Ub({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{if(!BL)return;let{main:t,aux:i}=e._room.jitterBufferDelay||{},{jitterDelay:r=t,jitterDelayAux:n=i}=e._room.scheduleResult.config||{};(hw(r)||hw(n))&&e.setJitterBufferDelay({mainDelay:r,auxDelay:n})}}}()}))}removeDownlink(){return Ab(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(!BL||!this.singlePC||!this._peerConnection||cN(t)&&cN(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return hw(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),hw(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,cN(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||cN(t)&&e.track===this.remoteAudioTrack.outMediaTrack;if(n&&cN(i)||!n&&cN(t))return;let o=n?i||0:t,s=(e.jitterBufferTarget||0)+100;s>o||(e.jitterBufferTarget=s,this._log.debug("set ".concat(n?"aux ":"").concat(null==(r=null==e?void 0:e.track)?void 0:r.kind," jitterBuffer delay ").concat(s," -> ").concat(o)))})),!r.find((e=>{let r=e.track===this.remoteAuxiliaryTrack.outMediaTrack?i||0:t;return e.jitterBufferTarget<r})))return this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i," done")),n();this.jitterBufferTimeoutId=setTimeout((()=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:n})}),1e3)}catch(Yb){this._log.warn("set jitterBuffer delay error: ".concat(Yb)),clearTimeout(this.jitterBufferTimeoutId),n()}}get audioReceiver(){var e;return(null==(e=this.singlePC)?void 0:e.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){"h265"===this._room.downlinkVideoCodec&&this._room.requestRemoteFallbackToH264()}};yb([JV(),FV((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 Ub({code:xb.API_CALL_ABORTED,message:kP({key:AP.CONNECTION_ABORTED,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],fJ.prototype,"subscribe",1),yb([JV()],fJ.prototype,"unsubscribe",1),yb([qV((()=>"jitter"))],fJ.prototype,"setJitterBufferDelay",1);var gJ=fJ;var EJ=vb(Rb());var TJ=class e extends EJ.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,Sb(this,"log"),Sb(this,"cmdIdSeqMap",new Map),Sb(this,"messageMap",new Map),this.log=_M.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(vG.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(XG,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),jw(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 o=null==r?void 0:r.cachedMessageMap.get(n.seq+1);o&&this.emitMessage(o.message)}};Sb(TJ,"SEQ_INTERVAL",300);var vJ,yJ=TJ,{isString:SJ,isUndefined:IJ,getNetworkType:AJ,isEmpty:RJ}=Gb,CJ=class extends Fj{constructor(e){super(e),Sb(this,"_businessInfo"),Sb(this,"userManager"),Sb(this,"_version"),Sb(this,"_heartbeat",-1),Sb(this,"_lastHeartBeatTime",-1),Sb(this,"_stats"),Sb(this,"_joinTimeout",-1),Sb(this,"_firstPublishedList",null),Sb(this,"_joinReject",null),Sb(this,"_isRelayChanged",!1),Sb(this,"sdpSemantics"),Sb(this,"signalChannel",null),Sb(this,"uplinkConnection",null),Sb(this,"singlePC",null),Sb(this,"enableSPC",EL),Sb(this,"_changeBigSmallRecords",new Map),Sb(this,"networkQuality"),Sb(this,"_iceTransportPolicy"),Sb(this,"forceRelay",!1),Sb(this,"_turnServers",[]),Sb(this,"_iceServersFromJoin"),Sb(this,"_syncUserListInterval",-1),Sb(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),Sb(this,"enableSEI",!1),Sb(this,"_enableAudioVolumeEvaluation",!1),Sb(this,"_audioVolumeIntervalId",0),Sb(this,"_enableMultiAuxStream",!1),Sb(this,"_pureAudioPushMode",!1),Sb(this,"_customMessageManager"),Sb(this,"preferHW",!1),Sb(this,"healthDetector"),Sb(this,"playoutDelay"),Sb(this,"jitterBufferDelay"),Sb(this,"_updateAudioLevelTaskId",-1),Sb(this,"switchRoomSubedReq"),Sb(this,"resolveSwitchRoomSubedReq"),this._stats=new fj(this,this._log),this.userManager=new aH(this.userId,this._log),this._version=Kb,this.sdpSemantics=rD,IJ(e.sdpSemantics)?EM.isUnifiedPlanDefault()&&(this.sdpSemantics=iD):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(AJ())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!IJ(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&EL,!IJ(e.enableSPC)&&EL&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new Xj(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])))}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264"}get downlinkVideoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.downlinkVideoCodec)||"h264"}join(e,t,i){return Ab(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",(e=>{this.emit("peer-join",e)})),this.userManager.on("2",(e=>{this.closeDownLinkConnection(e,"remote user exitRoom"),this.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(e=>{var t=((e,t)=>{var i={};for(var r in e)ub.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&lb)for(var r of lb(e))t.indexOf(r)<0&&hb.call(e,r)&&(i[r]=e[r]);return i})(e,[]);dM.emit(hM.REMOTE_PUBLISH_STATE_CHANGED,fb({room:this},t)),this.emit("remote-publish-state-changed",fb({},t))})),this.joinParams=e,new Promise(((t,i)=>Ab(this,null,(function*(){var r,n;this._joinReject=i;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(o){if(!(o instanceof Ub&&o.code===xb.SPC_INITIALIZED_FAILED))return i(o);null==(r=this.signalChannel)||r.destroy(),yield this.initialize()}let s=Aw();yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),BP.addSuccessEvent({key:521708,cost:Aw()-s}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(yM){BP.addFailedEvent({key:521708,error:yM}),i(yM)}this._joinReject=null}))))}))}initSinglePC(){return Ab(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new nJ({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(zb){throw this.fallbackToMPC(),new Ub({code:xb.SPC_INITIALIZED_FAILED,message:null==zb?void 0:zb.message})}}}))}doJoin(e,t){return new Promise(((i,r)=>Ab(this,null,(function*(){var n,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(_G,(e=>{this.clearJoinTimeout(),dM.emit(hM.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)})),pw(null==(o=null==(n=this.scheduleResult)?void 0:n.config)?void 0:o.singlePC)&&EL&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);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:aM(),netType:QD(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;null!=(s=this.scheduleResult.config)&&s.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{r(new Ub({code:xb.JOIN_ROOM_FAILED,message:kP({key:AP.JOIN_ROOM_TIMEOUT})}))}),c),dM.emit(hM.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?JG:SG,a),this.signalChannel.once(vG.JOIN_ROOM_RESULT,(t=>Ab(this,null,(function*(){this.clearJoinTimeout();let{code:n,message:o,data:s,tinyId:a}=t.data;dM.emit(hM.JOIN_RECEIVED_CMD_RES,{room:this,code:n}),0===n?(this._log.info("Join room success, start heartbeat"),a&&(this.tinyId=a),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=s.publishers,this._iceServersFromJoin=s.iceServer?[s.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then((()=>{var t;null==(t=this.singlePC)||t.connect(gb(fb({},s.ability),{useVp8:s.ability.useVp8||!!e.useVp8,useH265:s.ability.useH265||!!e.useH265})).catch((()=>{}))})),i()):(this._log.error("Join room failed result: ".concat(n," error: ").concat(o)),r(new Ub({code:xb.JOIN_ROOM_FAILED,extraCode:n,message:kP({key:AP.JOIN_ROOM_FAILED,data:{error:o,code:n}})})))}))))}))))}reJoin(){return Ab(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then((t=>(e=t,t))))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(gb(fb({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),px.logSuccessEvent({userId:this.userId,eventType:Zk.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off($j.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof mJ&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on($j.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof _j&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(zb){this._log.warn("reJoin fail ".concat(zb)),this.reset(),px.logFailedEvent({userId:this.userId,eventType:Zk.REJOIN,error:zb}),this.emit("error",new Ub({code:xb.JOIN_ROOM_FAILED,message:kP({key:AP.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return Ab(this,null,(function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this.signalChannel||function(e){let t=[...ZG.values()].find((t=>t.room.userId===e&&!t.room.isJoined));return t||null}(this.userId),n=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId&&r.room===this);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):(r&&r.close(),this.signalChannel=new ej({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:t,backupUrl:i,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?e:void 0}),this._customMessageManager=new yJ(this,this.signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this.networkQuality||(this.networkQuality=new vj({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(vj.EVENT_NETWORK_QUALITY,(e=>{var t;this.emit("network-quality",e),null==(t=this.singlePC)||t.detectTCPAndUDP(e)}))),ux(this,this.signalChannel).add(hG,(e=>{dM.emit(hM.SIGNAL_CONNECTION_STATE_CHANGED,fb({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(mG,(e=>{this.reset(),this.emit("error",e)})).add(vG.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})).add(vG.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(vG.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(vG.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(px.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})})).add(vG.SEND_SWITCH_ROOM_SUBED_REQ,(e=>{if(!this.singlePC)return;let{subList:t}=e.data.data;t.forEach((e=>{this.singlePC.autoSubscribedUserMap.set(e.userId,e)})),this.resolveSwitchRoomSubedReq()})).add(vG.FALLBACK_CODEC,(e=>Ab(this,null,(function*(){var t,i,r,n,o;let s=e.data.data;this._log.warn("fallback codec enableH265Enc: ".concat(null==(t=s.videoControlInfo)?void 0:t.enableH265Enc)),0===(null==(i=s.videoControlInfo)?void 0:i.enableH265Enc)&&"h265"===(null==(r=this.singlePC)?void 0:r.videoCodec)&&(BP.addCount({key:513e3}),yield null==(n=this.singlePC)?void 0:n.switchVideoEncoder("h264"),yield null==(o=this.uplinkConnection)?void 0:o.sendMediaSettings())})))),this.signalChannel.once(uG,(e=>{this.tinyId=e.signalInfo.tinyId,dM.emit(hM.JOIN_SIGNAL_CONNECTION_END,{room:this})})),dM.emit(hM.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&dM.emit(hM.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this.signalChannel=e,e||hx(this)}leave(){return Ab(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(Xk){}this._log.info("leave() => leaving room"),dM.emit(hM.LEAVE_SEND_CMD,{room:this}),null==(e=this.signalChannel)||e.send(IG),this.switchRoomSubedReq=void 0}))}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=ax.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),ax.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return Ab(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});this.badCaseDetector.resetMonitor();let r=null!=(e=this.signalChannel)&&e.isConnected?function(e){if(iH.has(e)){let t=iH.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 iH.delete(e),t}return[]}(this.userId):[],n=gb(fb({str_sdk_version:Jb,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:fb({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:QD()},i.msg_device_info)});if(this.heartbeatReport=n,dM.emit(hM.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(AG,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",gb(fb({},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!==Mk)).map((e=>{let{userId:t,srcTinyId:i,flag:r}=e;t===this.userId&&(this.uplinkConnection&&(this.uplinkConnection.flag=r),this.localPublishFlag!==r&&(this.localPublishFlag=r,this.emit("local-publish-flag-changed",r)));let n=this.remotePublishedUserMap.get(t);return n&&this.checkSubscribeBigSmallVideo(n),{userId:t,tinyId:i,flag:r}}));e.data.mixRobotList.forEach((e=>{let{userId:i,srcTinyId:r,flag:n,mixUserList:o}=e;t.unshift({userId:i,tinyId:r,flag:n,isRobot:!0,mixUserList:o})})),e.data.fakeMixUser&&(e.data.fakeMixUser.tinyId=e.data.fakeMixUser.srcTinyId,t.push(e.data.fakeMixUser)),dM.emit(hM.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),t.find((e=>e.userId===this.userId))||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),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().catch((()=>{})),this.uplinkConnection.close(e),this.uplinkConnection instanceof _j&&(this.uplinkConnection=null)),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r,isRobot:n}=e,o=new(this.singlePC?gJ:hj)({userId:t,tinyId:i,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:n});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,t),this.emit("remote-published",o)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",(e=>{let i=e.getCode();i!==xb.ICE_TRANSPORT_ERROR&&(i===xb.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",gb(fb({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=ax.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){ax.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:HG,responseCommand:vG.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 kP({key:AP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:vG.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||!oj)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?(null==(e=this.singlePC.getPeerConnection())?void 0:e.connectionState)===Kk.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof sj&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===Kk.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return Ab(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),px.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,null==(e=this.singlePC)||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new _j({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 hj({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 Ub({code:xb.INVALID_OPERATION,message:kP({key:AP.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),ax.clearTask(this._audioVolumeIntervalId))}switchRole(e){return Ab(this,null,(function*(){this.role!==e&&("audience"===e&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))}))}doSwitchRole(e){let t={command:WG,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:vG.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 Ub({code:xb.SWITCH_ROLE_FAILED,message:kP({key:AP.SWITCH_ROLE_FAILED,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof Ub&&e.getCode()===xb.API_CALL_TIMEOUT&&(e=new Ub({code:xb.SWITCH_ROLE_FAILED,message:kP({key:AP.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e}))}publish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Ab(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof hB&&(t instanceof qB?i.audio=t:e.audio=t),t instanceof fB&&(t instanceof JB&&2===t.mediaType?i.video=t:e.video=t)}));let r=RJ(e),n=RJ(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new mJ({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new _j({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",gb(fb({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==xb.ICE_TRANSPORT_ERROR&&(t===xb.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})));let o=t.map((e=>e.kind)).join(",");r||(this._log.info("publish() => main ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:e.audio,localVideoTrack:e.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info("publish() => aux ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:i.audio,localVideoTrack:i.video,isAuxiliary:!0}),this._log.info("aux is published"))}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Ab(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let e={},i={};t.forEach((t=>{!t.mediaTrack||!t.isPublished||(t instanceof hB&&(t instanceof qB?i.audio=t:e.audio=t),t instanceof fB&&(t instanceof JB&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");RJ(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),RJ(i)||(this._log.info("unpublish() => aux ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(kM){}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&&yL()?this.uplinkConnection.replaceTrack(e).then((t=>{t&&dM.emit(hM.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return Ab(this,null,(function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return Ab(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:Sk.VIDEO,videoType:Sk.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)}))}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Ab(this,null,(function*(){if(t=t.filter((e=>!e.isSubscribed)),0===t.length)return;let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let r=t.find((e=>2===e.mediaType))?"auxiliary":"main";try{let n=fb({},i.subscribeState);t.forEach((e=>{switch(e.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0}}));let o=this._changeBigSmallRecords.get(e);o&&o.options.smallVideo&&i.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),dM.emit(hM.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(dj(n),"] prev: [").concat(dj(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());dM.emit(hM.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(Yb){let i=Yb instanceof Ub?Yb.getCode():xb.UNKNOWN,n=Yb;throw Yb instanceof Ub?i===xb.REMOTE_STREAM_NOT_EXIST&&(n=new Ub({code:xb.API_CALL_ABORTED,message:kP({key:AP.API_CALL_ABORTED,data:{message:Yb.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new Ub({code:i,message:kP({key:AP.SUBSCRIBE_FAILED,data:{message:Yb.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 Ab(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(Yb){this._log.warn("unsubscribe() => failed ".concat(Yb))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),dM.emit(hM.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 ax.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),dM.emit(hM.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&ax.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=ax.run("intervalInWorker",(()=>{var i;lV.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];null==(i=this.remotePublishedUserMap)||i.forEach((e=>{if(e.muteState.hasAudio){!lV.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,floatVolume:e.remoteAudioTrack.getInternalAudioLevel()})}})),this.emit("audio-volume",r)}),{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return Ab(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=ax.run("intervalInWorker",(()=>Ab(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack)return void this.stopUpdateAudioLevelFromSenderStat();let e=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:t}=this.uplinkConnection;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"),ax.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(!IL||!i)return;let r=null==(t=i.getSynchronizationSources()[0])?void 0:t.audioLevel;hw(r)?e.remoteAudioTrack.volume=Math.min(2*r,1):i.getStats().then((t=>{t.forEach((t=>{"inbound-rtp"===t.type&&hw(t.audioLevel)&&(e.remoteAudioTrack.volume=t.audioLevel)}))}))}getLocalAudioStats(){return Ab(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 Ab(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 Ab(this,null,(function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let i=yield this._stats.getReceiverStats(t);e.downlinksRTT[i.userId]=i.rtt}return e}))}getRemoteVideoStats(e){return Ab(this,null,(function*(){let t={};for(let[i,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 Ab(this,null,(function*(){let e={};for(let[t,i]of this.remotePublishedUserMap)i.muteState.hasAudio&&(e[t]=i.remoteAudioTrack.stat);return e}))}setTurnServer(e,t){this._log.info("set turn server: ".concat(JSON.stringify(e)," ").concat(t||""));let i=[];Array.isArray(e)?e.forEach((e=>i.push(Gb.getTurnServer(e)))):Gb.isPlainObject(e)&&i.push(Gb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:xG,data:e,timeout:5e3,responseCommand:vG.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e}))}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:VG,data:e,timeout:5e3,responseCommand:vG.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e}))}sendStartPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?OG:PG,data:e,timeout:5e3,responseCommand:t?vG.START_PUBLISH_TENCENT_CDN_RES:vG.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e}))}sendStopPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?MG:LG,data:e,timeout:5e3,responseCommand:t?vG.STOP_PUBLISH_TENCENT_CDN_RES:vG.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e}))}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:UG,data:e,timeout:5e3,responseCommand:vG.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e}))}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:FG,data:e,timeout:5e3,responseCommand:vG.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e}))}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:BG,data:e,timeout:5e3,responseCommand:vG.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e}))}sendAbilityStatus(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:zG,data:e,timeout:5e3,responseCommand:vG.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch((e=>{}))}getIceServers(e){var t,i;return this._turnServers.length>0?this._turnServers:null!=(t=this.scheduleResult.iceServers)&&t.length?this.scheduleResult.iceServers:null!=e&&e.length?e:null!=(i=this._iceServersFromJoin)&&i.length?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=Gb.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 Ab(this,null,(function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:r,hasVideo:n}}=e;if(!r&&!n||!t.video&&!t.smallVideo)return;let o=this._changeBigSmallRecords.get(i);if(!o||o.isSubscribing||o.reSubscribeCount<=0)return;let{options:s,reSubscribeCount:a}=o;if(s.video&&t.video||s.smallVideo&&t.smallVideo&&r)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:s.video,smallVideo:s.smallVideo};try{if(!r&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;o.isSubscribing=!0,o.reSubscribeCount=a-1,yield e.subscribe(c,"main"),e.remoteVideoTrack.setMediaType(c.smallVideo?8:4),this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video successfully. count ").concat(vD-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=vD}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(vD-o.reSubscribeCount,". reason: ").concat(l)),o.isSubscribing=!1,0===o.reSubscribeCount&&this._changeBigSmallRecords.delete(i)}}))}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:vD};this._changeBigSmallRecords.set(t.userId,i),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big")),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});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(SJ(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!IJ(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new Ub({code:xb.INVALID_PARAMETER,message:kP({key:AP.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(!IJ(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new Ub({code:xb.INVALID_PARAMETER,message:kP({key:AP.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!IJ(e.userDefinePushArgs)){if(!(SJ(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new Ub({code:xb.INVALID_PARAMETER,message:kP({key:AP.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}RJ(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){return Ab(this,null,(function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&bL)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 Ub({code:xb.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}switchRoom(e){return Ab(this,null,(function*(){var t;if(!this.signalChannel||!this.singlePC)return;let{roomId:i,strRoomId:r,userSig:n,privateMapKey:o}=e,s=(null==(t=this.scheduleResult.config)?void 0:t.autoSubscribeCount)||(null==e?void 0:e.autoSubscribeCount)||1,a=String(this.useStringRoomId?r:i),c=[];for(let e=0;e<s;e++)c.push({audioSsrc:cJ(),bigVideoSsrc:cJ(),bigVideoRtxSsrc:cJ(),auxVideoSsrc:cJ(),auxVideoRtxSsrc:cJ()});let l={currRoomId:this.roomId,targetRoomId:a,useStringRoomId:this.useStringRoomId,ability:this.singlePC.clientAbility,userSig:n,privateMapKey:null!=o?o:this.privateMapKey,subscribe:c};this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(a,c);let d,u=this.roomId;this.roomId=this.useStringRoomId?r:String(i),this.switchRoomSubedReq=new Promise((e=>{this.resolveSwitchRoomSubedReq=e,jw(5e3).then(e)})),dM.emit(hM.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();try{d=yield this.signalChannel.sendWaitForResponse({command:QG,responseCommand:vG.SEND_SWITCH_ROOM_RES,data:l});let{code:e,message:t}=d.data;if(0!==e){this._log.error("switch room failed. result: ".concat(e," error: ").concat(t));let i=new Ub({code:xb.SWITCH_ROOM_FAILED,extraCode:e,message:t});throw dM.emit(hM.SWITCH_ROOM_FAILED,{room:this,error:i}),i}this.userSig=n,IJ(o)||(this.privateMapKey=o),dM.emit(hM.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:u,targetRoomId:a})}catch(h){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=u,this.resolveSwitchRoomSubedReq(),h}}))}isSwitchRoomSupported(){var e;let t="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return!0!==(null==(e=this.scheduleResult.config)?void 0:e.switchRoom)?(this._log.warn("".concat(t," Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.")),!1):"live"!==this.scene?(this._log.warn("".concat(t," Reason: the scene is not 'live'.")),!1):"audience"!==this.role?(this._log.warn("".concat(t," Reason: the role is not 'audience'.")),!1):!!this.singlePC||(this._log.warn("".concat(t," Reason: is not using single peerConnection.")),!1)}requestRemoteFallbackToH264(){var e;null==(e=this.singlePC)||e.requestRemoteFallbackToH264()}};return yb([ZL(["left",tx.INIT],"joined"),_x({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"),YH(!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())}}),FV((e=>{let t=new cG;return function(i,r,n){return Ab(this,null,(function*(){let o=String(i.roomId||i.strRoomId);if(this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.userSig=i.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,i.privateMapKey=i.privateMapKey||"",this.isJoined)throw new Ub({code:xb.INVALID_OPERATION,message:kP({key:AP.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new Ub({code:xb.INVALID_OPERATION,message:kP({key:AP.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:o}),this.role=21===i.role?"audience":"anchor",this._log.info("Join() => joining room: ".concat(o," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),dM.emit(hM.JOIN_START,{room:this,roomId:o,params:i});let s=Gb.getEnv();s||(s=uk.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Ak.OLD_CLOUD_LADDER)?s=uk.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Ak.WEBRTC)&&(s=uk.WEBRTC))),px.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),EM.checkSystemRequirementsInternal(n).then((e=>{this.checkSystemResult=e,lG.call(this)}));try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Gb.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=Gb.performanceNow(),dM.emit(hM.JOIN_SUCCESS,{room:this}),30===n&&!i.component&&px.uploadEvent({log:"stat-conv-".concat(Number(KO),"-").concat(location.hostname),userId:this.userId}),t}catch(RM){throw t.delete({room:this,roomId:o}),dM.emit(hM.JOIN_FAILED,{room:this,error:RM}),RM}}))}}))],CJ.prototype,"join",1),yb([ZL("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),FV((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Ab(this,null,(function*(){dM.emit(hM.LEAVE_START,{room:this}),yield e.call(this,...i),dM.emit(hM.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),KV("leave room"),fx({fnName:"publish",validateArgs:!1}),fx({fnName:"unsubscribe",validateArgs:!1})],CJ.prototype,"leave",1),yb([JV(),FV((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Ab(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"ready"===e.state)),!i.length))return;dM.emit("61",{room:this});let t=e.apply(this,i);return Promise.all(i.map((e=>e.publish(this,t))))}))})),_x({settings:{retries:Yk,timeout:e=>aw(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),dM.emit(hM.PUBLISH_FAILED,{room:this}))}})],CJ.prototype,"publish",1),yb([fx({fnName:"publish"}),(vJ="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=GV.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 Ub({code:xb.API_CALL_ABORTED,message:vJ})),!1)}));n.queue=e}return r.apply(this,t)},i}),JV(),FV((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})),VV((function(){var e,t;0===this.localTracks.size&&_L()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((e=>e.track&&e.replaceTrack(null))))}))],CJ.prototype,"unpublish",1),yb([UV((e=>{if(e.code!==xb.API_CALL_ABORTED)throw e})),qV((e=>e.userId))],CJ.prototype,"replaceTrack",1),yb([qV((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),XB(),FV((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})),_x({settings:{retries:Yk,timeout:e=>aw(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),dM.emit(hM.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],CJ.prototype,"subscribe",1),yb([fx({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")}))}}),qV((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],CJ.prototype,"unsubscribe",1),aG.create=aG._create.bind(aG,CJ),UL(30),aG}));
|