trtc-sdk-v5 5.15.1-beta.7 → 5.15.1-wasm.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/av_processing.wasm +0 -0
- package/assets/debug-dialog.js +1 -1
- package/assets/worker.js +17 -0
- package/index.d.ts +5 -6
- package/package.json +4 -6
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/chorus/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/package.json +1 -1
- package/plugins/lebplayer/package.json +1 -1
- package/plugins/realtime-transcriber/package.json +1 -1
- package/plugins/small-stream-auto-switcher/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/face-detection/package.json +1 -1
- package/plugins/video-effect/video-mixer/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +69 -41
- 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,N=Object,w=I("".split),P=k(function(){return!N("z").propertyIsEnumerable(0)})?function(e){return"String"===D(e)?w(e,""):N(e)}:N,O=function(e){return null==e},M=O,L=TypeError,x=function(e){if(M(e))throw new L("Can't call method on "+e);return e},U=P,V=x,F=function(e){return U(V(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,z=H,J=function(e,t){return arguments.length<2?(i=j[e],z(i)?i:void 0):j[e]&&j[e][t];var i},K=I({}.isPrototypeOf),q=n.navigator,Y=q&&q.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=J,de=H,ue=K,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=O,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,Ne=function(e,t){try{De(ke,e,{value:t,configurable:!0,writable:!0})}catch(i){ke[e]=t}return t},we=n,Pe=Ne,Oe="__core-js_shared__",Me=be.exports=we[Oe]||Pe(Oe,{});(Me.versions||(Me.versions=[])).push({version:"3.47.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru), 2025 CoreJS Company (core-js.io)",license:"https://github.com/zloirock/core-js/blob/v3.47.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Le=be.exports,xe=Le,Ue=function(e,t){return xe[e]||(xe[e]=t||{})},Ve=x,Fe=Object,Be=function(e){return Fe(Ve(e))},He=Be,We=I({}.hasOwnProperty),Ge=Object.hasOwn||function(e,t){return We(He(e),t)},je=I,ze=0,Je=Math.random(),Ke=je(1.1.toString),qe=function(e){return"Symbol("+(void 0===e?"":e)+")_"+Ke(++ze+Je,36)},Ye=Ue,Xe=Ge,Qe=qe,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 Nt={},wt=a&&s(function(){return 42!==Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype}),Pt=G,Ot=String,Mt=TypeError,Lt=function(e){if(Pt(e))return e;throw new Mt(Ot(e)+" is not an object")},xt=a,Ut=vt,Vt=wt,Ft=Lt,Bt=mt,Ht=TypeError,Wt=Object.defineProperty,Gt=Object.getOwnPropertyDescriptor,jt="enumerable",zt="configurable",Jt="writable";Nt.f=xt?Vt?function(e,t,i){if(Ft(e),t=Bt(t),Ft(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Jt in i&&!i[Jt]){var r=Gt(e,t);r&&r[Jt]&&(e[t]=i.value,i={configurable:zt in i?i[zt]:r[zt],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),Ut)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 Kt=Nt,qt=E,Yt=a?function(e,t,i){return Kt.f(e,t,qt(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=qe,mi=Ue("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 Ni={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}}},wi=I,Pi=s,Oi=H,Mi=Ge,Li=a,xi=ii.CONFIGURABLE,Ui=li,Vi=Ni.enforce,Fi=Ni.get,Bi=String,Hi=Object.defineProperty,Wi=wi("".slice),Gi=wi("".replace),ji=wi([].join),zi=Li&&!Pi(function(){return 8!==Hi(function(){},"length",{value:8}).length}),Ji=String(String).split("String"),Ki=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),(!Mi(e,"name")||xi&&e.name!==t)&&(Li?Hi(e,"name",{value:t,configurable:!0}):e.name=t),zi&&i&&Mi(i,"arity")&&e.length!==i.arity&&Hi(e,"length",{value:i.arity});try{i&&Mi(i,"constructor")&&i.constructor?Li&&Hi(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var r=Vi(e);return Mi(r,"source")||(r.source=ji(Ji,"string"==typeof t?t:"")),e};Function.prototype.toString=Ki(function(){return Oi(this)&&Fi(this).source||Ui(this)},"toString");var qi=Xt.exports,Yi=H,Xi=Nt,Qi=qi,Zi=Ne,$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 Nr=J,wr=er,Pr=Dr,Or=Lt,Mr=I([].concat),Lr=Nr("Reflect","ownKeys")||function(e){var t=wr.f(Or(e)),i=Pr.f;return i?Mr(t,i(e)):t},xr=Ge,Ur=Lr,Vr=o,Fr=Nt,Br=function(e,t,i){for(var r=Ur(t),n=Fr.f,o=Vr.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=Jr[zr(e)];return i===qr||i!==Kr&&(Wr(t)?Hr(t):!!t)},zr=jr.normalize=function(e){return String(e).replace(Gr,".").toLowerCase()},Jr=jr.data={},Kr=jr.NATIVE="N",qr=jr.POLYFILL="P",Yr=jr,Xr=n,Qr=o.f,Zr=Yt,$r=$i,en=Ne,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=qi,gn=Nt,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=K,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 Nn={},wn=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&&(Nn[t]=!0),t};bn(wn,kn),wn.prototype=Dn,Dn.constructor=wn;var Pn="Symbol(description detection)"===String(kn("description detection")),On=yn(Dn.valueOf),Mn=yn(Dn.toString),Ln=/^Symbol\((.*)\)[^)]+$/,xn=yn("".replace),Un=yn("".slice);Cn(Dn,"description",{configurable:!0,get:function(){var e=On(this);if(Sn(Nn,e))return"";var t=Mn(e),i=Pn?Un(t,7,-1):xn(t,Ln,"$1");return""===i?void 0:i}}),Tn({global:!0,constructor:!0,forced:!0},{Symbol:wn})}var Vn={},Fn=Rr,Bn=Cr,Hn=Object.keys||function(e){return Fn(e,Bn)},Wn=a,Gn=wt,jn=Nt,zn=Lt,Jn=F,Kn=Hn;Vn.f=Wn&&!Gn?Object.defineProperties:function(e,t){zn(e);for(var i,r=Jn(t),n=Kn(t),o=n.length,s=0;o>s;)jn.f(e,i=n[s++],r[i]);return e};var qn,Yn=J("document","documentElement"),Xn=Lt,Qn=Vn,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{qn=new ActiveXObject("htmlfile")}catch(n){}var e,t,i;co="undefined"!=typeof document?document.domain&&qn?ao(qn):(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(qn);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=Nt.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,No=Do.prototype,wo=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?No:null},Po=s,Oo=H,Mo=G,Lo=wo,xo=$i,Uo=rt("iterator"),Vo=!1;[].keys&&("next"in(yo=[].keys())?(vo=Lo(Lo(yo)))!==Object.prototype&&(To=vo):Vo=!0);var Fo=!Mo(To)||Po(function(){var e={};return To[Uo].call(e)!==e});Fo&&(To={}),Oo(To[Uo])||xo(To,Uo,function(){return this});var Bo={IteratorPrototype:To,BUGGY_SAFARI_ITERATORS:Vo},Ho=Nt.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})},zo=Bo.IteratorPrototype,Jo=lo,Ko=E,qo=jo,Yo=So,Xo=function(){return this},Qo=function(e,t,i,r){var n=t+" Iterator";return e.prototype=Jo(zo,{next:Ko(+!r,i)}),qo(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=wo,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}},Ns=F,ws=fo,Ps=So,Os=Ni,Ms=Nt.f,Ls=ks,xs=Ds,Us=a,Vs="Array Iterator",Fs=Os.set,Bs=Os.getterFor(Vs),Hs=Ls(Array,"Array",function(e,t){Fs(this,{type:Vs,target:Ns(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=Ps.Arguments=Ps.Array;if(ws("keys"),ws("values"),ws("entries"),Us&&"values"!==Ws.name)try{Ms(Ws,"name",{value:"values"})}catch(XJ){}var Gs=Te,js=Be,zs=P,Js=mr,Ks=TypeError,qs="Reduce of empty array with no initial value",Ys=function(e){return function(t,i,r,n){var o=js(t),s=zs(o),a=Js(o);if(Gs(i),0===a&&r<2)throw new Ks(qs);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 Ks(qs)}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,Na=function(e,t){if(!delete e[t])throw new ma("Cannot delete property "+pa(t)+" of "+pa(e))},wa=_n,Pa=s,Oa=Ta,Ma=Zs,La=ya,xa=Sa,Ua=re,Va=Aa,Fa=[],Ba=Ca(Fa.sort),Ha=Ca(Fa.push),Wa=Pa(function(){Fa.sort(void 0)}),Ga=Pa(function(){Fa.sort(null)}),ja=Ma("sort"),za=!Pa(function(){if(Ua)return Ua<70;if(!(La&&La>3)){if(xa)return!0;if(Va)return Va<603;var e,t,i,r,n="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(r=0;r<47;r++)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||!za},{sort:function(e){void 0!==e&&ba(e);var t=ka(this);if(za)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(Oa(n,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:wa(t)>wa(i)?1:-1}}(e)),i=Da(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)Na(t,r++);return t}});var Ja="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,Ka=$i,qa=function(e,t,i){for(var r in t)Ka(e,r,t[r],i);return e},Ya=K,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=Ja,kc=Yt,Dc=En,Nc=qa,wc=s,Pc=Qa,Oc=or,Mc=hr,Lc=tc,xc=cc,Uc=_c,Vc=wo,Fc=cs,Bc=Tc,Hc=_a,Wc=Ic,Gc=Br,jc=jo,zc=Ni,Jc=ii.PROPER,Kc=ii.CONFIGURABLE,qc="ArrayBuffer",Yc="DataView",Xc="prototype",Qc="Wrong index",Zc=zc.getterFor(qc),$c=zc.getterFor(Yc),el=zc.set,tl=Ac[qc],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=Uc.pack,hl=Uc.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=Jc&&tl.name!==qc;wc(function(){tl(1)})&&wc(function(){new tl(-1)})&&!wc(function(){return new tl,new tl(1.5),new tl(NaN),1!==tl.length||Sl&&!Kc})?Sl&&Kc&&kc(tl,"name",qc):((il=function(e){return Pc(this,rl),Wc(new tl(Lc(e)),this,il)})[Xc]=rl,rl.constructor=il,Gc(il,tl)),Fc&&Vc(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)||Nc(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){Pc(this,rl);var t=Lc(e);el(this,{type:qc,bytes:ll(al(t),0),byteLength:t}),Cc||(this.byteLength=t,this.detached=!1)})[Xc],ol=(nl=function(e,t,i){Pc(this,ol),Pc(e,rl);var r=Zc(e),n=r.byteLength,o=Oc(t);if(o<0||o>n)throw new cl("Wrong offset");if(o+(i=void 0===i?n-o:Mc(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)),Nc(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,qc),jc(nl,Yc);var Rl={ArrayBuffer:il,DataView:nl},Cl=J,bl=En,kl=a,Dl=rt("species"),Nl=function(e){var t=Cl(e);kl&&t&&!t[Dl]&&bl(t,Dl,{configurable:!0,get:function(){return this}})},wl=Nl,Pl="ArrayBuffer",Ol=Rl[Pl];nn({global:!0,constructor:!0,forced:n[Pl]!==Ol},{ArrayBuffer:Ol}),wl(Pl);var Ml=b,Ll=I,xl=function(e){if("Function"===Ml(e))return Ll(e)},Ul=nn,Vl=xl,Fl=s,Bl=Lt,Hl=lr,Wl=hr,Gl=Rl.ArrayBuffer,jl=Rl.DataView,zl=jl.prototype,Jl=Vl(Gl.prototype.slice),Kl=Vl(zl.getUint8),ql=Vl(zl.setUint8);Ul({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:Fl(function(){return!new Gl(2).slice(1,void 0).byteLength})},{slice:function(e,t){if(Jl&&void 0===t)return Jl(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;)ql(a,c++,Kl(s,r++));return o}});var Yl=n,Xl=I,Ql=s,Zl=H,$l=hn,ed=li,td=function(){},id=J("Reflect","construct"),rd=/^\s*(?:class|function)\b/,nd=Xl(rd.exec),od=!rd.test(td),sd=function(e){if(!Zl(e))return!1;try{return id(td,[],e),!0}catch(XJ){return!1}},ad=function(e){if(!Zl(e))return!1;switch($l(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return od||!!nd(rd,ed(e))}catch(XJ){return!0}};ad.sham=!0;var cd,ld,dd,ud,hd=!id||Ql(function(){var e;return sd(sd.call)||!sd(Object)||!sd(function(){e=!0})||e})?ad:sd,pd=hd,md=_e,_d=TypeError,fd=function(e){if(pd(e))return e;throw new _d(md(e)+" is not a constructor")},gd=Lt,Ed=fd,Td=O,vd=rt("species"),yd=function(e,t){var i,r=gd(e).constructor;return void 0===r||Td(i=gd(r)[vd])?t:Ed(i)},Sd=c,Id=Function.prototype,Ad=Id.apply,Rd=Id.call,Cd="object"==typeof Reflect&&Reflect.apply||(Sd?Rd.bind(Ad):function(){return Rd.apply(Ad,arguments)}),bd=Te,kd=c,Dd=xl(xl.bind),Nd=function(e,t){return bd(e),void 0===t?e:kd?Dd(e,t):function(){return e.apply(t,arguments)}},wd=TypeError,Pd=function(e,t){if(e<t)throw new wd("Not enough arguments");return e},Od=/(?:ipad|iphone|ipod).*applewebkit/i.test(X),Md=n,Ld=Cd,xd=Nd,Ud=H,Vd=Ge,Fd=s,Bd=Yn,Hd=_a,Wd=Et,Gd=Pd,jd=Od,zd=na,Jd=Md.setImmediate,Kd=Md.clearImmediate,qd=Md.process,Yd=Md.Dispatch,Xd=Md.Function,Qd=Md.MessageChannel,Zd=Md.String,$d=0,eu={},tu="onreadystatechange";Fd(function(){cd=Md.location});var iu=function(e){if(Vd(eu,e)){var t=eu[e];delete eu[e],t()}},ru=function(e){return function(){iu(e)}},nu=function(e){iu(e.data)},ou=function(e){Md.postMessage(Zd(e),cd.protocol+"//"+cd.host)};Jd&&Kd||(Jd=function(e){Gd(arguments.length,1);var t=Ud(e)?e:Xd(e),i=Hd(arguments,1);return eu[++$d]=function(){Ld(t,void 0,i)},ld($d),$d},Kd=function(e){delete eu[e]},zd?ld=function(e){qd.nextTick(ru(e))}:Yd&&Yd.now?ld=function(e){Yd.now(ru(e))}:Qd&&!jd?(ud=(dd=new Qd).port2,dd.port1.onmessage=nu,ld=xd(ud.postMessage,ud)):Md.addEventListener&&Ud(Md.postMessage)&&!Md.importScripts&&cd&&"file:"!==cd.protocol&&!Fd(ou)?(ld=ou,Md.addEventListener("message",nu,!1)):ld=tu in Wd("script")?function(e){Bd.appendChild(Wd("script"))[tu]=function(){Bd.removeChild(this),iu(e)}}:function(e){setTimeout(ru(e),0)});var su={set:Jd,clear:Kd},au=n,cu=a,lu=Object.getOwnPropertyDescriptor,du=function(e){if(!cu)return au[e];var t=lu(au,e);return t&&t.value},uu=function(){this.head=null,this.tail=null};uu.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 hu,pu,mu,_u,fu,gu=uu,Eu=/ipad|iphone|ipod/i.test(X)&&"undefined"!=typeof Pebble,Tu=/web0s(?!.*chrome)/i.test(X),vu=n,yu=du,Su=Nd,Iu=su.set,Au=gu,Ru=Od,Cu=Eu,bu=Tu,ku=na,Du=vu.MutationObserver||vu.WebKitMutationObserver,Nu=vu.document,wu=vu.process,Pu=vu.Promise,Ou=yu("queueMicrotask");if(!Ou){var Mu=new Au,Lu=function(){var e,t;for(ku&&(e=wu.domain)&&e.exit();t=Mu.get();)try{t()}catch(XJ){throw Mu.head&&hu(),XJ}e&&e.enter()};Ru||ku||bu||!Du||!Nu?!Cu&&Pu&&Pu.resolve?((_u=Pu.resolve(void 0)).constructor=Pu,fu=Su(_u.then,_u),hu=function(){fu(Lu)}):ku?hu=function(){wu.nextTick(Lu)}:(Iu=Su(Iu,vu),hu=function(){Iu(Lu)}):(pu=!0,mu=Nu.createTextNode(""),new Du(Lu).observe(mu,{characterData:!0}),hu=function(){mu.data=pu=!pu}),Ou=function(e){Mu.head||hu(),Mu.add(e)}}var xu=Ou,Uu=function(e){try{return{error:!1,value:e()}}catch(XJ){return{error:!0,value:XJ}}},Vu=n.Promise,Fu=n,Bu=Vu,Hu=H,Wu=Yr,Gu=li,ju=rt,zu=ra,Ju=re;Bu&&Bu.prototype;var Ku=ju("species"),qu=!1,Yu=Hu(Fu.PromiseRejectionEvent),Xu=Wu("Promise",function(){var e=Gu(Bu),t=e!==String(Bu);if(!t&&66===Ju)return!0;if(!Ju||Ju<51||!/native code/.test(e)){var i=new Bu(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"!==zu&&"DENO"!==zu||Yu)}),Qu={CONSTRUCTOR:Xu,REJECTION_EVENT:Yu,SUBCLASSING:qu},Zu={},$u=Te,eh=TypeError,th=function(e){var t,i;this.promise=new e(function(e,r){if(void 0!==t||void 0!==i)throw new eh("Bad Promise constructor");t=e,i=r}),this.resolve=$u(t),this.reject=$u(i)};Zu.f=function(e){return new th(e)};var ih,rh,nh,oh,sh=nn,ah=na,ch=n,lh=Yl,dh=u,uh=$i,hh=cs,ph=jo,mh=Nl,_h=Te,fh=H,gh=G,Eh=Qa,Th=yd,vh=su.set,yh=xu,Sh=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(XJ){}},Ih=Uu,Ah=gu,Rh=Ni,Ch=Vu,bh=Zu,kh="Promise",Dh=Qu.CONSTRUCTOR,Nh=Qu.REJECTION_EVENT,wh=Qu.SUBCLASSING,Ph=Rh.getterFor(kh),Oh=Rh.set,Mh=Ch&&Ch.prototype,Lh=Ch,xh=Mh,Uh=ch.TypeError,Vh=ch.document,Fh=ch.process,Bh=bh.f,Hh=Bh,Wh=!!(Vh&&Vh.createEvent&&ch.dispatchEvent),Gh="unhandledrejection",jh=function(e){var t;return!(!gh(e)||!fh(t=e.then))&&t},zh=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&&Xh(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),n=!0)),i===e.promise?l(new Uh("Promise-chain cycle")):(r=jh(i))?dh(r,i,c,l):c(i)):l(o)}catch(XJ){d&&!n&&d.exit(),l(XJ)}},Jh=function(e,t){e.notified||(e.notified=!0,yh(function(){for(var i,r=e.reactions;i=r.get();)zh(i,e);e.notified=!1,t&&!e.rejection&&qh(e)}))},Kh=function(e,t,i){var r,n;Wh?((r=Vh.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),ch.dispatchEvent(r)):r={promise:t,reason:i},!Nh&&(n=ch["on"+e])?n(r):e===Gh&&Sh("Unhandled promise rejection",i)},qh=function(e){dh(vh,ch,function(){var t,i=e.facade,r=e.value;if(Yh(e)&&(t=Ih(function(){ah?Fh.emit("unhandledRejection",r,i):Kh(Gh,i,r)}),e.rejection=ah||Yh(e)?2:1,t.error))throw t.value})},Yh=function(e){return 1!==e.rejection&&!e.parent},Xh=function(e){dh(vh,ch,function(){var t=e.facade;ah?Fh.emit("rejectionHandled",t):Kh("rejectionhandled",t,e.value)})},Qh=function(e,t,i){return function(r){e(t,r,i)}},Zh=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Jh(e,!0))},$h=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new Uh("Promise can't be resolved itself");var r=jh(t);r?yh(function(){var i={done:!1};try{dh(r,t,Qh($h,i,e),Qh(Zh,i,e))}catch(XJ){Zh(i,XJ,e)}}):(e.value=t,e.state=1,Jh(e,!1))}catch(XJ){Zh({done:!1},XJ,e)}}};if(Dh&&(xh=(Lh=function(e){Eh(this,xh),_h(e),dh(ih,this);var t=Ph(this);try{e(Qh($h,t),Qh(Zh,t))}catch(XJ){Zh(t,XJ)}}).prototype,(ih=function(e){Oh(this,{type:kh,done:!1,notified:!1,parent:!1,reactions:new Ah,rejection:!1,state:0,value:null})}).prototype=uh(xh,"then",function(e,t){var i=Ph(this),r=Bh(Th(this,Lh));return i.parent=!0,r.ok=!fh(e)||e,r.fail=fh(t)&&t,r.domain=ah?Fh.domain:void 0,0===i.state?i.reactions.add(r):yh(function(){zh(r,i)}),r.promise}),rh=function(){var e=new ih,t=Ph(e);this.promise=e,this.resolve=Qh($h,t),this.reject=Qh(Zh,t)},bh.f=Bh=function(e){return e===Lh||e===nh?new rh(e):Hh(e)},fh(Ch)&&Mh!==Object.prototype)){oh=Mh.then,wh||uh(Mh,"then",function(e,t){var i=this;return new Lh(function(e,t){dh(oh,i,e,t)}).then(e,t)},{unsafe:!0});try{delete Mh.constructor}catch(XJ){}hh&&hh(Mh,xh)}sh({global:!0,constructor:!0,wrap:!0,forced:Dh},{Promise:Lh}),nh=lh.Promise,ph(Lh,kh,!1),mh(kh);var ep=So,tp=rt("iterator"),ip=Array.prototype,rp=function(e){return void 0!==e&&(ep.Array===e||ip[tp]===e)},np=hn,op=Se,sp=O,ap=So,cp=rt("iterator"),lp=function(e){if(!sp(e))return op(e,cp)||op(e,"@@iterator")||ap[np(e)]},dp=u,up=Te,hp=Lt,pp=_e,mp=lp,_p=TypeError,fp=function(e,t){var i=arguments.length<2?mp(e):t;if(up(i))return hp(dp(i,e));throw new _p(pp(e)+" is not iterable")},gp=u,Ep=Lt,Tp=Se,vp=function(e,t,i){var r,n;Ep(e);try{if(!(r=Tp(e,"return"))){if("throw"===t)throw i;return i}r=gp(r,e)}catch(XJ){n=!0,r=XJ}if("throw"===t)throw i;if(n)throw r;return Ep(r),i},yp=Nd,Sp=u,Ip=Lt,Ap=_e,Rp=rp,Cp=mr,bp=K,kp=fp,Dp=lp,Np=vp,wp=TypeError,Pp=function(e,t){this.stopped=e,this.result=t},Op=Pp.prototype,Mp=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),_=yp(t,d),f=function(e){return r&&Np(r,"normal"),new Pp(!0,e)},g=function(e){return u?(Ip(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=Dp(e)))throw new wp(Ap(e)+" is not iterable");if(Rp(n)){for(o=0,s=Cp(e);s>o;o++)if((a=g(e[o]))&&bp(Op,a))return a;return new Pp(!1)}r=kp(e,n)}for(c=h?e.next:r.next;!(l=Sp(c,r)).done;){try{a=g(l.value)}catch(XJ){Np(r,"throw",XJ)}if("object"==typeof a&&a&&bp(Op,a))return a}return new Pp(!1)},Lp=rt("iterator"),xp=!1;try{var Up=0,Vp={next:function(){return{done:!!Up++}},return:function(){xp=!0}};Vp[Lp]=function(){return this},Array.from(Vp,function(){throw 2})}catch(XJ){}var Fp=function(e,t){try{if(!t&&!xp)return!1}catch(XJ){return!1}var i=!1;try{var r={};r[Lp]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(XJ){}return i},Bp=Vu,Hp=Qu.CONSTRUCTOR||!Fp(function(e){Bp.all(e).then(void 0,function(){})}),Wp=u,Gp=Te,jp=Zu,zp=Uu,Jp=Mp;nn({target:"Promise",stat:!0,forced:Hp},{all:function(e){var t=this,i=jp.f(t),r=i.resolve,n=i.reject,o=zp(function(){var i=Gp(t.resolve),o=[],s=0,a=1;Jp(e,function(e){var c=s++,l=!1;a++,Wp(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 Kp=nn,qp=Qu.CONSTRUCTOR,Yp=Vu,Xp=J,Qp=H,Zp=$i,$p=Yp&&Yp.prototype;if(Kp({target:"Promise",proto:!0,forced:qp,real:!0},{catch:function(e){return this.then(void 0,e)}}),Qp(Yp)){var em=Xp("Promise").prototype.catch;$p.catch!==em&&Zp($p,"catch",em,{unsafe:!0})}var tm=u,im=Te,rm=Zu,nm=Uu,om=Mp;nn({target:"Promise",stat:!0,forced:Hp},{race:function(e){var t=this,i=rm.f(t),r=i.reject,n=nm(function(){var n=im(t.resolve);om(e,function(e){tm(n,t,e).then(i.resolve,r)})});return n.error&&r(n.value),i.promise}});var sm=Zu;nn({target:"Promise",stat:!0,forced:Qu.CONSTRUCTOR},{reject:function(e){var t=sm.f(this);return(0,t.reject)(e),t.promise}});var am=Lt,cm=G,lm=Zu,dm=function(e,t){if(am(e),cm(t)&&t.constructor===e)return t;var i=lm.f(e);return(0,i.resolve)(t),i.promise},um=nn,hm=Qu.CONSTRUCTOR,pm=dm;J("Promise"),um({target:"Promise",stat:!0,forced:hm},{resolve:function(e){return pm(this,e)}});var mm=nn,_m=Vu,fm=s,gm=J,Em=H,Tm=yd,vm=dm,ym=$i,Sm=_m&&_m.prototype;if(mm({target:"Promise",proto:!0,real:!0,forced:!!_m&&fm(function(){Sm.finally.call({then:function(){}},function(){})})},{finally:function(e){var t=Tm(this,gm("Promise")),i=Em(e);return this.then(i?function(i){return vm(t,e()).then(function(){return i})}:e,i?function(i){return vm(t,e()).then(function(){throw i})}:e)}}),Em(_m)){var Im=gm("Promise").prototype.finally;Sm.finally!==Im&&ym(Sm,"finally",Im,{unsafe:!0})}var Am=G,Rm=b,Cm=rt("match"),bm=function(e){var t;return Am(e)&&(void 0!==(t=e[Cm])?!!t:"RegExp"===Rm(e))},km=s,Dm=n.RegExp,Nm=!km(function(){var e=!0;try{Dm(".","d")}catch(XJ){e=!1}var t={},i="",r=e?"dgimsy":"gimsy",n=function(e,r){Object.defineProperty(t,e,{get:function(){return i+=r,!0}})},o={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var s in e&&(o.hasIndices="d"),o)n(s,o[s]);return Object.getOwnPropertyDescriptor(Dm.prototype,"flags").get.call(t)!==r||i!==r}),wm=Lt,Pm=function(){var e=wm(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},Om=u,Mm=Ge,Lm=K,xm={correct:Nm},Um=Pm,Vm=RegExp.prototype,Fm=xm.correct?function(e){return e.flags}:function(e){return xm.correct||!Lm(Vm,e)||Mm(e,"flags")?e.flags:Om(Um,e)},Bm=s,Hm=n.RegExp,Wm=Bm(function(){var e=Hm("a","y");return e.lastIndex=2,null!==e.exec("abcd")}),Gm=Wm||Bm(function(){return!Hm("a","y").sticky}),jm=Wm||Bm(function(){var e=Hm("^r","gy");return e.lastIndex=2,null!==e.exec("str")}),zm={BROKEN_CARET:jm,MISSED_STICKY:Gm,UNSUPPORTED_Y:Wm},Jm=Nt.f,Km=s,qm=n.RegExp,Ym=Km(function(){var e=qm(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)}),Xm=s,Qm=n.RegExp,Zm=Xm(function(){var e=Qm("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")}),$m=a,e_=n,t_=I,i_=Yr,r_=Ic,n_=Yt,o_=lo,s_=er.f,a_=K,c_=bm,l_=_n,d_=Fm,u_=zm,h_=function(e,t,i){i in e||Jm(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},p_=$i,m_=s,__=Ge,f_=Ni.enforce,g_=Nl,E_=Ym,T_=Zm,v_=rt("match"),y_=e_.RegExp,S_=y_.prototype,I_=e_.SyntaxError,A_=t_(S_.exec),R_=t_("".charAt),C_=t_("".replace),b_=t_("".indexOf),k_=t_("".slice),D_=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,N_=/a/g,w_=/a/g,P_=new y_(N_)!==N_,O_=u_.MISSED_STICKY,M_=u_.UNSUPPORTED_Y,L_=$m&&(!P_||O_||E_||T_||m_(function(){return w_[v_]=!1,y_(N_)!==N_||y_(w_)===w_||"/a/i"!==String(y_(N_,"i"))}));if(i_("RegExp",L_)){for(var x_=function(e,t){var i,r,n,o,s,a,c=a_(S_,this),l=c_(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===x_)return e;if((l||a_(S_,e))&&(e=e.source,d&&(t=d_(h))),e=void 0===e?"":l_(e),t=void 0===t?"":l_(t),h=e,E_&&"dotAll"in N_&&(r=!!t&&b_(t,"s")>-1)&&(t=C_(t,/s/g,"")),i=t,O_&&"sticky"in N_&&(n=!!t&&b_(t,"y")>-1)&&M_&&(t=C_(t,/y/g,"")),T_&&(o=function(e){for(var t,i=e.length,r=0,n="",o=[],s=o_(null),a=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=R_(e,r)))t+=R_(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:if(n+=t,"?:"===k_(e,r+1,r+3))continue;A_(D_,k_(e,r+1))&&(r+=2,c=!0),l++;continue;case">"===t&&c:if(""===d||__(s,d))throw new I_("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=r_(y_(e,t),c?this:S_,x_),(r||n||u.length)&&(a=f_(s),r&&(a.dotAll=!0,a.raw=x_(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=R_(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+R_(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{n_(s,"source",""===h?"(?:)":h)}catch(XJ){}return s},U_=s_(y_),V_=0;U_.length>V_;)h_(x_,y_,U_[V_++]);S_.constructor=x_,x_.prototype=S_,p_(e_,"RegExp",x_,{constructor:!0})}g_("RegExp");var F_=u,B_=I,H_=_n,W_=Pm,G_=zm,j_=lo,z_=Ni.get,J_=Ym,K_=Zm,q_=Ue("native-string-replace",String.prototype.replace),Y_=RegExp.prototype.exec,X_=Y_,Q_=B_("".charAt),Z_=B_("".indexOf),$_=B_("".replace),ef=B_("".slice),tf=function(){var e=/a/,t=/b*/g;return F_(Y_,e,"a"),F_(Y_,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),rf=G_.BROKEN_CARET,nf=void 0!==/()??/.exec("")[1];(tf||nf||rf||J_||K_)&&(X_=function(e){var t,i,r,n,o,s,a,c=this,l=z_(c),d=H_(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=F_(X_,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=rf&&c.sticky,m=F_(W_,c),_=c.source,f=0,g=d;if(p&&(m=$_(m,"y",""),-1===Z_(m,"g")&&(m+="g"),g=ef(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Q_(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),nf&&(i=new RegExp("^"+_+"$(?!\\s)",m)),tf&&(r=c.lastIndex),n=F_(Y_,p?i:c,g),p?n?(n.input=ef(n.input,f),n[0]=ef(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:tf&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),nf&&n&&n.length>1&&F_(q_,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=j_(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=n[a[1]];return n});var of=X_;nn({target:"RegExp",proto:!0,forced:/./.exec!==of},{exec:of});var sf=or,af=_n,cf=x,lf=RangeError,df=I,uf=hr,hf=_n,pf=function(e){var t=af(cf(this)),i="",r=sf(e);if(r<0||Infinity===r)throw new lf("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},mf=x,_f=df(pf),ff=df("".slice),gf=Math.ceil,Ef=function(e){return function(t,i,r){var n,o,s=hf(mf(t)),a=uf(i),c=s.length,l=void 0===r?" ":hf(r);return a<=c||""===l?s:((o=_f(l,gf((n=a-c)/l.length))).length>n&&(o=ff(o,0,n)),e?s+o:o+s)}},Tf={start:Ef(!1),end:Ef(!0)},vf=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(X),yf=Tf.start;nn({target:"String",proto:!0,forced:vf},{padStart:function(e){return yf(this,e,arguments.length>1?arguments[1]:void 0)}});var Sf=u,If=$i,Af=of,Rf=s,Cf=rt,bf=Yt,kf=Cf("species"),Df=RegExp.prototype,Nf=I,wf=or,Pf=_n,Of=x,Mf=Nf("".charAt),Lf=Nf("".charCodeAt),xf=Nf("".slice),Uf=function(e){return function(t,i){var r,n,o=Pf(Of(t)),s=wf(i),a=o.length;return s<0||s>=a?e?"":void 0:(r=Lf(o,s))<55296||r>56319||s+1===a||(n=Lf(o,s+1))<56320||n>57343?e?Mf(o,s):r:e?xf(o,s,s+2):n-56320+(r-55296<<10)+65536}},Vf={codeAt:Uf(!1),charAt:Uf(!0)},Ff=Vf.charAt,Bf=I,Hf=Be,Wf=Math.floor,Gf=Bf("".charAt),jf=Bf("".replace),zf=Bf("".slice),Jf=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Kf=/\$([$&'`]|\d{1,2})/g,qf=function(e,t,i,r,n,o){var s=i+e.length,a=r.length,c=Kf;return void 0!==n&&(n=Hf(n),c=Jf),jf(o,c,function(o,c){var l;switch(Gf(c,0)){case"$":return"$";case"&":return e;case"`":return zf(t,0,i);case"'":return zf(t,s);case"<":l=n[zf(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Wf(d/10);return 0===u?o:u<=a?void 0===r[u-1]?Gf(c,1):r[u-1]+Gf(c,1):o}l=r[d-1]}return void 0===l?"":l})},Yf=u,Xf=Lt,Qf=H,Zf=b,$f=of,eg=TypeError,tg=Cd,ig=u,rg=I,ng=function(e,t,i,r){var n=Cf(e),o=!Rf(function(){var t={};return t[n]=function(){return 7},7!==""[e](t)}),s=o&&!Rf(function(){var t=!1,i=/a/;if("split"===e){var r={};r[kf]=function(){return i},(i={constructor:r,flags:""})[n]=/./[n]}return 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===Af||s===Df.exec?o&&!n?{done:!0,value:Sf(a,t,i,r)}:{done:!0,value:Sf(e,i,t,r)}:{done:!1}});If(String.prototype,e,c[0]),If(Df,n,c[1])}r&&bf(Df[n],"sham",!0)},og=s,sg=Lt,ag=H,cg=G,lg=or,dg=hr,ug=_n,hg=x,pg=function(e,t,i){return t+(i?Ff(e,t).length:1)},mg=Se,_g=qf,fg=Fm,gg=function(e,t){var i=e.exec;if(Qf(i)){var r=Yf(i,e,t);return null!==r&&Xf(r),r}if("RegExp"===Zf(e))return Yf($f,e,t);throw new eg("RegExp#exec called on incompatible receiver")},Eg=rt("replace"),Tg=Math.max,vg=Math.min,yg=rg([].concat),Sg=rg([].push),Ig=rg("".indexOf),Ag=rg("".slice),Rg=function(e){return void 0===e?e:String(e)},Cg="$0"==="a".replace(/./,"$0"),bg=!!/./[Eg]&&""===/./[Eg]("a","$0"),kg=!og(function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")});ng("replace",function(e,t,i){var r=bg?"$":"$0";return[function(e,i){var r=hg(this),n=cg(e)?mg(e,Eg):void 0;return n?ig(n,e,r,i):ig(t,ug(r),e,i)},function(e,n){var o=sg(this),s=ug(e);if("string"==typeof n&&-1===Ig(n,r)&&-1===Ig(n,"$<")){var a=i(t,o,s,n);if(a.done)return a.value}var c=ag(n);c||(n=ug(n));var l,d=ug(fg(o)),u=-1!==Ig(d,"g");u&&(l=-1!==Ig(d,"u"),o.lastIndex=0);for(var h,p=[];null!==(h=gg(o,s))&&(Sg(p,h),u);){""===ug(h[0])&&(o.lastIndex=pg(s,dg(o.lastIndex),l))}for(var m="",_=0,f=0;f<p.length;f++){for(var g,E=ug((h=p[f])[0]),T=Tg(vg(lg(h.index),s.length),0),v=[],y=1;y<h.length;y++)Sg(v,Rg(h[y]));var S=h.groups;if(c){var I=yg([E],v,T,s);void 0!==S&&Sg(I,S),g=ug(tg(n,void 0,I))}else g=_g(E,s,T,v,S,n);T>=_&&(m+=Ag(s,_,T)+g,_=T+E.length)}return m+Ag(s,_)}]},!kg||!Cg||bg);var Dg="\t\n\v\f\r \u2028\u2029\ufeff",Ng=x,wg=_n,Pg=Dg,Og=I("".replace),Mg=RegExp("^["+Pg+"]+"),Lg=RegExp("(^|[^"+Pg+"])["+Pg+"]+$"),xg=function(e){return function(t){var i=wg(Ng(t));return 1&e&&(i=Og(i,Mg,"")),2&e&&(i=Og(i,Lg,"$1")),i}},Ug={start:xg(1),end:xg(2),trim:xg(3)},Vg=ii.PROPER,Fg=s,Bg=Dg,Hg=Ug.trim;nn({target:"String",proto:!0,forced:function(e){return Fg(function(){return!!Bg[e]()||"
"!=="
"[e]()||Vg&&Bg[e].name!==e})}("trim")},{trim:function(){return Hg(this)}});var Wg,Gg,jg,zg={exports:{}},Jg=Ja,Kg=a,qg=n,Yg=H,Xg=G,Qg=Ge,Zg=hn,$g=_e,eE=Yt,tE=$i,iE=En,rE=K,nE=wo,oE=cs,sE=rt,aE=qe,cE=Ni.enforce,lE=Ni.get,dE=qg.Int8Array,uE=dE&&dE.prototype,hE=qg.Uint8ClampedArray,pE=hE&&hE.prototype,mE=dE&&nE(dE),_E=uE&&nE(uE),fE=Object.prototype,gE=qg.TypeError,EE=sE("toStringTag"),TE=aE("TYPED_ARRAY_TAG"),vE="TypedArrayConstructor",yE=Jg&&!!oE&&"Opera"!==Zg(qg.opera),SE=!1,IE={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},AE={BigInt64Array:8,BigUint64Array:8},RE=function(e){var t=nE(e);if(Xg(t)){var i=lE(t);return i&&Qg(i,vE)?i[vE]:RE(t)}},CE=function(e){if(!Xg(e))return!1;var t=Zg(e);return Qg(IE,t)||Qg(AE,t)};for(Wg in IE)(jg=(Gg=qg[Wg])&&Gg.prototype)?cE(jg)[vE]=Gg:yE=!1;for(Wg in AE)(jg=(Gg=qg[Wg])&&Gg.prototype)&&(cE(jg)[vE]=Gg);if((!yE||!Yg(mE)||mE===Function.prototype)&&(mE=function(){throw new gE("Incorrect invocation")},yE))for(Wg in IE)qg[Wg]&&oE(qg[Wg],mE);if((!yE||!_E||_E===fE)&&(_E=mE.prototype,yE))for(Wg in IE)qg[Wg]&&oE(qg[Wg].prototype,_E);if(yE&&nE(pE)!==_E&&oE(pE,_E),Kg&&!Qg(_E,EE))for(Wg in SE=!0,iE(_E,EE,{configurable:!0,get:function(){return Xg(this)?this[TE]:void 0}}),IE)qg[Wg]&&eE(qg[Wg],TE,Wg);var bE={NATIVE_ARRAY_BUFFER_VIEWS:yE,TYPED_ARRAY_TAG:SE&&TE,aTypedArray:function(e){if(CE(e))return e;throw new gE("Target is not a typed array")},aTypedArrayConstructor:function(e){if(Yg(e)&&(!oE||rE(mE,e)))return e;throw new gE($g(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(Kg){if(i)for(var n in IE){var o=qg[n];if(o&&Qg(o.prototype,e))try{delete o.prototype[e]}catch(XJ){try{o.prototype[e]=t}catch(s){}}}_E[e]&&!i||tE(_E,e,i?t:yE&&uE[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(Kg){if(oE){if(i)for(r in IE)if((n=qg[r])&&Qg(n,e))try{delete n[e]}catch(XJ){}if(mE[e]&&!i)return;try{return tE(mE,e,i?t:yE&&mE[e]||t)}catch(XJ){}}for(r in IE)!(n=qg[r])||n[e]&&!i||tE(n,e,t)}},getTypedArrayConstructor:RE,isView:function(e){if(!Xg(e))return!1;var t=Zg(e);return"DataView"===t||Qg(IE,t)||Qg(AE,t)},isTypedArray:CE,TypedArray:mE,TypedArrayPrototype:_E},kE=n,DE=s,NE=Fp,wE=bE.NATIVE_ARRAY_BUFFER_VIEWS,PE=kE.ArrayBuffer,OE=kE.Int8Array,ME=!wE||!DE(function(){OE(1)})||!DE(function(){new OE(-1)})||!NE(function(e){new OE,new OE(null),new OE(1.5),new OE(e)},!0)||DE(function(){return 1!==new OE(new PE(2),1,void 0).length}),LE=G,xE=Math.floor,UE=Number.isInteger||function(e){return!LE(e)&&isFinite(e)&&xE(e)===e},VE=or,FE=RangeError,BE=function(e){var t=VE(e);if(t<0)throw new FE("The argument can't be less than 0");return t},HE=RangeError,WE=function(e,t){var i=BE(e);if(i%t)throw new HE("Wrong offset");return i},GE=Math.round,jE=hn,zE=ut,JE=TypeError,KE=function(e){var t=zE(e,"number");if("number"==typeof t)throw new JE("Can't convert number to bigint");return BigInt(t)},qE=Nd,YE=u,XE=fd,QE=Be,ZE=mr,$E=fp,eT=lp,tT=rp,iT=function(e){var t=jE(e);return"BigInt64Array"===t||"BigUint64Array"===t},rT=bE.aTypedArrayConstructor,nT=KE,oT=function(e){var t,i,r,n,o,s,a,c,l=XE(this),d=QE(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=eT(d);if(m&&!tT(m))for(c=(a=$E(d,m)).next,d=[];!(s=YE(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=qE(h,arguments[2])),i=ZE(d),r=new(rT(l))(i),n=iT(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?nT(o):+o;return r},sT=ca,aT=hd,cT=G,lT=rt("species"),dT=Array,uT=function(e){var t;return sT(e)&&(t=e.constructor,(aT(t)&&(t===dT||sT(t.prototype))||cT(t)&&null===(t=t[lT]))&&(t=void 0)),void 0===t?dT:t},hT=Nd,pT=P,mT=Be,_T=mr,fT=function(e,t){return new(uT(e))(0===t?0:t)},gT=I([].push),ET=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=mT(c),_=pT(m),f=_T(_),g=hT(l,d),E=0,T=u||fT,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:gT(v,h)}else switch(e){case 4:return!1;case 7:gT(v,h)}return o?-1:r||n?n:v}},TT={forEach:ET(0),map:ET(1),filter:ET(2),some:ET(3),every:ET(4),find:ET(5),findIndex:ET(6),filterReject:ET(7)},vT=mr,yT=nn,ST=n,IT=u,AT=a,RT=ME,CT=bE,bT=Rl,kT=Qa,DT=E,NT=Yt,wT=UE,PT=hr,OT=tc,MT=WE,LT=function(e){var t=GE(e);return t<0?0:t>255?255:255&t},xT=mt,UT=Ge,VT=hn,FT=G,BT=pe,HT=lo,WT=K,GT=cs,jT=er.f,zT=oT,JT=TT.forEach,KT=Nl,qT=En,YT=Nt,XT=o,QT=function(e,t,i){for(var r=0,n=arguments.length>2?i:vT(t),o=new e(n);n>r;)o[r]=t[r++];return o},ZT=Ic,$T=Ni.get,ev=Ni.set,tv=Ni.enforce,iv=YT.f,rv=XT.f,nv=ST.RangeError,ov=bT.ArrayBuffer,sv=ov.prototype,av=bT.DataView,cv=CT.NATIVE_ARRAY_BUFFER_VIEWS,lv=CT.TYPED_ARRAY_TAG,dv=CT.TypedArray,uv=CT.TypedArrayPrototype,hv=CT.isTypedArray,pv="BYTES_PER_ELEMENT",mv="Wrong length",_v=function(e,t){qT(e,t,{configurable:!0,get:function(){return $T(this)[t]}})},fv=function(e){var t;return WT(sv,e)||"ArrayBuffer"===(t=VT(e))||"SharedArrayBuffer"===t},gv=function(e,t){return hv(e)&&!BT(t)&&t in e&&wT(+t)&&t>=0},Ev=function(e,t){return t=xT(t),gv(e,t)?DT(2,e[t]):rv(e,t)},Tv=function(e,t,i){return t=xT(t),!(gv(e,t)&&FT(i)&&UT(i,"value"))||UT(i,"get")||UT(i,"set")||i.configurable||UT(i,"writable")&&!i.writable||UT(i,"enumerable")&&!i.enumerable?iv(e,t,i):(e[t]=i.value,e)};AT?(cv||(XT.f=Ev,YT.f=Tv,_v(uv,"buffer"),_v(uv,"byteOffset"),_v(uv,"byteLength"),_v(uv,"length")),yT({target:"Object",stat:!0,forced:!cv},{getOwnPropertyDescriptor:Ev,defineProperty:Tv}),zg.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=ST[n],c=a,l=c&&c.prototype,d={},u=function(e,t){iv(e,t,{get:function(){return function(e,t){var i=$T(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=$T(e);o.view[s](t*r+o.byteOffset,i?LT(n):n,!0)}(this,t,e)},enumerable:!0})};cv?RT&&(c=t(function(e,t,i,n){return kT(e,l),ZT(FT(t)?fv(t)?void 0!==n?new a(t,MT(i,r),n):void 0!==i?new a(t,MT(i,r)):new a(t):hv(t)?QT(c,t):IT(zT,c,t):new a(OT(t)),e,c)}),GT&>(c,dv),JT(jT(a),function(e){e in c||NT(c,e,a[e])}),c.prototype=l):(c=t(function(e,t,i,n){kT(e,l);var o,s,a,d=0,h=0;if(FT(t)){if(!fv(t))return hv(t)?QT(c,t):IT(zT,c,t);o=t,h=MT(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw new nv(mv);if((s=p-h)<0)throw new nv(mv)}else if((s=PT(n)*r)+h>p)throw new nv(mv);a=s/r}else a=OT(t),o=new ov(s=a*r);for(ev(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new av(o)});d<a;)u(e,d++)}),GT&>(c,dv),l=c.prototype=HT(uv)),l.constructor!==c&&NT(l,"constructor",c),tv(l).TypedArrayConstructor=c,lv&&NT(l,lv,n);var h=c!==a;d[n]=c,yT({global:!0,constructor:!0,forced:h,sham:!cv},d),pv in c||NT(c,pv,r),pv in l||NT(l,pv,r),KT(n)}):zg.exports=function(){};var vv=zg.exports;vv("Float32",function(e){return function(t,i,r){return e(this,t,i,r)}}),vv("Uint8",function(e){return function(t,i,r){return e(this,t,i,r)}});var yv=Tc,Sv=KE,Iv=hn,Av=u,Rv=s,Cv=bE.aTypedArray,bv=bE.exportTypedArrayMethod,kv=I("".slice);bv("fill",function(e){var t=arguments.length;Cv(this);var i="Big"===kv(Iv(this),0,3)?Sv(e):+e;return Av(yv,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)},Rv(function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})),(0,bE.exportTypedArrayStaticMethod)("from",oT,ME);var Dv=n,Nv=u,wv=bE,Pv=mr,Ov=WE,Mv=Be,Lv=s,xv=Dv.RangeError,Uv=Dv.Int8Array,Vv=Uv&&Uv.prototype,Fv=Vv&&Vv.set,Bv=wv.aTypedArray,Hv=wv.exportTypedArrayMethod,Wv=!Lv(function(){var e=new Uint8ClampedArray(2);return Nv(Fv,e,{length:1,0:3},1),3!==e[1]}),Gv=Wv&&wv.NATIVE_ARRAY_BUFFER_VIEWS&&Lv(function(){var e=new Uv(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]});Hv("set",function(e){Bv(this);var t=Ov(arguments.length>1?arguments[1]:void 0,1),i=Mv(e);if(Wv)return Nv(Fv,this,i,t);var r=this.length,n=Pv(i),o=0;if(n+t>r)throw new xv("Wrong length");for(;o<n;)this[t+o]=i[o++]},!Wv||Gv);var jv=xl,zv=s,Jv=Te,Kv=Ta,qv=ya,Yv=Sa,Xv=re,Qv=Aa,Zv=bE.aTypedArray,$v=bE.exportTypedArrayMethod,ey=n.Uint16Array,ty=ey&&jv(ey.prototype.sort),iy=!(!ty||zv(function(){ty(new ey(2),null)})&&zv(function(){ty(new ey(2),{})})),ry=!!ty&&!zv(function(){if(Xv)return Xv<74;if(qv)return qv<67;if(Yv)return!0;if(Qv)return Qv<602;var e,t,i=new ey(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(ty(i,function(e,t){return(e/4|0)-(t/4|0)}),e=0;e<516;e++)if(i[e]!==r[e])return!0});$v("sort",function(e){return void 0!==e&&Jv(e),ry?ty(this,e):Kv(Zv(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))},!ry||iy);var ny=nn,oy=u,sy=I,ay=x,cy=H,ly=G,dy=bm,uy=_n,hy=Se,py=Fm,my=qf,_y=rt("replace"),fy=TypeError,gy=sy("".indexOf);sy("".replace);var Ey=sy("".slice),Ty=Math.max;ny({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,n,o,s,a,c,l,d,u=ay(this),h=0,p="";if(ly(e)){if(dy(e)&&(i=uy(ay(py(e))),!~gy(i,"g")))throw new fy("`.replaceAll` does not allow non-global regexes");if(r=hy(e,_y))return oy(r,e,u,t)}for(n=uy(u),o=uy(e),(s=cy(t))||(t=uy(t)),a=o.length,c=Ty(1,a),l=gy(n,o);-1!==l;)d=s?uy(t(o,l,n)):my(o,n,l,[],void 0,t),p+=Ey(n,h,l)+d,h=l+a,l=l+c>n.length?-1:gy(n,o,l+c);return h<n.length&&(p+=Ey(n,h)),p}});var vy={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},yy=Et("span").classList,Sy=yy&&yy.constructor&&yy.constructor.prototype,Iy=Sy===Object.prototype?void 0:Sy,Ay=TT.forEach,Ry=Zs("forEach")?[].forEach:function(e){return Ay(this,e,arguments.length>1?arguments[1]:void 0)},Cy=n,by=vy,ky=Iy,Dy=Ry,Ny=Yt,wy=function(e){if(e&&e.forEach!==Dy)try{Ny(e,"forEach",Dy)}catch(XJ){e.forEach=Dy}};for(var Py in by)by[Py]&&wy(Cy[Py]&&Cy[Py].prototype);wy(ky);var Oy=n,My=vy,Ly=Iy,xy=Hs,Uy=Yt,Vy=jo,Fy=rt("iterator"),By=xy.values,Hy=function(e,t){if(e){if(e[Fy]!==By)try{Uy(e,Fy,By)}catch(XJ){e[Fy]=By}if(Vy(e,t,!0),My[t])for(var i in xy)if(e[i]!==xy[i])try{Uy(e,i,xy[i])}catch(XJ){e[i]=xy[i]}}};for(var Wy in My)Hy(Oy[Wy]&&Oy[Wy].prototype,Wy);Hy(Ly,"DOMTokenList");var Gy=su.clear;nn({global:!0,bind:!0,enumerable:!0,forced:n.clearImmediate!==Gy},{clearImmediate:Gy});var jy=n,zy=Cd,Jy=H,Ky=ra,qy=X,Yy=_a,Xy=Pd,Qy=jy.Function,Zy=/MSIE .\./.test(qy)||"BUN"===Ky&&function(){var e=jy.Bun.version.split(".");return e.length<3||"0"===e[0]&&(e[1]<3||"3"===e[1]&&"0"===e[2])}(),$y=nn,eS=n,tS=su.set,iS=function(e,t){var i=t?2:1;return Zy?function(r,n){var o=Xy(arguments.length,1)>i,s=Jy(r)?r:Qy(r),a=o?Yy(arguments,i):[],c=o?function(){zy(s,this,a)}:s;return t?e(c,n):e(c)}:e},rS=eS.setImmediate?iS(tS,!1):tS;$y({global:!0,bind:!0,enumerable:!0,forced:eS.setImmediate!==rS},{setImmediate:rS});var nS=Vf.charAt,oS=_n,sS=Ni,aS=ks,cS=Ds,lS="String Iterator",dS=sS.set,uS=sS.getterFor(lS);aS(String,"String",function(e){dS(this,{type:lS,string:oS(e),index:0})},function(){var e,t=uS(this),i=t.string,r=t.index;return r>=i.length?cS(void 0,!0):(e=nS(i,r),t.index+=e.length,cS(e,!1))});var hS=s,pS=a,mS=rt("iterator"),_S=!hS(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&&!pS||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[mS]||"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}),fS=a,gS=I,ES=u,TS=s,vS=Hn,yS=Dr,SS=h,IS=Be,AS=P,RS=Object.assign,CS=Object.defineProperty,bS=gS([].concat),kS=!RS||TS(function(){if(fS&&1!==RS({b:1},RS(CS({},"a",{enumerable:!0,get:function(){CS(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!==RS({},e)[i]||vS(RS({},t)).join("")!==r})?function(e,t){for(var i=IS(e),r=arguments.length,n=1,o=yS.f,s=SS.f;r>n;)for(var a,c=AS(arguments[n++]),l=o?bS(vS(c),o(c)):vS(c),d=l.length,u=0;d>u;)a=l[u++],fS&&!ES(s,c,a)||(i[a]=c[a]);return i}:RS,DS=Lt,NS=vp,wS=a,PS=Nt,OS=E,MS=Nd,LS=u,xS=Be,US=function(e,t,i,r){try{return r?t(DS(i)[0],i[1]):t(i)}catch(XJ){NS(e,"throw",XJ)}},VS=rp,FS=hd,BS=mr,HS=function(e,t,i){wS?PS.f(e,t,OS(0,i)):e[t]=i},WS=fp,GS=lp,jS=Array,zS=I,JS=2147483647,KS=/[^\0-\u007E]/,qS=/[.\u3002\uFF0E\uFF61]/g,YS="Overflow: input needs wider integers to process",XS=RangeError,QS=zS(qS.exec),ZS=Math.floor,$S=String.fromCharCode,eI=zS("".charCodeAt),tI=zS([].join),iI=zS([].push),rI=zS("".replace),nI=zS("".split),oI=zS("".toLowerCase),sI=function(e){return e+22+75*(e<26)},aI=function(e,t,i){var r=0;for(e=i?ZS(e/700):e>>1,e+=ZS(e/t);e>455;)e=ZS(e/35),r+=36;return ZS(r+36*e/(e+38))},cI=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=eI(e,i++);if(n>=55296&&n<=56319&&i<r){var o=eI(e,i++);56320==(64512&o)?iI(t,((1023&n)<<10)+(1023&o)+65536):(iI(t,n),i--)}else iI(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&&iI(t,$S(r));var c=t.length,l=c;for(c&&iI(t,"-");l<n;){var d=JS;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>ZS((JS-s)/u))throw new XS(YS);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++s>JS)throw new XS(YS);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;iI(t,$S(sI(m+_%f))),h=ZS(_/f),p+=36}iI(t,$S(sI(h))),a=aI(s,u,l===c),s=0,l++}}s++,o++}return tI(t,"")},lI=nn,dI=I,uI=lr,hI=RangeError,pI=String.fromCharCode,mI=String.fromCodePoint,_I=dI([].join);lI({target:"String",stat:!0,arity:1,forced:!!mI&&1!==mI.length},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,n=0;r>n;){if(t=+arguments[n++],uI(t,1114111)!==t)throw new hI(t+" is not a valid code point");i[n]=t<65536?pI(t):pI(55296+((t-=65536)>>10),t%1024+56320)}return _I(i,"")}});var fI=nn,gI=n,EI=du,TI=J,vI=u,yI=I,SI=a,II=_S,AI=$i,RI=En,CI=qa,bI=jo,kI=Qo,DI=Ni,NI=Qa,wI=H,PI=Ge,OI=Nd,MI=hn,LI=Lt,xI=G,UI=_n,VI=lo,FI=E,BI=fp,HI=lp,WI=Ds,GI=Pd,jI=Ta,zI=rt("iterator"),JI="URLSearchParams",KI=JI+"Iterator",qI=DI.set,YI=DI.getterFor(JI),XI=DI.getterFor(KI),QI=EI("fetch"),ZI=EI("Request"),$I=EI("Headers"),eA=ZI&&ZI.prototype,tA=$I&&$I.prototype,iA=gI.TypeError,rA=gI.encodeURIComponent,nA=String.fromCharCode,oA=TI("String","fromCodePoint"),sA=parseInt,aA=yI("".charAt),cA=yI([].join),lA=yI([].push),dA=yI("".replace),uA=yI([].shift),hA=yI([].splice),pA=yI("".split),mA=yI("".slice),_A=yI(/./.exec),fA=/\+/g,gA=/^[0-9a-f]+$/i,EA=function(e,t){var i=mA(e,t,t+2);return _A(gA,i)?sA(i,16):NaN},TA=function(e){for(var t=0,i=128;i>0&&0!==(e&i);i>>=1)t++;return t},vA=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},yA=function(e){for(var t=(e=dA(e,fA," ")).length,i="",r=0;r<t;){var n=aA(e,r);if("%"===n){if("%"===aA(e,r+1)||r+3>t){i+="%",r++;continue}var o=EA(e,r+1);if(o!=o){i+=n,r++;continue}r+=2;var s=TA(o);if(0===s)n=nA(o);else{if(1===s||s>4){i+="�",r++;continue}for(var a=[o],c=1;c<s&&!(++r+3>t||"%"!==aA(e,r));){var l=EA(e,r+1);if(l!=l){r+=3;break}if(l>191||l<128)break;lA(a,l),r+=2,c++}if(a.length!==s){i+="�";continue}var d=vA(a);null===d?i+="�":n=oA(d)}}i+=n,r++}return i},SA=/[!'()~]|%20/g,IA={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},AA=function(e){return IA[e]},RA=function(e){return dA(rA(e),SA,AA)},CA=kI(function(e,t){qI(this,{type:KI,target:YI(e).entries,index:0,kind:t})},JI,function(){var e=XI(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,WI(void 0,!0);var r=t[i];switch(e.kind){case"keys":return WI(r.key,!1);case"values":return WI(r.value,!1)}return WI([r.key,r.value],!1)},!0),bA=function(e){this.entries=[],this.url=null,void 0!==e&&(xI(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===aA(e,0)?mA(e,1):e:UI(e)))};bA.prototype={type:JI,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,s,a,c=this.entries,l=HI(e);if(l)for(i=(t=BI(e,l)).next;!(r=vI(i,t)).done;){if(o=(n=BI(LI(r.value))).next,(s=vI(o,n)).done||(a=vI(o,n)).done||!vI(o,n).done)throw new iA("Expected sequence with length 2");lA(c,{key:UI(s.value),value:UI(a.value)})}else for(var d in e)PI(e,d)&&lA(c,{key:d,value:UI(e[d])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,n=pA(e,"&"),o=0;o<n.length;)(t=n[o++]).length&&(i=pA(t,"="),lA(r,{key:yA(uA(i)),value:yA(cA(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],lA(i,RA(e.key)+"="+RA(e.value));return cA(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var kA=function(){NI(this,DA);var e=qI(this,new bA(arguments.length>0?arguments[0]:void 0));SI||(this.size=e.entries.length)},DA=kA.prototype;if(CI(DA,{append:function(e,t){var i=YI(this);GI(arguments.length,2),lA(i.entries,{key:UI(e),value:UI(t)}),SI||this.size++,i.updateURL()},delete:function(e){for(var t=YI(this),i=GI(arguments.length,1),r=t.entries,n=UI(e),o=i<2?void 0:arguments[1],s=void 0===o?o:UI(o),a=0;a<r.length;){var c=r[a];if(c.key!==n||void 0!==s&&c.value!==s)a++;else if(hA(r,a,1),void 0!==s)break}SI||(this.size=r.length),t.updateURL()},get:function(e){var t=YI(this).entries;GI(arguments.length,1);for(var i=UI(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=YI(this).entries;GI(arguments.length,1);for(var i=UI(e),r=[],n=0;n<t.length;n++)t[n].key===i&&lA(r,t[n].value);return r},has:function(e){for(var t=YI(this).entries,i=GI(arguments.length,1),r=UI(e),n=i<2?void 0:arguments[1],o=void 0===n?n:UI(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=YI(this);GI(arguments.length,1);for(var r,n=i.entries,o=!1,s=UI(e),a=UI(t),c=0;c<n.length;c++)(r=n[c]).key===s&&(o?hA(n,c--,1):(o=!0,r.value=a));o||lA(n,{key:s,value:a}),SI||(this.size=n.length),i.updateURL()},sort:function(){var e=YI(this);jI(e.entries,function(e,t){return e.key>t.key?1:-1}),e.updateURL()},forEach:function(e){for(var t,i=YI(this).entries,r=OI(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 CA(this,"keys")},values:function(){return new CA(this,"values")},entries:function(){return new CA(this,"entries")}},{enumerable:!0}),AI(DA,zI,DA.entries,{name:"entries"}),AI(DA,"toString",function(){return YI(this).serialize()},{enumerable:!0}),SI&&RI(DA,"size",{get:function(){return YI(this).entries.length},configurable:!0,enumerable:!0}),bI(kA,JI),fI({global:!0,constructor:!0,forced:!II},{URLSearchParams:kA}),!II&&wI($I)){var NA=yI(tA.has),wA=yI(tA.set),PA=function(e){if(xI(e)){var t,i=e.body;if(MI(i)===JI)return t=e.headers?new $I(e.headers):new $I,NA(t,"content-type")||wA(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),VI(e,{body:FI(0,UI(i)),headers:FI(0,t)})}return e};if(wI(QI)&&fI({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return QI(e,arguments.length>1?PA(arguments[1]):{})}}),wI(ZI)){var OA=function(e){return NI(this,eA),new ZI(e,arguments.length>1?PA(arguments[1]):{})};eA.constructor=OA,OA.prototype=eA,fI({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:OA})}}var MA,LA=nn,xA=a,UA=_S,VA=n,FA=Nd,BA=I,HA=$i,WA=En,GA=Qa,jA=Ge,zA=kS,JA=function(e){var t=xS(e),i=FS(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=MS(n,r>2?arguments[2]:void 0));var s,a,c,l,d,u,h=GS(t),p=0;if(!h||this===jS&&VS(h))for(s=BS(t),a=i?new this(s):jS(s);s>p;p++)u=o?n(t[p],p):t[p],HS(a,p,u);else for(a=i?new this:[],d=(l=WS(t,h)).next;!(c=LS(d,l)).done;p++)u=o?US(l,n,[c.value,p],!0):c.value,HS(a,p,u);return a.length=p,a},KA=_a,qA=Vf.codeAt,YA=function(e){var t,i,r=[],n=nI(rI(oI(e),qS,"."),".");for(t=0;t<n.length;t++)i=n[t],iI(r,QS(KS,i)?"xn--"+cI(i):i);return tI(r,".")},XA=_n,QA=jo,ZA=Pd,$A={URLSearchParams:kA,getState:YI},eR=Ni,tR=eR.set,iR=eR.getterFor("URL"),rR=$A.URLSearchParams,nR=$A.getState,oR=VA.URL,sR=VA.TypeError,aR=VA.parseInt,cR=Math.floor,lR=Math.pow,dR=BA("".charAt),uR=BA(/./.exec),hR=BA([].join),pR=BA(1.1.toString),mR=BA([].pop),_R=BA([].push),fR=BA("".replace),gR=BA([].shift),ER=BA("".split),TR=BA("".slice),vR=BA("".toLowerCase),yR=BA([].unshift),SR="Invalid scheme",IR="Invalid host",AR="Invalid port",RR=/[a-z]/i,CR=/[\d+-.a-z]/i,bR=/\d/,kR=/^0x/i,DR=/^[0-7]+$/,NR=/^\d+$/,wR=/^[\da-f]+$/i,PR=/[\0\t\n\r #%/:<>?@[\\\]^|]/,OR=/[\0\t\n\r #/:<>?@[\\\]^|]/,MR=/^[\u0000-\u0020]+/,LR=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,xR=/[\t\n\r]/g,UR=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)yR(t,e%256),e=cR(e/256);return hR(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+=pR(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},VR={},FR=zA({},VR,{" ":1,'"':1,"<":1,">":1,"`":1}),BR=zA({},FR,{"#":1,"?":1,"{":1,"}":1}),HR=zA({},BR,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),WR=function(e,t){var i=qA(e,0);return i>32&&i<127&&!jA(t,e)?e:encodeURIComponent(e)},GR={ftp:21,file:null,http:80,https:443,ws:80,wss:443},jR=function(e,t){var i;return 2===e.length&&uR(RR,dR(e,0))&&(":"===(i=dR(e,1))||!t&&"|"===i)},zR=function(e){var t;return e.length>1&&jR(TR(e,0,2))&&(2===e.length||"/"===(t=dR(e,2))||"\\"===t||"?"===t||"#"===t)},JR=function(e){return"."===e||"%2e"===vR(e)},KR=function(e){return".."===(e=vR(e))||"%2e."===e||".%2e"===e||"%2e%2e"===e},qR={},YR={},XR={},QR={},ZR={},$R={},eC={},tC={},iC={},rC={},nC={},oC={},sC={},aC={},cC={},lC={},dC={},uC={},hC={},pC={},mC={},_C=function(e,t,i){var r,n,o,s=XA(e);if(t){if(n=this.parse(s))throw new sR(n);this.searchParams=null}else{if(void 0!==i&&(r=new _C(i,!0)),n=this.parse(s,null,r))throw new sR(n);(o=nR(new rR)).bindURL(this),this.searchParams=o}};_C.prototype={type:"URL",parse:function(e,t,i){var r,n,o,s,a=this,c=t||qR,l=0,d="",u=!1,h=!1,p=!1;for(e=XA(e),t||(a.scheme="",a.username="",a.password="",a.host=null,a.port=null,a.path=[],a.query=null,a.fragment=null,a.cannotBeABaseURL=!1,e=fR(e,MR,""),e=fR(e,LR,"$1")),e=fR(e,xR,""),r=JA(e);l<=r.length;){switch(n=r[l],c){case qR:if(!n||!uR(RR,n)){if(t)return SR;c=XR;continue}d+=vR(n),c=YR;break;case YR:if(n&&(uR(CR,n)||"+"===n||"-"===n||"."===n))d+=vR(n);else{if(":"!==n){if(t)return SR;d="",c=XR,l=0;continue}if(t&&(a.isSpecial()!==jA(GR,d)||"file"===d&&(a.includesCredentials()||null!==a.port)||"file"===a.scheme&&!a.host))return;if(a.scheme=d,t)return void(a.isSpecial()&&GR[a.scheme]===a.port&&(a.port=null));d="","file"===a.scheme?c=aC:a.isSpecial()&&i&&i.scheme===a.scheme?c=QR:a.isSpecial()?c=tC:"/"===r[l+1]?(c=ZR,l++):(a.cannotBeABaseURL=!0,_R(a.path,""),c=hC)}break;case XR:if(!i||i.cannotBeABaseURL&&"#"!==n)return SR;if(i.cannotBeABaseURL&&"#"===n){a.scheme=i.scheme,a.path=KA(i.path),a.query=i.query,a.fragment="",a.cannotBeABaseURL=!0,c=mC;break}c="file"===i.scheme?aC:$R;continue;case QR:if("/"!==n||"/"!==r[l+1]){c=$R;continue}c=iC,l++;break;case ZR:if("/"===n){c=rC;break}c=uC;continue;case $R:if(a.scheme=i.scheme,n===MA)a.username=i.username,a.password=i.password,a.host=i.host,a.port=i.port,a.path=KA(i.path),a.query=i.query;else if("/"===n||"\\"===n&&a.isSpecial())c=eC;else if("?"===n)a.username=i.username,a.password=i.password,a.host=i.host,a.port=i.port,a.path=KA(i.path),a.query="",c=pC;else{if("#"!==n){a.username=i.username,a.password=i.password,a.host=i.host,a.port=i.port,a.path=KA(i.path),a.path.length--,c=uC;continue}a.username=i.username,a.password=i.password,a.host=i.host,a.port=i.port,a.path=KA(i.path),a.query=i.query,a.fragment="",c=mC}break;case eC:if(!a.isSpecial()||"/"!==n&&"\\"!==n){if("/"!==n){a.username=i.username,a.password=i.password,a.host=i.host,a.port=i.port,c=uC;continue}c=rC}else c=iC;break;case tC:if(c=iC,"/"!==n||"/"!==dR(d,l+1))continue;l++;break;case iC:if("/"!==n&&"\\"!==n){c=rC;continue}break;case rC:if("@"===n){u&&(d="%40"+d),u=!0,o=JA(d);for(var m=0;m<o.length;m++){var _=o[m];if(":"!==_||p){var f=WR(_,HR);p?a.password+=f:a.username+=f}else p=!0}d=""}else if(n===MA||"/"===n||"?"===n||"#"===n||"\\"===n&&a.isSpecial()){if(u&&""===d)return"Invalid authority";l-=JA(d).length+1,d="",c=nC}else d+=n;break;case nC:case oC:if(t&&"file"===a.scheme){c=lC;continue}if(":"!==n||h){if(n===MA||"/"===n||"?"===n||"#"===n||"\\"===n&&a.isSpecial()){if(a.isSpecial()&&""===d)return IR;if(t&&""===d&&(a.includesCredentials()||null!==a.port))return;if(s=a.parseHost(d))return s;if(d="",c=dC,t)return;continue}"["===n?h=!0:"]"===n&&(h=!1),d+=n}else{if(""===d)return IR;if(s=a.parseHost(d))return s;if(d="",c=sC,t===oC)return}break;case sC:if(!uR(bR,n)){if(n===MA||"/"===n||"?"===n||"#"===n||"\\"===n&&a.isSpecial()||t){if(""!==d){var g=aR(d,10);if(g>65535)return AR;a.port=a.isSpecial()&&g===GR[a.scheme]?null:g,d=""}if(t)return;c=dC;continue}return AR}d+=n;break;case aC:if(a.scheme="file","/"===n||"\\"===n)c=cC;else{if(!i||"file"!==i.scheme){c=uC;continue}switch(n){case MA:a.host=i.host,a.path=KA(i.path),a.query=i.query;break;case"?":a.host=i.host,a.path=KA(i.path),a.query="",c=pC;break;case"#":a.host=i.host,a.path=KA(i.path),a.query=i.query,a.fragment="",c=mC;break;default:zR(hR(KA(r,l),""))||(a.host=i.host,a.path=KA(i.path),a.shortenPath()),c=uC;continue}}break;case cC:if("/"===n||"\\"===n){c=lC;break}i&&"file"===i.scheme&&!zR(hR(KA(r,l),""))&&(jR(i.path[0],!0)?_R(a.path,i.path[0]):a.host=i.host),c=uC;continue;case lC:if(n===MA||"/"===n||"\\"===n||"?"===n||"#"===n){if(!t&&jR(d))c=uC;else if(""===d){if(a.host="",t)return;c=dC}else{if(s=a.parseHost(d))return s;if("localhost"===a.host&&(a.host=""),t)return;d="",c=dC}continue}d+=n;break;case dC:if(a.isSpecial()){if(c=uC,"/"!==n&&"\\"!==n)continue}else if(t||"?"!==n)if(t||"#"!==n){if(n!==MA&&(c=uC,"/"!==n))continue}else a.fragment="",c=mC;else a.query="",c=pC;break;case uC:if(n===MA||"/"===n||"\\"===n&&a.isSpecial()||!t&&("?"===n||"#"===n)){if(KR(d)?(a.shortenPath(),"/"===n||"\\"===n&&a.isSpecial()||_R(a.path,"")):JR(d)?"/"===n||"\\"===n&&a.isSpecial()||_R(a.path,""):("file"===a.scheme&&!a.path.length&&jR(d)&&(a.host&&(a.host=""),d=dR(d,0)+":"),_R(a.path,d)),d="","file"===a.scheme&&(n===MA||"?"===n||"#"===n))for(;a.path.length>1&&""===a.path[0];)gR(a.path);"?"===n?(a.query="",c=pC):"#"===n&&(a.fragment="",c=mC)}else d+=WR(n,BR);break;case hC:"?"===n?(a.query="",c=pC):"#"===n?(a.fragment="",c=mC):n!==MA&&(a.path[0]+=WR(n,VR));break;case pC:t||"#"!==n?n!==MA&&("'"===n&&a.isSpecial()?a.query+="%27":a.query+="#"===n?"%23":WR(n,VR)):(a.fragment="",c=mC);break;case mC:n!==MA&&(a.fragment+=WR(n,FR))}l++}},parseHost:function(e){var t,i,r;if("["===dR(e,0)){if("]"!==dR(e,e.length-1))return IR;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 dR(e,u)};if(":"===h()){if(":"!==dR(e,1))return;u+=2,d=++l}for(;h();){if(8===l)return;if(":"!==h()){for(t=i=0;i<4&&uR(wR,h());)t=16*t+aR(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(!uR(bR,h()))return;for(;uR(bR,h());){if(o=aR(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}(TR(e,1,-1)),!t)return IR;this.host=t}else if(this.isSpecial()){if(e=YA(e),uR(PR,e))return IR;if(t=function(e){var t,i,r,n,o,s,a,c=ER(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"===dR(n,0)&&(o=uR(kR,n)?16:8,n=TR(n,8===o?1:2)),""===n)s=0;else{if(!uR(10===o?NR:8===o?DR:wR,n))return e;s=aR(n,o)}_R(i,s)}for(r=0;r<t;r++)if(s=i[r],r===t-1){if(s>=lR(256,5-t))return null}else if(s>255)return null;for(a=mR(i),r=0;r<i.length;r++)a+=i[r]*lR(256,3-r);return a}(e),null===t)return IR;this.host=t}else{if(uR(OR,e))return IR;for(t="",i=JA(e),r=0;r<i.length;r++)t+=WR(i[r],VR);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return jA(GR,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&jR(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+=UR(n),null!==o&&(l+=":"+o)):"file"===t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+hR(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw new sR(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new fC(e.path[0]).origin}catch(XJ){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+UR(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(XA(e)+":",qR)},getUsername:function(){return this.username},setUsername:function(e){var t=JA(XA(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=WR(t[i],HR)}},getPassword:function(){return this.password},setPassword:function(e){var t=JA(XA(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=WR(t[i],HR)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?UR(e):UR(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,nC)},getHostname:function(){var e=this.host;return null===e?"":UR(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,oC)},getPort:function(){var e=this.port;return null===e?"":XA(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=XA(e))?this.port=null:this.parse(e,sC))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+hR(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,dC))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=XA(e))?this.query=null:("?"===dR(e,0)&&(e=TR(e,1)),this.query="",this.parse(e,pC)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=XA(e))?("#"===dR(e,0)&&(e=TR(e,1)),this.fragment="",this.parse(e,mC)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var fC=function(e){var t=GA(this,gC),i=ZA(arguments.length,1)>1?arguments[1]:void 0,r=tR(t,new _C(e,!1,i));xA||(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())},gC=fC.prototype,EC=function(e,t){return{get:function(){return iR(this)[e]()},set:t&&function(e){return iR(this)[t](e)},configurable:!0,enumerable:!0}};if(xA&&(WA(gC,"href",EC("serialize","setHref")),WA(gC,"origin",EC("getOrigin")),WA(gC,"protocol",EC("getProtocol","setProtocol")),WA(gC,"username",EC("getUsername","setUsername")),WA(gC,"password",EC("getPassword","setPassword")),WA(gC,"host",EC("getHost","setHost")),WA(gC,"hostname",EC("getHostname","setHostname")),WA(gC,"port",EC("getPort","setPort")),WA(gC,"pathname",EC("getPathname","setPathname")),WA(gC,"search",EC("getSearch","setSearch")),WA(gC,"searchParams",EC("getSearchParams")),WA(gC,"hash",EC("getHash","setHash"))),HA(gC,"toJSON",function(){return iR(this).serialize()},{enumerable:!0}),HA(gC,"toString",function(){return iR(this).serialize()},{enumerable:!0}),oR){var TC=oR.createObjectURL,vC=oR.revokeObjectURL;TC&&HA(fC,"createObjectURL",FA(TC,oR)),vC&&HA(fC,"revokeObjectURL",FA(vC,oR))}QA(fC,"URL"),LA({global:!0,constructor:!0,forced:!UA,sham:!xA},{URL:fC});var yC=u;nn({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return yC(URL.prototype.toString,this)}});let SC=!0,IC=!0;function AC(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseFloat(r[i],10)}function RC(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 CC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(SC=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function bC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(IC=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function kC(){if("object"==typeof window){if(SC)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function DC(e,t){IC&&console.warn(e+" is deprecated, please use "+t+" instead.")}function NC(e){return"[object Object]"===Object.prototype.toString.call(e)}function wC(e){return NC(e)?Object.keys(e).reduce(function(t,i){const r=NC(e[i]),n=r?wC(e[i]):e[i],o=r&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[i]:n})},{}):e}function PC(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith("Id")?PC(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach(t=>{PC(e,e.get(t),i)})}))}function OC(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&&PC(e,i,n)})}),n}const MC=kC;function LC(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),MC("chrome: "+JSON.stringify(e)),n(e)})}e.video=r(e.video)}return MC("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 xC(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function UC(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 RC(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function VC(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 FC(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 BC(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=>OC(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}),RC(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>OC(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 HC(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 WC(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return HC(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 GC(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 jC(e,t){RC(e,"negotiationneeded",e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var zC=Object.freeze({__proto__:null,shimMediaStream:xC,shimOnTrack:UC,shimGetSendersWithDtmf:VC,shimGetStats:FC,shimSenderReceiverGetStats:BC,shimAddTrackRemoveTrackWithNative:HC,shimAddTrackRemoveTrack:WC,shimPeerConnection:GC,fixNegotiationNeeded:jC,shimGetUserMedia:LC,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 JC(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){DC("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 KC(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 qC(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(Ik){if("TypeError"!==Ik.name)throw Ik;e.forEach((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))})}return e}).then(n,o)}}function YC(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 XC(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}),RC(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function QC(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){DC("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function ZC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function $C(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 eb(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 tb(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 ib(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 rb=Object.freeze({__proto__:null,shimOnTrack:KC,shimPeerConnection:qC,shimSenderGetStats:YC,shimReceiverGetStats:XC,shimRemoveStream:QC,shimRTCDataChannel:ZC,shimAddTransceiver:$C,shimGetParameters:eb,shimCreateOffer:tb,shimCreateAnswer:ib,shimGetUserMedia:JC,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 nb(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 ob(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 sb(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 ab(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(cb(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function cb(e){return e&&void 0!==e.video?Object.assign({},e,{video:wC(e.video)}):e}function lb(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?(DC("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 db(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 ub(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 hb(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var pb=Object.freeze({__proto__:null,shimLocalStreamsAPI:nb,shimRemoteStreamsAPI:ob,shimCallbacksAPI:sb,shimGetUserMedia:ab,shimConstraints:cb,shimRTCIceServerUrls:lb,shimTrackEventTransceiver:db,shimCreateOfferLegacy:ub,shimAudioContext:hb}),mb={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}(mb);var _b=mb.exports,fb=i(_b),gb=e({__proto__:null,default:fb},[_b]);function Eb(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=fb.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,RC(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Tb(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||RC(e,"icecandidate",e=>{if(e.candidate){const t=fb.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function vb(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=fb.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=fb.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=fb.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 yb(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},RC(e,"datachannel",e=>(t(e.channel,e.target),e))}function Sb(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 Ib(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)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 Ab(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 Rb(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 Cb=Object.freeze({__proto__:null,shimRTCIceCandidate:Eb,shimRTCIceCandidateRelayProtocol:Tb,shimMaxMessageSize:vb,shimSendThrowTypeError:yb,shimConnectionState:Sb,removeExtmapAllowMixed:Ib,shimAddIceCandidateNullOrEmpty:Ab,shimParameterlessSetLocalDescription:Rb});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=kC,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=parseInt(AC(i.userAgent,/Firefox\/(\d+)\./,1));else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(AC(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=parseInt(AC(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=AC(i.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),n={browserDetails:r,commonShim:Cb,extractVersion:AC,disableLog:CC,disableWarnings:bC,sdp:gb};switch(r.browser){case"chrome":if(!zC||!GC||!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=zC,Ab(e,r),Rb(e),LC(e,r),xC(e),GC(e,r),UC(e),WC(e,r),VC(e),FC(e),BC(e),jC(e,r),Eb(e),Tb(e),Sb(e),vb(e,r),yb(e),Ib(e,r);break;case"firefox":if(!rb||!qC||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=rb,Ab(e,r),Rb(e),JC(e,r),qC(e,r),KC(e),QC(e),YC(e),XC(e),ZC(e),$C(e),eb(e),tb(e),ib(e),Eb(e),Sb(e),vb(e,r),yb(e);break;case"safari":if(!pb||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=pb,Ab(e,r),Rb(e),lb(e),ub(e),sb(e),nb(e),ob(e),db(e),ab(e),hb(e),Eb(e),Tb(e),vb(e,r),yb(e),Ib(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var bb,kb=Object.create,Db=Object.defineProperty,Nb=Object.defineProperties,wb=Object.getOwnPropertyDescriptor,Pb=Object.getOwnPropertyDescriptors,Ob=Object.getOwnPropertyNames,Mb=Object.getOwnPropertySymbols,Lb=Object.getPrototypeOf,xb=Object.prototype.hasOwnProperty,Ub=Object.prototype.propertyIsEnumerable,Vb=Reflect.get,Fb=Math.pow,Bb=(e,t,i)=>t in e?Db(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Hb=(e,t)=>{for(var i in t||(t={}))xb.call(t,i)&&Bb(e,i,t[i]);if(Mb)for(var i of Mb(t))Ub.call(t,i)&&Bb(e,i,t[i]);return e},Wb=(e,t)=>Nb(e,Pb(t)),Gb=(e,t)=>{var i={};for(var r in e)xb.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&Mb)for(var r of Mb(e))t.indexOf(r)<0&&Ub.call(e,r)&&(i[r]=e[r]);return i},jb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),zb=(e,t)=>{for(var i in t)Db(e,i,{get:t[i],enumerable:!0})},Jb=(e,t,i)=>(i=null!=e?kb(Lb(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of Ob(t))!xb.call(e,n)&&n!==i&&Db(e,n,{get:()=>t[n],enumerable:!(r=wb(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:Db(i,"default",{value:e,enumerable:!0}),e)),Kb=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?wb(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&&Db(t,i,o),o},qb=(e,t,i)=>Bb(e,"symbol"!=typeof t?t+"":t,i),Yb=(e,t,i)=>Vb(Lb(e),i,t),Xb=(e,t,i)=>new Promise((r,n)=>{var o=e=>{try{a(i.next(e))}catch(fM){n(fM)}},s=e=>{try{a(i.throw(e))}catch(fM){n(fM)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())}),Qb=jb((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)}),Zb=jb((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")})})}),$b=jb(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=Zb(),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}})})}}),ek=jb((e,t)=>{var i=Zb(),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"}}),tk=jb(e=>{var t=$b(),i=ek(),r=Zb();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}),ik=jb((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")})})}),rk=jb(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=ik(),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}})})}}),nk=jb((e,t)=>{var i=ik(),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"}}),ok=jb(e=>{var t=rk(),i=nk();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}),sk=Jb(Qb()),ak=((bb=ak||{})[bb.INVALID_PARAMETER=4096]="INVALID_PARAMETER",bb[bb.INVALID_OPERATION=4097]="INVALID_OPERATION",bb[bb.NOT_SUPPORTED=4098]="NOT_SUPPORTED",bb[bb.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",bb[bb.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",bb[bb.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",bb[bb.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",bb[bb.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",bb[bb.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",bb[bb.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",bb[bb.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",bb[bb.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",bb[bb.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",bb[bb.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",bb[bb.CLIENT_BANNED=16448]="CLIENT_BANNED",bb[bb.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",bb[bb.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",bb[bb.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",bb[bb.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",bb[bb.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",bb[bb.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",bb[bb.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",bb[bb.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",bb[bb.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",bb[bb.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",bb[bb.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",bb[bb.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",bb[bb.API_CALL_ABORTED=16461]="API_CALL_ABORTED",bb[bb.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",bb[bb.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",bb[bb.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",bb[bb.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",bb[bb.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",bb[bb.UNKNOWN=65535]="UNKNOWN",bb),ck=ak,lk=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=ck.UNKNOWN,extraCode:n=0,constraint:o}=e,s="<".concat(function(e){for(let t in ck)if(ck[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),qb(this,"code"),qb(this,"extraCode"),qb(this,"message"),qb(this,"originMessage"),qb(this,"name"),qb(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}},dk=lk,uk=0,hk=!0,pk=function(e){uk=e;let t=new Date;t.setTime(t.getTime()+e),dM[hk?"info":"debug"]("baseTime from server: ".concat(t," offset: ").concat(e)),hk=!1},mk=function(){return uk},_k=function(){return Date.now()+uk},fk=function(){let e=new Date;return e.setTime(_k()),e.toLocaleString()},gk=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)},Ek={};zb(Ek,{REPORT_TYPE:()=>Lw,buildSSOPackage:()=>xw,bytes2ms:()=>xN,calculateScaleResolutionDownNumber:()=>ww,concatArrayBuffers:()=>Uw,convertObjectNumberToInt:()=>Cw,copyProperties:()=>LN,deepClone:()=>fw,deepCloneBasic:()=>Mw,deepMerge:()=>_w,delay:()=>bw,fibonacci:()=>GN,formatedTime:()=>Tw,getConstructorName:()=>rw,getContainerFromElement:()=>Ew,getEnv:()=>AN,getFirst16Bits:()=>Fw,getInternalVersion:()=>lw,getLast16Bits:()=>Vw,getLoggerUrl:()=>bN,getMediaStreamTrackInfo:()=>Nw,getMuteStateFromFlag:()=>hw,getNetworkType:()=>DN,getNumNetworkType:()=>MN,getReconnectionTimeout:()=>jN,getStringByteLength:()=>Sw,getTestSignalDomain:()=>RN,getTurnServer:()=>pw,getUint32Version:()=>Rw,getValueType:()=>zN,getViewListFromView:()=>gw,glog:()=>BN,ipv4ToUint32:()=>mw,isArray:()=>ZN,isAudioWorkletSupported:()=>nw,isBoolean:()=>XN,isConstructor:()=>iw,isEmpty:()=>uw,isFunction:()=>JN,isLangChinese:()=>HN,isMediaStreamTrack:()=>$N,isNumber:()=>YN,isObject:()=>QN,isOverseaSdkAppId:()=>CN,isPlainObject:()=>WN,isPortrait:()=>Iw,isPromise:()=>tw,isRemoteTrack:()=>ew,isRotate90Or270:()=>Pw,isSetSinkIdSupported:()=>ow,isString:()=>qN,isUndefined:()=>KN,loadImage:()=>Aw,loadVideo:()=>Ow,ms2bytes:()=>VN,ms2samples:()=>FN,normalizeUrl:()=>Dw,performanceNow:()=>aw,promiseAny:()=>sw,samples2ms:()=>UN,setNetworkTypeFromWebRTC:()=>ON,stringify:()=>vw,stringifyIncludeValue:()=>yw,throttlePromise:()=>kw});var Tk={};zb(Tk,{ASR_ROBOT_FROM_TYPE:()=>iN,AUDIO_MUTE_BIT:()=>aD,AUDIO_STAT_BIT:()=>sD,AUX_STAT_BIT:()=>oD,AUX_STREAM_MSID:()=>pD,BACKEND_ENV:()=>tD,BASE_DOC_URL:()=>Mk,BASE_HOST:()=>Nk,CAPABILITIES_KEYS:()=>eN,CLASS_NAME:()=>zD,CLOUD_CONSOLE_URL:()=>Ok,CROSS_ROOM_BIT:()=>dD,DATA_CHANNEL_FROM_TYPE_BIT:()=>uD,DATA_FREEZE_TIMING:()=>VD,DOC_BILLING_CN:()=>xk,DOC_BILLING_OVERSEA:()=>Uk,DOC_URL:()=>Lk,DTLS_STATE_UNKNOWN:()=>ID,ENV_NAME:()=>Wk,EXCHANGE_SDP_TIMEOUT:()=>OD,IS_WORKER:()=>Rk,IS_WORKLET:()=>Ck,KIBANA_EVENT:()=>ND,LOCAL_STREAM_PUBLISH_STATE:()=>UD,LOGGER_CMD_TYPE:()=>Hk,LOGGER_DOMAIN:()=>Vk,LOGGER_DOMAIN_OVERSEA:()=>Fk,LOG_LEVEL:()=>Gk,LOG_LEVEL_NAME:()=>XD,MAIN_STREAM_MSID:()=>hD,MAX_RTT:()=>tN,MICROPHONE_COMMUNICATIONS:()=>YD,MICROPHONE_DEFAULT:()=>KD,MUTE_ALL_BIT:()=>lD,NAME:()=>$k,NETWORK_TYPE:()=>Jk,NOT_SUPPORTED_H264:()=>xD,PAUSED_RETRY_COUNT:()=>JD,PEERCONNECTION_CONNECTING_TIMEOUT:()=>WD,PEER_CONNECTION_STATE:()=>AD,PEER_LEAVE_REASON:()=>QD,RECOVER_CAPTURE_INTERVAL:()=>$D,REMOTE_STREAM_TYPE_AUX:()=>_D,REMOTE_STREAM_TYPE_MAIN:()=>mD,RENDER_FREEZE_TIMING:()=>FD,SCHEDULE_DOMAIN:()=>GD,SCHEDULE_TIMEOUT:()=>jD,SDP_SEMANTICS_PLAN_B:()=>LD,SDP_SEMANTICS_UNIFIED_PLAN:()=>MD,SECOND_HOST:()=>wk,SIGNAL_PING_PONG_INTERVAL:()=>zk,SIGNAL_PING_TIMEOUT:()=>jk,SIGNAL_RECONNECTION_COUNT:()=>DD,SMALL_STAT_BIT:()=>nD,SPEAKER_DEFAULT:()=>qD,STORAGE_EXPIRES_TIME:()=>Kk,STREAM_TYPE_BIG:()=>BD,STREAM_TYPE_SMALL:()=>HD,SUBSCRIBE_SMALL_RETRY_COUNT:()=>ZD,SYNC_USER_LIST_INTERVAL:()=>wD,Scene:()=>iD,THIRD_HOST:()=>Pk,TRANSPORT_DIRECTION:()=>eD,TRTC_ERROR_ASSISTANCE:()=>Bk,TRTC_QUALITY_BAD:()=>vD,TRTC_QUALITY_DISCONNECTED:()=>SD,TRTC_QUALITY_EXCELLENT:()=>gD,TRTC_QUALITY_GOOD:()=>ED,TRTC_QUALITY_POOR:()=>TD,TRTC_QUALITY_UNKNOWN:()=>fD,TRTC_QUALITY_VERY_BAD:()=>yD,UPDATE_OFFER_TIMEOUT:()=>PD,VIDEO_MUTE_BIT:()=>cD,VIDEO_STAT_BIT:()=>rD,WEBGL_ATTRIBUTES:()=>rN,audioProfileMap:()=>qk,defaultBigVideoProfile:()=>Xk,defaultSmallVideoProfile:()=>Qk,getRetryCount:()=>bD,getScriptDir:()=>bk,innerVersion:()=>vk,loggerProxy:()=>kk,screenProfileMap:()=>Zk,setLoggerProxy:()=>Dk,setRetryCount:()=>CD,setVersion:()=>Sk,version:()=>yk,videoProfileMap:()=>Yk});var vk="4.15.00.1600",yk="5.0.0";function Sk(e){yk=e;let[t,i,r]=e.split(".").map(e=>parseInt(e,10));vk="".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 Ik,Ak,Rk="undefined"!=typeof importScripts,Ck="undefined"!=typeof registerProcessor,bk=()=>{let e=Rk?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},kk="",Dk=e=>kk=e,Nk="web.sdk.qcloud.com",wk="web.sdk.tencent.cn",Pk="web.sdk.cloud.tencent.cn",Ok="https://console.cloud.tencent.com/trtc",Mk="https://".concat(Nk,"/trtc/webrtc/doc"),Lk="".concat(Mk,"/zh-cn/"),xk="https://cloud.tencent.com/document/product/647/85386",Uk="https://trtc.io/document/56025",Vk="https://yun.tim.qq.com",Fk="https://apisgp.my-imcloud.com",Bk="trtc_error_assistance",Hk={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Wk={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Gk=((Ak=Gk||{})[Ak.TRACE=0]="TRACE",Ak[Ak.DEBUG=1]="DEBUG",Ak[Ak.INFO=2]="INFO",Ak[Ak.WARN=3]="WARN",Ak[Ak.ERROR=4]="ERROR",Ak[Ak.NONE=5]="NONE",Ak),jk=18e3,zk=2e3,Jk={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},Kk=6048e5,qk={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}},Yk={"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}},Xk=Yk["480p_2"],Qk=Yk["120p_2"],Zk={"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}},$k={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",LOADSTART:"loadstart",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",FULLSCREEN_CHANGE:"fullscreenchange",RESIZE:"resize",TIME_UPDATE:"timeupdate"},eD={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},tD={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},iD=((Ik=iD||{}).LIVE="live",Ik.RTC="rtc",Ik),rD=1,nD=2,oD=4,sD=8,aD=64,cD=16,lD=112,dD=128,uD=256,hD="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",pD="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",mD=$k.MAIN,_D=$k.AUXILIARY,fD=0,gD=1,ED=2,TD=3,vD=4,yD=5,SD=6,ID="unknown",AD={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},RD=1/0;function CD(e){RD=e}function bD(){return RD}var kD,DD=30,ND={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",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",VIDEO_ENCODE_RESUME_DURING_CALL:"video-encode-resume-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call",AUDIO_ENCODE_RESUME_DURING_CALL:"audio-encode-resume-during-call",VIDEO_DECODE_FAILED_DURING_CALL:"video-decode-failed-during-call",VIDEO_DECODE_RESUME_DURING_CALL:"video-decode-resume-during-call",AUDIO_DECODE_FAILED_DURING_CALL:"audio-decode-failed-during-call",AUDIO_DECODE_RESUME_DURING_CALL:"audio-decode-resume-during-call",VIDEO_HARDWARE_DECODE_FAILED:"video-hardware-decode-failed",VIDEO_HARDWARE_DECODE_RESUME:"video-hardware-decode-resume"},wD=1e4,PD=1e4,OD=1e4,MD="unified-plan",LD="plan-b",xD=1028,UD=((kD=UD||{})[kD.UNPUBLISH=-1]="UNPUBLISH",kD[kD.PUBLISHING=0]="PUBLISHING",kD[kD.PUBLISHED=1]="PUBLISHED",kD),VD=500,FD=1e3,BD=$k.BIG,HD=$k.SMALL,WD=1e4,GD={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"},jD=2e3,zD={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},JD=5,KD="default",qD=KD,YD="communications",XD=Object.keys(Gk),QD=["normal leave","timeout leave","kick","role change"],ZD=10,$D=2e3,eN=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],tN=1e4,iN=14,rN={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},nN=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())})},oN=Symbol(32),sN=Symbol(16),aN=Symbol(8),cN=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 nN(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(oN)}readU16(){return this.read(sN)}readU8(){return this.read(aN)}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===oN){if(r(4))return;e=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===sN){if(r(2))return;e=t[0]<<8|t[1]}else if(this.need===aN){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}};cN.U32=oN,cN.U16=sN,cN.U8=aN;var lN=128;function dN(e){let t=new cN;for(;e>=128;)t.malloc(1)[0]=255&e|lN,e>>>=7;return t.malloc(1)[0]=255&e,t.buffer||new Uint8Array(0)}function uN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=new cN,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(dN(e));break;case"string":i.malloc(1)[0]=2|r;let o=(new TextEncoder).encode(e);i.write(dN(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 cN;if(Array.isArray(e))for(let t=0;t<e.length;t++){let i=uN(e[t],t+1);i&&a.write(i)}else{let t=1;for(let i in e){let r=uN(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(dN(a.buffer.length)),i.write(a.buffer)))}return i.buffer||new Uint8Array(0)}var hN=class{constructor(){qb(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 pN(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 mN(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function _N(e,t){return e[t]}function fN(e,t,i){return(new TextDecoder).decode(function(e,t,i){return e.slice(t,t+i)}(e,t,i))}var gN=0,EN=2654435769,TN=16,vN=2,yN=7;function SN(e,t){let i=new hN,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,gN);gN=gN+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 hN;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,qN(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+vN+yN)%8;r&&(r=8-r);let n=i+1+vN+yN+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<vN;)if(d<8&&(a[d]=255&Math.floor(256*Math.random()),d+=1,h+=1),8===d){IN(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){IN(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<yN;)if(d<8&&(a[d]=0,d+=1,h+=1),8===d){IN(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 IN(e,t,i,r,n,o){for(let s=0;s<8;s++)e[s]^=r[s];!function(e,t,i,r){let n=mN(e,0),o=mN(e,4),s=[];for(let c=0;c<4;c++)s[c]=mN(t,4*c);let a=0;for(let c=0;c<TN;c++)a+=EN,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;pN(i,n,r),pN(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 AN=function(){return new URLSearchParams(location.search).get("trtc_env")||""},RN=function(e){return e.includes(".")?e:"".concat(e).concat(".rtc.qq.com")},CN=e=>Number(e)<14e8,bN=function(e,t){let i;i=kk||(CN(e)?Fk:Vk);let r=Math.floor(Math.random()*Fb(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},kN="unknown";function DN(){!function(){var e;wN||(wN=!0,null==(e=navigator.connection)||e.addEventListener("typechange",NN))}();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?PN(r,n):kN}function NN(){dM.warn("netType changed",DN())}var wN=!1;function PN(e,t){if(Jk[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function ON(e){kN=PN(e)}function MN(){return Jk[DN()]}function LN(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 xN(e){return UN(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function UN(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function VN(e){return 4*FN(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function FN(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var BN="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},HN=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},WN=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 GN(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:GN(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function jN(e){return e>8?3e4:1e3*GN(e)}function zN(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var JN=e=>"function"==typeof e,KN=e=>void 0===e,qN=e=>"string"==typeof e,YN=e=>"number"==typeof e,XN=e=>"boolean"==typeof e,QN=e=>"object"===zN(e),ZN=e=>"array"===zN(e),$N=e=>zN(e)==="MediaStreamTrack".toLowerCase(),ew=e=>e.isRemote,tw=e=>"promise"===zN(e),iw=e=>JN(e)&&e.prototype.constructor===e,rw=e=>iw(e)?e.prototype.constructor.name:"",nw="undefined"!=typeof AudioWorkletNode,ow="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype;function sw(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 cw=e=>+e<10?"0".concat(e):e,lw=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=cw(i[1])+cw(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},dw=Object.prototype.hasOwnProperty;function uw(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(WN(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(dw.call(e,t))return!1;return!0}return!1}function hw(e,t){return{userId:t,hasAudio:!!(e&sD),hasVideo:!!(e&rD),hasAuxiliary:!!(e&oD),hasSmall:!!(e&nD),audioMuted:!!(e&aD),videoMuted:!!(e&cD),audioAvailable:!(!(e&sD)||e&aD),videoAvailable:!(!(e&rD)||e&cD),hasDatachannel:!!(e&uD)}}function pw(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!KN(e.username)&&!KN(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",KN(e.credentialType)||(t.credentialType=e.credentialType)),t}function mw(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!qN(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 _w=function(e,t,i,r){if(!QN(e)||!QN(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],!(KN(t[n])||i&&i.includes(n)))if(QN(e[n])&&QN(t[n]))o+=_w(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=fw(t[n]),o+=1)}return o};function fw(e){if(ZN(e)){let t=[];return e.forEach((e,i)=>{t[i]=fw(e)}),t}if(QN(e)){let t={};return Object.keys(e).forEach(i=>{t[i]=fw(e[i])}),t}return e}var gw=e=>{let t=[];if(ZN(e))t=[...e];else if(qN(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},Ew=e=>qN(e)?document.getElementById(e):e,Tw=()=>(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(ZN(e))return"[".concat(e.map(e=>vw(e,{keysToInclude:i,keysToExclude:r})).join(","),"]");if(!WN(e)||!ZN(i)&&!ZN(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]=WN(e[s])||ZN(e[s])?JSON.parse(vw(e[s],{keysToExclude:r,keysToInclude:i})):e[s])}),JSON.stringify(t)}catch(kD){return"{}"}}function yw(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 Sw(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Iw=()=>{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},Aw=e=>Xb(null,null,function*(){return new Promise((t,i)=>{let r;if(qN(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 dk({code:ck.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}})}),Rw=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},Cw=e=>(Object.keys(e).forEach(t=>{YN(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(WN(e[t])||ZN(e[t]))&&Cw(e[t])}),e);function bw(e,t){return new Promise(i=>{let r=setTimeout(i,e);t&&t(r)})}function kw(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 Dw(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function Nw(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===$k.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(Ik){return""}}function ww(e,t){return e.width*e.height===t.width*t.height?1:Iw()&&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 Pw(e){return 90===e||270===e}function Ow(e){return Xb(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 Mw(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]=Mw(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]=Mw(e[r],t)}),i}return e}var Lw=(e=>(e[e.END_REPORT=2001]="END_REPORT",e[e.LOG=2002]="LOG",e[e.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",e))(Lw||{});function xw(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 KN(r)||(n=Wb(Hb({},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 SN(uN(n),i)}catch(TM){return JSON.stringify(e)}}function Uw(e,t){let i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i.buffer}function Vw(e){return(65535&e)>>>0}function Fw(e){return(4294901760&e)>>>0}function Bw(e){let t=function(e){try{let t={},i=0;t.totalLength=mN(e,i),i+=4,t.version=mN(e,i),i+=4,t.encryption=_N(e,i),i+=1,t.uinType=_N(e,i),i+=1,t.uinLength=mN(e,i),i+=4,t.uin=t.uinLength>4?fN(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=Hw(n,t),s=7&o[0],a=e.length-1-s-vN-yN,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<=vN;)if(h<8)h++,m++;else if(8===h){let r=Ww(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=Ww(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<=yN;)if(h<8)o[h],d[h],h++,m++;else if(8===h){if(i>=e.length)break;let r=Ww(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=mN(e,i),i+=4,t.seqNo=mN(e,i),i+=4,t.retCode=mN(e,i),i+=4,t.retStrLength=mN(e,i),i+=4,t.retStr=t.retStrLength?fN(e,i,t.retStrLength-4):"",i+=t.retStrLength-4,t.serviceCmdLength=mN(e,i),i+=4,t.serviceCmd=t.serviceCmdLength?fN(e,i,t.serviceCmdLength-4):"",i+=t.serviceCmdLength-4,t.cookieLength=mN(e,i),i+=4,t.cookie=t.cookieLength?fN(e,i,t.cookieLength-4):"",i+=t.cookieLength-4,t.flag=mN(e,i),i+=4,t.busiBuffLength=mN(e,i),i+=4,t.busiBuff=t.busiBuffLength?fN(e,i,t.busiBuffLength-4):"",i+=t.busiBuffLength-4,t}catch(t){}}(e);return null==t?void 0:t.busiBuff}function Hw(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=EN*TN>>>0;for(let o=0;o<TN;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-=EN,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 Ww(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:Hw(c,o),bufPos:t+8}}var Gw="undefined"!=typeof TextDecoder?new TextDecoder:void 0;function jw(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:Bw(new Uint8Array(e))||(Gw?Gw.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(SM){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 zw(e){return Xb(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 dM.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(aw()-t,"ms")),r}catch(kD){return i}})}var Jw=Object.prototype.hasOwnProperty,Kw=e=>"function"==typeof e,qw=e=>void 0===e,Yw=e=>"string"==typeof e,Xw=e=>"boolean"==typeof e,Qw=e=>e.isRemote,Zw=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 $w=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)=>Xb(this,null,function*(){let l=a||this;try{let i=yield t.apply(l,c);h>0&&s&&s.call(this,h),h=0,e(i)}catch(f){let t=()=>{clearTimeout(p),h=0,m=2,i(f)},s=()=>{2!==m&&h<(Kw(d)?d():d)?(h++,m=1,Kw(n)&&n.call(this,h,t),p=window.setTimeout(()=>{p=-1,_(e,i)},Kw(u)?u(h):u)):(t(),Kw(o)&&o.call(this,f))};Kw(r)?r.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retriedCount:h}):s()}});return new Promise(_)}},eP=class e{constructor(e){qb(this,"_parentPath"),qb(this,"userId"),qb(this,"remoteUserId"),qb(this,"id"),qb(this,"sdkAppId"),qb(this,"type"),qb(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!Xw(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}getFullId(){return this._parentPath&&this.id?"".concat(this._parentPath,"-").concat(this.id):this._parentPath?this._parentPath:this.id}createChild(t){let i=new e({id:t.id,userId:qw(t.userId)?this.userId:t.userId,sdkAppId:qw(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:qw(t.type)?this.type:t.type,isLocal:qw(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:qw(t.remoteUserId)?this.remoteUserId:t.remoteUserId});return i.bindParent(this),i}bindParent(e){let t=e.getFullId();this._parentPath!==t&&(this.debug("bind logger parent: ".concat(e.id)),this._parentPath=t,this.userId=e.userId||this.userId,this.sdkAppId=e.sdkAppId||this.sdkAppId)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId,r=this.getFullId();t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(r).concat(i?"|".concat(i):"","]")),dM.log(e,t,qw(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(Zw(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(Jw.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)}},tP={};zb(tP,{ANDROID_VERSION:()=>_P,CHROME_MAJOR_VERSION:()=>vO,CHROME_VERSION:()=>SO,EDGE_VERSION:()=>SP,EDG_MAJOR_VERSION:()=>RP,EDG_VERSION:()=>AP,ELECTRON_MAJOR_VERSION:()=>IO,FIREFOX_MAJOR_VERSION:()=>vP,FIREFOX_VERSION:()=>TP,HUAWEI_VERSION:()=>sO,IE_VERSION:()=>xP,IOS_MAIN_VERSION:()=>wO,IOS_VERSION:()=>kO,IPADQQB_VERSION:()=>KP,IS_ANDROID:()=>mP,IS_ANDROID_WEBVIEW:()=>bO,IS_ANY_SAFARI:()=>RO,IS_CHROME:()=>EO,IS_CHROME_OS:()=>QP,IS_CHROMIUM_128_TO_143:()=>yO,IS_CHROMIUM_BASE:()=>gO,IS_DESKTOP_IOS_CHROME:()=>LO,IS_EDG:()=>IP,IS_EDGE:()=>yP,IS_ELECTRON:()=>eO,IS_FIREFOX:()=>EP,IS_HEADLESS_CHROME:()=>TO,IS_HONOR:()=>oO,IS_HUAWEI:()=>nO,IS_HUAWEIBROWSER:()=>rO,IS_IE:()=>LP,IS_IE8:()=>MP,IS_IOS:()=>hP,IS_IOS_13_OR_14:()=>MO,IS_IOS_15_1:()=>OO,IS_IOS_CHROME:()=>fO,IS_IPAD:()=>cP,IS_IPADQQB:()=>JP,IS_IPAD_PRO:()=>lP,IS_IPHONE:()=>dP,IS_IPOD:()=>uP,IS_LINUX:()=>XP,IS_LOCAL:()=>xO,IS_MAC:()=>YP,IS_MACQQB:()=>jP,IS_MIBROWSER:()=>tO,IS_MQQB:()=>BP,IS_NATIVE_ANDROID:()=>gP,IS_OLD_ANDROID:()=>fP,IS_OPENHARMONY:()=>pO,IS_OPPOBROWSER:()=>lO,IS_SAFARI:()=>AO,IS_SAFARI_15_1:()=>PO,IS_SAMSUNGBROWSER:()=>aO,IS_SOGOU:()=>kP,IS_SOGOUM:()=>CP,IS_TBS:()=>NP,IS_UCBROWSER:()=>$P,IS_VIVOBROWSER:()=>uO,IS_WECHAT:()=>UP,IS_WIN:()=>qP,IS_WQQB:()=>WP,IS_WX:()=>ZP,IS_X5MQQB:()=>FP,IS_XWEB:()=>PP,MACQQB_VERSION:()=>zP,MI_VERSION:()=>iO,MQQB_VERSION:()=>HP,OPENHARMONY_VERSION:()=>mO,OPPO_VERSION:()=>dO,SAFARI_VERSION:()=>CO,SAMSUNG_VERSION:()=>cO,SOGOUM_VERSION:()=>bP,SOGOU_VERSION:()=>DP,TBS_VERSION:()=>wP,UA_DATA_STRING:()=>WO,USER_AGENT:()=>iP,VIVO_VERSION:()=>hO,WECHAT_VERSION:()=>VP,WQQB_VERSION:()=>GP,XWEB_VERSION:()=>OP,browserInfo:()=>VO,getBrowserCoreNumber:()=>eM,getBrowserInfo:()=>FO,getChromeMajorVersion:()=>_O,getDeviceModel:()=>YO,getDeviceModelFromUA:()=>XO,getGPUInfo:()=>zO,getOSName:()=>ZO,getOSNumber:()=>$O,getOSString:()=>tM,getOSType:()=>rM,getTerminalType:()=>iM,getUserAgentData:()=>GO,isAMDGPU:()=>JO,isAppleSiliconGPU:()=>qO,isLocalStorageEnabled:()=>UO,isMobile:()=>HO,isNvidiaGPU:()=>KO,isRealIOS:()=>pP,isVersionLargerThan:()=>NO,isVersionSmallerThan:()=>DO});var iP="undefined"==typeof navigator?"":navigator.userAgent,rP=e=>new RegExp(e,"i").test(iP),nP=e=>{if(rP(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=iP.match(t);if(i&&i[1])return i[1]}return""},oP=e=>{if(rP(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=iP.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},sP=/AppleWebKit\/([\d.]+)/i.exec(iP),aP=sP?parseFloat(sP[1]):NaN,cP=rP("iPad"),lP="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&rP("Macintosh"),dP=rP("iPhone")&&!cP,uP=rP("iPod"),hP=dP||cP||uP||lP,pP=()=>{try{return hP&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch(e){return hP}},mP=rP("Android"),_P=function(){if(mP){let e=iP.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}(),fP=mP&&rP("webkit")&&_P<2.3,gP=mP&&_P<5&&aP<537,EP=rP("Firefox"),TP=nP("Firefox"),vP=oP("Firefox"),yP=rP("Edge"),SP=nP("Edge"),IP=rP("Edg"),AP=nP("Edg"),RP=oP("Edg"),CP=rP("SogouMobileBrowser"),bP=nP("SogouMobileBrowser"),kP=rP("MetaSr\\s"),DP=nP("MetaSr\\s"),NP=rP("TBS"),wP=nP("TBS"),PP=rP("XWEB"),OP=nP("XWEB"),MP=rP("MSIE\\s8\\.0"),LP=rP("MSIE\\/\\d+"),xP=function(){if(LP){let e=/MSIE\s(\d+)\.\d/.exec(iP),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(iP)&&/rv:11.0/.test(iP)&&(t=11),t}return NaN}(),UP=rP("(micromessenger|webbrowser)"),VP=nP("MicroMessenger"),FP=!NP&&rP("MQQBrowser")&&rP("COVC"),BP=!NP&&rP("MQQBrowser")&&!rP("COVC"),HP=BP||FP?nP("MQQBrowser"):"",WP=!NP&&rP(" QQBrowser"),GP=nP(" QQBrowser"),jP=!NP&&rP("QQBrowserLite"),zP=nP("QQBrowserLite"),JP=!NP&&rP("MQBHD"),KP=nP("MQBHD"),qP=rP("Windows"),YP=!hP&&rP("MAC OS X"),XP=!mP&&rP("Linux"),QP=rP("CrOS"),ZP=rP("MicroMessenger"),$P=rP("UCBrowser"),eO=rP("Electron"),tO=rP("MiuiBrowser"),iO=nP("MiuiBrowser"),rO=rP("HuaweiBrowser"),nO=rP("Huawei")||rP("HUAWEI"),oO=rP("Honor")||rP("HONOR"),sO=nP("HuaweiBrowser"),aO=rP("SamsungBrowser"),cO=nP("SamsungBrowser"),lO=rP("HeyTapBrowser"),dO=nP("HeyTapBrowser"),uO=rP("VivoBrowser"),hO=nP("VivoBrowser"),pO=rP("OpenHarmony"),mO=nP("OpenHarmony"),_O=()=>oP("Chrome"),fO=rP("CriOS"),gO=rP("Chrome"),EO=!yP&&!kP&&!CP&&!NP&&!PP&&!IP&&!WP&&!tO&&!rO&&!aO&&!lO&&!uO&&gO,TO=rP("HeadlessChrome"),vO=_O(),yO=gO&&vO>=128&&vO<=143,SO=nP("Chrome"),IO=oP("Electron"),AO=!gO&&!BP&&!FP&&!jP&&!JP&&rP("Safari"),RO=AO||hP,CO=nP("Version"),bO=/Android.*(wv|.0.0.0)/.test(iP),kO=(()=>{if(lP)return CO;if(hP){let e=iP.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})();function DO(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 NO(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 wO=Number(kO.split(".")[0]),PO="15.1"===CO,OO="15.1"===kO,MO=(()=>{let e=Number(kO.split(".")[0]);return 14===e||13===e})(),LO=fO&&"11.1.1"===CO,xO="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),UO=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(EM){e=!1}return e}})(),VO=FO();function FO(){let e=new Map([[EP,["Firefox",TP]],[IP,["Edg",AP]],[EO,["Chrome",SO]],[fO,["ChiOS",nP("CriOS")]],[AO&&!fO,["Safari",CO]],[NP,["TBS",wP]],[PP,["XWEB",OP]],[UP&&dP,["WeChat",VP]],[WP,["QQ(Win)",GP]],[BP,["QQ(Mobile)",HP]],[FP,["QQ(Mobile X5)",HP]],[jP,["QQ(Mac)",zP]],[JP,["QQ(iPad)",KP]],[tO,["MI",iO]],[rO,["HW",sO]],[aO,["Samsung",cO]],[lO,["OPPO",dO]],[uO,["VIVO",hO]],[yP,["EDGE",SP]],[CP,["SogouMobile",bP]],[kP,["Sogou",DP]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var BO=null;function HO(){return BO&&"boolean"==typeof BO.mobile?BO.mobile:mP||hP||dP||cP||pO}var WO="";function GO(){return Xb(this,null,function*(){if(BO)return BO;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(BO=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!WO&&(WO="UAData: ".concat(BO.platform,"/").concat(BO.platformVersion),BO.architecture&&BO.bitness&&(WO+=" ".concat(BO.architecture,"/").concat(BO.bitness)),BO.mobile&&(WO+=" mobile"),BO.model&&(WO+=" model: ".concat(BO.model.replace(/\s+/g,"/"))),BO.fullVersionList&&(WO+=" ".concat(BO.fullVersionList.filter(e=>"Not/A)Brand"!==e.brand).map(e=>"".concat(e.brand,"/").concat(e.version)).join(",")))),BO}catch(e){return null}})}var jO="";function zO(){try{if(jO)return jO;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 jO="".concat(e," ").concat(r)}return""}catch(e){return""}}function JO(){try{let e=zO();return e.includes("AMD")||e.includes("ATI")}catch(e){return!1}}function KO(){try{let e=zO();return e.includes("NVIDIA")||e.includes("GeForce")}catch(e){return!1}}function qO(){try{return zO().includes("Apple M")}catch(e){return!1}}function YO(){return(null==BO?void 0:BO.model)||XO()||""}function XO(){let e=iP.match(/;\s*([^;)]+)\s+Build\//);return null!=e&&e[1]?e[1].trim():null}var QO=new Map([[mP,"Android"],[hP,"iOS"],[qP,"Windows"],[YP,"MacOS"],[XP,"Linux"],[QP,"ChromeOS"]]),ZO=function(){return QO.get(!0)?QO.get(!0):BO?BO.platform:"unknown"};function $O(){return qP?1:mP?2:YP?3:hP?4:XP?5:QP?6:pO?7:0}function eM(){return UP||PP?4:gO?1:AO?2:EP?3:0}var tM=()=>{let e=ZO();return null!=BO&&BO.platformVersion?e+="/".concat(BO.platformVersion):hP?e+="/".concat(kO):mP&&(e+="/".concat(_P)),e+="/".concat(VO.name,"/").concat(AO&&!fO?VO.version:VO.version.split(".")[0]),null!=BO&&BO.architecture&&(e+="/".concat(BO.architecture)),e};function iM(){return mP?4:dP?2:cP?3:YP?12:qP?5:XP?13:pO?22:1}function rM(){return mP?"Android":dP?"iPhone":cP?"iPad":YP?"Mac":qP?"Windows":XP?"Linux":"unknown"}var nM,oM=new(Jb(Qb(),1).default),sM=((nM=sM||{}).ROOM_DESTROY="1",nM.JOIN_START="21",nM.JOIN_SCHEDULE_SUCCESS="22",nM.JOIN_SIGNAL_CONNECTION_START="23",nM.JOIN_SIGNAL_CONNECTION_END="24",nM.JOIN_SEND_CMD="25",nM.JOIN_RECEIVED_CMD_RES="26",nM.JOIN_SUCCESS="27",nM.JOIN_FAILED="28",nM.LEAVE_START="51",nM.LEAVE_SEND_CMD="52",nM.LEAVE_SUCCESS="53",nM.PUBLISH_START="61",nM.SEND_FIRST_VIDEO_FRAME="62",nM.PUBLISH_FAILED="63",nM.SUBSCRIBE_START="81",nM.SUBSCRIBE_SUCCESS="82",nM.SUBSCRIBE_FAILED="84",nM.UNSUBSCRIBE_SUCCESS="83",nM.LOCAL_TRACK_CAPTURE_START="101",nM.LOCAL_TRACK_CAPTURE_SUCCESS="102",nM.LOCAL_TRACK_CAPTURE_FAILED="103",nM.LOCAL_TRACK_PUBLISHED="104",nM.LOCAL_TRACK_UNPUBLISHED="105",nM.LOCAL_TRACK_REPLACED="106",nM.SWITCH_DEVICE_SUCCESS="107",nM.TRACK_MUTED="108",nM.TRACK_UNMUTED="109",nM.REMOTE_TRACK_SUBSCRIBED="110",nM.REMOTE_TRACK_UNSUBSCRIBED="111",nM.LOCAL_TRACK_RECAPTURE="112",nM.LOCAL_AUDIO_STARTED="113",nM.LOCAL_AUDIO_STOPPED="114",nM.REMOTE_AUDIO_STARTED="115",nM.REMOTE_AUDIO_STOPPED="116",nM.PLAY_TRACK_START="151",nM.PLAYER_STATE_CHANGED="152",nM.VIDEO_LOADED_DATA="153",nM.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",nM.AUDIO_CONTEXT_LONG_SUSPENDED="155",nM.REMOTE_VIDEO_PLAY_START="156",nM.REMOTE_VIDEO_PLAY_FINISH="157",nM.SIGNAL_CONNECTION_STATE_CHANGED="201",nM.PEER_CONNECTION_STATE_CHANGED="202",nM.SINGLE_CONNECTION_STAT="203",nM.SPC_RECONNECTED="204",nM.HEARTBEAT_REPORT="251",nM.RECEIVED_PUBLISHED_USER_LIST="252",nM.REMOTE_PUBLISH_STATE_CHANGED="253",nM.AUDIO_LEVEL_INTERVAL="260",nM.NETWORK_QUALITY="261",nM.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",nM.QUALITY_LIMITATION_CHANGED="263",nM.LOG="264",nM.AUDIO_PROCESSOR_DEBUG="265",nM.SSO_SWITCH="266",nM.SEI_MESSAGE="267",nM.USER_PAUSE_IN_PIP="268",nM.USER_RESUME_IN_PIP="269",nM.ENTER_PICTURE_IN_PICTURE="270",nM.LEAVE_PICTURE_IN_PICTURE="271",nM.SWITCH_ROOM_START="401",nM.SWITCH_ROOM_SUCCESS="407",nM.SWITCH_ROOM_FAILED="408",nM),aM=sM,cM=new class{constructor(){qb(this,"enable",!1),qb(this,"ssoFailCount",0),oM.on("22",e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.sso&&oM.emit("266",{enable:!0})}),oM.on("266",e=>{let{enable:t}=e;this.enable=t})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&oM.emit("266",{enable:!1})}},lM=class e{constructor(){qb(this,"_isEnableUploadLog",!0),qb(this,"_localJoinedUser",new Map),qb(this,"_queue",[]),qb(this,"_timeoutId",-1),qb(this,"_logLevel",1),qb(this,"_logLevelToUpload",2),!Rk&&!Ck&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){oM.on(aM.JOIN_SCHEDULE_SUCCESS,e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.logLevelToUpload&&Gk[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),oM.on(aM.JOIN_START,e=>{let{params:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),oM.on(aM.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(qN(i.userId)&&YN(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 Xb(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:fk(),sdkAppId:String(r),userId:i,version:yk,log:n.map(e=>e.log).join("\n")},s=JSON.stringify(o),a=cM.enable?xw(o,2002,r):s;yield this.uploadLogWithRetry(a,r,a instanceof Uint8Array,s),n.forEach(e=>e.uploaded=!0)}}catch(TM){}let i=t.filter(e=>!e.uploaded);i.length>0&&(this._queue=i.concat(this._queue))})}uploadLogWithRetry(e,t,i,r){return $w({retryFunction:()=>jw({url:bN(t,Hk.LOG),body:e,timeout:5e3,priority:"low"}).then(e=>{i&&"ok"!==e.data&&(cM.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(_k()),"[".concat(gk(t),"] <").concat(Gk[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){KN(Gk[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(qN(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(Ik){return""}}addLogToQueue(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0,o={log:t.reduce((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim(),""),level:e,userId:r,sdkAppId:n,forAllJoinedClients:i};oM.emit(aM.LOG,{log:o}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(o)}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;if(i.unshift(this.getPrefix(t)),this.addLogToQueue(t,i,r,n,o),t<this._logLevel)return;let a=(null==(s=Gk[t])?void 0:s.toLowerCase())||"info";e.PRINT_LOG_TAG?console[a]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...i):console[a](...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){if(e.parent instanceof eP){let t=e,{parent:i}=t,r=Gb(t,["parent"]),n=new eP(r);return n.bindParent(i),n}return new eP(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Gk[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};qb(lM,"PRINT_LOG_TAG",!(hP||mP||TO));var dM=new lM,uM=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)})},hM=new class{constructor(){qb(this,"_prefix","TRTC"),qb(this,"_queue",new Map)}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){UO()&&(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(TM){return!1}return!1}).forEach(e=>localStorage.removeItem(e)))}doFlush(){if(UO())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(EM){dM.warn(EM)}}getItem(e){if(!UO())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(Ik){dM.warn(Ik)}}setItem(e,t){if(UO())try{let i={expiresIn:Date.now()+Kk,value:t};this._queue.set(this.getRealKey(e),i)}catch(kD){dM.warn(kD)}}deleteItem(e){if(!UO())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(Ik){return dM.warn(Ik),!1}}clear(){if(UO())try{localStorage.clear()}catch(EM){dM.warn(EM)}}},pM={};zb(pM,{HTTPS_API:()=>ix,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>Ax,IS_GET_CAPABILITIES_SUPPORTED:()=>Ix,IS_GET_SETTINGS_SUPPORTED:()=>Sx,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>yx,IS_INSERTABLE_STREAM_SUPPORTED:()=>Rx,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>Vx,IS_RTC_RTP_SENDER_SUPPORTED:()=>Ex,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>Cx,IS_SEI_SUPPORTED:()=>bx,IS_SPC_SUPPORTED:()=>fx,basis:()=>Ox,capabilityCheck:()=>xx,checkSystemRequirementsInternal:()=>XL,decodeSupportStatus:()=>YL,detectVideoCodecCapabilities:()=>Hx,detectVideoDecoderCapabilities:()=>Gx,detectVideoEncoderCapabilities:()=>Wx,encodeSupportStatus:()=>qL,getBrowserInfo:()=>BL,getDisplayResolution:()=>nx,getH264ProfileLevelIds:()=>jx,isAddTransceiverSupported:()=>_x,isBrowserSupported:()=>HL,isCanvasCaptureStreamAPISupported:()=>ax,isCanvasSmallStreamSupported:()=>cx,isGetReceiversSupported:()=>hx,isGetSendersSupported:()=>px,isGetTransceiversSupported:()=>mx,isGetUserMediaSupported:()=>ox,isMediaDevicesSupported:()=>GL,isMediaSessionSupported:()=>Nx,isMediaStreamTrackGeneratorSupported:()=>KL,isMediaStreamTrackProcessorSupported:()=>JL,isReplaceTrackSupported:()=>Tx,isRequestVideoFrameCallbackSupported:()=>Ux,isSIMDSupported:()=>Px,isScaleResolutionDownBySupported:()=>lx,isScreenCaptureApiAvailable:()=>ZL,isSelectedCandidatePair:()=>rx,isSetParametersSupported:()=>vx,isSetSinkIdSupported:()=>$L,isSmallStreamSupported:()=>dx,isStopTransceiverSupported:()=>gx,isTRTCSupported:()=>QL,isUnifiedPlanDefault:()=>ux,isUsedInHttpProtocol:()=>zL,isWebAudioSupported:()=>sx,isWebCodecSupported:()=>Dx,isWebCodecsSupported:()=>WL,isWebRTCSupported:()=>kx,isWebTransportSupported:()=>wx});var mM={};zb(mM,{AUDIO_LEVEL_SCALE:()=>sL,AlphaStitchingType:()=>vL,AudioCodecPipelineType:()=>hL,AudioDecoderDowngradeState:()=>HM,AudioPlayerMode:()=>rL,AudioType:()=>KM,BASIC_TYPE:()=>lL,BannedReason:()=>nL,CONNECTION_CLOSED_REASON:()=>kM,CheckPermissionType:()=>EL,ClientEvent:()=>DM,CodecType:()=>pL,ConnectionEvent:()=>bM,ConnectionState:()=>BM,DECODE_FAILED_ERROR_CODE:()=>mL,DenoiserMode:()=>aL,DeviceType:()=>TL,FacingMode:()=>tL,FrameWorkType:()=>CM,LeaveReason:()=>oL,LocalTrackEvent:()=>wM,MULTI_VIDEO_DATA_TYPE:()=>QM,MediaType:()=>zM,MediaTypeLabel:()=>JM,MonitorEventId:()=>ZM,MutedFlag:()=>xM,NetworkQualityValue:()=>$M,PlayerState:()=>PM,ReceiveMode:()=>eL,RemoteStreamType:()=>XM,RemoteTrackEvent:()=>LM,RoomEvent:()=>OM,SMALL_MODE:()=>gL,SceneNumber:()=>UM,StreamEvent:()=>NM,StreamType:()=>YM,SubscribeMediaType:()=>cL,TIMER_TYPE:()=>fL,TRACK_ACTION:()=>jM,TRACK_KIND:()=>GM,TrackEvent:()=>MM,UserRole:()=>FM,UserRoleNumber:()=>VM,VideoCodec:()=>dL,VideoCodecPipelineType:()=>uL,VideoContentHint:()=>_L,VideoDecoderDowngradeState:()=>WM,VideoPlayerMode:()=>iL,VideoType:()=>qM});var _M,fM,gM,EM,TM,vM,yM,SM,IM,AM,RM,CM=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(CM||{}),bM=((RM=bM||{}).TRACK_ADDED="track-added",RM.TRACK_UPDATED="track-updated",RM.TRACK_SUBSCRIBED="track-subscribed",RM.STREAM_ADDED="stream-added",RM.STREAM_REMOVED="stream-removed",RM.STREAM_UPDATED="stream-updated",RM.STREAM_PUBLISHED="stream-published",RM.STREAM_SUBSCRIBED="stream-subscribed",RM.STREAM_UNSUBSCRIBED="stream-unsubscribed",RM.STATE_CHANGED="state-changed",RM.ERROR="error",RM.CONNECTION_STATE_CHANGED="connection-state-changed",RM.FIREWALL_RESTRICTION="firewall-restriction",RM.SEI_MESSAGE="sei-message",RM.CLOSED="closed",RM),kM=(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))(kM||{}),DM=((AM=DM||{}).STREAM_ADDED="stream-added",AM.STREAM_REMOVED="stream-removed",AM.STREAM_UPDATED="stream-updated",AM.STREAM_SUBSCRIBED="stream-subscribed",AM.CONNECTION_STATE_CHANGED="connection-state-changed",AM.PEER_JOIN="peer-join",AM.PEER_LEAVE="peer-leave",AM.MUTE_AUDIO="mute-audio",AM.MUTE_VIDEO="mute-video",AM.UNMUTE_AUDIO="unmute-audio",AM.UNMUTE_VIDEO="unmute-video",AM.CLIENT_BANNED="client-banned",AM.NETWORK_QUALITY="network-quality",AM.AUDIO_VOLUME="audio-volume",AM.SEI_MESSAGE="sei-message",AM.ERROR="error",AM),NM=((IM=NM||{}).PLAYER_STATE_CHANGED="player-state-changed",IM.SCREEN_SHARING_STOPPED="screen-sharing-stopped",IM.CONNECTION_STATE_CHANGED="connection-state-changed",IM.DEVICE_AUTO_RECOVERED="device-auto-recovered",IM.ERROR="error",IM),wM=((SM=wM||{}).DEVICE_AUTO_RECOVERED="1",SM.DEVICE_RECOVER_FAILED="5",SM.DEVICE_CHANGED="2",SM.ERROR="3",SM.PUBLISH_STATE_CHANGED="4",SM.ENCODE_FAILED="6",SM.TRACK_ENDED="7",SM.RENDER="render",SM),PM=(e=>(e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e))(PM||{}),OM=((yM=OM||{}).PEER_JOIN="peer-join",yM.PEER_LEAVE="peer-leave",yM.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",yM.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",yM.BANNED="banned",yM.NETWORK_QUALITY="network-quality",yM.AUDIO_VOLUME="audio-volume",yM.SEI_MESSAGE="sei-message",yM.ERROR="error",yM.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",yM.REMOTE_PUBLISHED="remote-published",yM.REMOTE_UNPUBLISHED="remote-unpublished",yM.FIREWALL_RESTRICTION="firewall-restriction",yM.HEARTBEAT_REPORT="heartbeat-report",yM.CUSTOM_MESSAGE="custom-message",yM.LAYER_DATA="layerData",yM.FIRST_VIDEO_FRAME="first-video-frame",yM.DUMP="dump",yM.AUDIO_FRAME="audio-frame",yM.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",yM.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",yM.NTP_TIME_UPDATED="ntp-time-updated",yM.DATA_CHANNEL_MESSAGE="data-channel-message",yM.ASR_ROBOT_PEER_JOIN="asr-robot-peer-join",yM.ASR_ROBOT_PEER_LEAVE="asr-robot-peer-leave",yM),MM=(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))(MM||{}),LM=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_FAILED_DURING_CALL="decode-failed-during-call",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e.REMOTE_PUBLISH_CHANGED="remote-publish-changed",e.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",e))(LM||{}),xM=((vM=xM||{})[vM.VIDEO=1]="VIDEO",vM[vM.SMALL=2]="SMALL",vM[vM.AUX=4]="AUX",vM[vM.AUDIO=8]="AUDIO",vM[vM.VIDEO_MUTE=16]="VIDEO_MUTE",vM[vM.AUX_MUTE=32]="AUX_MUTE",vM[vM.AUDIO_MUTE=64]="AUDIO_MUTE",vM),UM=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(UM||{}),VM=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(VM||{}),FM=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(FM||{}),BM=(e=>(e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e))(BM||{}),HM=((TM=HM||{}).INITIALIZED="INITIALIZED",TM.STARTING="STARTING",TM.STARTED="STARTED",TM.FAILED="FAILED",TM),WM=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(WM||{}),GM=(e=>(e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e))(GM||{}),jM=(e=>(e.ADD="add",e.REMOVE="remove",e))(jM||{}),zM=(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))(zM||{}),JM={1:"audio",2:"auxVideo",4:"video"},KM=((EM=KM||{})[EM.opus=111]="opus",EM),qM=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(qM||{}),YM=(e=>(e.Big="big",e.Small="small",e))(YM||{}),XM=(e=>(e.Main="main",e.Aux="auxiliary",e))(XM||{}),QM=(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))(QM||{}),ZM=((gM=ZM||{})[gM.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",gM[gM.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",gM[gM.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",gM[gM.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",gM[gM.MUTE_AUDIO=32772]="MUTE_AUDIO",gM[gM.MUTE_VIDEO=32773]="MUTE_VIDEO",gM[gM.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",gM[gM.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",gM[gM.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",gM[gM.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",gM[gM.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",gM[gM.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",gM[gM.SWITCH_CAMERA=32780]="SWITCH_CAMERA",gM[gM.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",gM[gM.REPLACE_VIDEO=32782]="REPLACE_VIDEO",gM[gM.REPLACE_AUDIO=32783]="REPLACE_AUDIO",gM[gM.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",gM[gM.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",gM[gM.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",gM[gM.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",gM[gM.JOIN=32788]="JOIN",gM[gM.LEAVE=32789]="LEAVE",gM[gM.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",gM[gM.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",gM[gM.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",gM[gM.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",gM[gM.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",gM[gM.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",gM[gM.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",gM[gM.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",gM[gM.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",gM[gM.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",gM[gM.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",gM[gM.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",gM[gM.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",gM[gM.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",gM[gM.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",gM[gM.PUBLISH_AUX=32805]="PUBLISH_AUX",gM[gM.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",gM[gM.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",gM[gM.VIDEO_ENCODER=4004]="VIDEO_ENCODER",gM[gM.VIDEO_DECODER=4005]="VIDEO_DECODER",gM),$M=(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))($M||{}),eL=(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))(eL||{}),tL=(e=>(e.user="user",e.environment="environment",e))(tL||{}),iL=(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))(iL||{}),rL=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(rL||{}),nL=(e=>(e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e))(nL||{}),oL=((fM=oL||{})[fM.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",fM[fM.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",fM[fM.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",fM[fM.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",fM[fM.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",fM[fM.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",fM[fM.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",fM[fM.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",fM[fM.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",fM),sL=1e8,aL=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(aL||{}),cL=class{constructor(){qb(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)}},lL=(e=>(e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e))(lL||{}),dL=(e=>(e.H264="h264",e.H265="h265",e.VP8="vp8",e.VP9="vp9",e.AV1="av1",e))(dL||{}),uL=(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))(uL||{}),hL=(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))(hL||{}),pL=(e=>(e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e))(pL||{}),mL=((_M=mL||{})[_M.SUCCESS=0]="SUCCESS",_M[_M.FAILED=1]="FAILED",_M[_M.WEBCODEC_INIT=2]="WEBCODEC_INIT",_M[_M.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",_M[_M.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",_M[_M.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",_M[_M.WASM_INIT=6]="WASM_INIT",_M[_M.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",_M[_M.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",_M[_M.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",_M[_M.TEST=10]="TEST",_M[_M.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",_M),_L=(e=>(e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e))(_L||{}),fL=(e=>(e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e))(fL||{}),gL=(e=>(e.CANVAS="canvas",e.API="api",e))(gL||{}),EL=(e=>(e[e.NONE=0]="NONE",e[e.MICROPHONE=1]="MICROPHONE",e[e.CAMERA=2]="CAMERA",e[e.BOTH=3]="BOTH",e))(EL||{}),TL=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(TL||{}),vL=(e=>(e[e.none=0]="none",e[e.horizontal=1]="horizontal",e[e.vertical=2]="vertical",e))(vL||{}),yL={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"},SL={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(zN(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(zN(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,"()")},IL=(e,t)=>t?"".concat(Mk,"/").concat(e,"/").concat(t):"".concat(Mk,"/").concat(e,"/index.html"),AL=()=>{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(Bk);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 RL(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",s="",a="";JN(SL[t])?o=SL[t](i):qN(SL[t])&&(o=SL[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=AL();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(JN(l[t])?a=l[t](i):qN(l[t])&&(a=l[t]));let d=o;return HN()&&(c&&c[t]&&(JN(c[t])?s=c[t](i):qN(c[t])&&(s=c[t])),s&&(d=n?"".concat(s,"\n请查看文档: ").concat(IL("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(IL("en",a),"\n")),d}var CL,bL,kL=Jb(tk(),1),DL=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];qb(this,"countMap",new Map),qb(this,"distributionMap",new Map),qb(this,"version"),qb(this,"log",dM.createLogger({id:"kv"})),e&&(oM.on("102",e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===$k.AUDIO?501700:511700,cost:i})}),oM.on("103",e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===$k.AUDIO?501700:511700,error:i})}),oM.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(e,t){let i={msg_sdk_basic_info:{uint32_sdk_version:Rw(this.version||yk),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}})}}),str_user_sig:e,bytes_report_token:t};return this.countMap.clear(),this.distributionMap.clear(),i}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(YN(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=ck.UNKNOWN;i&&(YN(i)?r=i:(!KN(i.extraCode)||!KN(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})}},NL=((CL=NL||{})[CL.enterRoom=500700]="enterRoom",CL[CL.exitRoom=500701]="exitRoom",CL[CL.switchRole=500702]="switchRole",CL[CL.destroy=500703]="destroy",CL[CL.startLocalAudio=500704]="startLocalAudio",CL[CL.updateLocalAudio=500705]="updateLocalAudio",CL[CL.stopLocalAudio=500706]="stopLocalAudio",CL[CL.startLocalVideo=500707]="startLocalVideo",CL[CL.updateLocalVideo=500708]="updateLocalVideo",CL[CL.stopLocalVideo=500709]="stopLocalVideo",CL[CL.startScreenShare=500710]="startScreenShare",CL[CL.updateScreenShare=500711]="updateScreenShare",CL[CL.stopScreenShare=500712]="stopScreenShare",CL[CL.startRemoteVideo=500713]="startRemoteVideo",CL[CL.updateRemoteVideo=500714]="updateRemoteVideo",CL[CL.stopRemoteVideo=500715]="stopRemoteVideo",CL[CL.muteRemoteAudio=500716]="muteRemoteAudio",CL[CL.setRemoteAudioVolume=500717]="setRemoteAudioVolume",CL[CL.use=500718]="use",CL[CL.switchRoom=500719]="switchRoom",CL[CL.getPermissions=500720]="getPermissions",CL[CL.sendSEIMessage=5e5]="sendSEIMessage",CL[CL.sendCustomMessage=500001]="sendCustomMessage",CL),wL=(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.FaceDetector=575700]="FaceDetector",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[e.LEBPlayer=596700]="LEBPlayer",e[e.RealtimeTranscriber=597700]="RealtimeTranscriber",e))(wL||{}),PL=(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.FaceDetector=575701]="FaceDetector",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[e.LEBPlayer=596701]="LEBPlayer",e[e.RealtimeTranscriber=597701]="RealtimeTranscriber",e))(PL||{}),OL=(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.FaceDetector=575702]="FaceDetector",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[e.LEBPlayer=596702]="LEBPlayer",e[e.RealtimeTranscriber=597702]="RealtimeTranscriber",e))(OL||{}),ML=((bL=ML||{})[bL.DECODER_TYPE=514700]="DECODER_TYPE",bL[bL.DECODER_HW_SW=514701]="DECODER_HW_SW",bL[bL.DECODE_RESULT=514702]="DECODE_RESULT",bL[bL.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",bL[bL.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",bL[bL.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",bL[bL.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",bL[bL.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",bL[bL.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",bL[bL.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",bL[bL.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",bL[bL.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",bL[bL.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",bL[bL.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",bL[bL.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",bL[bL.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",bL[bL.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",bL[bL.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",bL[bL.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",bL),LL=new DL(!0),xL=new DL(!1),UL=LL,VL={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}},FL=new Map([[EP,["Firefox",TP]],[IP,["Edg",AP]],[EO,["Chrome",SO]],[AO,["Safari",CO]],[NP,["TBS",wP]],[PP,["XWEB",OP]],[UP&&dP,["WeChat",VP]],[WP,["QQ(Win)",GP]],[BP,["QQ(Mobile)",HP]],[FP,["QQ(Mobile X5)",HP]],[jP,["QQ(Mac)",zP]],[JP,["QQ(iPad)",KP]],[tO,["MI",iO]],[rO,["HW",sO]],[aO,["Samsung",cO]],[lO,["OPPO",dO]],[uO,["VIVO",hO]],[yP,["EDGE",SP]],[CP,["SogouMobile",bP]],[kP,["Sogou",DP]]]);function BL(){let e=FL.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var HL=function(){return!($P||yP||IP&&RP<80||EP&&vP<56)},WL=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(e=>e in window)},GL=function(){if(!navigator.mediaDevices)return zL()||dM.error(SL.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter(e=>e in navigator.mediaDevices).length===e.length},jL=!1;function zL(){return"http:"===location.protocol&&!xO&&(jL||dM.error(RL({key:yL.NOT_SUPPORTED_HTTP})),jL=!0,!0)}var JL=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},KL=function(){return!(null==window||!window.MediaStreamTrackGenerator)},qL=function(){return Xb(this,null,function*(){var e,t,i;if(VL.detail.isH264EncodeSupported&&VL.detail.isVp8EncodeSupported)return{isH264EncodeSupported:VL.detail.isH264EncodeSupported,isVp8EncodeSupported:VL.detail.isVp8EncodeSupported,isH265EncodeSupported:VL.detail.isH265EncodeSupported};let r,n=!1,o=!1,s=!1;try{let a=new RTCPeerConnection,c=document.createElement($k.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(vM){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},YL=function(){return Xb(this,null,function*(){var e;if(VL.detail.isH264DecodeSupported&&VL.detail.isVp8DecodeSupported)return{isH264DecodeSupported:VL.detail.isH264DecodeSupported,isVp8DecodeSupported:VL.detail.isVp8DecodeSupported,isH265DecodeSupported:VL.detail.isH265DecodeSupported};let t,i=!1,r=!1;try{let n=new RTCPeerConnection;_x()?(n.addTransceiver($k.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(TM){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})};var XL=kw(e=>Xb(null,null,function*(){let t=Date.now(),i=kx(),r=GL(),n=WL();if(VL.detail.isWebRTCSupported=i,VL.detail.isMediaDevicesSupported=r,VL.detail.isWebCodecsSupported=n,VL.detail.isScreenShareSupported=ZL(),VL.detail.isSmallStreamSupported=dx(),37===e)return Object.assign(VL.detail,yield function(){return Xb(this,null,function*(){return tx||(tx=new Promise(e=>Xb(null,null,function*(){let t={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!WL())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=>Xb(null,null,function*(){let t,r={type:e.type,encodeSupported:!1,decodeSupported:!1};try{t=yield new Promise((t,n)=>Xb(null,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(RM){n(RM)}}))}catch(p){return dM.warn("".concat(e.type," encoder error:"),p),r}try{yield new Promise((i,n)=>Xb(null,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(RM){n(RM)}}))}catch(p){dM.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(),dM.warn("detectWebCodecsSupported failed:",s),e(t)}})),tx)})}()),VL.detail.isBrowserSupported=n,VL.result=r&&n,VL.result||dM.error("".concat(navigator.userAgent," ").concat(yw(VL.detail,!1))),Lx(e),UL.addNumber({key:523800,value:Date.now()-t}),VL;if(VL.result&&VL.detail.isH264EncodeSupported&&VL.detail.isVp8EncodeSupported&&VL.detail.isH265EncodeSupported&&VL.detail.isH264DecodeSupported&&VL.detail.isVp8DecodeSupported&&VL.detail.isH265DecodeSupported)return VL;let o=HL(),{encode:s,decode:a}=yield function(){return Xb(this,null,function*(){let[e,t]=yield Promise.all([qL(),YL()]);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 qL();dM.warn("detect encode again h264:".concat(c," vp8:").concat(l," result: ").concat(JSON.stringify(e))),c=e.isH264EncodeSupported,l=e.isVp8EncodeSupported}if(c&&d&&mP&&gO&&!PP&&!NP&&(!lO||115!==vO)){let{encode:e,decode:t}=yield function(){return Xb(this,null,function*(){return ex||(ex=new Promise(e=>Xb(null,null,function*(){let t={encode:!1,decode:!1},i=()=>{};try{let r=document.createElement("canvas"),n=r.getContext("2d");r.width=640,r.height=480;let o=setInterval(()=>{n.fillText("test",Math.floor(640*Math.random()),Math.floor(480*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=kL.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=kL.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval(()=>Xb(null,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===$k.VIDEO&&e.bytesSent>0&&(t.encode=!0)}),t.decode||n.forEach(e=>{"inbound-rtp"===e.type&&e.mediaType===$k.VIDEO&&e.bytesReceived>0&&(t.decode=!0)})}),100)}catch(r){i(),dM.warn("detectH264Supported failed",r),e({encode:!0,decode:!0})}})).then(e=>(e.encode||(e.decode=!0),(!e.encode||!e.decode)&&dM.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(WO)),e)),ex)})}();c=e,d=t}return VL.result=o&&i&&r&&(c||l)&&(d||h),VL.detail.isBrowserSupported=o,VL.detail.isWebRTCSupported=i,VL.detail.isH264EncodeSupported=c,VL.detail.isVp8EncodeSupported=l,VL.detail.isH265EncodeSupported=u,VL.detail.isH264DecodeSupported=d,VL.detail.isVp8DecodeSupported=h,VL.detail.isH265DecodeSupported=p,VL.result||dM.error("".concat(navigator.userAgent," ").concat(yw(VL.detail,!1))),Lx(),UL.addNumber({key:523800,value:Date.now()-t}),VL})),QL=function(){return VL.result},ZL=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},$L="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype,ex=null;var tx=null;var ix=(e,t,i)=>{"http:"===location.protocol&&!xO&&(e[t]=()=>{throw new dk({code:ck.INVALID_OPERATION,message:SL.NOT_SUPPORTED_HTTP})})},rx=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(XN(e.selected)&&!e.selected)};function nx(){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 ox(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function sx(){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 ax(){return"captureStream"in HTMLCanvasElement.prototype}function cx(){return!(UP||hP||vO&&vO<63)&&!(!HL()||!ax())}function lx(){return!(vO<74||yP||wO<11||vP<46)}function dx(){return cx()||lx()}var ux=function(){if(KN(window.RTCRtpTransceiver)||!_x()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:MD}),e.addTransceiver($k.AUDIO),t=!0}catch(Ik){}return null==e||e.close(),t};function hx(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function px(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function mx(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function _x(){return!(11===wO&&!LO)&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var fx=!(!_x()||gO&&vO<86);function gx(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var Ex="RTCRtpSender"in window;function Tx(){return Ex&&"replaceTrack"in window.RTCRtpSender.prototype}function vx(){return Ex&&"setParameters"in window.RTCRtpSender.prototype&&px()}var yx="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,Sx=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Ix=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Ax="undefined"!=typeof InputDeviceInfo&&"getCapabilities"in InputDeviceInfo.prototype,Rx=Ex&&"createEncodedStreams"in window.RTCRtpSender.prototype&&_O()>=86,Cx="RTCRtpScriptTransform"in window,bx=Ex&&(Rx||Cx),kx=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(e=>e in window).length>0};function Dx(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return KN(window.AudioDecoder)||(e.AudioDecoder=!0),KN(window.AudioEncoder)||(e.AudioEncoder=!0),KN(window.VideoDecoder)||(e.VideoDecoder=!0),KN(window.VideoEncoder)||(e.VideoEncoder=!0),KN(window.ImageDecoder)||(e.ImageDecoder=!0),e}function Nx(){return"mediaSession"in navigator&&!KN(navigator.mediaSession.setActionHandler)}function wx(){return!KN(window.WebTransport)}function Px(){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 Ox(){let e={browser:"".concat(VO.name,"/").concat(VO.version),os:ZO(),displayResolution:nx(),isScreenShareSupported:ZL(),isWebRTCSupported:kx(),isGetUserMediaSupported:ox(),isWebAudioSupported:sx(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:Dx(),isMediaSessionSupported:Nx(),isWebTransportSupported:wx()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var Mx="checkResult";function Lx(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30;hM.setItem(Mx+e,{ua:navigator.userAgent,checkResult:VL})}function xx(e){zL();let t=hM.getItem(Mx+e);t&&t.ua===navigator.userAgent&&t.checkResult&&function(e,t){return!!QN(e)&&Object.keys(t).every(t=>t in e)}(t.checkResult.detail,VL.detail)&&(VL=t.checkResult),XL(e)}function Ux(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var Vx="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function Fx(e){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[e]}var Bx=!1;function Hx(){return Xb(this,null,function*(){var e;try{if(Bx||null==(e=null==navigator?void 0:navigator.mediaCapabilities)||!e.encodingInfo)return;let t=$O(),i=eM();if(0===t||0===i)return;Bx=!0;let r=["H264","VP8","VP9","AV1","H265"],[n,o]=yield Promise.all([Wx(r),Gx(r)]);n&&Object.keys(n).forEach(e=>{let r=Fx(e.toLowerCase());UL.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=Fx(e.toLowerCase());UL.addEnum({key:514713,value:+"".concat(r).concat(+o[e].supported).concat(+o[e].powerEfficient).concat(t).concat(i),useUV:!1})});let{sender:s,receiver:a}=jx();UL.addEnum({key:513708,value:+"".concat(t).concat(i).concat(+s.high),useUV:!1}),UL.addEnum({key:513709,value:+"".concat(t).concat(i).concat(+s.main),useUV:!1}),UL.addEnum({key:514714,value:+"".concat(t).concat(i).concat(+a.high),useUV:!1}),UL.addEnum({key:514715,value:+"".concat(t).concat(i).concat(+a.main),useUV:!1})}catch(EM){dM.info("detectVideoCodecCapabilities failed",EM)}})}function Wx(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 Xb(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(Ak){}return o})}function Gx(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 Xb(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(Ak){}return o})}function jx(){let e={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&"function"==typeof RTCRtpSender.getCapabilities){let t=RTCRtpSender.getCapabilities("video");t&&t.codecs&&t.codecs.filter(e=>"video/h264"===e.mimeType.toLowerCase()).forEach(t=>{if(t.sdpFmtpLine){let i=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(i&&i[1])switch(i[1].slice(0,2)){case"42":e.sender.base=!0;break;case"4d":e.sender.main=!0;break;case"64":e.sender.high=!0}}})}if(RTCRtpReceiver&&"function"==typeof RTCRtpReceiver.getCapabilities){let t=RTCRtpReceiver.getCapabilities("video");t&&t.codecs&&t.codecs.filter(e=>"video/h264"===e.mimeType.toLowerCase()).forEach(t=>{if(t.sdpFmtpLine){let i=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(i&&i[1])switch(i[1].slice(0,2)){case"42":e.receiver.base=!0;break;case"4d":e.receiver.main=!0;break;case"64":e.receiver.high=!0}}})}}catch(EM){dM.warn("get H264 profile levelId failed",EM)}return e}var zx=Jb(Qb(),1),Jx=Symbol("instance"),Kx=Symbol("cacheResult"),qx=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,$x.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},Yx=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var Xx=new Map;function Qx(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=Xx.get(r)||[];Xx.has(r)||Xx.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=eU.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return i.sync?r[Kx]:Promise.resolve(r[Kx]);r.state instanceof qx&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof qx&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new Yx(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 Yx(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 qx(u,t,s);$x.call(r,h);let p=e=>{var n;return r[Kx]=e,h.aborted||($x.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[Kx])),e},m=e=>($x.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(AM){return m(new Yx(r._state,"".concat(r.name," ").concat(s," from ").concat(e," to ").concat(t," failed: ").concat(AM),AM instanceof Error?AM:new Error(String(AM))))}}}}var Zx="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 $x(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(eU.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var eU=class e extends zx.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[Jx];n?this.name=n.name+"-"+n.count++:r[Jx]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=Xx.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);Xx.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]:{};Zx(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){$x.call(this,e)}};eU.STATECHANGED="stateChanged",eU.UPDATEAFSM="updateAFSM",eU.INIT="[*]",eU.ON="on",eU.OFF="off",eU.instances=new Map,eU.instances2=new WeakMap;var tU="undefined"!=typeof window,iU=tU&&window.requestIdleCallback||function(e){let t=Date.now();return setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})},1e3)},rU=tU&&window.cancelIdleCallback||function(e){clearTimeout(e)},nU=tU&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),oU=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=Hb("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=Wb(Hb({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=iU(n,{timeout:t.delay})};return t.ricID=iU(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&&nU&&nU(r),n&&rU(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)}};qb(oU,"taskMap",new Map),qb(oU,"currentTaskID",1),qb(oU,"sharedWorker",null),qb(oU,"workerTasks",new Map);var sU=oU;$k.SEI_MESSAGE;var aU={LOAD_START:$k.LOADSTART,LOADED_DATA:$k.LOADEDDATA,LOADED_META_DATA:$k.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:$k.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:$k.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:$k.ENTER_PICTURE_IN_PICTURE,USER_RESUME_IN_PIP_OR_FULL_SCREEN:"user-resume-in-pip-or-full-screen",USER_PAUSE_IN_PIP_OR_FULL_SCREEN:"user-pause-in-pip-or-full-screen",ENTER_FULL_SCREEN:"enter-full-screen",LEAVE_FULL_SCREEN:"leave-full-screen",VOLUME_CHANGE:"volume-change"},cU={};zb(cU,{create:()=>dU,remove:()=>uU});var lU=new WeakMap;function dU(e,t){lU.has(e)||lU.set(e,[]);let i=lU.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 uU(e){let t=lU.get(e);t&&(t.forEach(e=>e()),lU.delete(e))}var hU=new class{constructor(){qb(this,"_roomIdMap",new Map),qb(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:yk,env:Wk.QCLOUD,browserVersion:VO.name+VO.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){xO||!dM.isAbleToUpload||this._configs.env===Wk.QCLOUD&&this.uploadEventToKibana(Wb(Hb({},e),{result:"success"}))}logFailedEvent(e){if(xO||!dM.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)||ck.UNKNOWN};this._configs.env===Wk.QCLOUD&&this.uploadEventToKibana(Wb(Hb({},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:fk(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:yk,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+="\n".concat(r.stack)));let o=cM.enable?xw(n,2002,Number(this._configs.sdkAppId)):JSON.stringify(n);this.sendRequest(bN(this._configs.sdkAppId,Hk.LOG),o)}sendRequest(e,t){setTimeout(()=>jw({url:e,body:t,priority:"low"}).catch(()=>{}),2e3)}},pU=new WeakMap;function mU(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,s){let a=$w({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=pU.get(e))&&t.has(o)?n():s(r)},s,a):null!=(c=pU.get(e))&&c.has(o)?n():s(r)},onRetrying(t,i){var n;Kw(r)&&r.call(this,t,i),null!=(n=pU.get(e))&&n.has(o)&&(pU.get(e).get(o).stopRetry=i)},onRetryFailed:n});return s.value=function(){let t=pU.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}):pU.set(e,new Map([[o,{args:r}]])),a.apply(this,r).finally(()=>{var t;return null==(t=pU.get(e))?void 0:t.delete(o)})},s}}function _U(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=pU.get(e))&&n.has(t)){let{stopRetry:n,args:s}=pU.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=pU.get(e))||o.delete(t))}return s.apply(this,c)},o}}var fU=class extends eU{constructor(e,t){super(e.id,"".concat(t,"-player")),this.options=e,this.kind=t,qb(this,"id"),qb(this,"element",null),qb(this,"track"),qb(this,"url"),qb(this,"attr"),qb(this,"mode"),qb(this,"muted"),qb(this,"_log"),qb(this,"isPausedByUserCall",!1),qb(this,"_pausedRetryCount"),qb(this,"_isElementPlayingFired",!1),qb(this,"_interval"),qb(this,"_delayDestroyTimeoutId",0),qb(this,"_playSuccessResolve"),qb(this,"_isReplayByRecreateMediaStreamCalled",!1),qb(this,"isPlayCalled",!1),qb(this,"isInAutoPlayFailedState",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=JD,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 Xb(this,null,function*(){if(!this.isPlaying)try{this.isPlayCalled=!0,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(Ik){let t=RL({key:yL.PLAY_FAILED,data:{media:this.kind,error:Ik}});if(this._log.warn(Ik),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new dk({code:ck.PLAY_NOT_ALLOWED,message:t})}})}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;this.isPlayCalled=!1,this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!RO?this._delayDestroyTimeoutId||(null==(t=this.element)||t.remove(),this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped($k.ENDED),this._interval>0&&sU.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){this._log.info("pause"),this.isPausedByUserCall=!0,this.doPause()}doPause(){var e;null==(e=this.element)||e.pause()}resume(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.isPausedByUserCall=!1,this.doResume(e)}doResume(){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():OO?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 dU(this.element,this.element).add($k.PLAYING,e).add($k.ENDED,e).add($k.PAUSE,e).add($k.ERROR,e).add($k.LOADSTART,e).add($k.LOADEDDATA,e).add($k.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==cU||cU.create(e,e).add($k.ENDED,t).add($k.MUTE,t).add($k.UNMUTE,t),e.readyState===$k.ENDED&&this.handleTrackEvent({type:$k.ENDED}),e.muted&&this.handleTrackEvent({type:$k.MUTE})}}bindAutoPlayEvent(){oM.listeners(aM.AUTOPLAY_DIALOG_CLICK_CONFIRM).includes(this.resume)||oM.on(aM.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;e&&uU(e)}unbindEvents(){this.element&&uU(this.element),this.unbindTrackEvents(),oM.off(aM.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case $k.PLAYING:MU()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying($k.PLAYING),this._interval&&(sU.clearTask(this._interval),this._interval=-1);break;case $k.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped($k.ENDED);break;case $k.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused($k.PAUSE);break;case $k.ERROR:if(this.element&&this.element.error){this.handlePaused($k.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)),hU.uploadEvent({log:"stat-".concat(this.kind,"-").concat(ND.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),oO||nO?this.emit(aU.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case $k.LOADEDDATA:this.kind===$k.VIDEO&&this.emit(aU.LOADED_DATA);break;case $k.LOADEDMETADATA:this.kind===$k.VIDEO&&this.emit(aU.LOADED_META_DATA);break;case $k.LOADSTART:this.emit(aU.LOAD_START)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),hU.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),UL.addSuccessEvent({key:this.kind===$k.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),hU.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),UL.addFailedEvent({key:this.kind===$k.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(aU.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise((t,i)=>{bw(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)}),bw(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 Xb(this,null,function*(){let t=e.type;switch(this.options.enableLogTrackState&&this._log[t===$k.UNMUTE?"info":"warn"]("track ".concat(t)),t){case $k.ENDED:this.handleStopped($k.ENDED);break;case $k.MUTE:this.handlePaused($k.MUTE);break;case $k.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&!this.isPausedByUserCall&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying($k.UNMUTE))}})}handlePlaying(e){var t;return this._log.debug("handlePlaying",e),null==(t=this._playSuccessResolve)||t.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};qb(fU,"PlayerEvent",aU),Kb([mU({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],fU.prototype,"doReplayByRecreateMediaStream",1),Kb([Qx([],"PLAYING",{sync:!0,success(e){this.emit(aU.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],fU.prototype,"handlePlaying",1),Kb([Qx("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(aU.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],fU.prototype,"handlePaused",1),Kb([Qx([],"STOPPED",{sync:!0,success(e){this.emit(aU.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],fU.prototype,"handleStopped",1);var gU="trtc_autoplay",EU="".concat(gU,"_mask"),TU="".concat(gU,"_wrapper"),vU="".concat(gU,"_header"),yU="".concat(gU,"_content"),SU="".concat(gU,"_action_wrapper"),IU="".concat(gU,"_question"),AU="".concat(gU,"_collapse"),RU="".concat(gU,"_action_confirm"),CU="".concat(gU,"_detail"),bU="#2473E8",kU="dialog",DU="".concat(kU,"-show"),NU="".concat(kU,"-1"),wU="".concat(kU,"-2"),PU=!1,OU=!1,MU=()=>OU,LU="".concat(Mk,"/").concat(HN()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),xU="<br><a href='".concat(LU,"' target='_blank'>").concat(HN()?"其他方案?":"Any other solution?","</a>"),UU="".concat(HN()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(xU):"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(xU)),VU=class{constructor(){if(qb(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),qb(this,"_dialogNode",null),qb(this,"_bodyPosition",""),qb(this,"_showDetail",!1),qb(this,"_isCollapseClicked",!1),qb(this,"_isQuestionClicked",!1),HN()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!PU){let e=document.createElement("style");e.innerHTML=".".concat(EU,"{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(EU," div:not(.").concat(SU,"){display:block !important;}.").concat(TU,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(TU," a{color:").concat(bU,";}.").concat(vU,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(yU,"{margin:8px 0;}.").concat(SU,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(AU,"{margin-right:auto;cursor:pointer}.").concat(IU,"{height:100%;line-height:16px;cursor:pointer;}.").concat(RU,"{margin-left:8px;color:#fff;background:").concat(bU,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(RU,":hover{opacity:0.9;}.").concat(AU,",.").concat(RU,",.").concat(yU,",.").concat(IU,"{font-size:14px;}@media screen and (max-width:750px){.").concat(TU,"{width:80vw;}}"),document.head.appendChild(e),PU=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(EU,"\"><div class='").concat(TU,"'><div class='").concat(vU,"'>").concat(location.host,"</div><div class='").concat(yU,"'>").concat(this.content,"</div><div class='").concat(CU,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(UU,"</div><div class='").concat(SU,"'></div></div></div>").trim();let t=document.createElement("button");t.className=RU,t.innerText=HN()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=IU,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=AU,r.innerText="".concat(HN()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(SU));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){MU()||(OU=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(TU)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",dM.info("show autoplay dialog"),hU.uploadEvent({log:DU}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,OU=!1),FU=null}onConfirm(){dM.warn("confirm clicked, try resume stream"),oM.emit(aM.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(CU));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||hU.uploadEvent({log:NU}),this._isCollapseClicked=!0}onQuestionClick(){window.open(LU,"_blank"),this._isQuestionClicked||hU.uploadEvent({log:wU}),this._isQuestionClicked=!0}},FU=null;function BU(){FU||(FU=new VU)}var HU,WU=class e extends fU{constructor(e){super(e,$k.VIDEO),qb(this,"stat",{}),qb(this,"_calculateTimeout",-1),qb(this,"viewMirror",!1),qb(this,"objectFit","cover"),qb(this,"container"),qb(this,"canvas"),qb(this,"shouldRenderAlpha",!1),qb(this,"_preSize",{width:0,height:0}),qb(this,"posterImg"),qb(this,"pipWindow"),qb(this,"enterPIPPromise"),qb(this,"_originContainerPosition"),qb(this,"_isResettingSrcObject",!1),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,KN(e.viewMirror)||(this.viewMirror=e.viewMirror),KN(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($k.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,mP&&(t.poster="data:,"),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,";").concat(this.shouldRenderAlpha?"":"background-color:black",";");return this.viewMirror&&(e+="transform:scaleX(-1);"),e}setContainer(e){var t;this.container=e,this._pausedRetryCount=JD,this.track&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),e&&e.add($k.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add($k.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add($k.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener($k.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.addEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.addEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.addEventListener("volumechange",this.handleVolumeChange))}handleTrackEvent(e){var t;return e.type===$k.MUTE&&(null!=(t=this.stat)&&t.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(e)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(aU.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(aU.LEAVE_FULL_SCREEN))}handleVolumeChange(){var e;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(aU.VOLUME_CHANGE,{muted:null==(e=this.element)?void 0:e.muted})}handleElementEvent(e){var t,i,r,n,o,s;if(2===this.mode)return;super.handleElementEvent(e);let a=e.type,c=this.isPictureInPicture(),l=this.isFullscreen(),d=e.isTrusted&&(c&&AO||l);if(a===$k.PLAYING&&d&&!this._isResettingSrcObject&&(this._log.warn("user resume in ".concat(l?"fullscreen":"pip")),this.emit(aU.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),a===$k.PAUSE&&(d&&(this._log.warn("user pause in ".concat(l?"fullscreen":"pip")),this.emit(aU.USER_PAUSE_IN_PIP_OR_FULL_SCREEN)),this.container&&!this.container.isConnected&&(this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(this.container.id)),bw(500).then(()=>{var e;null!=(e=this.container)&&e.isConnected&&(this._pausedRetryCount=JD,this._log.info("view container ".concat(this.container.id," is in dom, reset pausedRetryCount")))})),this._pausedRetryCount>0&&!MU()&&!this.isPausedByUserCall&&!d&&(this._log.info("[".concat(JD-this._pausedRetryCount+1,"/").concat(JD,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),hP&&!d&&(this._interval=sU.run("timeout",()=>{this.element&&"PAUSED"===this._state&&!this.isPausedByUserCall&&this.doResume()},{delay:3e3})),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let e=this.element.style.transform;a===$k.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):a===$k.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}a===$k.RESIZE&&(this._preSize.height!==(null==(t=this.element)?void 0:t.videoHeight)||this._preSize.width!==(null==(i=this.element)?void 0:i.videoWidth))&&(this._log.info("video size changed to ".concat(null==(r=this.element)?void 0:r.videoWidth,"x").concat(null==(n=this.element)?void 0:n.videoHeight)),this._preSize.height=(null==(o=this.element)?void 0:o.videoHeight)||0,this._preSize.width=(null==(s=this.element)?void 0:s.videoWidth)||0,this.emit(aU.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height})),a===$k.LEAVE_PICTURE_IN_PICTURE&&(this._log.warn("exit pip"),this.isPaused&&!this.isPausedByUserCall&&(this._log.warn("resume after exit pip"),this.doResume()),this.resetSrcObjectToReplay(),this.emit(aU.LEAVE_PICTURE_IN_PICTURE)),a===$k.ENTER_PICTURE_IN_PICTURE&&this.emit(aU.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){mP&&yO&&this.isPlayCalled&&this.element&&this.track&&!this.isPausedByUserCall&&(this._log.warn("reset srcObject to replay for android chromium"),this._isResettingSrcObject=!0,this.element.srcObject=new MediaStream([this.track]),this.element.play().catch(e=>{this._log.warn("play failed after reset srcObject",e)}).finally(()=>{this._isResettingSrcObject=!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){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise(i=>{if(!this.element||(this._log.info("setPoster",e.slice(0,10)),""===e?this.element.removeAttribute("poster"):this.element.poster=e,!t||!AO&&!EP))return i();if(""===e)return this.removePosterImg(),i();if(this.posterImg)return i();let r=document.createElement("img");r.src=e;let n=window.getComputedStyle(this.element).objectFit||this.objectFit;r.style="position:absolute;top:0;left:0;width:100%;height:100%;object-fit:".concat(n,";"),r.onload=()=>Xb(this,null,function*(){var e;try{r.decode&&(yield r.decode()),this.container&&"static"===window.getComputedStyle(this.container).position&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=r,null==(e=this.container)||e.appendChild(r),pP()&&wO<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(t){this._log.warn("decode poster image error",t)}return i()}),r.onerror=()=>(this._log.warn("load poster image error"),i())})}removePosterImg(){this.posterImg&&(pP()&&wO<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this.container&&!KN(this._originContainerPosition)&&"relative"===this.container.style.position&&(this.container.style.position=this._originContainerPosition),delete this.posterImg)}get hasPoster(){var e;return!!this.posterImg||!(null==(e=this.element)||!e.getAttribute("poster"))}pause(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Xb(this,null,function*(){Yb(e.prototype,this,"pause").call(this),!this.isPictureInPicture()&&!this.hasPoster&&(yO||t&&(EP||AO))&&(yield this.setPoster(this.getVideoFrame(),!0))})}resume(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return super.resume(e).then(()=>{var e;(this.posterImg||null!=(e=this.element)&&e.poster)&&this.setPoster("",!0)})}doResume(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.isPaused&&e&&this.element&&this.track&&yO&&"video"===this.track.kind&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;this.isPictureInPicture()&&this.exitPictureInPicture().catch(e=>{}),this.isFullscreen()&&this.exitFullscreen().catch(e=>{}),this.element&&(this.element.removeEventListener($k.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.removeEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.removeEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.removeEventListener("volumechange",this.handleVolumeChange)),super.stop(e),null==(t=this.canvas)||t.remove(),this.removePosterImg()}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(aU.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(Ux()&&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(Ik){this._log.warn("init stat failed",Ik)}}enterFullscreen(){return Xb(this,null,function*(){let e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(hP&&this.isPictureInPicture()){this._log.info("exit pip before entering fullscreen");try{yield this.exitPictureInPicture()}catch(kD){this._log.warn("exit pip failed before fullscreen:",kD)}}try{if(e.requestFullscreen)yield e.requestFullscreen();else if(e.webkitRequestFullscreen)yield e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)yield e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)yield e.mozRequestFullScreen();else{if(!e.msRequestFullscreen)throw new Error("Fullscreen API not supported");yield e.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(kD){throw this._log.error("failed to enter fullscreen:",kD),kD}})}exitFullscreen(){return Xb(this,null,function*(){try{if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Exit fullscreen API not supported");yield document.msExitFullscreen()}this._log.info("exited fullscreen mode")}catch(Ik){throw this._log.error("failed to exit fullscreen:",Ik),Ik}})}isFullscreen(){let e=this.elementToRender;return!!e&&(this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e)}toggleFullscreen(){return Xb(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return Xb(this,null,function*(){this.enterPIPPromise=this._enterPictureInPicture();try{return yield this.enterPIPPromise}finally{delete this.enterPIPPromise}})}_enterPictureInPicture(){return Xb(this,null,function*(){var e;try{if(!this.element)throw new Error("No video element available for pip");if(this.canvas&&1!==this.mode)throw new Error("pip is not supported for canvas-only mode");let{element:t}=this;if(t.requestPictureInPicture){this._log.info("requestPictureInPicture");let i=yield t.requestPictureInPicture();return this.pipWindow=i,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),null==(e=this.container)||e.appendChild(this.element)),i}if(t.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield t.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered pip mode (webkit)"),{};throw new Error("pip API not supported")}catch(kD){throw this._log.error("failed to enter pip:",kD.name,kD.message),kD}})}exitPictureInPicture(){return Xb(this,null,function*(){var e,t;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this.elementToRender===this.canvas&&(null==(e=this.element)||e.remove(),this._pausedRetryCount=JD,null==(t=this.container)||t.appendChild(this.canvas)),this._log.info("exited pip mode");else{if(!this.element||!this.element.webkitSetPresentationMode)throw new Error("Exit pip API not supported or not in PiP mode");yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited pip mode (webkit)")}}catch(TM){throw this._log.error("failed to exit pip:",TM),TM}})}isPictureInPicture(){if(!this.element)return!1;let{element:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:!!e.webkitPresentationMode&&"picture-in-picture"===e.webkitPresentationMode}togglePictureInPicture(){return Xb(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function GU(e,t){return Xb(this,null,function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),dM.info("worklet addModule success")}catch(Ik){throw dM.info("worklet addModule catch error. ".concat(Ik.message)),Ik}})}"undefined"!=typeof AudioContext?HU=AudioContext:"undefined"!=typeof webkitAudioContext?HU=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(HU=mozAudioContext);var jU,zU=1500,JU=-1,KU=0,qU=-1,YU=!1,XU=0,QU=-1,ZU=-1;!function e(){try{if(jU)return;(jU=new HU({sampleRate:48e3})).onstatechange=()=>{dM.info("context state: ".concat(jU.state).concat("running"!==jU.state?" visibilityState: ".concat(document.visibilityState):"")),$U()},clearTimeout(JU)}catch(t){dM.error("initAudioContext failed: ".concat(t," typeof AudioContextClass: ").concat(typeof HU)),JU=setTimeout(e,1e3)}}();var $U=()=>{"suspended"===jU.state?(KU=aw(),-1===qU&&(qU=setTimeout(()=>{"suspended"===jU.state&&(YU=!0,oM.emit("155",{isSuspended:!0}))},zU)),iV(),document.addEventListener("click",$U)):"interrupted"===jU.state?iV():(KU&&(UL.addNumber({key:507800,value:aw()-KU,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),KU=0),-1!==qU&&(clearTimeout(qU),qU=-1,YU&&(YU=!1,oM.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",$U),document.removeEventListener("click",$U))},eV=0,tV=-1;function iV(){return new Promise((e,t)=>{if("running"===jU.state)return e();Date.now()-eV<1e3?(clearTimeout(tV),tV=setTimeout(()=>{eV=Date.now(),jU.resume().then(e,t)},1e3)):(clearTimeout(tV),eV=Date.now(),jU.resume().then(e,t))}).catch(e=>{dM.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",$U)})}document.addEventListener("click",$U);var rV=e=>jU,nV=class{constructor(e){this.name=e,qb(this,"node"),qb(this,"node2"),qb(this,"pre",new Set),qb(this,"next",new Set),qb(this,"context"),qb(this,"connectedNodes",new Set),qb(this,"nextInputChannelMap",new Map),qb(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(kD){dM.error(kD)}}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(),UL.addSuccessEvent({key:502701})}catch(TM){dM.error(TM),UL.addFailedEvent({key:502701,error:TM})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),UL.addSuccessEvent({key:502702})}catch(Ik){dM.error(Ik),UL.addFailedEvent({key:502702,error:Ik})}}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}},oV=class extends nV{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,qb(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}},sV=class{constructor(){qb(this,"source",new nV),qb(this,"gain",new nV),qb(this,"destination",new nV)}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(rV().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){let t=dV(e);t&&this.source.replaceNode(t)}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}},aV=class extends sV{constructor(e){super(),this.context=e,qb(this,"aec",new nV("aec")),qb(this,"mixNode",new nV("mixNode")),qb(this,"silentNode",new nV("silentNode")),qb(this,"denoiser",new nV("denoiser")),qb(this,"voiceChanger",new nV("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()}},cV=class{constructor(){qb(this,"audioContext",rV()),qb(this,"destination",this.audioContext.createMediaStreamDestination()),qb(this,"inputs",new Set),qb(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]}},lV=new WeakMap;function dV(e){try{let t=lV.get(e);if(t)return t;let i=rV();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return lV.set(e,t),t}catch(EM){if(!(EP&&EM instanceof Error&&"NotSupportedError"===EM.name))throw EM;dM.warn(EM)}}var uV=class e{constructor(e){qb(this,"_volume",0),qb(this,"_volumeDb",0),qb(this,"_log"),qb(this,"_scriptProcessorNode",null),qb(this,"_audioWorkletNode",null),qb(this,"_interval",200),qb(this,"ready",this.preload());let{log:t}=e;this._log=t,oM.on(aM.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=GU(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(EM){this._log.error("volumeMeter init audio worklet error: ".concat(EM)),hU.logFailedEvent({userId:this._log.userId,eventType:ND.LOAD_WORKLET,error:EM}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=rV().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(EM){this._log.error("volumeMeter init script processor error: ".concat(EM))}}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,oM.off(aM.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})}};qb(uV,"lastMessageTime",0),qb(uV,"audioContext",rV()),qb(uV,"workletReady");var hV=uV,pV=class extends nV{constructor(e){super(),qb(this,"_volumeMeter"),this._volumeMeter=new hV(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return Xb(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()}}},mV=hV,_V=Jb(Qb(),1),fV=e=>t=>t.deviceId===e,gV=class{constructor(e,t){qb(this,"kind"),qb(this,"type"),qb(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&&vV(this.devices[0])||t&&(i.forEach(e=>{if(e.deviceId&&!this.devices.find(fV(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");dM.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}),this.devices.forEach(e=>{if(e.deviceId&&!i.find(fV(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");dM.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices=i}hasDevice(e){return!!this.devices.find(t=>t.deviceId===e)}},EV=class extends _V.EventEmitter{constructor(){super(),qb(this,"audioInputs",new gV($k.AUDIO,"Input")),qb(this,"videoInputs",new gV($k.VIDEO,"Input")),qb(this,"audioOutputs",new gV($k.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||sU.run("interval",()=>{this.update()},{delay:1e4}))}init(){yV().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return Xb(this,arguments,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield yV(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()})}hasBlueTooth(){var e;if(1e3*(null==(e=rV())?void 0:e.outputLatency)>150)return!0;let t=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(e=>t.some(t=>e.label.toLowerCase().includes(t)))||this.audioInputs.devices.some(e=>t.some(t=>e.label.toLowerCase().includes(t)))}},TV=Ck||Rk?null:new EV;function vV(e){return e.deviceId===e.groupId&&""===e.groupId}function yV(){return Xb(this,arguments,function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(zL()||!GL())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach(e=>{vV(e)&&(e.kind===$k.AUDIO_INPUT?i.audio=!0:e.kind===$k.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&&iV()}catch(TM){dM.debug("capture before getDevices failed: ",TM)}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&&CV.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i})}()})}function SV(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return TV.update(e?1:0).then(e=>e.audioInputs.devices)}function IV(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return TV.update(e?2:0).then(e=>e.videoInputs.devices)}var AV=!1;function RV(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Xb(this,null,function*(){return(hP||AO)&&(e=!1),TV.update(e?1:0).then(e=>e.audioOutputs.devices)})}var CV=new Set;function bV(e,t){return Xb(this,null,function*(){let i=(yield SV()).find(e=>e.deviceId===KD);return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t})}var kV,DV=class extends sV{constructor(e){super(),this.log=e,qb(this,"volumeMeter"),qb(this,"volumeMeterAfter3A"),qb(this,"volumeDestination"),qb(this,"analyser",new oV),this.volumeMeter=new pV({log:this.log}),this.volumeMeterAfter3A=new pV({log:this.log}),this.volumeDestination=new nV,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},NV=class e extends fU{constructor(e){super(e,$k.AUDIO),qb(this,"_outputDeviceId"),qb(this,"_floatVolume",1),qb(this,"_destination"),qb(this,"pipeline"),qb(this,"volumeMeterMode","worklet"),qb(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new DV(this._log)}setTrack(e){}get duration(){var e;return Math.floor(1e3*((null==(e=this.element)?void 0:e.duration)||0))}get currentTime(){var e;return Math.floor(1e3*((null==(e=this.element)?void 0:e.currentTime)||0))}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(("15.2"===kO||"15.3"===kO||"15.4"===kO)&&this.muted)return void this._log.info("audioElement is muted.");let t=kV||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.url&&(t.crossOrigin="anonymous",t.src=this.url),this.element=t,this.setVolume(YN(e)?e/100:this._floatVolume),t===kV&&(kV=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(aU.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(t){return Xb(this,null,function*(){if(this.track||this.url){try{!this.pipeline.source.node&&this.track&&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(rV().createAnalyser()),function(){Xb(this,null,function*(){try{AV||(AV=!0,dM.info("speakers:".concat((yield RV()).map(e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label)))))}catch(e){}})}()}catch(kD){throw this._log.warn("audio play error: ".concat(kD)),NO(kO,"18.7",!0)&&this.bindAutoPlayEvent(),kD}return Yb(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)}setVolume(e){this._floatVolume=e,this.element&&(this.element.volume=e)}setSinkId(e){return Xb(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()}},wV=class extends NV{setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(aU.MEDIA_TRACK_CHANGED,e),e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]))))}},PV=class extends NV{constructor(e){super(e),qb(this,"_sourceElement"),qb(this,"_output",new nV),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(rV().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(aU.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){var t;let i=e<=1&&!pP();if(this._floatVolume!==e||!(i&&(null==(t=this.element)?void 0:t.volume)===e||!i&&this.pipeline.volume===e))if(this._floatVolume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e));else if(i)this.element?(this._log.info("set element volume: ".concat(e)),this.element.volume=e):this._log.info("set element volume: no element");else{if(pP()){if(!this.enableVolumeControlInIOS)return;!function(){if(!hP||-1!==ZU)return;let e=()=>{aw()-XU<500||(jU&&"running"===jU.state&&jU.currentTime===QU&&(dM.warn("context is fake running, auto resume"),jU.suspend().catch(e=>{dM.warn("context suspend failed: ".concat(e))})),QU=jU.currentTime,XU=aw())};ZU=setInterval(()=>{e()},2e3),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&e()})}()}if(EP&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this._destination||(this._destination=rV().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),uU(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(e=>{this.emit(aU.AUTOPLAY_FAILED,e)}))}}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&RO&&(kV=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},OV=class extends eU{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:o=(1===r?PV:WU)}=e;var s;super(),qb(this,"id",uM()),qb(this,"userId",""),qb(this,"isRemote"),qb(this,"mediaType"),qb(this,"room"),qb(this,"user"),qb(this,"_log"),qb(this,"_inputTrack"),qb(this,"_outputTrack"),qb(this,"isPlayCalled"),qb(this,"container",null),qb(this,"player"),qb(this,"subVideoPlayerMap"),qb(this,"muted",!1),qb(this,"abortCtrl"),qb(this,"objectFit","cover"),qb(this,"mirror"),qb(this,"rotation"),qb(this,"isScreen",!1),qb(this,"manager"),qb(this,"trackSettings"),qb(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=dM.createLogger({parent:null==n?void 0:n.getLogger(),id:"".concat(this.kind[0],"t"),userId:null==(s=n||this.room)?void 0:s.userId,remoteUserId:this instanceof vH?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof vH}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:null==n?void 0:n.enableVolumeControlInIOS}),this.player.on(aU.PLAYER_STATE_CHANGED,e=>{if(oM.emit(aM.PLAYER_STATE_CHANGED,Hb({track:this},e)),this.emit("player-state-changed",e),"PLAYING"===e.state&&this.room){let e=!0;for(let{remoteAudioTrack:t,remoteVideoTrack:i,remoteAuxiliaryTrack:r}of[...this.room.remotePublishedUserMap.values()])if(t.isAvailable&&!t.player.isPlaying||i.isAvailable&&!i.player.isPlaying||r.isAvailable&&!r.player.isPlaying){e=!1;break}e&&MU()&&FU&&FU.deleteDialog()}}),this.kind===$k.VIDEO&&(this.player.on(aU.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(aU.LOADED_DATA),oM.emit(aM.VIDEO_LOADED_DATA,{track:this})}),this.player.on(aU.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(aU.LOADED_META_DATA)}),this.player.on(aU.MEDIA_TRACK_CHANGED,e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach(t=>t.setTrack(e))}),this.player.on(aU.RESIZE,e=>{this.emitFirstVideoFrameEvent(aU.RESIZE),this.emit("video-size-changed",Hb({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(aU.ERROR,this.onPlayerError.bind(this)),this.player.on(aU.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||dM}get kind(){return 1===this.mediaType?$k.AUDIO:$k.VIDEO}get isAudio(){return this.kind===$k.AUDIO}get strMediaType(){return 4===this.mediaType?$k.VIDEO:2===this.mediaType?$k.SCREEN:$k.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 Xb(this,null,function*(){let i=ZN(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!KN(t.muted)&&this.setPlayerMute(t.muted),t&&!KN(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof WU&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(ZN(e)&&e.length>=1&&this.container&&e.includes(this.container)&&this.container.contains(this.player.elementToRender)?(e.splice(e.indexOf(this.container),1),e.unshift(this.container)):(this.container=i,this.player.setContainer(i))),ZN(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!KN(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===$k.VIDEO)&&this.setPlayerMute(!0),t&&!KN(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof WU&&(this.player.setObjectFit(this.objectFit),t&&!KN(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof WU&&this.player.setContainer(i)),oM.emit(aM.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),ZN(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(IM){throw this.handleAutoPlayFailed(IM),IM}}else this.log.info("play has not mediaTrack, abort")})}setMirror(e,t){if(this.isScreen||this.kind!==$k.VIDEO||KN(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(XN(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 Xb(this,null,function*(){if(!this._outputTrack||this.kind===$k.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&&(KN(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new WU({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.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(Qw(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),this.container=null)}resume(){return Xb(this,null,function*(){var e;this.isPlayCalled&&(yield null==(e=this.player)?void 0:e.resume())})}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),oM.emit(e?aM.TRACK_MUTED:aM.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){dU(e,e).add($k.MUTE,this.onTrackMuted).add($k.UNMUTE,this.onTrackUnmuted).add($k.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===$k.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){uU(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,i,r;let n=this._outputTrack;null!=n&&n.canvas&&null!=(i=null==(t=n.canvas)?void 0:t.id)&&i.includes("trtc_mix")||e!==n&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(r=e.getSettings)?void 0:r.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){var t,i;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){if(Qw(this)&&this.isAudio&&null!=(t=this.user)&&t.muteState.hasAudio&&null!=(i=this.user)&&i.muteState.audioMuted)return;return this.player.stop(Qw(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){return Xb(this,null,function*(){var t;this.log.warn("handleAutoPlayFailed",e);let i=()=>{this.resume().then(()=>{document.removeEventListener("click",i,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((PP||UP)&&(yield bw(100),null!=(t=this.player)&&t.isPlaying))return;BU()}else document.addEventListener("click",i,!0);oM.once(aM.LOCAL_TRACK_CAPTURE_SUCCESS,e=>{let{track:t}=e;"audio"===t.kind&&MU()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&i()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof WU?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===aU.RESIZE&&!o&&!s||e===aU.LOADED_META_DATA&&!o&&!s||(e===aU.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,Pw(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"))}};Kb([Qx([],eU.INIT,{sync:!0})],OV.prototype,"_toInitState",1);var MV=Object.prototype.hasOwnProperty;var LV=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(WN(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(MV.call(e,t))return!1;return!0}return!1},xV=$w({retryFunction:function(e){return Xb(this,null,function*(){let t=function(e){return{audio:VV(e),video:FV(e)}}(e);dM.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId","groupId"];if(t.audio&&(i=yield SV(),dM.info("microphones: ".concat(vw(i.map(e=>Wb(Hb({},e),{groupId:e.groupId.substring(0,8)})),{keysToInclude:n})))),t.video&&(r=yield IV(),dM.info("cameras: ".concat(vw(r,{keysToInclude:n}))),!XN(t.video)&&"user"===t.video.facingMode&&!t.video.deviceId)){let e=r.filter(e=>!e.label.includes("infrared")).find(e=>e.label.includes("facing front"));e&&(t.video.deviceId=e.deviceId,dM.info("exclude infrared camera: ".concat(JSON.stringify(t))))}try{let i=yield navigator.mediaDevices.getUserMedia(t);return Ix&&i.getTracks().forEach(t=>{var i;let r=t.getCapabilities();dM.info("".concat(t.kind," capabilities: ").concat(vw(r,{keysToInclude:eN}))),!KN(e.echoCancellation)&&-1===(null==(i=r.echoCancellation)?void 0:i.indexOf(e.echoCancellation))&&dM.warn("Invalid argument for 'echoCancellation'. Expected one of [".concat(JSON.stringify(r.echoCancellation),"], but received '").concat(e.echoCancellation,"'"))}),t.audio&&iV(),i}catch(IM){let{message:n}=IM;throw"NotFoundError"===IM.name&&(e.video&&r&&0===r.length&&(n=RL({key:yL.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(n=RL({key:yL.MICROPHONE_NOT_FOUND}))),new dk({code:ck.INITIALIZE_FAILED,name:IM.name,message:n,constraint:IM.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||"AbortError"===t.name?(1===s?(n[0].video&&(n[0].maxResolution=!1,(!AO||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&&UV(n[0].microphoneId,!1),n[0].cameraId&&UV(n[0].cameraId,!0)},onRetrying:e=>{dM.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{hU.logFailedEvent({eventType:ND.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{hU.logSuccessEvent({eventType:ND.GET_USER_MEDIA_RETRY}),hU.uploadEvent({log:"stat-".concat(ND.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function UV(e,t){return Xb(this,null,function*(){let i=(t?yield IV():yield SV()).find(t=>t.deviceId===e);i&&JN(i.getCapabilities)&&dM.warn(vw(i.getCapabilities(),{keysToInclude:eN}))})}function VV(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!LV(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(YN(e.channelCount)&&(t.channelCount=e.channelCount),(XN(e.echoCancellation)||"remote-only"===e.echoCancellation||"all"===e.echoCancellation)&&(t.echoCancellation=e.echoCancellation),XN(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),XN(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!LV(t)||t)}function FV(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&&!LV(i)?i:(e.width&&(i.width={ideal:e.width},t&&!EP&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!EP&&(i.height.max=e.height)),EP&&YP&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!LV(i)||i)}var BV=xV;function HV(e){return jV((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Xb(this,null,function*(){return yield e.apply(this,r),t.apply(this,r)})})}function WV(e){return jV((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Xb(this,null,function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i})})}function GV(e){return jV((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Xb(this,null,function*(){try{return yield t.apply(this,r)}catch(TM){e.call(this,TM)}})})}function jV(e){return function(t,i,r){return r.value=e(r.value,i),r}}var zV=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&dM.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",()=>{dM.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState}),e=!0)}})(),JV=0,KV=class{constructor(e){qb(this,"log"),qb(this,"isRunning",!1),qb(this,"queue",[]);let t="fq".concat(++JV);e&&(t+="|".concat(e)),this.log=dM.createLogger({id:t})}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=Hb({},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),e.funcName,e.args),this.isRunning||this.callNext(),o}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length),null==e?void 0:e.funcName,null==e?void 0:e.args),e}callNext(){if(this.isRunning||0===this.length)return;let{fn:e,args:t,context:i,resolve:r,reject:n,funcName:o}=this.queue[0];this.log.debug("callNext",this.length,o,t),this.isRunning=!0,e.apply(i,t).then(r,n).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},qV=new WeakMap,YV=new WeakMap;function XV(){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=qV.get(this)||new KV;for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return qV.set(this,t),t.push({fn:n,args:o,context:this,funcName:i},e)},r}}function QV(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=qV.get(this))?void 0:t.queue)||i.forEach(e=>o.push(e)),null==(r=YV.get(this))||r.forEach(e=>null==e?void 0:e.queue.forEach(e=>o.push(e))),o.forEach(t=>{t.reject(new dk({code:ck.API_CALL_ABORTED,message:e}))}),qV.delete(this),YV.delete(this),n.apply(this,a)},r}}function ZV(e,t){return function(i,r,n){let o=n.value,s=t=>e(...t);return n.value=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];let a=YV.get(this)||new Map,c=a.get(s(i))||new KV(null==t?void 0:t(...i));return a.set(s(i),c),YV.set(this,a),c.push({fn:o,args:i,context:this,funcName:r})},n}}function $V(e,t){return jV((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 tw(e)?e.then(e=>(t?UL.addSuccessEvent({key:r,cost:aw()-a}):UL.addSuccessEvent({key:r}),e)).catch(e=>{throw UL.addFailedEvent({key:r,error:e}),e}):(UL.addSuccessEvent({key:r}),e)}catch(Ak){throw UL.addFailedEvent({key:r,error:Ak}),Ak}})}var eF={};function tF(){}zb(eF,{Events:()=>fF,Inspect:()=>aF,LastSink:()=>cF,Sink:()=>lF,Subscribe:()=>dF,TimeoutError:()=>gF,audit:()=>AB,bindCallback:()=>$F,bindNodeCallback:()=>eB,buffer:()=>NF,bufferCount:()=>DF,bufferTime:()=>aH,call:()=>iF,catchError:()=>lH,combineLatest:()=>RF,concat:()=>SF,concatMap:()=>YB,concatMapTo:()=>XB,count:()=>sB,create:()=>hF,debounce:()=>bB,debounceTime:()=>kB,defer:()=>OF,delay:()=>cH,deliver:()=>pF,dispose:()=>nF,elementAt:()=>DB,empty:()=>rB,every:()=>MB,exhaustMap:()=>rH,exhaustMapTo:()=>nH,expand:()=>uH,filter:()=>dB,find:()=>NB,findIndex:()=>wB,first:()=>PB,fromAnimationFrame:()=>QF,fromArray:()=>BF,fromEvent:()=>zF,fromEventPattern:()=>jF,fromFetch:()=>KF,fromIterable:()=>qF,fromPromise:()=>JF,fromReadableStream:()=>XF,fromReader:()=>YF,groupBy:()=>oH,identity:()=>rF,ignoreElements:()=>uB,iif:()=>AF,inspect:()=>oF,interval:()=>HF,last:()=>OB,map:()=>VB,mapTo:()=>FB,max:()=>aB,merge:()=>vF,mergeMap:()=>$B,mergeMapTo:()=>eH,min:()=>cB,never:()=>tB,nothing:()=>tF,of:()=>FF,pairwise:()=>xB,pipe:()=>uF,race:()=>yF,range:()=>ZF,reduce:()=>oB,retry:()=>gH,scan:()=>LB,setAsapScheduler:()=>UF,share:()=>TF,shareReplay:()=>IF,skip:()=>fB,skipUntil:()=>gB,skipWhile:()=>EB,startWith:()=>bF,subject:()=>PF,subscribe:()=>mH,sum:()=>lB,switchMap:()=>jB,switchMapTo:()=>JB,take:()=>hB,takeLast:()=>_B,takeUntil:()=>pB,takeWhile:()=>mB,tap:()=>_H,throttle:()=>SB,throwError:()=>iB,timeInterval:()=>sH,timeout:()=>fH,timer:()=>WF,toPromise:()=>hH,toReadableStream:()=>pH,withLatestFrom:()=>kF,zip:()=>CF});var iF=e=>e(),rF=e=>e;function nF(){this.dispose()}var oF=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,sF=1,aF=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new _F(e,this,this.streamId++);return fF.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},cF=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=tF,this.error=tF,this.next=tF,this.dispose=tF,this.subscribe=tF,this.doDefer()}subscribe(e){return e instanceof aF?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(iF),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}},lF=class extends cF{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)}},dF=class extends cF{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tF,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:tF,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:tF;if(super(),this._next=t,this._error=i,this._complete=r,this.then=tF,e instanceof aF){let n={toString:()=>"subscribe",id:0,source:e};this.defer(()=>{fF.defer(n,0)}),fF.create(n),fF.pipe(n),this.sourceId=n.id,this.subscribe(e),fF.subscribe({id:n.id,end:!0}),t==tF?this._next=e=>fF.next(n,0,e):this.next=e=>{fF.next(n,0,e),t(e)},r==tF?this._complete=()=>fF.complete(n,0):this.complete=()=>{this.dispose(),fF.complete(n,0),r()},i==tF?this._error=e=>fF.complete(n,0,e):this.error=e=>{this.dispose(),fF.complete(n,0,e),i(e)}}else this.subscribe(e)}next(e){this._next(e)}complete(){this.dispose(),this._complete()}error(e){this.dispose(),this._error(e)}};function uF(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 hF(e,t,i){if(oF()){let r=Object.defineProperties(Object.setPrototypeOf(e,aF.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}});fF.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof aF&&fF.addSource(r,t)}return r}return e}function pF(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 aF){let n=hF(t=>{let o=new e(t,...r);o.sourceId=n.id,o.subscribe(i)},t,arguments);return n.source=i,fF.pipe(n),n}return t=>i(new e(t,...r))}}}function mF(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var _F=class extends lF{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer(()=>{fF.defer(this.source,this.id)})}next(e){fF.next(this.source,this.id,e),this.sink.next(e)}complete(){fF.complete(this.source,this.id),this.sink.complete()}error(e){fF.complete(this.source,this.id,e),this.sink.error(e)}},fF={addSource(e,t){mF("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){mF("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;mF("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){mF("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){mF("defer",{id:e.id,streamId:t})},pipe(e){mF("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){mF("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=sF++),mF("create",{name:e.toString(),id:e.id})}},gF=class extends Error{constructor(e){super("timeout after ".concat(e,"ms")),this.timeout=e}},EF=class extends cF{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 TF(){return e=>{let t=new EF(e);if(e instanceof aF){let i=hF(e=>{t.add(e)},"share",arguments);return t.sourceId=i.id,i.source=e,fF.pipe(i),i}return hF(t.add.bind(t),"share",arguments)}}function vF(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return hF(e=>{let i=new lF(e),r=t.length;i.complete=()=>{0===--r&&e.complete()},t.forEach(i.bindSubscribe)},"merge",arguments)}function yF(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return hF(e=>{let i=new Map;t.forEach(t=>{let r=new lF(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 SF(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return hF(e=>{let i=0,r=t.length,n=new lF(e);n.complete=()=>{i<r&&!n.disposed?(n.doDefer(),n.subscribe(t[i++])):e.complete()},n.complete()},"concat",arguments)}function IF(e){return t=>{let i=new EF(t),r=[];return i.next=function(t){r.push(t),r.length>e&&r.shift(),this.sinks.forEach(e=>e.next(t))},hF(e=>{e.defer(()=>i.remove(e)),r.forEach(t=>e.next(t)),i.add(e)},"shareReplay",arguments)}}function AF(e,t,i){return hF(r=>e()?t(r):i(r),"iif",arguments)}function RF(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return hF(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 lF(e);n.next=t=>{r--,n.next=t=>{o[i]=t,0===r&&e.next(o)},n.next(t)},n.complete=s,n.subscribe(t)})},"combineLatest",arguments)}function CF(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return hF(e=>{let i=t.length,r=i,n=new Array(i),o=()=>{0===--r&&e.complete()};t.forEach((t,i)=>{let r=new lF(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 bF(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>hF(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 kF=pF(class extends lF{constructor(e){super(e);let t=new lF(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=tF,t.subscribe(RF(...r))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},"withLatestFrom"),DF=pF(class extends lF{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"),NF=pF(class extends lF{constructor(e,t){super(e),this.buffer=[];let i=new lF(e);i.next=t=>{e.next(this.buffer),this.buffer=[]},i.complete=tF,i.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),wF=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 PF(e){let t=arguments,i=TF()(hF(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=tF,i.complete=tF,i.error=tF,i}function OF(e){return hF(t=>t.subscribe(e()),"defer",arguments)}var MF={promise:e=>{Promise.resolve().then(e)},setImmediate:"undefined"!=typeof setImmediate?e=>setImmediate(e):null,setTimeout:e=>setTimeout(e,0)},LF="undefined"!=typeof Promise?MF.promise:MF.setImmediate?MF.setImmediate:MF.setTimeout,xF=e=>t=>{LF(()=>e(t))},UF=e=>{"function"==typeof e?LF=e:MF[e]&&(LF=MF[e])},VF=e=>xF(t=>{for(let i=0;!t.disposed&&i<e.length;i++)t.next(e[i]);t.complete()});function FF(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return hF(VF(t),"of",arguments)}function BF(e){return hF(VF(e),"fromArray",arguments)}function HF(e){return hF(t=>{let i=0,r=setInterval(()=>t.next(i++),e);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function WF(e,t){return hF(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 GF(e,t){return i=>{let r=e=>i.next(e);i.defer(()=>t(r)),e(r)}}function jF(e,t){return hF(GF(e,t),"fromEventPattern",arguments)}function zF(e,t){if("on"in e&&"off"in e)return hF(GF(i=>e.on(t,i),i=>e.off(t,i)),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return hF(GF(i=>e.addListener(t,i),i=>e.removeListener(t,i)),"fromEvent",arguments);if("addEventListener"in e)return hF(GF(i=>e.addEventListener(t,i),i=>e.removeEventListener(t,i)),"fromEvent",arguments);throw"target is not a EventDispachter"}function JF(e){return hF(t=>{e.then(e=>{t.next(e),t.complete()},t.error.bind(t))},"fromPromise",arguments)}function KF(e,t){return hF(OF(()=>JF(fetch(e,t))),"fromFetch",arguments)}function qF(e){return hF(xF(t=>{try{for(let i of e){if(t.disposed)return;t.next(i)}t.complete()}catch(Ik){t.error(Ik)}}),"fromIterable",arguments)}function YF(e){let t=i=>wF(this,void 0,void 0,function*(){try{if(i.disposed)return;let{done:r,value:n}=yield e.read();if(r)return void i.complete();i.next(n),t(i)}catch(kD){i.error(kD)}});return hF(e=>{t(e)},"fromReader",arguments)}function XF(e){return hF(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 QF(){return hF(e=>{let t=requestAnimationFrame(function i(r){e.disposed||(e.next(r),t=requestAnimationFrame(i))});e.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function ZF(e,t){return hF(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 $F(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 hF(i=>{let n=r.concat(e=>(i.next(e),i.complete()));e.apply(t,n)},"bindCallback",arguments)}function eB(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 hF(i=>{let n=r.concat((e,t)=>e?i.error(e):(i.next(t),i.complete()));e.apply(t,n)},"bindNodeCallback",arguments)}function tB(){return hF(()=>{},"never",arguments)}function iB(e){return hF(t=>t.error(e),"throwError",arguments)}function rB(){return hF(e=>e.complete(),"empty",arguments)}var nB=class extends lF{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)}},oB=pF(nB,"reduce"),sB=e=>pF(nB,"count")((t,i)=>e(i)?t+1:t,0),aB=()=>pF(nB,"max")(Math.max),cB=()=>pF(nB,"min")(Math.min),lB=()=>pF(nB,"sum")((e,t)=>e+t,0),dB=pF(class extends lF{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"),uB=pF(class extends lF{next(e){}},"ignoreElements"),hB=pF(class extends lF{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0===--this.count&&(this.doDefer(),this.complete())}},"take"),pB=pF(class extends lF{constructor(e,t){super(e);let i=new lF(e);i.next=()=>{i.doDefer(),e.complete()},i.complete=nF,i.subscribe(t)}},"takeUntil"),mB=pF(class extends lF{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):(this.doDefer(),this.complete())}},"takeWhile"),_B=e=>oB((t,i)=>(t.push(i),t.length>e&&t.shift(),t),[]),fB=pF(class extends lF{constructor(e,t){super(e),this.count=t}next(e){0===--this.count&&(this.next=super.next)}},"skip"),gB=pF(class extends lF{constructor(e,t){super(e),e.next=tF;let i=new lF(e);i.next=()=>{i.doDefer(),e.resetNext()},i.complete=nF,i.subscribe(t)}},"skipUntil"),EB=pF(class extends lF{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),TB={leading:!0,trailing:!1},vB=class extends lF{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)}},yB=class extends lF{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:TB;super(e),this.durationSelector=t,this.config=i,this._throttle=new vB(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=tF,this._throttle.complete(),super.complete()}},SB=pF(yB,"throttle"),IB={leading:!1,trailing:!0},AB=e=>pF(yB,"audit")(e,IB),RB=class extends lF{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},CB=class extends lF{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new RB(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()}},bB=pF(CB,"debounce"),kB=e=>pF(CB,"debounceTime")(t=>WF(e)),DB=pF(class extends lF{constructor(e,t,i){super(e),this.count=t,this.defaultValue=i}next(e){0===this.count--&&(this.defaultValue=e,this.doDefer(),this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("not enough elements in sequence"))}},"elementAt"),NB=e=>t=>hB(1)(EB(t=>!e(t))(t)),wB=pF(class extends lF{constructor(e,t){super(e),this.f=t,this.i=0}next(e){this.f(e)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},"findIndex"),PB=pF(class extends lF{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.doDefer(),this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"first"),OB=pF(class extends lF{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"),MB=pF(class extends lF{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.doDefer(),this.complete())}complete(){void 0!==this.result?(this.sink.next(this.result),super.complete()):this.error(new Error("no elements in sequence"))}},"every"),LB=pF(class extends lF{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"),xB=pF(class extends lF{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},"pairwise"),UB=class extends lF{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},VB=pF(UB,"map"),FB=e=>pF(UB,"mapTo")(t=>e),BB=class extends lF{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()}},HB=class e extends lF{constructor(e,t,i){super(e),this.makeSource=t,this.combineResults=i,this.index=0}subInner(t,i){let r=this.currentSink=new i(this.sink,t,this);this.complete===e.prototype.complete&&(this.complete=this.tryComplete),r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},WB=class extends BB{},GB=class extends HB{next(e){this.subInner(e,WB),this.next=e=>{this.currentSink.dispose(),this.subInner(e,WB)}}},jB=pF(GB,"switchMap");function zB(e){return(t,i)=>e(()=>t,i)}var JB=zB(pF(GB,"switchMapTo")),KB=class extends BB{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},qB=class extends HB{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(),KB),this.disposed&&0===this.sources.length&&this.currentSink.resetComplete()}tryComplete(){0===this.sources.length&&this.currentSink.resetComplete(),this.dispose()}},YB=pF(qB,"concatMap"),XB=zB(pF(qB,"concatMapTo")),QB=class extends BB{tryComplete(){this.context.inners.delete(this),super.dispose(),0===this.context.inners.size&&this.context.resetComplete()}},ZB=class extends HB{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,QB),this.inners.add(this.currentSink)}tryComplete(){1===this.inners.size?this.inners.forEach(e=>e.resetComplete()):this.dispose()}},$B=pF(ZB,"mergeMap"),eH=zB(pF(ZB,"mergeMapTo")),tH=class extends BB{dispose(){this.context.resetNext(),super.dispose()}},iH=class extends HB{next(e){this.next=tF,this.subInner(e,tH)}},rH=pF(iH,"exhaustMap"),nH=zB(pF(iH,"exhaustMapTo")),oH=pF(class extends lF{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=PF(),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"),sH=pF(class extends lF{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"),aH=pF(class extends lF{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"),cH=pF(class extends lF{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"),lH=pF(class extends lF{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),dH=class extends BB{tryComplete(){let e=this.context.inners.delete(this);super.dispose(),e&&this.context.checkComplete()}next(e){this.sink.next(e),this.context.expandValue(e)}},uH=pF(class extends HB{constructor(e,t){super(e,t),this.project=t,this.inners=new Set,this.sourceCompleted=!1}next(e){this.sink.next(e),this.expandValue(e)}expandValue(e){let t=new dH(this.sink,e,this);this.currentSink=t,this.complete=this.tryComplete,t.complete=t.tryComplete,this.inners.add(t),t.subscribe(this.makeSource(e,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&0===this.inners.size&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},"expand"),hH=()=>e=>new Promise((t,i)=>{let r;new dF(e,e=>r=e,i,()=>t(r))}),pH=()=>e=>{let t;return new ReadableStream({start(i){t=new dF(e,i.enqueue.bind(i),i.error.bind(i),i.close.bind(i))},cancel(){t.dispose()}})},mH=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tF,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tF,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:tF;return r=>new dF(r,e,t,i)},_H=pF(class extends lF{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"),fH=pF(class extends lF{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout(()=>this.error(new gF(this.timeout)),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),gH=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0;return t=>{if(t instanceof aF){let i=hF(r=>{let n=e,o=new lF(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,fF.pipe(i),i}return i=>{let r=e,n=new lF(i);n.error=e=>{r-- >0?t(n):i.error(e)},t(n)}}},EH=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(EH||{}),TH=class e extends OV{constructor(e,t){super({mediaType:e,PlayerClass:t}),qb(this,"isRemote",!1),qb(this,"deviceId"),qb(this,"groupId",""),qb(this,"label",""),qb(this,"sourceTrack"),qb(this,"enableAutoSwitchWhenRecapturing",!0),qb(this,"_isRecapturing",!1),qb(this,"_lastRecaptureTime",0),qb(this,"_onMuteTimeoutId",-1),qb(this,"_encodeCheckTimeoutId",-1),qb(this,"recaptureMode",0),qb(this,"profile"),qb(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return"publishing"===this.state.toString()}get isPublished(){return"publish"===this.state}get isUseCustomSource(){return!(!this.mediaTrack||this.sourceTrack===this.mediaTrack)}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener($k.MUTE,this.onTrackMuted),e.addEventListener($k.UNMUTE,this.onTrackUnmuted),e.addEventListener($k.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===$k.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener($k.MUTE,this.onTrackMuted),e.removeEventListener($k.UNMUTE,this.onTrackUnmuted),e.removeEventListener($k.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Xb(this,null,function*(){var i;let r=this.sourceTrack;try{let r,n=aw();oM.emit(aM.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(r=new MediaStream,r.addTrack(e.customSource)):(t||null==(i=this.sourceTrack)||i.stop(),r=yield BV(e));let o=r.getTracks()[0];return yield this.setInputMediaStreamTrack(o),e.customSource||(this.sourceTrack=o,this.updateDeviceIdInUse(),this.listenDeviceChange()),oM.emit(aM.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:aw()-n}),r}catch(Ak){throw oM.emit(aM.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:Ak}),this.log.error("getUserMedia error observed ".concat(Ak)),Ak}finally{t&&(null==r||r.stop())}})}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=hw((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 Xb(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((t,i)=>Xb(this,null,function*(){var r,n,o,s,a;let c=()=>i(new dk({code:ck.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===eU.INIT||"ready"===this.state)&&c(),uF(zF(e,"local-publish-flag-changed"),dB(()=>this.hasFlag),pB(vF(zF(this,eU.INIT),zF(this,"ready"))),mH(t,i,c))),null!=(o=null==(n=null==(r=this.room)?void 0:r.networkQuality)?void 0:n.hadRecentBadUplink)&&o.call(n,2))return t();let l=e.heartbeatCount,d=(null==(a=null==(s=this.mediaTrack)?void 0:s.stats)?void 0:a.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>Xb(this,null,function*(){var r,n,o,s,a,c,u,h;if(null!=(o=null==(n=null==(r=this.room)?void 0:r.networkQuality)?void 0:n.hadRecentBadUplink)&&o.call(n,2)||e.heartbeatCount-l<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if(null!=(s=this.mediaTrack)&&s.stats){let e=this.mediaTrack.stats.totalFrames||0;e-d===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",e)}let e=this.kind===$k.AUDIO,r=this.stat.bytesSent>0;if(UL[r?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),!e){let e={H264:513704,H265:513705,VP8:513706}[(null==(c=null==(a=this.room)?void 0:a.videoCodec)?void 0:c.toUpperCase())||"H264"];e&&UL[r?"addSuccessEvent":"addFailedEvent"]({key:e})}if(!r){if(UL.addEnum({key:e?503701:513703,value:$O()}),hU.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(YO()||tM()),userId:this.userId}),this.log.warn(e?"encode failed":"".concat(null==(h=null==(u=this.room)?void 0:u.videoCodec)?void 0:h.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield bw(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),i(new dk({message:"".concat(this.strMediaType," encode failed"),code:e?ck.AUDIO_ENCODE_FAILED:ck.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),oM.emit(aM.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return Xb(this,null,function*(){if(this.sourceTrack&&Sx){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:i}=this.sourceTrack;(yield function(e){return Xb(this,arguments,function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==$k.AUDIO||t!==KD||(yield bV(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),yV().then(i=>{let r=i.find(i=>{let r=i.deviceId===e;return t&&(r=r&&i.groupId===t),r});r&&this.emit("2",r)}))}})}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===$k.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($k.AUDIO_INPUT);return!!CV.has(i)}(this.sourceTrack)||this.kind===$k.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($k.VIDEO_INPUT);return!!CV.has(i)}(this.sourceTrack)||this._isRecapturing||e&&YP&&AO)}onTrackMuted(){if(super.onTrackMuted(),zV(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<$D)return void setTimeout(()=>this.onTrackMuted(),$D);this._onMuteTimeoutId=setTimeout(()=>Xb(this,null,function*(){var e;if(null!=(e=this.sourceTrack)&&e.muted){if((hP||mP)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return Xb(this,null,function*(){if(Yb(e.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&0===this.recaptureMode){if(Date.now()-this._lastRecaptureTime<$D)return void setTimeout(()=>this.onTrackEnded(),$D);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Xb(this,null,function*(){var i;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||null==(i=this.sourceTrack)||i.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let n={useExactDeviceId:!0};if("user"===e||"environment"===e)n.facingMode=e;else{let t;("audio"===this.kind?yield SV():yield IV()).find(t=>t.deviceId===e)&&(t=e),n.deviceId=t}return this.capture(n,t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),oM.emit(aM.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),oM.emit(aM.LOCAL_TRACK_RECAPTURE,{track:this,error:e})}).finally(()=>{t&&(null==r||r.stop())})})}getRecoverCaptureDeviceId(){return Xb(this,null,function*(){let e=this instanceof kH;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(yH.get(t)||0)+1;if(yH.set(t,i),i>=3&&this.enableAutoSwitchWhenRecapturing){let r=e?(yield IV()).find(e=>!yH.has(e.deviceId)):(yield SV()).find(e=>!yH.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)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),null==(e=this.manager)||e.removeInput(this)}close(){super.close(),this.stopCapture()}};Kb([Qx(eU.INIT,"ready",{ignoreError:!0,sync:!0})],TH.prototype,"setStateToReady",1),Kb([XV()],TH.prototype,"capture",1),Kb([Qx("ready","publish",{ignoreError:!0,success(){oM.emit(aM.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var t;null==(t=this.room)||t.localTracks.delete(this);let i="error",r=e instanceof dk?e:e.cause instanceof dk?e.cause:e,n=!1;r instanceof dk&&(r.message.includes("timeout")?i="timeout":r.code===ck.API_CALL_ABORTED&&(n=!0,i="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:r}),this.log[n?"info":"error"]("publish failed",r)}}),$V(521714,!1)],TH.prototype,"publish",1),Kb([jV(e=>function(){return Xb(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)})}),Qx([],"ready",{sync:!0})],TH.prototype,"unpublish",1);var vH=TH,yH=new Map;oM.on(aM.SWITCH_DEVICE_SUCCESS,e=>{e.track.deviceId&&yH.delete(e.track.deviceId)});var SH=class e extends vH{constructor(e){super(1,wV),qb(this,"mediaType",1),qb(this,"volume",0),qb(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),qb(this,"playerMuted",!0),qb(this,"pipeline"),qb(this,"earMonitorGainNode",new nV),qb(this,"_output",new nV),qb(this,"codecPipeline",[]),qb(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),qb(this,"mixedAudioReferenceMap",new Map),qb(this,"isAudioContextLongSuspended",!1),qb(this,"after3aSilenceStartTime",0),qb(this,"_micMuted",!1),qb(this,"_volumeDetectionTrack",null),qb(this,"_volumeDetectionSource",new nV),this.manager=e,this.pipeline=new aV(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._volumeDetectionSource.pipeTo(this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),oM.on(aM.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return mV.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.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){KN(e)||(0!==e||this.after3aSilenceStartTime?e>0&&(this.after3aSilenceStartTime=0):this.after3aSilenceStartTime=aw())}setInputMediaStreamTrack(t){return Xb(this,null,function*(){let i=this.trackSettings||{};UL.addEnum({key:501701,value:i.channelCount||0,useUV:!1}),UL.addEnum({key:501702,value:i.sampleRate||0,useUV:!1}),UL.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 Yb(e.prototype,this,"setInputMediaStreamTrack").call(this,t),this.updatePlayingState(!!t)})}capture(t){return Xb(this,arguments,function(t){var i=this;let{deviceId:r,customSource:n,useExactDeviceId:o=!0,retryWhenExactFailed:s}=t,a=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){let t=yield Yb(e.prototype,i,"capture").call(i,{video:!1,audio:!0,microphoneId:r,echoCancellation:i.profile.echoCancellation,autoGainControl:i.profile.autoGainControl,noiseSuppression:i.profile.noiseSuppression,sampleRate:i.profile.sampleRate,channelCount:i.profile.channelCount,useExactDeviceId:o,retryWhenExactFailed:s,customSource:n},a);return iV(),t}()})}switchDevice(e){return Xb(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource){if(e!==KD)return;if(yield bV(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}),oM.emit(aM.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(kD){throw this.log.error("switch microphone failed ".concat(kD)),this.deviceId&&this.recapture(this.deviceId),kD}}})}listenDeviceChange(){TV&&!TV.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&TV.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return Xb(this,null,function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(EH[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){_W(this.userId,{eventId:2003,param1:6,streamType:1});let e=yield SV();e[0]?this.recapture(e[0].deviceId):t=!0}t&&TV.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){1===this.recaptureMode&&e.deviceId!==this.deviceId||(TV.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}update3A(e){return Xb(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;!KN(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,o.echoCancellation=i,s=!0),!KN(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,o.noiseSuppression=r,s=!0),!KN(n)&&n!==t.profile.autoGainControl&&(t.profile.autoGainControl=n,o.autoGainControl=n,s=!0),s&&(EP||AO?yield e.applyConstraints(o).catch(e=>t._log.warn("update3A failed: ",e)):t.deviceId&&(yield t.recapture(t.deviceId,!0)))}()})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&UL.addEnum({key:502700,value:2})}setMute(e,t){var i;this._cleanupVolumeDetectionTrack(),"microphone"===e?(this._micMuted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),t&&this._setupVolumeDetectionTrack(),(null==(i=this.manager)?void 0:i.mixWeight)<=1?(this.muted=!0,this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),this.emit("mute",this),oM.emit(aM.TRACK_MUTED,{track:this})):this._outputTrack&&(this._outputTrack.enabled=!0)):!0===e?(this._micMuted=!1,this.muted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),t&&this._setupVolumeDetectionTrack(),this.emit("mute",this),oM.emit(aM.TRACK_MUTED,{track:this})):(this._micMuted=!1,this.muted=!1,this.sourceTrack&&(this.sourceTrack.enabled=!0),this._inputTrack&&(this._inputTrack.enabled=!0),this._outputTrack&&(this._outputTrack.enabled=!0),this.emit("unmute",this),oM.emit(aM.TRACK_UNMUTED,{track:this}))}_setupVolumeDetectionTrack(){let e=this.sourceTrack||this.mediaTrack;if(!e)return;this._volumeDetectionTrack=e.clone(),this._volumeDetectionTrack.enabled=!0;let t=dV(this._volumeDetectionTrack);t&&this._volumeDetectionSource.setNode(t)}_cleanupVolumeDetectionTrack(){this._volumeDetectionTrack&&(this._volumeDetectionTrack.stop(),this._volumeDetectionTrack=null),this._volumeDetectionSource.deleteNode()}get isMicMuted(){return this._micMuted}setAudioVolume(e){super.setAudioVolume(0),hP&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(rV().createGain()),this._output.setNode(rV().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!AO&&!hP)return this.update3A({echoCancellation:e})}addDenoiser(e){var t;vO<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(UL.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=dV(e);if(!i)return;let r=new nV,n=rV().createGain();n.gain.value=1;let o=new nV;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._cleanupVolumeDetectionTrack(),this.mixedAudioReferenceMap.forEach(e=>{let[t,i]=e;t.deleteNode(),i.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),TV.off("audioInputAdded",this.handleMicrophoneAdded,this),TV.off("audioInputRemoved",this.handleMicrophoneRemoved,this),oM.off(aM.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(t){let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Xb(this,null,function*(){try{yield Yb(e.prototype,this,"recapture").call(this,t,i)}catch(TM){let r=(yield SV()).find(e=>e.deviceId!==t);if(!r)throw TM;yield Yb(e.prototype,this,"recapture").call(this,r.deviceId)}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((e,t)=>t?t({frame:e,ntp:_k()}):e,e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(e=>e)}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}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(RO?"":", 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)}};function IH(e,t){return t+4<=e.byteLength&&0===e.getUint8(t)&&0===e.getUint8(t+1)&&0===e.getUint8(t+2)&&1===e.getUint8(t+3)?4:t+3<=e.byteLength&&0===e.getUint8(t)&&0===e.getUint8(t+1)&&1===e.getUint8(t+2)?3:0}function AH(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=new DataView(e),r=[],n=0;for(;n<i.byteLength;){let e=IH(i,n);if(0===e){n+=1;continue}let o=-1;for(let t=n+e;t<i.byteLength;t+=1)if(IH(i,t)>0){o=t;break}let s=-1===o?i.byteLength:o,a=s-n,c=new ArrayBuffer(a),l=new DataView(c);for(let t=0;t<a;t+=1)l.setUint8(t,i.getUint8(n+t));r.push(new RH(l,t)),n=s}return r}var RH=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{seiPayloadStartIndex:e}=this,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+=1: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{seiPayloadStartIndex:e}=this,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 seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e+=1,255===this.dataView.getUint8(t));t+=1);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 o=6;o<this.dataView.buffer.byteLength;o+=1){let i=this.dataView.getUint8(o);if(t+=1,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),r=new DataView(i),n=t;for(let o=0;o<i.byteLength;o+=1)r.setInt8(o,this.dataView.getInt8(n+o));return r}get naluType(){let e=this.getStartCodeLength();return e>=this.dataView.byteLength?0:31&this.dataView.getUint8(e)}getStartCodeLength(){return this.dataView.byteLength>=4&&0===this.dataView.getUint8(0)&&0===this.dataView.getUint8(1)&&0===this.dataView.getUint8(2)&&1===this.dataView.getUint8(3)?4:this.dataView.byteLength>=3&&0===this.dataView.getUint8(0)&&0===this.dataView.getUint8(1)&&1===this.dataView.getUint8(2)?3:0}get isIDR(){return 5===this.naluType}get isSPS(){return 7===this.naluType}get isPPS(){return 8===this.naluType}get isSEI(){return 6===this.naluType}},CH=class{constructor(){qb(this,"_seiMessageList",[]),qb(this,"_smallSeiMessageList",[]),qb(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 RH(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}},bH=class e extends vH{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,WU),qb(this,"profile",Hb({},Xk)),qb(this,"avoidCropping",!1),qb(this,"_scaleResolutionDownBy"),qb(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0}),qb(this,"small"),qb(this,"isNeedToSetBandwidth"),qb(this,"muteImage"),qb(this,"manager"),qb(this,"_seiCodec",new CH),this.manager=e;let t=()=>{var e;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1});else{let t=CN((null==(e=this.room)?void 0:e.sdkAppId)||0)?Uk:xk;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(t)),this.setProfile(Wb(Hb({},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(Sx&&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)}get hasSmall(){var e;return!(null==(e=this.manager)||!e.hasSmall)}setMute(t){return Xb(this,null,function*(){var i,r,n;if(qN(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,fillVideo:!0}),this.muteImage=t,Yb(e.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield null==(n=this.manager)?void 0:n.deleteWatermark("mute"),this.muteImage=void 0),Yb(e.prototype,this,"setMute").call(this,t)})}capture(t){return Xb(this,arguments,function(t){var i=this;let{deviceId:r,facingMode:n,useExactDeviceId:o=!0,customSource:s,retryWhenExactFailed:a=!0}=t;return function*(){let t={audio:!1,video:!0,facingMode:n||i.facingMode,cameraId:r,width:i.profile.width,height:i.profile.height,frameRate:i.profile.frameRate,useExactDeviceId:o,retryWhenExactFailed:a,customSource:s};if("environment"===t.facingMode){let e=yield i.getDeviceIdWhenUsingBackCamera();e&&(t.cameraId=e)}return Yb(e.prototype,i,"capture").call(i,t)}()})}setProfile(e){var t;let i=this.fallbackProfile(e);if(i.bitrate&&(this.isNeedToSetBandwidth=i.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(i);else{let e=CN((null==(t=this.room)?void 0:t.sdkAppId)||0)?Uk:xk;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(e)),super.setProfile(Wb(Hb({},this.profile),{width:1920,height:1080}))}}applyProfile(){return Xb(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===wO&&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:$k.VIDEO,videoType:$k.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return Sx&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:ww(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 Xb(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),oM.emit(aM.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(kD){throw this.log.error("switch camera failed ".concat(kD)),this.deviceId&&this.recapture(this.deviceId),kD}})}getDeviceIdWhenUsingBackCamera(){return Xb(this,null,function*(){let e;try{if(nO&&!pO&&Ax){let t=(yield IV(!0)).map(e=>{var t;return Wb(Hb({},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=t[0];t.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&&(this._log.info("use max resolution back camera",i),e=i.deviceId)}}catch(kD){this._log.warn("get max res camera failed",kD)}return e})}updateSmallConfig(e){return Xb(this,null,function*(){var t,i;this._log.info("update small stream config: ".concat(JSON.stringify(e)));let r=!this.small;this.small=this.fallbackProfile(e,!0),yield null==(t=this.manager)?void 0:t.update(),r&&(yield null==(i=this.room)?void 0: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=Hb({},e);return e.width*e.height<=19200&&mP&&gO&&(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&&MO&&(r.width=i?1280:720,r.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),DO(kO,"14.3")&&NO(kO,"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&&(gO||EP)&&!HO()&&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(){TV&&!TV.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&TV.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return Xb(this,null,function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(EH[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){_W(this.userId,{eventId:2003,param1:7,streamType:2});let e=yield IV();e[0]?this.recapture(e[0].deviceId):t=!0}t&&TV.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return Xb(this,null,function*(){1===this.recaptureMode&&e.deviceId!==this.deviceId||(TV.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 KN(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){TV.off("videoInputAdded",this.handleCameraAdded,this),TV.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return Xb(this,null,function*(){try{yield Yb(e.prototype,this,"recapture").call(this,t)}catch(kD){let r=(yield IV()).find(e=>e.deviceId!==t);if(!r)throw kD;yield Yb(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||KN(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};Kb([WV(function(e){this.setContentHint(e.contentHint||"motion")})],bH.prototype,"capture",1);var kH=bH,DH={};zb(DH,{REPORT_TYPE:()=>Lw,buildSSOPackage:()=>xw,bytes2ms:()=>xN,calculateScaleResolutionDownNumber:()=>ww,concatArrayBuffers:()=>Uw,convertObjectNumberToInt:()=>Cw,copyProperties:()=>LN,deepClone:()=>fw,deepCloneBasic:()=>Mw,deepMerge:()=>_w,delay:()=>bw,fibonacci:()=>GN,formatedTime:()=>Tw,getConstructorName:()=>rw,getContainerFromElement:()=>Ew,getEnv:()=>AN,getFirst16Bits:()=>Fw,getInternalVersion:()=>lw,getLast16Bits:()=>Vw,getLoggerUrl:()=>bN,getMediaStreamTrackInfo:()=>Nw,getMuteStateFromFlag:()=>hw,getNetworkType:()=>DN,getNumNetworkType:()=>MN,getReconnectionTimeout:()=>jN,getStringByteLength:()=>Sw,getTestSignalDomain:()=>RN,getTurnServer:()=>pw,getUint32Version:()=>Rw,getValueType:()=>zN,getViewListFromView:()=>gw,glog:()=>BN,ipv4ToUint32:()=>mw,isArray:()=>ZN,isAudioWorkletSupported:()=>nw,isBoolean:()=>XN,isConstructor:()=>iw,isEmpty:()=>uw,isFunction:()=>JN,isLangChinese:()=>HN,isMediaStreamTrack:()=>$N,isNumber:()=>YN,isObject:()=>QN,isOverseaSdkAppId:()=>CN,isPlainObject:()=>WN,isPortrait:()=>Iw,isPromise:()=>tw,isRemoteTrack:()=>ew,isRotate90Or270:()=>Pw,isSetSinkIdSupported:()=>ow,isString:()=>qN,isUndefined:()=>KN,loadImage:()=>Aw,loadVideo:()=>Ow,ms2bytes:()=>VN,ms2samples:()=>FN,normalizeUrl:()=>Dw,performanceNow:()=>aw,promiseAny:()=>sw,samples2ms:()=>UN,setNetworkTypeFromWebRTC:()=>ON,stringify:()=>vw,stringifyIncludeValue:()=>yw,throttlePromise:()=>kw});var NH=[-1,-1,1,-1,-1,1,1,1],wH=[0,0,1,0,0,1,1,1],PH=class e extends eU{constructor(e,t){if(super(),this.context=e,qb(this,"name"),qb(this,"input"),qb(this,"output"),qb(this,"texture"),qb(this,"ctx2d",null),qb(this,"fbo"),qb(this,"width",0),qb(this,"height",0),qb(this,"x",0),qb(this,"y",0),qb(this,"program"),qb(this,"vertexShader"),qb(this,"fragmentShader"),qb(this,"totalFrames",0),qb(this,"dropFrames",0),qb(this,"matchInputSize",!0),qb(this,"texCoordBuffer"),qb(this,"positionBuffer"),qb(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),qb(this,"cost",0),qb(this,"_canvas",null),qb(this,"_image"),qb(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 KH)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==wO?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(wH),this.positionBuffer=this.createBuffer(NH),!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.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(TM){this.context.destroy(new dk({code:ck.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(TM.message||TM)}))}}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 JH&&this.render(e)||this.context instanceof KH&&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 JH){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=!(KN(s)||KN(a)||KN(c)||KN(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},Hb({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.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};qb(PH,"RENDER","render"),Kb([Qx(eU.INIT,"connected",{sync:!0})],PH.prototype,"connect",1),Kb([Qx("connected",eU.INIT,{ignoreError:!0,sync:!0})],PH.prototype,"disconnect",1),Kb([Qx([],"closed",{sync:!0})],PH.prototype,"close",1);var OH=PH,MH=uF(HF(250),VB(()=>performance.now()),TF()),LH=[0,1,1,1,0,0,1,0],xH=class extends OH{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),qb(this,"_intervalId",0),qb(this,"_sequence",0),qb(this,"checkGLError",!1),qb(this,"checkVisibilityChange"),e instanceof KH?this.ctx2d=e.ctx||null:e.available&&null!=t&&t.mirrorUpAndDown&&this.setTexBuffer(LH)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),sU.clearTask(this._intervalId),this._intervalId=sU.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(sU.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof JH){let e=this.context.ctx.getError();e&&this.context.destroy(new dk({code:ck.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(OH.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;"closed"!==this.state&&(this._intervalId&&(sU.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),sU.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),sU.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},UH=class extends xH{constructor(e,t){super(e,t),qb(this,"_videoTrack"),qb(this,"_muteOb"),qb(this,"_closedOb",zF(this,"closed")),qb(this,"_subscription"),qb(this,"_canvasContainer"),Number(CO)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=zF(this._videoTrack,"mute"),uF(zF(this._videoTrack,"ended"),pB(this._closedOb),mH(()=>{this.context.destroy(new dk({code:ck.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){var e;this._subscription=uF(this._muteOb,pB(this._closedOb),JB((e=5e3,t=>{let i=performance.now();uF(MH,EB(t=>t-i<e),hB(1))(t)})),dB(()=>{var e;return!(null==(e=this._videoTrack)||!e.muted||document.hidden)}),mH(()=>{this.context.destroy(new dk({code:ck.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()}},VH=class extends UH{render(e){var t;let i=!(null==(t=this.input)||!t.requestFrame(e));if(this.context._canvas2d){let e=this.context._canvas2d.getContext("2d");e.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),e.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height),this.emit(OH.RENDER,this.context._canvas2d)}else this.emit(OH.RENDER,this.context._canvas);return i}},FH=class extends UH{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))}},BH=class extends OH{constructor(e,t){super(e,Hb({name:"imageSource"},t)),qb(this,"_lastImage"),qb(this,"_totalFrames",0),qb(this,"_autoResize",!1),qb(this,"_canvasRendered"),qb(this,"videoCallbackId",0),qb(this,"waitingFirstFrame",!0),qb(this,"shouldUpdate",!0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===wO&&(this._canvasRendered=PF(),uF(this._canvasRendered,bF(this._image),jB(e=>e instanceof HTMLCanvasElement?zF(e,"rendered"):rB()),pB(zF(this,"closed")),mH(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Ux()&&!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)}},HH=class extends BH{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",uF(zF(this._player,aU.PLAYER_STATE_CHANGED),pB(zF(this,"closed")),dB(e=>{let{state:t}=e;return"PLAYING"===t}),mH(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},WH=class extends HH{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,t,i){super(e,new WU({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()}},GH=class extends OH{constructor(e,t,i){super(e,Wb(Hb({name:"textSource"},i),{create2d:!0})),qb(this,"hasChange",!0),qb(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)}},jH=class extends eU{constructor(e){super(),qb(this,"frameRate"),qb(this,"_canvas"),qb(this,"log"),qb(this,"hasAlpha",!1),qb(this,"name"),qb(this,"error"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}get canvas(){return this._canvas}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 WH(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new UH(this,e)}createVideoImageSource(e,t){return new BH(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new HH(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new GH(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};qb(jH,"_ids",0);var zH=class extends jH{constructor(){super(...arguments),qb(this,"defaultProgam"),qb(this,"defaultVShader"),qb(this,"defaultFShader"),qb(this,"ctx"),qb(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(jH._ids++)),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",rN),!this.ctx)throw new dk({code:ck.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 dk({code:ck.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,UL.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,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=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}};qb(zH,"UNAVAILABLE","unavailable"),Kb([Qx(eU.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),UL.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),UL.addSuccessEvent({key:512700})}})],zH.prototype,"create",1),Kb([Qx("created",eU.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(zH.UNAVAILABLE,e),this.removeAllListeners()}})],zH.prototype,"destroy",1);var JH=zH,KH=class extends jH{constructor(){super(...arguments),qb(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(jH._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new dk({code:ck.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,UL.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(),UL.addSuccessEvent({key:512703})}};function qH(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}Kb([Qx(eU.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),UL.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),UL.addSuccessEvent({key:512701})}})],KH.prototype,"create",1),Kb([Qx("created",eU.INIT,{ignoreError:!0,sync:!0})],KH.prototype,"destroy",1);var YH=class{constructor(e,t){this.node=e,this.layout=t,qb(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}},XH=class extends OH{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),qb(this,"inputs",[]),qb(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 YH(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(!KN(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];KN(r)||(u.layout.x=r),KN(n)||(u.layout.y=n),KN(o)||(u.layout.width=o),KN(s)||(u.layout.height=s),KN(l)||(u.layout.rotation=l),KN(d)||(u.layout.hidden=d),c&&(u.layout.fillMode=c),!KN(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 JH&&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=qH(t.node.width,t.node.height,t.width,t.height,t.fillMode,Pw(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},Hb({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 JH)try{null==(t=this.context.ctx)||t.deleteBuffer(e.positionBuffer)}catch(TM){}})}close(){super.close(),this.removeAllInputs()}},QH=[1,0,0,0,1,1,0,1],ZH=class extends OH{constructor(e,t,i,r){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t}),qb(this,"mirror",!1),qb(this,"rotation",0),i&&(this.mirror=i),r&&(this.rotation=r),e instanceof JH)try{this.setTexBuffer(QH)}catch(Ak){e.destroy(new dk({code:ck.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(Ak.message||Ak)}))}}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){Pw(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}},$H=class extends vH{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,WU),qb(this,"inputLocalVideoTracks",new Map),qb(this,"inputLocalScreenTracks",new Map),qb(this,"cameraNodeMap",new Map),qb(this,"screenNodeMap",new Map),qb(this,"textNodeMap",new Map),qb(this,"imageNodeMap",new Map),qb(this,"videoNodeMap",new Map),qb(this,"endedIds",new Set),qb(this,"videoContext"),qb(this,"mixNode"),qb(this,"destination"),qb(this,"manager"),qb(this,"stat"),qb(this,"_checkId",0),qb(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(OH.RENDER,e=>{this.emit("render",e)}),this.mixNode=new XH(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=sU.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new KH({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 Xb(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),RO&&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,dU(this,TV).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===wO&&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 screenSource failed");t.on("output-media-track-changed",()=>{this.updateScreenSource(e,i,t.mediaTrack)});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===wO&&i instanceof CanvasCaptureMediaStreamTrack)if(n instanceof WH){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 WH)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=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=this.screenNodeMap.get(e);r&&(i&&r.replaceTrack(i),this._changeMixLayout(r,t))}updateTextSource(e){let{id:t,content:i,font:r,color:n,layout:o}=e,s=this.textNodeMap.get(t);s&&(KN(i)||(s.content=i),KN(r)||(s.font=r),KN(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 ZH(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 ZH&&(KN(i)||(n.mirror=i),KN(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 ZH&&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 ZH&&i.output.close(),i.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof ZH&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof ZH&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof ZH&&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(),sU.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(),uU(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")}},eW=uM();if("undefined"!=typeof navigator&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:eW,exposeOrigin:!0,permittedOrigins:["*"]})}catch(QJ){}var tW=function(e){return Xb(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:AO?{max:e.width}:{ideal:e.width,max:e.width},height:AO?{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);dM.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(EO&&vO<74||AO||EP)&&dM.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(IM){dM.warn("screen applyConstraints failed: ".concat(IM))}e.captureElement&&(yield function(e,t){return Xb(this,null,function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&JN(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==eW)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){dM.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 KN(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);dM.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r})},iW=class extends kH{constructor(e){super(e,2),qb(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),qb(this,"objectFit","contain"),qb(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}get isShareCurrentTab(){var e,t;try{return eW===(null==(t=null==(e=this.mediaTrack)?void 0:e.getCaptureHandle())?void 0:t.handle)}catch(TM){return}}capture(e){return Xb(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,d=aw();return a||s?(e=new MediaStream,a&&e.addTrack(a),s&&e.addTrack(s)):(e=yield tW({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]),oM.emit(aM.LOCAL_TRACK_CAPTURE_SUCCESS,{track:t,cost:aw()-d}),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof dk?e:new dk({code:ck.INITIALIZE_FAILED,name:e.name,message:e.message})}}()})}switchDevice(e){return Xb(this,null,function*(){throw new Error("Method not implemented.")})}};Kb([WV(function(e){this.setContentHint(e.contentHint||"detail")})],iW.prototype,"capture",1);var rW,nW=class extends SH{constructor(e){super(e),this._log.id="s-".concat(this._log.id),this.isScreen=!0}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 oW(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 Xb(this,null,function*(){let n=rV();rW||(rW=GU(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 rW;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 sW=class extends cV{constructor(e){super(),this.room=e,qb(this,"_localAudioTrack"),qb(this,"_localScreenAudioTrack"),qb(this,"log"),qb(this,"denoiser"),qb(this,"voiceChanger"),qb(this,"mixChangedDebounce"),qb(this,"audioProcessor"),qb(this,"encodePipeline",[]),qb(this,"decodePipeline",[]),qb(this,"getPCMAbortCtrlMap",new Map),qb(this,"audioFrameEventConfigMap",new Map),qb(this,"audioReferenceMap",new Map),qb(this,"isLocalAudioNeedAudioProcess",!1),qb(this,"isScreenAudioNeedAudioProcess",!1),this.log=dM.createLogger({parent:null==e?void 0:e.getLogger(),id:"am",userId:null==e?void 0:e.userId,sdkAppId:null==e?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}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=oW(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 oW([rV().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!KN(this._localScreenAudioTrack)}get hasAudioTrack(){return!KN(this._localAudioTrack)}changeInput(e){var t,i;return e instanceof nW?(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 SH?(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 dW?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 nW?delete this._localScreenAudioTrack:e instanceof SH&&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(){oM.on("113",this.handleLocalTrackStarted,this),oM.on("114",this.handleLocalTrackStopped,this),oM.on("115",this.handleRemoteTrackStarted,this),oM.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){oM.off("113",this.handleLocalTrackStarted),oM.off("114",this.handleLocalTrackStopped),oM.off("115",this.handleRemoteTrackStarted),oM.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||KN(n))return;this.setAudioReferenceVolume(r,n)}}};function aW(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return jV((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 dk({code:ck.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});(this.log||this._log||dM).warn(i),2===t?s(i):1===t&&n()},1e3*e);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),i.apply(this,o).then(n,s).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}var cW=class e extends OV{constructor(t,i,r){super({userId:i.userId,sdkAppId:t.sdkAppId,mediaType:r,room:t}),this.room=t,this.user=i,qb(this,"tinyId"),qb(this,"isRemote",!0),qb(this,"jitterBufferDelay",0),qb(this,"availableState"),qb(this,"remotePublishState"),qb(this,"_triggerCheckDecodeSubject",PF(zF(this,e.STATE_SUBSCRIBE))),qb(this,"ignoreUpdatePlayingState"),this.tinyId=i.tinyId,this.availableState=new eU("".concat(i.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new eU("".concat(i.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),uF(vF(zF(this,eU.STATECHANGED),zF(this.remotePublishState,eU.STATECHANGED)),VB(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),mH(e=>{this.availableState.state!==(e?eU.ON:eU.OFF)&&(this.availableState.state=e?eU.ON:eU.OFF),(!this.isRemotePublished||!this.ignoreUpdatePlayingState)&&this.updatePlayingState(e)}));let n=uF(zF(this.player,aU.ERROR),dB(e=>e.code===MediaError.MEDIA_ERR_DECODE)),o=uF(WF(5e3),dB(()=>!!(!this.ignoreDecodeError&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived&&this.isRemotePublished)&&(!this.player.isPlaying&&!(this.kind===$k.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1)))),s=uF(yF(n,o),pB(zF(this,eU.INIT)));uF(this._triggerCheckDecodeSubject,dB(()=>!this.ignoreDecodeError),JB(s),mH(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,i,r;return null!=(r=null==(i=null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.hadRecentBadDownlink)?void 0:i.call(t,2))&&r||this.player.isInAutoPlayFailedState}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===e.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===eU.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var i,r;let n=this.kind===$k.AUDIO;if(UL[e?"addSuccessEvent":"addFailedEvent"]({key:n?504700:514702}),!n){let t=(null==(i=this.room)?void 0:i.downlinkVideoCodec.toUpperCase())||"H264";UL[e?"addSuccessEvent":"addFailedEvent"]({key:ML["DECODE_".concat(t,"_RESULT")]}),e||this.log.warn("".concat(null==(r=this.room)?void 0:r.downlinkVideoCodec," decode failed"))}e||(UL.addEnum({key:n?504701:514703,value:$O()}),hU.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(YO()||tM()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===$k.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),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?eU.ON:eU.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};qb(cW,"STATE_SUBSCRIBE","subscribe"),Kb([aW(5,1)],cW.prototype,"waitHasMediaTrack",1),Kb([Qx(eU.INIT,cW.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),oM.emit(aM.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),$V(521716,!1)],cW.prototype,"subscribe",1),Kb([Qx(cW.STATE_SUBSCRIBE,eU.INIT,{sync:!0,success(){this.log.info("unsubscribed"),oM.emit(aM.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],cW.prototype,"unsubscribe",1);var lW=cW,dW=class extends lW{constructor(e,t){super(e,t,1),qb(this,"volume",0),qb(this,"mediaType",1),qb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}get dbVolume(){return mV.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return!!this.manager&&(this.manager.decodePipeline.some(e=>e)||(null==(t=null==(e=this.player.element)?void 0:e.error)?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Dx().AudioDecoder&&Rx)}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[i,r]of this.manager.decodePipeline.entries()){if(!r)continue;let n={frame:e,track:this};if(1===i&&this.isAvailable&&"audience"===this.room.role&&(n.onAudioFrameNTPTime=e=>{let{ntp:t,frame:i,hasLeavingTag:r}=e;this.emit("audio-frame-with-ntp",{ntp:t,frame:i,hasLeavingTag:r})}),t=r(n),!t)return}return t}getAudioLevel(){if(!this.isAvailable)return 0;let e=this.volume||super.getAudioLevel();return e>1?1:e}getInternalAudioLevel(){return this.isAvailable?super.getInternalAudioLevel():0}get isRemotePublished(){return this.user.muteState.audioAvailable}},uW=class extends OH{constructor(e,t,i,r,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t}),this.setContainer=r,qb(this,"initStat",{alphaStitchingType:1}),qb(this,"end",PF()),qb(this,"minSize",320),qb(this,"maxSize",1280),qb(this,"draggable",!1),qb(this,"startDragX",0),qb(this,"startDragY",0),qb(this,"left",0),qb(this,"top",0),qb(this,"baseWidth",320),qb(this,"baseRatio"),qb(this,"container"),this.initStat=n,this.draggable=i,this.bindDragEvents(),UL.addEnum({key:515700,value:1}),this.draggable&&UL.addEnum({key:515700,value:11})}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=pB(this.end);uF(zF(e,"mousedown"),_H(this.startDrag.bind(this)),jB(()=>uF(zF(window,"mousemove"),pB(zF(window,"mouseup")))),t,mH(this.doDrag.bind(this))),uF(zF(e,"dblclick"),t,mH(this.resetPosition.bind(this))),uF(zF(e,"wheel"),t,mH(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}startDrag(e){e.preventDefault(),0===e.button&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),e&&this.baseRatio&&this.draggable&&(e.style.setProperty("width","".concat(this.baseWidth,"px")),e.style.setProperty("height","".concat(this.baseWidth/this.baseRatio,"px")),e.style.setProperty("position","fixed"),e.style.setProperty("left","".concat(this.left,"px")),e.style.setProperty("top","".concat(this.top,"px")))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=e.deltaY,i=this.context._canvas;i&&(this.baseWidth||(this.baseWidth=i.offsetWidth),this.baseWidth=t<0?Math.min(1.1*this.baseWidth,this.maxSize):Math.max(.9*this.baseWidth,this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,i,r,n){var o;let{ctx2d:s}=this,a=this.context._canvas;if(!s||!a)return!1;let c=super.draw2d(e,t,i,r,n),l=s.getImageData(0,0,r,n),{data:d}=l,u=!1;if(1===this.initStat.alphaStitchingType){let e=Math.floor(r/2);for(let t=0;t<n;t++)for(let i=0;i<e;i++){let n=4*(t*r+i),o=4*(t*r+(i+e)),s=d[o];d[o+3]=0;let a=s>=100;d[n+3]=a?255:0}u=super.draw2d(l,0,0,0,0,e,n),a.width=e}else if(2===this.initStat.alphaStitchingType){let e=Math.floor(n/2);for(let t=0;t<e;t++)for(let i=0;i<r;i++){let n=4*(t*r+i),o=4*((t+e)*r+i),s=d[o];d[o+3]=0;let a=s>=100;d[n+3]=a?255:0}u=super.draw2d(l,0,0,0,0,r,e),a.height=e}return null==(o=this.context.ctx)||o.clearRect(0,0,r,n),c&&u}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};var hW=class extends lW{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),qb(this,"mediaType",4),qb(this,"source"),qb(this,"shouldRenderAlpha",!1),qb(this,"alphaNode"),qb(this,"shouldBeDraggable",!0),qb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0,keyFramesDecoded:0}),qb(this,"_keyFrameCountLogged",!1),qb(this,"_keyFrameStartTimestamp",0),qb(this,"_keyFrameStartCount",0),qb(this,"_keyFrameIntervals",[]),qb(this,"_prevKeyFrameTimestamp",0),this.manager=e.videoManager,this.on("first-video-frame",e=>{this.room.emit("first-video-frame",e)})}isAlphaSei(e){if(this.userId!==e.userId||50!==e.seiPayloadType)return!1;let t=new Uint8Array(e.data);return t.length%3==0&&0===t[0]&&1===t[1]&&t}play(e,t){return null!=t&&t.canvasRender&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),oM.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(this.alphaNode){let e=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===e)return;this.alphaNode.initStat={alphaStitchingType:e};let i=this.player.getElement();if(i){let t=i.videoWidth/i.videoHeight;t&&(this.alphaNode.baseRatio=t*(1===e?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(e))}else this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2])}generateAlphaCanvasName(e){let t=vL[e];return"".concat("alpha","_").concat(t,"_").concat(this.userId)}useCanvasPlayer(e){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let t=new KH({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let i=new xH(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let r=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new uW(t,this.log,this.shouldBeDraggable,r,{alphaStitchingType:e});this.source.connect(n),n.connect(i),this.alphaNode=n}else this.source.connect(i);Ux()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),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;!YN(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),oM.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),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)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}updateKeyFramesDecoded(e){let t=this.stat.keyFramesDecoded||0;if(this.stat.keyFramesDecoded=e,this._keyFrameCountLogged)return;let i=Date.now();if(!this._keyFrameStartTimestamp)return this._keyFrameStartTimestamp=i,this._keyFrameStartCount=e,void(this._prevKeyFrameTimestamp=i);if(this._prevKeyFrameTimestamp&&e>t){let r=e-t,n=(i-this._prevKeyFrameTimestamp)/1e3/r;this._keyFrameIntervals.push(n)}this._prevKeyFrameTimestamp=i;let r=i-this._keyFrameStartTimestamp;if(r>=16e3){let t=e-this._keyFrameStartCount,i=t>0?r/1e3/t:0,n="".concat(t," keyframes in 16s ").concat(i," [").concat(this._keyFrameIntervals.map(e=>e.toFixed(1)).join(","),"] keyFramesDecoded ").concat(e),o=i<=2.5?"debug":"info";this.log[o](n),this._keyFrameCountLogged=!0}}},pW=class extends hW{constructor(e,t){super(e,t,2),qb(this,"mediaType",2),qb(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},mW=new Map;function _W(e,t){let i=Wb(Hb({},t),{timestamp:_k()});mW.has(e)?mW.get(e).push(i):mW.set(e,[i])}function fW(e,t,i,r){try{if(ZN(e))for(let n=0;n<e.length;n++)gW.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else gW.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}catch(TM){throw dM.error(TM),TM}}function gW(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;if(KN(i)){if(t.required)throw new dk({code:ck.INVALID_PARAMETER,message:RL({key:yL.INVALID_PARAMETER_REQUIRED,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(KN(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),JN(t.type[r])&&i instanceof t.type[r]&&(e=!0),qN(t.type[r])&&zN(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new dk({code:ck.INVALID_PARAMETER,message:RL({key:yL.INVALID_PARAMETER_TYPE,data:{key:r,rule:{type:t.type.map(e=>iw(e)?rw(e):qN(e)?e:zN(e))},fnName:n,value:i},link:{className:o,fnName:n}})})}else if(!KN(t.type)&&zN(i)!==t.type)throw new dk({code:ck.INVALID_PARAMETER,message:RL({key:yL.INVALID_PARAMETER_TYPE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!1===t.allowEmpty){let e=YN(i)&&(0===i||Number.isNaN(i)),s=qN(i)&&""===i.trim();if(e||s)throw new dk({code:ck.INVALID_PARAMETER,message:RL({key:yL.INVALID_PARAMETER_EMPTY,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})})}if(t.notLessThanZero&&YN(i)&&i<0)throw new dk({code:ck.INVALID_PARAMETER,message:RL({key:yL.CANNOT_LESS_THAN_ZERO,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!KN(t.min)&&YN(i)&&i<t.min)throw new dk({code:ck.INVALID_PARAMETER,message:RL({key:yL.INVALID_PARAMETER_MIN,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!KN(t.max)&&YN(i)&&i>t.max)throw new dk({code:ck.INVALID_PARAMETER,message:RL({key:yL.INVALID_PARAMETER_MAX,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(qN(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new dk({code:ck.INVALID_PARAMETER,message:RL({key:yL.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})})}else if(JN(t.instanceOf)&&!(i instanceof t.instanceOf))throw new dk({code:ck.INVALID_PARAMETER,message:RL({key:yL.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 dk({code:ck.INVALID_PARAMETER,message:RL({key:yL.INVALID_PARAMETER_RANGE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});let{properties:s}=t;WN(s)&&QN(i)&&Object.keys(s).forEach(e=>{gW.call(this,{rule:s[e],value:i&&i[e],key:"".concat(r,".").concat(e),fnName:n,className:o})});let{arrayItem:a}=t;WN(a)&&ZN(i)&&i.forEach((e,t)=>{gW.call(this,{rule:a,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})}),JN(t.validate)&&t.validate.call(this,i,r,n,o,this)}oM.on(aM.JOIN_SUCCESS,e=>{let{room:t}=e;_W(t.userId,{eventId:32788})}),oM.on(aM.LEAVE_START,e=>{let{room:t}=e;_W(t.userId,{eventId:32789})}),oM.on(aM.LOCAL_TRACK_PUBLISHED,e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),_W(t.room.userId,{eventId:e})}}),oM.on(aM.LOCAL_TRACK_UNPUBLISHED,e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),_W(t.room.userId,{eventId:e})}}),oM.on(aM.TRACK_MUTED,e=>{let{track:t}=e;t.room&&(t.kind===$k.AUDIO?_W(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):_W(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))}),oM.on(aM.TRACK_UNMUTED,e=>{let{track:t}=e;t.room&&(t.kind===$k.AUDIO?_W(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):_W(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))}),oM.on(aM.REMOTE_TRACK_SUBSCRIBED,e=>{let{track:t}=e;t.room&&(1===t.mediaType&&_W(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&_W(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&_W(t.room.userId,{eventId:32803,remoteUserId:t.userId}))}),oM.on(aM.REMOTE_TRACK_UNSUBSCRIBED,e=>{let{track:t}=e;t.room&&(1===t.mediaType&&_W(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&_W(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&_W(t.room.userId,{eventId:32804,remoteUserId:t.userId}))}),oM.on(aM.SWITCH_DEVICE_SUCCESS,e=>{let{track:t}=e;t.room&&_W(t.room.userId,{eventId:t.kind===$k.VIDEO?32780:32781})}),oM.on(aM.LOCAL_TRACK_REPLACED,e=>{let{track:t}=e;t.room&&_W(t.room.userId,{eventId:t.kind===$k.VIDEO?32782:32783})}),oM.on(aM.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&&_W(i.userId,{eventId:t})}),oM.on(aM.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&&_W(i.userId,{eventId:t,remoteUserId:o})}),oM.on(aM.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),_W(i,d),UL.addEnum({key:r?514701:513701,value:c}),UL.addEnum({key:r?514700:513700,value:l})}),oM.on(aM.LOCAL_TRACK_RECAPTURE,e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===$k.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),_W(t.userId,e)}});var EW=Jb(Qb(),1),TW=class extends EW.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,qb(this,"userMap",new Map),qb(this,"remotePublishedUserMap",new Map),qb(this,"asrRobotUserMap",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,fromType:o}=e;if(o===iN)return void this.addAsrRobotUser(e);if(this.userMap.has(t))return;let s={userId:i,tinyId:r,role:20===n?"anchor":"audience"};this.userMap.set(t,s),this.emit("1",s)}addAsrRobotUser(e){let t=e[this.key],{userId:i,tinyId:r,role:n}=e;if(this.asrRobotUserMap.has(t))return;let o={userId:i,tinyId:r,role:20===n?"anchor":"audience"};this.asrRobotUserMap.set(t,o),this.emit("8",o)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;if(this.asrRobotUserMap.has(e))return void this.deleteAsrRobotUser(e);let r="peer leave [".concat(e,"]");KN(t)||(r+=":".concat(QD[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",{userId:i.userId,reason:t})}deleteAsrRobotUser(e){if(!this.asrRobotUserMap.has(e))return;let t=this.asrRobotUserMap.get(e);t&&(this.asrRobotUserMap.delete(e),this.emit("9",t))}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 void this.emit("7",e);let{flag:r,userId:n,tinyId:o,fromType:s}=e,a=hw(r,n),c=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(c){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:c,muteState:a,flag:r}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(a))),this.addUser({userId:n,tinyId:o,role:20,fromType:s}),this.emit("3",e),this.emit("6",{prevMuteState:hw(0,n),muteState:a,flag:r})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}},vW=Jb(Qb(),1),yW=class extends vW.default{constructor(){super(...arguments),qb(this,"_connectionTimeoutCount",0),qb(this,"_isFirewallRestrictionEventEmitted",!1)}increaseTimeoutCount(){this._connectionTimeoutCount+=1,this.checkAndEmitFirewallRestriction()}resetTimeoutCount(){this._connectionTimeoutCount=0}checkAndEmitFirewallRestriction(){this._connectionTimeoutCount>=3&&!this._isFirewallRestrictionEventEmitted&&(this._isFirewallRestrictionEventEmitted=!0,this.emit("firewall-restriction"))}destroy(){this._connectionTimeoutCount=0,this._isFirewallRestrictionEventEmitted=!1,this.removeAllListeners()}};function SW(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return jV((e,n)=>{let o=new WeakMap;return oM.on(aM.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 dk({code:ck.INVALID_OPERATION,message:RL({key:yL.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 IW,AW=!0,RW={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"},CW={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},bW=((IW=bW||{})[IW.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",IW[IW.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",IW[IW.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",IW[IW.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",IW[IW.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",IW[IW.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",IW[IW.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",IW[IW.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",IW[IW.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",IW[IW.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",IW[IW.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",IW[IW.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",IW[IW.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",IW[IW.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",IW[IW.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",IW[IW.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",IW[IW.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",IW[IW.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",IW[IW.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",IW[IW.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",IW[IW.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",IW[IW.INVALID_OPERATION=5100]="INVALID_OPERATION",IW[IW.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",IW[IW.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",IW[IW.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",IW[IW.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",IW[IW.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",IW[IW.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",IW[IW.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",IW[IW.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",IW[IW.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",IW[IW.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",IW[IW.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",IW[IW.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",IW[IW.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",IW[IW.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",IW[IW.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",IW[IW.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",IW[IW.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",IW[IW.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",IW[IW.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",IW[IW.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",IW[IW.DEVICE_ERROR=5300]="DEVICE_ERROR",IW[IW.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",IW[IW.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",IW[IW.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",IW[IW.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",IW[IW.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",IW[IW.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",IW[IW.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",IW[IW.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",IW[IW.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",IW[IW.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",IW[IW.SERVER_ERROR=5400]="SERVER_ERROR",IW[IW.NEED_TO_BUY=5401]="NEED_TO_BUY",IW[IW.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",IW[IW.OPERATION_FAILED=5500]="OPERATION_FAILED",IW[IW.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",IW[IW.REJOIN_FAILED=5502]="REJOIN_FAILED",IW[IW.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",IW[IW.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",IW[IW.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",IW[IW.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",IW[IW.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",IW[IW.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",IW[IW.OPERATION_ABORT=5998]="OPERATION_ABORT",IW[IW.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",IW);var kW=Wb(Hb({},SL),{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(zN(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(zN(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=DW(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=DW(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=DW(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=DW(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=DW(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=DW(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=DW(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 DW(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var NW=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=bW[i];try{t=kW[a]}catch(o){t=kW.UNKNOWN_ERROR}return JN(t)?s=t(r):qN(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===CW.SERVER_ERROR?t:i||t,params:Hb({fnName:o,error:s},n)}),super(l),qb(this,"name","RtcError"),qb(this,"code"),qb(this,"extraCode"),qb(this,"functionName"),qb(this,"message"),qb(this,"data"),qb(this,"handler"),qb(this,"originError"),this.name=bW[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");qP?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):YP&&(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 dk){let{stack:o}=t,s={code:CW.UNKNOWN_ERROR,fnName:i,originError:t};switch(t.getCode()){case ck.INVALID_PARAMETER:s.code=CW.INVALID_PARAMETER,s.message=t.message;break;case ck.INVALID_OPERATION:s.code=CW.INVALID_OPERATION;break;case ck.NOT_SUPPORTED:case ck.NOT_SUPPORTED_H264:s.code=CW.ENV_NOT_SUPPORTED,t.getCode()===ck.NOT_SUPPORTED_H264&&(s.extraCode=t.message.includes(SL.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case ck.JOIN_ROOM_FAILED:s.messageParams={fnParams:r};case ck.SERVER_TIMEOUT:case ck.SWITCH_ROLE_FAILED:case ck.SWITCH_ROOM_FAILED:s.code=CW.SERVER_ERROR,s.extraCode=t.getExtraCode();break;case ck.API_CALL_ABORTED:s.code=CW.OPERATION_ABORT;break;case ck.DEVICE_NOT_FOUND:case ck.DEVICE_AUTO_RECOVER_FAILED:case ck.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 ck.VIDEO_ENCODE_FAILED:s.extraCode=5505;case ck.AUDIO_ENCODE_FAILED:s.extraCode=5506,s.code=CW.OPERATION_FAILED;break;case ck.UNKNOWN:break;default:s.code=CW.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:CW.UNKNOWN_ERROR,fnName:i,originError:t})}return n}};var wW=NW;function PW(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function OW(e){return e===RW.QOS_PREFERENCE_CLEAR?"detail":e===RW.QOS_PREFERENCE_SMOOTH?"motion":""}function MW(e,t){let i=t?Qk:Xk;return Zw(e)?Hb(Hb({},i),e):Yk[e]?Yk[e]:i}var LW={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}}},xW={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}}},UW={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(qN(e)&&!document.getElementById(e))throw new wW({code:CW.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},VW={name:"userId",required:!0,type:"string"},FW={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function BW(e,t){if(!e)throw new wW({code:CW.INVALID_OPERATION,extraCode:5101,fnName:t})}function HW(e,t,i){if(!e)throw new wW({code:CW.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}function WW(e,t,i){if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new wW({code:CW.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:i}})}function GW(e,t,i){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new wW({code:CW.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:i}})}function jW(e){var t;if(null==(t=null==e?void 0:e.option)||!t.small)return;if(!dx())return dM.warn("small stream is not supported"),void delete e.option.small;let i=MW(e.option.profile),r=MW(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:(dM.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 zW={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 wW({code:CW.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(qN(e.roomId))throw new wW({code:CW.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});WW(e.roomId,i,t)}else{if(!e.strRoomId)throw new wW({code:CW.INVALID_PARAMETER,extraCode:5015,fnName:i});GW(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:UW,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:LW},validate(e){var t,i;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&zL())throw new wW({code:CW.ENV_NOT_SUPPORTED,extraCode:5201});null!=(i=null==e?void 0:e.option)&&i.small&&jW(e)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:Wb(Hb({},UW),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:LW},validate(e){var t;null!=(t=null==e?void 0:e.option)&&t.small&&jW(e)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:FW},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&zL())throw new wW({code:CW.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:FW}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:UW,publish:{type:"boolean"},option:xW},validate(e,t,i,r,n){var o;if(null==(o=null==e?void 0:e.option)||!o.videoTrack){if(zL())throw new wW({code:CW.ENV_NOT_SUPPORTED,extraCode:5201});if(!ZL())throw new wW({code:CW.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:UW,publish:{type:"boolean"},option:xW}},muteRemoteAudio:[VW,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[VW,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:UW,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){BW(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(HW(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new wW({code:CW.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:Wb(Hb({},UW),{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){BW(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(HW(!!r,i,e),r){if("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary)throw new wW({code:CW.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}});if(e.option){let t="main"===e.streamType?r.remoteVideoTrack:r.remoteAuxiliaryTrack;if((e.option.pictureInPicture||e.option.fullScreen||e.option.fullScreen)&&(!t.isSubscribed||!t.player.isPlaying))throw new wW({code:CW.INVALID_OPERATION,message:"cannot set pictureInPicture or fullScreen when remote video is not playing"})}}}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(e,t,i){if("*"!==e.userId&&KN(e.streamType))throw new wW({code:CW.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){BW(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(!bx)throw new wW({code:CW.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new wW({code:CW.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new wW({code:CW.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new wW({code:CW.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});BW(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 wW({code:CW.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 wW({code:CW.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new wW({code:CW.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(BW(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new wW({code:CW.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(e,t,i){if(BW(this._room.isJoined,i),this._room.useStringRoomId&&e.strRoomId===this._room.roomId||!this._room.useStringRoomId&&e.roomId===Number(this._room.roomId))throw new wW({code:CW.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 wW({code:CW.INVALID_PARAMETER,extraCode:5019,fnName:i,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId)WW(e.roomId,i,t);else{if(!e.strRoomId)throw new wW({code:CW.INVALID_PARAMETER,extraCode:5015,fnName:i});GW(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}}}},JW={TRTC:zW},KW=class extends Error{};function qW(e,t){let i=fw(e);for(let r=0;r<t.length;r++)_w(i[r],t[r]);return i}function YW(e){this._resolve=Promise.resolve(e)}function XW(e){this._reject=Promise.reject(e)}var QW=class e{constructor(t,i){this.instance=t,this.group=i,qb(this,"started",!1),qb(this,"ops",[]),qb(this,"startSame",()=>!0),qb(this,"mergeUpdate",qW);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 KW("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:YW,reject:XW};try{switch(this.state){case 1:if(0===e)throw new KW("already started");break;case 4:if(2===e)throw new KW("not started");break;default:return this.cacheOp(o)}}catch(vM){return Promise.reject(vM)}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 KW("already start");break;case 3:switch(e.type){case 2:throw new KW("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new KW("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new KW("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 KW("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new KW("start not allowed after update");case 0:throw new KW("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new KW("keep start")),new KW("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}};qb(QW,"instances",new WeakMap);var ZW=QW,$W=new WeakMap,eG=(e,t)=>{if(t instanceof KW){let{stack:i}=t;t=new wW({code:CW.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function tG(e,t){return jV((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let a=ZW.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(eG.bind(null,r))):i.apply(this,o)})}function iG(e,t){let{merge:i,debounce:r}=t||{};return jV((t,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=ZW.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=$W.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(eG.bind(null,n)).then(r,o)},e);$W.has(this)?null==(l=$W.get(this))||l.set(i(...s),{timeoutId:u,resolve:r}):$W.set(this,new Map([[i(...s),{timeoutId:u,resolve:r}]]))})}return c.action(2,t.bind(this),s).catch(eG.bind(null,n))})}function rG(e){return jV((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(ZW.gets(this,s).map(e=>e.action(3,()=>Promise.resolve(),n))).then(()=>t.call(this,...n));let a=ZW.get(this,s);return a?a.action(3,t.bind(this),n).catch(eG.bind(null,i)):t.apply(this,n)})}function nG(){return function(e,t,i){return e.prototype[t]=function(){let e=this._log||console,i='"'.concat(t,'" is a static method. Use TRTC.').concat(t,"() instead. See: ").concat(Mk,"/en/TRTC.html#.").concat(t);e.warn(i)},i}}var oG={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",REALTIME_TRANSCRIBER_MESSAGE:"realtime-transcriber-message",REALTIME_TRANSCRIBER_STATE_CHANGED:"realtime-transcriber-state-changed",PICTURE_IN_PICTURE_STATE_CHANGED:"picture-in-picture-state-changed",FULL_SCREEN_STATE_CHANGED:"full-screen-state-changed"},sG=new Set([oG.AUDIO_VOLUME,oG.AUDIO_FRAME,oG.NETWORK_QUALITY,oG.STATISTICS,oG.SEI_MESSAGE,oG.CUSTOM_MESSAGE,oG.LAYER_DATA]),aG={};zb(aG,{ScheduleRequestType:()=>fG,getAbilityConfig:()=>EG,getScheduleDomain:()=>TG,isNeedToSchedule:()=>uG,scheduleProxy:()=>mG,sendScheduleRequest:()=>pG,setIsNeedToSchedule:()=>hG,setScheduleProxy:()=>_G});var cG=null,lG=0,dG=1728e5,uG=!0;function hG(e){XN(e)&&e!==uG&&(uG=e,dM.info("setIsNeedToSchedule ".concat(e)),e||(lG=Date.now()+dG))}function pG(e){return Xb(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*(){var e;if(!uG&&cG&&lG>Date.now())return{isCached:!0,result:cG};let d={delta:0,count:[1,1],msg:[],detail:[]};try{let u=new FormData;u.append("userId",String(t)),u.append("sdkAppId",String(i)),u.append("isStrGroupId",String(r)),u.append("groupId",String(n)),u.append("sdkVersion",s),u.append("userSig",String(o));let h=(null==(e=yield GO())?void 0:e.model)||XO();h&&u.append("model",h);let p=tM();p&&u.append("osString",p);let m=zO();m&&u.append("gpu",m),c&&u.append("role",String(c)),l&&u.append("latencyLevel",String(l)),a&&u.append("frameWorkType",String(a));let _=aw(),f=yield function(e,t,i){return new Promise((r,n)=>{let o=null;sw([yG(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]=gG(i,"config",$k.MAIN,!0)),n())})(gG(i,"config",$k.MAIN),e,{get timeout(){return 1e3*GN(2+t.count[0])}}),yG(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]=gG(i,"config",$k.BACKUP,!0)),n())})(gG(i,"config",$k.BACKUP),e,{get timeout(){return 1e3*GN(2+t.count[1])}})]).then(e=>{o=e,r(o)}).catch(n)})}(u,d,i);f.config&&(f.config.loggerDomain&&Dk(f.config.loggerDomain),XN(f.config.scheduleCache)&&hG(!f.config.scheduleCache)),d.delta=aw()-_;let g=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=gG(e,"config",$k.MAIN),s=gG(e,"config",$k.BACKUP);for(let e of n)if(e.startTime>=i&&(e.name===o||e.name===s)&&e.transferSize>0){let i=e.name===o?$k.MAIN:$k.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];hU.uploadEvent({log:"stat-schedule-net:".concat(n,"(").concat(s,"(").concat(a,"->").concat(c,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=Wb(Hb({},r),{totalCost:n,local:s,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(o){dM.error("getScheduleDetailCost error",o)}return r}(Number(i),t,_);return cG=f,{isCached:!1,result:f,detailCost:g}}catch(_M){let t=ZN(_M)?_M[0]:_M,i=YN(t.code)?t.code:0,r="schedule failed".concat(t.message?": ".concat(t.message):""),n=new dk({code:ck.SCHEDULE_FAILED,extraCode:i,message:RL({key:yL.JOIN_ROOM_FAILED,data:{error:r,code:i}})});throw dM.error(r,i),n}}()})}"undefined"!=typeof document&&document.head.insertAdjacentHTML("beforeend",Object.values(GD).map(e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">')).join("\r\n")),oM.on("28",()=>hG(!0)),oM.on("63",()=>hG(!0)),oM.on("84",()=>hG(!0)),oM.on("201",e=>{"RECONNECTING"===e.state&&hG(!0)}),oM.on("202",e=>{"RECONNECTING"===e.state&&hG(!0)});var mG={main:"",backup:""};function _G(e){ZN(e)?(mG.main=e[0],mG.backup=e[1]):(mG.main=e,mG.backup=e)}var fG=(e=>(e.CONFIG="config",e.TRTC_AUTO_CONF="trtcAutoConf",e.AUDIO_AI_AUTH="audioAiAuth",e))(fG||{});function gG(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$k.MAIN,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return"https://".concat(mG[i]||TG(e,i,r),"/api/v1/").concat(t)}function EG(e,t,i){let r=gG(e,t),n=gG(e,t,$k.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 sw([s,a])}function TG(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$k.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=CN(e)?r?i===$k.MAIN?GD.MAIN_OVERSEA_BACKUP:GD.BACKUP_OVERSEA:i===$k.MAIN?GD.MAIN_OVERSEA:GD.BACKUP_OVERSEA:i===$k.MAIN?GD.MAIN:GD.BACKUP,t}function vG(e,t,i){return new Promise((r,n)=>{jw({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 yG=(e,t)=>$w({retryFunction:vG,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var SG=class{constructor(){qb(this,"_log"),this._log=dM.createLogger({id:"fd"})}download(e,t){return Xb(this,null,function*(){let{type:i="blob"}=t||{};e=Dw(e);try{let t,r=aw();if(t=JN(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")),UL.addSuccessEvent({key:522700,cost:aw()-r}),t.data}catch(TM){throw this._log.error("failed to download: ".concat(e,", error: ").concat(TM)),UL.addFailedEvent({key:522700,error:TM}),TM}})}downloadWithFetch(e,t){return Xb(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(kD){throw kD}})}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 Xb(this,null,function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=aw(),r=null,n=null;if(JN(WebAssembly.instantiateStreaming)&&!e.startsWith("data:application/octet-stream;base64,")&&!(e=>e.startsWith("file://"))(e)&&JN(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(Ak){n=Ak}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(Ak){n=Ak}if(r){let t=aw()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),UL.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),UL.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")),UL.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))),UL.addFailedEvent({key:522702}),r(t)},n.crossOrigin="anonymous",n.src=e,document.head.append?document.head.append(n):document.getElementsByTagName("head")[0].appendChild(n)})}};Kb([mU({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))}})],SG.prototype,"download",1),Kb([mU({settings:{timeout:3e3,retries:3},onRetrying(e){this._log.warn("loadScript retrying: ".concat(e))}})],SG.prototype,"loadScript",1);var IG=new SG;function AG(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 RH(new DataView(new Uint8Array(s).buffer),!0)}function RG(e){return"empty"===e.type||0===e.data.byteLength}function CG(e){let t=new DataView(e),i=0;for(;i<t.byteLength;){let e=IH(t,i);if(0===e){i+=1;continue}let r=i+e;if(r<t.byteLength&&6==(31&t.getUint8(r)))return!0;i+=e+1}return!1}function bG(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 kG(e){let{frame:t,seiMessageList:i}=e;if(!i||0===i.length||0===t.data.byteLength)return t;let r=9-bG(t.data);if(r<=0)return t;let n=i.splice(0,r).reverse().map(AG),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 DG(e){let{frame:t,onSEI:i}=e;try{if(RG(t)||!CG(t.data))return t;let e=AH(t.data,!1).filter(e=>e.isSEI);null==i||i(e.reverse())}catch(Ik){}return t}function NG(e){let{seiMessageList:t,isAudio:i,getNtpTime:r,isMain:n}=e;return new TransformStream({transform(e,o){let s=e;i?audioEncodePipeline.forEach(e=>{s=e({frame:s,ntp:r(),onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:s.data,userId:""})}})}):videoEncodePipeline.forEach(e=>{s=e({frame:s,seiMessageList:t,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:s.data,userId:"",streamType:n?"main":"auxiliary"})}})}),o.enqueue(s)}})}function wG(e){let{userId:t,streamType:i,isAudio:r}=e;return new TransformStream({transform(e,n){let o=e;r?(audioDecodePipeline.forEach(e=>{o=e({frame:o,onAudioFrameNTPTime:e=>{self.postMessage({type:"audio-ntp",data:e,userId:t,streamType:i})},onDump:()=>{self.postMessage({type:"dump",isAudio:r,data:o.data,userId:t})}})}),n.enqueue(o)):videoDecodePipeline.forEach(e=>{o=e({frame:o,onSEI:e=>{e.forEach(e=>{self.postMessage({type:"sei",seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:t,streamType:i})})},onDump:()=>{self.postMessage({type:"dump",isAudio:r,data:o.data,userId:t,streamType:i})}})}),n.enqueue(o)}})}function PG(e){let t=[RH],i=[bG,RG,AH,CG,AG,NG,wG,Vw,Uw,IH],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=[],r=0;self.onmessage=n=>{switch(n.data.type){case"sei":n.data.isMain?(e.push(n.data.data),n.data.small&&i.push(n.data.data)):t.push(n.data.data);break;case"ntp-offset":r=n.data.data}},self.onrtctransform=n=>{let{options:o}=n.transformer,s=o.isReceiver?wG({userId:o.userId,streamType:o.streamType,isAudio:o.isAudio}):NG({getNtpTime:()=>Date.now()+r,isAudio:o.isAudio,isMain:o.isMain,seiMessageList:o.isMain?o.small?i:e:t});n.transformer.readable.pipeThrough(s).pipeTo(n.transformer.writable)}},")();").concat(r,"})()"),o=new Blob([n],{type:"text/javascript"}),s=URL.createObjectURL(o),a=new Worker(s);return URL.revokeObjectURL(s),a}var OG,MG=class{constructor(e){qb(this,"audioPlayer"),qb(this,"videoPlayer"),qb(this,"log"),this.audioPlayer=e.audioPlayer,this.videoPlayer=e.videoPlayer,this.log=e.log.createChild({id:"pip"}),this.videoPlayer.on(aU.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.on(aU.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.on(aU.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(aU.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(aU.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.on(aU.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.on(aU.VOLUME_CHANGE,this.handleVolumeChange,this)}handleUserResumeInPIPOrFullScreen(){this.audioPlayer.isPaused&&(this.log.warn("resume audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doResume()),mP&&yO&&this.videoPlayer.resetSrcObjectToReplay()}handleUserPauseInPIPOrFullScreen(){this.audioPlayer.isPaused||(this.log.warn("pause audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doPause())}handleEnterPIPOrFullScreen(){this.videoPlayer.element&&this.audioPlayer.muted!==this.videoPlayer.element.muted&&(this.log.warn("sync video muted to ".concat(this.audioPlayer.muted," when enter ").concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.videoPlayer.element.muted=this.audioPlayer.muted)}handleLeavePIP(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume after leave pip"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave pip"),this.videoPlayer.doResume())}handleLeaveFullScreen(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume audio after leave fullscreen"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave fullscreen"),mP&&yO?this.videoPlayer.resetSrcObjectToReplay():this.videoPlayer.doResume())}handleVolumeChange(e){void 0!==e.muted&&this.audioPlayer.muted!==e.muted&&(this.log.warn("sync audio muted to ".concat(e.muted," in ").concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.setMuted(e.muted))}destroy(){this.videoPlayer.off(aU.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.off(aU.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.off(aU.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(aU.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(aU.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.off(aU.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.off(aU.VOLUME_CHANGE,this.handleVolumeChange,this)}},LG=!1;function xG(e){var t=this;let{TRTC:i,room:r,errorModule:n,assetsPath:o}=e;return{TRTC:i,LocalMixVideoTrack:$H,LocalVideoTrack:kH,LocalScreenTrack:iW,room:r,assetsPath:o,fileDownloader:IG,innerEmitter:oM,INNER_EVENT:aM,constants:Tk,environment:tP,utils:DH,eventLogger:hU,log:this.room.getLogger(),loggerManager:dM,errorModule:n,kvStatManager:UL,rtcDectection:pM,trtc:this,rx:eF,enums:mM,schedule:aG,getDevices:yV,initVisionTaskRegistry:function(e,i){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"/mediapipe/vision.js";return Xb(t,null,function*(){!window.VisionTaskRegistry&&!LG&&(LG=!0,OG=IG.loadScript("".concat(e,"/").concat(r).replace(/([^:]\/)\/+/g,"$1"))),yield OG,yield(yield window.VisionTaskRegistry.getInstance(e)).preloadModels(i)})},audioContext:rV(),deviceDetector:TV,AudioPlayer:NV,RemoteAudioPlayer:PV,VideoPlayer:WU,showAutoPlayDialog:BU,Timer:sU,clearStarted:(e,t)=>{let i=e.getAlias(),r=ZW.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:oW,createAudioNode:dV,getNetworkTimeOffset:mk,validateSourceNode:()=>{var e;if(EP&&(null==(e=this.room.audioManager._localAudioPipline)||!e.source.node))throw new wW({code:CW.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})},createScriptTransformWorker:PG,AVPlayerStateSyncManager:MG,PlayerEvent:aU}}var UG=new WeakMap;var VG="5.15.1-beta.7";function FG(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return jV((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{HG.call(this,t,n,i,this._name)}catch(TM){return Promise.reject(TM)}return e.apply(this,n)})}function BG(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return jV((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{HG.call(this,t,n,i,this._name)}catch(TM){throw TM}return e.apply(this,n)})}function HG(e,t,i,r){if(ZN(e))for(let n=0;n<e.length;n++)WG.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else WG.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function WG(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function s(e){return{code:CW.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(KN(i)){if(t.required)throw new wW(s(5001));if(KN(t.defaultValue))return void(JN(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),JN(t.type[r])&&i instanceof t.type[r]&&(e=!0),qN(t.type[r])&&zN(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new wW({code:CW.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map(e=>iw(e)?rw(e):qN(e)?e:zN(e))},value:i}})}else if(!KN(t.type)&&zN(i)!==t.type)throw new wW(s(5002));if(!1===t.allowEmpty){let e=YN(i)&&(0===i||Number.isNaN(i)),t=qN(i)&&""===i.trim();if(e||t)throw new wW(s(5003))}if(t.notLessThanZero&&YN(i)&&i<0)throw new wW(s(5006));if(!KN(t.min)&&YN(i)&&i<t.min)throw new wW(s(5007));if(!KN(t.max)&&YN(i)&&i>t.max)throw new wW(s(5008));if(qN(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new wW(s(5004))}else if(JN(t.instanceOf)&&!(i instanceof t.instanceOf))throw new wW(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new wW(s(5005));let{properties:a}=t;WN(a)&&QN(i)&&Object.keys(a).forEach(e=>{WG.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})});let{arrayItem:c}=t;WN(c)&&ZN(i)&&i.forEach((e,t)=>{WG.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})}),JN(t.validate)&&t.validate.call(this,i,r,n,o,this)}var GG=0;function jG(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r,ignoreLog:n,ignoreErrorLog:o}=e;return jV((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(zN(t)):t instanceof MediaStreamTrack?Nw(t):(JSON.stringify(t),t)}catch(n){return"type:".concat(zN(t))}}let m=(null==this?void 0:this._log)||dM,_=++GG;if(null!=n&&n(...c))return e.apply(this,c);c.length>0?m.info("".concat(s,"() ").concat(_," ").concat(JSON.stringify(c,(e,t)=>p(e,t,["userSig","privateMapKey"])))):m.info("".concat(s,"() ").concat(_));let f=r?r(...c):NL[s],g=(null==o?void 0:o(...c))||!1;try{let i=e.apply(this,c),r=aw();if(tw(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(_," ").concat(e).concat(t.call(this,...c))),UL.addSuccessEvent({key:f,cost:aw()-r}),i)).catch(i=>{var r;let n=(i=wW.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),a=(null==i?void 0:i.code)===CW.OPERATION_ABORT;throw g||m[a?"warn":"error"]("".concat(s,"() failed ").concat(_," ").concat(e).concat(t.call(this,...c)," ").concat(i).concat(o," params: ").concat(JSON.stringify(c,p))),UL.addFailedEvent({key:f,error:i}),i})}return UL.addSuccessEvent({key:f}),i}catch(E){let e=(E=wW.convertFrom.call(this,E,s)).extraCode||E.code,t=null!=(h=E.message)&&h.includes(e)?"":" code:".concat(e),i=(null==E?void 0:E.code)===CW.OPERATION_ABORT;throw g||m[i?"warn":"error"]("".concat(s,"() failed ").concat(_," ").concat(E).concat(t," params: ").concat(JSON.stringify(c,p))),UL.addFailedEvent({key:f,error:E}),E}})}var zG,JG=e=>jV((t,i)=>function(r,n){return Xb(this,null,function*(){let o=this._plugins.get(r);if(!o)throw this._log.error("plugin ".concat(String(r)," is not found")),new wW({code:CW.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(JN(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new wW({code:CW.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return HG.call(this,o.getValidateRule(e),[n],i,"TRTC"),t.call(this,o,n)})}),KG=0,qG=class e{constructor(e){this.core=e,qb(this,"log"),qb(this,"customAudioReferenceMap",new Map),qb(this,"audioRefId",0),qb(this,"audioContext",rV()),qb(this,"localAudioWorkletNode"),qb(this,"screenAudioWorkletNode"),qb(this,"mixNode"),qb(this,"silentNode"),KG+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(KG)}),this.log.info("created id=".concat(this.getAlias()).concat(KG)),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 wW({code:CW.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return zG||(zG=this.doPreload(e)),zG}doPreload(e){return Xb(this,null,function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield GU(this.audioContext,i)}catch(TM){this.log.error("preload audioProcessor failed. ".concat(TM))}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 Xb(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 wW({code:CW.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),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),KN(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++)})}),KN(u)||null==(r=this.localAudioWorkletNode)||r.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:u}}),KN(h)||null==(n=this.localAudioWorkletNode)||n.port.postMessage({type:"dump",data:{enable:h}})})}update(e){return Xb(this,null,function*(){var t,i,r;let{audioReference:n,enableDump:o,processLevel:s}=e;KN(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++)})})),KN(s)||null==(t=this.localAudioWorkletNode)||t.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:s}}),KN(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 Xb(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 Xb(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:n,sign:o,status:s,message:a}=yield function(e){return Xb(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]:$k.MAIN;return"https://".concat(mG[t]||TG(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=CN(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 wW({code:CW.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(gk(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 oM.emit("265",{room:a,data:r.value,type:"localAudio"===t?"dump":"dump-screen-audio"});case"detectEcho":return void this.log.warn("".concat("localAudio"===t?"":"[".concat(t,"] "),"detect echo: ").concat(HO()?YO():tM()))}}}handleLocalAudioStarted(e){return Xb(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(kD){this.log.warn("audio processor auto start failed, error: ".concat(kD))}})}handleLocalAudioStopped(e){return Xb(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}};qb(qG,"updateValidateRule",{type:"object"}),qb(qG,"stopValidateRule",{type:"object"}),qb(qG,"Name","AudioProcessor");var YG=qG;var XG=0,QG=class{constructor(e,t){qb(this,"audioObjectURL"),qb(this,"player"),qb(this,"publisher"),qb(this,"mixInput"),this.mixInput=new aV(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&&(KN(e.volume)||(this.volume=e.volume),KN(e.loop)||(this.loop=e.loop),KN(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)}}reload(e){return Xb(this,null,function*(){if(e.url){let t=yield IG.download(e.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(t),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(e),this.updateSettings(e))}else this.mixInput.replaceSource(e.track)})}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 Promise.all([null==(e=this.player)?void 0:e.play(),null==(t=this.publisher)?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 ZG(e,t){if(t&&"function"!=typeof t)throw new wW({code:CW.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var $G=class e{constructor(e){this.core=e,qb(this,"log"),qb(this,"mixedMusicMap",new Map),qb(this,"cacheMusicMap",new Map),XG+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(XG)}),this.log.info("created id=".concat(this.getAlias()).concat(XG))}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 Xb(this,null,function*(){let{room:t}=this.core;this.core.validateSourceNode(),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 QG(e,t.audioManager),this.cacheMusicMap.set(i,n)),n.updateListener(e),n.updateSettings(e);try{yield n.play()}catch(Ak){yield this.handleAutoPlayFailed(n,e,Ak)}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.")),UL.addEnum({key:502700,value:3}),this.kvUpload(e)})}handleAutoPlayFailed(e,t,i){return Xb(this,null,function*(){if("NotSupportedError"===i.name)this.log.error("play failed, try to reload source. error: ".concat(i)),yield e.reload(t),yield e.play();else{if("NotAllowedError"!==i.name)throw i;if(this.core.room.enableAutoPlayDialog){let t=()=>{var i;null==(i=e.play())||i.finally(()=>{oM.off("154",t,this)})};oM.on("154",t,this),BU()}else this.core.trtc.emit(oG.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>Xb(this,null,function*(){return e.play()})})}})}update(e){return Xb(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),KN(i)||o.setOperation(i),KN(r)||o.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))})}stop(e){return Xb(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&&UL.addCount({key:502009}),i&&UL.addCount({key:502001}),r&&UL.addCount({key:502002}),n&&UL.addCount({key:502003}),o&&UL.addCount({key:502004}),s&&UL.addCount({key:502005}),"function"!=typeof a&&UL.addCount({key:502007}),"function"!=typeof l&&UL.addCount({key:502008}),"function"!=typeof c&&UL.addCount({key:502006})}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()}};qb($G,"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 wW({code:CW.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new wW({code:CW.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});ZG("onTimeUpdate",e.onTimeUpdate),ZG("onEnded",e.onEnded),ZG("onDurationChange",e.onDurationChange)}}),qb($G,"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){ZG("onTimeUpdate",e.onTimeUpdate),ZG("onEnded",e.onEnded),ZG("onDurationChange",e.onDurationChange)}}),qb($G,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),qb($G,"Name","AudioMixer");var ej,tj=$G,ij=0,rj=class e{constructor(e){this.core=e,qb(this,"log"),qb(this,"audioContext",rV()),qb(this,"workletNode"),qb(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),ij+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(ij)}),this.log.info("created id=".concat(this.getAlias()).concat(ij))}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},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(t,i,r,n){if(!e.room.audioManager.hasAudioTrack)throw new wW({code:CW.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return ej||(ej=this.doPreload(e)),ej}doPreload(e){return Xb(this,null,function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield GU(this.audioContext,i)}catch(TM){throw this.log.error("load worklet failed",TM),TM}finally{URL.revokeObjectURL(i)}})}getName(){return e.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return e.startValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return Xb(this,null,function*(){let{room:t,schedule:i}=this.core,{assetsPath:r=this.core.assetsPath}=e;if(!r)throw new wW({code:CW.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(r,"/denoiser-wasm").concat(Px()?"":"-nosimd",".js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:n,status:o,message:s}=yield function(e,t){return Xb(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=CN(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,Wb(Hb({},e),{timestamp:t}));if(!r)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(r,". Message: ").concat(s)),new wW({code:CW.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(gk(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.updateConfig(e),this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})})}update(e){return Xb(this,null,function*(){this.updateConfig(e)})}stop(){return Xb(this,null,function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)})}updateConfig(e){if(!this.workletNode)return;let t=!1;KN(e.mode)||(0===e.mode?this.config.enableFarFieldReduce=!1:1===e.mode&&(this.config.enableFarFieldReduce=!0),t=!0),KN(e.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=e.farFieldReduceThreshold,t=!0),t&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};qb(rj,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),qb(rj,"stopValidateRule",{type:"object"}),qb(rj,"Name","AIDenoiser");var nj=rj;var oj=Jb(Qb(),1),sj=class extends oj.EventEmitter{constructor(){super(),qb(this,"observer"),qb(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 Xb(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!mP&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(Ik){hU.uploadEvent({log:"stat-pressure-detector-start-failed",error:Ik})}})}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&dM.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(kD){hU.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:kD})}}},aj=new sj,cj=0,lj=class e{constructor(e){this.core=e,qb(this,"log"),qb(this,"_seiMessageList",[]),qb(this,"_smallSeiMessageList",[]),qb(this,"_subStreamSeiMessageList",[]),cj++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(cj)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(cj)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:t,mediaType:i}=e;try{return kG({frame:t,seiMessageList:8===i?this._smallSeiMessageList:2===i?this._subStreamSeiMessageList:this._seiMessageList})}catch(kD){this.log.warn(kD)}return t}decode(e){let{frame:t,track:i}=e;return DG({frame:t,onSEI:e=>{e.forEach(e=>{null!=i&&i.userId?this.core.trtc.emit(oG.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:i.userId,streamType:2===i.mediaType?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:e})})}})}destroy(){this.log.debug("destroy"),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:Rx?this.encode:kG,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Rx?this.decode:DG,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"}};qb(lj,"autoStart",!0),qb(lj,"Name","SEI");var dj,uj=lj,hj=0,pj=class e{constructor(e){this.core=e,qb(this,"_core"),qb(this,"log"),qb(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++hj)}),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 Xb(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())})}update(e){return Xb(this,arguments,function(e){var t=this;let{visible:i}=e;return function*(){i?yield t.openDebugDiaLog():t.closeDebugDiaLog()}()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return Xb(this,null,function*(){var e;if(!this.dialog)try{if(dj)yield dj;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(yk,"/assets/debug-dialog.js");dj=this._core.fileDownloader.loadScript(t),yield dj}this.dialog=new TRTCDebugDialog(this._core,this.log),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(Ik){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(Ik))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};qb(pj,"Name","Debug"),qb(pj,"autoStart",!0);var mj=pj,_j=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},fj=class{constructor(e,t,i){qb(this,"trackDoneOB"),qb(this,"startOB"),qb(this,"stopOB"),qb(this,"inputFrameCount",0),qb(this,"decodedFrameCount",0),qb(this,"type","auto"),qb(this,"config"),qb(this,"decoder"),qb(this,"_decodeSink");let{kvStatManager:r,trtc:n}=e;this.config=i.config,this.trackDoneOB=zF(t,eU.INIT),this.stopOB=PF(),this.startOB=PF(),"auto"===i.type?this.type="webCodecs":this.type=i.type;let o=PF();uF(this.startOB,bF(0),jB(e=>{let i=this.pipe(t);return o.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),uF(i,pB(this.stopOB),mH(()=>{},i=>{t.log.error(i),r.addFailedEvent({key:_j(this.type),error:i}),e>4?this.startOB.error(i):this.startOB.next(e+1)})),uF(i,hB(1),lH(rB))}),pB(this.stopOB),mH(()=>{t.player.setOutput(),o.next("STARTED")},e=>{o.next("FAILED")},()=>{r.addSuccessEvent({key:_j(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 TF()(t=>Xb(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(TM){e.log.error(TM),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"}))}},gj={type:"object"},Ej=class e{constructor(e){this.core=e,qb(this,"log"),qb(this,"contextMap",new Map),qb(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 gj}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 fj(this.core,r,e);return uF(n.trackDoneOB,hB(1),mH(()=>{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 fj(this.core,e.track,e))}}};qb(Ej,"Name","TRTCAudioDecoder");var Tj=Ej,vj=class{constructor(){qb(this,"log"),this.log=dM.createLogger({id:"exp"})}call(e,t){return Xb(this,null,function*(){return JN(this[e])?this[e](t):Promise.reject(new dk({code:ck.INVALID_PARAMETER,message:RL({key:yL.API_NOT_EXIST,data:{name:e}})}))})}enableAudioFrameEvent(e){return Xb(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(oG.AUDIO_FRAME,e)},e.userId);c.set(e.userId,i)}});else{if(c.get(r))return;let e=a.getPCM(e=>{t.emit(oG.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)}})}resumeRemotePlayer(e){return Xb(this,null,function*(){if("*"===e.userId){let t=[];return e.trtcInstance.room.remotePublishedUserMap.forEach(i=>{let{remoteAudioTrack:r,remoteVideoTrack:n,remoteAuxiliaryTrack:o}=i;e.streamType?"main"===e.streamType?(r.isAvailable&&t.push(r.player.resume()),n.isAvailable&&t.push(n.player.resume())):o.isAvailable&&t.push(o.player.resume()):(r.isAvailable&&t.push(r.player.resume()),n.isAvailable&&t.push(n.player.resume()),o.isAvailable&&t.push(o.player.resume()))}),Promise.all(t)}let t=e.trtcInstance.room.remotePublishedUserMap.get(e.userId);if(t)return"main"===e.streamType?Promise.all([t.remoteAudioTrack.player.resume(),t.remoteVideoTrack.player.resume()]):t.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(e){if("*"===e.userId)e.trtcInstance.room.remotePublishedUserMap.forEach(t=>{let{remoteAudioTrack:i,remoteVideoTrack:r,remoteAuxiliaryTrack:n}=t;e.streamType?"main"===e.streamType?(i.isAvailable&&i.player.pause(),r.isAvailable&&r.player.pause(!1)):n.isAvailable&&n.player.pause(!1):(i.isAvailable&&i.player.pause(),r.isAvailable&&r.player.pause(!1),n.isAvailable&&n.player.pause(!1))});else{let t=e.trtcInstance.room.remotePublishedUserMap.get(e.userId);t&&("main"===e.streamType?(t.remoteAudioTrack.player.pause(),t.remoteVideoTrack.player.pause(!1)):t.remoteAuxiliaryTrack.player.pause(!1))}}};Kb([function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return jV((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return fW.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"}}})],vj.prototype,"enableAudioFrameEvent",1);var yj=new vj,Sj=Jb(Qb(),1),Ij=class extends Sj.EventEmitter{constructor(){super(),qb(this,"states",{}),qb(this,"permissionChangeHandler"),qb(this,"log"),this.log=dM.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 Xb(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 Xb(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(kD){return this.log.error("get ".concat(e," permission failed, error: ").concat(kD instanceof Error?kD.message:kD)),null}})}destroy(){Object.values(this.states).forEach(e=>{null==e||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Aj=new Ij,Rj=0,Cj=new Set,bj=null;Sk(VG),hM.checkStorage();var kj=class e extends sk.EventEmitter{constructor(t,i){super(),qb(this,"_room"),qb(this,"_eventListened",new Set),qb(this,"_localVideoTrack",null),qb(this,"_localAudioTrack",null),qb(this,"_localScreenTrack",null),qb(this,"_localScreenAudioTrack",null),qb(this,"_localVideoConfig",null),qb(this,"_localScreenConfig",null),qb(this,"_localAudioConfig",null),qb(this,"_remoteVideoConfigMap",new Map),qb(this,"_remoteAudioConfigMap",new Map),qb(this,"_remoteAudioVolumeMap",new Map),qb(this,"_remoteAudioMuteMap",new Map),qb(this,"_mediaTrackMap",new WeakMap),qb(this,"_log",dM.createLogger({id:"t".concat(++Rj)})),qb(this,"_plugins",new Map),qb(this,"_networkQuality",null),qb(this,"_speakerId"),qb(this,"enterRoomParams"),qb(this,"_enableAutoSwitchWhenRecapturing",!0),qb(this,"_autoSubscribeDataChannel",!1),this._room=new t(Hb({logger:this._log,frameWorkType:e.frameWorkType},i)),this._room.videoDecodeFallbackType=i.videoDecodeFallback,XN(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(tj,i.assetsPath),this._use(YG,i.assetsPath),this._use(nj,i.assetsPath),this._use(Tj,i.assetsPath),this._use(mj),i.enableSEI&&bx&&this._use(uj),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)}),i.enableDbVolume&&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(oG.AUDIO_VOLUME,{result:e.sort((e,t)=>t.volume-e.volume)})}),this._room.videoManager.on("error",e=>{this._log.error(new wW({code:CW.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(TM){let i=RL({key:yL.CATCH_HANDLER_ERROR,data:{name:t,event:n[0]},addDocLink:!1});return dM.warn("".concat(i,"\n\n").concat(TM.stack)),!1}}})(this,"trtc")}static create(e){}static _create(t,i){!function(){var e;if(AW){AW=!1,5!==dM.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Mk,"/en/index.html")),console.info("* Changelog: ".concat(Mk,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),dM.info("TRTC Web SDK Version:",yk),xO||dM.debug("Build Time:","2026-01-22 10:08:09");let t="UA: ".concat(navigator.userAgent," \nCPU core: ").concat(navigator.hardwareConcurrency,", GPU: ").concat(zO());if(hP&&window.screen&&(window.screen.width||window.screen.height)){let e="".concat(window.screen.width,"x").concat(window.screen.height,"@").concat(window.devicePixelRatio);t+=", screen: ".concat(e)}let i=navigator.deviceMemory;i&&(t+=", minRAM: ".concat(i,"GB")),dM.info(t),dM.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),GO().then(e=>{e&&dM.info(WO)})}}();let r=new e(t,i||{});return Cj.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){dU(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(oG.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{let{userId:t,reason:i}=e;this.emit(oG.REMOTE_USER_EXIT,{userId:t,reason:i})}).add("banned",e=>{hG(!0),this._exitRoom().finally(()=>{this.emit(oG.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(oG.ERROR,wW.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(oG.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=Wb(Hb({},e),{uplinkRTT:Math.min(e.uplinkRTT,tN),downlinkRTT:Math.min(e.downlinkRTT,tN)});this.emit(oG.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(t=>{dU(t,t).add("player-state-changed",i=>{let r=Wb(Hb({},i),{userId:e.userId});t.kind===$k.VIDEO&&(r.streamType=PW(t.streamType)),this.emit(t.kind===$k.AUDIO?oG.AUDIO_PLAY_STATE_CHANGED:oG.VIDEO_PLAY_STATE_CHANGED,r)}).add("error",e=>{e.getCode()===ck.PLAY_NOT_ALLOWED&&this.emit(oG.AUTOPLAY_FAILED,{userId:t.userId,mediaType:t.strMediaType,resume:()=>t.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(e=>{uU(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?oG.REMOTE_VIDEO_AVAILABLE:oG.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),n!==s&&(s?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i}),this.emit(s?oG.REMOTE_AUDIO_AVAILABLE:oG.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?oG.REMOTE_VIDEO_AVAILABLE:oG.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"})),t.hasDatachannel!==i.hasDatachannel&&i.hasDatachannel&&this._onDataChannelAvailable()}).add("sei-message",e=>{this.emit(oG.SEI_MESSAGE,Wb(Hb({},e),{streamType:PW(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(oG.ERROR,new wW({code:CW.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,tN),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)/sL},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)/sL,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(oG.STATISTICS,l)}).add("custom-message",e=>{this.emit(oG.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(oG.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(oG.FIRST_VIDEO_FRAME,Wb(Hb({},e),{streamType:PW(e.streamType)}))}).add("audio-frame",e=>{this.emit(oG.AUDIO_FRAME,e)}).add("data-channel-message",e=>{var t,i,r,n,o;let{data:s}=e;if(""===s.sender)return;let a={segmentId:null==(t=s.payload)?void 0:t.roundid,speakerUserId:s.sender,sourceText:null==(i=s.payload)?void 0:i.text,translationTexts:null==(r=s.payload)?void 0:r.translate_msg,timestamp:null==(n=s.payload)?void 0:n.start_utc_ms,isCompleted:null==(o=s.payload)?void 0:o.end,robotId:s.robotid};""!==a.sourceText&&this.emit(oG.REALTIME_TRANSCRIBER_MESSAGE,a)}).add("asr-robot-peer-join",e=>{this.emit(oG.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"started",roomId:this.room.roomId,transcriberRobotId:e.userId})}).add("asr-robot-peer-leave",e=>{this.emit(oG.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"stopped",roomId:this.room.roomId,transcriberRobotId:e.userId})}),dU(this,TV).add("audioInputAdded",e=>{this.emit(oG.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(oG.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(oG.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(oG.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>Xb(this,null,function*(){if(this.emit(oG.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),bj&&bj.deviceId===qD){let e=(yield RV()).find(e=>e.deviceId===qD);e&&bj.groupId!==e.groupId&&(bj=e,this.emit(oG.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})).add("audioOutputRemoved",e=>Xb(this,null,function*(){this.emit(oG.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield RV())[0];if(!t||!bj||bj.groupId===t.groupId)return;let i=bj.deviceId===e.deviceId,r=bj.deviceId===qD&&bj.deviceId===t.deviceId;(i||r)&&(bj=t,this.emit(oG.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})),dU(this,Aj).add("permission-state-change",e=>{this.emit(oG.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(oG.SEI_MESSAGE,e=>{var t;let i=null==(t=this.room.remotePublishedUserMap.get(e.userId))?void 0:t.remoteVideoTrack;i&&i.updateAlphaRenderInfo(e)})}getNetworkTime(){return _k()}use(e){let t,i;return"plugin"in e?(t=e.plugin,i=e.assetsPath):t=e,"Chorus"===t.Name&&(this.room.enableChorus=!0),this._use(t,i)}_use(t,i){let r=this._plugins.get(t.Name);if(r)return this._log.warn("duplicate install plugin",t.Name),r;let n=new t(xG.call(this,{TRTC:e,room:this._room,assetsPath:i,errorModule:{RtcError:wW,ErrorCode:CW,CoreErrorCode:ck,ErrorCodeDictionary:bW}}));return this._plugins.set(t.Name,n),n.__v_skip=!0,t.autoStart&&this.startPlugin(t.Name),n}enterRoom(t){return Xb(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),!qN(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,XN(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,enableDataChannel:this._plugins.has("RealtimeTranscriber"),frameWorkType:t.frameWorkType,component:t.component,language:t.language,priority:t.priority,useVp8:t.useVp8,useH265:t.useH265||!1,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(),aj.start()})}exitRoom(){return Xb(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return Xb(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(kD){if(!(kD instanceof lk)||kD.code!==ck.API_CALL_TIMEOUT&&kD.code!==ck.SWITCH_ROOM_FAILED)throw kD;this._log.warn("switchRoom ".concat(kD.code===ck.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(e)}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return Xb(this,null,function*(){yield this.exitRoom();let t=Hb(Hb({},this.enterRoomParams),e);yield this.enterRoom(t)})}_clearRemoteTracks(){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=UG.get(e);t&&(t.forEach(e=>clearTimeout(e)),UG.delete(e))}(this),this._room.remotePublishedUserMap.forEach(e=>{uU(e.remoteAudioTrack),uU(e.remoteVideoTrack),uU(e.remoteAuxiliaryTrack)})}switchRole(e,t){return Xb(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(){this._plugins.forEach(e=>{var t;return null==(t=e.destroy)?void 0:t.call(e)}),this._plugins.clear(),uU(this),this.removeAllListeners(),this._room.destroy(),Cj.delete(this),0===Cj.size&&aj.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),oM.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return Xb(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,muteKeepVolumeDetection:n,option:o}=t,s=new SH(e._room.audioManager),a={},c={muted:!0};o&&(KN(o.microphoneId)?KN(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&YN(o.captureVolume)&&s.setCaptureVolume(o.captureVolume),KN(o.profile)||(qN(o.profile)?qk[o.profile]&&s.setProfile(qk[o.profile]):s.setProfile(o.profile)),YN(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),KN(o.echoCancellation)||(s.profile.echoCancellation=o.echoCancellation),KN(o.noiseSuppression)||(s.profile.noiseSuppression=o.noiseSuppression),KN(o.autoGainControl)||(s.profile.autoGainControl=o.autoGainControl),XN(e._enableAutoSwitchWhenRecapturing)&&(s.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),s.on("5",t=>{e.emit(oG.ERROR,new wW({code:CW.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))}),s.on("2",t=>{e.emit(oG.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})}),s.on("4",t=>{let i;t.error&&(i=wW.convertFrom(t.error)),e.emit(oG.PUBLISH_STATE_CHANGED,Wb(Hb({},t),{error:i}))}),s.on("6",()=>{}),e._listenOutputTrackChanged(s),e._speakerId&&s.setAudioOutput(e._speakerId),yield s.capture(a),KN(r)||s.setMute(r,n),dU(s,s).add("player-state-changed",t=>{e.emit(oG.AUDIO_PLAY_STATE_CHANGED,Wb(Hb({},t),{userId:""}))}),i&&e._room.isJoined&&e._room.publish(s).catch(()=>{}),e._localAudioTrack=s,e._room.capturedLocalMainAudioTrack=s,e._localAudioConfig=Wb(Hb({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:c,track:s}),oM.emit("113",{userId:"",room:e.room})}()})}updateLocalAudio(e){return Xb(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,muteKeepVolumeDetection:r,option:n}=e,o={};n&&(yield this._localAudioTrack.update3A(n),n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):KN(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),KN(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),KN(n.earMonitorVolume)||(o.muted=!(n.earMonitorVolume>0),o.volume=n.earMonitorVolume)),this._room.isJoined&&!KN(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),KN(i)||this._localAudioTrack.setMute(i,r),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),_w(this._localAudioConfig,e)})}stopLocalAudio(){return Xb(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),oM.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),uU(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,delete this._room.capturedLocalMainAudioTrack)})}startLocalVideo(){return Xb(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,r;if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:n,publish:o=!0,capture:s=!0,mute:a,option:c}=t,l=o,d=new kH(e._room.videoManager),u={},h={};c&&(XN(c.avoidCropping)&&(d.avoidCropping=c.avoidCropping),c.cameraId?u.deviceId=c.cameraId:KN(c.useFrontCamera)?KN(c.videoTrack)||(u.customSource=c.videoTrack):u.facingMode=c.useFrontCamera?$k.FACING_MODE_USER:$k.FACING_MODE_ENVIRONMENT,KN(c.retryWhenExactFailed)||(u.retryWhenExactFailed=c.retryWhenExactFailed),c.qosPreference&&(u.contentHint=OW(c.qosPreference)),KN(c.profile)||(qN(c.profile)?Yk[c.profile]&&d.setProfile(Yk[c.profile]):d.setProfile(c.profile)),KN(c.fillMode)||(h.objectFit=c.fillMode),KN(c.mirror)||(h.mirror=c.mirror),KN(c.small)||(KN(c.smallMode)||(e._room.smallMode=c.smallMode),XN(c.small)&&!1===c.small?d.stopSmall():d.updateSmallConfig(MW(c.small,!0))),KN(c.rotation)||d.setRotation(c.rotation),XN(e._enableAutoSwitchWhenRecapturing)&&(d.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),d.once("first-video-frame",t=>{e.emit(oG.FIRST_VIDEO_FRAME,Wb(Hb({},t),{streamType:PW(t.streamType)}))}),d.on("5",t=>{e.emit(oG.ERROR,new wW({code:CW.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))}),d.on("2",t=>{e.emit(oG.DEVICE_CHANGED,{type:"camera",action:"active",device:t})}),d.on("4",t=>{let i;t.error&&(i=wW.convertFrom(t.error)),e.emit(oG.PUBLISH_STATE_CHANGED,Wb(Hb({},t),{error:i}))}),d.on("6",()=>{}),e._listenOutputTrackChanged(d),s?yield d.capture(u):null==(i=d.manager)||i.changeInput(d),KN(a)||(yield d.setMute(a)),dU(d,d).add("player-state-changed",t=>{e.emit(oG.VIDEO_PLAY_STATE_CHANGED,Wb(Hb({},t),{userId:"",streamType:"main"}))}).add("video-size-changed",t=>{e.emit(oG.VIDEO_SIZE_CHANGED,Wb(Hb({},t),{streamType:PW(t.streamType)}))}),l&&e._room.isJoined&&(e._localScreenTrack&&(null==(r=e._localScreenConfig)?void 0:r.publish)&&"main"===e._localScreenConfig.streamType?(l=!1,e._log.warn("main stream is already published, local video track will not publish")):e._room.publish(d).catch(()=>{})),e._localVideoTrack=d,e._room.capturedLocalMainVideoTrack=d,e._localVideoConfig=Wb(Hb({},t),{view:n,publish:l,capture:s}),yield e._updateVideoPlayOption({view:n,playOption:h,track:d})}()})}updateLocalVideo(e){return Xb(this,null,function*(){var t,i,r,n;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:o,publish:s=!0,mute:a,capture:c,option:l,forcePublish:d=!1}=e,u=s||d,h={};if(l&&(KN(l.profile)||(qN(l.profile)?Yk[l.profile]&&this._localVideoTrack.setProfile(Yk[l.profile]):this._localVideoTrack.setProfile(l.profile),(!l.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(l.cameraId))&&KN(l.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),KN(l.fillMode)||(h.objectFit=l.fillMode),KN(l.mirror)||(h.mirror=l.mirror),KN(l.rotation)||this._localVideoTrack.setRotation(l.rotation),KN(l.small)||(XN(l.small)&&!l.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(MW(l.small,!0)))),this._localVideoConfig.capture)!1!==c?null!=l&&l.cameraId?yield this._localVideoTrack.switchDevice(null==l?void 0:l.cameraId):KN(null==l?void 0:l.useFrontCamera)?KN(null==l?void 0:l.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(null==l?void 0:l.videoTrack)):yield this._localVideoTrack.switchDevice(null!=l&&l.useFrontCamera?$k.FACING_MODE_USER:$k.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(c){let e={};e.deviceId=(null==l?void 0:l.cameraId)||(null==(t=this._localVideoConfig.option)?void 0:t.cameraId),e.facingMode=null!=l&&l.useFrontCamera||null!=(i=this._localVideoConfig.option)&&i.useFrontCamera?$k.FACING_MODE_USER:$k.FACING_MODE_ENVIRONMENT,e.customSource=(null==l?void 0:l.videoTrack)||(null==(r=this._localVideoConfig.option)?void 0:r.videoTrack),yield this._localVideoTrack.capture(e)}l&&l.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(OW(l.qosPreference)),this._room.isJoined&&KN(u)&&this._localVideoConfig.publish&&c&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((null!=u?u:this._localVideoConfig.publish)||d?this._localScreenTrack&&(null==(n=this._localScreenConfig)?void 0:n.publish)&&"main"===this._localScreenConfig.streamType&&!d?(u=!1,this._log.warn("main stream is already published, local video track will not publish")):this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),KN(a)||(yield this._localVideoTrack.setMute(a)),yield this._updateVideoPlayOption({view:o,playOption:h,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),_w(this._localVideoConfig,Wb(Hb({},e),{publish:u}))})}stopLocalVideo(){return Xb(this,null,function*(){var e;this._localVideoTrack&&(this._room.isJoined&&null!=(e=this._localVideoConfig)&&e.publish&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),uU(this._localVideoTrack),this._localVideoTrack=null,delete this._room.capturedLocalMainVideoTrack,this._localVideoConfig=null)})}startScreenShare(){return Xb(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,n;if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:o=null,publish:s=!0,muteSystemAudio:a,option:c}=t,l=s,d=new iW(e._room.videoManager);d.on("4",t=>{let i;t.error&&(i=wW.convertFrom(t.error)),e.emit(oG.PUBLISH_STATE_CHANGED,Wb(Hb({},t),{error:i}))}),d.once("first-video-frame",t=>{e.emit(oG.FIRST_VIDEO_FRAME,Wb(Hb({},t),{streamType:PW(t.streamType)}))}),e._listenOutputTrackChanged(d),"main"===t.streamType&&(d.mediaType=4);let u=null,h={},p={};c&&(KN(c.profile)||(qN(c.profile)?Zk[c.profile]&&d.setProfile(Zk[c.profile]):d.setProfile(c.profile)),c.systemAudio&&(h.systemAudio=!0,h.echoCancellation=c.echoCancellation,h.noiseSuppression=c.noiseSuppression,h.autoGainControl=c.autoGainControl),KN(c.fillMode)||(p.objectFit=c.fillMode),c.videoTrack&&(h.videoTrack=c.videoTrack),c.audioTrack&&(h.audioTrack=c.audioTrack),c.captureElement&&(h.captureElement=c.captureElement),c.preferDisplaySurface&&(h.preferDisplaySurface=c.preferDisplaySurface),c.qosPreference&&(h.contentHint=OW(c.qosPreference)));let m=yield d.capture(h);if(d.mediaTrack.addEventListener($k.ENDED,()=>{e._stopScreenShare(),e.emit(oG.SCREEN_SHARE_STOPPED)}),m.getAudioTracks()[0]){u=new nW(e._room.audioManager);let n=m.getAudioTracks()[0];null!=(i=t.option)&&i.systemAudio&&!(null!=(r=t.option)&&r.audioTrack)&&(u.sourceTrack=n),yield u.setInputMediaStreamTrack(n),XN(a)&&u.mediaTrack&&(u.mediaTrack.enabled=!a),e._speakerId&&u.setAudioOutput(e._speakerId)}if(dU(d,d).add("player-state-changed",t=>{e.emit(oG.VIDEO_PLAY_STATE_CHANGED,Wb(Hb({},t),{userId:"",streamType:"sub"}))}),l&&e._room.isJoined){let i=e._localVideoTrack&&(null==(n=e._localVideoConfig)?void 0:n.publish);"main"===t.streamType&&i?(l=!1,e._log.warn("main stream is already published, screen share main will not publish")):e._room.publish(d).catch(()=>{}),u&&(e._checkScreenAudioEchoCancellation(d,u),e._room.publish(u).catch(()=>{}))}e._localScreenTrack=d,e._room.capturedLocalAuxVideoTrack=d,e._localScreenAudioTrack=u,e._localScreenConfig=Wb(Hb({},t),{view:o,publish:l}),yield e._updateVideoPlayOption({view:o,playOption:p,track:d})}()})}updateScreenShare(e){return Xb(this,null,function*(){var t,i;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:n,muteSystemAudio:o,option:s}=e,a=n,c={};if(s){if(KN(s.fillMode)||(c.objectFit=s.fillMode),s.qosPreference){let e=OW(s.qosPreference);this._localScreenTrack.setContentHint(e)}s.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(s.videoTrack),s.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(s.audioTrack)}if(this._room.isJoined&&!KN(a)){if(a&&!this._localScreenConfig.publish){let e=this._localVideoTrack&&(null==(t=this._localVideoConfig)?void 0:t.publish);"main"===this._localScreenConfig.streamType&&e?(a=!1,this._log.warn("main stream is already published, screen share main will not publish")):this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})}if(this._localScreenConfig.publish&&!a){let e=[this._localScreenTrack];this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),e.forEach(e=>this._room.unpublish(e).catch(()=>{}))}}null!=(i=this._localScreenAudioTrack)&&i.mediaTrack&&XN(o)&&(this._localScreenAudioTrack.mediaTrack.enabled=!o),yield this._updateVideoPlayOption({view:r,playOption:c,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),_w(this._localScreenConfig,Wb(Hb({},e),{publish:a}))})}stopScreenShare(){return Xb(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return Xb(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,l=this._bindRemoteVideoTrackEvents(c);this._listenOutputTrackChanged(c),n&&(KN(n.fillMode)||(a.objectFit=n.fillMode),KN(n.mirror)||(a.mirror=n.mirror),KN(n.poster)||(a.poster=n.poster),a.canvasRender=n.canvasRender,"main"===r&&!KN(n.small)&&(!s.remoteVideoTrack.isSubscribing&&!s.remoteVideoTrack.isSubscribed&&s.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,c.user)),KN(n.draggable)||c.setDraggable(n.draggable)),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,handlers:l}),n&&!KN(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})})}updateRemoteVideo(e){return Xb(this,null,function*(){var t,i;let{view:r,userId:n,streamType:o,option:s,mute:a}=e,c="".concat(n,"_").concat(o),l=this._remoteVideoConfigMap.get(c);if(!l||!this._room.remotePublishedUserMap.has(n))return;let d={};s&&(KN(s.fillMode)||(d.objectFit=s.fillMode),KN(s.mirror)||(d.mirror=s.mirror));let u=null,h=this._room.remotePublishedUserMap.get(n);if("main"===o&&null!=h&&h.muteState.hasVideo&&(u=h.remoteVideoTrack),"sub"===o&&null!=h&&h.muteState.hasAuxiliary&&(u=h.remoteAuxiliaryTrack),!u)return;let{config:p}=l;"main"===o&&s&&!KN(s.small)&&this._room.changeType(s.small,u.user),s&&!KN(s.draggable)&&u.setDraggable(s.draggable),s&&(XN(s.pictureInPicture)&&(s.pictureInPicture?yield u.player.enterPictureInPicture():yield u.player.exitPictureInPicture()),XN(s.fullScreen)&&(s.fullScreen?yield u.player.enterFullscreen():yield u.player.exitFullscreen())),XN(a)&&(u.ignoreUpdatePlayingState=!0,a?(yield u.player.pause(),yield this.room.unsubscribe(u)):(yield this.room.subscribe(u),yield u.player.resume(!0))),yield this._updateVideoPlayOption({view:r,playOption:d,track:u,prevConfig:p}),_w(p,e);let m=KN(null==s?void 0:s.receiveWhenViewVisible)?null==(t=p.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,_=KN(r)?p.view:r,f=KN(null==s?void 0:s.viewRoot)?null==(i=p.option)?void 0:i.viewRoot:s.viewRoot;this._observeView({remoteTrack:u,view:_,receiveWhenViewVisible:m,viewRoot:f})})}stopRemoteVideo(e){return Xb(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Xb(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&&(delete e.ignoreUpdatePlayingState,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);if(r&&(r.observer&&r.observer.disconnect(),r.handlers)){let i=this._room.remotePublishedUserMap.get(e);if(i){let e="main"===t?i.remoteVideoTrack:i.remoteAuxiliaryTrack;this._unbindRemoteVideoTrackEvents(e,r.handlers)}}this._remoteVideoConfigMap.delete(i)}_bindRemoteVideoTrackEvents(e){let t={onEnterPIP:()=>Xb(this,null,function*(){yield e.player.enterPIPPromise,this.emit(oG.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:PW(e.streamType),userId:e.userId,isPictureInPicture:!0,pictureInPictureWindow:e.player.pipWindow})}),onLeavePIP:()=>{this.emit(oG.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:PW(e.streamType),userId:e.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(oG.FULL_SCREEN_STATE_CHANGED,{streamType:PW(e.streamType),userId:e.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(oG.FULL_SCREEN_STATE_CHANGED,{streamType:PW(e.streamType),userId:e.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(oG.ERROR,new wW({code:CW.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:e=>{this.emit(oG.VIDEO_SIZE_CHANGED,Wb(Hb({},e),{streamType:PW(e.streamType)}))}};return e.player.on(aU.ENTER_PICTURE_IN_PICTURE,t.onEnterPIP),e.player.on(aU.LEAVE_PICTURE_IN_PICTURE,t.onLeavePIP),e.player.on(aU.ENTER_FULL_SCREEN,t.onEnterFullScreen),e.player.on(aU.LEAVE_FULL_SCREEN,t.onLeaveFullScreen),e.on("decode-failed",t.onDecodeFailed),e.on("video-size-changed",t.onVideoSizeChanged),t}_unbindRemoteVideoTrackEvents(e,t){e.player.off(aU.ENTER_PICTURE_IN_PICTURE,t.onEnterPIP),e.player.off(aU.LEAVE_PICTURE_IN_PICTURE,t.onLeavePIP),e.player.off(aU.ENTER_FULL_SCREEN,t.onEnterFullScreen),e.player.off(aU.LEAVE_FULL_SCREEN,t.onLeaveFullScreen),e.off("decode-failed",t.onDecodeFailed),e.off("video-size-changed",t.onVideoSizeChanged)}muteRemoteAudio(e,t){return Xb(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)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):!this._remoteAudioConfigMap.has(e)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:e}))}catch(TM){throw TM.code!==CW.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),TM}})}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 Xb(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return Xb(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return Xb(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(oG.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"realtime-transcriber-message"===e&&this._room.subscribeDataChannel(),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{sG.has(e)||this._log.debug("emit ".concat(e," ").concat(JSON.stringify(i)))}catch(TM){}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),("realtime-transcriber-message"===t||"*"===t)&&0===this.listeners("realtime-transcriber-message").length&&this._room.unsubscribeDataChannel(),(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(qN(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 Xb(this,null,function*(){(yield RV()).forEach(t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(oG.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),bj=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: '.concat(Mk,"/en/TRTC.html#.setCurrentSpeaker"))})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return Xb(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(oG.ERROR,new wW({code:CW.OPERATION_FAILED,extraCode:5508,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=YN(r)?r:100;n.volume=s,this._remoteAudioConfigMap.set(i,e),yield this._room.subscribe(o),uF(zF(o,"decode-failed"),pB(zF(o,eU.INIT)),mH(()=>{this.startPlugin(Tj.Name,{track:o,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:n,track:o}),oM.emit("115",{userId:i,room:this.room}),o.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:o.outMediaTrack,refId:"ra-".concat(i)})}catch(SM){throw this._remoteAudioConfigMap.delete(i),SM}this._emitTrackEvent(o)})}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Xb(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)),oM.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),uF(zF(e,"decode-failed"),pB(zF(e,eU.INIT)),_H(()=>{"h265"!==this._room.downlinkVideoCodec&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),JB(zF(e,"decode-downgrade-state-changed")),mH(r=>{i=r.state,this.emit(oG.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Wb(Hb({},r),{streamType:t,userId:e.userId}))},t=>{e.log.error("fallback",t)},()=>{"STARTED"===i&&e.log.info("fallback complete")})))}_updateVideoPlayOption(e){return Xb(this,arguments,function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),KN(t)&&n&&n.view&&!uw(i)){let e=gw(n.view);e.length>0&&(yield r.play(e,i))}if(!KN(t)){let e=gw(t);e.length>0?yield r.play(e,i):r.stop()}}()})}_updateAudioPlayOption(e){return Xb(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(Ak){}if(KN(i.muted)||r.setPlayerMute(i.muted),KN(i.volume)||r.setAudioVolume(i.volume/100),r instanceof SH&&r.mediaTrack){let e=!1===i.muted&&!KN(i.volume)&&i.volume>0?"add":"remove";t.room.audioManager.updateAudioReference({type:e,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof dW){let e=i.muted?0:i.volume;if(KN(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(oG.TRACK,{userId:i,streamType:PW(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 Promise.all(r.map(e=>this._room.publish(e).catch(()=>{})))}_observeView(e){let{remoteTrack:t,view:i,receiveWhenViewVisible:r,viewRoot:n}=e;if(KN(i)||KN(r))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(PW(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||ZN(i)&&0===i.length||!r)return null==s||s.disconnect(),void(t.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",t.userId,t.strMediaType),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(gw(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 Xb(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return Xb(this,null,function*(){var e,t;if(this._localScreenTrack){if(this._room.isJoined){let t=[];null!=(e=this._localScreenConfig)&&e.publish&&t.push(this._localScreenTrack),this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield Promise.all(t.map(e=>this._room.unpublish(e).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),uU(this._localScreenTrack),this._localScreenTrack=null,delete this._room.capturedLocalAuxVideoTrack,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,t){return Xb(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(vM){this._log.warn("start audioProcessor plugin failed: ",vM)}}})}_onLocalTrackCaptured(e){let{track:t}=e;"audio"===t.kind&&(!bj||vV(bj))&&(this._initActiveSpeaker(),oM.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return Xb(this,null,function*(){if(bj&&!vV(bj))this.emit(oG.DEVICE_CHANGED,{type:"speaker",action:"active",device:bj});else{let e=yield RV();e[0]&&!vV(e[0])?(bj=e[0],this.emit(oG.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):oM.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(()=>{})}_onDataChannelAvailable(){if(this.listeners("realtime-transcriber-message").length>0)return this._room.subscribeDataChannel()}sendSEIMessage(e,t){var i;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:Wb(Hb({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),UL.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),UL.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return Xb(this,null,function*(){return this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(t),")")),yj.call(e,Hb({trtcInstance:this},t))})}static setLogLevel(e,t){dM.setLogLevel(e),KN(t)||(t?dM.enableUploadLog():dM.disableUploadLog())}static isSupported(){return XL(e.frameWorkType)}static getPermissions(e){return Xb(this,arguments,function(e){let{request:t=!0,types:i=["camera","microphone"]}=e;return function*(){t&&(yield Aj.request(i).catch(e=>{var t;return dM.error("getPermissions request failed, error: ".concat(null!=(t=null==e?void 0:e.message)?t:e))}));let[e,r]=yield Promise.all([Aj.get("camera"),Aj.get("microphone")]);return{camera:e,microphone:r}}()})}static getCameraList(){return IV(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return SV(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return RV(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(t){return Xb(this,null,function*(){if(mP&&(t===RW.SPEAKER||t===RW.HEADSET)){let i=yield e.getMicrophoneList(),r="";if(i.forEach(e=>{e.label===t&&(r=e.deviceId)}),!r)return;return void Cj.forEach(e=>Xb(null,null,function*(){e._localAudioTrack&&(yield e.updateLocalAudio({option:{microphoneId:r}}))}))}(yield RV()).forEach(e=>{e.deviceId===t&&(Cj.forEach(i=>{i._setCurrentSpeaker(t),i.emit(oG.DEVICE_CHANGED,{type:"speaker",action:"active",device:e})}),bj=e)})})}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:o,version:s,max:a}=e;switch(s&&(xL.version=s),t){case"count":xL.addCount({key:i,useUV:o});break;case"enum":xL.addEnum({key:i,value:r,useUV:o});break;case"number":xL.addNumber({key:i,value:r,split:n,max:a})}}get localVideoTrack(){return this._localVideoTrack}get localScreenTrack(){return this._localScreenTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}};qb(kj,"VERSION",VG),qb(kj,"_loggerManager",dM),qb(kj,"EVENT",oG),qb(kj,"ERROR_CODE",CW),qb(kj,"TYPE",RW),qb(kj,"frameWorkType",30),Kb([jG({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"}})})],kj.prototype,"use",1),Kb([FG(JW.TRTC.enterRoom),tG("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}),jV(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),jG()],kj.prototype,"enterRoom",1),Kb([jG()],kj.prototype,"exitRoom",1),Kb([FG(JW.TRTC.switchRoom),jG(),XV()],kj.prototype,"switchRoom",1),Kb([FG(JW.TRTC.switchRole),iG("room",{merge:(e,t)=>t}),jG()],kj.prototype,"switchRole",1),Kb([jG()],kj.prototype,"destroy",1),Kb([FG(JW.TRTC.startLocalAudio),tG("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)}),jG()],kj.prototype,"startLocalAudio",1),Kb([FG(JW.TRTC.updateLocalAudio),iG("audio",{debounce:{delay:200,getKey:()=>"".concat(Rj,"-localAudio"),isNeedToDebounce:e=>{var t;return!KN(null==(t=e.option)?void 0:t.captureVolume)}}}),jG()],kj.prototype,"updateLocalAudio",1),Kb([rG("audio"),jG()],kj.prototype,"stopLocalAudio",1),Kb([FG(JW.TRTC.startLocalVideo),tG("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)}),jG()],kj.prototype,"startLocalVideo",1),Kb([FG(JW.TRTC.updateLocalVideo),iG("video"),jG()],kj.prototype,"updateLocalVideo",1),Kb([rG("video"),jG()],kj.prototype,"stopLocalVideo",1),Kb([FG(JW.TRTC.startScreenShare),tG("screen",()=>!0),jG()],kj.prototype,"startScreenShare",1),Kb([FG(JW.TRTC.updateScreenShare),iG("screen"),jG()],kj.prototype,"updateScreenShare",1),Kb([jG()],kj.prototype,"stopScreenShare",1),Kb([FG(JW.TRTC.startRemoteVideo),tG(e=>"v".concat(e.userId).concat(e.streamType),()=>!0),jG({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],kj.prototype,"startRemoteVideo",1),Kb([FG(JW.TRTC.updateRemoteVideo),iG(e=>"v".concat(e.userId).concat(e.streamType)),jG({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],kj.prototype,"updateRemoteVideo",1),Kb([FG(JW.TRTC.stopRemoteVideo),jV(e=>function(t){return Xb(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)})}),jG({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],kj.prototype,"stopRemoteVideo",1),Kb([rG(e=>"v".concat(e.userId).concat(e.streamType))],kj.prototype,"_stopRemoteVideo",1),Kb([FG(...JW.TRTC.muteRemoteAudio),jG({getRemoteId:e=>e})],kj.prototype,"muteRemoteAudio",1),Kb([BG(...JW.TRTC.setRemoteAudioVolume),function(e,t){return jV((i,r)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let s=UG.get(this);s||(s=new Map,UG.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=UG.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=UG.get(this))||e.delete(a)},e);s.set(a,t)}})}(200,e=>e),jG({getRemoteId:e=>e})],kj.prototype,"setRemoteAudioVolume",1),Kb([JG("start"),WV(e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)}),tG((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),jG({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>wL[e.getName()],ignoreLog:e=>"Debug"===e.getName(),ignoreErrorLog:e=>"AudioProcessor"===e.getName()})],kj.prototype,"startPlugin",1),Kb([JG("update"),iG((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(_w(e[1],t[1]),e)}),jG({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>PL[e.getName()]})],kj.prototype,"updatePlugin",1),Kb([JG("stop"),rG((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i}),jG({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>OL[e.getName()]})],kj.prototype,"stopPlugin",1),Kb([BG(...JW.TRTC.enableAudioVolumeEvaluation)],kj.prototype,"enableAudioVolumeEvaluation",1),Kb([jG()],kj.prototype,"getVideoSnapshot",1),Kb([jG()],kj.prototype,"_setCurrentSpeaker",1),Kb([tG(e=>"a".concat(e.userId),()=>!0)],kj.prototype,"_startRemoteAudio",1),Kb([jV(e=>function(t){return Xb(this,null,function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(Wb(Hb({},t),{userId:e.userId})).catch(()=>{}))):e.call(this,t)})}),rG(e=>"a".concat(e.userId))],kj.prototype,"_stopRemoteAudio",1),Kb([rG("room")],kj.prototype,"_exitRoom",1),Kb([rG("screen")],kj.prototype,"_stopScreenShare",1),Kb([FG(...JW.TRTC.sendSEIMessage),SW({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}})],kj.prototype,"sendSEIMessage",1),Kb([FG(JW.TRTC.sendCustomMessage),SW({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],kj.prototype,"sendCustomMessage",1),Kb([nG()],kj,"create",1),Kb([FG(JW.TRTC.create)],kj,"_create",1),Kb([nG()],kj,"setLogLevel",1),Kb([nG()],kj,"isSupported",1),Kb([nG(),jG()],kj,"getPermissions",1),Kb([nG()],kj,"getCameraList",1),Kb([nG()],kj,"getMicrophoneList",1),Kb([nG()],kj,"getSpeakerList",1);var Dj=kj,Nj=class{constructor(){qb(this,"_set",new Set),oM.on(aM.LEAVE_SUCCESS,this.delete,this),oM.on(aM.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 wj(){return Xb(this,null,function*(){let e,t;try{let t=yield SV();e=t&&t.length}catch(p){}try{let e=yield IV();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=pM.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};hU.uploadEvent({log:"trtcstats-".concat(JSON.stringify(u)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(u))),hU.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(h)),userId:this.userId}),Hx()})}var Pj=Jb(Qb()),Oj="1",Mj="2",Lj="3",xj="4",Uj="5",Vj="6",Fj="7",Bj="8",Hj={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,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},Wj=[Hj.UPDATE_REMOTE_MUTE_STAT,Hj.UPLINK_NETWORK_STATS,Hj.USER_LIST_RES,Hj.MUTE_RESULT,Hj.SERVER_FIRST_PACKAGE_RECEIVED,Hj.RECEIVE_CUSTOM_MSG,Hj.UPDATE_NETWORK_TIME_RESULT],Gj={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",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},jj="publish_change",zj="join",Jj="leave",Kj="quality_report",qj="mute_uplink",Yj="publish",Xj="publish_state_change",Qj="unpublish",Zj="subscribe",$j="unsubscribe",ez="subscribe_change",tz="start_publishing",iz="stop_publishing",rz="start_push_user_cdn",nz="stop_push_user_cdn",oz="start_mcu_mix",sz="stop_mcu_mix",az="start_publish_cdn_stream",cz="update_publish_cdn_stream",lz="stop_publish_cdn_stream",dz="get_user_list",uz="change_role",hz="update_constraint_config",pz="rebuild_pc",mz="join/v2",_z="publish/v2",fz="subscribe/v3",gz="ability_status_report",Ez="reconnect",Tz="channel_msg",vz="switch_room",yz="update_network_time",Sz=new Set([Yj,jj,Xj,Qj,Zj,ez,$j,_z,fz]),Iz=new Set;var Az=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],Rz=0,Cz=class extends Pj.default{constructor(e){var t,i,r;super(),qb(this,"room"),qb(this,"sdkAppId"),qb(this,"userId"),qb(this,"userSig"),qb(this,"url"),qb(this,"backupUrl"),qb(this,"destroyed",!1),qb(this,"_socketInUse"),qb(this,"_socket"),qb(this,"_backupSocket"),qb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0}),qb(this,"_currentState","DISCONNECTED"),qb(this,"_isReconnecting",!1),qb(this,"_seq",0),qb(this,"_log"),qb(this,"_lastMessageTime",-1),qb(this,"_connectStartTime",-1),qb(this,"_stopConnectRetry"),qb(this,"_isFirstConnect",!0),qb(this,"bytesSent",0),qb(this,"bytesReceived",0),qb(this,"keepAlive",!1),qb(this,"signalDomainWhenUnifiedProxy"),qb(this,"stopKeepAliveTimeout"),qb(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-Iz.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Iz.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=dM.createLogger({parent:this.room.getLogger(),id:"ws".concat(++Rz),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 Az.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 Xb(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 sw(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?$k.BACKUP:$k.MAIN),e._isFirstConnect&&(UL.addSuccessEvent({key:521720}),e._isFirstConnect=!1),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?$k.MAIN:$k.BACKUP),t(new dk({code:ck.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===$k.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(kD){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(kD){}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(Uj,new dk({code:ck.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($k.MAIN),this.unbindAndCloseSocket($k.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Uj,new dk({code:ck.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(Bj),this.bytesReceived+=Sw(e.data);let i=JSON.parse(e.data),{cmd:r,data:n}=i,o=Object.values(Hj),s=Object.keys(Hj)[o.indexOf(r)],a=Gj[s]||r;switch(Wj.includes(r)||(this._log.debug("received ".concat(r," msg: ").concat(e.data)),a&&this._log.info("Received event: [ ".concat(a," ]"))),r){case Hj.CHANNEL_SETUP_RESULT:if(0===i.code)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&pk(n.svrTime-(new Date).getTime()),this._log.info("ChannelSetup Success ".concat(aw()-this._connectStartTime)),UL.addSuccessEvent({key:521701,cost:aw()-this._connectStartTime}),this._connectStartTime=-1,this.room.firewallDetector.resetTimeoutCount(),this.emit(Oj,{signalInfo:this._signalInfo});else{let e=new dk({code:ck.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:i.code,message:RL({key:yL.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:i.code,errorMsg:i.message}})});this._log.error("".concat(i.code,", ").concat(i.message)),this.close(),UL.addFailedEvent({key:521701,error:e}),this.emit(Uj,e)}break;case Hj.JOIN_ROOM_RESULT:0===i.code&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.bakRelayIps=n.bakRelayIps,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=i.tinyId,this._signalInfo.endReportExtend=n.endReportExtend,this._signalInfo.reportToken=n.reportToken,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(a,{data:i});break;default:this.emit(String(a),{data:i})}}reGetSignalChannelUrl(){return Xb(this,null,function*(){try{if(!this.room.joinParams)return;hG(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(Ik){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?$k.MAIN:$k.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return Xb(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:Ez,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:Gj.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),UL.addSuccessEvent({key:521702,cost:aw()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(UL.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(Ik){this._log.error(Ik),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),Sz.has(e)&&this._log.info("send",e,t),this.bytesSent+=Sw(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 dk({code:ck.API_CALL_ABORTED,message:"".concat(t," aborted due to connection closed")}))};this.once(Fj,l);let d=setTimeout(()=>{this.off(n,u),this.off(Fj,l);let e=new dk({code:ck.API_CALL_TIMEOUT,message:RL({key:yL.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(Fj,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 $w({retryFunction:this.sendWaitForResponse,onError:e=>{let{retry:t,reject:r,error:n}=e;!this.room.isJoined||this.destroyed||n.code===ck.API_CALL_ABORTED?r(n):this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(Bj,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),Iz.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket($k.MAIN),this.unbindAndCloseSocket($k.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Fj)}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(Gj.JOIN_ROOM_RESULT,t)},1e3*e);let t=e=>{0===e.data.code&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(Gj.JOIN_ROOM_RESULT,t))};this.on(Gj.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){if(e===this._currentState)return;this._log.info("".concat(this._currentState," -> ").concat(e));let t={prevState:this._currentState,state:e};"CONNECTING"===e&&(t.isReconnecting=this._isReconnecting),this.emit(Mj,t),this._currentState=e,"CONNECTED"===e?this.emit(Lj):"DISCONNECTED"===e&&this.emit(Vj)}};Kb([mU({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(UL.addFailedEvent({key:521720,error:e}),this._isFirstConnect=!1),this.room.firewallDetector.increaseTimeoutCount(),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())}})],Cz.prototype,"connect",1);var bz=Jb(Qb()),kz=!1,Dz=class{constructor(e){qb(this,"userId"),qb(this,"tinyId"),qb(this,"_sdpSemantics"),qb(this,"_isUplink"),qb(this,"_room"),qb(this,"_log"),qb(this,"_signalChannel"),qb(this,"_isErrorObserved",!1),qb(this,"_waitForPeerConnectionConnectedPromise"),qb(this,"_waitForPeerConnectionConnectedPromiseReject",null),qb(this,"_peerConnection",null),qb(this,"_emitter",new bz.default),qb(this,"_currentState","DISCONNECTED"),qb(this,"_isReconnecting",!1),qb(this,"_reconnectionCount",0),qb(this,"_reconnectionTimer",-1),qb(this,"_isFirstConnection",!0),qb(this,"_prevTime",-1),qb(this,"_localAddress"),qb(this,"_remoteAddress"),qb(this,"isDestoyed",!1),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=e.room.getLogger().createChild({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,UL.addSuccessEvent({key:521705,cost:Math.min(aw()-this._prevTime,3e4)})):this._isReconnecting&&UL.addSuccessEvent({key:521706,cost:aw()-this._prevTime}),this._prevTime=-1}catch(EM){throw this._isFirstConnection?(this._isFirstConnection=!1,UL.addFailedEvent({key:521705,error:EM})):this._isReconnecting&&this._reconnectionCount>=3&&UL.addFailedEvent({key:521706,error:EM}),EM}}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()}destroy(){this.isDestoyed=!0}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 dk({code:ck.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return ID;let e=null;if(this._isUplink){if(!px()||0===this._peerConnection.getSenders().length)return ID;e=this._peerConnection.getSenders()[0].transport}else{if(!hx()||0===this._peerConnection.getReceivers().length)return ID;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:ID}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===AD.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===AD.FAILED||e.target.connectionState===AD.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new dk({message:r,code:ck.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===AD.CONNECTED||e.target.connectionState===AD.COMPLETED)&&(this.logSelectedCandidate(),hU.logSuccessEvent({userId:this._room.userId,eventType:ND.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e&&(this._room.firewallDetector.resetTimeoutCount(),kz=!0),oM.emit(aM.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 Xb(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(rx(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 dk({code:ck.API_CALL_ABORTED,message:RL({key:yL.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{oM.off(aM.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout(()=>{n();let e=new dk({code:ck.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),t(e)},WD);oM.on(aM.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(Lj,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=bD()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new dk({code:this._isUplink?ck.UPLINK_RECONNECTION_FAILED:ck.DOWNLINK_RECONNECTION_FAILED,message:RL({key:this._isUplink?yL.UPLINK_RECONNECTION_FAILED:yL.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(Lj,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)}};Kb([$V(521712,!1)],Dz.prototype,"setOffer",1),Kb([$V(521713,!1)],Dz.prototype,"setAnswer",1);var Nz=Jb(ok()),wz=function(e){return Nz.default.parse(e)},Pz=function(e){return Nz.default.write(e)};function Oz(e){return Object.keys(e).filter(t=>e[t])}var Mz=class e extends Dz{constructor(e){super(Wb(Hb({},e),{isUplink:!1})),qb(this,"_flag",0),qb(this,"isRobot",!1),qb(this,"role","anchor"),qb(this,"remoteAudioTrack"),qb(this,"remoteVideoTrack"),qb(this,"remoteAuxiliaryTrack"),qb(this,"avPlayerStateSyncManager"),qb(this,"ssrc",{audio:0,video:0,auxiliary:0}),qb(this,"_isSDPExchanging",!1),qb(this,"_videoCodec"),qb(this,"fromType"),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new dW(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new hW(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new pW(this._room,this),this.avPlayerStateSyncManager=new MG({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player})}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 hw(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===$k.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.avPlayerStateSyncManager.destroy(),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===hD?$k.MAIN:$k.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=$k.AUDIO;i.kind===$k.VIDEO&&(n=r===$k.MAIN?$k.VIDEO:$k.AUXILIARY);let o=this.remoteAudioTrack;n===$k.VIDEO?o=this.remoteVideoTrack:n===$k.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=wz(e);return t.media.forEach(e=>{e.type===$k.VIDEO&&e.fmtp.forEach(e=>{e.config+=";sps-pps-idr-in-keyframe=1"})}),Pz(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=wz(e);return i.media.forEach(e=>{e.ext&&(e.ext=e.ext.filter(e=>!t.includes(e.uri)))}),Pz(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return Xb(this,null,function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===AD.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===AD.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(Ak){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Ak.message," ").concat(JSON.stringify(this.muteState))),new dk({code:ck.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Ak}})}unsubscribe(e){return Xb(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=Hb({},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(Oz(e),"]")),yield t.sendSubscription(n,e),"unsubscribe"===n&&(t.closePeerConnection(),t.emitConnectionStateChangedEvent("DISCONNECTED"))}()})}unsubscribeDataChannel(){return Xb(this,null,function*(){})}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=$j,n=Gj.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=ez,n=Gj.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 dk({code:i.code,message:RL({key:yL.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}})}connect(){return Xb(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(kD){throw e.closePeerConnection(!0),kD}}()})}exchangeSDP(e){return Xb(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:Zj,commandDesc:"exchange sdp",data:r,responseCommand:Gj.SUBSCRIBE_RESULT,timeout:OD});if(!this._peerConnection){let e=new dk({code:ck.INVALID_OPERATION,message:RL({key:yL.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(kD){throw this._isSDPExchanging=!1,kD}})}createOffer(){return Xb(this,null,function*(){let e={voiceActivityDetection:!1};_x()&&this._sdpSemantics===MD?(this._peerConnection.addTransceiver($k.AUDIO,{direction:eD.RECVONLY}),this._peerConnection.addTransceiver($k.VIDEO,{direction:eD.RECVONLY}),this._peerConnection.addTransceiver($k.VIDEO,{direction:eD.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield YL();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=wz(e);return t.media.forEach(e=>{var t,i;if(e.type===$k.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(" ")}}),Pz(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=wz(e);return t.media.forEach(e=>{e.type===$k.AUDIO&&e.fmtp.forEach(e=>{e.config+=";sprop-stereo=1;stereo=1"})}),Pz(t)}(t.sdp),this._sdpSemantics===MD&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return Xb(this,null,function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===xD)throw new dk({code:ck.NOT_SUPPORTED_H264,message:RL({key:yL.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new dk({code:t,message:RL({key:yL.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(vM){throw this._log.error(vM),vM}})}updateSSRC(e){try{wz(e).media.forEach(e=>{if(e.ssrcs)if(e.type===$k.AUDIO){let t=e.ssrcs.find(e=>{var t;return null==(t=e.value)?void 0:t.includes(hD)});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(hD)}),i=e.ssrcs.find(e=>{var t;return null==(t=e.value)?void 0:t.includes(pD)});t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}})}catch(kD){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return Xb(this,null,function*(){if(!(Yb(e.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(kD){let t=jN(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}};Kb([jV(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 dk({code:ck.API_CALL_ABORTED,message:RL({key:yL.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally(()=>{this._emitter.off("closed",n)})})})],Mz.prototype,"subscribe",1),Kb([$V(521717,!1)],Mz.prototype,"unsubscribe",1),Kb([WV(Dz.prototype.afterConnect),HV(Dz.prototype.beforeConnect)],Mz.prototype,"connect",1);var Lz=Mz,xz={voiceActivityDetection:!1},Uz=class e extends Dz{constructor(e){super(Wb(Hb({},e),{isUplink:!0})),qb(this,"localMainAudioTrack",null),qb(this,"localMainVideoTrack",null),qb(this,"localAuxAudioTrack",null),qb(this,"localAuxVideoTrack",null),qb(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),qb(this,"_isPublishingAux",!1),qb(this,"_publishingLocalAudioTrack"),qb(this,"_publishingLocalVideoTrack"),qb(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}),qb(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)}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 Xb(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(),_x()?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 Xb(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||$k.AUDIO,{direction:eD.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?$k.VIDEO:s||$k.VIDEO,{direction:eD.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||$k.VIDEO,{direction:eD.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||$k.VIDEO,{direction:eD.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:$k.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:$k.VIDEO,videoType:o?$k.AUXILIARY:$k.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:$k.VIDEO,videoType:$k.SMALL}),e.push(2))}yield t.setTransceiverDirection(eD.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 Xb(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 Xb(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(eD.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(eD.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 Xb(this,arguments,function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!mx())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=Wb(Hb({},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=Wb(Hb({},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(eD.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 Xb(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:Xj,data:t,responseCommand:Gj.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:Qj,commandDesc:"unpublish",responseCommand:Gj.UNPUBLISH_RESULT,enableLog:e}).catch(e=>{if(e.getCode()===ck.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),Sx){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:hz,data:this._mediaSettings,responseCommand:Gj.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{0!==e.data.code&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return Xb(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?$k.AUXILIARY:$k.MAIN," stream")),_x()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return Xb(this,null,function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===$k.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===eD.INACTIVE&&(yield this.setTransceiverDirection(eD.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return Xb(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;mx()&&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===$k.VIDEO&&e instanceof kH&&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===LD||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=wz(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===$k.VIDEO)return!0;return!1}removeSender(e){let t=null;mx()&&(t=this._peerConnection.getTransceivers().find(t=>t.sender&&t.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&JN(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return Xb(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?$k.AUXILIARY:$k.MAIN," stream")),_x()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return Xb(this,null,function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===$k.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(eD.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return Xb(this,null,function*(){if(!EP)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(eD.INACTIVE,"|").concat(eD.RECVONLY,"|").concat(eD.SENDONLY,")")))&&o++,t.includes(o)){if(e===eD.INACTIVE&&i.includes("a=".concat(eD.RECVONLY)))return r=!0,"a=".concat(e);if(e===eD.SENDONLY&&i.includes("a=".concat(eD.INACTIVE)))return r=!0,"a=".concat(eD.RECVONLY)}return i}).join("\r\n");r&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:s}))})}removeTrackBySender(e){return Xb(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===$k.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===$k.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(e=>{e.track&&e.track.kind===$k.VIDEO&&this.removeSender(e)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return Xb(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=_x()?e.kind===$k.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?$k.AUXILIARY:$k.MAIN," stream")),e.kind===$k.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===$k.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return Xb(this,null,function*(){try{let i=yield this._peerConnection.createOffer(xz);EP&&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===$k.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:r,state:this._room.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:jj,data:n,responseCommand:Gj.UPDATE_OFFER_RESULT,timeout:PD,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(TM){throw this._log.error(TM),TM}})}setBandwidth(e){return Xb(this,arguments,function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!vx())return o?r===$k.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(_x()){let t=0;r===$k.VIDEO&&(t=n===$k.SMALL?2:n===$k.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===$k.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()})}updateVideoBandwidthRestriction(e,t,i){let r="AS";EP&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===$k.SMALL?n=1:i===$k.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 EP&&(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 Xb(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(Ik){throw this.closePeerConnection(!0),this.uninstallEvents(),Ik}})}exchangeSDP(){return Xb(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(Ik){throw Ik}})}createOffer(){return Xb(this,null,function*(){try{let e=yield this._peerConnection.createOffer(xz);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(Ik){throw Ik}})}doExchangeSDP(){let e={command:Yj,responseCommand:Gj.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof iW||this.localAuxVideoTrack instanceof iW,state:this._room.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=wz(e);return r.media.forEach(e=>{("all"===i||e.type===i)&&(e.direction=t)}),Pz(r)}acceptAnswer(e){return Xb(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?$k.AUXILIARY:$k.BIG;s=yield this.setBandwidth({bandwidth:e,type:$k.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:$k.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:$k.VIDEO,videoType:$k.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this.setAnswer(a),this._log.debug("accepted answer: ".concat(s))}catch(SM){throw this._log.error("failed to accept remote answer ".concat(SM)),SM}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.send(qj,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return Xb(this,null,function*(){if(!(Yb(e.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Qj,responseCommand:Gj.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(kD){let t=jN(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)&&oM.emit(aM.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{wz(e).media.forEach((e,t)=>{if(e.type===$k.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===LD&&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(kD){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:$k.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===$k.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===$k.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===$k.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===$k.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===xD?(this._log.error(SL.NOT_SUPPORTED_H264ENCODE),new dk({code:ck.NOT_SUPPORTED_H264,message:RL({key:yL.NOT_SUPPORTED_H264ENCODE})})):new dk({code:ck.UNKNOWN,message:RL({key:yL.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Gj.PUBLISH_RESULT,code:e,message:t}})})}};Kb([jV(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 dk({code:ck.API_CALL_ABORTED,message:RL({key:yL.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally(()=>{this._emitter.off("closed",n)})})})],Uz.prototype,"publish",1),Kb([$V(521715,!1)],Uz.prototype,"unpublish",1),Kb([WV(Dz.prototype.afterConnect),HV(Dz.prototype.beforeConnect)],Uz.prototype,"connect",1);var Vz=Uz,Fz=class{constructor(e,t){this.room=e,qb(this,"_log"),qb(this,"_prevReportTime",0),qb(this,"_prevReport",{}),qb(this,"_prevStats",null),qb(this,"_prevEncoderImplementation",""),qb(this,"_prevAuxEncoderImpl",""),qb(this,"_prevQualityLimitationReason",""),qb(this,"_prevAuxQualityLimitationReason",""),qb(this,"_prevDecoderImplementationMap",new Map),qb(this,"_decodeMap",new Map),qb(this,"_prevQpSum",0),qb(this,"_prevAuxQpSum",0),qb(this,"totalBytesSent",0),qb(this,"totalBytesReceived",0),qb(this,"_spcStats",null),this._log=t}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return Xb(this,null,function*(){var t,i,r,n,o,s,a;let c={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},l=e.getPeerConnection(),d=e.getSSRC();if(l)try{if((this._spcStats||(yield l.getStats())).forEach(t=>{var i,r,n,o,s,a,l,u,h,p,m,_,f;let g,E;if("outbound-rtp"===t.type)if((t.mediaType||t.kind)===$k.VIDEO){if(t.ssrc===d.video?(g=$k.VIDEO,E=e.localMainVideoTrack):t.ssrc===d.small?g=$k.SMALL:t.ssrc===d.auxiliary&&(E=e.localAuxVideoTrack,g=$k.AUXILIARY),!g)return;c[g].bytesSent=t.bytesSent,c[g].packetsSent=t.packetsSent,c[g].framesEncoded=t.framesEncoded,KN(t.keyFramesEncoded)||(c[g].keyFramesEncoded=t.keyFramesEncoded),KN(t.nackCount)||(c[g].nackCount=t.nackCount),KN(t.pliCount)||(c[g].pliCount=t.pliCount),KN(t.retransmittedPacketsSent)||(c[g].retransmittedPacketsSent=t.retransmittedPacketsSent),KN(t.totalEncodeTime)||(c[g].totalEncodeTime=t.totalEncodeTime),KN(t.totalPacketSendDelay)||(c[g].totalPacketSendDelay=t.totalPacketSendDelay);let l=0;if(!KN(t.qpSum)&&!KN(t.framesEncoded)&&t.framesEncoded>0){let s=t.qpSum,a=t.framesEncoded,c=g===$k.VIDEO?this._prevQpSum:this._prevAuxQpSum,d=g===$k.VIDEO?(null==(r=null==(i=e.localMainVideoTrack)?void 0:i.stat)?void 0:r.framesEncoded)||0:(null==(o=null==(n=e.localAuxVideoTrack)?void 0:n.stat)?void 0:o.framesEncoded)||0;if(a>d&&s>c){let i=s-c,r=a-d;l=Math.round(i/r),l>35&&this._log.warn("".concat(g===$k.AUXILIARY?"aux ":"","video encoder QP is high: ").concat(l,", resolution: ").concat(t.frameWidth,"x").concat(t.frameHeight,", codec: ").concat(e.videoCodec,", "))}g===$k.VIDEO?this._prevQpSum=s:g===$k.AUXILIARY&&(this._prevAuxQpSum=s)}if(!KN(t.encoderImplementation)&&(g===$k.VIDEO&&this._prevEncoderImplementation!==t.encoderImplementation||g===$k.AUXILIARY&&this._prevAuxEncoderImpl!==t.encoderImplementation)){let i=2,r=this._prevEncoderImplementation;g===$k.AUXILIARY&&(i=7,r=this._prevAuxEncoderImpl),oM.emit("262",{userId:e.userId,streamType:i,prevImplementation:r,implementation:t.encoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientEncoder}),this[g===$k.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=t.encoderImplementation,null==E||E.log.info("encoderImplementation change to ".concat(t.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(t.powerEfficientEncoder))}t.ssrc===d.video?!KN(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(null==E||E.log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),oM.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:null==(s=e.localMainVideoTrack)?void 0:s.isQosClearFirst}),this._prevQualityLimitationReason=t.qualityLimitationReason):t.ssrc===d.auxiliary&&!KN(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),oM.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(a=e.localAuxVideoTrack)?void 0:a.isQosClearFirst}),this._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else c.audio.bytesSent=t.bytesSent,c.audio.packetsSent=t.packetsSent;else if("candidate-pair"===t.type)rx(t)&&(this.totalBytesSent=t.bytesSent,YN(t.currentRoundTripTime)&&(c.rtt=Math.floor(1e3*t.currentRoundTripTime)));else if("media-source"===t.type)if(t.kind===$k.AUDIO)c.audio.audioLevel=t.audioLevel||0,c.audio.totalAudioEnergy=t.totalAudioEnergy||0,t.echoReturnLoss,KN(null==(h=null==(u=null==(l=e.localMainAudioTrack)?void 0:l.sourceTrack)?void 0:u.stats)?void 0:h.deliveredFramesDuration)?t.totalSamplesDuration&&(c.audio.totalSamplesDuration=t.totalSamplesDuration):c.audio.totalSamplesDuration=e.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(t.kind===$k.VIDEO)if(t.trackIdentifier===e.getVideoTrackId($k.VIDEO))if(null!=(_=null==(m=null==(p=e.localMainVideoTrack)?void 0:p.sourceTrack)?void 0:m.stats)&&_.deliveredFrames){let{deliveredFrames:i}=e.localMainVideoTrack.sourceTrack.stats;c.video.framesCaptured=i,e.localMainVideoTrack.stat.framesCaptured&&e.localMainVideoTrack.stat.framesCaptured>0&&i>=e.localMainVideoTrack.stat.framesCaptured?c.video.fpsCapture=Math.floor((i-e.localMainVideoTrack.stat.framesCaptured)/this.statInterval):c.video.fpsCapture=t.framesPerSecond}else c.video.fpsCapture=t.framesPerSecond;else t.trackIdentifier===e.getVideoTrackId($k.AUXILIARY)?c.auxiliary.fpsCapture=t.framesPerSecond:c.small.fpsCapture=t.framesPerSecond;if(!KN(t.audioLevel)&&null!=(f=e.localMainAudioTrack)&&f.mediaTrack&&t.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(c.audio.audioLevel=t.audioLevel||0),!KN(t.frameWidth)){let i=$k.SMALL;t.trackIdentifier===e.getVideoTrackId($k.VIDEO)||t.ssrc===d.video?i=$k.VIDEO:(t.trackIdentifier===e.getVideoTrackId($k.AUXILIARY)||t.ssrc===d.auxiliary)&&(i=$k.AUXILIARY),c[i].frameWidth=t.frameWidth,c[i].frameHeight=t.frameHeight,c[i].framesSent=t.framesSent}}),e.localMainAudioTrack||e.getRoom().capturedLocalMainAudioTrack){let r=e.localMainAudioTrack||e.getRoom().capturedLocalMainAudioTrack;if(r){let n=r.getInternalAudioLevel(),o=r.getInternalAudioLevelAfter3A();c.audio.audioCaptureEnergyAfter3a=o,c.audio.micAudioLevel=n,0===c.audio.audioLevel&&e.localMainAudioTrack&&(c.audio.audioLevel=null!=o?o:n),!e.localMainAudioTrack&&!KN(null==(i=null==(t=r.sourceTrack)?void 0:t.stats)?void 0:i.deliveredFramesDuration)&&(c.audio.totalSamplesDuration=r.sourceTrack.stats.deliveredFramesDuration/1e3)}}if(!e.localMainVideoTrack&&e.getRoom().capturedLocalMainVideoTrack){let t=e.getRoom().capturedLocalMainVideoTrack;if(null!=(n=null==(r=null==t?void 0:t.sourceTrack)?void 0:r.stats)&&n.deliveredFrames){let{deliveredFrames:e}=t.sourceTrack.stats;c.video.framesCaptured=e,t.stat.framesCaptured&&t.stat.framesCaptured>0&&e>=t.stat.framesCaptured&&(c.video.fpsCapture=Math.floor((e-t.stat.framesCaptured)/this.statInterval)),t.stat.framesCaptured=e}}if(!e.localAuxVideoTrack&&e.getRoom().capturedLocalAuxVideoTrack){let t=e.getRoom().capturedLocalAuxVideoTrack;if(null!=(s=null==(o=null==t?void 0:t.sourceTrack)?void 0:o.stats)&&s.deliveredFrames){let{deliveredFrames:e}=t.sourceTrack.stats;c.auxiliary.framesCaptured=e,t.stat.framesCaptured&&t.stat.framesCaptured>0&&e>=t.stat.framesCaptured&&(c.auxiliary.fpsCapture=Math.floor((e-t.stat.framesCaptured)/this.statInterval)),t.stat.framesCaptured=e}}this.totalBytesSent||(this.totalBytesSent+=c.audio.bytesSent+c.video.bytesSent+c.auxiliary.bytesSent),Object.keys(c).forEach(t=>{t===$k.AUDIO?(e.localMainAudioTrack&&(e.localMainAudioTrack.stat=c[t]),e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=c[t])):t===$k.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=c[t]):t===$k.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=c[t])})}catch(_M){this._log.warn("failed to getStats on sender connection ".concat(_M))}return 0===c.rtt&&(c.rtt=(null==(a=this.room.networkQuality)?void 0:a.uplinkRTT)||0),c})}getReceiverStats(e){return Xb(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,avSyncDelay:0,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)===$k.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(EP&&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=dL[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)&&(c.log.info("decoderImplementation change to ".concat(t.decoderImplementation,"(").concat(e.videoCodec,") HWDecoder: ").concat(t.powerEfficientDecoder)),oM.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)),KN(t.keyFramesDecoded)||c.updateKeyFramesDecoded(t.keyFramesDecoded)),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",KN(t.keyFramesDecoded)||c.updateKeyFramesDecoded(t.keyFramesDecoded)),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,n.audio.estimatedPlayoutTimestamp=t.estimatedPlayoutTimestamp):t.ssrc===r.video&&s.hasVideo?(n.video.totalJitter=t.jitterBufferDelay,n.video.totalJitterCount=t.jitterBufferEmittedCount,n.video.estimatedPlayoutTimestamp=t.estimatedPlayoutTimestamp):t.ssrc===r.auxiliary&&s.hasAuxiliary&&(n.auxiliary.totalJitter=t.jitterBufferDelay,n.auxiliary.totalJitterCount=t.jitterBufferEmittedCount))}else"candidate-pair"===t.type&&rx(t)&&(this.totalBytesReceived=t.bytesReceived,YN(t.currentRoundTripTime)&&(n.rtt=Math.floor(1e3*t.currentRoundTripTime)));KN(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)),!KN(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),KN(null==(t=e.remoteVideoTrack.player.stat)?void 0:t.fps)||(n.video.fpsRender=e.remoteVideoTrack.player.stat.fps),KN(null==(i=e.remoteAuxiliaryTrack.player.stat)?void 0:i.fps)||(n.auxiliary.fpsRender=e.remoteAuxiliaryTrack.player.stat.fps);let c=n.audio.estimatedPlayoutTimestamp,l=n.video.estimatedPlayoutTimestamp;if(c&&l&&e.remoteAudioTrack.isAvailable&&e.remoteVideoTrack.isAvailable){let e=l-c;Math.abs(e)<=1e4&&(n.avSyncDelay=e,Math.abs(e)>150&&this._log.warn("av sync delay",e))}}catch(vM){this._log.warn("failed to getStats on receiver connection ".concat(vM))}return 0===n.rtt&&(n.rtt=(null==(r=this.room.networkQuality)?void 0:r.uplinkRTT)||0),n})}getStats(e,t){return Xb(this,null,function*(){let i,r={},n=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:r,receiverStats:n};let t=aw(),i=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","media-playout"]);i.forEach(e=>a.has(e.type)&&s.push(e)),this._spcStats=s}e&&(r=yield this.getSenderStats(e));for(let[e,o]of t){let e=yield this.getReceiverStats(o);e&&n.push(e)}return t.size&&(i=this.getMediaPlayoutStats(this._spcStats)),{senderStats:r,receiverStats:n,mediaPlayoutStats:i}})}getDifferenceValue(e,t){if(LV(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r,uplinkConnection:n}=e;var o,s,a,c,l,d,u,h,p;if(!LV(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*sL,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*sL),KN(t.senderStats.audio.audioCaptureEnergyAfter3a)||(e.uint32_audio_capture_energy_after3a=t.senderStats.audio.audioCaptureEnergyAfter3a*sL),t.senderStats.audio.totalSamplesDuration&&(i.msg_device_info.uint32_audio_capture_cost=t.senderStats.audio.totalSamplesDuration);let r=[];if(t.senderStats.video.bytesSent){let e={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};r.push(e)}if(t.senderStats.small.bytesSent){let e={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};r.push(e)}if(t.senderStats.auxiliary.bytesSent){let e={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};r.push(e)}let n={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:e,msg_video_status:r,msg_network_status:n}}let{statInterval:m}=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(mD)),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,int32_video_audio_relative_delay:e.avSyncDelay+5e3};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=r.get("".concat(e.userId,"_").concat(_D)),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)}),t.mediaPlayoutStats&&!LV(t.mediaPlayoutStats)&&(t.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,t.mediaPlayoutStats.totalSamplesDuration*=1e3);let _=this._prevReport,f=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&&_.msg_up_stream_info.msg_audio_status){let e=_.msg_up_stream_info.msg_audio_status,r=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)r.uint32_audio_codec_bitrate=0;else{let t=this.getDifferenceValue(e.uint32_audio_codec_bitrate,r.uint32_audio_codec_bitrate);r.uint32_audio_codec_bitrate=Math.round(8*t/m),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=r.uint32_audio_codec_bitrate}null!=(o=_.msg_device_info)&&o.uint32_audio_capture_cost?(i.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(_.msg_device_info.uint32_audio_capture_cost,i.msg_device_info.uint32_audio_capture_cost)/m),i.msg_device_info.uint32_audio_capture_cost>0&&(null==(a=null==n?void 0:n.localMainAudioTrack)||a.updateAfter3aSilenceStartTime(null!=(s=t.senderStats.audio.audioCaptureEnergyAfter3a)?s:t.senderStats.audio.micAudioLevel))):delete i.msg_device_info.uint32_audio_capture_cost}let g=_.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach(e=>{let t=g.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/m),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)/m),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_codec_fps)/m),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),KN(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),KN(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),KN(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),KN(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),KN(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/m)),KN(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/m))});let E=_.msg_down_stream_info;i.msg_down_stream_info=i.msg_down_stream_info.filter(e=>E.find(t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));let T=i.msg_down_stream_info;if(T.forEach(e=>{let t=E.find(t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid);if(LV(e.msg_audio_status)||LV(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/m),i.uint32_audio_total_bitrate=Math.round(8*s/m)}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 c=this.getDifferenceValue(o,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*c/m);let l=this.getDifferenceValue(s,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(l/m),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(a,e.uint32_video_dec_fps)/m);let d=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)/d)||0})}}),!KN(null==(c=null==f?void 0:f.mediaPlayoutStats)?void 0:c.totalSamplesDuration)&&!KN(null==(l=t.mediaPlayoutStats)?void 0:l.totalSamplesDuration)){let e=2*Math.floor(this.getDifferenceValue(null==(d=null==f?void 0:f.mediaPlayoutStats)?void 0:d.synthesizedSamplesDuration,null==(u=t.mediaPlayoutStats)?void 0:u.synthesizedSamplesDuration)/m),r=2*Math.floor(this.getDifferenceValue(null==(h=null==f?void 0:f.mediaPlayoutStats)?void 0:h.totalSamplesDuration,null==(p=t.mediaPlayoutStats)?void 0:p.totalSamplesDuration)/m);i.msg_device_info.uint32_audio_play_cost=r-e}return f&&t.receiverStats.forEach(e=>{if(e.audio.concealedSamples&&e.audio.totalSamplesReceived){let t=f.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*m);if(o>1e3*m/5){let t=T.find(t=>t.msg_user_info.str_identifier===e.userId);t&&(t.msg_audio_status.uint32_audio_block_time=o)}}}}),i.msg_down_stream_info.forEach(e=>{e.msg_video_status.forEach(e=>{0===e.uint32_video_codec_bitrate&&0===e.uint32_video_receive_fps&&(e.uint32_video_width=0,e.uint32_video_height=0)})}),i}getStatsReport(e){return Xb(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,uint32_video_codec_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,uplinkConnection:i}),t._prevReportTime=Date.now(),e}()})}getMediaPlayoutStats(e){let t;if(ZN(e)){for(let i of e)if("media-playout"===i.type){let{synthesizedSamplesDuration:e,totalSamplesDuration:r}=i;t={synthesizedSamplesDuration:e,totalSamplesDuration:r};break}return t}}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map,[this.room.localMainVideoTrack,this.room.capturedLocalMainVideoTrack,this.room.localAuxVideoTrack,this.room.capturedLocalAuxVideoTrack].forEach(e=>{null!=e&&e.stat&&(e.stat.framesCaptured=0)})}},Bz=Jb(Qb());function Hz(e){return new Promise(t=>Xb(null,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(Ak){}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=Wb(Hb({},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 Wz=class e extends Bz.default{constructor(e){let{signalChannel:t,room:i}=e;super(),qb(this,"_room"),qb(this,"_signalChannel"),qb(this,"_log"),qb(this,"uplinkRTT",0),qb(this,"uplinkLoss",0),qb(this,"downlinkRTT",0),qb(this,"downlinkLoss",0),qb(this,"pingResults",{}),qb(this,"_downlinkPrevStatMap",new Map),qb(this,"_downlinkLossAndRTTMap",new Map),qb(this,"_interval",-1),qb(this,"_uplinkNetworkQuality",0),qb(this,"_downlinkNetworkQuality",0),qb(this,"_uplinkQualityHistory",[]),qb(this,"_downlinkQualityHistory",[]),this._room=i,this._signalChannel=t,this._log=dM.createLogger({parent:i.getLogger(),id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(t){t!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(t,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=t,this._uplinkQualityHistory.push(t),this._uplinkQualityHistory.length>e.HISTORY_SIZE&&this._uplinkQualityHistory.shift()}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(t){if(t!==this._downlinkNetworkQuality){let{rtt:e,loss:i}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(t,", rtt: ").concat(e,", loss: ").concat(i," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=t,this._downlinkQualityHistory.push(t),this._downlinkQualityHistory.length>e.HISTORY_SIZE&&this._downlinkQualityHistory.shift()}initialize(){this._signalChannel.on(Gj.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(Mj,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 Xb(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)===AD.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 Xb(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!hx())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&&YN(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===$k.AUDIO||e.mediaType===$k.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)});return 0===t.rtt&&(t.rtt=this.uplinkRTT),t}catch(IM){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!==AD.DISCONNECTED&&e.connectionState!==AD.FAILED&&e.connectionState!==AD.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=sU.run("ric",()=>{var t;this.handleDownlinkNetworkQuality();let i=[...this._downlinkLossAndRTTMap.values()];oM.emit(aM.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=Wb(Hb({},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=>Hz(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=>{UL.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")}hadRecentBadUplink(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2;return this._uplinkQualityHistory.some(t=>t>e)}hadRecentBadDownlink(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2;return this._downlinkQualityHistory.some(t=>t>e)}stop(){this._log.debug("stopped"),-1!==this._interval&&(sU.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})}})}};qb(Wz,"HISTORY_SIZE",10),qb(Wz,"EVENT_NETWORK_QUALITY","0"),qb(Wz,"lastPingTime",0);var Gz=Wz;var jz=class{constructor(e){qb(this,"_frameWorkType"),qb(this,"_component"),qb(this,"_language"),qb(this,"connectionType"),qb(this,"_room"),qb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0}),qb(this,"_keyPrefix"),qb(this,"_log"),qb(this,"_intervalId"),qb(this,"_firstPublishedUserList"),qb(this,"_networkQuality"),qb(this,"_basicInfo"),qb(this,"_pathJoinRoom"),qb(this,"_pathLeaveRoom"),qb(this,"_pathMainVideoMap"),qb(this,"_pathMainAudioMap"),qb(this,"_pathAuxiliaryMap"),qb(this,"_remoteStreamStatMap"),qb(this,"_localStreamStat"),qb(this,"_eventMap",new Map),qb(this,"_captureCostSum",0),qb(this,"_captureCostCount",0),qb(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=dM.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&JN(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 tw(o)?o.catch(e=>dM.error("".concat(t.name,"() error observed ").concat(e))):o}catch(kD){dM.error("".concat(t.name,"() error observed ").concat(kD))}}}({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:yk,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,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,GO().then(()=>{this._basicInfo.string_os_version=tM(),this._basicInfo.string_device_name=YO()||this._basicInfo.string_os_version})}addEvent(e,t){return this._eventMap.set(e,t),oM.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(aM.JOIN_START,this.handleJoinStart).addEvent(aM.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(aM.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(aM.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(aM.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(aM.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(aM.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(aM.JOIN_FAILED,this.handleJoinFailed).addEvent(aM.LEAVE_START,this.handleLeaveStart).addEvent(aM.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(aM.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(aM.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(aM.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(aM.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(aM.PUBLISH_START,this.handlePublishStart).addEvent(aM.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(aM.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(aM.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(aM.PLAY_TRACK_START,this.handlePlayStart).addEvent(aM.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(aM.PLAYER_STATE_CHANGED,e=>{let{track:t,state:i,type:r}=e;!t.isRemote||!this.hitTest(t.room)||"PLAYING"===i&&(r===$k.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(aM.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(aM.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(aM.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(aM.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(aM.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(aM.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(aM.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(aM.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)=>oM.off(t,e)),this._eventMap.clear()}destroy(){this.uninstallEvents(),sU.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&&(KN(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),KN(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),KN(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 dk?Number(i.getExtraCode()||i.getCode()):ck.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){var t;if(this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time){if(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;let e=null==(t=this._room.audioManager.localAudioTrack)?void 0:t.after3aSilenceStartTime;e&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=aw()-e)}else 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 dk?Number(i.getExtraCode()||i.getCode()):ck.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:Wb(Hb({},Jz),{msg_user_info:new Kz({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 Kz({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,UL.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){var t;if(this.hitTest(e.room)){let{msg_device_info:i,msg_up_stream_info:r,msg_down_stream_info:n}=e.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:t,uint32_video_width:i,uint32_video_height:n}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=t,this._localStreamStat.totalVideoWidth+=i,this._localStreamStat.totalVideoHeight+=n,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:e}=r.msg_audio_status;Math.floor(e/sL*100)>0&&(this._localStreamStat.totalAudioLevel+=e/sL,this._localStreamStat.audioLevelCount++)}n.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*Fb(10,6)))}}),!uw(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/sL*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/sL,t.audioLevelCount++),i.uint32_audio_block_time&&(t.statsToReport.uint32_audio_block_time+=i.uint32_audio_block_time))}}),i.uint32_audio_capture_cost&&(this._captureCostSum+=i.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)),0===i.uint32_audio_capture_cost&&!1===(null==(t=this._room.audioManager.localAudioTrack)?void 0:t.muted)&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}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 dk?i.getExtraCode()||i.getCode():ck.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&rD)>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&sD)>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&oD)>=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,$k.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,$k.VIDEO)),e.statsToReport.uint32_video_render_first&&(e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,zz));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),e.statsToReport.uint32_audio_block_time=Math.min(e.statsToReport.uint32_audio_block_time,e.statsToReport.uint32_audio_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>zz&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+zz):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>zz&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+zz):this._pathMainVideoMap.delete(t)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>zz&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+zz)}getReportData(){this._basicInfo.uint32_networkType=MN();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Kz({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:mw(this._signalInfo.relayIp),uint32_client_ip:mw(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Fb(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:mw(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return Cw(e),e}report(){return Xb(this,null,function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(EM){this._log.warn(EM)}finally{this.isDestroyed&&(this._room=null)}})}upload(e){return Xb(this,null,function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=cM.enable?xw(e,2001,t):yield zw(e),r=i instanceof ArrayBuffer,n="".concat(bN(t,Hk.KEY_POINT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i));let s=[this.uploadKVStat(UL),this.uploadKVStat(xL)];o||s.push(jw({url:n,body:i,priority:"low"})),yield Promise.all(s)})}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return Xb(this,arguments,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this._room.sdkAppId;return function*(){var r,n;let o=e.getReportData(null==(r=t._room)?void 0:r.userSig,null==(n=t._signalInfo)?void 0:n.reportToken);if(0===o.stats_count.length&&0===o.stats_distribution.length)return;o.msg_sdk_basic_info=Wb(Hb({},o.msg_sdk_basic_info),{bytes_device_name:t._basicInfo.string_device_name||"",bytes_os_version:t._basicInfo.string_os_version||"",uint32_framework:t._frameWorkType,uint32_network_type:t._basicInfo.uint32_networkType||0}),t._log.debug(o);let s=cM.enable?xw(o,2003,i):yield zw(o),a=s instanceof ArrayBuffer,c="".concat(bN(+i,Hk.KV_STAT),"&gzip=").concat(+a),l=!1;navigator.sendBeacon&&(l=navigator.sendBeacon(c,s)),l||jw({url:c,body:s})}()})}};Kb([mU({settings:{timeout:500,retries:3}})],jz.prototype,"upload",1);var zz=5e3,Jz={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},Kz=class{constructor(e){qb(this,"str_identifier"),qb(this,"str_tinyid"),qb(this,"uint32_role"),this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},qz=jz,Yz=class{constructor(){qb(this,"_startTime"),qb(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}},Xz=class{constructor(e){qb(this,"_room",null),qb(this,"_durationMap"),qb(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(aM.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(aM.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(aM.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"),$k.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_main"),$k.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_auxiliary"),$k.VIDEO);let s=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);s&&(!i.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,$k.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,$k.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,$k.VIDEO,"auxiliary"))}),this._eventMap.forEach((e,t)=>oM.on(t,e,this))}uninstallEvents(){this._eventMap.forEach((e,t)=>oM.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 Yz,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===$k.AUDIO?[n]:[],video:t===$k.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()}},Qz=class{constructor(){qb(this,"renderFreezeMap",new Map),qb(this,"dataFreezeMap",new Map)}get(e,t){let i=this.renderFreezeMap.get(e),r=this.dataFreezeMap.get(e);return t?"data"===t?r:i:(AO||EP)&&i&&r&&i.duration>r.duration?i:r}set(e,t,i){"data"===i?this.dataFreezeMap.set(e,t):this.renderFreezeMap.set(e,t)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},Zz=class{constructor(e){qb(this,"_room"),qb(this,"_renderFreezeMap",new Map),qb(this,"_isVideoPlayingEventFiredMap",new Map),qb(this,"_dataFreezeMap",new Map),qb(this,"_monitorFreezeData",new Qz),qb(this,"_eventMap",new Map),qb(this,"_videoEncodeFailedCount",0),qb(this,"_audioEncodeFailedCount",0),qb(this,"_encodeFailedThreshold",3),qb(this,"ABNORMAL_TIME_LOWER_LIMIT",3e3),qb(this,"ABNORMAL_TIME_UPPER_LIMIT",5e3),qb(this,"_videoAbnormalTimestampMap",new Map),qb(this,"_remoteVideoAbnormalTimestampMap",new Map),qb(this,"_audioAbnormalTimestampMap",new Map),qb(this,"eventListenerMap",new Map),this._room=e.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(aM.LEAVE_SUCCESS,e=>{let{room:t}=e;this.hitTest(t)&&this.stop()}).set(aM.PLAY_TRACK_START,this.onPlayTrackStart).set(aM.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(aM.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(aM.PLAYER_STATE_CHANGED,e=>{let{track:t,state:i,reason:r,type:n}=e;if(t.isRemote&&t.room&&this.hitTest(t.room)&&n===$k.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===$k.MUTE?this.onVideoTrackMuted(t):r===$k.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(aM.HEARTBEAT_REPORT,this.onHearBeatReport).set(aM.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(aM.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((e,t)=>oM.on(t,e,this))}uninstallEvents(){this._eventMap.forEach((e,t)=>oM.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 Yz;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)&&(this.localMediaTrackDetector(i),this.remoteMediaTrackDetector(i))}remoteMediaTrackDetector(e){e.msg_down_stream_info.length>0&&e.msg_down_stream_info.forEach(e=>{var t;if(0===e.msg_video_status.length)return;let i=e.msg_user_info.str_identifier,r=null==(t=this._room.remotePublishedUserMap.get(i))?void 0:t.remoteVideoTrack;e.msg_video_status.forEach(e=>{let t=aw();if(void 0!==e.uint32_video_codec_bitrate&&e.uint32_video_codec_bitrate>0&&0===e.uint32_video_receive_fps&&null!=r&&r.muted)if(this._remoteVideoAbnormalTimestampMap.has("".concat(i,"-decode"))){let e=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-decode"));e&&t-e>this.ABNORMAL_TIME_LOWER_LIMIT&&t-e<this.ABNORMAL_TIME_UPPER_LIMIT&&hU.uploadEvent({userId:this._room.userId,log:"stat-".concat(ND.VIDEO_DECODE_FAILED_DURING_CALL)})}else this._remoteVideoAbnormalTimestampMap.set("".concat(i,"-decode"),t);else{let e=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-decode"));e&&t-e>=this.ABNORMAL_TIME_UPPER_LIMIT&&(hU.uploadEvent({userId:this._room.userId,log:"stat-".concat(ND.VIDEO_DECODE_RESUME_DURING_CALL)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(i,"-decode")))}if(void 0!==e.uint32_video_codec_bitrate&&e.uint32_video_codec_bitrate>5e5&&void 0!==e.uint32_video_dec_fps&&e.uint32_video_dec_fps<=5)if(this._remoteVideoAbnormalTimestampMap.has("".concat(i,"-hardware"))){let r=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-hardware"));if(r&&t-r>this.ABNORMAL_TIME_LOWER_LIMIT/2&&t-r<2*this.ABNORMAL_TIME_UPPER_LIMIT){hU.uploadEvent({userId:this._room.userId,log:"stat-".concat(ND.VIDEO_HARDWARE_DECODE_FAILED)});let t=this._room.remotePublishedUserMap.get(i);if(t){let i=2===e.uint32_video_stream_type?t.remoteVideoTrack:t.remoteAuxiliaryTrack;i&&(i.log.warn("decode failed during call"),i.emit("decode-failed-during-call"))}}}else this._remoteVideoAbnormalTimestampMap.set("".concat(i,"-hardware"),t);else{let e=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-hardware"));e&&t-e>=2*this.ABNORMAL_TIME_UPPER_LIMIT&&(hU.uploadEvent({userId:this._room.userId,log:"stat-".concat(ND.VIDEO_HARDWARE_DECODE_RESUME)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(i,"-hardware")))}})})}localMediaTrackDetector(e){if(e.msg_up_stream_info.msg_video_status){let t=e.msg_up_stream_info.msg_video_status,i=Array.from(this._room.localTracks).find(e=>"video"===e.kind&&!e.isScreen),r=(null==i?void 0:i.stat.bytesSent)||0;if(!1===(null==i?void 0:i.isMediaTrackActive)||r<=0||null!=i&&i.isUseCustomSource)return;t.forEach(e=>{let t=aw();if(2===e.uint32_video_stream_type)if(0!==e.uint32_video_capture_fps&&0===e.uint32_video_codec_bitrate&&0===e.uint32_video_enc_fps&&null!=i&&i.isPublished)if(this._videoAbnormalTimestampMap.has("local-encode")){let e=this._videoAbnormalTimestampMap.get("local-encode");e&&t-e>this.ABNORMAL_TIME_LOWER_LIMIT&&t-e<this.ABNORMAL_TIME_UPPER_LIMIT&&hU.uploadEvent({userId:this._room.userId,log:"stat-".concat(ND.VIDEO_ENCODE_FAILED_DURING_CALL)})}else this._videoAbnormalTimestampMap.set("local-encode",t);else{let e=this._videoAbnormalTimestampMap.get("local-encode");e&&t-e>=this.ABNORMAL_TIME_UPPER_LIMIT&&hU.uploadEvent({userId:this._room.userId,log:"stat-".concat(ND.VIDEO_ENCODE_RESUME_DURING_CALL)}),this._videoAbnormalTimestampMap.delete("local-encode")}})}if(e.msg_up_stream_info.msg_audio_status){let t=e.msg_up_stream_info.msg_audio_status,i=Array.from(this._room.localTracks).find(e=>"audio"===e.kind),r=(null==i?void 0:i.stat.bytesSent)||0;if(!1===(null==i?void 0:i.isMediaTrackActive)||r<=0||null!=i&&i.isUseCustomSource)return;let n=aw();if(0===t.uint32_audio_codec_bitrate&&null!=i&&i.isPublished)if(this._audioAbnormalTimestampMap.has("local-encode")){let e=this._audioAbnormalTimestampMap.get("local-encode");e&&n-e>this.ABNORMAL_TIME_LOWER_LIMIT&&n-e<this.ABNORMAL_TIME_UPPER_LIMIT&&hU.uploadEvent({userId:this._room.userId,log:"stat-".concat(ND.AUDIO_ENCODE_FAILED_DURING_CALL)})}else this._audioAbnormalTimestampMap.set("local-encode",n);else{let e=this._audioAbnormalTimestampMap.get("local-encode");e&&n-e>=this.ABNORMAL_TIME_UPPER_LIMIT&&hU.uploadEvent({userId:this._room.userId,log:"stat-".concat(ND.AUDIO_ENCODE_RESUME_DURING_CALL)}),this._audioAbnormalTimestampMap.delete("local-encode")}}}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();if(s>VD){let e=this._monitorFreezeData.get(t,"data");this._monitorFreezeData.set(t,{userId:i,type:r,duration:e?e.duration+s:s},"data")}else n.durationItemList.pop()}getTotalDuration(e){return e.reduce((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)},0)}onPlayTrackStart(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room)||t.kind!==$k.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()<VD&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){let t={renderFreeze:0,count:0},i=this._renderFreezeMap.get(e);return i&&(t.renderFreeze=i.totalDuration,t.count=i.count),t}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}onRemoteVideoPlayStart(e){let{track:t,player:i}=e;var r;if(!Ux())return;let n=0,o=()=>{document.hidden||(n=0)};document.addEventListener("visibilitychange",o);let s=(e,r)=>{var o;if(n){let e=t.decodeFPS,i=e>0&&e<=5?600+1e3/e:600,o=r.presentationTime-n;if(o>i){o=Math.min(o,5e3);let e="".concat(t.userId,"_").concat(t.streamType),i=this._monitorFreezeData.get(e,"render");i?i.duration+=o:this._monitorFreezeData.set(e,{userId:t.userId,type:t.streamType,duration:o},"render");let r=this._renderFreezeMap.get(e);r?(r.totalDuration+=o,r.count+=1):this._renderFreezeMap.set(e,{userId:t.userId,type:t.streamType,totalDuration:o,count:1})}}n=r.presentationTime,null==(o=i.element)||o.requestVideoFrameCallback(s)};null==(r=i.element)||r.requestVideoFrameCallback(s),this.eventListenerMap.set("".concat(t.userId,"_").concat(t.streamType),{onVisibilityChange:o})}onRemoteVideoPlayEnd(e){let{track:t,player:i}=e,r="".concat(t.userId,"_").concat(t.streamType),n=this.eventListenerMap.get(r);n&&document.removeEventListener("visibilitychange",n.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},$z=Jb(Qb(),1),eJ=class{constructor(e,t,i,r,n){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:4/3;this.vbMode=e,this.faceDetectorHash=i,this.visionTaskRegistry=r,this.logger=n,qb(this,"animationState"),qb(this,"originalAspect"),qb(this,"totalOffsetX",0),qb(this,"totalOffsetY",0),qb(this,"defaultScaleRatio",.1),qb(this,"isRecovering",!1),qb(this,"boundaryY",280),qb(this,"lastActionTime",0),qb(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=o||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,t)}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?UL.addSuccessEvent({key:r.key}):UL.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(IM){this.logger.error(IM)}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=Hb({},e),void(this.animationState.target=Hb({},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)),YN(this.animationState.current.scaleOffsetX)&&YN(this.animationState.target.scaleOffsetX)&&YN(this.animationState.current.scaleOffsetY)&&YN(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(Fb(e.sx-t.sx,2)+Fb(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}},tJ=class extends WH{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}),qb(this,"_bgTexture"),qb(this,"_waterMarkTexture"),qb(this,"_lastMaskTexture"),qb(this,"_lastMaskFbo"),qb(this,"_textureValid",!1),qb(this,"_selfieTextureValid",!1),qb(this,"_selfieSegmentationHash"),qb(this,"wasm"),qb(this,"predictReady"),qb(this,"_color"),qb(this,"_prePrograme"),qb(this,"_segmentationMask"),qb(this,"_weixin",!1),qb(this,"_centerFace"),qb(this,"_textureMatrixLocation"),qb(this,"_offsetMatrixLocation"),qb(this,"_colorLocation"),qb(this,"_enableFaceCentering",!1),qb(this,"_enableEffectOptimization",!1),qb(this,"_mat4"),qb(this,"_postProcessing"),qb(this,"_onAbort"),qb(this,"_visionTaskRegistry"),qb(this,"resolvePreditReady"),this.init(t).catch(t=>{e.log.error(t),e.destroy(new dk({code:ck.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(t.message||t)})),this.resolvePreditReady()})}init(e){return Xb(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?this._postProcessing=void 0:HO()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):null==(r=this._postProcessing)||r.init(o,this.positionBuffer,this.texCoordBuffer,4/3),yield this.initVisionTasks(e)})}initVisionTasks(e){return Xb(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._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),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 eJ(this.wasm.vbMode,this.image,e,this._visionTaskRegistry,this.context.log)}catch(kD){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._postProcessing&&(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(),Pw(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(Pw(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(SM){this._onAbort&&this._onAbort(SM)}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()}},iJ=class extends OH{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 }"}),qb(this,"yTextureRef"),qb(this,"uTextureRef"),qb(this,"vTextureRef"),qb(this,"Y"),qb(this,"U"),qb(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)}},rJ=(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 nJ=0,oJ=class{constructor(e){qb(this,"id",nJ++),qb(this,"trackDoneOB"),qb(this,"startOB"),qb(this,"stopOB"),qb(this,"decoder"),qb(this,"videoContext"),qb(this,"gop",0),qb(this,"gop_helper",0),qb(this,"waitFirstKeyFrame",!0),qb(this,"startTimestamp",0),qb(this,"startTime",0),qb(this,"startPerformanceTime",0),qb(this,"inputFrameCount",0),qb(this,"decodedFrameCount",0),qb(this,"decodeFrameCount",0),qb(this,"downgradeLevel",0),qb(this,"lastDowngradeTime",0),qb(this,"lastFrameDiff",0),qb(this,"lastDecodeFrameTimestamp",0),qb(this,"config"),qb(this,"gop_before_configure",[]),qb(this,"videoElement"),qb(this,"type","wasm"),qb(this,"goodType"),qb(this,"renderer","2d"),qb(this,"wasmOption"),qb(this,"createDecoder"),qb(this,"_decodeSink"),qb(this,"isReported",!1),qb(this,"track"),qb(this,"stateChangeOB"),qb(this,"failedReason");let{track:t,createDecoder:i}=e;if(this.stateChangeOB=PF(),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=zF(t.availableState,eU.OFF),this.stopOB=PF(),"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),uF(this.stateChangeOB,LB((e,i)=>(e!==i&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:e,state:i}),i),"INITIALIZED"),pB(this.stopOB),mH()),this.start()}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=uF(this.pipe(this.track),pB(this.stopOB),TF());uF(t,mH(()=>{this.track.stat.framesDecoded++},t=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(t," retryCount: ").concat(e)),UL.addFailedEvent({key:rJ(this.type,this.renderer),error:t}),e>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),UL.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")),UL.addSuccessEvent({key:rJ(this.type,this.renderer)}),UL.addSuccessEvent({key:514704})})),uF(t,hB(1),mH(()=>{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&&!JL()&&(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=>Xb(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":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 JH({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(JH.UNAVAILABLE,i=>{e.log.error(i),t.error(7)});let r=new iJ(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 KH({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 xH(this.videoContext,{name:"remotePlayer",logger:e.log});r.connect(n),e.source=r,e.player.setCanvas(this.videoContext._canvas,2)}this.decoder=i}catch(vM){e.log.error(vM),t.error("webCodecs"===o?2:6)}})}},sJ=Promise.resolve(),aJ=class extends $z.EventEmitter{constructor(e){super(),this.room=e,qb(this,"videoContext"),qb(this,"_glVideoContext"),qb(this,"_2dVideoContext"),qb(this,"destination"),qb(this,"smallVideoContext"),qb(this,"smallDestination"),qb(this,"smallTrackSource"),qb(this,"smallImageSource"),qb(this,"_isMirror",!1),qb(this,"_rotation",0),qb(this,"cameraTrack"),qb(this,"cameraNode"),qb(this,"transformNode"),qb(this,"mixNode"),qb(this,"screenTrack"),qb(this,"screenNode"),qb(this,"selfModel",!1),qb(this,"blurRadius",3),qb(this,"arTrack"),qb(this,"_enableFaceCentering",!1),qb(this,"_enableEffectOptimization",!1),qb(this,"onAbort"),qb(this,"_color"),qb(this,"Wasm"),qb(this,"waterMarkNode"),qb(this,"_waterMarkOption"),qb(this,"watermarkImageList",[]),qb(this,"_beautyParams"),qb(this,"isUsingArTrack",!1),qb(this,"mixTrack"),qb(this,"_isMixScreen",!1),qb(this,"_virtualBackground"),qb(this,"_virtualBackgroundAbortCallback"),qb(this,"virtualBackgroundInstance"),qb(this,"_bgAssetPath"),qb(this,"log"),qb(this,"_mat4"),qb(this,"_postProcessing"),qb(this,"_checkId",0),qb(this,"_use2d",!1),qb(this,"_autoSwitchRenderMode",!0),qb(this,"encodePipeline",[]),qb(this,"decodePipeline",[]),qb(this,"updated",sJ),qb(this,"_updateFlag",!1),this.log=dM.createLogger({parent:null==e?void 0:e.getLogger(),id:"vm",userId:null==e?void 0:e.userId,sdkAppId:null==e?void 0:e.sdkAppId}),this.smallVideoContext=new KH({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 Pw(this._rotation)?{width:i,height:t}:{width:t,height:i}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new KH({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 JH({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(IO<=22),this._glVideoContext.on(JH.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(Ik){this.emit("error",Ik)}}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=sU.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(),sU.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(RO||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?UL.addFailedEvent({key:t,error:e}):UL.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 JH({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 FH(this.smallVideoContext,e,this.log),this.smallVideoContext.on(JH.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;RO&&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(TM){this.log.error("set main output failed",TM)}}update(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Xb(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(OH.RENDER,e=>{var t;null==(t=this.cameraTrack)||t.emit("render",e)})),16===wO?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof WH?(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 WH?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 VH(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(OH.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 tJ(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 ZH(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 XH(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 iW)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof kH)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof hW){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 $H)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 iW?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof kH?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 hW?e.source&&e.source.context.destroy():e instanceof $H&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return Xb(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 Xb(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 dk({code:ck.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(i=>{let{image:n,x:o,y:s,width:a,height:c,fillVideo:l}=i,d=l&&e||a,u=l&&t||c,h=l?0:o,p=l?0:s;r.drawImage(n,h,p,d,u)}),Aw(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&&t.fillVideo===e.fillVideo)||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter(e=>e.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return Xb(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return Xb(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return Xb(this,null,function*(){let t;try{t=yield Aw((null==e?void 0:e.imageElement)||e.imageUrl)}catch(_M){throw new dk({code:ck.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,fillVideo:c=!1}=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,fillVideo:c}),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,fillVideo:c}),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 Xb(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 Xb(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 Xb(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 Aw(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 dk({code:ck.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 Xb(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 oJ(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}};Kb([GV(function(e){this.log.error("update failed",e)}),jV(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Xb(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield sJ,this.updated=new Promise((t,r)=>{e.apply(this,i).then(t,r),setTimeout(r,5e3,new dk({code:ck.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],aJ.prototype,"update",1);var cJ=0,lJ=class extends eU{constructor(e){super("room"),qb(this,"seq",++cJ),qb(this,"sdkAppId"),qb(this,"userId"),qb(this,"userSig"),qb(this,"privateMapKey"),qb(this,"latencyLevel"),qb(this,"tinyId"),qb(this,"scene"),qb(this,"roomId"),qb(this,"useStringRoomId"),qb(this,"role","anchor"),qb(this,"joinParams",null),qb(this,"localPublishFlag",0),qb(this,"localTracks",new Set),qb(this,"enableAutoPlayDialog",!0),qb(this,"autoReceiveAudio",!0),qb(this,"autoReceiveVideo",!0),qb(this,"proxy_ws"),qb(this,"proxy_wt"),qb(this,"proxy_unified"),qb(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}}),qb(this,"keyPointManager"),qb(this,"audioManager"),qb(this,"videoManager"),qb(this,"callDurationCalculator"),qb(this,"badCaseDetector"),qb(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),qb(this,"videoDecodeFallbackType"),qb(this,"smallMode","canvas"),qb(this,"enableChorus",!1),qb(this,"_isUsingCachedSchedule",!1),qb(this,"_log"),qb(this,"_joinedTimestamp",0),qb(this,"_sdkType"),qb(this,"heartbeatReport"),qb(this,"heartbeatCount",0),qb(this,"quality"),qb(this,"enableSEI"),qb(this,"isDestroyed",!1),this._log=dM.createLogger({parent:e.logger,id:"r".concat(this.seq)}),this.useStringRoomId=!!e.useStringRoomId,XN(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),XN(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),XN(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new qz({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Xz({room:this}),this.badCaseDetector=new Zz({room:this}),this.audioManager=new sW(this),this.videoManager=new aJ(this)}get videoCodec(){return"h264"}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 localMainAudioTrack(){for(let e of this.localTracks)if(1&e.mediaType)return e;return null}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}get publishState(){let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach(t=>{if(t.isPublished||t.isPublishing)switch(t.mediaType){case 1:e.audio=!0;break;case 4:e.bigVideo=!0,e.smallVideo=t.hasSmall;break;case 2:e.auxVideo=!0}}),e}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)}}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 Xb(this,null,function*(){return this.publish(e)})}removeTrack(e){return Xb(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return Xb(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(qN(e))/^wss?:\/\//i.test(e)?this.proxy_ws=e:/^https?:\/\//i.test(e)&&(this.proxy_wt=e);else if(WN(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?(_G([o,o]),Dk("https://".concat(o))):(r&&Dk(r),n&&_G(n))}oM.once(aM.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:mG.main,sched_back_domain:mG.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return Xb(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return Xb(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 Xb(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 dk({code:ck.INVALID_OPERATION,message:RL({key:yL.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(SL.INVALID_DESTROY),new dk({code:ck.INVALID_OPERATION,message:RL({key:yL.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,oM.emit(aM.ROOM_DESTROY,{room:this})}schedule(e,t){return Xb(this,null,function*(){var i,r,n,o;let s=aw();try{let{isCached:a,result:c,detailCost:l}=yield pG({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:yk,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&&oM.once(aM.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=Hb(Hb({},this.scheduleResult),c),YN(null==(i=c.config)?void 0:i.retryCount)&&CD(c.config.retryCount),qN(null==(r=c.config)?void 0:r.loggerDomain)&&Dk(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,oM.emit(aM.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:l}),UL.addSuccessEvent({key:521700,cost:aw()-s})}catch(fM){throw UL.addFailedEvent({key:521700,error:fM}),fM}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}},dJ=Jb(Qb()),uJ=Jb(ok());function hJ(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 pJ=(e,t,i)=>Xb(null,null,function*(){var r;let n=wz(e),o={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:i};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})));for(let e of s.rtp){if("opus"!==e.codec)continue;let t=s.fmtp.find(t=>t.payload===e.payload);if(!t)continue;let i={codec:e.codec,fmtp:t.config,payload:t.payload,rate:e.rate,channels:e.encoding,rtcpfb:[],rtx:0};null==(r=s.rtcpFb)||r.forEach(e=>{let{payload:t,type:r,subtype:n}=e;if(t===i.payload){let e={id:r,params:[]};n&&e.params.push(n),i.rtcpfb.push(e)}}),o.audio.codecs.push(i);break}let c=["h264","vp8","h265"];return t&&c.shift(),o.video.codecs=[...hJ(a)].filter(e=>c.includes(e.codec.toLocaleLowerCase())),o.video.decoders=(yield function(){return Xb(this,null,function*(){let e=new RTCPeerConnection;e.addTransceiver($k.VIDEO,{direction:$k.TRANSCEIVER_DIRECTION_RECVONLY});let t=yield e.createOffer();if(!t.sdp)return[];let i=hJ(wz(t.sdp).media[0]);return e.close(),i})}()).filter(e=>["h264","vp8","h265"].includes(e.codec.toLocaleLowerCase())),o}),mJ=(e,t)=>{let i=(e||"").trim(),r=(t||"").trim(),n="profile-level-id",o="".concat(n,"=[0-9a-fA-F]{6}");if(new RegExp(o).test(i)){let e=new RegExp(o,"g");return i.replace(e,"".concat(n,"=").concat(r))}if(!i)return"".concat(n,"=").concat(r);let s=i.endsWith(";")?"":";";return"".concat(i).concat(s).concat(n,"=").concat(r)},_J=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n,profileLevelIdConfig:o}=e,s=wz(r),a={extmapAllowMixed:"extmap-allow-mixed",groups:s.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},c={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:$k.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map(e=>({value:e.id,uri:e.uri})),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:s.media[0].port,protocol:s.media[0].protocol,type:$k.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}]};a.media.push(c);let l=[null==o?void 0:o.big,null==o?void 0:o.small,null==o?void 0:o.aux];return[1,2,3].forEach((e,r)=>{a.media.push(fJ({mid:e,serverAbility:t,clientAbility:i,parsedOffer:s,profileLevelId:l[r]}))}),n&&a.media.push(s.media.find(e=>"dc"===e.mid)),Pz(a)},fJ=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,isDownlink:o=!1,profileLevelId:s}=e,a={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:$k.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:$k.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=>{gJ(a,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];gJ(a,t)}if(!o&&s){let e=a.fmtp,t=a.rtp.find(e=>{var t;return"h264"===(null==(t=e.codec)?void 0:t.toLowerCase())});if(t){let i=e.find(e=>String(e.payload)===String(t.payload));i&&(i.config=mJ(i.config,s))}}return a},gJ=(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 EJ=(e,t,i)=>{let r=uJ.default.parse(e);return r.media.forEach((e,n)=>{var o;if((e.type===$k.AUDIO||e.type===$k.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===$k.VIDEO&&e.fmtp&&e.fmtp.forEach(e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")})}(e),function(e){e.type===$k.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===$k.VIDEO))if(n<4)e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach(t=>gJ(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=>gJ(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")}),uJ.default.write(r)};function TJ(e){var t,i;let r=/profile-level-id=([0-9a-fA-F]{6})/.exec(e);return null!=(i=null==(t=null==r?void 0:r[1])?void 0:t.toLowerCase())?i:null}function vJ(e){let t=e.toLowerCase();if(!/^[0-9a-f]{6}$/.test(t))return"unknown";let i=parseInt(t.slice(0,2),16);return 66===i?"baseline":77===i?"main":100===i?"high":"unknown"}function yJ(e,t){if(!t)return"";let i=e.trim().toLowerCase().replace(/_/g,"-");if(!i)return"";if(/^[0-9a-f]{6}$/.test(i))return i;if("baseline"!==i&&"main"!==i&&"high"!==i)return"";for(let r of t.video.codecs){let e=TJ(r.fmtp);if(e&&vJ(e)===i)return e}return""}var SJ=Jb(Qb()),IJ=class extends SJ.EventEmitter{constructor(e){super(),this.room=e,qb(this,"mainFpsHealth",1),qb(this,"mainBitrateHealth",1),qb(this,"badMainBitrateHealthCount",0),qb(this,"lastEmitBadHealthTime",0),qb(this,"log"),!mP&&gO&&oM.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(){oM.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};qb(IJ,"EVENT_BAD_HEALTH","bad_health");var AJ=IJ,RJ=(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))(RJ||{}),CJ=1,bJ=class extends dJ.default{constructor(e){let{signalChannel:t,room:i,enableDataChannel:r}=e;super(),qb(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),qb(this,"isDestroyed",!1),qb(this,"currentState","DISCONNECTED"),qb(this,"_room"),qb(this,"_signalChannel"),qb(this,"_peerConnection",null),qb(this,"_datachannel",null),qb(this,"_enableDataChannel"),qb(this,"_log"),qb(this,"_downlinkMIDMap",new Map),qb(this,"_downlinkMIDUserIDMap",new Map),qb(this,"_reconnectionTimer",-1),qb(this,"reconnectionCount",0),qb(this,"clientAbility"),qb(this,"_serverAbility",null),qb(this,"addDownlinkQueue",new Set),qb(this,"removeDownlinkQueue",new Set),qb(this,"_parsedAnswer",null),qb(this,"_updateSDPPromise",null),qb(this,"_waitForPCConnectedPromise"),qb(this,"clearWaitForConnectedPromise"),qb(this,"clearConnectTimeout"),qb(this,"_isSDPLogged",!1),qb(this,"enableInsertableStreams",!1),qb(this,"insertableStreamsAbortMap",new Map),qb(this,"receiverRemoteTrackMap",new WeakMap),qb(this,"scriptTransformWorker"),qb(this,"_isRelayTried",!1),qb(this,"_rttOverCount",0),qb(this,"originOffer",null),qb(this,"autoSubscribedSsrcGroups",new Map),qb(this,"autoSubscribedUserMap",new Map),qb(this,"_h265DecodeFailed",!1),this._room=i,this._enableDataChannel=r,this._signalChannel=t,this._log=dM.createLogger({parent:this._room.getLogger(),id:"spc".concat(CJ++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(Rx?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("destroy"),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"))}isProfileLevelIdSupported(e){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find(t=>t.fmtp.includes(e))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=wz(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&&!KN(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){}initScriptTransformWorker(){Cx&&(this.scriptTransformWorker=PG({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):e.data.type,"dump"===e.data.type&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e.message)})}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 Xw(r)&&(i.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(i)),i}initialize(e){return Xb(this,null,function*(){var t;let i;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let e=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(e)),"checking"===e&&0===this.stat.iceStartTime?this.stat.iceStartTime=Date.now():"connected"===e&&0===this.stat.iceEndTime?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),UL.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):"failed"===e&&UL.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._enableDataChannel&&(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 DJ(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver($k.AUDIO,{direction:$k.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver($k.VIDEO,{direction:$k.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver($k.VIDEO,{direction:$k.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver($k.VIDEO,{direction:$k.TRANSCEIVER_DIRECTION_SENDONLY}),i=yield this._peerConnection.createOffer(),this.clientAbility=yield pJ(i.sdp,(null==(t=this._room.scheduleResult.config)?void 0:t.remove264FromSDP)||!1,this._enableDataChannel),this.originOffer=i,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;e&&(this._log.debug("dtls state: ".concat(e.state)),"connecting"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():"connected"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()))}),UL.addSuccessEvent({key:521707}),this.clientAbility}catch(IM){throw UL.addFailedEvent({key:521707,error:IM}),this._log.error("initialize failed ".concat(IM," \noffer: ").concat(null==i?void 0:i.sdp)),IM}})}setIceServers(e){return Xb(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(TM){this._log.warn("setIceServers error ",TM)}})}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(kD){this._log.warn("setPriority error ",kD)}}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Xb(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=this.getProfileLevelIdConfig(),a={type:"answer",sdp:_J({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableDataChannel,profileLevelIdConfig:s})};this._serverAbility=e,yield this.setAnswer(a),yield this.waitForPeerConnectionConnected(),this._room.firewallDetector.resetTimeoutCount();let c=(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");c&&this.setPriority(c),t||UL.addSuccessEvent({key:521703,cost:aw()-o})}catch(vM){let i=vM instanceof dk&&vM.code===ck.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(vM),e),this.reset(),!i&&!this.isReconnecting&&!this.isDestroyed&&(UL.addFailedEvent({key:521703,error:vM}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),vM}})}reconnect(){return Xb(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(Lj,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=Hb({ability:t},e),r=yield this._signalChannel.sendWaitForResponse({command:pz,responseCommand:Gj.REBUILD_PEER_CONNECTION_RES,data:i,enableLog:!1});if(0!==r.data.code)throw new dk({code:r.data.code,message:r.data.message});yield this.connect(r.data.data.ability,!0),UL.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),oM.emit(aM.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(Ik){if(!this.isReconnecting||this.isDestroyed)return;if(null!=Ik&&Ik.message.includes("timeout")){let e=jN(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield bw(e,e=>{this._reconnectionTimer=e}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(null==Ik?void 0:Ik.code," ").concat(Ik)),UL.addFailedEvent({key:521704,error:Ik}),this.reconnectionCount>=bD()&&this._log.warn("SDK has tried reconnect for ".concat(bD()," 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 Xb(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(Lj,this.reconnect,this),"RECONNECTING"===this.currentState&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===AD.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===AD.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===AD.FAILED||e.target.connectionState===AD.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===AD.CONNECTED||e.target.connectionState===AD.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),oM.emit(aM.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 ID;let e=null;return px()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,hx()&&0!==this._peerConnection.getReceivers().length&&e?e.state:ID):ID}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(RJ.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return Xb(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(rx(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(t.relayProtocol?"relayProtocol:".concat(t.relayProtocol," url: ").concat(t.url):"")),t.networkType&&ON(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 dk({code:ck.API_CALL_ABORTED,message:RL({key:yL.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{oM.off(aM.LEAVE_SUCCESS,r,this),this.off(RJ.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout(()=>{n();let e=new dk({code:ck.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),t(e)},WD);this.clearConnectTimeout=()=>{n(),clearTimeout(o),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new dk({code:ck.API_CALL_TIMEOUT,message:"connection timeout"}))},oM.on(aM.LEAVE_SUCCESS,r,this),this.on(RJ.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 Xb(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(kD){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(kD)),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=$k.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid)));this._parsedAnswer||(this._parsedAnswer=wz(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($k.AUDIO,{direction:$k.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver($k.VIDEO,{direction:$k.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver($k.VIDEO,{direction:$k.TRANSCEIVER_DIRECTION_RECVONLY}),o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=fJ({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:wz(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=$k.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($k.MAIN," ").concat(l,"-audio")}],s.direction=$k.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat($k.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat($k.MAIN," ").concat(l,"-bigvideo")}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=$k.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($k.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat($k.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat($k.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 Xb(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=wz(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 Xb(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(vx()){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(vM){this._log.error("failed to set bandwidth: ".concat(vM))}})}setStartBitrate(e,t){var i,r;return!(null==(i=this._peerConnection)||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=wz(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();if((!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),"unlimited"===t)delete i.encodings[0].maxBitrate;else{if(i.encodings[0].maxBitrate===1e3*t)return;i.encodings[0].maxBitrate=1e3*t}return e.setParameters(i)}setBandwidthBySDP(e){let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=wz(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=wz(this._peerConnection.remoteDescription.sdp));let s=EP?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:EP?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:EP?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:EP?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:EP?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:s,limit:EP?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:EP?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:s,limit:EP?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:EP?1e3*n:n}]);let a={type:"offer",sdp:Pz(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(KN(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(gO&&vO<83||hP&&DO(kO,"12.1")||EP&&vP<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=Pz(this._parsedAnswer);return this._updateSDPPromise=new Promise((i,r)=>Xb(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(SM){this._log.error(SM),!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(SM)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return Xb(this,null,function*(){if(!EP||!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===eD.INACTIVE&&t===eD.RECVONLY&&(this._parsedAnswer.media[r].direction=e),e===eD.SENDONLY&&t===eD.INACTIVE&&(this._parsedAnswer.media[r].direction=eD.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(){return wz(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map(e=>e.direction)}setOffer(e){this._log.info("setting offer");let t=EJ(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 Xb(this,null,function*(){if("h265"===e&&!this._parsedAnswer&&(this._parsedAnswer=wz(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(i=>{var r;if(i.type===$k.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=[],gJ(i,n),t=!0)}}),t&&(this._log.warn("switch video encoder to ".concat(e)),yield this.updateSDP())})}getScheduleProfileLevelId(e){var t;try{let i=null==(t=this._room.scheduleResult.config)?void 0:t.profileLevelId,r="";if(2===e?r=Yw(null==i?void 0:i.big)?i.big:"":3===e?r=Yw(null==i?void 0:i.small)?i.small:"":7===e&&(r=Yw(null==i?void 0:i.aux)?i.aux:""),!r)return"";let n=yJ(r,this.clientAbility);return n?this._log.info("use schedule profile level id: streamType=".concat(e,", raw=").concat(r,", resolved=").concat(n)):this._log.warn("schedule profile level id not resolved: streamType=".concat(e,", raw=").concat(r)),n}catch(TM){return this._log.warn("getScheduleProfileLevelId error: ".concat(TM)),""}}getProfileLevelIdConfig(){try{let e=new URLSearchParams(location.search).get("profileLevelId")||"",t=yJ(e,this.clientAbility);if(t)return this._log.info("use url profile level id: raw=".concat(e,", resolved=").concat(t)),{big:t,small:t,aux:t};let i=this.getScheduleProfileLevelId(2),r=this.getScheduleProfileLevelId(3),n=this.getScheduleProfileLevelId(7);if(!i&&!r&&!n)return;let o={};return i&&(o.big=i),r&&(o.small=r),n&&(o.aux=n),o}catch(Ik){return void this._log.warn("getProfileLevelIdConfig error: ".concat(Ik))}}setH264ProfileLevelId(e,t){return Xb(this,null,function*(){if(!this._peerConnection||!this._serverAbility)return;this._updateSDPPromise&&(yield this._updateSDPPromise),this._log.info("set H264 profile-level-id to ".concat(t?"high":"default"," for ").concat(e)),this._parsedAnswer||(this._parsedAnswer=wz(this._peerConnection.remoteDescription.sdp));let i="main"===e?1:3,r=this._parsedAnswer.media[i];if(!r||r.type!==$k.VIDEO)return;let n=r.rtp||[],o=r.fmtp||[],s=n.find(e=>{var t;return"h264"===(null==(t=e.codec)?void 0:t.toLowerCase())});if(!s)return;let a=o.find(e=>String(e.payload)===String(s.payload));if(!a)return;let c=TJ(a.config);if(!c)return;let l="high"===vJ(c);if(t&&l||!t&&!l)return;let d=this._serverAbility.video.codecs.map(e=>TJ(e.fmtp)).filter(Boolean).find(e=>{let i=vJ(e);return t?"high"===i:"high"!==i});if(!d)return;let u=a.config;a.config=mJ(a.config,d),a.config!==u&&(yield this.updateSDP(),this._log.info("set H264 profile-level-id to ".concat(t?"high":"default"," success")))})}useHWEncoder(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;return Xb(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];KN(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===$k.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=[],gJ(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),this._datachannel=null,null==(e=this.clearWaitForConnectedPromise)||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.isDestroyed=!0,this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Kw(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 Xb(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")),UL.addSuccessEvent({key:r,cost:Date.now()-t})}catch(Ak){this._log.warn("switchRelay ".concat(i," failed"),Ak),UL.addFailedEvent({key:r,error:Ak}),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:hz,data:{videoDecCodec:"h264"},responseCommand:Gj.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{0!==e.data.code&&this._log.warn(e.data.message)})}};Kb([QV("reconnect")],bJ.prototype,"startReconnection",1),Kb([ZV(e=>e.userId)],bJ.prototype,"addDownlink",1),Kb([ZV(e=>e)],bJ.prototype,"removeDownlink",1),Kb([XV(!0)],bJ.prototype,"updateSDP",1),Kb([$V(521712,!1),aW(10,0)],bJ.prototype,"setOffer",1),Kb([$V(521713,!1),aW(10,0)],bJ.prototype,"setAnswer",1),Kb([jV((e,t)=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(e=>clearTimeout(e)),this._checkPendingPromiseSet.clear()),e.apply(this,i)})],bJ.prototype,"close",1);var kJ=class{constructor(e){qb(this,"tag"),qb(this,"len"),qb(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}},DJ=class{constructor(e){qb(this,"tinyId"),qb(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new kJ(new Uint8Array(e).slice(i,i+2+2+n).buffer);r.push(o),i+=4+n}let n=[];r.forEach(e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&n.push(e.data)});let o=n.reduce((e,t)=>e+t.byteLength,0),s=new Uint8Array(o),a=0;n.forEach(e=>{s.set(new Uint8Array(e),a),a+=e.byteLength}),this.data=s.buffer}},NJ=new Set;function wJ(){let e=Math.floor(4294967296*Math.random());return NJ.has(e)?wJ():(NJ.add(e),e)}var PJ=Jb(Qb()),OJ=class extends PJ.default{constructor(e){super(),qb(this,"userId"),qb(this,"tinyId"),qb(this,"_sdpSemantics"),qb(this,"_isUplink"),qb(this,"_room"),qb(this,"_log"),qb(this,"_currentState","DISCONNECTED"),qb(this,"_prevTime",-1),qb(this,"_blackSmallVideoDetectionId"),qb(this,"isDestroyed",!1),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=dM.createLogger({parent:this._room.getLogger(),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)}destroy(){this.isDestroyed=!0}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(oM.emit(aM.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"))}};function MJ(e){let{when:t,onSkip:i}=e;return jV((e,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];return Xb(this,null,function*(){if(!t.apply(this,o))return e.apply(this,o);null==i||i.call(this,r,...o)})})}var LJ=new class{constructor(){qb(this,"worker"),qb(this,"callbacks",new Map),qb(this,"_log"),qb(this,"sleep",{}),qb(this,"heartbeatListenerCleaner",new Map),qb(this,"userIdMap",new Map),this._log=dM.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),!JL()||!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(kD){this._log.warn("check error:",kD),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)}},xJ=class extends OJ{constructor(e){super(Wb(Hb({},e),{isUplink:!0})),qb(this,"localMainAudioTrack",null),qb(this,"localMainVideoTrack",null),qb(this,"localAuxAudioTrack",null),qb(this,"localAuxVideoTrack",null),qb(this,"_isPublishingAux",!1),qb(this,"_publishingLocalAudioTrack"),qb(this,"_publishingLocalVideoTrack"),qb(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}),qb(this,"_flag",0),qb(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{serverPublishState:t}=this,{publishState:i}=this._room,r=Object.keys(i).filter(e=>{if(i[e]!==t[e]&&i[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=sU.run("timeout",()=>this.checkPublishState(!0),{delay:1e4,count:1}));UL.addCount({key:521e3}),r.forEach(e=>{this._log.warn("".concat(e," publish failed during call ").concat(tM()," ").concat(YO())),UL.addEnum({key:521719,value:UJ[e]})}),sU.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(kD){this._log.warn("checkPublishState failed",kD)}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&sD),bigVideo:!!(this.flag&rD),smallVideo:!!(this.flag&nD),auxVideo:!!(this.flag&oD)}}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){return Xb(this,null,function*(){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"},h264:{supported:i.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if("vp9"===t||"av1"===t)return;let n=r[t];this._log.warn(n.log),null!=n&&n.supported&&(yield i.switchVideoEncoder(n.target))})}publish(e){return Xb(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;if(t.installEvents(),t.installTrackMuteEvents(i,r),r&&(r.retryEncodeFailed=t.onVideoEncodeFailed.bind(t)),yield t.singlePC.waitForPeerConnectionConnected(),i&&(t._publishingLocalAudioTrack=i),r){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new dk({code:ck.NOT_SUPPORTED_H264,message:RL({key:yL.NOT_SUPPORTED_H264ENCODE})});t.singlePC.isUsingH264&&!t.singlePC.isH264EncodeSupported&&t.singlePC.isVP8EncodeSupported&&(t._log.warn("h264 encoder not supported"),yield t.singlePC.switchVideoEncoder("vp8")),mP&&115===_O()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(Xk))),r.setProfile(Xk),yield r.applyProfile()),t._publishingLocalVideoTrack=r}let u;if(t._isPublishingAux=n,r&&!n&&r.small&&(u=t._room.videoManager.smallTrack),yield t._signalChannel.sendWaitForResponseWithRetry({command:_z,responseCommand:Gj.SPC_PUBLISH_RESULT,data:Wb(Hb({},t.singlePC.uplinkSSRC),{state:t._room.publishState,muteState:t._room.muteState}),retries:3}),r&&(yield t.checkHighProfile({streamType:r.streamType,newWidth:r.settings.width,newHeight:r.settings.height})),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();let h=n?7:2;(t._room.preferHW||null!=(d=t._room.scheduleResult.config)&&d.preferHW)&&r&&r.profile.width*r.profile.height>=921600&&t.singlePC.useHWEncoder(!0,h)}()})}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!_x())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(eD.SENDONLY,l);return c.push(u),Promise.all(c)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._room.localMainAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._room.localMainVideoTrack;case 2:return this.localAuxVideoTrack||this._room.localAuxVideoTrack;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);if(!o||!o.encodeFrame)return i.enqueue(e);o.isAudio?i.enqueue(o.enableEncodeFrame?o.encodeFrame(e):e):i.enqueue(null!=(r=this.singlePC)&&r.isUsingH264||null!=(n=this.singlePC)&&n.isUsingH265?o.encodeFrame(e,8===t):e)}}),o):n.readable).pipeTo(n.writable,o).catch(e=>{this._log.debug("encoded stream error",e),"destroy"!==e&&this._log.warn(e)})}initSenderTransform(e,t){if(!(this._peerConnection&&this.singlePC&&this.singlePC.scriptTransformWorker&&Cx))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 Xb(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(e){return Xb(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&&!cx())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;UL.addSuccessEvent({key:a}),s?(null!=(r=t.singlePC)&&r.enableInsertableStreams&&t.createEncodedStreams(o,8),t.initSenderTransform(o,8),yield t.singlePC.setTransceiverDirection(eD.SENDONLY,[2]),t.updateMediaSettings(),yield t.doPublishChange(),o.track&&(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;UL.addFailedEvent({key:i,error:10002}),LJ.stop(t._blackSmallVideoDetectionId),t._blackSmallVideoDetectionId=void 0}}))):UL.addFailedEvent({key:a,error:10001})}()})}doPublishSmall(e){return Xb(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=ww(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 Xb(this,null,function*(){this.singlePC&&(this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(eD.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),LJ.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)})}checkHighProfile(e){return Xb(this,null,function*(){var t,i;if("high"!==((null==(t=this._room.scheduleResult.config)?void 0:t.profileLevelId)||{})["main"===e.streamType?"big":"aux"])return;let r=e.newWidth*e.newHeight>=921600&&!JO();try{yield null==(i=this.singlePC)?void 0:i.setH264ProfileLevelId(e.streamType,r)}catch(fM){this._log.warn("setH264ProfileLevelId failed, ignore",fM)}})}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 Xb(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=Wb(Hb({},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=Wb(Hb({},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(eD.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 Xb(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:Xj,data:t,responseCommand:Gj.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:Qj,commandDesc:"unpublish",responseCommand:Gj.UNPUBLISH_RESULT,enableLog:e}).catch(e=>{if(e.getCode()===ck.API_CALL_TIMEOUT||e.getCode()===ck.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),Sx){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||0)/t||0,this._mediaSettings.videoHeight=(e.height||0)/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||0)/t||0,this._mediaSettings.auxVideoHeight=(e.height||0)/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:hz,data:this._mediaSettings,responseCommand:Gj.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{0!==e.data.code&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return Xb(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?$k.AUXILIARY:$k.MAIN," stream")),mx()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return Xb(this,null,function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===$k.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&&this._room.videoManager.smallTrack&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===eD.INACTIVE&&(yield this.singlePC.setTransceiverDirection(eD.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return Xb(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?$k.AUXILIARY:$k.MAIN," stream")),mx()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return Xb(this,null,function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===$k.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(eD.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return Xb(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=2===e.mediaType||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?$k.AUXILIARY:$k.MAIN," stream")),r.kind===$k.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===$k.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0})}setBandwidth(e){return Xb(this,arguments,function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===$k.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._room.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:qj,responseCommand:Gj.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&oM.emit(aM.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:$k.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===$k.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===$k.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===$k.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===$k.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===xD?(this._log.error(SL.NOT_SUPPORTED_H264ENCODE),new dk({code:ck.NOT_SUPPORTED_H264,message:RL({key:yL.NOT_SUPPORTED_H264ENCODE})})):new dk({code:ck.UNKNOWN,message:RL({key:yL.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Gj.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return Xb(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}))})}};Kb([WV(e=>{let{localVideoTrack:t}=e;null==t||delete t.retryEncodeFailed})],xJ.prototype,"unpublish",1),Kb([MJ({when(){return this.isDestroyed}})],xJ.prototype,"doPublishChange",1),Kb([MJ({when(){return this.isDestroyed}})],xJ.prototype,"doUnpublish",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||{}),VJ=xJ;function FJ(e){return Object.keys(e).filter(t=>e[t])}var BJ=class extends OJ{constructor(e){super(Wb(Hb({},e),{isUplink:!1})),qb(this,"_flag",0),qb(this,"isRobot",!1),qb(this,"role","anchor"),qb(this,"fromType"),qb(this,"remoteAudioTrack"),qb(this,"remoteVideoTrack"),qb(this,"remoteAuxiliaryTrack"),qb(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),qb(this,"jitterBufferTimeoutId",-1),qb(this,"_videoCodec"),qb(this,"avPlayerStateSyncManager"),qb(this,"isDataChannelSubscribed",!1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.fromType=e.fromType,this.remoteAudioTrack=new dW(this._room,this),this.remoteVideoTrack=new hW(this._room,this),this.remoteAuxiliaryTrack=new pW(this._room,this),this.avPlayerStateSyncManager=new MG({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player}),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,datachannel:this.isDataChannelSubscribed}}get muteState(){return hw(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===$k.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.avPlayerStateSyncManager.destroy(),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=$k.AUDIO;n.kind===$k.VIDEO&&(a=s===$k.MAIN?$k.VIDEO:$k.AUXILIARY);let c=this.remoteAudioTrack;a===$k.VIDEO?c=this.remoteVideoTrack:a===$k.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===$k.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=>{"destroy"!==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 Xb(this,null,function*(){var i,r;try{let n=!0;if(this._log.info("subscribe ".concat(t," ").concat(FJ(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)}let{user:o,mediaTrack:s}=this.remoteVideoTrack;e.smallVideo&&s?(UL.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=LJ.start({track:s,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,o),UL.addFailedEvent({key:524702}),LJ.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(LJ.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(Ak){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Ak.message," ").concat(JSON.stringify(this.muteState))),new dk({code:ck.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Ak}})}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.readyState))&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),gO&&vO<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return Xb(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=Hb({},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(FJ(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())}()})}subscribeDataChannel(){return Xb(this,null,function*(){if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let e=Wb(Hb({},this.subscribeState),{datachannel:!0});yield this.doSubscribe(e)})}unsubscribeDataChannel(){return Xb(this,null,function*(){let e=Wb(Hb({},this.subscribeState),{datachannel:!1});yield this.sendSubscription("unsubscribe",e),yield this.removeDownlink()})}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=$j,n=Gj.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:t.datachannel,srcTinyId:this.tinyId},r=ez,n=Gj.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 dk({code:i.code,message:RL({key:yL.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 Xb(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary||this.isDataChannelSubscribed)&&(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 Xb(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*(){var r,n;if(e.singlePC){e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected();try{if(i||!e.hasSSRC){let i={audioSsrc:wJ(),bigVideoSsrc:wJ(),bigVideoRtxSsrc:wJ(),auxVideoSsrc:wJ(),auxVideoRtxSsrc:wJ()},{audioSsrc:o,bigVideoSsrc:s,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=i;e.ssrc={audio:o,video:s,videoRtx:a,auxiliary:c,auxiliaryRtx:l},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let o=yield e._signalChannel.sendWaitForResponseWithRetry({command:fz,responseCommand:Gj.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:null!=(r=t.datachannel)&&r,ssrc:i},retries:3,retryTimeout:0});if(0!==o.data.code&&-10036!==o.data.code)throw new dk({code:o.data.code,message:o.data.message});e.isDataChannelSubscribed=null!=(n=t.datachannel)&&n}catch(_M){throw yield e.removeDownlink(),_M}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}finally{if((t.audio||t.video||t.smallVideo||t.auxiliary||!t.datachannel)&&Vx){let{main:t,aux:i}=e._room.jitterBufferDelay||{},{jitterDelay:r=t,jitterDelayAux:n=i}=e._room.scheduleResult.config||{};(YN(r)||YN(n))&&e.setJitterBufferDelay({mainDelay:r,auxDelay:n})}}}}()})}removeDownlink(){return Xb(this,null,function*(){if(!this.singlePC)return;this.isDataChannelSubscribed=!1,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(!Vx||!this.singlePC||!this._peerConnection||qw(t)&&qw(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return YN(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),YN(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,qw(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||qw(t)&&e.track===this.remoteAudioTrack.outMediaTrack;if(n&&qw(i)||!n&&qw(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(Ak){this._log.warn("set jitterBuffer delay error: ".concat(Ak)),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()}};Kb([XV(),jV(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 dk({code:ck.API_CALL_ABORTED,message:RL({key:yL.CONNECTION_ABORTED,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally(()=>{this.off("closed",n)})})})],BJ.prototype,"subscribe",1),Kb([XV()],BJ.prototype,"unsubscribe",1),Kb([ZV(()=>"jitter")],BJ.prototype,"setJitterBufferDelay",1);var HJ=BJ;var WJ=Jb(Qb());var GJ=class e extends WJ.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,qb(this,"log"),qb(this,"cmdIdSeqMap",new Map),qb(this,"messageMap",new Map),this.log=dM.createLogger({parent:e.getLogger(),id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(Gj.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",e=>{let{userId:t}=e;[...this.messageMap.keys()].forEach(e=>{e.split("_").slice(0,-1).join("_")===t&&this.messageMap.delete(e)})})}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(Tz,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),bw(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)}};qb(GJ,"SEQ_INTERVAL",300);var jJ=GJ,{isString:zJ,isUndefined:JJ,getNetworkType:KJ,isEmpty:qJ}=Ek,YJ=class extends lJ{constructor(e){super(e),qb(this,"_businessInfo"),qb(this,"userManager"),qb(this,"_version"),qb(this,"_heartbeat",-1),qb(this,"_lastHeartBeatTime",-1),qb(this,"_stats"),qb(this,"_joinTimeout",-1),qb(this,"_firstPublishedList",null),qb(this,"_joinReject",null),qb(this,"_isRelayChanged",!1),qb(this,"sdpSemantics"),qb(this,"signalChannel",null),qb(this,"uplinkConnection",null),qb(this,"singlePC",null),qb(this,"enableSPC",fx),qb(this,"_changeBigSmallRecords",new Map),qb(this,"networkQuality"),qb(this,"_iceTransportPolicy"),qb(this,"forceRelay",!1),qb(this,"_turnServers",[]),qb(this,"_iceServersFromJoin"),qb(this,"_syncUserListInterval",-1),qb(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),qb(this,"enableSEI",!1),qb(this,"_enableAudioVolumeEvaluation",!1),qb(this,"_audioVolumeIntervalId",0),qb(this,"_enableMultiAuxStream",!1),qb(this,"_pureAudioPushMode",!1),qb(this,"_customMessageManager"),qb(this,"_enableDataChannel",!1),qb(this,"preferHW",!1),qb(this,"healthDetector"),qb(this,"playoutDelay"),qb(this,"jitterBufferDelay"),qb(this,"_updateAudioLevelTaskId",-1),qb(this,"switchRoomSubedReq"),qb(this,"resolveSwitchRoomSubedReq"),qb(this,"enableVolumeControlInIOS"),qb(this,"capturedLocalMainAudioTrack"),qb(this,"capturedLocalMainVideoTrack"),qb(this,"capturedLocalAuxVideoTrack"),qb(this,"firewallDetector"),this.firewallDetector=new yW,this.firewallDetector.on("firewall-restriction",()=>{this._log.warn("firewall restriction"),this.emit("firewall-restriction")}),this._stats=new Fz(this,this._log),this.userManager=new TW(this.userId,this._log),this._version=yk,this.sdpSemantics=LD,JJ(e.sdpSemantics)?pM.isUnifiedPlanDefault()&&(this.sdpSemantics=MD):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(KJ())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!JJ(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&fx,!JJ(e.enableSPC)&&fx&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this._initBusinessInfo(e),this.healthDetector=new AJ(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 Xb(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",e=>{this.emit("peer-join",e)}),this.userManager.on("8",e=>{this.emit("asr-robot-peer-join",e)}),this.userManager.on("9",e=>{this.emit("asr-robot-peer-leave",e)}),this.userManager.on("2",e=>{let{userId:t,reason:i}=e;this.closeDownLinkConnection(t,"remote user exitRoom"),this.emit("peer-leave",{userId:t,reason:i})}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",e=>{var t=Gb(e,[]);oM.emit(aM.REMOTE_PUBLISH_STATE_CHANGED,Hb({room:this},t)),this.emit("remote-publish-state-changed",Hb({},t))}),this.joinParams=e,XN(e.enableDataChannel)&&(this._enableDataChannel=e.enableDataChannel),new Promise((t,i)=>Xb(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 dk&&o.code===ck.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),UL.addSuccessEvent({key:521708,cost:aw()-s}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(fM){UL.addFailedEvent({key:521708,error:fM}),i(fM)}this._joinReject=null}))})}initSinglePC(){return Xb(this,null,function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new bJ({signalChannel:this.signalChannel,room:this,enableDataChannel:this._enableDataChannel}),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()),this.singlePC.on("data_channel_msg",e=>{let t=(new TextDecoder).decode(e.data.data||e.data);try{this.emit("data-channel-message",{data:JSON.parse(t)})}catch(TM){}});try{return yield this.singlePC.initialize()}catch(Ik){throw this.fallbackToMPC(),new dk({code:ck.SPC_INITIALIZED_FAILED,message:null==Ik?void 0:Ik.message})}}})}doJoin(e,t){return new Promise((i,r)=>Xb(this,null,function*(){var n,o,s,a,c,l,d,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Uj,e=>{this.clearJoinTimeout(),oM.emit(aM.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)}),XN(null==(o=null==(n=this.scheduleResult)?void 0:n.config)?void 0:o.singlePC)&&fx&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),(!(null==(a=null==(s=this.scheduleResult)?void 0:s.config)?void 0:a.jitterDelay)&&!(null==(l=null==(c=this.scheduleResult)?void 0:c.config)?void 0:l.jitterDelayAux)||!Vx)&&t&&this.playoutDelay&&(this._log.info("set playoutDelay",JSON.stringify(this.playoutDelay)),t.playoutDelay=this.playoutDelay);let h={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:iM(),netType:MN(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&WL(),transcription:this._enableDataChannel,downUseVp8:(null==(d=this.scheduleResult.config)?void 0:d.downUseVp8)||!1};this._log.debug("join room signal data: ".concat(JSON.stringify(h)));let p=5e3;null!=(u=this.scheduleResult.config)&&u.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(p=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout(()=>{r(new dk({code:ck.JOIN_ROOM_FAILED,message:RL({key:yL.JOIN_ROOM_TIMEOUT})}))},p),oM.emit(aM.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?mz:zj,h),this.signalChannel.once(Gj.JOIN_ROOM_RESULT,t=>Xb(this,null,function*(){this.clearJoinTimeout();let{code:n,message:o,data:s,tinyId:a}=t.data;oM.emit(aM.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(Wb(Hb({},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 dk({code:ck.JOIN_ROOM_FAILED,extraCode:n,message:RL({key:yL.JOIN_ROOM_FAILED,data:{error:o,code:n}})})))}))}))}reJoin(){return Xb(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(Wb(Hb({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),hU.logSuccessEvent({userId:this.userId,eventType:ND.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(RJ.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof VJ&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(e=>{e.installEvents(),e.onSinglePCReconnected()}))};this.singlePC.on(RJ.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Vz&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(Ik){this._log.warn("reJoin fail ".concat(Ik)),this.reset(),hU.logFailedEvent({userId:this.userId,eventType:ND.REJOIN,error:Ik}),this.emit("error",new dk({code:ck.JOIN_ROOM_FAILED,message:RL({key:yL.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")})}initialize(){return Xb(this,null,function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this.signalChannel||function(e){let t=[...Iz.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 Cz({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 jJ(this,this.signalChannel),this._customMessageManager.on("message",e=>{this.emit("custom-message",e)})),this.networkQuality||(this.networkQuality=new Gz({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Gz.EVENT_NETWORK_QUALITY,e=>{var t;this.emit("network-quality",e),null==(t=this.singlePC)||t.detectTCPAndUDP(e)})),dU(this,this.signalChannel).add(Mj,e=>{oM.emit(aM.SIGNAL_CONNECTION_STATE_CHANGED,Hb({room:this},e)),this.emit("signal-connection-state-changed",e)}).add(xj,e=>{this.reset(),this.emit("error",e)}).add(Gj.PEER_JOIN,e=>{let{srcTinyId:t,userId:i,role:r,fromType:n}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r,fromType:n})}).add(Gj.PEER_LEAVE,e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)}).add(Gj.UPDATE_REMOTE_MUTE_STAT,e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)}).add(Gj.CLIENT_BANNED,e=>{let t=e.data.data,{reason:i}=t;if(hU.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(Gj.SEND_SWITCH_ROOM_SUBED_REQ,e=>{if(!this.singlePC)return;let{subList:t}=e.data.data;this._log.info("auto subscribe ".concat(vw(t,{keysToInclude:["userId"]}))),t.forEach(e=>{this.singlePC.autoSubscribedUserMap.set(e.userId,e)}),this.resolveSwitchRoomSubedReq()}).add(Gj.FALLBACK_CODEC,e=>Xb(this,null,function*(){var t,i,r,n,o;let s=e.data.data;0===(null==(t=s.videoControlInfo)?void 0:t.enableH265Enc)&&"h265"===(null==(i=this.singlePC)?void 0:i.videoCodec)&&(this._log.warn("fallback codec enableH265Enc: ".concat(null==(r=s.videoControlInfo)?void 0:r.enableH265Enc)),UL.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(Oj,e=>{this.tinyId=e.signalInfo.tinyId,oM.emit(aM.JOIN_SIGNAL_CONNECTION_END,{room:this})}),oM.emit(aM.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&oM.emit(aM.JOIN_SIGNAL_CONNECTION_END,{room:this}),n})}setSignalChannel(e){this.signalChannel=e,e||uU(this)}leave(){return Xb(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(kD){}this._log.info("leave() => leaving room"),oM.emit(aM.LEAVE_SEND_CMD,{room:this}),null==(e=this.signalChannel)||e.send(Jj),this.switchRoomSubedReq=void 0,this._changeBigSmallRecords.clear()})}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=sU.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),sU.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return Xb(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(mW.has(e)){let t=mW.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 mW.delete(e),t}return[]}(this.userId):[],n=Wb(Hb({str_sdk_version:vk,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:Hb({uint32_terminal_type:15,str_device_name:YO(),str_os_version:"",uint32_net_type:MN()},i.msg_device_info)});if(this.heartbeatReport=n,this.heartbeatCount++,oM.emit(aM.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Kj,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",Wb(Hb({},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=!1,i=e.data.userList||[],r=e.data.mixRobotList||[],n=[];for(let s of i){if(s.flag===dD)continue;let{userId:e,srcTinyId:i,flag:r,fromType:o}=s;e===this.userId&&(t=!0,this.uplinkConnection&&(this.uplinkConnection.flag=r),this.localPublishFlag!==r&&(this.localPublishFlag=r,this.emit("local-publish-flag-changed",r))),n.push({userId:e,tinyId:i,flag:r,fromType:o})}let o=[...r.map(e=>{let{userId:t,srcTinyId:i,flag:r,mixUserList:n,fromType:o}=e;return{userId:t,tinyId:i,flag:r,isRobot:!0,mixUserList:n,fromType:o}}),...n];o.forEach(e=>{let{userId:t}=e,i=this.remotePublishedUserMap.get(t);i&&this.checkSubscribeBigSmallVideo(i)}),e.data.fakeMixUser&&(e.data.fakeMixUser.tinyId=e.data.fakeMixUser.srcTinyId,o.push(e.data.fakeMixUser)),oM.emit(aM.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:o}),t||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(o)}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),"you exitRoom"===e&&(this.uplinkConnection.destroy(),this.uplinkConnection=null),this.uplinkConnection instanceof Vz&&(this.uplinkConnection=null)),this.localTracks.forEach(e=>e.unpublish()),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r,isRobot:n,fromType:o}=e,s=new(this.singlePC?HJ:Lz)({userId:t,tinyId:i,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:n,fromType:o});this.userManager.addRemotePublishedUser(s),this.installDownlinkEvents(s,t),this.emit("remote-published",s)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",e=>{let i=e.getCode();i!==ck.ICE_TRANSPORT_ERROR&&(i===ck.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))}),e.on("connection-state-changed",t=>{this.emit("media-connection-state-changed",Wb(Hb({},t),{userId:e.userId}))})}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=sU.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){sU.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:dz,responseCommand:Gj.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,fromType:n}=e;return{userId:t,tinyId:i,role:r,fromType:n}});throw RL({key:yL.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Gj.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||!kz)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)===AD.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(e=>{if(e instanceof Dz&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===AD.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}})}fallbackToMPC(){return Xb(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),hU.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 Vz({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 Lz({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 dk({code:ck.INVALID_OPERATION,message:RL({key:yL.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.firewallDetector.destroy(),this.removeAllListeners(),this.healthDetector.destroy(),sU.clearTask(this._audioVolumeIntervalId))}switchRole(e){return Xb(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:uz,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:Gj.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 dk({code:ck.SWITCH_ROLE_FAILED,message:RL({key:yL.SWITCH_ROLE_FAILED,data:{message:r,code:i}})});this.role=e}).catch(e=>{throw e instanceof dk&&e.getCode()===ck.API_CALL_TIMEOUT&&(e=new dk({code:ck.SWITCH_ROLE_FAILED,message:RL({key:yL.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e})}subscribeDataChannel(){return Xb(this,null,function*(){if(0===this.remotePublishedUserMap.size)return;let e=[...this.remotePublishedUserMap.values()].filter(e=>e.fromType===iN);this._log.info("subscribeDataChannel",e.map(e=>e.userId)),yield Promise.all(e.map(e=>Xb(this,null,function*(){try{yield e.subscribe(Wb(Hb({},e.subscribeState),{datachannel:!0}),"main")}catch(TM){this._log.error("subscribeDataChannel failed:",e.userId,TM)}})))})}unsubscribeDataChannel(){return Xb(this,null,function*(){if(0===this.remotePublishedUserMap.size)return;let e=[...this.remotePublishedUserMap.values()].filter(e=>e.fromType===iN);this._log.info("unsubscribeDataChannel",e.map(e=>e.userId)),yield Promise.all(e.map(e=>e.unsubscribeDataChannel()))})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new VJ({userId:this.userId,tinyId:this.tinyId,room:this}):new Vz({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",Wb(Hb({},e),{userId:this.userId}))}),this.uplinkConnection.on("error",e=>{let t=e.getCode();t!==ck.ICE_TRANSPORT_ERROR&&(t===ck.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})}publish(e){return Xb(this,null,function*(){var t;this.uplinkConnection||this._initUplinkConnection();let i="".concat(e.streamType," ").concat(e.isAudio&&e.isScreen?"screen":"").concat(e.kind);this._log.info("publish() => ".concat(i)),yield null==(t=this.singlePC)?void 0:t.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:e instanceof SH?e:null,localVideoTrack:e instanceof kH?e:null,isAuxiliary:"auxiliary"===e.streamType})})}unpublish(e){return Xb(this,null,function*(){if(("live"!==this.scene||"anchor"===this.role)&&(this.isMainStreamPublished||this.isAuxStreamPublished)&&this.uplinkConnection){try{let t="".concat(e.streamType," ").concat(e.isAudio&&e.isScreen?"screen":"").concat(e.kind);this._log.info("unpublish() => ".concat(t)),yield this.uplinkConnection.unpublish({localAudioTrack:e instanceof SH?e:null,localVideoTrack:e instanceof kH?e:null})}catch(kD){}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?(e.unpublish(),this.uplinkConnection.removeTrack(e)):Promise.resolve()}replaceTrack(e){return this.uplinkConnection&&e.mediaTrack&&Tx()?this.uplinkConnection.replaceTrack(e).then(t=>{t&&oM.emit(aM.LOCAL_TRACK_REPLACED,{track:e})}):Promise.resolve()}setBandWidth(e){return Xb(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return Xb(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:$k.VIDEO,videoType:$k.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 Xb(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=Hb({},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),oM.emit(aM.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," ").concat(t.map(e=>e.strMediaType).join(",")," [").concat(Oz(n),"] prev: [").concat(Oz(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());oM.emit(aM.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(Ak){let i=Ak instanceof dk?Ak.getCode():ck.UNKNOWN,n=Ak;throw Ak instanceof dk?i===ck.REMOTE_STREAM_NOT_EXIST&&(n=new dk({code:ck.API_CALL_ABORTED,message:RL({key:yL.API_CALL_ABORTED,data:{message:Ak.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new dk({code:i,message:RL({key:yL.SUBSCRIBE_FAILED,data:{message:Ak.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 Xb(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," ").concat(t.map(e=>e.strMediaType).join(",")));try{yield i.unsubscribe({remoteTracks:t,streamType:r})}catch(Ak){this._log.warn("unsubscribe() => failed ".concat(Ak))}t.forEach(e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)}),oM.emit(aM.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 sU.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),oM.emit(aM.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&sU.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=sU.run("intervalInWorker",()=>{var i;mV.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];null==(i=this.remotePublishedUserMap)||i.forEach(e=>{if(e.muteState.hasAudio){!mV.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 Xb(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=sU.run("intervalInWorker",()=>Xb(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"),sU.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(!yx||!i)return;let r=null==(t=i.getSynchronizationSources()[0])?void 0:t.audioLevel;YN(r)?e.remoteAudioTrack.volume=Math.min(2*r,1):i.getStats().then(t=>{t.forEach(t=>{"inbound-rtp"===t.type&&YN(t.audioLevel)&&(e.remoteAudioTrack.volume=t.audioLevel)})})}getLocalAudioStats(){return Xb(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 Xb(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 Xb(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 Xb(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 Xb(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(Ek.getTurnServer(e))):Ek.isPlainObject(e)&&i.push(Ek.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:oz,data:e,timeout:5e3,responseCommand:Gj.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(e=>{if(e.code!==ck.API_CALL_ABORTED)throw e})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:sz,data:e,timeout:5e3,responseCommand:Gj.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(e=>{if(e.code!==ck.API_CALL_ABORTED)throw e})}sendStartPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?tz:rz,data:e,timeout:5e3,responseCommand:t?Gj.START_PUBLISH_TENCENT_CDN_RES:Gj.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(e=>{if(e.code!==ck.API_CALL_ABORTED)throw e})}sendStopPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?iz:nz,data:e,timeout:5e3,responseCommand:t?Gj.STOP_PUBLISH_TENCENT_CDN_RES:Gj.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(e=>{if(e.code!==ck.API_CALL_ABORTED)throw e})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:az,data:e,timeout:5e3,responseCommand:Gj.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(e=>{if(e.code!==ck.API_CALL_ABORTED)throw e})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:cz,data:e,timeout:5e3,responseCommand:Gj.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(e=>{if(e.code!==ck.API_CALL_ABORTED)throw e})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:lz,data:e,timeout:5e3,responseCommand:Gj.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(e=>{if(e.code!==ck.API_CALL_ABORTED)throw e})}sendAbilityStatus(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:gz,data:e,timeout:5e3,responseCommand:Gj.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=Ek.getEnv();return t?(e.mainUrl="wss://".concat(Ek.getTestSignalDomain(t)),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.localPublishFlag=0,this.heartbeatCount=0,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 Xb(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,datachannel:e.subscribeState.datachannel};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(ZD-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=ZD}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(ZD-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:ZD};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(zJ(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!JJ(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new dk({code:ck.INVALID_PARAMETER,message:RL({key:yL.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(!JJ(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new dk({code:ck.INVALID_PARAMETER,message:RL({key:yL.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!JJ(e.userDefinePushArgs)){if(!(zJ(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new dk({code:ck.INVALID_PARAMETER,message:RL({key:yL.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}qJ(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){return Xb(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Rx)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 dk({code:ck.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 Xb(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:wJ(),bigVideoSsrc:wJ(),bigVideoRtxSsrc:wJ(),auxVideoSsrc:wJ(),auxVideoRtxSsrc:wJ()});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,bw(5e3).then(e)}),oM.emit(aM.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();try{this.userManager.clear(),d=yield this.signalChannel.sendWaitForResponse({command:vz,responseCommand:Gj.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 dk({code:ck.SWITCH_ROOM_FAILED,extraCode:e,message:t});throw oM.emit(aM.SWITCH_ROOM_FAILED,{room:this,error:i}),i}this.userSig=n,JJ(o)||(this.privateMapKey=o),oM.emit(aM.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()}startUpdateNTPTime(){if(!this.signalChannel)return;let e=[];for(let t=0;t<5;t++)e.push(this.updateNTPTime());return Promise.all(e).then(e=>{var t;let i=e[0].offset,r=e[0].offset;e.forEach(e=>{i=Math.min(e.offset,i),r=Math.max(e.offset,r)});let n=Math.floor(e.reduce((e,t)=>e+t.rtt,0)/e.length),o=Math.floor(e.reduce((e,t)=>e+t.offset,0)/e.length);(r-i>30||n>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),pk(o),null==(t=this.scriptTransformWorker)||t.postMessage({type:"ntp-offset",data:o}),this._log.debug("ntp updated offset: ".concat(o)),this.emit("ntp-time-updated")}).catch(e=>{this._log.warn("ntp updated failed: ".concat(e))})}updateNTPTime(){let e=Date.now();return this.signalChannel.sendWaitForResponse({command:yz,responseCommand:Gj.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(e)},enableLog:!1}).then(t=>{let i=Number(t.data.data.serverSendTime),r=Number(t.data.data.serverRecvTime),n=t.data.receiveTime||Date.now();return{rtt:n-e-(r-i),offset:(r-e+(i-n))/2}})}};return Kb([Qx(["left",eU.INIT],"joined"),mU({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"),hG(!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())}}),jV(e=>{let t=new Nj;return function(i,r,n){return Xb(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 dk({code:ck.INVALID_OPERATION,message:RL({key:yL.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new dk({code:ck.INVALID_OPERATION,message:RL({key:yL.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)),oM.emit(aM.JOIN_START,{room:this,roomId:o,params:i});let s=Ek.getEnv();s||(s=Wk.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(tD.OLD_CLOUD_LADDER)?s=Wk.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(tD.WEBRTC)&&(s=Wk.WEBRTC))),hU.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),pM.checkSystemRequirementsInternal(n).then(e=>{this.checkSystemResult=e,wj.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Ek.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=Ek.performanceNow(),oM.emit(aM.JOIN_SUCCESS,{room:this}),30===n&&!i.component&&hU.uploadEvent({log:"stat-conv-".concat(Number(xO),"-").concat(location.hostname),userId:this.userId}),t}catch(vM){throw t.delete({room:this,roomId:o}),oM.emit(aM.JOIN_FAILED,{room:this,error:vM}),vM}})}})],YJ.prototype,"join",1),Kb([Qx("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),jV(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Xb(this,null,function*(){oM.emit(aM.LEAVE_START,{room:this}),yield e.call(this,...i),oM.emit(aM.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})}),QV("leave room"),_U({fnName:"publish",validateArgs:!1}),_U({fnName:"unsubscribe",validateArgs:!1})],YJ.prototype,"leave",1),Kb([ZV(e=>e.mediaType),jV(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Xb(this,null,function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter(e=>e.outMediaTrack&&"ready"===e.state),!i.length))return;oM.emit("61",{room:this});let t=e.apply(this,i);return Promise.all(i.map(e=>e.publish(this,t)))})}),mU({settings:{retries:bD,timeout:e=>jN(e)},onError(e,t,i,r){let[n]=r;var o;null!=(o=e.message)&&o.includes("timeout")?(this._log.warn("publish ".concat(n.strMediaType," timeout"),e),t()):(this._log.error("publish ".concat(n.strMediaType," failed: ").concat(e)),i(e),oM.emit(aM.PUBLISH_FAILED,{room:this}))}})],YJ.prototype,"publish",1),Kb([_U({fnName:"publish"}),ZV(e=>e.mediaType),jV(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}),WV(function(){var e,t;0===this.localTracks.size&&px()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach(e=>e.track&&e.replaceTrack(null)))})],YJ.prototype,"unpublish",1),Kb([GV(e=>{if(e.code!==ck.API_CALL_ABORTED)throw e}),ZV(e=>e.userId)],YJ.prototype,"replaceTrack",1),Kb([ZV(function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId},function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return"".concat(t[0].userId,"|sub")}),aW(),jV(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}),mU({settings:{retries:bD,timeout:e=>jN(e)},onError(e,t,i,r){if(e.message.includes("timeout"))this._log.warn("subscribe timeout"),t();else{let t=(null==e?void 0:e.code)===ck.API_CALL_ABORTED;this._log[t?"warn":"error"]("subscribe failed ".concat(r.map(e=>e.strMediaType).join(","),": ").concat(e)),i(e),oM.emit(aM.SUBSCRIBE_FAILED,{room:this,remoteTracks:r})}}})],YJ.prototype,"subscribe",1),Kb([_U({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")})}}),ZV(function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId},function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return"".concat(t[0].userId,"|sub")})],YJ.prototype,"unsubscribe",1),Dj.create=Dj._create.bind(Dj,YJ),xx(30),Dj});
|
|
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(){var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},t=function(e){return e&&e.Math===Math&&e},i=t("object"==typeof globalThis&&globalThis)||t("object"==typeof window&&window)||t("object"==typeof self&&self)||t("object"==typeof e&&e)||t("object"==typeof e&&e)||function(){return this}()||Function("return this")(),r={},o=function(e){try{return!!e()}catch(t){return!0}},n=!o(function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]}),a=!o(function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")}),s=a,l=Function.prototype.call,c=s?l.bind(l):function(){return l.apply(l,arguments)},d={},u={}.propertyIsEnumerable,h=Object.getOwnPropertyDescriptor,p=h&&!u.call({1:2},1);d.f=p?function(e){var t=h(this,e);return!!t&&t.enumerable}:u;var m,f,_=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},g=a,E=Function.prototype,v=E.call,y=g&&E.bind.bind(v,v),T=g?y:function(e){return function(){return v.apply(e,arguments)}},I=T,A=I({}.toString),S=I("".slice),R=function(e){return S(A(e),8,-1)},b=o,w=R,C=Object,D=T("".split),N=b(function(){return!C("z").propertyIsEnumerable(0)})?function(e){return"String"===w(e)?D(e,""):C(e)}:C,k=function(e){return null==e},O=k,M=TypeError,P=function(e){if(O(e))throw new M("Can't call method on "+e);return e},L=N,x=P,U=function(e){return L(x(e))},V="object"==typeof document&&document.all,F=void 0===V&&void 0!==V?function(e){return"function"==typeof e||e===V}:function(e){return"function"==typeof e},B=F,H=function(e){return"object"==typeof e?null!==e:B(e)},W=i,G=F,j=function(e,t){return arguments.length<2?(i=W[e],G(i)?i:void 0):W[e]&&W[e][t];var i},z=T({}.isPrototypeOf),K=i.navigator,q=K&&K.userAgent,Y=q?String(q):"",J=i,X=Y,Q=J.process,$=J.Deno,Z=Q&&Q.versions||$&&$.version,ee=Z&&Z.v8;ee&&(f=(m=ee.split("."))[0]>0&&m[0]<4?1:+(m[0]+m[1])),!f&&X&&(!(m=X.match(/Edge\/(\d+)/))||m[1]>=74)&&(m=X.match(/Chrome\/(\d+)/))&&(f=+m[1]);var te=f,ie=te,re=o,oe=i.String,ne=!!Object.getOwnPropertySymbols&&!re(function(){var e=Symbol("symbol detection");return!oe(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ie&&ie<41}),ae=ne&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,se=j,le=F,ce=z,de=Object,ue=ae?function(e){return"symbol"==typeof e}:function(e){var t=se("Symbol");return le(t)&&ce(t.prototype,de(e))},he=String,pe=function(e){try{return he(e)}catch(t){return"Object"}},me=F,fe=pe,_e=TypeError,ge=function(e){if(me(e))return e;throw new _e(fe(e)+" is not a function")},Ee=ge,ve=k,ye=function(e,t){var i=e[t];return ve(i)?void 0:Ee(i)},Te=c,Ie=F,Ae=H,Se=TypeError,Re={exports:{}},be=i,we=Object.defineProperty,Ce=function(e,t){try{we(be,e,{value:t,configurable:!0,writable:!0})}catch(i){be[e]=t}return t},De=i,Ne=Ce,ke="__core-js_shared__",Oe=Re.exports=De[ke]||Ne(ke,{});(Oe.versions||(Oe.versions=[])).push({version:"3.47.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru), 2025 CoreJS Company (core-js.io)",license:"https://github.com/zloirock/core-js/blob/v3.47.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Me=Re.exports,Pe=Me,Le=function(e,t){return Pe[e]||(Pe[e]=t||{})},xe=P,Ue=Object,Ve=function(e){return Ue(xe(e))},Fe=Ve,Be=T({}.hasOwnProperty),He=Object.hasOwn||function(e,t){return Be(Fe(e),t)},We=T,Ge=0,je=Math.random(),ze=We(1.1.toString),Ke=function(e){return"Symbol("+(void 0===e?"":e)+")_"+ze(++Ge+je,36)},qe=Le,Ye=He,Je=Ke,Xe=ne,Qe=ae,$e=i.Symbol,Ze=qe("wks"),et=Qe?$e.for||$e:$e&&$e.withoutSetter||Je,tt=function(e){return Ye(Ze,e)||(Ze[e]=Xe&&Ye($e,e)?$e[e]:et("Symbol."+e)),Ze[e]},it=c,rt=H,ot=ue,nt=ye,at=function(e,t){var i,r;if("string"===t&&Ie(i=e.toString)&&!Ae(r=Te(i,e)))return r;if(Ie(i=e.valueOf)&&!Ae(r=Te(i,e)))return r;if("string"!==t&&Ie(i=e.toString)&&!Ae(r=Te(i,e)))return r;throw new Se("Can't convert object to primitive value")},st=TypeError,lt=tt("toPrimitive"),ct=function(e,t){if(!rt(e)||ot(e))return e;var i,r=nt(e,lt);if(r){if(void 0===t&&(t="default"),i=it(r,e,t),!rt(i)||ot(i))return i;throw new st("Can't convert object to primitive value")}return void 0===t&&(t="number"),at(e,t)},dt=ct,ut=ue,ht=function(e){var t=dt(e,"string");return ut(t)?t:t+""},pt=H,mt=i.document,ft=pt(mt)&&pt(mt.createElement),_t=function(e){return ft?mt.createElement(e):{}},gt=_t,Et=!n&&!o(function(){return 7!==Object.defineProperty(gt("div"),"a",{get:function(){return 7}}).a}),vt=n,yt=c,Tt=d,It=_,At=U,St=ht,Rt=He,bt=Et,wt=Object.getOwnPropertyDescriptor;r.f=vt?wt:function(e,t){if(e=At(e),t=St(t),bt)try{return wt(e,t)}catch(i){}if(Rt(e,t))return It(!yt(Tt.f,e,t),e[t])};var Ct={},Dt=n&&o(function(){return 42!==Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype}),Nt=H,kt=String,Ot=TypeError,Mt=function(e){if(Nt(e))return e;throw new Ot(kt(e)+" is not an object")},Pt=n,Lt=Et,xt=Dt,Ut=Mt,Vt=ht,Ft=TypeError,Bt=Object.defineProperty,Ht=Object.getOwnPropertyDescriptor,Wt="enumerable",Gt="configurable",jt="writable";Ct.f=Pt?xt?function(e,t,i){if(Ut(e),t=Vt(t),Ut(i),"function"==typeof e&&"prototype"===t&&"value"in i&&jt in i&&!i[jt]){var r=Ht(e,t);r&&r[jt]&&(e[t]=i.value,i={configurable:Gt in i?i[Gt]:r[Gt],enumerable:Wt in i?i[Wt]:r[Wt],writable:!1})}return Bt(e,t,i)}:Bt:function(e,t,i){if(Ut(e),t=Vt(t),Ut(i),Lt)try{return Bt(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Ft("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var zt=Ct,Kt=_,qt=n?function(e,t,i){return zt.f(e,t,Kt(1,i))}:function(e,t,i){return e[t]=i,e},Yt={exports:{}},Jt=n,Xt=He,Qt=Function.prototype,$t=Jt&&Object.getOwnPropertyDescriptor,Zt=Xt(Qt,"name"),ei={EXISTS:Zt,PROPER:Zt&&"something"===function(){}.name,CONFIGURABLE:Zt&&(!Jt||Jt&&$t(Qt,"name").configurable)},ti=F,ii=Me,ri=T(Function.toString);ti(ii.inspectSource)||(ii.inspectSource=function(e){return ri(e)});var oi,ni,ai,si=ii.inspectSource,li=F,ci=i.WeakMap,di=li(ci)&&/native code/.test(String(ci)),ui=Ke,hi=Le("keys"),pi=function(e){return hi[e]||(hi[e]=ui(e))},mi={},fi=di,_i=i,gi=H,Ei=qt,vi=He,yi=Me,Ti=pi,Ii=mi,Ai="Object already initialized",Si=_i.TypeError,Ri=_i.WeakMap;if(fi||yi.state){var bi=yi.state||(yi.state=new Ri);bi.get=bi.get,bi.has=bi.has,bi.set=bi.set,oi=function(e,t){if(bi.has(e))throw new Si(Ai);return t.facade=e,bi.set(e,t),t},ni=function(e){return bi.get(e)||{}},ai=function(e){return bi.has(e)}}else{var wi=Ti("state");Ii[wi]=!0,oi=function(e,t){if(vi(e,wi))throw new Si(Ai);return t.facade=e,Ei(e,wi,t),t},ni=function(e){return vi(e,wi)?e[wi]:{}},ai=function(e){return vi(e,wi)}}var Ci={set:oi,get:ni,has:ai,enforce:function(e){return ai(e)?ni(e):oi(e,{})},getterFor:function(e){return function(t){var i;if(!gi(t)||(i=ni(t)).type!==e)throw new Si("Incompatible receiver, "+e+" required");return i}}},Di=T,Ni=o,ki=F,Oi=He,Mi=n,Pi=ei.CONFIGURABLE,Li=si,xi=Ci.enforce,Ui=Ci.get,Vi=String,Fi=Object.defineProperty,Bi=Di("".slice),Hi=Di("".replace),Wi=Di([].join),Gi=Mi&&!Ni(function(){return 8!==Fi(function(){},"length",{value:8}).length}),ji=String(String).split("String"),zi=Yt.exports=function(e,t,i){"Symbol("===Bi(Vi(t),0,7)&&(t="["+Hi(Vi(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Oi(e,"name")||Pi&&e.name!==t)&&(Mi?Fi(e,"name",{value:t,configurable:!0}):e.name=t),Gi&&i&&Oi(i,"arity")&&e.length!==i.arity&&Fi(e,"length",{value:i.arity});try{i&&Oi(i,"constructor")&&i.constructor?Mi&&Fi(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(o){}var r=xi(e);return Oi(r,"source")||(r.source=Wi(ji,"string"==typeof t?t:"")),e};Function.prototype.toString=zi(function(){return ki(this)&&Ui(this).source||Li(this)},"toString");var Ki=Yt.exports,qi=F,Yi=Ct,Ji=Ki,Xi=Ce,Qi=function(e,t,i,r){r||(r={});var o=r.enumerable,n=void 0!==r.name?r.name:t;if(qi(i)&&Ji(i,n,r),r.global)o?e[t]=i:Xi(t,i);else{try{r.unsafe?e[t]&&(o=!0):delete e[t]}catch(a){}o?e[t]=i:Yi.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},$i={},Zi=Math.ceil,er=Math.floor,tr=Math.trunc||function(e){var t=+e;return(t>0?er:Zi)(t)},ir=tr,rr=function(e){var t=+e;return t!=t||0===t?0:ir(t)},or=rr,nr=Math.max,ar=Math.min,sr=function(e,t){var i=or(e);return i<0?nr(i+t,0):ar(i,t)},lr=rr,cr=Math.min,dr=function(e){var t=lr(e);return t>0?cr(t,9007199254740991):0},ur=dr,hr=function(e){return ur(e.length)},pr=U,mr=sr,fr=hr,_r=function(e){return function(t,i,r){var o=pr(t),n=fr(o);if(0===n)return!e&&-1;var a,s=mr(r,n);if(e&&i!=i){for(;n>s;)if((a=o[s++])!=a)return!0}else for(;n>s;s++)if((e||s in o)&&o[s]===i)return e||s||0;return!e&&-1}},gr={includes:_r(!0),indexOf:_r(!1)},Er=He,vr=U,yr=gr.indexOf,Tr=mi,Ir=T([].push),Ar=function(e,t){var i,r=vr(e),o=0,n=[];for(i in r)!Er(Tr,i)&&Er(r,i)&&Ir(n,i);for(;t.length>o;)Er(r,i=t[o++])&&(~yr(n,i)||Ir(n,i));return n},Sr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Rr=Ar,br=Sr.concat("length","prototype");$i.f=Object.getOwnPropertyNames||function(e){return Rr(e,br)};var wr={};wr.f=Object.getOwnPropertySymbols;var Cr=j,Dr=$i,Nr=wr,kr=Mt,Or=T([].concat),Mr=Cr("Reflect","ownKeys")||function(e){var t=Dr.f(kr(e)),i=Nr.f;return i?Or(t,i(e)):t},Pr=He,Lr=Mr,xr=r,Ur=Ct,Vr=function(e,t,i){for(var r=Lr(t),o=Ur.f,n=xr.f,a=0;a<r.length;a++){var s=r[a];Pr(e,s)||i&&Pr(i,s)||o(e,s,n(t,s))}},Fr=o,Br=F,Hr=/#|\.prototype\./,Wr=function(e,t){var i=jr[Gr(e)];return i===Kr||i!==zr&&(Br(t)?Fr(t):!!t)},Gr=Wr.normalize=function(e){return String(e).replace(Hr,".").toLowerCase()},jr=Wr.data={},zr=Wr.NATIVE="N",Kr=Wr.POLYFILL="P",qr=Wr,Yr=i,Jr=r.f,Xr=qt,Qr=Qi,$r=Ce,Zr=Vr,eo=qr,to=function(e,t){var i,r,o,n,a,s=e.target,l=e.global,c=e.stat;if(i=l?Yr:c?Yr[s]||$r(s,{}):Yr[s]&&Yr[s].prototype)for(r in t){if(n=t[r],o=e.dontCallGetSet?(a=Jr(i,r))&&a.value:i[r],!eo(l?r:s+(c?".":"#")+r,e.forced)&&void 0!==o){if(typeof n==typeof o)continue;Zr(n,o)}(e.sham||o&&o.sham)&&Xr(n,"sham",!0),Qr(i,r,n,e)}},io={};io[tt("toStringTag")]="z";var ro="[object z]"===String(io),oo=F,no=R,ao=tt("toStringTag"),so=Object,lo="Arguments"===no(function(){return arguments}()),co=ro?no: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=so(e),ao))?i:lo?no(t):"Object"===(r=no(t))&&oo(t.callee)?"Arguments":r},uo=co,ho=String,po=function(e){if("Symbol"===uo(e))throw new TypeError("Cannot convert a Symbol value to a string");return ho(e)},mo=Ki,fo=Ct,_o=function(e,t,i){return i.get&&mo(i.get,t,{getter:!0}),i.set&&mo(i.set,t,{setter:!0}),fo.f(e,t,i)},go=to,Eo=n,vo=T,yo=He,To=F,Io=z,Ao=po,So=_o,Ro=Vr,bo=i.Symbol,wo=bo&&bo.prototype;if(Eo&&To(bo)&&(!("description"in wo)||void 0!==bo().description)){var Co={},Do=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:Ao(arguments[0]),t=Io(wo,this)?new bo(e):void 0===e?bo():bo(e);return""===e&&(Co[t]=!0),t};Ro(Do,bo),Do.prototype=wo,wo.constructor=Do;var No="Symbol(description detection)"===String(bo("description detection")),ko=vo(wo.valueOf),Oo=vo(wo.toString),Mo=/^Symbol\((.*)\)[^)]+$/,Po=vo("".replace),Lo=vo("".slice);So(wo,"description",{configurable:!0,get:function(){var e=ko(this);if(yo(Co,e))return"";var t=Oo(e),i=No?Lo(t,7,-1):Po(t,Mo,"$1");return""===i?void 0:i}}),go({global:!0,constructor:!0,forced:!0},{Symbol:Do})}var xo=i,Uo={},Vo=tt;Uo.f=Vo;var Fo=xo,Bo=He,Ho=Uo,Wo=Ct.f,Go=function(e){var t=Fo.Symbol||(Fo.Symbol={});Bo(t,e)||Wo(t,e,{value:Ho.f(e)})};Go("asyncIterator");var jo=R,zo=Array.isArray||function(e){return"Array"===jo(e)},Ko=TypeError,qo=R,Yo=T,Jo=function(e){if("Function"===qo(e))return Yo(e)},Xo=ge,Qo=a,$o=Jo(Jo.bind),Zo=function(e,t){return Xo(e),void 0===t?e:Qo?$o(e,t):function(){return e.apply(t,arguments)}},en=zo,tn=hr,rn=function(e){if(e>9007199254740991)throw Ko("Maximum allowed index exceeded");return e},on=Zo,nn=function(e,t,i,r,o,n,a,s){for(var l,c,d=o,u=0,h=!!a&&on(a,s);u<r;)u in i&&(l=h?h(i[u],u,t):i[u],n>0&&en(l)?(c=tn(l),d=nn(e,t,l,c,d,n-1)-1):(rn(d+1),e[d]=l),d++),u++;return d},an=nn,sn=T,ln=o,cn=F,dn=co,un=si,hn=function(){},pn=j("Reflect","construct"),mn=/^\s*(?:class|function)\b/,fn=sn(mn.exec),_n=!mn.test(hn),gn=function(e){if(!cn(e))return!1;try{return pn(hn,[],e),!0}catch(t){return!1}},En=function(e){if(!cn(e))return!1;switch(dn(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return _n||!!fn(mn,un(e))}catch(t){return!0}};En.sham=!0;var vn=!pn||ln(function(){var e;return gn(gn.call)||!gn(Object)||!gn(function(){e=!0})||e})?En:gn,yn=zo,Tn=vn,In=H,An=tt("species"),Sn=Array,Rn=function(e){var t;return yn(e)&&(t=e.constructor,(Tn(t)&&(t===Sn||yn(t.prototype))||In(t)&&null===(t=t[An]))&&(t=void 0)),void 0===t?Sn:t},bn=function(e,t){return new(Rn(e))(0===t?0:t)},wn=an,Cn=Ve,Dn=hr,Nn=rr,kn=bn;to({target:"Array",proto:!0},{flat:function(){var e=arguments.length?arguments[0]:void 0,t=Cn(this),i=Dn(t),r=kn(t,0);return r.length=wn(r,t,t,i,0,void 0===e?1:Nn(e)),r}});var On={},Mn=Ar,Pn=Sr,Ln=Object.keys||function(e){return Mn(e,Pn)},xn=n,Un=Dt,Vn=Ct,Fn=Mt,Bn=U,Hn=Ln;On.f=xn&&!Un?Object.defineProperties:function(e,t){Fn(e);for(var i,r=Bn(t),o=Hn(t),n=o.length,a=0;n>a;)Vn.f(e,i=o[a++],r[i]);return e};var Wn,Gn=j("document","documentElement"),jn=Mt,zn=On,Kn=Sr,qn=mi,Yn=Gn,Jn=_t,Xn="prototype",Qn="script",$n=pi("IE_PROTO"),Zn=function(){},ea=function(e){return"<"+Qn+">"+e+"</"+Qn+">"},ta=function(e){e.write(ea("")),e.close();var t=e.parentWindow.Object;return e=null,t},ia=function(){try{Wn=new ActiveXObject("htmlfile")}catch(t){}ia="undefined"!=typeof document?document.domain&&Wn?ta(Wn):function(){var e,t=Jn("iframe"),i="java"+Qn+":";return t.style.display="none",Yn.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(ea("document.F=Object")),e.close(),e.F}():ta(Wn);for(var e=Kn.length;e--;)delete ia[Xn][Kn[e]];return ia()};qn[$n]=!0;var ra=Object.create||function(e,t){var i;return null!==e?(Zn[Xn]=jn(e),i=new Zn,Zn[Xn]=null,i[$n]=e):i=ia(),void 0===t?i:zn.f(i,t)},oa=tt,na=ra,aa=Ct.f,sa=oa("unscopables"),la=Array.prototype;void 0===la[sa]&&aa(la,sa,{configurable:!0,value:na(null)});var ca=function(e){la[sa][e]=!0},da=gr.includes,ua=ca;to({target:"Array",proto:!0,forced:o(function(){return!Array(1).includes()})},{includes:function(e){return da(this,e,arguments.length>1?arguments[1]:void 0)}}),ua("includes");var ha,pa,ma,fa={},_a=!o(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),ga=He,Ea=F,va=Ve,ya=_a,Ta=pi("IE_PROTO"),Ia=Object,Aa=Ia.prototype,Sa=ya?Ia.getPrototypeOf:function(e){var t=va(e);if(ga(t,Ta))return t[Ta];var i=t.constructor;return Ea(i)&&t instanceof i?i.prototype:t instanceof Ia?Aa:null},Ra=o,ba=F,wa=H,Ca=Sa,Da=Qi,Na=tt("iterator"),ka=!1;[].keys&&("next"in(ma=[].keys())?(pa=Ca(Ca(ma)))!==Object.prototype&&(ha=pa):ka=!0);var Oa=!wa(ha)||Ra(function(){var e={};return ha[Na].call(e)!==e});Oa&&(ha={}),ba(ha[Na])||Da(ha,Na,function(){return this});var Ma={IteratorPrototype:ha,BUGGY_SAFARI_ITERATORS:ka},Pa=Ct.f,La=He,xa=tt("toStringTag"),Ua=function(e,t,i){e&&!i&&(e=e.prototype),e&&!La(e,xa)&&Pa(e,xa,{configurable:!0,value:t})},Va=Ma.IteratorPrototype,Fa=ra,Ba=_,Ha=Ua,Wa=fa,Ga=function(){return this},ja=function(e,t,i,r){var o=t+" Iterator";return e.prototype=Fa(Va,{next:Ba(+!r,i)}),Ha(e,o,!1),Wa[o]=Ga,e},za=T,Ka=ge,qa=H,Ya=function(e){return qa(e)||null===e},Ja=String,Xa=TypeError,Qa=function(e,t,i){try{return za(Ka(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},$a=H,Za=P,es=function(e){if(Ya(e))return e;throw new Xa("Can't set "+Ja(e)+" as a prototype")},ts=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Qa(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return Za(i),es(r),$a(i)?(t?e(i,r):i.__proto__=r,i):i}}():void 0),is=to,rs=c,os=F,ns=ja,as=Sa,ss=ts,ls=Ua,cs=qt,ds=Qi,us=fa,hs=ei.PROPER,ps=ei.CONFIGURABLE,ms=Ma.IteratorPrototype,fs=Ma.BUGGY_SAFARI_ITERATORS,_s=tt("iterator"),gs="keys",Es="values",vs="entries",ys=function(){return this},Ts=function(e,t,i,r,o,n,a){ns(i,t,r);var s,l,c,d=function(e){if(e===o&&f)return f;if(!fs&&e&&e in p)return p[e];switch(e){case gs:case Es:case vs:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[_s]||p["@@iterator"]||o&&p[o],f=!fs&&m||d(o),_="Array"===t&&p.entries||m;if(_&&(s=as(_.call(new e)))!==Object.prototype&&s.next&&(as(s)!==ms&&(ss?ss(s,ms):os(s[_s])||ds(s,_s,ys)),ls(s,u,!0)),hs&&o===Es&&m&&m.name!==Es&&(ps?cs(p,"name",Es):(h=!0,f=function(){return rs(m,this)})),o)if(l={values:d(Es),keys:n?f:d(gs),entries:d(vs)},a)for(c in l)(fs||h||!(c in p))&&ds(p,c,l[c]);else is({target:t,proto:!0,forced:fs||h},l);return p[_s]!==f&&ds(p,_s,f,{name:o}),us[t]=f,l},Is=function(e,t){return{value:e,done:t}},As=U,Ss=ca,Rs=fa,bs=Ci,ws=Ct.f,Cs=Ts,Ds=Is,Ns=n,ks="Array Iterator",Os=bs.set,Ms=bs.getterFor(ks),Ps=Cs(Array,"Array",function(e,t){Os(this,{type:ks,target:As(e),index:0,kind:t})},function(){var e=Ms(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,Ds(void 0,!0);switch(e.kind){case"keys":return Ds(i,!1);case"values":return Ds(t[i],!1)}return Ds([i,t[i]],!1)},"values"),Ls=Rs.Arguments=Rs.Array;if(Ss("keys"),Ss("values"),Ss("entries"),Ns&&"values"!==Ls.name)try{ws(Ls,"name",{value:"values"})}catch(uq){}var xs=ge,Us=Ve,Vs=N,Fs=hr,Bs=TypeError,Hs="Reduce of empty array with no initial value",Ws=function(e){return function(t,i,r,o){var n=Us(t),a=Vs(n),s=Fs(n);if(xs(i),0===s&&r<2)throw new Bs(Hs);var l=e?s-1:0,c=e?-1:1;if(r<2)for(;;){if(l in a){o=a[l],l+=c;break}if(l+=c,e?l<0:s<=l)throw new Bs(Hs)}for(;e?l>=0:s>l;l+=c)l in a&&(o=i(o,a[l],l,n));return o}},Gs={left:Ws(!1),right:Ws(!0)},js=o,zs=function(e,t){var i=[][e];return!!i&&js(function(){i.call(null,t||function(){return 1},1)})},Ks=i,qs=Y,Ys=R,Js=function(e){return qs.slice(0,e.length)===e},Xs=Js("Bun/")?"BUN":Js("Cloudflare-Workers")?"CLOUDFLARE":Js("Deno/")?"DENO":Js("Node.js/")?"NODE":Ks.Bun&&"string"==typeof Bun.version?"BUN":Ks.Deno&&"object"==typeof Deno.version?"DENO":"process"===Ys(Ks.process)?"NODE":Ks.window&&Ks.document?"BROWSER":"REST",Qs="NODE"===Xs,$s=Gs.left;to({target:"Array",proto:!0,forced:!Qs&&te>79&&te<83||!zs("reduce")},{reduce:function(e){var t=arguments.length;return $s(this,e,t,t>1?arguments[1]:void 0)}});var Zs=Gs.right;to({target:"Array",proto:!0,forced:!Qs&&te>79&&te<83||!zs("reduceRight")},{reduceRight:function(e){return Zs(this,e,arguments.length,arguments.length>1?arguments[1]:void 0)}});var el=to,tl=zo,il=T([].reverse),rl=[1,2];el({target:"Array",proto:!0,forced:String(rl)===String(rl.reverse())},{reverse:function(){return tl(this)&&(this.length=this.length),il(this)}});var ol=pe,nl=TypeError,al=T([].slice),sl=al,ll=Math.floor,cl=function(e,t){var i=e.length;if(i<8)for(var r,o,n=1;n<i;){for(o=n,r=e[n];o&&t(e[o-1],r)>0;)e[o]=e[--o];o!==n++&&(e[o]=r)}else for(var a=ll(i/2),s=cl(sl(e,0,a),t),l=cl(sl(e,a),t),c=s.length,d=l.length,u=0,h=0;u<c||h<d;)e[u+h]=u<c&&h<d?t(s[u],l[h])<=0?s[u++]:l[h++]:u<c?s[u++]:l[h++];return e},dl=cl,ul=Y.match(/firefox\/(\d+)/i),hl=!!ul&&+ul[1],pl=/MSIE|Trident/.test(Y),ml=Y.match(/AppleWebKit\/(\d+)\./),fl=!!ml&&+ml[1],_l=to,gl=T,El=ge,vl=Ve,yl=hr,Tl=function(e,t){if(!delete e[t])throw new nl("Cannot delete property "+ol(t)+" of "+ol(e))},Il=po,Al=o,Sl=dl,Rl=zs,bl=hl,wl=pl,Cl=te,Dl=fl,Nl=[],kl=gl(Nl.sort),Ol=gl(Nl.push),Ml=Al(function(){Nl.sort(void 0)}),Pl=Al(function(){Nl.sort(null)}),Ll=Rl("sort"),xl=!Al(function(){if(Cl)return Cl<70;if(!(bl&&bl>3)){if(wl)return!0;if(Dl)return Dl<603;var e,t,i,r,o="";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++)Nl.push({k:t+r,v:i})}for(Nl.sort(function(e,t){return t.v-e.v}),r=0;r<Nl.length;r++)t=Nl[r].k.charAt(0),o.charAt(o.length-1)!==t&&(o+=t);return"DGBEFHACIJK"!==o}});_l({target:"Array",proto:!0,forced:Ml||!Pl||!Ll||!xl},{sort:function(e){void 0!==e&&El(e);var t=vl(this);if(xl)return void 0===e?kl(t):kl(t,e);var i,r,o=[],n=yl(t);for(r=0;r<n;r++)r in t&&Ol(o,t[r]);for(Sl(o,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:Il(t)>Il(i)?1:-1}}(e)),i=yl(o),r=0;r<i;)t[r]=o[r++];for(;r<n;)Tl(t,r++);return t}}),ca("flat");var Ul="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,Vl=Qi,Fl=function(e,t,i){for(var r in t)Vl(e,r,t[r],i);return e},Bl=z,Hl=TypeError,Wl=function(e,t){if(Bl(t,e))return e;throw new Hl("Incorrect invocation")},Gl=rr,jl=dr,zl=RangeError,Kl=function(e){if(void 0===e)return 0;var t=Gl(e),i=jl(t);if(t!==i)throw new zl("Wrong length or index");return i},ql=Math.sign||function(e){var t=+e;return 0===t||t!=t?t:t<0?-1:1},Yl=4503599627370496,Jl=ql,Xl=function(e){return e+Yl-Yl},Ql=Math.abs,$l=function(e,t,i,r){var o=+e,n=Ql(o),a=Jl(o);if(n<r)return a*Xl(n/r/t)*r*t;var s=(1+t/2220446049250313e-31)*n,l=s-(s-n);return l>i||l!=l?Infinity*a:a*l},Zl=Math.fround||function(e){return $l(e,1.1920928955078125e-7,34028234663852886e22,11754943508222875e-54)},ec=Array,tc=Math.abs,ic=Math.pow,rc=Math.floor,oc=Math.log,nc=Math.LN2,ac={pack:function(e,t,i){var r,o,n,a=ec(i),s=8*i-t-1,l=(1<<s)-1,c=l>>1,d=23===t?ic(2,-24)-ic(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=tc(e))!=e||Infinity===e?(o=e!=e?1:0,r=l):(r=rc(oc(e)/nc),e*(n=ic(2,-r))<1&&(r--,n*=2),(e+=r+c>=1?d/n:d*ic(2,1-c))*n>=2&&(r++,n/=2),r+c>=l?(o=0,r=l):r+c>=1?(o=(e*n-1)*ic(2,t),r+=c):(o=e*ic(2,c-1)*ic(2,t),r=0));t>=8;)a[h++]=255&o,o/=256,t-=8;for(r=r<<t|o,s+=t;s>0;)a[h++]=255&r,r/=256,s-=8;return a[h-1]|=128*u,a},unpack:function(e,t){var i,r=e.length,o=8*r-t-1,n=(1<<o)-1,a=n>>1,s=o-7,l=r-1,c=e[l--],d=127&c;for(c>>=7;s>0;)d=256*d+e[l--],s-=8;for(i=d&(1<<-s)-1,d>>=-s,s+=t;s>0;)i=256*i+e[l--],s-=8;if(0===d)d=1-a;else{if(d===n)return i?NaN:c?-Infinity:Infinity;i+=ic(2,t),d-=a}return(c?-1:1)*i*ic(2,d-t)}},sc=Ve,lc=sr,cc=hr,dc=function(e){for(var t=sc(this),i=cc(t),r=arguments.length,o=lc(r>1?arguments[1]:void 0,i),n=r>2?arguments[2]:void 0,a=void 0===n?i:lc(n,i);a>o;)t[o++]=e;return t},uc=F,hc=H,pc=ts,mc=function(e,t,i){var r,o;return pc&&uc(r=t.constructor)&&r!==i&&hc(o=r.prototype)&&o!==i.prototype&&pc(e,o),e},fc=i,_c=T,gc=n,Ec=Ul,vc=qt,yc=_o,Tc=Fl,Ic=o,Ac=Wl,Sc=rr,Rc=dr,bc=Kl,wc=Zl,Cc=ac,Dc=Sa,Nc=ts,kc=dc,Oc=al,Mc=mc,Pc=Vr,Lc=Ua,xc=Ci,Uc=ei.PROPER,Vc=ei.CONFIGURABLE,Fc="ArrayBuffer",Bc="DataView",Hc="prototype",Wc="Wrong index",Gc=xc.getterFor(Fc),jc=xc.getterFor(Bc),zc=xc.set,Kc=fc[Fc],qc=Kc,Yc=qc&&qc[Hc],Jc=fc[Bc],Xc=Jc&&Jc[Hc],Qc=Object.prototype,$c=fc.Array,Zc=fc.RangeError,ed=_c(kc),td=_c([].reverse),id=Cc.pack,rd=Cc.unpack,od=function(e){return[255&e]},nd=function(e){return[255&e,e>>8&255]},ad=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},sd=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},ld=function(e){return id(wc(e),23,4)},cd=function(e){return id(e,52,8)},dd=function(e,t,i){yc(e[Hc],t,{configurable:!0,get:function(){return i(this)[t]}})},ud=function(e,t,i,r){var o=jc(e),n=bc(i),a=!!r;if(n+t>o.byteLength)throw new Zc(Wc);var s=o.bytes,l=n+o.byteOffset,c=Oc(s,l,l+t);return a?c:td(c)},hd=function(e,t,i,r,o,n){var a=jc(e),s=bc(i),l=r(+o),c=!!n;if(s+t>a.byteLength)throw new Zc(Wc);for(var d=a.bytes,u=s+a.byteOffset,h=0;h<t;h++)d[u+h]=l[c?h:t-h-1]};if(Ec){var pd=Uc&&Kc.name!==Fc;Ic(function(){Kc(1)})&&Ic(function(){new Kc(-1)})&&!Ic(function(){return new Kc,new Kc(1.5),new Kc(NaN),1!==Kc.length||pd&&!Vc})?pd&&Vc&&vc(Kc,"name",Fc):((qc=function(e){return Ac(this,Yc),Mc(new Kc(bc(e)),this,qc)})[Hc]=Yc,Yc.constructor=qc,Pc(qc,Kc)),Nc&&Dc(Xc)!==Qc&&Nc(Xc,Qc);var md=new Jc(new qc(2)),fd=_c(Xc.setInt8);md.setInt8(0,2147483648),md.setInt8(1,2147483649),!md.getInt8(0)&&md.getInt8(1)||Tc(Xc,{setInt8:function(e,t){fd(this,e,t<<24>>24)},setUint8:function(e,t){fd(this,e,t<<24>>24)}},{unsafe:!0})}else Yc=(qc=function(e){Ac(this,Yc);var t=bc(e);zc(this,{type:Fc,bytes:ed($c(t),0),byteLength:t}),gc||(this.byteLength=t,this.detached=!1)})[Hc],Xc=(Jc=function(e,t,i){Ac(this,Xc),Ac(e,Yc);var r=Gc(e),o=r.byteLength,n=Sc(t);if(n<0||n>o)throw new Zc("Wrong offset");if(n+(i=void 0===i?o-n:Rc(i))>o)throw new Zc("Wrong length");zc(this,{type:Bc,buffer:e,byteLength:i,byteOffset:n,bytes:r.bytes}),gc||(this.buffer=e,this.byteLength=i,this.byteOffset=n)})[Hc],gc&&(dd(qc,"byteLength",Gc),dd(Jc,"buffer",jc),dd(Jc,"byteLength",jc),dd(Jc,"byteOffset",jc)),Tc(Xc,{getInt8:function(e){return ud(this,1,e)[0]<<24>>24},getUint8:function(e){return ud(this,1,e)[0]},getInt16:function(e){var t=ud(this,2,e,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=ud(this,2,e,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return sd(ud(this,4,e,arguments.length>1&&arguments[1]))},getUint32:function(e){return sd(ud(this,4,e,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(e){return rd(ud(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return rd(ud(this,8,e,arguments.length>1&&arguments[1]),52)},setInt8:function(e,t){hd(this,1,e,od,t)},setUint8:function(e,t){hd(this,1,e,od,t)},setInt16:function(e,t){hd(this,2,e,nd,t,arguments.length>2&&arguments[2])},setUint16:function(e,t){hd(this,2,e,nd,t,arguments.length>2&&arguments[2])},setInt32:function(e,t){hd(this,4,e,ad,t,arguments.length>2&&arguments[2])},setUint32:function(e,t){hd(this,4,e,ad,t,arguments.length>2&&arguments[2])},setFloat32:function(e,t){hd(this,4,e,ld,t,arguments.length>2&&arguments[2])},setFloat64:function(e,t){hd(this,8,e,cd,t,arguments.length>2&&arguments[2])}});Lc(qc,Fc),Lc(Jc,Bc);var _d={ArrayBuffer:qc,DataView:Jc},gd=j,Ed=_o,vd=n,yd=tt("species"),Td=function(e){var t=gd(e);vd&&t&&!t[yd]&&Ed(t,yd,{configurable:!0,get:function(){return this}})},Id=Td,Ad="ArrayBuffer",Sd=_d[Ad];to({global:!0,constructor:!0,forced:i[Ad]!==Sd},{ArrayBuffer:Sd}),Id(Ad);var Rd=to,bd=Jo,wd=o,Cd=Mt,Dd=sr,Nd=dr,kd=_d.ArrayBuffer,Od=_d.DataView,Md=Od.prototype,Pd=bd(kd.prototype.slice),Ld=bd(Md.getUint8),xd=bd(Md.setUint8);Rd({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:wd(function(){return!new kd(2).slice(1,void 0).byteLength})},{slice:function(e,t){if(Pd&&void 0===t)return Pd(Cd(this),e);for(var i=Cd(this).byteLength,r=Dd(e,i),o=Dd(void 0===t?i:t,i),n=new kd(Nd(o-r)),a=new Od(this),s=new Od(n),l=0;r<o;)xd(s,l++,Ld(a,r++));return n}});var Ud,Vd,Fd,Bd,Hd=vn,Wd=pe,Gd=TypeError,jd=function(e){if(Hd(e))return e;throw new Gd(Wd(e)+" is not a constructor")},zd=Mt,Kd=jd,qd=k,Yd=tt("species"),Jd=function(e,t){var i,r=zd(e).constructor;return void 0===r||qd(i=zd(r)[Yd])?t:Kd(i)},Xd=a,Qd=Function.prototype,$d=Qd.apply,Zd=Qd.call,eu="object"==typeof Reflect&&Reflect.apply||(Xd?Zd.bind($d):function(){return Zd.apply($d,arguments)}),tu=TypeError,iu=function(e,t){if(e<t)throw new tu("Not enough arguments");return e},ru=/(?:ipad|iphone|ipod).*applewebkit/i.test(Y),ou=i,nu=eu,au=Zo,su=F,lu=He,cu=o,du=Gn,uu=al,hu=_t,pu=iu,mu=ru,fu=Qs,_u=ou.setImmediate,gu=ou.clearImmediate,Eu=ou.process,vu=ou.Dispatch,yu=ou.Function,Tu=ou.MessageChannel,Iu=ou.String,Au=0,Su={},Ru="onreadystatechange";cu(function(){Ud=ou.location});var bu=function(e){if(lu(Su,e)){var t=Su[e];delete Su[e],t()}},wu=function(e){return function(){bu(e)}},Cu=function(e){bu(e.data)},Du=function(e){ou.postMessage(Iu(e),Ud.protocol+"//"+Ud.host)};_u&&gu||(_u=function(e){pu(arguments.length,1);var t=su(e)?e:yu(e),i=uu(arguments,1);return Su[++Au]=function(){nu(t,void 0,i)},Vd(Au),Au},gu=function(e){delete Su[e]},fu?Vd=function(e){Eu.nextTick(wu(e))}:vu&&vu.now?Vd=function(e){vu.now(wu(e))}:Tu&&!mu?(Bd=(Fd=new Tu).port2,Fd.port1.onmessage=Cu,Vd=au(Bd.postMessage,Bd)):ou.addEventListener&&su(ou.postMessage)&&!ou.importScripts&&Ud&&"file:"!==Ud.protocol&&!cu(Du)?(Vd=Du,ou.addEventListener("message",Cu,!1)):Vd=Ru in hu("script")?function(e){du.appendChild(hu("script"))[Ru]=function(){du.removeChild(this),bu(e)}}:function(e){setTimeout(wu(e),0)});var Nu={set:_u,clear:gu},ku=i,Ou=n,Mu=Object.getOwnPropertyDescriptor,Pu=function(e){if(!Ou)return ku[e];var t=Mu(ku,e);return t&&t.value},Lu=function(){this.head=null,this.tail=null};Lu.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var xu,Uu,Vu,Fu,Bu,Hu=Lu,Wu=/ipad|iphone|ipod/i.test(Y)&&"undefined"!=typeof Pebble,Gu=/web0s(?!.*chrome)/i.test(Y),ju=i,zu=Pu,Ku=Zo,qu=Nu.set,Yu=Hu,Ju=ru,Xu=Wu,Qu=Gu,$u=Qs,Zu=ju.MutationObserver||ju.WebKitMutationObserver,eh=ju.document,th=ju.process,ih=ju.Promise,rh=zu("queueMicrotask");if(!rh){var oh=new Yu,nh=function(){var e,t;for($u&&(e=th.domain)&&e.exit();t=oh.get();)try{t()}catch(uq){throw oh.head&&xu(),uq}e&&e.enter()};Ju||$u||Qu||!Zu||!eh?!Xu&&ih&&ih.resolve?((Fu=ih.resolve(void 0)).constructor=ih,Bu=Ku(Fu.then,Fu),xu=function(){Bu(nh)}):$u?xu=function(){th.nextTick(nh)}:(qu=Ku(qu,ju),xu=function(){qu(nh)}):(Uu=!0,Vu=eh.createTextNode(""),new Zu(nh).observe(Vu,{characterData:!0}),xu=function(){Vu.data=Uu=!Uu}),rh=function(e){oh.head||xu(),oh.add(e)}}var ah=rh,sh=function(e){try{return{error:!1,value:e()}}catch(uq){return{error:!0,value:uq}}},lh=i.Promise,ch=i,dh=lh,uh=F,hh=qr,ph=si,mh=tt,fh=Xs,_h=te;dh&&dh.prototype;var gh=mh("species"),Eh=!1,vh=uh(ch.PromiseRejectionEvent),yh=hh("Promise",function(){var e=ph(dh),t=e!==String(dh);if(!t&&66===_h)return!0;if(!_h||_h<51||!/native code/.test(e)){var i=new dh(function(e){e(1)}),r=function(e){e(function(){},function(){})};if((i.constructor={})[gh]=r,!(Eh=i.then(function(){})instanceof r))return!0}return!(t||"BROWSER"!==fh&&"DENO"!==fh||vh)}),Th={CONSTRUCTOR:yh,REJECTION_EVENT:vh,SUBCLASSING:Eh},Ih={},Ah=ge,Sh=TypeError,Rh=function(e){var t,i;this.promise=new e(function(e,r){if(void 0!==t||void 0!==i)throw new Sh("Bad Promise constructor");t=e,i=r}),this.resolve=Ah(t),this.reject=Ah(i)};Ih.f=function(e){return new Rh(e)};var bh,wh,Ch,Dh,Nh=to,kh=Qs,Oh=i,Mh=xo,Ph=c,Lh=Qi,xh=ts,Uh=Ua,Vh=Td,Fh=ge,Bh=F,Hh=H,Wh=Wl,Gh=Jd,jh=Nu.set,zh=ah,Kh=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(uq){}},qh=sh,Yh=Hu,Jh=Ci,Xh=lh,Qh=Ih,$h="Promise",Zh=Th.CONSTRUCTOR,ep=Th.REJECTION_EVENT,tp=Th.SUBCLASSING,ip=Jh.getterFor($h),rp=Jh.set,op=Xh&&Xh.prototype,np=Xh,ap=op,sp=Oh.TypeError,lp=Oh.document,cp=Oh.process,dp=Qh.f,up=dp,hp=!!(lp&&lp.createEvent&&Oh.dispatchEvent),pp="unhandledrejection",mp=function(e){var t;return!(!Hh(e)||!Bh(t=e.then))&&t},fp=function(e,t){var i,r,o,n=t.value,a=1===t.state,s=a?e.ok:e.fail,l=e.resolve,c=e.reject,d=e.domain;try{s?(a||(2===t.rejection&&yp(t),t.rejection=1),!0===s?i=n:(d&&d.enter(),i=s(n),d&&(d.exit(),o=!0)),i===e.promise?c(new sp("Promise-chain cycle")):(r=mp(i))?Ph(r,i,l,c):l(i)):c(n)}catch(uq){d&&!o&&d.exit(),c(uq)}},_p=function(e,t){e.notified||(e.notified=!0,zh(function(){for(var i,r=e.reactions;i=r.get();)fp(i,e);e.notified=!1,t&&!e.rejection&&Ep(e)}))},gp=function(e,t,i){var r,o;hp?((r=lp.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),Oh.dispatchEvent(r)):r={promise:t,reason:i},!ep&&(o=Oh["on"+e])?o(r):e===pp&&Kh("Unhandled promise rejection",i)},Ep=function(e){Ph(jh,Oh,function(){var t,i=e.facade,r=e.value;if(vp(e)&&(t=qh(function(){kh?cp.emit("unhandledRejection",r,i):gp(pp,i,r)}),e.rejection=kh||vp(e)?2:1,t.error))throw t.value})},vp=function(e){return 1!==e.rejection&&!e.parent},yp=function(e){Ph(jh,Oh,function(){var t=e.facade;kh?cp.emit("rejectionHandled",t):gp("rejectionhandled",t,e.value)})},Tp=function(e,t,i){return function(r){e(t,r,i)}},Ip=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,_p(e,!0))},Ap=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new sp("Promise can't be resolved itself");var r=mp(t);r?zh(function(){var i={done:!1};try{Ph(r,t,Tp(Ap,i,e),Tp(Ip,i,e))}catch(uq){Ip(i,uq,e)}}):(e.value=t,e.state=1,_p(e,!1))}catch(uq){Ip({done:!1},uq,e)}}};if(Zh&&(ap=(np=function(e){Wh(this,ap),Fh(e),Ph(bh,this);var t=ip(this);try{e(Tp(Ap,t),Tp(Ip,t))}catch(uq){Ip(t,uq)}}).prototype,(bh=function(e){rp(this,{type:$h,done:!1,notified:!1,parent:!1,reactions:new Yh,rejection:!1,state:0,value:null})}).prototype=Lh(ap,"then",function(e,t){var i=ip(this),r=dp(Gh(this,np));return i.parent=!0,r.ok=!Bh(e)||e,r.fail=Bh(t)&&t,r.domain=kh?cp.domain:void 0,0===i.state?i.reactions.add(r):zh(function(){fp(r,i)}),r.promise}),wh=function(){var e=new bh,t=ip(e);this.promise=e,this.resolve=Tp(Ap,t),this.reject=Tp(Ip,t)},Qh.f=dp=function(e){return e===np||e===Ch?new wh(e):up(e)},Bh(Xh)&&op!==Object.prototype)){Dh=op.then,tp||Lh(op,"then",function(e,t){var i=this;return new np(function(e,t){Ph(Dh,i,e,t)}).then(e,t)},{unsafe:!0});try{delete op.constructor}catch(uq){}xh&&xh(op,ap)}Nh({global:!0,constructor:!0,wrap:!0,forced:Zh},{Promise:np}),Ch=Mh.Promise,Uh(np,$h,!1),Vh($h);var Sp=fa,Rp=tt("iterator"),bp=Array.prototype,wp=function(e){return void 0!==e&&(Sp.Array===e||bp[Rp]===e)},Cp=co,Dp=ye,Np=k,kp=fa,Op=tt("iterator"),Mp=function(e){if(!Np(e))return Dp(e,Op)||Dp(e,"@@iterator")||kp[Cp(e)]},Pp=c,Lp=ge,xp=Mt,Up=pe,Vp=Mp,Fp=TypeError,Bp=function(e,t){var i=arguments.length<2?Vp(e):t;if(Lp(i))return xp(Pp(i,e));throw new Fp(Up(e)+" is not iterable")},Hp=c,Wp=Mt,Gp=ye,jp=function(e,t,i){var r,o;Wp(e);try{if(!(r=Gp(e,"return"))){if("throw"===t)throw i;return i}r=Hp(r,e)}catch(uq){o=!0,r=uq}if("throw"===t)throw i;if(o)throw r;return Wp(r),i},zp=Zo,Kp=c,qp=Mt,Yp=pe,Jp=wp,Xp=hr,Qp=z,$p=Bp,Zp=Mp,em=jp,tm=TypeError,im=function(e,t){this.stopped=e,this.result=t},rm=im.prototype,om=function(e,t,i){var r,o,n,a,s,l,c,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),f=zp(t,d),_=function(e){return r&&em(r,"normal"),new im(!0,e)},g=function(e){return u?(qp(e),m?f(e[0],e[1],_):f(e[0],e[1])):m?f(e,_):f(e)};if(h)r=e.iterator;else if(p)r=e;else{if(!(o=Zp(e)))throw new tm(Yp(e)+" is not iterable");if(Jp(o)){for(n=0,a=Xp(e);a>n;n++)if((s=g(e[n]))&&Qp(rm,s))return s;return new im(!1)}r=$p(e,o)}for(l=h?e.next:r.next;!(c=Kp(l,r)).done;){try{s=g(c.value)}catch(uq){em(r,"throw",uq)}if("object"==typeof s&&s&&Qp(rm,s))return s}return new im(!1)},nm=tt("iterator"),am=!1;try{var sm=0,lm={next:function(){return{done:!!sm++}},return:function(){am=!0}};lm[nm]=function(){return this},Array.from(lm,function(){throw 2})}catch(uq){}var cm=function(e,t){try{if(!t&&!am)return!1}catch(uq){return!1}var i=!1;try{var r={};r[nm]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(uq){}return i},dm=lh,um=Th.CONSTRUCTOR||!cm(function(e){dm.all(e).then(void 0,function(){})}),hm=c,pm=ge,mm=Ih,fm=sh,_m=om;to({target:"Promise",stat:!0,forced:um},{all:function(e){var t=this,i=mm.f(t),r=i.resolve,o=i.reject,n=fm(function(){var i=pm(t.resolve),n=[],a=0,s=1;_m(e,function(e){var l=a++,c=!1;s++,hm(i,t,e).then(function(e){c||(c=!0,n[l]=e,--s||r(n))},o)}),--s||r(n)});return n.error&&o(n.value),i.promise}});var gm=to,Em=Th.CONSTRUCTOR,vm=lh,ym=j,Tm=F,Im=Qi,Am=vm&&vm.prototype;if(gm({target:"Promise",proto:!0,forced:Em,real:!0},{catch:function(e){return this.then(void 0,e)}}),Tm(vm)){var Sm=ym("Promise").prototype.catch;Am.catch!==Sm&&Im(Am,"catch",Sm,{unsafe:!0})}var Rm=c,bm=ge,wm=Ih,Cm=sh,Dm=om;to({target:"Promise",stat:!0,forced:um},{race:function(e){var t=this,i=wm.f(t),r=i.reject,o=Cm(function(){var o=bm(t.resolve);Dm(e,function(e){Rm(o,t,e).then(i.resolve,r)})});return o.error&&r(o.value),i.promise}});var Nm=Ih;to({target:"Promise",stat:!0,forced:Th.CONSTRUCTOR},{reject:function(e){var t=Nm.f(this);return(0,t.reject)(e),t.promise}});var km=Mt,Om=H,Mm=Ih,Pm=function(e,t){if(km(e),Om(t)&&t.constructor===e)return t;var i=Mm.f(e);return(0,i.resolve)(t),i.promise},Lm=to,xm=Th.CONSTRUCTOR,Um=Pm;j("Promise"),Lm({target:"Promise",stat:!0,forced:xm},{resolve:function(e){return Um(this,e)}});var Vm=to,Fm=lh,Bm=o,Hm=j,Wm=F,Gm=Jd,jm=Pm,zm=Qi,Km=Fm&&Fm.prototype;if(Vm({target:"Promise",proto:!0,real:!0,forced:!!Fm&&Bm(function(){Km.finally.call({then:function(){}},function(){})})},{finally:function(e){var t=Gm(this,Hm("Promise")),i=Wm(e);return this.then(i?function(i){return jm(t,e()).then(function(){return i})}:e,i?function(i){return jm(t,e()).then(function(){throw i})}:e)}}),Wm(Fm)){var qm=Hm("Promise").prototype.finally;Km.finally!==qm&&zm(Km,"finally",qm,{unsafe:!0})}var Ym=H,Jm=R,Xm=tt("match"),Qm=function(e){var t;return Ym(e)&&(void 0!==(t=e[Xm])?!!t:"RegExp"===Jm(e))},$m=o,Zm=i.RegExp,ef=!$m(function(){var e=!0;try{Zm(".","d")}catch(uq){e=!1}var t={},i="",r=e?"dgimsy":"gimsy",o=function(e,r){Object.defineProperty(t,e,{get:function(){return i+=r,!0}})},n={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var a in e&&(n.hasIndices="d"),n)o(a,n[a]);return Object.getOwnPropertyDescriptor(Zm.prototype,"flags").get.call(t)!==r||i!==r}),tf={correct:ef},rf=Mt,of=function(){var e=rf(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},nf=c,af=He,sf=z,lf=tf,cf=of,df=RegExp.prototype,uf=lf.correct?function(e){return e.flags}:function(e){return lf.correct||!sf(df,e)||af(e,"flags")?e.flags:nf(cf,e)},hf=o,pf=i.RegExp,mf=hf(function(){var e=pf("a","y");return e.lastIndex=2,null!==e.exec("abcd")}),ff=mf||hf(function(){return!pf("a","y").sticky}),_f=mf||hf(function(){var e=pf("^r","gy");return e.lastIndex=2,null!==e.exec("str")}),gf={BROKEN_CARET:_f,MISSED_STICKY:ff,UNSUPPORTED_Y:mf},Ef=Ct.f,vf=o,yf=i.RegExp,Tf=vf(function(){var e=yf(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)}),If=o,Af=i.RegExp,Sf=If(function(){var e=Af("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")}),Rf=n,bf=i,wf=T,Cf=qr,Df=mc,Nf=qt,kf=ra,Of=$i.f,Mf=z,Pf=Qm,Lf=po,xf=uf,Uf=gf,Vf=function(e,t,i){i in e||Ef(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Ff=Qi,Bf=o,Hf=He,Wf=Ci.enforce,Gf=Td,jf=Tf,zf=Sf,Kf=tt("match"),qf=bf.RegExp,Yf=qf.prototype,Jf=bf.SyntaxError,Xf=wf(Yf.exec),Qf=wf("".charAt),$f=wf("".replace),Zf=wf("".indexOf),e_=wf("".slice),t_=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,i_=/a/g,r_=/a/g,o_=new qf(i_)!==i_,n_=Uf.MISSED_STICKY,a_=Uf.UNSUPPORTED_Y,s_=Rf&&(!o_||n_||jf||zf||Bf(function(){return r_[Kf]=!1,qf(i_)!==i_||qf(r_)===r_||"/a/i"!==String(qf(i_,"i"))}));if(Cf("RegExp",s_)){for(var l_=function(e,t){var i,r,o,n,a,s,l=Mf(Yf,this),c=Pf(e),d=void 0===t,u=[],h=e;if(!l&&c&&d&&e.constructor===l_)return e;if((c||Mf(Yf,e))&&(e=e.source,d&&(t=xf(h))),e=void 0===e?"":Lf(e),t=void 0===t?"":Lf(t),h=e,jf&&"dotAll"in i_&&(r=!!t&&Zf(t,"s")>-1)&&(t=$f(t,/s/g,"")),i=t,n_&&"sticky"in i_&&(o=!!t&&Zf(t,"y")>-1)&&a_&&(t=$f(t,/y/g,"")),zf&&(n=function(e){for(var t,i=e.length,r=0,o="",n=[],a=kf(null),s=!1,l=!1,c=0,d="";r<=i;r++){if("\\"===(t=Qf(e,r)))t+=Qf(e,++r);else if("]"===t)s=!1;else if(!s)switch(!0){case"["===t:s=!0;break;case"("===t:if(o+=t,"?:"===e_(e,r+1,r+3))continue;Xf(t_,e_(e,r+1))&&(r+=2,l=!0),c++;continue;case">"===t&&l:if(""===d||Hf(a,d))throw new Jf("Invalid capture group name");a[d]=!0,n[n.length]=[d,c],l=!1,d="";continue}l?d+=t:o+=t}return[o,n]}(e),e=n[0],u=n[1]),a=Df(qf(e,t),l?this:Yf,l_),(r||o||u.length)&&(s=Wf(a),r&&(s.dotAll=!0,s.raw=l_(function(e){for(var t,i=e.length,r=0,o="",n=!1;r<=i;r++)"\\"!==(t=Qf(e,r))?n||"."!==t?("["===t?n=!0:"]"===t&&(n=!1),o+=t):o+="[\\s\\S]":o+=t+Qf(e,++r);return o}(e),i)),o&&(s.sticky=!0),u.length&&(s.groups=u)),e!==h)try{Nf(a,"source",""===h?"(?:)":h)}catch(uq){}return a},c_=Of(qf),d_=0;c_.length>d_;)Vf(l_,qf,c_[d_++]);Yf.constructor=l_,l_.prototype=Yf,Ff(bf,"RegExp",l_,{constructor:!0})}Gf("RegExp");var u_=c,h_=T,p_=po,m_=of,f_=gf,__=ra,g_=Ci.get,E_=Tf,v_=Sf,y_=Le("native-string-replace",String.prototype.replace),T_=RegExp.prototype.exec,I_=T_,A_=h_("".charAt),S_=h_("".indexOf),R_=h_("".replace),b_=h_("".slice),w_=function(){var e=/a/,t=/b*/g;return u_(T_,e,"a"),u_(T_,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),C_=f_.BROKEN_CARET,D_=void 0!==/()??/.exec("")[1];(w_||D_||C_||E_||v_)&&(I_=function(e){var t,i,r,o,n,a,s,l=this,c=g_(l),d=p_(e),u=c.raw;if(u)return u.lastIndex=l.lastIndex,t=u_(I_,u,d),l.lastIndex=u.lastIndex,t;var h=c.groups,p=C_&&l.sticky,m=u_(m_,l),f=l.source,_=0,g=d;if(p&&(m=R_(m,"y",""),-1===S_(m,"g")&&(m+="g"),g=b_(d,l.lastIndex),l.lastIndex>0&&(!l.multiline||l.multiline&&"\n"!==A_(d,l.lastIndex-1))&&(f="(?: "+f+")",g=" "+g,_++),i=new RegExp("^(?:"+f+")",m)),D_&&(i=new RegExp("^"+f+"$(?!\\s)",m)),w_&&(r=l.lastIndex),o=u_(T_,p?i:l,g),p?o?(o.input=b_(o.input,_),o[0]=b_(o[0],_),o.index=l.lastIndex,l.lastIndex+=o[0].length):l.lastIndex=0:w_&&o&&(l.lastIndex=l.global?o.index+o[0].length:r),D_&&o&&o.length>1&&u_(y_,o[0],i,function(){for(n=1;n<arguments.length-2;n++)void 0===arguments[n]&&(o[n]=void 0)}),o&&h)for(o.groups=a=__(null),n=0;n<h.length;n++)a[(s=h[n])[0]]=o[s[1]];return o});var N_=I_;to({target:"RegExp",proto:!0,forced:/./.exec!==N_},{exec:N_});var k_=_o,O_=tf,M_=of;n&&!O_.correct&&(k_(RegExp.prototype,"flags",{configurable:!0,get:M_}),O_.correct=!0);var P_=rr,L_=po,x_=P,U_=RangeError,V_=T,F_=dr,B_=po,H_=function(e){var t=L_(x_(this)),i="",r=P_(e);if(r<0||Infinity===r)throw new U_("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},W_=P,G_=V_(H_),j_=V_("".slice),z_=Math.ceil,K_=function(e){return function(t,i,r){var o,n,a=B_(W_(t)),s=F_(i),l=a.length,c=void 0===r?" ":B_(r);return s<=l||""===c?a:((n=G_(c,z_((o=s-l)/c.length))).length>o&&(n=j_(n,0,o)),e?a+n:n+a)}},q_={start:K_(!1),end:K_(!0)},Y_=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Y),J_=q_.start;to({target:"String",proto:!0,forced:Y_},{padStart:function(e){return J_(this,e,arguments.length>1?arguments[1]:void 0)}});var X_=c,Q_=Qi,$_=N_,Z_=o,eg=tt,tg=qt,ig=eg("species"),rg=RegExp.prototype,og=T,ng=rr,ag=po,sg=P,lg=og("".charAt),cg=og("".charCodeAt),dg=og("".slice),ug=function(e){return function(t,i){var r,o,n=ag(sg(t)),a=ng(i),s=n.length;return a<0||a>=s?e?"":void 0:(r=cg(n,a))<55296||r>56319||a+1===s||(o=cg(n,a+1))<56320||o>57343?e?lg(n,a):r:e?dg(n,a,a+2):o-56320+(r-55296<<10)+65536}},hg={codeAt:ug(!1),charAt:ug(!0)},pg=hg.charAt,mg=T,fg=Ve,_g=Math.floor,gg=mg("".charAt),Eg=mg("".replace),vg=mg("".slice),yg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Tg=/\$([$&'`]|\d{1,2})/g,Ig=function(e,t,i,r,o,n){var a=i+e.length,s=r.length,l=Tg;return void 0!==o&&(o=fg(o),l=yg),Eg(n,l,function(n,l){var c;switch(gg(l,0)){case"$":return"$";case"&":return e;case"`":return vg(t,0,i);case"'":return vg(t,a);case"<":c=o[vg(l,1,-1)];break;default:var d=+l;if(0===d)return n;if(d>s){var u=_g(d/10);return 0===u?n:u<=s?void 0===r[u-1]?gg(l,1):r[u-1]+gg(l,1):n}c=r[d-1]}return void 0===c?"":c})},Ag=c,Sg=Mt,Rg=F,bg=R,wg=N_,Cg=TypeError,Dg=eu,Ng=c,kg=T,Og=function(e,t,i,r){var o=eg(e),n=!Z_(function(){var t={};return t[o]=function(){return 7},7!==""[e](t)}),a=n&&!Z_(function(){var t=!1,i=/a/;if("split"===e){var r={};r[ig]=function(){return i},(i={constructor:r,flags:""})[o]=/./[o]}return i.exec=function(){return t=!0,null},i[o](""),!t});if(!n||!a||i){var s=/./[o],l=t(o,""[e],function(e,t,i,r,o){var a=t.exec;return a===$_||a===rg.exec?n&&!o?{done:!0,value:X_(s,t,i,r)}:{done:!0,value:X_(e,i,t,r)}:{done:!1}});Q_(String.prototype,e,l[0]),Q_(rg,o,l[1])}r&&tg(rg[o],"sham",!0)},Mg=o,Pg=Mt,Lg=F,xg=H,Ug=rr,Vg=dr,Fg=po,Bg=P,Hg=function(e,t,i){return t+(i?pg(e,t).length:1)},Wg=ye,Gg=Ig,jg=uf,zg=function(e,t){var i=e.exec;if(Rg(i)){var r=Ag(i,e,t);return null!==r&&Sg(r),r}if("RegExp"===bg(e))return Ag(wg,e,t);throw new Cg("RegExp#exec called on incompatible receiver")},Kg=tt("replace"),qg=Math.max,Yg=Math.min,Jg=kg([].concat),Xg=kg([].push),Qg=kg("".indexOf),$g=kg("".slice),Zg=function(e){return void 0===e?e:String(e)},eE="$0"==="a".replace(/./,"$0"),tE=!!/./[Kg]&&""===/./[Kg]("a","$0"),iE=!Mg(function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")});Og("replace",function(e,t,i){var r=tE?"$":"$0";return[function(e,i){var r=Bg(this),o=xg(e)?Wg(e,Kg):void 0;return o?Ng(o,e,r,i):Ng(t,Fg(r),e,i)},function(e,o){var n=Pg(this),a=Fg(e);if("string"==typeof o&&-1===Qg(o,r)&&-1===Qg(o,"$<")){var s=i(t,n,a,o);if(s.done)return s.value}var l=Lg(o);l||(o=Fg(o));var c,d=Fg(jg(n)),u=-1!==Qg(d,"g");u&&(c=-1!==Qg(d,"u"),n.lastIndex=0);for(var h,p=[];null!==(h=zg(n,a))&&(Xg(p,h),u);){""===Fg(h[0])&&(n.lastIndex=Hg(a,Vg(n.lastIndex),c))}for(var m="",f=0,_=0;_<p.length;_++){for(var g,E=Fg((h=p[_])[0]),v=qg(Yg(Ug(h.index),a.length),0),y=[],T=1;T<h.length;T++)Xg(y,Zg(h[T]));var I=h.groups;if(l){var A=Jg([E],y,v,a);void 0!==I&&Xg(A,I),g=Fg(Dg(o,void 0,A))}else g=Gg(E,a,v,y,I,o);v>=f&&(m+=$g(a,f,v)+g,f=v+E.length)}return m+$g(a,f)}]},!iE||!eE||tE);var rE="\t\n\v\f\r \u2028\u2029\ufeff",oE=P,nE=po,aE=rE,sE=T("".replace),lE=RegExp("^["+aE+"]+"),cE=RegExp("(^|[^"+aE+"])["+aE+"]+$"),dE=function(e){return function(t){var i=nE(oE(t));return 1&e&&(i=sE(i,lE,"")),2&e&&(i=sE(i,cE,"$1")),i}},uE={start:dE(1),end:dE(2),trim:dE(3)},hE=ei.PROPER,pE=o,mE=rE,fE=uE.trim;to({target:"String",proto:!0,forced:function(e){return pE(function(){return!!mE[e]()||"
"!=="
"[e]()||hE&&mE[e].name!==e})}("trim")},{trim:function(){return fE(this)}});var _E,gE,EE,vE={exports:{}},yE=Ul,TE=n,IE=i,AE=F,SE=H,RE=He,bE=co,wE=pe,CE=qt,DE=Qi,NE=_o,kE=z,OE=Sa,ME=ts,PE=tt,LE=Ke,xE=Ci.enforce,UE=Ci.get,VE=IE.Int8Array,FE=VE&&VE.prototype,BE=IE.Uint8ClampedArray,HE=BE&&BE.prototype,WE=VE&&OE(VE),GE=FE&&OE(FE),jE=Object.prototype,zE=IE.TypeError,KE=PE("toStringTag"),qE=LE("TYPED_ARRAY_TAG"),YE="TypedArrayConstructor",JE=yE&&!!ME&&"Opera"!==bE(IE.opera),XE=!1,QE={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},$E={BigInt64Array:8,BigUint64Array:8},ZE=function(e){var t=OE(e);if(SE(t)){var i=UE(t);return i&&RE(i,YE)?i[YE]:ZE(t)}},ev=function(e){if(!SE(e))return!1;var t=bE(e);return RE(QE,t)||RE($E,t)};for(_E in QE)(EE=(gE=IE[_E])&&gE.prototype)?xE(EE)[YE]=gE:JE=!1;for(_E in $E)(EE=(gE=IE[_E])&&gE.prototype)&&(xE(EE)[YE]=gE);if((!JE||!AE(WE)||WE===Function.prototype)&&(WE=function(){throw new zE("Incorrect invocation")},JE))for(_E in QE)IE[_E]&&ME(IE[_E],WE);if((!JE||!GE||GE===jE)&&(GE=WE.prototype,JE))for(_E in QE)IE[_E]&&ME(IE[_E].prototype,GE);if(JE&&OE(HE)!==GE&&ME(HE,GE),TE&&!RE(GE,KE))for(_E in XE=!0,NE(GE,KE,{configurable:!0,get:function(){return SE(this)?this[qE]:void 0}}),QE)IE[_E]&&CE(IE[_E],qE,_E);var tv={NATIVE_ARRAY_BUFFER_VIEWS:JE,TYPED_ARRAY_TAG:XE&&qE,aTypedArray:function(e){if(ev(e))return e;throw new zE("Target is not a typed array")},aTypedArrayConstructor:function(e){if(AE(e)&&(!ME||kE(WE,e)))return e;throw new zE(wE(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(TE){if(i)for(var o in QE){var n=IE[o];if(n&&RE(n.prototype,e))try{delete n.prototype[e]}catch(uq){try{n.prototype[e]=t}catch(a){}}}GE[e]&&!i||DE(GE,e,i?t:JE&&FE[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,o;if(TE){if(ME){if(i)for(r in QE)if((o=IE[r])&&RE(o,e))try{delete o[e]}catch(uq){}if(WE[e]&&!i)return;try{return DE(WE,e,i?t:JE&&WE[e]||t)}catch(uq){}}for(r in QE)!(o=IE[r])||o[e]&&!i||DE(o,e,t)}},getTypedArrayConstructor:ZE,isView:function(e){if(!SE(e))return!1;var t=bE(e);return"DataView"===t||RE(QE,t)||RE($E,t)},isTypedArray:ev,TypedArray:WE,TypedArrayPrototype:GE},iv=i,rv=o,ov=cm,nv=tv.NATIVE_ARRAY_BUFFER_VIEWS,av=iv.ArrayBuffer,sv=iv.Int8Array,lv=!nv||!rv(function(){sv(1)})||!rv(function(){new sv(-1)})||!ov(function(e){new sv,new sv(null),new sv(1.5),new sv(e)},!0)||rv(function(){return 1!==new sv(new av(2),1,void 0).length}),cv=H,dv=Math.floor,uv=Number.isInteger||function(e){return!cv(e)&&isFinite(e)&&dv(e)===e},hv=rr,pv=RangeError,mv=function(e){var t=hv(e);if(t<0)throw new pv("The argument can't be less than 0");return t},fv=RangeError,_v=function(e,t){var i=mv(e);if(i%t)throw new fv("Wrong offset");return i},gv=Math.round,Ev=co,vv=ct,yv=TypeError,Tv=function(e){var t=vv(e,"number");if("number"==typeof t)throw new yv("Can't convert number to bigint");return BigInt(t)},Iv=Zo,Av=c,Sv=jd,Rv=Ve,bv=hr,wv=Bp,Cv=Mp,Dv=wp,Nv=function(e){var t=Ev(e);return"BigInt64Array"===t||"BigUint64Array"===t},kv=tv.aTypedArrayConstructor,Ov=Tv,Mv=Zo,Pv=N,Lv=Ve,xv=hr,Uv=bn,Vv=T([].push),Fv=function(e){var t=1===e,i=2===e,r=3===e,o=4===e,n=6===e,a=7===e,s=5===e||n;return function(l,c,d,u){for(var h,p,m=Lv(l),f=Pv(m),_=xv(f),g=Mv(c,d),E=0,v=u||Uv,y=t?v(l,_):i||a?v(l,0):void 0;_>E;E++)if((s||E in f)&&(p=g(h=f[E],E,m),e))if(t)y[E]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return E;case 2:Vv(y,h)}else switch(e){case 4:return!1;case 7:Vv(y,h)}return n?-1:r||o?o:y}},Bv={forEach:Fv(0),map:Fv(1),filter:Fv(2),some:Fv(3),every:Fv(4),find:Fv(5),findIndex:Fv(6),filterReject:Fv(7)},Hv=hr,Wv=to,Gv=i,jv=c,zv=n,Kv=lv,qv=tv,Yv=_d,Jv=Wl,Xv=_,Qv=qt,$v=uv,Zv=dr,ey=Kl,ty=_v,iy=function(e){var t=gv(e);return t<0?0:t>255?255:255&t},ry=ht,oy=He,ny=co,ay=H,sy=ue,ly=ra,cy=z,dy=ts,uy=$i.f,hy=function(e){var t,i,r,o,n,a,s,l,c=Sv(this),d=Rv(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=Cv(d);if(m&&!Dv(m))for(l=(s=wv(d,m)).next,d=[];!(a=Av(l,s)).done;)d.push(a.value);for(p&&u>2&&(h=Iv(h,arguments[2])),i=bv(d),r=new(kv(c))(i),o=Nv(r),t=0;i>t;t++)n=p?h(d[t],t):d[t],r[t]=o?Ov(n):+n;return r},py=Bv.forEach,my=Td,fy=_o,_y=Ct,gy=r,Ey=function(e,t,i){for(var r=0,o=arguments.length>2?i:Hv(t),n=new e(o);o>r;)n[r]=t[r++];return n},vy=mc,yy=Ci.get,Ty=Ci.set,Iy=Ci.enforce,Ay=_y.f,Sy=gy.f,Ry=Gv.RangeError,by=Yv.ArrayBuffer,wy=by.prototype,Cy=Yv.DataView,Dy=qv.NATIVE_ARRAY_BUFFER_VIEWS,Ny=qv.TYPED_ARRAY_TAG,ky=qv.TypedArray,Oy=qv.TypedArrayPrototype,My=qv.isTypedArray,Py="BYTES_PER_ELEMENT",Ly="Wrong length",xy=function(e,t){fy(e,t,{configurable:!0,get:function(){return yy(this)[t]}})},Uy=function(e){var t;return cy(wy,e)||"ArrayBuffer"===(t=ny(e))||"SharedArrayBuffer"===t},Vy=function(e,t){return My(e)&&!sy(t)&&t in e&&$v(+t)&&t>=0},Fy=function(e,t){return t=ry(t),Vy(e,t)?Xv(2,e[t]):Sy(e,t)},By=function(e,t,i){return t=ry(t),!(Vy(e,t)&&ay(i)&&oy(i,"value"))||oy(i,"get")||oy(i,"set")||i.configurable||oy(i,"writable")&&!i.writable||oy(i,"enumerable")&&!i.enumerable?Ay(e,t,i):(e[t]=i.value,e)};zv?(Dy||(gy.f=Fy,_y.f=By,xy(Oy,"buffer"),xy(Oy,"byteOffset"),xy(Oy,"byteLength"),xy(Oy,"length")),Wv({target:"Object",stat:!0,forced:!Dy},{getOwnPropertyDescriptor:Fy,defineProperty:By}),vE.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,o=e+(i?"Clamped":"")+"Array",n="get"+e,a="set"+e,s=Gv[o],l=s,c=l&&l.prototype,d={},u=function(e,t){Ay(e,t,{get:function(){return function(e,t){var i=yy(e);return i.view[n](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,o){var n=yy(e);n.view[a](t*r+n.byteOffset,i?iy(o):o,!0)}(this,t,e)},enumerable:!0})};Dy?Kv&&(l=t(function(e,t,i,o){return Jv(e,c),vy(ay(t)?Uy(t)?void 0!==o?new s(t,ty(i,r),o):void 0!==i?new s(t,ty(i,r)):new s(t):My(t)?Ey(l,t):jv(hy,l,t):new s(ey(t)),e,l)}),dy&&dy(l,ky),py(uy(s),function(e){e in l||Qv(l,e,s[e])}),l.prototype=c):(l=t(function(e,t,i,o){Jv(e,c);var n,a,s,d=0,h=0;if(ay(t)){if(!Uy(t))return My(t)?Ey(l,t):jv(hy,l,t);n=t,h=ty(i,r);var p=t.byteLength;if(void 0===o){if(p%r)throw new Ry(Ly);if((a=p-h)<0)throw new Ry(Ly)}else if((a=Zv(o)*r)+h>p)throw new Ry(Ly);s=a/r}else s=ey(t),n=new by(a=s*r);for(Ty(e,{buffer:n,byteOffset:h,byteLength:a,length:s,view:new Cy(n)});d<s;)u(e,d++)}),dy&&dy(l,ky),c=l.prototype=ly(Oy)),c.constructor!==l&&Qv(c,"constructor",l),Iy(c).TypedArrayConstructor=l,Ny&&Qv(c,Ny,o);var h=l!==s;d[o]=l,Wv({global:!0,constructor:!0,forced:h,sham:!Dy},d),Py in l||Qv(l,Py,r),Py in c||Qv(c,Py,r),my(o)}):vE.exports=function(){};var Hy=vE.exports;Hy("Float32",function(e){return function(t,i,r){return e(this,t,i,r)}}),Hy("Float64",function(e){return function(t,i,r){return e(this,t,i,r)}}),Hy("Int8",function(e){return function(t,i,r){return e(this,t,i,r)}}),Hy("Int16",function(e){return function(t,i,r){return e(this,t,i,r)}}),Hy("Int32",function(e){return function(t,i,r){return e(this,t,i,r)}}),Hy("Uint8",function(e){return function(t,i,r){return e(this,t,i,r)}}),Hy("Uint8",function(e){return function(t,i,r){return e(this,t,i,r)}},!0),Hy("Uint16",function(e){return function(t,i,r){return e(this,t,i,r)}}),Hy("Uint32",function(e){return function(t,i,r){return e(this,t,i,r)}});var Wy=dc,Gy=Tv,jy=co,zy=c,Ky=o,qy=tv.aTypedArray,Yy=tv.exportTypedArrayMethod,Jy=T("".slice);Yy("fill",function(e){var t=arguments.length;qy(this);var i="Big"===Jy(jy(this),0,3)?Gy(e):+e;return zy(Wy,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)},Ky(function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e}));var Xy=i,Qy=c,$y=tv,Zy=hr,eT=_v,tT=Ve,iT=o,rT=Xy.RangeError,oT=Xy.Int8Array,nT=oT&&oT.prototype,aT=nT&&nT.set,sT=$y.aTypedArray,lT=$y.exportTypedArrayMethod,cT=!iT(function(){var e=new Uint8ClampedArray(2);return Qy(aT,e,{length:1,0:3},1),3!==e[1]}),dT=cT&&$y.NATIVE_ARRAY_BUFFER_VIEWS&&iT(function(){var e=new oT(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]});lT("set",function(e){sT(this);var t=eT(arguments.length>1?arguments[1]:void 0,1),i=tT(e);if(cT)return Qy(aT,this,i,t);var r=this.length,o=Zy(i),n=0;if(o+t>r)throw new rT("Wrong length");for(;n<o;)this[t+n]=i[n++]},!cT||dT);var uT=Jo,hT=o,pT=ge,mT=dl,fT=hl,_T=pl,gT=te,ET=fl,vT=tv.aTypedArray,yT=tv.exportTypedArrayMethod,TT=i.Uint16Array,IT=TT&&uT(TT.prototype.sort),AT=!(!IT||hT(function(){IT(new TT(2),null)})&&hT(function(){IT(new TT(2),{})})),ST=!!IT&&!hT(function(){if(gT)return gT<74;if(fT)return fT<67;if(_T)return!0;if(ET)return ET<602;var e,t,i=new TT(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(IT(i,function(e,t){return(e/4|0)-(t/4|0)}),e=0;e<516;e++)if(i[e]!==r[e])return!0});yT("sort",function(e){return void 0!==e&&pT(e),ST?IT(this,e):mT(vT(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))},!ST||AT);var RT=to,bT=c,wT=T,CT=P,DT=F,NT=H,kT=Qm,OT=po,MT=ye,PT=uf,LT=Ig,xT=tt("replace"),UT=TypeError,VT=wT("".indexOf);wT("".replace);var FT=wT("".slice),BT=Math.max;RT({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,o,n,a,s,l,c,d,u=CT(this),h=0,p="";if(NT(e)){if(kT(e)&&(i=OT(CT(PT(e))),!~VT(i,"g")))throw new UT("`.replaceAll` does not allow non-global regexes");if(r=MT(e,xT))return bT(r,e,u,t)}for(o=OT(u),n=OT(e),(a=DT(t))||(t=OT(t)),s=n.length,l=BT(1,s),c=VT(o,n);-1!==c;)d=a?OT(t(n,c,o)):LT(n,o,c,[],void 0,t),p+=FT(o,h,c)+d,h=c+s,c=c+l>o.length?-1:VT(o,n,c+l);return h<o.length&&(p+=FT(o,h)),p}});var HT={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},WT=_t("span").classList,GT=WT&&WT.constructor&&WT.constructor.prototype,jT=GT===Object.prototype?void 0:GT,zT=Bv.forEach,KT=zs("forEach")?[].forEach:function(e){return zT(this,e,arguments.length>1?arguments[1]:void 0)},qT=i,YT=HT,JT=jT,XT=KT,QT=qt,$T=function(e){if(e&&e.forEach!==XT)try{QT(e,"forEach",XT)}catch(uq){e.forEach=XT}};for(var ZT in YT)YT[ZT]&&$T(qT[ZT]&&qT[ZT].prototype);$T(JT);var eI=i,tI=HT,iI=jT,rI=Ps,oI=qt,nI=Ua,aI=tt("iterator"),sI=rI.values,lI=function(e,t){if(e){if(e[aI]!==sI)try{oI(e,aI,sI)}catch(uq){e[aI]=sI}if(nI(e,t,!0),tI[t])for(var i in rI)if(e[i]!==rI[i])try{oI(e,i,rI[i])}catch(uq){e[i]=rI[i]}}};for(var cI in tI)lI(eI[cI]&&eI[cI].prototype,cI);lI(iI,"DOMTokenList");var dI=Nu.clear;to({global:!0,bind:!0,enumerable:!0,forced:i.clearImmediate!==dI},{clearImmediate:dI});var uI=i,hI=eu,pI=F,mI=Xs,fI=Y,_I=al,gI=iu,EI=uI.Function,vI=/MSIE .\./.test(fI)||"BUN"===mI&&function(){var e=uI.Bun.version.split(".");return e.length<3||"0"===e[0]&&(e[1]<3||"3"===e[1]&&"0"===e[2])}(),yI=to,TI=i,II=Nu.set,AI=function(e,t){var i=t?2:1;return vI?function(r,o){var n=gI(arguments.length,1)>i,a=pI(r)?r:EI(r),s=n?_I(arguments,i):[],l=n?function(){hI(a,this,s)}:a;return t?e(l,o):e(l)}:e},SI=TI.setImmediate?AI(II,!1):II;yI({global:!0,bind:!0,enumerable:!0,forced:TI.setImmediate!==SI},{setImmediate:SI});var RI=hg.charAt,bI=po,wI=Ci,CI=Ts,DI=Is,NI="String Iterator",kI=wI.set,OI=wI.getterFor(NI);CI(String,"String",function(e){kI(this,{type:NI,string:bI(e),index:0})},function(){var e,t=OI(this),i=t.string,r=t.index;return r>=i.length?DI(void 0,!0):(e=RI(i,r),t.index+=e.length,DI(e,!1))});var MI=o,PI=n,LI=tt("iterator"),xI=!MI(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&&!PI||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[LI]||"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}),UI=n,VI=T,FI=c,BI=o,HI=Ln,WI=wr,GI=d,jI=Ve,zI=N,KI=Object.assign,qI=Object.defineProperty,YI=VI([].concat),JI=!KI||BI(function(){if(UI&&1!==KI({b:1},KI(qI({},"a",{enumerable:!0,get:function(){qI(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!==KI({},e)[i]||HI(KI({},t)).join("")!==r})?function(e,t){for(var i=jI(e),r=arguments.length,o=1,n=WI.f,a=GI.f;r>o;)for(var s,l=zI(arguments[o++]),c=n?YI(HI(l),n(l)):HI(l),d=c.length,u=0;d>u;)s=c[u++],UI&&!FI(a,l,s)||(i[s]=l[s]);return i}:KI,XI=Mt,QI=jp,$I=n,ZI=Ct,eA=_,tA=Zo,iA=c,rA=Ve,oA=function(e,t,i,r){try{return r?t(XI(i)[0],i[1]):t(i)}catch(uq){QI(e,"throw",uq)}},nA=wp,aA=vn,sA=hr,lA=function(e,t,i){$I?ZI.f(e,t,eA(0,i)):e[t]=i},cA=Bp,dA=Mp,uA=Array,hA=T,pA=2147483647,mA=/[^\0-\u007E]/,fA=/[.\u3002\uFF0E\uFF61]/g,_A="Overflow: input needs wider integers to process",gA=RangeError,EA=hA(fA.exec),vA=Math.floor,yA=String.fromCharCode,TA=hA("".charCodeAt),IA=hA([].join),AA=hA([].push),SA=hA("".replace),RA=hA("".split),bA=hA("".toLowerCase),wA=function(e){return e+22+75*(e<26)},CA=function(e,t,i){var r=0;for(e=i?vA(e/700):e>>1,e+=vA(e/t);e>455;)e=vA(e/35),r+=36;return vA(r+36*e/(e+38))},DA=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var o=TA(e,i++);if(o>=55296&&o<=56319&&i<r){var n=TA(e,i++);56320==(64512&n)?AA(t,((1023&o)<<10)+(1023&n)+65536):(AA(t,o),i--)}else AA(t,o)}return t}(e);var i,r,o=e.length,n=128,a=0,s=72;for(i=0;i<e.length;i++)(r=e[i])<128&&AA(t,yA(r));var l=t.length,c=l;for(l&&AA(t,"-");c<o;){var d=pA;for(i=0;i<e.length;i++)(r=e[i])>=n&&r<d&&(d=r);var u=c+1;if(d-n>vA((pA-a)/u))throw new gA(_A);for(a+=(d-n)*u,n=d,i=0;i<e.length;i++){if((r=e[i])<n&&++a>pA)throw new gA(_A);if(r===n){for(var h=a,p=36;;){var m=p<=s?1:p>=s+26?26:p-s;if(h<m)break;var f=h-m,_=36-m;AA(t,yA(wA(m+f%_))),h=vA(f/_),p+=36}AA(t,yA(wA(h))),s=CA(a,u,c===l),a=0,c++}}a++,n++}return IA(t,"")},NA=to,kA=T,OA=sr,MA=RangeError,PA=String.fromCharCode,LA=String.fromCodePoint,xA=kA([].join);NA({target:"String",stat:!0,arity:1,forced:!!LA&&1!==LA.length},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,o=0;r>o;){if(t=+arguments[o++],OA(t,1114111)!==t)throw new MA(t+" is not a valid code point");i[o]=t<65536?PA(t):PA(55296+((t-=65536)>>10),t%1024+56320)}return xA(i,"")}});var UA=to,VA=i,FA=Pu,BA=j,HA=c,WA=T,GA=n,jA=xI,zA=Qi,KA=_o,qA=Fl,YA=Ua,JA=ja,XA=Ci,QA=Wl,$A=F,ZA=He,eS=Zo,tS=co,iS=Mt,rS=H,oS=po,nS=ra,aS=_,sS=Bp,lS=Mp,cS=Is,dS=iu,uS=dl,hS=tt("iterator"),pS="URLSearchParams",mS=pS+"Iterator",fS=XA.set,_S=XA.getterFor(pS),gS=XA.getterFor(mS),ES=FA("fetch"),vS=FA("Request"),yS=FA("Headers"),TS=vS&&vS.prototype,IS=yS&&yS.prototype,AS=VA.TypeError,SS=VA.encodeURIComponent,RS=String.fromCharCode,bS=BA("String","fromCodePoint"),wS=parseInt,CS=WA("".charAt),DS=WA([].join),NS=WA([].push),kS=WA("".replace),OS=WA([].shift),MS=WA([].splice),PS=WA("".split),LS=WA("".slice),xS=WA(/./.exec),US=/\+/g,VS=/^[0-9a-f]+$/i,FS=function(e,t){var i=LS(e,t,t+2);return xS(VS,i)?wS(i,16):NaN},BS=function(e){for(var t=0,i=128;i>0&&0!==(e&i);i>>=1)t++;return t},HS=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},WS=function(e){for(var t=(e=kS(e,US," ")).length,i="",r=0;r<t;){var o=CS(e,r);if("%"===o){if("%"===CS(e,r+1)||r+3>t){i+="%",r++;continue}var n=FS(e,r+1);if(n!=n){i+=o,r++;continue}r+=2;var a=BS(n);if(0===a)o=RS(n);else{if(1===a||a>4){i+="�",r++;continue}for(var s=[n],l=1;l<a&&!(++r+3>t||"%"!==CS(e,r));){var c=FS(e,r+1);if(c!=c){r+=3;break}if(c>191||c<128)break;NS(s,c),r+=2,l++}if(s.length!==a){i+="�";continue}var d=HS(s);null===d?i+="�":o=bS(d)}}i+=o,r++}return i},GS=/[!'()~]|%20/g,jS={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},zS=function(e){return jS[e]},KS=function(e){return kS(SS(e),GS,zS)},qS=JA(function(e,t){fS(this,{type:mS,target:_S(e).entries,index:0,kind:t})},pS,function(){var e=gS(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,cS(void 0,!0);var r=t[i];switch(e.kind){case"keys":return cS(r.key,!1);case"values":return cS(r.value,!1)}return cS([r.key,r.value],!1)},!0),YS=function(e){this.entries=[],this.url=null,void 0!==e&&(rS(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===CS(e,0)?LS(e,1):e:oS(e)))};YS.prototype={type:pS,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,o,n,a,s,l=this.entries,c=lS(e);if(c)for(i=(t=sS(e,c)).next;!(r=HA(i,t)).done;){if(n=(o=sS(iS(r.value))).next,(a=HA(n,o)).done||(s=HA(n,o)).done||!HA(n,o).done)throw new AS("Expected sequence with length 2");NS(l,{key:oS(a.value),value:oS(s.value)})}else for(var d in e)ZA(e,d)&&NS(l,{key:d,value:oS(e[d])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,o=PS(e,"&"),n=0;n<o.length;)(t=o[n++]).length&&(i=PS(t,"="),NS(r,{key:WS(OS(i)),value:WS(DS(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],NS(i,KS(e.key)+"="+KS(e.value));return DS(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var JS=function(){QA(this,XS);var e=fS(this,new YS(arguments.length>0?arguments[0]:void 0));GA||(this.size=e.entries.length)},XS=JS.prototype;if(qA(XS,{append:function(e,t){var i=_S(this);dS(arguments.length,2),NS(i.entries,{key:oS(e),value:oS(t)}),GA||this.size++,i.updateURL()},delete:function(e){for(var t=_S(this),i=dS(arguments.length,1),r=t.entries,o=oS(e),n=i<2?void 0:arguments[1],a=void 0===n?n:oS(n),s=0;s<r.length;){var l=r[s];if(l.key!==o||void 0!==a&&l.value!==a)s++;else if(MS(r,s,1),void 0!==a)break}GA||(this.size=r.length),t.updateURL()},get:function(e){var t=_S(this).entries;dS(arguments.length,1);for(var i=oS(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=_S(this).entries;dS(arguments.length,1);for(var i=oS(e),r=[],o=0;o<t.length;o++)t[o].key===i&&NS(r,t[o].value);return r},has:function(e){for(var t=_S(this).entries,i=dS(arguments.length,1),r=oS(e),o=i<2?void 0:arguments[1],n=void 0===o?o:oS(o),a=0;a<t.length;){var s=t[a++];if(s.key===r&&(void 0===n||s.value===n))return!0}return!1},set:function(e,t){var i=_S(this);dS(arguments.length,1);for(var r,o=i.entries,n=!1,a=oS(e),s=oS(t),l=0;l<o.length;l++)(r=o[l]).key===a&&(n?MS(o,l--,1):(n=!0,r.value=s));n||NS(o,{key:a,value:s}),GA||(this.size=o.length),i.updateURL()},sort:function(){var e=_S(this);uS(e.entries,function(e,t){return e.key>t.key?1:-1}),e.updateURL()},forEach:function(e){for(var t,i=_S(this).entries,r=eS(e,arguments.length>1?arguments[1]:void 0),o=0;o<i.length;)r((t=i[o++]).value,t.key,this)},keys:function(){return new qS(this,"keys")},values:function(){return new qS(this,"values")},entries:function(){return new qS(this,"entries")}},{enumerable:!0}),zA(XS,hS,XS.entries,{name:"entries"}),zA(XS,"toString",function(){return _S(this).serialize()},{enumerable:!0}),GA&&KA(XS,"size",{get:function(){return _S(this).entries.length},configurable:!0,enumerable:!0}),YA(JS,pS),UA({global:!0,constructor:!0,forced:!jA},{URLSearchParams:JS}),!jA&&$A(yS)){var QS=WA(IS.has),$S=WA(IS.set),ZS=function(e){if(rS(e)){var t,i=e.body;if(tS(i)===pS)return t=e.headers?new yS(e.headers):new yS,QS(t,"content-type")||$S(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),nS(e,{body:aS(0,oS(i)),headers:aS(0,t)})}return e};if($A(ES)&&UA({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return ES(e,arguments.length>1?ZS(arguments[1]):{})}}),$A(vS)){var eR=function(e){return QA(this,TS),new vS(e,arguments.length>1?ZS(arguments[1]):{})};TS.constructor=eR,eR.prototype=TS,UA({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:eR})}}var tR,iR=to,rR=n,oR=xI,nR=i,aR=Zo,sR=T,lR=Qi,cR=_o,dR=Wl,uR=He,hR=JI,pR=function(e){var t=rA(e),i=aA(this),r=arguments.length,o=r>1?arguments[1]:void 0,n=void 0!==o;n&&(o=tA(o,r>2?arguments[2]:void 0));var a,s,l,c,d,u,h=dA(t),p=0;if(!h||this===uA&&nA(h))for(a=sA(t),s=i?new this(a):uA(a);a>p;p++)u=n?o(t[p],p):t[p],lA(s,p,u);else for(s=i?new this:[],d=(c=cA(t,h)).next;!(l=iA(d,c)).done;p++)u=n?oA(c,o,[l.value,p],!0):l.value,lA(s,p,u);return s.length=p,s},mR=al,fR=hg.codeAt,_R=function(e){var t,i,r=[],o=RA(SA(bA(e),fA,"."),".");for(t=0;t<o.length;t++)i=o[t],AA(r,EA(mA,i)?"xn--"+DA(i):i);return IA(r,".")},gR=po,ER=Ua,vR=iu,yR={URLSearchParams:JS,getState:_S},TR=Ci,IR=TR.set,AR=TR.getterFor("URL"),SR=yR.URLSearchParams,RR=yR.getState,bR=nR.URL,wR=nR.TypeError,CR=nR.parseInt,DR=Math.floor,NR=Math.pow,kR=sR("".charAt),OR=sR(/./.exec),MR=sR([].join),PR=sR(1.1.toString),LR=sR([].pop),xR=sR([].push),UR=sR("".replace),VR=sR([].shift),FR=sR("".split),BR=sR("".slice),HR=sR("".toLowerCase),WR=sR([].unshift),GR="Invalid scheme",jR="Invalid host",zR="Invalid port",KR=/[a-z]/i,qR=/[\d+-.a-z]/i,YR=/\d/,JR=/^0x/i,XR=/^[0-7]+$/,QR=/^\d+$/,$R=/^[\da-f]+$/i,ZR=/[\0\t\n\r #%/:<>?@[\\\]^|]/,eb=/[\0\t\n\r #/:<>?@[\\\]^|]/,tb=/^[\u0000-\u0020]+/,ib=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,rb=/[\t\n\r]/g,ob=function(e){var t,i,r,o;if("number"==typeof e){for(t=[],i=0;i<4;i++)WR(t,e%256),e=DR(e/256);return MR(t,".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,i=1,r=null,o=0,n=0;n<8;n++)0!==e[n]?(o>i&&(t=r,i=o),r=null,o=0):(null===r&&(r=n),++o);return o>i?r:t}(e),i=0;i<8;i++)o&&0===e[i]||(o&&(o=!1),r===i?(t+=i?":":"::",o=!0):(t+=PR(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},nb={},ab=hR({},nb,{" ":1,'"':1,"<":1,">":1,"`":1}),sb=hR({},ab,{"#":1,"?":1,"{":1,"}":1}),lb=hR({},sb,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),cb=function(e,t){var i=fR(e,0);return i>32&&i<127&&!uR(t,e)?e:encodeURIComponent(e)},db={ftp:21,file:null,http:80,https:443,ws:80,wss:443},ub=function(e,t){var i;return 2===e.length&&OR(KR,kR(e,0))&&(":"===(i=kR(e,1))||!t&&"|"===i)},hb=function(e){var t;return e.length>1&&ub(BR(e,0,2))&&(2===e.length||"/"===(t=kR(e,2))||"\\"===t||"?"===t||"#"===t)},pb=function(e){return"."===e||"%2e"===HR(e)},mb=function(e){return".."===(e=HR(e))||"%2e."===e||".%2e"===e||"%2e%2e"===e},fb={},_b={},gb={},Eb={},vb={},yb={},Tb={},Ib={},Ab={},Sb={},Rb={},bb={},wb={},Cb={},Db={},Nb={},kb={},Ob={},Mb={},Pb={},Lb={},xb=function(e,t,i){var r,o,n,a=gR(e);if(t){if(o=this.parse(a))throw new wR(o);this.searchParams=null}else{if(void 0!==i&&(r=new xb(i,!0)),o=this.parse(a,null,r))throw new wR(o);(n=RR(new SR)).bindURL(this),this.searchParams=n}};xb.prototype={type:"URL",parse:function(e,t,i){var r,o,n,a,s=this,l=t||fb,c=0,d="",u=!1,h=!1,p=!1;for(e=gR(e),t||(s.scheme="",s.username="",s.password="",s.host=null,s.port=null,s.path=[],s.query=null,s.fragment=null,s.cannotBeABaseURL=!1,e=UR(e,tb,""),e=UR(e,ib,"$1")),e=UR(e,rb,""),r=pR(e);c<=r.length;){switch(o=r[c],l){case fb:if(!o||!OR(KR,o)){if(t)return GR;l=gb;continue}d+=HR(o),l=_b;break;case _b:if(o&&(OR(qR,o)||"+"===o||"-"===o||"."===o))d+=HR(o);else{if(":"!==o){if(t)return GR;d="",l=gb,c=0;continue}if(t&&(s.isSpecial()!==uR(db,d)||"file"===d&&(s.includesCredentials()||null!==s.port)||"file"===s.scheme&&!s.host))return;if(s.scheme=d,t)return void(s.isSpecial()&&db[s.scheme]===s.port&&(s.port=null));d="","file"===s.scheme?l=Cb:s.isSpecial()&&i&&i.scheme===s.scheme?l=Eb:s.isSpecial()?l=Ib:"/"===r[c+1]?(l=vb,c++):(s.cannotBeABaseURL=!0,xR(s.path,""),l=Mb)}break;case gb:if(!i||i.cannotBeABaseURL&&"#"!==o)return GR;if(i.cannotBeABaseURL&&"#"===o){s.scheme=i.scheme,s.path=mR(i.path),s.query=i.query,s.fragment="",s.cannotBeABaseURL=!0,l=Lb;break}l="file"===i.scheme?Cb:yb;continue;case Eb:if("/"!==o||"/"!==r[c+1]){l=yb;continue}l=Ab,c++;break;case vb:if("/"===o){l=Sb;break}l=Ob;continue;case yb:if(s.scheme=i.scheme,o===tR)s.username=i.username,s.password=i.password,s.host=i.host,s.port=i.port,s.path=mR(i.path),s.query=i.query;else if("/"===o||"\\"===o&&s.isSpecial())l=Tb;else if("?"===o)s.username=i.username,s.password=i.password,s.host=i.host,s.port=i.port,s.path=mR(i.path),s.query="",l=Pb;else{if("#"!==o){s.username=i.username,s.password=i.password,s.host=i.host,s.port=i.port,s.path=mR(i.path),s.path.length--,l=Ob;continue}s.username=i.username,s.password=i.password,s.host=i.host,s.port=i.port,s.path=mR(i.path),s.query=i.query,s.fragment="",l=Lb}break;case Tb:if(!s.isSpecial()||"/"!==o&&"\\"!==o){if("/"!==o){s.username=i.username,s.password=i.password,s.host=i.host,s.port=i.port,l=Ob;continue}l=Sb}else l=Ab;break;case Ib:if(l=Ab,"/"!==o||"/"!==kR(d,c+1))continue;c++;break;case Ab:if("/"!==o&&"\\"!==o){l=Sb;continue}break;case Sb:if("@"===o){u&&(d="%40"+d),u=!0,n=pR(d);for(var m=0;m<n.length;m++){var f=n[m];if(":"!==f||p){var _=cb(f,lb);p?s.password+=_:s.username+=_}else p=!0}d=""}else if(o===tR||"/"===o||"?"===o||"#"===o||"\\"===o&&s.isSpecial()){if(u&&""===d)return"Invalid authority";c-=pR(d).length+1,d="",l=Rb}else d+=o;break;case Rb:case bb:if(t&&"file"===s.scheme){l=Nb;continue}if(":"!==o||h){if(o===tR||"/"===o||"?"===o||"#"===o||"\\"===o&&s.isSpecial()){if(s.isSpecial()&&""===d)return jR;if(t&&""===d&&(s.includesCredentials()||null!==s.port))return;if(a=s.parseHost(d))return a;if(d="",l=kb,t)return;continue}"["===o?h=!0:"]"===o&&(h=!1),d+=o}else{if(""===d)return jR;if(a=s.parseHost(d))return a;if(d="",l=wb,t===bb)return}break;case wb:if(!OR(YR,o)){if(o===tR||"/"===o||"?"===o||"#"===o||"\\"===o&&s.isSpecial()||t){if(""!==d){var g=CR(d,10);if(g>65535)return zR;s.port=s.isSpecial()&&g===db[s.scheme]?null:g,d=""}if(t)return;l=kb;continue}return zR}d+=o;break;case Cb:if(s.scheme="file","/"===o||"\\"===o)l=Db;else{if(!i||"file"!==i.scheme){l=Ob;continue}switch(o){case tR:s.host=i.host,s.path=mR(i.path),s.query=i.query;break;case"?":s.host=i.host,s.path=mR(i.path),s.query="",l=Pb;break;case"#":s.host=i.host,s.path=mR(i.path),s.query=i.query,s.fragment="",l=Lb;break;default:hb(MR(mR(r,c),""))||(s.host=i.host,s.path=mR(i.path),s.shortenPath()),l=Ob;continue}}break;case Db:if("/"===o||"\\"===o){l=Nb;break}i&&"file"===i.scheme&&!hb(MR(mR(r,c),""))&&(ub(i.path[0],!0)?xR(s.path,i.path[0]):s.host=i.host),l=Ob;continue;case Nb:if(o===tR||"/"===o||"\\"===o||"?"===o||"#"===o){if(!t&&ub(d))l=Ob;else if(""===d){if(s.host="",t)return;l=kb}else{if(a=s.parseHost(d))return a;if("localhost"===s.host&&(s.host=""),t)return;d="",l=kb}continue}d+=o;break;case kb:if(s.isSpecial()){if(l=Ob,"/"!==o&&"\\"!==o)continue}else if(t||"?"!==o)if(t||"#"!==o){if(o!==tR&&(l=Ob,"/"!==o))continue}else s.fragment="",l=Lb;else s.query="",l=Pb;break;case Ob:if(o===tR||"/"===o||"\\"===o&&s.isSpecial()||!t&&("?"===o||"#"===o)){if(mb(d)?(s.shortenPath(),"/"===o||"\\"===o&&s.isSpecial()||xR(s.path,"")):pb(d)?"/"===o||"\\"===o&&s.isSpecial()||xR(s.path,""):("file"===s.scheme&&!s.path.length&&ub(d)&&(s.host&&(s.host=""),d=kR(d,0)+":"),xR(s.path,d)),d="","file"===s.scheme&&(o===tR||"?"===o||"#"===o))for(;s.path.length>1&&""===s.path[0];)VR(s.path);"?"===o?(s.query="",l=Pb):"#"===o&&(s.fragment="",l=Lb)}else d+=cb(o,sb);break;case Mb:"?"===o?(s.query="",l=Pb):"#"===o?(s.fragment="",l=Lb):o!==tR&&(s.path[0]+=cb(o,nb));break;case Pb:t||"#"!==o?o!==tR&&("'"===o&&s.isSpecial()?s.query+="%27":s.query+="#"===o?"%23":cb(o,nb)):(s.fragment="",l=Lb);break;case Lb:o!==tR&&(s.fragment+=cb(o,ab))}c++}},parseHost:function(e){var t,i,r;if("["===kR(e,0)){if("]"!==kR(e,e.length-1))return jR;if(t=function(e){var t,i,r,o,n,a,s,l=[0,0,0,0,0,0,0,0],c=0,d=null,u=0,h=function(){return kR(e,u)};if(":"===h()){if(":"!==kR(e,1))return;u+=2,d=++c}for(;h();){if(8===c)return;if(":"!==h()){for(t=i=0;i<4&&OR($R,h());)t=16*t+CR(h(),16),u++,i++;if("."===h()){if(0===i)return;if(u-=i,c>6)return;for(r=0;h();){if(o=null,r>0){if(!("."===h()&&r<4))return;u++}if(!OR(YR,h()))return;for(;OR(YR,h());){if(n=CR(h(),10),null===o)o=n;else{if(0===o)return;o=10*o+n}if(o>255)return;u++}l[c]=256*l[c]+o,2!==++r&&4!==r||c++}if(4!==r)return;break}if(":"===h()){if(u++,!h())return}else if(h())return;l[c++]=t}else{if(null!==d)return;u++,d=++c}}if(null!==d)for(a=c-d,c=7;0!==c&&a>0;)s=l[c],l[c--]=l[d+a-1],l[d+--a]=s;else if(8!==c)return;return l}(BR(e,1,-1)),!t)return jR;this.host=t}else if(this.isSpecial()){if(e=_R(e),OR(ZR,e))return jR;if(t=function(e){var t,i,r,o,n,a,s,l=FR(e,".");if(l.length&&""===l[l.length-1]&&l.length--,(t=l.length)>4)return e;for(i=[],r=0;r<t;r++){if(""===(o=l[r]))return e;if(n=10,o.length>1&&"0"===kR(o,0)&&(n=OR(JR,o)?16:8,o=BR(o,8===n?1:2)),""===o)a=0;else{if(!OR(10===n?QR:8===n?XR:$R,o))return e;a=CR(o,n)}xR(i,a)}for(r=0;r<t;r++)if(a=i[r],r===t-1){if(a>=NR(256,5-t))return null}else if(a>255)return null;for(s=LR(i),r=0;r<i.length;r++)s+=i[r]*NR(256,3-r);return s}(e),null===t)return jR;this.host=t}else{if(OR(eb,e))return jR;for(t="",i=pR(e),r=0;r<i.length;r++)t+=cb(i[r],nb);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return uR(db,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&ub(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,r=e.password,o=e.host,n=e.port,a=e.path,s=e.query,l=e.fragment,c=t+":";return null!==o?(c+="//",e.includesCredentials()&&(c+=i+(r?":"+r:"")+"@"),c+=ob(o),null!==n&&(c+=":"+n)):"file"===t&&(c+="//"),c+=e.cannotBeABaseURL?a[0]:a.length?"/"+MR(a,"/"):"",null!==s&&(c+="?"+s),null!==l&&(c+="#"+l),c},setHref:function(e){var t=this.parse(e);if(t)throw new wR(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new Ub(e.path[0]).origin}catch(uq){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+ob(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(gR(e)+":",fb)},getUsername:function(){return this.username},setUsername:function(e){var t=pR(gR(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=cb(t[i],lb)}},getPassword:function(){return this.password},setPassword:function(e){var t=pR(gR(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=cb(t[i],lb)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?ob(e):ob(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,Rb)},getHostname:function(){var e=this.host;return null===e?"":ob(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,bb)},getPort:function(){var e=this.port;return null===e?"":gR(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=gR(e))?this.port=null:this.parse(e,wb))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+MR(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,kb))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=gR(e))?this.query=null:("?"===kR(e,0)&&(e=BR(e,1)),this.query="",this.parse(e,Pb)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=gR(e))?("#"===kR(e,0)&&(e=BR(e,1)),this.fragment="",this.parse(e,Lb)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var Ub=function(e){var t=dR(this,Vb),i=vR(arguments.length,1)>1?arguments[1]:void 0,r=IR(t,new xb(e,!1,i));rR||(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())},Vb=Ub.prototype,Fb=function(e,t){return{get:function(){return AR(this)[e]()},set:t&&function(e){return AR(this)[t](e)},configurable:!0,enumerable:!0}};if(rR&&(cR(Vb,"href",Fb("serialize","setHref")),cR(Vb,"origin",Fb("getOrigin")),cR(Vb,"protocol",Fb("getProtocol","setProtocol")),cR(Vb,"username",Fb("getUsername","setUsername")),cR(Vb,"password",Fb("getPassword","setPassword")),cR(Vb,"host",Fb("getHost","setHost")),cR(Vb,"hostname",Fb("getHostname","setHostname")),cR(Vb,"port",Fb("getPort","setPort")),cR(Vb,"pathname",Fb("getPathname","setPathname")),cR(Vb,"search",Fb("getSearch","setSearch")),cR(Vb,"searchParams",Fb("getSearchParams")),cR(Vb,"hash",Fb("getHash","setHash"))),lR(Vb,"toJSON",function(){return AR(this).serialize()},{enumerable:!0}),lR(Vb,"toString",function(){return AR(this).serialize()},{enumerable:!0}),bR){var Bb=bR.createObjectURL,Hb=bR.revokeObjectURL;Bb&&lR(Ub,"createObjectURL",aR(Bb,bR)),Hb&&lR(Ub,"revokeObjectURL",aR(Hb,bR))}ER(Ub,"URL"),iR({global:!0,constructor:!0,forced:!oR,sham:!rR},{URL:Ub});var Wb=c;to({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return Wb(URL.prototype.toString,this)}});var Gb,jb=Object.create,zb=Object.defineProperty,Kb=Object.defineProperties,qb=Object.getOwnPropertyDescriptor,Yb=Object.getOwnPropertyDescriptors,Jb=Object.getOwnPropertyNames,Xb=Object.getOwnPropertySymbols,Qb=Object.getPrototypeOf,$b=Object.prototype.hasOwnProperty,Zb=Object.prototype.propertyIsEnumerable,ew=Reflect.get,tw=Math.pow,iw=(e,t,i)=>t in e?zb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,rw=(e,t)=>{for(var i in t||(t={}))$b.call(t,i)&&iw(e,i,t[i]);if(Xb)for(var i of Xb(t))Zb.call(t,i)&&iw(e,i,t[i]);return e},ow=(e,t)=>Kb(e,Yb(t)),nw=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),aw=(e,t)=>{for(var i in t)zb(e,i,{get:t[i],enumerable:!0})},sw=(e,t,i)=>(i=null!=e?jb(Qb(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of Jb(t))!$b.call(e,o)&&o!==i&&zb(e,o,{get:()=>t[o],enumerable:!(r=qb(t,o))||r.enumerable});return e})(!t&&e&&e.__esModule?i:zb(i,"default",{value:e,enumerable:!0}),e)),lw=(e,t,i,r)=>{for(var o,n=r>1?void 0:r?qb(t,i):t,a=e.length-1;a>=0;a--)(o=e[a])&&(n=(r?o(t,i,n):o(n))||n);return r&&n&&zb(t,i,n),n},cw=(e,t,i)=>iw(e,"symbol"!=typeof t?t+"":t,i),dw=(e,t,i)=>ew(Qb(e),i,t),uw=(e,t,i)=>new Promise((r,o)=>{var n=e=>{try{s(i.next(e))}catch(TM){o(TM)}},a=e=>{try{s(i.throw(e))}catch(TM){o(TM)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(n,a);s((i=i.apply(e,t)).next())}),hw=nw((e,t)=>{var i=Object.prototype.hasOwnProperty,r="~";function o(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,i,o,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var s=new n(i,o||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],s]:e._events[l].push(s):(e._events[l]=s,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new o:delete e._events[t]}function l(){this._events=new o,this._eventsCount=0}Object.create&&(o.prototype=Object.create(null),(new o).__proto__||(r=!1)),l.prototype.eventNames=function(){var e,t,o=[];if(0===this._eventsCount)return o;for(t in e=this._events)i.call(e,t)&&o.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},l.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 o=0,n=i.length,a=new Array(n);o<n;o++)a[o]=i[o].fn;return a},l.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},l.prototype.emit=function(e,t,i,o,n,a){var s=r?r+e:e;if(!this._events[s])return!1;var l,c,d=this._events[s],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,o),!0;case 5:return d.fn.call(d.context,t,i,o,n),!0;case 6:return d.fn.call(d.context,t,i,o,n,a),!0}for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d.fn.apply(d.context,l)}else{var h,p=d.length;for(c=0;c<p;c++)switch(d[c].once&&this.removeListener(e,d[c].fn,void 0,!0),u){case 1:d[c].fn.call(d[c].context);break;case 2:d[c].fn.call(d[c].context,t);break;case 3:d[c].fn.call(d[c].context,t,i);break;case 4:d[c].fn.call(d[c].context,t,i,o);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d[c].fn.apply(d[c].context,l)}}return!0},l.prototype.on=function(e,t,i){return a(this,e,t,i,!1)},l.prototype.once=function(e,t,i){return a(this,e,t,i,!0)},l.prototype.removeListener=function(e,t,i,o){var n=r?r+e:e;if(!this._events[n])return this;if(!t)return s(this,n),this;var a=this._events[n];if(a.fn)a.fn===t&&(!o||a.once)&&(!i||a.context===i)&&s(this,n);else{for(var l=0,c=[],d=a.length;l<d;l++)(a[l].fn!==t||o&&!a[l].once||i&&a[l].context!==i)&&c.push(a[l]);c.length?this._events[n]=1===c.length?c[0]:c:s(this,n)}return this},l.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new o,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=r,l.EventEmitter=l,void 0!==t&&(t.exports=l)}),pw=nw((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")})})}),mw=nw(e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var o=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:o&&!i[e.name]&&(i[e.name]={});var n=e.push?{}:o?i[e.name]:i;(function(e,i,r,o){if(o&&!r)i[o]=t(e[1]);else for(var n=0;n<r.length;n+=1)null!=e[n+1]&&(i[r[n]]=t(e[n+1]))})(r.match(e.reg),n,e.names,e.name),e.push&&i[e.push].push(n)},r=pw(),o=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},n=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(o).forEach(function(e){var t=e[0],o=e.slice(2);"m"===t&&(n.push({rtp:[],fmtp:[]}),a=n[n.length-1]);for(var s=0;s<(r[t]||[]).length;s+=1){var l=r[t][s];if(l.reg.test(o))return i(l,a,o)}}),t.media=n,t};var n=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(n,{})},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),o=0;o<r.length;o+=3)i.push({component:r[o],ip:r[o+1],port:r[o+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(n,{})})},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}})})}}),fw=nw((e,t)=>{var i=pw(),r=/%[sdv%]/g,o=function(e){var t=1,i=arguments,o=i.length;return e.replace(r,function(e){if(t>=o)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""}})},n=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 n=0;n<t.names.length;n+=1){var a=t.names[n];t.name?r.push(i[t.name][a]):r.push(i[t.names[n]])}else r.push(i[t.name]);return o.apply(null,r)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["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||a,o=t.innerOrder||s,l=[];return r.forEach(function(t){i[t].forEach(function(i){i.name in e&&null!=e[i.name]?l.push(n(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach(function(e){l.push(n(t,i,e))})})}),e.media.forEach(function(e){l.push(n("m",i.m[0],e)),o.forEach(function(t){i[t].forEach(function(i){i.name in e&&null!=e[i.name]?l.push(n(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach(function(e){l.push(n(t,i,e))})})})}),l.join("\r\n")+"\r\n"}}),_w=nw(e=>{var t=mw(),i=fw(),r=pw();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}),gw=((Gb=gw||{})[Gb.INVALID_PARAMETER=4096]="INVALID_PARAMETER",Gb[Gb.INVALID_OPERATION=4097]="INVALID_OPERATION",Gb[Gb.NOT_SUPPORTED=4098]="NOT_SUPPORTED",Gb[Gb.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",Gb[Gb.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",Gb[Gb.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",Gb[Gb.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",Gb[Gb.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",Gb[Gb.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",Gb[Gb.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",Gb[Gb.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",Gb[Gb.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",Gb[Gb.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",Gb[Gb.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",Gb[Gb.CLIENT_BANNED=16448]="CLIENT_BANNED",Gb[Gb.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",Gb[Gb.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",Gb[Gb.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",Gb[Gb.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",Gb[Gb.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",Gb[Gb.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",Gb[Gb.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",Gb[Gb.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",Gb[Gb.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",Gb[Gb.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",Gb[Gb.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",Gb[Gb.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",Gb[Gb.API_CALL_ABORTED=16461]="API_CALL_ABORTED",Gb[Gb.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",Gb[Gb.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",Gb[Gb.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",Gb[Gb.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",Gb[Gb.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",Gb[Gb.UNKNOWN=65535]="UNKNOWN",Gb),Ew=gw,vw=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=Ew.UNKNOWN,extraCode:o=0,constraint:n}=e,a="<".concat(function(e){for(let t in Ew)if(Ew[t]===e)return t;return"UNKNOWN"}(r)," 0x").concat(r.toString(16),">"),s="".concat(i).concat(n?" constraint: ".concat(n):"").concat(null!=i&&i.includes(a)?"":" ".concat(a));super(s),cw(this,"code"),cw(this,"extraCode"),cw(this,"message"),cw(this,"originMessage"),cw(this,"name"),cw(this,"constraint"),this.code=r,this.extraCode=o,this.name=t,this.message=s,this.constraint=n,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},yw=vw,Tw=function(){return 0},Iw=function(){return Date.now()+0},Aw=function(){let e=new Date;return e.setTime(Iw()),e.toLocaleString()},Sw=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)},Rw={};aw(Rw,{REPORT_TYPE:()=>WN,buildSSOPackage:()=>GN,bytes2ms:()=>GD,calculateScaleResolutionDownNumber:()=>VN,concatArrayBuffers:()=>jN,convertObjectNumberToInt:()=>MN,copyProperties:()=>WD,deepClone:()=>AN,deepCloneBasic:()=>HN,deepMerge:()=>IN,delay:()=>PN,fibonacci:()=>XD,formatedTime:()=>bN,getConstructorName:()=>dN,getContainerFromElement:()=>RN,getEnv:()=>kD,getFirst16Bits:()=>KN,getInternalVersion:()=>_N,getLast16Bits:()=>zN,getLoggerUrl:()=>PD,getMediaStreamTrackInfo:()=>UN,getMuteStateFromFlag:()=>vN,getNetworkType:()=>xD,getNumNetworkType:()=>HD,getReconnectionTimeout:()=>QD,getStringByteLength:()=>DN,getTestSignalDomain:()=>OD,getTurnServer:()=>yN,getUint32Version:()=>ON,getValueType:()=>$D,getViewListFromView:()=>SN,glog:()=>qD,ipv4ToUint32:()=>TN,isArray:()=>nN,isAudioWorkletSupported:()=>uN,isBoolean:()=>rN,isConstructor:()=>cN,isEmpty:()=>EN,isFunction:()=>ZD,isLangChinese:()=>YD,isMediaStreamTrack:()=>aN,isNumber:()=>iN,isObject:()=>oN,isOverseaSdkAppId:()=>MD,isPlainObject:()=>JD,isPortrait:()=>NN,isPromise:()=>lN,isRemoteTrack:()=>sN,isRotate90Or270:()=>FN,isSetSinkIdSupported:()=>hN,isString:()=>tN,isUndefined:()=>eN,loadImage:()=>kN,loadVideo:()=>BN,ms2bytes:()=>zD,ms2samples:()=>KD,normalizeUrl:()=>xN,performanceNow:()=>mN,promiseAny:()=>pN,samples2ms:()=>jD,setNetworkTypeFromWebRTC:()=>BD,stringify:()=>wN,stringifyIncludeValue:()=>CN,throttlePromise:()=>LN});var bw={};aw(bw,{ASR_ROBOT_FROM_TYPE:()=>cD,AUDIO_MUTE_BIT:()=>mC,AUDIO_STAT_BIT:()=>pC,AUX_STAT_BIT:()=>hC,AUX_STREAM_MSID:()=>yC,BACKEND_ENV:()=>lC,BASE_DOC_URL:()=>Hw,BASE_HOST:()=>Uw,CAPABILITIES_KEYS:()=>sD,CLASS_NAME:()=>$C,CLOUD_CONSOLE_URL:()=>Bw,CROSS_ROOM_BIT:()=>gC,DATA_CHANNEL_FROM_TYPE_BIT:()=>EC,DATA_FREEZE_TIMING:()=>zC,DOC_BILLING_CN:()=>Gw,DOC_BILLING_OVERSEA:()=>jw,DOC_URL:()=>Ww,DTLS_STATE_UNKNOWN:()=>NC,ENV_NAME:()=>Jw,EXCHANGE_SDP_TIMEOUT:()=>BC,IS_WORKER:()=>Ow,IS_WORKLET:()=>Mw,KIBANA_EVENT:()=>UC,LOCAL_STREAM_PUBLISH_STATE:()=>jC,LOGGER_CMD_TYPE:()=>Yw,LOGGER_DOMAIN:()=>zw,LOGGER_DOMAIN_OVERSEA:()=>Kw,LOG_LEVEL:()=>Xw,LOG_LEVEL_NAME:()=>rD,MAIN_STREAM_MSID:()=>vC,MAX_RTT:()=>lD,MICROPHONE_COMMUNICATIONS:()=>iD,MICROPHONE_DEFAULT:()=>eD,MUTE_ALL_BIT:()=>_C,NAME:()=>aC,NETWORK_TYPE:()=>Zw,NOT_SUPPORTED_H264:()=>GC,PAUSED_RETRY_COUNT:()=>ZC,PEERCONNECTION_CONNECTING_TIMEOUT:()=>JC,PEER_CONNECTION_STATE:()=>kC,PEER_LEAVE_REASON:()=>oD,RECOVER_CAPTURE_INTERVAL:()=>aD,REMOTE_STREAM_TYPE_AUX:()=>IC,REMOTE_STREAM_TYPE_MAIN:()=>TC,RENDER_FREEZE_TIMING:()=>KC,SCHEDULE_DOMAIN:()=>XC,SCHEDULE_TIMEOUT:()=>QC,SDP_SEMANTICS_PLAN_B:()=>WC,SDP_SEMANTICS_UNIFIED_PLAN:()=>HC,SECOND_HOST:()=>Vw,SIGNAL_PING_PONG_INTERVAL:()=>$w,SIGNAL_PING_TIMEOUT:()=>Qw,SIGNAL_RECONNECTION_COUNT:()=>xC,SMALL_STAT_BIT:()=>uC,SPEAKER_DEFAULT:()=>tD,STORAGE_EXPIRES_TIME:()=>eC,STREAM_TYPE_BIG:()=>qC,STREAM_TYPE_SMALL:()=>YC,SUBSCRIBE_SMALL_RETRY_COUNT:()=>nD,SYNC_USER_LIST_INTERVAL:()=>VC,Scene:()=>cC,THIRD_HOST:()=>Fw,TRANSPORT_DIRECTION:()=>sC,TRTC_ERROR_ASSISTANCE:()=>qw,TRTC_QUALITY_BAD:()=>wC,TRTC_QUALITY_DISCONNECTED:()=>DC,TRTC_QUALITY_EXCELLENT:()=>SC,TRTC_QUALITY_GOOD:()=>RC,TRTC_QUALITY_POOR:()=>bC,TRTC_QUALITY_UNKNOWN:()=>AC,TRTC_QUALITY_VERY_BAD:()=>CC,UPDATE_OFFER_TIMEOUT:()=>FC,VIDEO_MUTE_BIT:()=>fC,VIDEO_STAT_BIT:()=>dC,WEBGL_ATTRIBUTES:()=>dD,audioProfileMap:()=>tC,defaultBigVideoProfile:()=>rC,defaultSmallVideoProfile:()=>oC,getRetryCount:()=>PC,getScriptDir:()=>Pw,innerVersion:()=>ww,loggerProxy:()=>Lw,screenProfileMap:()=>nC,setLoggerProxy:()=>xw,setRetryCount:()=>MC,setVersion:()=>Dw,version:()=>Cw,videoProfileMap:()=>iC});var ww="4.15.00.1600",Cw="5.0.0";function Dw(e){Cw=e;let[t,i,r]=e.split(".").map(e=>parseInt(e,10));ww="".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 Nw,kw,Ow="undefined"!=typeof importScripts,Mw="undefined"!=typeof registerProcessor,Pw=()=>{let e=Ow?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Lw="",xw=e=>Lw=e,Uw="web.sdk.qcloud.com",Vw="web.sdk.tencent.cn",Fw="web.sdk.cloud.tencent.cn",Bw="https://console.cloud.tencent.com/trtc",Hw="https://".concat(Uw,"/trtc/webrtc/doc"),Ww="".concat(Hw,"/zh-cn/"),Gw="https://cloud.tencent.com/document/product/647/85386",jw="https://trtc.io/document/56025",zw="https://yun.tim.qq.com",Kw="https://apisgp.my-imcloud.com",qw="trtc_error_assistance",Yw={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Jw={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Xw=((kw=Xw||{})[kw.TRACE=0]="TRACE",kw[kw.DEBUG=1]="DEBUG",kw[kw.INFO=2]="INFO",kw[kw.WARN=3]="WARN",kw[kw.ERROR=4]="ERROR",kw[kw.NONE=5]="NONE",kw),Qw=18e3,$w=2e3,Zw={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},eC=6048e5,tC={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}},iC={"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}},rC=iC["480p_2"],oC=iC["120p_2"],nC={"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}},aC={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",LOADSTART:"loadstart",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",FULLSCREEN_CHANGE:"fullscreenchange",RESIZE:"resize",TIME_UPDATE:"timeupdate"},sC={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},lC={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},cC=((Nw=cC||{}).LIVE="live",Nw.RTC="rtc",Nw),dC=1,uC=2,hC=4,pC=8,mC=64,fC=16,_C=112,gC=128,EC=256,vC="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",yC="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",TC=aC.MAIN,IC=aC.AUXILIARY,AC=0,SC=1,RC=2,bC=3,wC=4,CC=5,DC=6,NC="unknown",kC={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},OC=1/0;function MC(e){OC=e}function PC(){return OC}var LC,xC=30,UC={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",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",VIDEO_ENCODE_RESUME_DURING_CALL:"video-encode-resume-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call",AUDIO_ENCODE_RESUME_DURING_CALL:"audio-encode-resume-during-call",VIDEO_DECODE_FAILED_DURING_CALL:"video-decode-failed-during-call",VIDEO_DECODE_RESUME_DURING_CALL:"video-decode-resume-during-call",AUDIO_DECODE_FAILED_DURING_CALL:"audio-decode-failed-during-call",AUDIO_DECODE_RESUME_DURING_CALL:"audio-decode-resume-during-call",VIDEO_HARDWARE_DECODE_FAILED:"video-hardware-decode-failed",VIDEO_HARDWARE_DECODE_RESUME:"video-hardware-decode-resume"},VC=1e4,FC=1e4,BC=1e4,HC="unified-plan",WC="plan-b",GC=1028,jC=((LC=jC||{})[LC.UNPUBLISH=-1]="UNPUBLISH",LC[LC.PUBLISHING=0]="PUBLISHING",LC[LC.PUBLISHED=1]="PUBLISHED",LC),zC=500,KC=1e3,qC=aC.BIG,YC=aC.SMALL,JC=1e4,XC={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"},QC=2e3,$C={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},ZC=5,eD="default",tD=eD,iD="communications",rD=Object.keys(Xw),oD=["normal leave","timeout leave","kick","role change"],nD=10,aD=2e3,sD=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],lD=1e4,cD=14,dD={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},uD=function(e,t,i,r){return new(i||(i=Promise))(function(o,n){function a(e){try{l(r.next(e))}catch(t){n(t)}}function s(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){e.done?o(e.value):function(e){return e instanceof i?e:new i(function(t){t(e)})}(e.value).then(a,s)}l((r=r.apply(e,t||[])).next())})},hD=Symbol(32),pD=Symbol(16),mD=Symbol(8),fD=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 uD(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(hD)}readU16(){return this.read(pD)}readU8(){return this.read(mD)}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===hD){if(r(4))return;e=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===pD){if(r(2))return;e=t[0]<<8|t[1]}else if(this.need===mD){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}};fD.U32=hD,fD.U16=pD,fD.U8=mD;var _D=128;function gD(e){let t=new fD;for(;e>=128;)t.malloc(1)[0]=255&e|_D,e>>>=7;return t.malloc(1)[0]=255&e,t.buffer||new Uint8Array(0)}function ED(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=new fD,r=t<<3;switch(typeof e){case"boolean":let o=i.malloc(2);o[0]=r,o[1]=e?1:0;break;case"number":i.malloc(1)[0]=r,i.write(gD(e));break;case"string":i.malloc(1)[0]=2|r;let n=(new TextEncoder).encode(e);i.write(gD(n.length));let a=i.malloc(n.length);for(let e=0;e<n.length;e++)a[e]=n[e];break;case"object":let s=new fD;if(Array.isArray(e))for(let t=0;t<e.length;t++){let i=ED(e[t],t+1);i&&s.write(i)}else{let t=1;for(let i in e){let r=ED(e[i],t++);r&&s.write(r)}}0===t?s.buffer&&i.write(s.buffer):(i.malloc(1)[0]=2|r,s.buffer&&(i.write(gD(s.buffer.length)),i.write(s.buffer)))}return i.buffer||new Uint8Array(0)}var vD=class{constructor(){cw(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 yD(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 TD(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function ID(e,t){return e[t]}function AD(e,t,i){return(new TextDecoder).decode(function(e,t,i){return e.slice(t,t+i)}(e,t,i))}var SD=0,RD=2654435769,bD=16,wD=2,CD=7;function DD(e,t){let i=new vD,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,SD);SD=SD+1&2147483647,i.writeInt32(0),i.writeInt32(r.version),i.writeByte(r.encryption);let o=(new TextEncoder).encode(r.d2);i.writeInt32(o.length+4),o&&i.writeBytes(o),i.writeByte(r.uinType);let n=(new TextEncoder).encode(r.uin);i.writeInt32(n.length+4),n.length&&i.writeBytes(n);let a=new vD;a.writeInt32(0),a.writeInt32(r.reqHead.seqNumber),a.writeInt32(r.reqHead.appId),a.writeByte(r.reqHead.appId>>>24&255),a.writeByte(r.reqHead.appId>>>16&255),a.writeByte(r.reqHead.appId>>>8&255),a.writeByte(255&r.reqHead.appId);for(let E=4;E<16;E++)a.writeByte(0);let s=(new TextEncoder).encode(r.reqHead.a2);a.writeInt32(s.length+4),s.length&&a.writeBytes(s);let l=(new TextEncoder).encode(r.reqHead.serviceCmd);a.writeInt32(l.length+4),l.length&&a.writeBytes(l);let c=(new TextEncoder).encode(r.reqHead.cookie);a.writeInt32(c.length+4),c.length&&a.writeBytes(c);let d=(new TextEncoder).encode(r.reqHead.imei);a.writeInt32(d.length+4),d.length&&a.writeBytes(d);let u=(new TextEncoder).encode(r.reqHead.ksid);a.writeInt32(u.length+4),u.length&&a.writeBytes(u);let h=(new TextEncoder).encode(r.reqHead.clientVersionInfo);a.writeInt16(h.length+2),h.length&&a.writeBytes(h);let p=a.length;a.data[0]=p>>>24&255,a.data[1]=p>>>16&255,a.data[2]=p>>>8&255,a.data[3]=255&p,tN(e)&&(e=(new TextEncoder).encode(e)),a.writeInt32(e.length+4),e.length&&a.writeBytes(e);let m=new Uint8Array(a.data),f=null;1===r.encryption?f=(new TextEncoder).encode(r.uin):2===r.encryption&&(f=new Uint8Array(16)),f&&(m=function(e,t){let i=e.length,r=(i+1+wD+CD)%8;r&&(r=8-r);let o=i+1+wD+CD+r,n=new Uint8Array(o),a=0,s=new Uint8Array(8),l=new Uint8Array(8),c=new Uint8Array(8),d=0;s[0]=248&Math.floor(256*Math.random())|r,d=1;for(let h=0;h<r;h++)s[d]=255&Math.floor(256*Math.random()),d+=1;for(let h=0;h<wD;)if(d<8&&(s[d]=255&Math.floor(256*Math.random()),d+=1,h+=1),8===d){ND(s,t,l,c,n,a),a+=8,d=0;for(let e=0;e<8;e++)c[e]=n[a-8+e]}let u=0;for(;u<i;)if(d<8&&(s[d]=e[u],d+=1,u+=1),8===d){ND(s,t,l,c,n,a),a+=8,d=0;for(let e=0;e<8;e++)c[e]=n[a-8+e]}for(let h=0;h<CD;)if(d<8&&(s[d]=0,d+=1,h+=1),8===d){ND(s,t,l,c,n,a),a+=8,d=0;for(let e=0;e<8;e++)c[e]=n[a-8+e]}return n}(m,f)),i.writeBytes(m);let _=new Uint8Array(i.data),g=_.length;return _[0]=g>>>24&255,_[1]=g>>>16&255,_[2]=g>>>8&255,_[3]=255&g,_}function ND(e,t,i,r,o,n){for(let a=0;a<8;a++)e[a]^=r[a];!function(e,t,i,r){let o=TD(e,0),n=TD(e,4),a=[];for(let l=0;l<4;l++)a[l]=TD(t,4*l);let s=0;for(let l=0;l<bD;l++)s+=RD,s>>>=0,o+=(n<<4)+a[0]^n+s^(n>>>5)+a[1],o>>>=0,n+=(o<<4)+a[2]^o+s^(o>>>5)+a[3],n>>>=0;yD(i,o,r),yD(i,n,r+4)}(e,t,o,n);for(let a=0;a<8;a++)o[n+a]^=i[a];for(let a=0;a<8;a++)i[a]=e[a]}var kD=function(){return new URLSearchParams(location.search).get("trtc_env")||""},OD=function(e){return e.includes(".")?e:"".concat(e).concat(".rtc.qq.com")},MD=e=>Number(e)<14e8,PD=function(e,t){let i;i=Lw||(MD(e)?Kw:zw);let r=Math.floor(Math.random()*tw(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},LD="unknown";function xD(){!function(){var e;VD||(VD=!0,null==(e=navigator.connection)||e.addEventListener("typechange",UD))}();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(),o=t&&t.effectiveType&&t.effectiveType.toLowerCase();return"slow-2"===o&&(o="2g"),r?FD(r,o):LD}function UD(){fM.warn("netType changed",xD())}var VD=!1;function FD(e,t){if(Zw[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function BD(e){LD=FD(e)}function HD(){return Zw[xD()]}function WD(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 GD(e){return jD(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function jD(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function zD(e){return 4*KD(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function KD(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var qD="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},YD=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},JD=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 XD(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:XD(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function QD(e){return e>8?3e4:1e3*XD(e)}function $D(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ZD=e=>"function"==typeof e,eN=e=>void 0===e,tN=e=>"string"==typeof e,iN=e=>"number"==typeof e,rN=e=>"boolean"==typeof e,oN=e=>"object"===$D(e),nN=e=>"array"===$D(e),aN=e=>$D(e)==="MediaStreamTrack".toLowerCase(),sN=e=>e.isRemote,lN=e=>"promise"===$D(e),cN=e=>ZD(e)&&e.prototype.constructor===e,dN=e=>cN(e)?e.prototype.constructor.name:"",uN="undefined"!=typeof AudioWorkletNode,hN="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype;function pN(e){return new Promise((t,i)=>{let r=[];e.forEach(o=>{o.then(t).catch(t=>{r.push(t),r.length===e.length&&i(r)})})})}function mN(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var fN=e=>+e<10?"0".concat(e):e,_N=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=fN(i[1])+fN(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},gN=Object.prototype.hasOwnProperty;function EN(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(JD(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(gN.call(e,t))return!1;return!0}return!1}function vN(e,t){return{userId:t,hasAudio:!!(e&pC),hasVideo:!!(e&dC),hasAuxiliary:!!(e&hC),hasSmall:!!(e&uC),audioMuted:!!(e&mC),videoMuted:!!(e&fC),audioAvailable:!(!(e&pC)||e&mC),videoAvailable:!(!(e&dC)||e&fC),hasDatachannel:!!(e&EC)}}function yN(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!eN(e.username)&&!eN(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",eN(e.credentialType)||(t.credentialType=e.credentialType)),t}function TN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!tN(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 IN=function(e,t,i,r){if(!oN(e)||!oN(t))return 0;let o,n=0,a=Object.keys(t);for(let s=0,l=a.length;s<l;s++)if(o=a[s],!(eN(t[o])||i&&i.includes(o)))if(oN(e[o])&&oN(t[o]))n+=IN(e[o],t[o],i,r);else{if(r&&r.includes(t[o]))continue;e[o]!==t[o]&&(e[o]=AN(t[o]),n+=1)}return n};function AN(e){if(nN(e)){let t=[];return e.forEach((e,i)=>{t[i]=AN(e)}),t}if(oN(e)){let t={};return Object.keys(e).forEach(i=>{t[i]=AN(e[i])}),t}return e}var SN=e=>{let t=[];if(nN(e))t=[...e];else if(tN(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},RN=e=>tN(e)?document.getElementById(e):e,bN=()=>(e=>{let t=e=>e<10?"0".concat(e):"".concat(e),i=e.getFullYear(),r=e.getMonth()+1,o=e.getDate(),n=t(e.getHours()),a=t(e.getMinutes()),s=t(e.getSeconds());return"".concat(i,"/").concat(r,"/").concat(o," ").concat(n,":").concat(a,":").concat(s)})(new Date);function wN(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(nN(e))return"[".concat(e.map(e=>wN(e,{keysToInclude:i,keysToExclude:r})).join(","),"]");if(!JD(e)||!nN(i)&&!nN(r))return JSON.stringify(e);let t={},o=new Set(i),n=new Set(r);return Object.keys(e).forEach(a=>{(0===n.size&&o.has(a)||0===o.size&&!n.has(a))&&(t[a]=JD(e[a])||nN(e[a])?JSON.parse(wN(e[a],{keysToExclude:r,keysToInclude:i})):e[a])}),JSON.stringify(t)}catch(LC){return"{}"}}function CN(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)}),wN(e,{keysToInclude:i})}function DN(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var NN=()=>{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},kN=e=>uw(null,null,function*(){return new Promise((t,i)=>{let r;if(tN(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 yw({code:Ew.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}})}),ON=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},MN=e=>(Object.keys(e).forEach(t=>{iN(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(JD(e[t])||nN(e[t]))&&MN(e[t])}),e);function PN(e,t){return new Promise(i=>{let r=setTimeout(i,e);t&&t(r)})}function LN(e,t){let i=null;return function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];return i||(i=e.apply(t||this,o),i.finally(()=>i=null),i)}}function xN(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function UN(e){var t;try{let{width:i,height:r,frameRate:o,sampleRate:n,sampleSize:a,channelCount:s}=null==(t=e.getSettings)?void 0:t.call(e),l=e.kind===aC.AUDIO?"".concat(n,"x").concat(a,"@").concat(s):"".concat(i,"x").concat(r,"@").concat(o),c=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(l).concat(c)}catch(Nw){return""}}function VN(e,t){return e.width*e.height===t.width*t.height?1:NN()&&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 FN(e){return 90===e||270===e}function BN(e){return uw(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 HN(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]=HN(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]=HN(e[r],t)}),i}return e}var WN=(e=>(e[e.END_REPORT=2001]="END_REPORT",e[e.LOG=2002]="LOG",e[e.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",e))(WN||{});function GN(e,t,i,r){try{let o=function(e,t,i,r){let o={data:e,random:Math.floor(2147483648*Math.random()),sdkAppId:i};return eN(r)||(o=ow(rw({},o),{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(o)}}}(e,t,i,r);return DD(ED(o),i)}catch(SM){return JSON.stringify(e)}}function jN(e,t){let i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i.buffer}function zN(e){return(65535&e)>>>0}function KN(e){return(4294901760&e)>>>0}function qN(e){let t=function(e){try{let t={},i=0;t.totalLength=TD(e,i),i+=4,t.version=TD(e,i),i+=4,t.encryption=ID(e,i),i+=1,t.uinType=ID(e,i),i+=1,t.uinLength=TD(e,i),i+=4,t.uin=t.uinLength>4?AD(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),o=new Uint8Array(e.slice(0,8)),n=YN(o,t),a=7&n[0],s=e.length-1-a-wD-CD,l=new Uint8Array(s),c=0,d=r,u=e.slice(0,8);i=8;let h=1;h+=a;for(let m=1;m<=wD;)if(h<8)h++,m++;else if(8===h){let r=JN(e,i,d,u,n,t);d=r.ivPreCrypt,u=r.ivCurCrypt,n=r.debiBuf,i=r.bufPos,h=0}let p=s;for(;p>0;)if(h<8)l[c++]=n[h]^d[h],h++,p--;else if(8===h){let r=JN(e,i,d,u,n,t);d=r.ivPreCrypt,u=r.ivCurCrypt,n=r.debiBuf,i=r.bufPos,h=0}for(let m=1;m<=CD;)if(h<8)n[h],d[h],h++,m++;else if(8===h){if(i>=e.length)break;let r=JN(e,i,d,u,n,t);if(!r.success)break;d=r.ivPreCrypt,u=r.ivCurCrypt,n=r.debiBuf,i=r.bufPos,h=0}return l}(r,new Uint8Array(16).fill(0)),t.decrypted=!0,i=0}else e=r,i=0;return t.rspHeadLength=TD(e,i),i+=4,t.seqNo=TD(e,i),i+=4,t.retCode=TD(e,i),i+=4,t.retStrLength=TD(e,i),i+=4,t.retStr=t.retStrLength?AD(e,i,t.retStrLength-4):"",i+=t.retStrLength-4,t.serviceCmdLength=TD(e,i),i+=4,t.serviceCmd=t.serviceCmdLength?AD(e,i,t.serviceCmdLength-4):"",i+=t.serviceCmdLength-4,t.cookieLength=TD(e,i),i+=4,t.cookie=t.cookieLength?AD(e,i,t.cookieLength-4):"",i+=t.cookieLength-4,t.flag=TD(e,i),i+=4,t.busiBuffLength=TD(e,i),i+=4,t.busiBuff=t.busiBuffLength?AD(e,i,t.busiBuffLength-4):"",i+=t.busiBuffLength-4,t}catch(t){}}(e);return null==t?void 0:t.busiBuff}function YN(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 o=RD*bD>>>0;for(let n=0;n<bD;n++)r-=(i<<4)+t[2]^i+o^(i>>>5)+t[3],r>>>=0,i-=(r<<4)+t[0]^r+o^(r>>>5)+t[1],i>>>=0,o-=RD,o>>>=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 JN(e,t,i,r,o,n){if(t+8>e.length)return{success:!1};let a=new Uint8Array(r),s=e.slice(t,t+8),l=new Uint8Array(8);for(let c=0;c<8;c++)l[c]=o[c]^s[c];return{success:!0,ivPreCrypt:a,ivCurCrypt:s,debiBuf:YN(l,n),bufPos:t+8}}var XN="undefined"!=typeof TextDecoder?new TextDecoder:void 0;function QN(e){let{url:t,body:i,method:r="POST",timeout:o,priority:n}=e;return new Promise((e,a)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:n}).then(e=>e.clone().json().then(e=>({data:e}),()=>e.arrayBuffer().then(e=>({data:qN(new Uint8Array(e))||(XN?XN.decode(e):e)})))).then(e,a);let s=new XMLHttpRequest;s.onreadystatechange=()=>{if(4===s.readyState)if(s.status>=200&&s.status<300)try{let t=JSON.parse(s.response);e({data:t})}catch(wM){e({data:s.response})}else a({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=o||5e3,s.open(r,t,!0),s.send(i)})}function $N(e){return uw(this,null,function*(){let t=mN(),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 fM.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(mN()-t,"ms")),r}catch(LC){return i}})}var ZN=Object.prototype.hasOwnProperty,ek=e=>"function"==typeof e,tk=e=>void 0===e,ik=e=>e.isRemote,rk=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 ok=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:o,onRetryFailed:n,onRetrySuccess:a,context:s}=e;return function(){for(var e=arguments.length,l=new Array(e),c=0;c<e;c++)l[c]=arguments[c];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,f=(e,i)=>uw(this,null,function*(){let c=s||this;try{let i=yield t.apply(c,l);h>0&&a&&a.call(this,h),h=0,e(i)}catch(_){let t=()=>{clearTimeout(p),h=0,m=2,i(_)},a=()=>{2!==m&&h<(ek(d)?d():d)?(h++,m=1,ek(o)&&o.call(this,h,t),p=window.setTimeout(()=>{p=-1,f(e,i)},ek(u)?u(h):u)):(t(),ek(n)&&n.call(this,_))};ek(r)?r.call(this,{error:_,retry:a,reject:i,retryFuncArgs:l,retriedCount:h}):a()}});return new Promise(f)}},nk=class e{constructor(e){cw(this,"_parentPath"),cw(this,"userId"),cw(this,"remoteUserId"),cw(this,"id"),cw(this,"sdkAppId"),cw(this,"type"),cw(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!(e=>"boolean"==typeof e)(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}getFullId(){return this._parentPath&&this.id?"".concat(this._parentPath,"-").concat(this.id):this._parentPath?this._parentPath:this.id}createChild(t){let i=new e({id:t.id,userId:tk(t.userId)?this.userId:t.userId,sdkAppId:tk(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:tk(t.type)?this.type:t.type,isLocal:tk(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:tk(t.remoteUserId)?this.remoteUserId:t.remoteUserId});return i.bindParent(this),i}bindParent(e){let t=e.getFullId();this._parentPath!==t&&(this.debug("bind logger parent: ".concat(e.id)),this._parentPath=t,this.userId=e.userId||this.userId,this.sdkAppId=e.sdkAppId||this.sdkAppId)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId,r=this.getFullId();t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(r).concat(i?"|".concat(i):"","]")),fM.log(e,t,tk(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(rk(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(ZN.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)}},ak={};aw(ak,{ANDROID_VERSION:()=>yk,CHROME_MAJOR_VERSION:()=>RO,CHROME_VERSION:()=>wO,EDGE_VERSION:()=>wk,EDG_MAJOR_VERSION:()=>Nk,EDG_VERSION:()=>Dk,ELECTRON_MAJOR_VERSION:()=>CO,FIREFOX_MAJOR_VERSION:()=>Rk,FIREFOX_VERSION:()=>Sk,HUAWEI_VERSION:()=>uO,IE_VERSION:()=>Hk,IOS_MAIN_VERSION:()=>xO,IOS_VERSION:()=>MO,IPADQQB_VERSION:()=>$k,IS_ANDROID:()=>vk,IS_ANDROID_WEBVIEW:()=>OO,IS_ANY_SAFARI:()=>NO,IS_CHROME:()=>AO,IS_CHROME_OS:()=>iO,IS_CHROMIUM_128_TO_143:()=>bO,IS_CHROMIUM_BASE:()=>IO,IS_DESKTOP_IOS_CHROME:()=>BO,IS_EDG:()=>Ck,IS_EDGE:()=>bk,IS_ELECTRON:()=>nO,IS_FIREFOX:()=>Ak,IS_HEADLESS_CHROME:()=>SO,IS_HONOR:()=>dO,IS_HUAWEI:()=>cO,IS_HUAWEIBROWSER:()=>lO,IS_IE:()=>Bk,IS_IE8:()=>Fk,IS_IOS:()=>gk,IS_IOS_13_OR_14:()=>FO,IS_IOS_15_1:()=>VO,IS_IOS_CHROME:()=>TO,IS_IPAD:()=>pk,IS_IPADQQB:()=>Qk,IS_IPAD_PRO:()=>mk,IS_IPHONE:()=>fk,IS_IPOD:()=>_k,IS_LINUX:()=>tO,IS_LOCAL:()=>HO,IS_MAC:()=>eO,IS_MACQQB:()=>Jk,IS_MIBROWSER:()=>aO,IS_MQQB:()=>zk,IS_NATIVE_ANDROID:()=>Ik,IS_OLD_ANDROID:()=>Tk,IS_OPENHARMONY:()=>EO,IS_OPPOBROWSER:()=>mO,IS_SAFARI:()=>DO,IS_SAFARI_15_1:()=>UO,IS_SAMSUNGBROWSER:()=>hO,IS_SOGOU:()=>Mk,IS_SOGOUM:()=>kk,IS_TBS:()=>Lk,IS_UCBROWSER:()=>oO,IS_VIVOBROWSER:()=>_O,IS_WECHAT:()=>Wk,IS_WIN:()=>Zk,IS_WQQB:()=>qk,IS_WX:()=>rO,IS_X5MQQB:()=>jk,IS_XWEB:()=>Uk,MACQQB_VERSION:()=>Xk,MI_VERSION:()=>sO,MQQB_VERSION:()=>Kk,OPENHARMONY_VERSION:()=>vO,OPPO_VERSION:()=>fO,SAFARI_VERSION:()=>kO,SAMSUNG_VERSION:()=>pO,SOGOUM_VERSION:()=>Ok,SOGOU_VERSION:()=>Pk,TBS_VERSION:()=>xk,UA_DATA_STRING:()=>qO,USER_AGENT:()=>sk,VIVO_VERSION:()=>gO,WECHAT_VERSION:()=>Gk,WQQB_VERSION:()=>Yk,XWEB_VERSION:()=>Vk,browserInfo:()=>GO,getBrowserCoreNumber:()=>nM,getBrowserInfo:()=>jO,getChromeMajorVersion:()=>yO,getDeviceModel:()=>eM,getDeviceModelFromUA:()=>tM,getGPUInfo:()=>XO,getOSName:()=>rM,getOSNumber:()=>oM,getOSString:()=>aM,getOSType:()=>lM,getTerminalType:()=>sM,getUserAgentData:()=>YO,isAMDGPU:()=>QO,isAppleSiliconGPU:()=>ZO,isLocalStorageEnabled:()=>WO,isMobile:()=>KO,isNvidiaGPU:()=>$O,isRealIOS:()=>Ek,isVersionLargerThan:()=>LO,isVersionSmallerThan:()=>PO});var sk="undefined"==typeof navigator?"":navigator.userAgent,lk=e=>new RegExp(e,"i").test(sk),ck=e=>{if(lk(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=sk.match(t);if(i&&i[1])return i[1]}return""},dk=e=>{if(lk(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=sk.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},uk=/AppleWebKit\/([\d.]+)/i.exec(sk),hk=uk?parseFloat(uk[1]):NaN,pk=lk("iPad"),mk="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&lk("Macintosh"),fk=lk("iPhone")&&!pk,_k=lk("iPod"),gk=fk||pk||_k||mk,Ek=()=>{try{return gk&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch(XH){return gk}},vk=lk("Android"),yk=function(){if(vk){let e=sk.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}(),Tk=vk&&lk("webkit")&&yk<2.3,Ik=vk&&yk<5&&hk<537,Ak=lk("Firefox"),Sk=ck("Firefox"),Rk=dk("Firefox"),bk=lk("Edge"),wk=ck("Edge"),Ck=lk("Edg"),Dk=ck("Edg"),Nk=dk("Edg"),kk=lk("SogouMobileBrowser"),Ok=ck("SogouMobileBrowser"),Mk=lk("MetaSr\\s"),Pk=ck("MetaSr\\s"),Lk=lk("TBS"),xk=ck("TBS"),Uk=lk("XWEB"),Vk=ck("XWEB"),Fk=lk("MSIE\\s8\\.0"),Bk=lk("MSIE\\/\\d+"),Hk=function(){if(Bk){let e=/MSIE\s(\d+)\.\d/.exec(sk),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(sk)&&/rv:11.0/.test(sk)&&(t=11),t}return NaN}(),Wk=lk("(micromessenger|webbrowser)"),Gk=ck("MicroMessenger"),jk=!Lk&&lk("MQQBrowser")&&lk("COVC"),zk=!Lk&&lk("MQQBrowser")&&!lk("COVC"),Kk=zk||jk?ck("MQQBrowser"):"",qk=!Lk&&lk(" QQBrowser"),Yk=ck(" QQBrowser"),Jk=!Lk&&lk("QQBrowserLite"),Xk=ck("QQBrowserLite"),Qk=!Lk&&lk("MQBHD"),$k=ck("MQBHD"),Zk=lk("Windows"),eO=!gk&&lk("MAC OS X"),tO=!vk&&lk("Linux"),iO=lk("CrOS"),rO=lk("MicroMessenger"),oO=lk("UCBrowser"),nO=lk("Electron"),aO=lk("MiuiBrowser"),sO=ck("MiuiBrowser"),lO=lk("HuaweiBrowser"),cO=lk("Huawei")||lk("HUAWEI"),dO=lk("Honor")||lk("HONOR"),uO=ck("HuaweiBrowser"),hO=lk("SamsungBrowser"),pO=ck("SamsungBrowser"),mO=lk("HeyTapBrowser"),fO=ck("HeyTapBrowser"),_O=lk("VivoBrowser"),gO=ck("VivoBrowser"),EO=lk("OpenHarmony"),vO=ck("OpenHarmony"),yO=()=>dk("Chrome"),TO=lk("CriOS"),IO=lk("Chrome"),AO=!bk&&!Mk&&!kk&&!Lk&&!Uk&&!Ck&&!qk&&!aO&&!lO&&!hO&&!mO&&!_O&&IO,SO=lk("HeadlessChrome"),RO=yO(),bO=IO&&RO>=128&&RO<=143,wO=ck("Chrome"),CO=dk("Electron"),DO=!IO&&!zk&&!jk&&!Jk&&!Qk&&lk("Safari"),NO=DO||gk,kO=ck("Version"),OO=/Android.*(wv|.0.0.0)/.test(sk),MO=(()=>{if(mk)return kO;if(gk){let e=sk.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})();function PO(e,t){let i=e.split(".").map(e=>Number(e)),r=t.split(".").map(e=>Number(e));for(let o=0;o<Math.max(i.length,r.length);o++){let e=i[o]||0,t=r[o]||0;if(e<t)return!0;if(e>t)return!1}return!1}function LO(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=e.split(".").map(e=>Number(e)),o=t.split(".").map(e=>Number(e));for(let n=0;n<Math.max(r.length,o.length);n++){let e=r[n]||0,t=o[n]||0;if(e>t)return!0;if(e<t)return!1}return i}var xO=Number(MO.split(".")[0]),UO="15.1"===kO,VO="15.1"===MO,FO=(()=>{let e=Number(MO.split(".")[0]);return 14===e||13===e})(),BO=TO&&"11.1.1"===kO,HO="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),WO=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(AM){e=!1}return e}})(),GO=jO();function jO(){let e=new Map([[Ak,["Firefox",Sk]],[Ck,["Edg",Dk]],[AO,["Chrome",wO]],[TO,["ChiOS",ck("CriOS")]],[DO&&!TO,["Safari",kO]],[Lk,["TBS",xk]],[Uk,["XWEB",Vk]],[Wk&&fk,["WeChat",Gk]],[qk,["QQ(Win)",Yk]],[zk,["QQ(Mobile)",Kk]],[jk,["QQ(Mobile X5)",Kk]],[Jk,["QQ(Mac)",Xk]],[Qk,["QQ(iPad)",$k]],[aO,["MI",sO]],[lO,["HW",uO]],[hO,["Samsung",pO]],[mO,["OPPO",fO]],[_O,["VIVO",gO]],[bk,["EDGE",wk]],[kk,["SogouMobile",Ok]],[Mk,["Sogou",Pk]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var zO=null;function KO(){return zO&&"boolean"==typeof zO.mobile?zO.mobile:vk||gk||fk||pk||EO}var qO="";function YO(){return uw(this,null,function*(){if(zO)return zO;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(zO=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!qO&&(qO="UAData: ".concat(zO.platform,"/").concat(zO.platformVersion),zO.architecture&&zO.bitness&&(qO+=" ".concat(zO.architecture,"/").concat(zO.bitness)),zO.mobile&&(qO+=" mobile"),zO.model&&(qO+=" model: ".concat(zO.model.replace(/\s+/g,"/"))),zO.fullVersionList&&(qO+=" ".concat(zO.fullVersionList.filter(e=>"Not/A)Brand"!==e.brand).map(e=>"".concat(e.brand,"/").concat(e.version)).join(",")))),zO}catch(XH){return null}})}var JO="";function XO(){try{if(JO)return JO;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 JO="".concat(e," ").concat(r)}return""}catch(XH){return""}}function QO(){try{let e=XO();return e.includes("AMD")||e.includes("ATI")}catch(XH){return!1}}function $O(){try{let e=XO();return e.includes("NVIDIA")||e.includes("GeForce")}catch(XH){return!1}}function ZO(){try{return XO().includes("Apple M")}catch(XH){return!1}}function eM(){return(null==zO?void 0:zO.model)||tM()||""}function tM(){let e=sk.match(/;\s*([^;)]+)\s+Build\//);return null!=e&&e[1]?e[1].trim():null}var iM=new Map([[vk,"Android"],[gk,"iOS"],[Zk,"Windows"],[eO,"MacOS"],[tO,"Linux"],[iO,"ChromeOS"]]),rM=function(){return iM.get(!0)?iM.get(!0):zO?zO.platform:"unknown"};function oM(){return Zk?1:vk?2:eO?3:gk?4:tO?5:iO?6:EO?7:0}function nM(){return Wk||Uk?4:IO?1:DO?2:Ak?3:0}var aM=()=>{let e=rM();return null!=zO&&zO.platformVersion?e+="/".concat(zO.platformVersion):gk?e+="/".concat(MO):vk&&(e+="/".concat(yk)),e+="/".concat(GO.name,"/").concat(DO&&!TO?GO.version:GO.version.split(".")[0]),null!=zO&&zO.architecture&&(e+="/".concat(zO.architecture)),e};function sM(){return vk?4:fk?2:pk?3:eO?12:Zk?5:tO?13:EO?22:1}function lM(){return vk?"Android":fk?"iPhone":pk?"iPad":eO?"Mac":Zk?"Windows":tO?"Linux":"unknown"}var cM,dM=new(sw(hw(),1).default),uM=((cM=uM||{}).ROOM_DESTROY="1",cM.JOIN_START="21",cM.JOIN_SCHEDULE_SUCCESS="22",cM.JOIN_SIGNAL_CONNECTION_START="23",cM.JOIN_SIGNAL_CONNECTION_END="24",cM.JOIN_SEND_CMD="25",cM.JOIN_RECEIVED_CMD_RES="26",cM.JOIN_SUCCESS="27",cM.JOIN_FAILED="28",cM.LEAVE_START="51",cM.LEAVE_SEND_CMD="52",cM.LEAVE_SUCCESS="53",cM.PUBLISH_START="61",cM.SEND_FIRST_VIDEO_FRAME="62",cM.PUBLISH_FAILED="63",cM.SUBSCRIBE_START="81",cM.SUBSCRIBE_SUCCESS="82",cM.SUBSCRIBE_FAILED="84",cM.UNSUBSCRIBE_SUCCESS="83",cM.LOCAL_TRACK_CAPTURE_START="101",cM.LOCAL_TRACK_CAPTURE_SUCCESS="102",cM.LOCAL_TRACK_CAPTURE_FAILED="103",cM.LOCAL_TRACK_PUBLISHED="104",cM.LOCAL_TRACK_UNPUBLISHED="105",cM.LOCAL_TRACK_REPLACED="106",cM.SWITCH_DEVICE_SUCCESS="107",cM.TRACK_MUTED="108",cM.TRACK_UNMUTED="109",cM.REMOTE_TRACK_SUBSCRIBED="110",cM.REMOTE_TRACK_UNSUBSCRIBED="111",cM.LOCAL_TRACK_RECAPTURE="112",cM.LOCAL_AUDIO_STARTED="113",cM.LOCAL_AUDIO_STOPPED="114",cM.REMOTE_AUDIO_STARTED="115",cM.REMOTE_AUDIO_STOPPED="116",cM.PLAY_TRACK_START="151",cM.PLAYER_STATE_CHANGED="152",cM.VIDEO_LOADED_DATA="153",cM.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",cM.AUDIO_CONTEXT_LONG_SUSPENDED="155",cM.REMOTE_VIDEO_PLAY_START="156",cM.REMOTE_VIDEO_PLAY_FINISH="157",cM.SIGNAL_CONNECTION_STATE_CHANGED="201",cM.PEER_CONNECTION_STATE_CHANGED="202",cM.SINGLE_CONNECTION_STAT="203",cM.SPC_RECONNECTED="204",cM.HEARTBEAT_REPORT="251",cM.RECEIVED_PUBLISHED_USER_LIST="252",cM.REMOTE_PUBLISH_STATE_CHANGED="253",cM.AUDIO_LEVEL_INTERVAL="260",cM.NETWORK_QUALITY="261",cM.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",cM.QUALITY_LIMITATION_CHANGED="263",cM.LOG="264",cM.AUDIO_PROCESSOR_DEBUG="265",cM.SSO_SWITCH="266",cM.SEI_MESSAGE="267",cM.USER_PAUSE_IN_PIP="268",cM.USER_RESUME_IN_PIP="269",cM.ENTER_PICTURE_IN_PICTURE="270",cM.LEAVE_PICTURE_IN_PICTURE="271",cM.SWITCH_ROOM_START="401",cM.SWITCH_ROOM_SUCCESS="407",cM.SWITCH_ROOM_FAILED="408",cM),hM=uM,pM=new class{constructor(){cw(this,"enable",!1),cw(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(){cw(this,"_isEnableUploadLog",!0),cw(this,"_localJoinedUser",new Map),cw(this,"_queue",[]),cw(this,"_timeoutId",-1),cw(this,"_logLevel",1),cw(this,"_logLevelToUpload",2),!Ow&&!Mw&&(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&&Xw[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),dM.on(hM.JOIN_START,e=>{let{params:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),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:o}=t;e.map.has(r)?e.map.get(r).logs.push(i):e.map.set(r,{userId:r,sdkAppId:o,logs:[i]})});else if(tN(i.userId)&&iN(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 uw(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:o}=t[e],n={timestamp:Aw(),sdkAppId:String(r),userId:i,version:Cw,log:o.map(e=>e.log).join("\n")},a=JSON.stringify(n),s=pM.enable?GN(n,2002,r):a;yield this.uploadLogWithRetry(s,r,s instanceof Uint8Array,a),o.forEach(e=>e.uploaded=!0)}}catch(SM){}let i=t.filter(e=>!e.uploaded);i.length>0&&(this._queue=i.concat(this._queue))})}uploadLogWithRetry(e,t,i,r){return ok({retryFunction:()=>QN({url:PD(t,Yw.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(Iw()),"[".concat(Sw(t),"] <").concat(Xw[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){eN(Xw[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(tN(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(Nw){return""}}addLogToQueue(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0,n={log:t.reduce((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim(),""),level:e,userId:r,sdkAppId:o,forAllJoinedClients:i};dM.emit(hM.LOG,{log:n}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(n)}log(t,i){let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],o=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;var a;if(i.unshift(this.getPrefix(t)),this.addLogToQueue(t,i,r,o,n),t<this._logLevel)return;let s=(null==(a=Xw[t])?void 0:a.toLowerCase())||"info";e.PRINT_LOG_TAG?console[s]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...i):console[s](...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){if(e.parent instanceof nk){let t=e,{parent:i}=t,r=((e,t)=>{var i={};for(var r in e)$b.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&Xb)for(var r of Xb(e))t.indexOf(r)<0&&Zb.call(e,r)&&(i[r]=e[r]);return i})(t,["parent"]),o=new nk(r);return o.bindParent(i),o}return new nk(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Xw[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};cw(mM,"PRINT_LOG_TAG",!(gk||vk||SO));var fM=new mM,_M=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(){cw(this,"_prefix","TRTC"),cw(this,"_queue",new Map)}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){WO()&&(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(SM){return!1}return!1}).forEach(e=>localStorage.removeItem(e)))}doFlush(){if(WO())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(AM){fM.warn(AM)}}getItem(e){if(!WO())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(Nw){fM.warn(Nw)}}setItem(e,t){if(WO())try{let i={expiresIn:Date.now()+eC,value:t};this._queue.set(this.getRealKey(e),i)}catch(LC){fM.warn(LC)}}deleteItem(e){if(!WO())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(Nw){return fM.warn(Nw),!1}}clear(){if(WO())try{localStorage.clear()}catch(AM){fM.warn(AM)}}},EM={};aw(EM,{HTTPS_API:()=>sL,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>DL,IS_GET_CAPABILITIES_SUPPORTED:()=>CL,IS_GET_SETTINGS_SUPPORTED:()=>wL,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>bL,IS_INSERTABLE_STREAM_SUPPORTED:()=>NL,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>GL,IS_RTC_RTP_SENDER_SUPPORTED:()=>AL,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>kL,IS_SEI_SUPPORTED:()=>OL,IS_SPC_SUPPORTED:()=>TL,basis:()=>VL,capabilityCheck:()=>HL,checkSystemRequirementsInternal:()=>tL,decodeSupportStatus:()=>eL,detectVideoCodecCapabilities:()=>KL,detectVideoDecoderCapabilities:()=>YL,detectVideoEncoderCapabilities:()=>qL,encodeSupportStatus:()=>ZP,getBrowserInfo:()=>zP,getDisplayResolution:()=>cL,getH264ProfileLevelIds:()=>JL,isAddTransceiverSupported:()=>yL,isBrowserSupported:()=>KP,isCanvasCaptureStreamAPISupported:()=>hL,isCanvasSmallStreamSupported:()=>pL,isGetReceiversSupported:()=>gL,isGetSendersSupported:()=>EL,isGetTransceiversSupported:()=>vL,isGetUserMediaSupported:()=>dL,isMediaDevicesSupported:()=>YP,isMediaSessionSupported:()=>LL,isMediaStreamTrackGeneratorSupported:()=>$P,isMediaStreamTrackProcessorSupported:()=>QP,isReplaceTrackSupported:()=>SL,isRequestVideoFrameCallbackSupported:()=>WL,isSIMDSupported:()=>UL,isScaleResolutionDownBySupported:()=>mL,isScreenCaptureApiAvailable:()=>rL,isSelectedCandidatePair:()=>lL,isSetParametersSupported:()=>RL,isSetSinkIdSupported:()=>oL,isSmallStreamSupported:()=>fL,isStopTransceiverSupported:()=>IL,isTRTCSupported:()=>iL,isUnifiedPlanDefault:()=>_L,isUsedInHttpProtocol:()=>XP,isWebAudioSupported:()=>uL,isWebCodecSupported:()=>PL,isWebCodecsSupported:()=>qP,isWebRTCSupported:()=>ML,isWebTransportSupported:()=>xL});var vM={};aw(vM,{AUDIO_LEVEL_SCALE:()=>uP,AlphaStitchingType:()=>RP,AudioCodecPipelineType:()=>gP,AudioDecoderDowngradeState:()=>KM,AudioPlayerMode:()=>lP,AudioType:()=>$M,BASIC_TYPE:()=>mP,BannedReason:()=>cP,CONNECTION_CLOSED_REASON:()=>MM,CheckPermissionType:()=>AP,ClientEvent:()=>PM,CodecType:()=>EP,ConnectionEvent:()=>OM,ConnectionState:()=>zM,DECODE_FAILED_ERROR_CODE:()=>vP,DenoiserMode:()=>hP,DeviceType:()=>SP,FacingMode:()=>aP,FrameWorkType:()=>kM,LeaveReason:()=>dP,LocalTrackEvent:()=>xM,MULTI_VIDEO_DATA_TYPE:()=>iP,MediaType:()=>XM,MediaTypeLabel:()=>QM,MonitorEventId:()=>rP,MutedFlag:()=>HM,NetworkQualityValue:()=>oP,PlayerState:()=>UM,ReceiveMode:()=>nP,RemoteStreamType:()=>tP,RemoteTrackEvent:()=>BM,RoomEvent:()=>VM,SMALL_MODE:()=>IP,SceneNumber:()=>WM,StreamEvent:()=>LM,StreamType:()=>eP,SubscribeMediaType:()=>pP,TIMER_TYPE:()=>TP,TRACK_ACTION:()=>JM,TRACK_KIND:()=>YM,TrackEvent:()=>FM,UserRole:()=>jM,UserRoleNumber:()=>GM,VideoCodec:()=>fP,VideoCodecPipelineType:()=>_P,VideoContentHint:()=>yP,VideoDecoderDowngradeState:()=>qM,VideoPlayerMode:()=>sP,VideoType:()=>ZM});var yM,TM,IM,AM,SM,RM,bM,wM,CM,DM,NM,kM=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(kM||{}),OM=((NM=OM||{}).TRACK_ADDED="track-added",NM.TRACK_UPDATED="track-updated",NM.TRACK_SUBSCRIBED="track-subscribed",NM.STREAM_ADDED="stream-added",NM.STREAM_REMOVED="stream-removed",NM.STREAM_UPDATED="stream-updated",NM.STREAM_PUBLISHED="stream-published",NM.STREAM_SUBSCRIBED="stream-subscribed",NM.STREAM_UNSUBSCRIBED="stream-unsubscribed",NM.STATE_CHANGED="state-changed",NM.ERROR="error",NM.CONNECTION_STATE_CHANGED="connection-state-changed",NM.FIREWALL_RESTRICTION="firewall-restriction",NM.SEI_MESSAGE="sei-message",NM.CLOSED="closed",NM),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=((CM=LM||{}).PLAYER_STATE_CHANGED="player-state-changed",CM.SCREEN_SHARING_STOPPED="screen-sharing-stopped",CM.CONNECTION_STATE_CHANGED="connection-state-changed",CM.DEVICE_AUTO_RECOVERED="device-auto-recovered",CM.ERROR="error",CM),xM=((wM=xM||{}).DEVICE_AUTO_RECOVERED="1",wM.DEVICE_RECOVER_FAILED="5",wM.DEVICE_CHANGED="2",wM.ERROR="3",wM.PUBLISH_STATE_CHANGED="4",wM.ENCODE_FAILED="6",wM.TRACK_ENDED="7",wM.RENDER="render",wM),UM=(e=>(e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e))(UM||{}),VM=((bM=VM||{}).PEER_JOIN="peer-join",bM.PEER_LEAVE="peer-leave",bM.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",bM.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",bM.BANNED="banned",bM.NETWORK_QUALITY="network-quality",bM.AUDIO_VOLUME="audio-volume",bM.SEI_MESSAGE="sei-message",bM.ERROR="error",bM.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",bM.REMOTE_PUBLISHED="remote-published",bM.REMOTE_UNPUBLISHED="remote-unpublished",bM.FIREWALL_RESTRICTION="firewall-restriction",bM.HEARTBEAT_REPORT="heartbeat-report",bM.CUSTOM_MESSAGE="custom-message",bM.LAYER_DATA="layerData",bM.FIRST_VIDEO_FRAME="first-video-frame",bM.DUMP="dump",bM.AUDIO_FRAME="audio-frame",bM.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",bM.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",bM.NTP_TIME_UPDATED="ntp-time-updated",bM.DATA_CHANNEL_MESSAGE="data-channel-message",bM.ASR_ROBOT_PEER_JOIN="asr-robot-peer-join",bM.ASR_ROBOT_PEER_LEAVE="asr-robot-peer-leave",bM),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_FAILED_DURING_CALL="decode-failed-during-call",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e.REMOTE_PUBLISH_CHANGED="remote-publish-changed",e.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",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||{}),zM=(e=>(e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e))(zM||{}),KM=((SM=KM||{}).INITIALIZED="INITIALIZED",SM.STARTING="STARTING",SM.STARTED="STARTED",SM.FAILED="FAILED",SM),qM=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(qM||{}),YM=(e=>(e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e))(YM||{}),JM=(e=>(e.ADD="add",e.REMOVE="remove",e))(JM||{}),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"},$M=((AM=$M||{})[AM.opus=111]="opus",AM),ZM=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(ZM||{}),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=((IM=rP||{})[IM.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",IM[IM.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",IM[IM.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",IM[IM.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",IM[IM.MUTE_AUDIO=32772]="MUTE_AUDIO",IM[IM.MUTE_VIDEO=32773]="MUTE_VIDEO",IM[IM.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",IM[IM.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",IM[IM.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",IM[IM.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",IM[IM.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",IM[IM.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",IM[IM.SWITCH_CAMERA=32780]="SWITCH_CAMERA",IM[IM.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",IM[IM.REPLACE_VIDEO=32782]="REPLACE_VIDEO",IM[IM.REPLACE_AUDIO=32783]="REPLACE_AUDIO",IM[IM.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",IM[IM.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",IM[IM.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",IM[IM.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",IM[IM.JOIN=32788]="JOIN",IM[IM.LEAVE=32789]="LEAVE",IM[IM.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",IM[IM.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",IM[IM.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",IM[IM.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",IM[IM.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",IM[IM.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",IM[IM.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",IM[IM.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",IM[IM.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",IM[IM.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",IM[IM.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",IM[IM.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",IM[IM.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",IM[IM.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",IM[IM.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",IM[IM.PUBLISH_AUX=32805]="PUBLISH_AUX",IM[IM.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",IM[IM.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",IM[IM.VIDEO_ENCODER=4004]="VIDEO_ENCODER",IM[IM.VIDEO_DECODER=4005]="VIDEO_DECODER",IM),oP=(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))(oP||{}),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||{}),aP=(e=>(e.user="user",e.environment="environment",e))(aP||{}),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||{}),lP=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(lP||{}),cP=(e=>(e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e))(cP||{}),dP=((TM=dP||{})[TM.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",TM[TM.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",TM[TM.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",TM[TM.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",TM[TM.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",TM[TM.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",TM[TM.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",TM[TM.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",TM[TM.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",TM),uP=1e8,hP=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(hP||{}),pP=class{constructor(){cw(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)}},mP=(e=>(e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e))(mP||{}),fP=(e=>(e.H264="h264",e.H265="h265",e.VP8="vp8",e.VP9="vp9",e.AV1="av1",e))(fP||{}),_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||{}),gP=(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))(gP||{}),EP=(e=>(e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e))(EP||{}),vP=((yM=vP||{})[yM.SUCCESS=0]="SUCCESS",yM[yM.FAILED=1]="FAILED",yM[yM.WEBCODEC_INIT=2]="WEBCODEC_INIT",yM[yM.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",yM[yM.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",yM[yM.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",yM[yM.WASM_INIT=6]="WASM_INIT",yM[yM.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",yM[yM.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",yM[yM.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",yM[yM.TEST=10]="TEST",yM[yM.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",yM),yP=(e=>(e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e))(yP||{}),TP=(e=>(e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e))(TP||{}),IP=(e=>(e.CANVAS="canvas",e.API="api",e))(IP||{}),AP=(e=>(e[e.NONE=0]="NONE",e[e.MICROPHONE=1]="MICROPHONE",e[e.CAMERA=2]="CAMERA",e[e.BOTH=3]="BOTH",e))(AP||{}),SP=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(SP||{}),RP=(e=>(e[e.none=0]="none",e[e.horizontal=1]="horizontal",e[e.vertical=2]="vertical",e))(RP||{}),bP={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"},wP={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:o}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(o,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:o}=e,n="".concat(t||i.name),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(n,"' must be type of ").concat(a," when calling ").concat(r,"(), received type: ").concat($D(o),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:o}=e;return"'".concat(t||i.name,"' cannot be '").concat(o,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:o}=e,n="".concat(t||i.name),a="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(n,"' must be instanceof ").concat(a," when calling ").concat(r,"(), received type: ").concat($D(o),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:o}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(o,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:r,value:o}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(o,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,fnName:r,value:o}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(o,".")},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:o}=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:o}=e;return"api ".concat(i," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(o," 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(Hw,"/").concat(e,"/").concat(t):"".concat(Hw,"/").concat(e,"/index.html"),DP=()=>{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(qw);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 NP(e){let{key:t,data:i,link:r,addDocLink:o=!0}=e,n="",a="",s="";ZD(wP[t])?n=wP[t](i):tN(wP[t])&&(n=wP[t]);let{TRTC_ERROR_INFO:l,TRTC_ERROR_LINK:c}=DP();r?s="".concat(r.className,".html#").concat(r.fnName):c&&c[t]&&(ZD(c[t])?s=c[t](i):tN(c[t])&&(s=c[t]));let d=n;return YD()&&(l&&l[t]&&(ZD(l[t])?a=l[t](i):tN(l[t])&&(a=l[t])),a&&(d=o?"".concat(a,"\n请查看文档: ").concat(CP("zh-cn",s),"\n\n"):"".concat(a,"\n\n"),d+=n)),o&&(d+=" \nRefer to: ".concat(CP("en",s),"\n")),d}var kP,OP,MP=sw(_w(),1),PP=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];cw(this,"countMap",new Map),cw(this,"distributionMap",new Map),cw(this,"version"),cw(this,"log",fM.createLogger({id:"kv"})),e&&(dM.on("102",e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===aC.AUDIO?501700:511700,cost:i})}),dM.on("103",e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===aC.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(e,t){let i={msg_sdk_basic_info:{uint32_sdk_version:ON(this.version||Cw),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}})}}),str_user_sig:e,bytes_report_token:t};return this.countMap.clear(),this.distributionMap.clear(),i}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 o;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 n=(null==(o=this.distributionMap)?void 0:o.get(t))||new Map;n.set(i,(n.get(i)||0)+1),this.distributionMap.set(t,n)}addNumber(e){let{key:t,value:i,split:r=100,useUV:o=!1,max:n=5e3}=e;var a;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(o&&this.countMap.has(t))return;i>n&&(i=n),this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=(null==(a=this.distributionMap)?void 0:a.get(t))||new Map,l=0;if(iN(r))l=Math.floor(i/r);else for(let c=r.length-1;c>0;c--)if(i>r[c]){l=c;break}s.set(l,(s.get(l)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent(e){let{key:t,cost:i,timeKey:r,split:o}=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:o}):r||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:i}=e;if(!t)return;let r=Ew.UNKNOWN;i&&(iN(i)?r=i:(!eN(i.extraCode)||!eN(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})}},LP=((kP=LP||{})[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.getPermissions=500720]="getPermissions",kP[kP.sendSEIMessage=5e5]="sendSEIMessage",kP[kP.sendCustomMessage=500001]="sendCustomMessage",kP),xP=(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.FaceDetector=575700]="FaceDetector",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[e.LEBPlayer=596700]="LEBPlayer",e[e.RealtimeTranscriber=597700]="RealtimeTranscriber",e))(xP||{}),UP=(e=>(e[e.AudioMixer=550701]="AudioMixer",e[e.AIDenoiser=551701]="AIDenoiser",e[e.VirtualBackground=570701]="VirtualBackground",e[e.Beauty=571701]="Beauty",e[e.Watermark=572701]="Watermark",e[e.BasicBeauty=574701]="BasicBeauty",e[e.FaceDetector=575701]="FaceDetector",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[e.LEBPlayer=596701]="LEBPlayer",e[e.RealtimeTranscriber=597701]="RealtimeTranscriber",e))(UP||{}),VP=(e=>(e[e.AudioMixer=550702]="AudioMixer",e[e.AIDenoiser=551702]="AIDenoiser",e[e.VirtualBackground=570702]="VirtualBackground",e[e.Beauty=571702]="Beauty",e[e.Watermark=572702]="Watermark",e[e.BasicBeauty=574702]="BasicBeauty",e[e.FaceDetector=575702]="FaceDetector",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[e.LEBPlayer=596702]="LEBPlayer",e[e.RealtimeTranscriber=597702]="RealtimeTranscriber",e))(VP||{}),FP=((OP=FP||{})[OP.DECODER_TYPE=514700]="DECODER_TYPE",OP[OP.DECODER_HW_SW=514701]="DECODER_HW_SW",OP[OP.DECODE_RESULT=514702]="DECODE_RESULT",OP[OP.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",OP[OP.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",OP[OP.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",OP[OP.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",OP[OP.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",OP[OP.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",OP[OP.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",OP[OP.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",OP[OP.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",OP[OP.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",OP[OP.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",OP[OP.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",OP[OP.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",OP[OP.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",OP[OP.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",OP[OP.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",OP),BP=new PP(!0),HP=new PP(!1),WP=BP,GP={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}},jP=new Map([[Ak,["Firefox",Sk]],[Ck,["Edg",Dk]],[AO,["Chrome",wO]],[DO,["Safari",kO]],[Lk,["TBS",xk]],[Uk,["XWEB",Vk]],[Wk&&fk,["WeChat",Gk]],[qk,["QQ(Win)",Yk]],[zk,["QQ(Mobile)",Kk]],[jk,["QQ(Mobile X5)",Kk]],[Jk,["QQ(Mac)",Xk]],[Qk,["QQ(iPad)",$k]],[aO,["MI",sO]],[lO,["HW",uO]],[hO,["Samsung",pO]],[mO,["OPPO",fO]],[_O,["VIVO",gO]],[bk,["EDGE",wk]],[kk,["SogouMobile",Ok]],[Mk,["Sogou",Pk]]]);function zP(){let e=jP.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var KP=function(){return!(oO||bk||Ck&&Nk<80||Ak&&Rk<56)},qP=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(e=>e in window)},YP=function(){if(!navigator.mediaDevices)return XP()||fM.error(wP.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter(e=>e in navigator.mediaDevices).length===e.length},JP=!1;function XP(){return"http:"===location.protocol&&!HO&&(JP||fM.error(NP({key:bP.NOT_SUPPORTED_HTTP})),JP=!0,!0)}var QP=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},$P=function(){return!(null==window||!window.MediaStreamTrackGenerator)},ZP=function(){return uw(this,null,function*(){var e,t,i;if(GP.detail.isH264EncodeSupported&&GP.detail.isVp8EncodeSupported)return{isH264EncodeSupported:GP.detail.isH264EncodeSupported,isVp8EncodeSupported:GP.detail.isVp8EncodeSupported,isH265EncodeSupported:GP.detail.isH265EncodeSupported};let r,o=!1,n=!1,a=!1;try{let s=new RTCPeerConnection,l=document.createElement(aC.CANVAS);l.getContext("2d");let c=l.captureStream(0);return s.addTrack(c.getVideoTracks()[0],c),r=yield s.createOffer(),o=-1!==(null==(e=r.sdp)?void 0:e.toLowerCase().indexOf("h264")),n=-1!==(null==(t=r.sdp)?void 0:t.toLowerCase().indexOf("vp8")),a=-1!==(null==(i=r.sdp)?void 0:i.toLowerCase().indexOf("h265")),s.close(),{isH264EncodeSupported:o,isVp8EncodeSupported:n,isH265EncodeSupported:a}}catch(RM){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},eL=function(){return uw(this,null,function*(){var e;if(GP.detail.isH264DecodeSupported&&GP.detail.isVp8DecodeSupported)return{isH264DecodeSupported:GP.detail.isH264DecodeSupported,isVp8DecodeSupported:GP.detail.isVp8DecodeSupported,isH265DecodeSupported:GP.detail.isH265DecodeSupported};let t,i=!1,r=!1;try{let o=new RTCPeerConnection;yL()?(o.addTransceiver(aC.VIDEO,{direction:"recvonly"}),t=yield o.createOffer()):t=yield o.createOffer({offerToReceiveVideo:!0}),-1!==t.sdp.toLowerCase().indexOf("h264")&&(i=!0),-1!==t.sdp.toLowerCase().indexOf("vp8")&&(r=!0);let n=-1!==(null==(e=t.sdp)?void 0:e.toLowerCase().indexOf("h265"));return o.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:r,isH265DecodeSupported:n}}catch(SM){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})};var tL=LN(e=>uw(null,null,function*(){let t=Date.now(),i=ML(),r=YP(),o=qP();if(GP.detail.isWebRTCSupported=i,GP.detail.isMediaDevicesSupported=r,GP.detail.isWebCodecsSupported=o,GP.detail.isScreenShareSupported=rL(),GP.detail.isSmallStreamSupported=fL(),37===e)return Object.assign(GP.detail,yield function(){return uw(this,null,function*(){return aL||(aL=new Promise(e=>uw(null,null,function*(){let t={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!qP())return void e(t);let i=null,r=null,o=null,n=()=>{o&&clearTimeout(o),i=null,r=null};try{i=document.createElement("canvas"),r=i.getContext("2d"),i.width=320,i.height=240;let a=0,s=()=>{!r||!i||(r.fillStyle="hsl(".concat(a%360,", 50%, 50%)"),r.fillRect(0,0,i.width,i.height),r.fillStyle="white",r.font="20px Arial",r.fillText("Frame ".concat(a),10,30),a++)};o=setTimeout(()=>{n(),e(t)},5e3);let l=[{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(l.map(e=>uw(null,null,function*(){let t,r={type:e.type,encodeSupported:!1,decodeSupported:!1};try{t=yield new Promise((t,o)=>uw(null,null,function*(){try{let n=new VideoEncoder({output:e=>{t(e),r.encodeSupported=!0},error:o});n.configure(e.encodeConfig),s();let a=new VideoFrame(i,{timestamp:0});n.encode(a,{keyFrame:!0}),a.close(),yield n.flush(),n.close()}catch(NM){o(NM)}}))}catch(p){return fM.warn("".concat(e.type," encoder error:"),p),r}try{yield new Promise((i,o)=>uw(null,null,function*(){try{let n=new VideoDecoder({output:e=>{r.decodeSupported=!0,i(0),e.close()},error:o});n.configure(e.decodeConfig),n.decode(t),yield n.flush(),n.close()}catch(NM){o(NM)}}))}catch(p){fM.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)}),n(),e(t)}catch(a){n(),fM.warn("detectWebCodecsSupported failed:",a),e(t)}})),aL)})}()),GP.detail.isBrowserSupported=o,GP.result=r&&o,GP.result||fM.error("".concat(navigator.userAgent," ").concat(CN(GP.detail,!1))),BL(e),WP.addNumber({key:523800,value:Date.now()-t}),GP;if(GP.result&&GP.detail.isH264EncodeSupported&&GP.detail.isVp8EncodeSupported&&GP.detail.isH265EncodeSupported&&GP.detail.isH264DecodeSupported&&GP.detail.isVp8DecodeSupported&&GP.detail.isH265DecodeSupported)return GP;let n=KP(),{encode:a,decode:s}=yield function(){return uw(this,null,function*(){let[e,t]=yield Promise.all([ZP(),eL()]);return{encode:{h264:e.isH264EncodeSupported,vp8:e.isVp8EncodeSupported,h265:e.isH265EncodeSupported},decode:{h264:t.isH264DecodeSupported,vp8:t.isVp8DecodeSupported,h265:t.isH265DecodeSupported}}})}(),{h264:l,vp8:c}=a,{h264:d}=s,{h265:u}=a,{vp8:h,h265:p}=s;if(!l||!c){let e=yield ZP();fM.warn("detect encode again h264:".concat(l," vp8:").concat(c," result: ").concat(JSON.stringify(e))),l=e.isH264EncodeSupported,c=e.isVp8EncodeSupported}if(l&&d&&vk&&IO&&!Uk&&!Lk&&(!mO||115!==RO)){let{encode:e,decode:t}=yield function(){return uw(this,null,function*(){return nL||(nL=new Promise(e=>uw(null,null,function*(){let t={encode:!1,decode:!1},i=()=>{};try{let r=document.createElement("canvas"),o=r.getContext("2d");r.width=640,r.height=480;let n=setInterval(()=>{o.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66),a=-1,s=-1;i=()=>{clearInterval(a),clearInterval(n),clearTimeout(s),c.close(),d.close(),l.getTracks().forEach(e=>e.stop())},s=setTimeout(()=>{i(),e(t)},2e3);let l=r.captureStream(),c=new RTCPeerConnection({}),d=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});c.addEventListener("icecandidate",e=>d.addIceCandidate(e.candidate)),d.addEventListener("icecandidate",e=>c.addIceCandidate(e.candidate)),c.addTrack(l.getVideoTracks()[0],l);let u=yield c.createOffer();yield c.setLocalDescription(u),yield d.setRemoteDescription(u);let h=yield d.createAnswer(),p=MP.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=MP.default.write(p),yield d.setLocalDescription(h),yield c.setRemoteDescription(h),a=setInterval(()=>uw(null,null,function*(){t.encode&&t.decode&&(i(),e(t));let[r,o]=yield Promise.all([c.getSenders()[0].getStats(),d.getReceivers()[0].getStats()]);t.encode||r.forEach(e=>{"outbound-rtp"===e.type&&e.mediaType===aC.VIDEO&&e.bytesSent>0&&(t.encode=!0)}),t.decode||o.forEach(e=>{"inbound-rtp"===e.type&&e.mediaType===aC.VIDEO&&e.bytesReceived>0&&(t.decode=!0)})}),100)}catch(r){i(),fM.warn("detectH264Supported failed",r),e({encode:!0,decode:!0})}})).then(e=>(e.encode||(e.decode=!0),(!e.encode||!e.decode)&&fM.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(qO)),e)),nL)})}();l=e,d=t}return GP.result=n&&i&&r&&(l||c)&&(d||h),GP.detail.isBrowserSupported=n,GP.detail.isWebRTCSupported=i,GP.detail.isH264EncodeSupported=l,GP.detail.isVp8EncodeSupported=c,GP.detail.isH265EncodeSupported=u,GP.detail.isH264DecodeSupported=d,GP.detail.isVp8DecodeSupported=h,GP.detail.isH265DecodeSupported=p,GP.result||fM.error("".concat(navigator.userAgent," ").concat(CN(GP.detail,!1))),BL(),WP.addNumber({key:523800,value:Date.now()-t}),GP})),iL=function(){return GP.result},rL=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},oL="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype,nL=null;var aL=null;var sL=(e,t,i)=>{"http:"===location.protocol&&!HO&&(e[t]=()=>{throw new yw({code:Ew.INVALID_OPERATION,message:wP.NOT_SUPPORTED_HTTP})})},lL=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(rN(e.selected)&&!e.selected)};function cL(){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 dL(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function uL(){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 hL(){return"captureStream"in HTMLCanvasElement.prototype}function pL(){return!(Wk||gk||RO&&RO<63)&&!(!KP()||!hL())}function mL(){return!(RO<74||bk||xO<11||Rk<46)}function fL(){return pL()||mL()}var _L=function(){if(eN(window.RTCRtpTransceiver)||!yL()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:HC}),e.addTransceiver(aC.AUDIO),t=!0}catch(Nw){}return null==e||e.close(),t};function gL(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function EL(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function vL(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function yL(){return!(11===xO&&!BO)&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var TL=!(!yL()||IO&&RO<86);function IL(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var AL="RTCRtpSender"in window;function SL(){return AL&&"replaceTrack"in window.RTCRtpSender.prototype}function RL(){return AL&&"setParameters"in window.RTCRtpSender.prototype&&EL()}var bL="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,wL=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,CL=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,DL="undefined"!=typeof InputDeviceInfo&&"getCapabilities"in InputDeviceInfo.prototype,NL=AL&&"createEncodedStreams"in window.RTCRtpSender.prototype&&yO()>=86,kL="RTCRtpScriptTransform"in window,OL=AL&&(NL||kL),ML=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(e=>e in window).length>0};function PL(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return eN(window.AudioDecoder)||(e.AudioDecoder=!0),eN(window.AudioEncoder)||(e.AudioEncoder=!0),eN(window.VideoDecoder)||(e.VideoDecoder=!0),eN(window.VideoEncoder)||(e.VideoEncoder=!0),eN(window.ImageDecoder)||(e.ImageDecoder=!0),e}function LL(){return"mediaSession"in navigator&&!eN(navigator.mediaSession.setActionHandler)}function xL(){return!eN(window.WebTransport)}function UL(){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 VL(){let e={browser:"".concat(GO.name,"/").concat(GO.version),os:rM(),displayResolution:cL(),isScreenShareSupported:rL(),isWebRTCSupported:ML(),isGetUserMediaSupported:dL(),isWebAudioSupported:uL(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:PL(),isMediaSessionSupported:LL(),isWebTransportSupported:xL()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var FL="checkResult";function BL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30;gM.setItem(FL+e,{ua:navigator.userAgent,checkResult:GP})}function HL(e){XP();let t=gM.getItem(FL+e);t&&t.ua===navigator.userAgent&&t.checkResult&&function(e,t){return!!oN(e)&&Object.keys(t).every(t=>t in e)}(t.checkResult.detail,GP.detail)&&(GP=t.checkResult),tL(e)}function WL(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var GL="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function jL(e){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[e]}var zL=!1;function KL(){return uw(this,null,function*(){var e;try{if(zL||null==(e=null==navigator?void 0:navigator.mediaCapabilities)||!e.encodingInfo)return;let t=oM(),i=nM();if(0===t||0===i)return;zL=!0;let r=["H264","VP8","VP9","AV1","H265"],[o,n]=yield Promise.all([qL(r),YL(r)]);o&&Object.keys(o).forEach(e=>{let r=jL(e.toLowerCase());WP.addEnum({key:513707,value:+"".concat(r).concat(+o[e].supported).concat(+o[e].powerEfficient).concat(t).concat(i),useUV:!1})}),n&&Object.keys(n).forEach(e=>{let r=jL(e.toLowerCase());WP.addEnum({key:514713,value:+"".concat(r).concat(+n[e].supported).concat(+n[e].powerEfficient).concat(t).concat(i),useUV:!1})});let{sender:a,receiver:s}=JL();WP.addEnum({key:513708,value:+"".concat(t).concat(i).concat(+a.high),useUV:!1}),WP.addEnum({key:513709,value:+"".concat(t).concat(i).concat(+a.main),useUV:!1}),WP.addEnum({key:514714,value:+"".concat(t).concat(i).concat(+s.high),useUV:!1}),WP.addEnum({key:514715,value:+"".concat(t).concat(i).concat(+s.main),useUV:!1})}catch(AM){fM.info("detectVideoCodecCapabilities failed",AM)}})}function qL(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,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:3e3;return uw(this,null,function*(){let n={};try{for(let a of e){let e=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:"video/".concat(a),width:t,height:i,bitrate:o,framerate:r}});n[a]=e}}catch(kw){}return n})}function YL(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,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:3e3;return uw(this,null,function*(){let n={};try{for(let a of e){let e=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:"video/".concat(a),width:t,height:i,bitrate:o,framerate:r}});n[a]=e}}catch(kw){}return n})}function JL(){let e={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&"function"==typeof RTCRtpSender.getCapabilities){let t=RTCRtpSender.getCapabilities("video");t&&t.codecs&&t.codecs.filter(e=>"video/h264"===e.mimeType.toLowerCase()).forEach(t=>{if(t.sdpFmtpLine){let i=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(i&&i[1])switch(i[1].slice(0,2)){case"42":e.sender.base=!0;break;case"4d":e.sender.main=!0;break;case"64":e.sender.high=!0}}})}if(RTCRtpReceiver&&"function"==typeof RTCRtpReceiver.getCapabilities){let t=RTCRtpReceiver.getCapabilities("video");t&&t.codecs&&t.codecs.filter(e=>"video/h264"===e.mimeType.toLowerCase()).forEach(t=>{if(t.sdpFmtpLine){let i=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(i&&i[1])switch(i[1].slice(0,2)){case"42":e.receiver.base=!0;break;case"4d":e.receiver.main=!0;break;case"64":e.receiver.high=!0}}})}}catch(AM){fM.warn("get H264 profile levelId failed",AM)}return e}var XL=sw(hw(),1),QL=Symbol("instance"),$L=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,ox.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},ex=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var tx=new Map;function ix(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,o,n)=>{let a=i.action||o;if(!i.context){let i=tx.get(r)||[];tx.has(r)||tx.set(r,i),i.push({from:e,to:t,action:a})}let s=n.value;n.value=function(){let r=this;for(var o=arguments.length,n=new Array(o),l=0;l<o;l++)n[l]=arguments[l];if(i.context&&(r=nx.get("function"==typeof i.context?i.context.call(this,...n):i.context)),r.state===t)return i.sync?r[$L]:Promise.resolve(r[$L]);r.state instanceof ZL&&r.state.action==i.abortAction&&r.state.abort(r);let c=null;Array.isArray(e)?0==e.length?r.state instanceof ZL&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(c=new ex(r._state,"".concat(r.name," ").concat(a," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e.join("|")))):e!==r.state&&(c=new ex(r._state,"".concat(r.name," ").concat(a," 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(c)return d(c);let u=r.state,h=new ZL(u,t,a);ox.call(r,h);let p=e=>{var o;return r[$L]=e,h.aborted||(ox.call(r,t),null===(o=i.success)||void 0===o||o.call(this,r[$L])),e},m=e=>(ox.call(r,u,e),d(e));try{let e=s.apply(this,n);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 ex(r._state,"".concat(r.name," ").concat(a," from ").concat(e," to ").concat(t," failed: ").concat(DM),DM instanceof Error?DM:new Error(String(DM))))}}}}var rx="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 ox(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(nx.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var nx=class e extends XL.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 o=r[QL];o?this.name=o.name+"-"+o.count++:r[QL]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=tx.get(e)||[],i=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(e);tx.has(a)&&(a.stateDiagram.forEach(e=>i.add(e)),a.allStates.forEach(e=>n.add(e))),t.forEach(e=>{let{from:t,to:i,action:n}=e;"string"==typeof t?r.push({from:t,to:i,action:n}):t.length?t.forEach(e=>{r.push({from:e,to:i,action:n})}):o.push({to:i,action:n})}),r.forEach(e=>{let{from:t,to:r,action:o}=e;n.add(t),n.add(r),n.add(o+"ing"),i.add("".concat(t," --\x3e ").concat(o,"ing : ").concat(o)),i.add("".concat(o,"ing --\x3e ").concat(r," : ").concat(o," 🟢")),i.add("".concat(o,"ing --\x3e ").concat(t," : ").concat(o," 🔴"))}),o.forEach(e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),n.forEach(e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))})});let s=[...i];return Object.defineProperties(e,{stateDiagram:{value:s},allStates:{value:n}}),s}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]:{};rx(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){ox.call(this,e)}};nx.STATECHANGED="stateChanged",nx.UPDATEAFSM="updateAFSM",nx.INIT="[*]",nx.ON="on",nx.OFF="off",nx.instances=new Map,nx.instances2=new WeakMap;var ax="undefined"!=typeof window,sx=ax&&window.requestIdleCallback||function(e){let t=Date.now();return setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})},1e3)},lx=ax&&window.cancelIdleCallback||function(e){clearTimeout(e)},cx=ax&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),dx=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=rw("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=ow(rw({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=mN(),o=()=>{if(i=mN()-r,i>=t.delay&&(r=mN()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!e.isBreakLoop(t))return t.ricID=sx(o,{timeout:t.delay})};return t.ricID=sx(o,{timeout:t.delay})}static raf(t){let i,r=mN(),o=()=>document.hidden&&t.backgroundTask?(i=mN()-r,r=mN(),t.callback(),t.loopCount+=1,e.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(o,t.delay-Math.floor(i%t.delay))):(i=mN()-r,i>=t.delay&&(r=mN()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),e.isBreakLoop(t)?void 0:t.rafID=requestAnimationFrame(o));if(t.rafID=requestAnimationFrame(o),t.backgroundTask){let e=()=>{if(document.hidden){let e=mN()-r;e>=t.delay?o():t.timeoutID=setTimeout(o,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:o,onVisibilitychange:n}=this.taskMap.get(e);return t&&clearInterval(t),i&&clearTimeout(i),r&&cx&&cx(r),o&&lx(o),n&&document.removeEventListener("visibilitychange",n),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)}};cw(dx,"taskMap",new Map),cw(dx,"currentTaskID",1),cw(dx,"sharedWorker",null),cw(dx,"workerTasks",new Map);var ux=dx;aC.SEI_MESSAGE;var hx={LOAD_START:aC.LOADSTART,LOADED_DATA:aC.LOADEDDATA,LOADED_META_DATA:aC.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:aC.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:aC.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:aC.ENTER_PICTURE_IN_PICTURE,USER_RESUME_IN_PIP_OR_FULL_SCREEN:"user-resume-in-pip-or-full-screen",USER_PAUSE_IN_PIP_OR_FULL_SCREEN:"user-pause-in-pip-or-full-screen",ENTER_FULL_SCREEN:"enter-full-screen",LEAVE_FULL_SCREEN:"leave-full-screen",VOLUME_CHANGE:"volume-change"},px={};aw(px,{create:()=>fx,remove:()=>_x});var mx=new WeakMap;function fx(e,t){mx.has(e)||mx.set(e,[]);let i=mx.get(e),r={add:(e,o)=>("addEventListener"in t?(i.push(t.removeEventListener.bind(t,e,o)),t.addEventListener(e,o)):(i.push(t.off.bind(t,e,o)),t.on(e,o)),r)};return r}function _x(e){let t=mx.get(e);t&&(t.forEach(e=>e()),mx.delete(e))}var gx=new class{constructor(){cw(this,"_roomIdMap",new Map),cw(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:Cw,env:Jw.QCLOUD,browserVersion:GO.name+GO.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:i,userId:r,roomId:o}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=r,this._roomIdMap.set(r,String(o))}logSuccessEvent(e){HO||!fM.isAbleToUpload||this._configs.env===Jw.QCLOUD&&this.uploadEventToKibana(ow(rw({},e),{result:"success"}))}logFailedEvent(e){if(HO||!fM.isAbleToUpload)return;let{eventType:t,code:i,error:r,userId:o}=e,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:t,result:"failed",code:i||(null==r?void 0:r.extraCode)||(null==r?void 0:r.code)||Ew.UNKNOWN};this._configs.env===Jw.QCLOUD&&this.uploadEventToKibana(ow(rw({},n),{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,o={timestamp:Aw(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:Cw,log:t};r&&(o.errorInfo=r.message,r.stack&&(o.errorInfo+="\n".concat(r.stack)));let n=pM.enable?GN(o,2002,Number(this._configs.sdkAppId)):JSON.stringify(o);this.sendRequest(PD(this._configs.sdkAppId,Yw.LOG),n)}sendRequest(e,t){setTimeout(()=>QN({url:e,body:t,priority:"low"}).catch(()=>{}),2e3)}},Ex=new WeakMap;function vx(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:o}=e;return function(e,n,a){let s=ok({retryFunction:a.value,settings:t,onError(t){let{error:r,retry:o,reject:a,retryFuncArgs:s}=t;var l;i?i.call(this,r,()=>{var t;null!=(t=Ex.get(e))&&t.has(n)?o():a(r)},a,s):null!=(l=Ex.get(e))&&l.has(n)?o():a(r)},onRetrying(t,i){var o;ek(r)&&r.call(this,t,i),null!=(o=Ex.get(e))&&o.has(n)&&(Ex.get(e).get(n).stopRetry=i)},onRetryFailed:o});return a.value=function(){let t=Ex.get(e);for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return t?t.set(n,{args:r}):Ex.set(e,new Map([[n,{args:r}]])),s.apply(this,r).finally(()=>{var t;return null==(t=Ex.get(e))?void 0:t.delete(n)})},a}}var yx=class extends nx{constructor(e,t){super(e.id,"".concat(t,"-player")),this.options=e,this.kind=t,cw(this,"id"),cw(this,"element",null),cw(this,"track"),cw(this,"url"),cw(this,"attr"),cw(this,"mode"),cw(this,"muted"),cw(this,"_log"),cw(this,"isPausedByUserCall",!1),cw(this,"_pausedRetryCount"),cw(this,"_isElementPlayingFired",!1),cw(this,"_interval"),cw(this,"_delayDestroyTimeoutId",0),cw(this,"_playSuccessResolve"),cw(this,"_isReplayByRecreateMediaStreamCalled",!1),cw(this,"isPlayCalled",!1),cw(this,"isInAutoPlayFailedState",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=ZC,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 uw(this,null,function*(){if(!this.isPlaying)try{this.isPlayCalled=!0,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(Nw){let t=NP({key:bP.PLAY_FAILED,data:{media:this.kind,error:Nw}});if(this._log.warn(Nw),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new yw({code:Ew.PLAY_NOT_ALLOWED,message:t})}})}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;this.isPlayCalled=!1,this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!NO?this._delayDestroyTimeoutId||(null==(t=this.element)||t.remove(),this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(aC.ENDED),this._interval>0&&ux.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){this._log.info("pause"),this.isPausedByUserCall=!0,this.doPause()}doPause(){var e;null==(e=this.element)||e.pause()}resume(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.isPausedByUserCall=!1,this.doResume(e)}doResume(){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():VO?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 fx(this.element,this.element).add(aC.PLAYING,e).add(aC.ENDED,e).add(aC.PAUSE,e).add(aC.ERROR,e).add(aC.LOADSTART,e).add(aC.LOADEDDATA,e).add(aC.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==px||px.create(e,e).add(aC.ENDED,t).add(aC.MUTE,t).add(aC.UNMUTE,t),e.readyState===aC.ENDED&&this.handleTrackEvent({type:aC.ENDED}),e.muted&&this.handleTrackEvent({type:aC.MUTE})}}bindAutoPlayEvent(){dM.listeners(hM.AUTOPLAY_DIALOG_CLICK_CONFIRM).includes(this.resume)||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&&_x(e)}unbindEvents(){this.element&&_x(this.element),this.unbindTrackEvents(),dM.off(hM.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case aC.PLAYING:Vx()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(aC.PLAYING),this._interval&&(ux.clearTask(this._interval),this._interval=-1);break;case aC.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(aC.ENDED);break;case aC.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(aC.PAUSE);break;case aC.ERROR:if(this.element&&this.element.error){this.handlePaused(aC.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)),gx.uploadEvent({log:"stat-".concat(this.kind,"-").concat(UC.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),dO||cO?this.emit(hx.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case aC.LOADEDDATA:this.kind===aC.VIDEO&&this.emit(hx.LOADED_DATA);break;case aC.LOADEDMETADATA:this.kind===aC.VIDEO&&this.emit(hx.LOADED_META_DATA);break;case aC.LOADSTART:this.emit(hx.LOAD_START)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),gx.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),WP.addSuccessEvent({key:this.kind===aC.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),gx.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),WP.addFailedEvent({key:this.kind===aC.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(hx.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise((t,i)=>{PN(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)}),PN(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 uw(this,null,function*(){let t=e.type;switch(this.options.enableLogTrackState&&this._log[t===aC.UNMUTE?"info":"warn"]("track ".concat(t)),t){case aC.ENDED:this.handleStopped(aC.ENDED);break;case aC.MUTE:this.handlePaused(aC.MUTE);break;case aC.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&!this.isPausedByUserCall&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(aC.UNMUTE))}})}handlePlaying(e){var t;return this._log.debug("handlePlaying",e),null==(t=this._playSuccessResolve)||t.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};cw(yx,"PlayerEvent",hx),lw([vx({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],yx.prototype,"doReplayByRecreateMediaStream",1),lw([ix([],"PLAYING",{sync:!0,success(e){this.emit(hx.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],yx.prototype,"handlePlaying",1),lw([ix("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(hx.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],yx.prototype,"handlePaused",1),lw([ix([],"STOPPED",{sync:!0,success(e){this.emit(hx.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],yx.prototype,"handleStopped",1);var Tx="trtc_autoplay",Ix="".concat(Tx,"_mask"),Ax="".concat(Tx,"_wrapper"),Sx="".concat(Tx,"_header"),Rx="".concat(Tx,"_content"),bx="".concat(Tx,"_action_wrapper"),wx="".concat(Tx,"_question"),Cx="".concat(Tx,"_collapse"),Dx="".concat(Tx,"_action_confirm"),Nx="".concat(Tx,"_detail"),kx="#2473E8",Ox="dialog",Mx="".concat(Ox,"-show"),Px="".concat(Ox,"-1"),Lx="".concat(Ox,"-2"),xx=!1,Ux=!1,Vx=()=>Ux,Fx="".concat(Hw,"/").concat(YD()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),Bx="<br><a href='".concat(Fx,"' target='_blank'>").concat(YD()?"其他方案?":"Any other solution?","</a>"),Hx="".concat(YD()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(Bx):"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(Bx)),Wx=class{constructor(){if(cw(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),cw(this,"_dialogNode",null),cw(this,"_bodyPosition",""),cw(this,"_showDetail",!1),cw(this,"_isCollapseClicked",!1),cw(this,"_isQuestionClicked",!1),YD()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!xx){let e=document.createElement("style");e.innerHTML=".".concat(Ix,"{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(Ix," div:not(.").concat(bx,"){display:block !important;}.").concat(Ax,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(Ax," a{color:").concat(kx,";}.").concat(Sx,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(Rx,"{margin:8px 0;}.").concat(bx,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(Cx,"{margin-right:auto;cursor:pointer}.").concat(wx,"{height:100%;line-height:16px;cursor:pointer;}.").concat(Dx,"{margin-left:8px;color:#fff;background:").concat(kx,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(Dx,":hover{opacity:0.9;}.").concat(Cx,",.").concat(Dx,",.").concat(Rx,",.").concat(wx,"{font-size:14px;}@media screen and (max-width:750px){.").concat(Ax,"{width:80vw;}}"),document.head.appendChild(e),xx=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(Ix,"\"><div class='").concat(Ax,"'><div class='").concat(Sx,"'>").concat(location.host,"</div><div class='").concat(Rx,"'>").concat(this.content,"</div><div class='").concat(Nx,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(Hx,"</div><div class='").concat(bx,"'></div></div></div>").trim();let t=document.createElement("button");t.className=Dx,t.innerText=YD()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=wx,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(YD()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let o=e.content.firstChild,n=o.querySelector(".".concat(bx));return n.appendChild(r),n.appendChild(i),n.appendChild(t),o}addDiaLog(){Vx()||(Ux=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(Ax)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",fM.info("show autoplay dialog"),gx.uploadEvent({log:Mx}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Ux=!1),Gx=null}onConfirm(){fM.warn("confirm clicked, try resume stream"),dM.emit(hM.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(Nx));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||gx.uploadEvent({log:Px}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Fx,"_blank"),this._isQuestionClicked||gx.uploadEvent({log:Lx}),this._isQuestionClicked=!0}},Gx=null;function jx(){Gx||(Gx=new Wx)}var zx,Kx=class e extends yx{constructor(e){super(e,aC.VIDEO),cw(this,"stat",{}),cw(this,"_calculateTimeout",-1),cw(this,"viewMirror",!1),cw(this,"objectFit","cover"),cw(this,"container"),cw(this,"canvas"),cw(this,"shouldRenderAlpha",!1),cw(this,"_preSize",{width:0,height:0}),cw(this,"posterImg"),cw(this,"pipWindow"),cw(this,"enterPIPPromise"),cw(this,"_originContainerPosition"),cw(this,"_isResettingSrcObject",!1),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,eN(e.viewMirror)||(this.viewMirror=e.viewMirror),eN(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(aC.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,vk&&(t.poster="data:,"),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,";").concat(this.shouldRenderAlpha?"":"background-color:black",";");return this.viewMirror&&(e+="transform:scaleX(-1);"),e}setContainer(e){var t;this.container=e,this._pausedRetryCount=ZC,this.track&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),e&&e.add(aC.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(aC.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(aC.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(aC.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.addEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.addEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.addEventListener("volumechange",this.handleVolumeChange))}handleTrackEvent(e){var t;return e.type===aC.MUTE&&(null!=(t=this.stat)&&t.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(e)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(hx.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(hx.LEAVE_FULL_SCREEN))}handleVolumeChange(){var e;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(hx.VOLUME_CHANGE,{muted:null==(e=this.element)?void 0:e.muted})}handleElementEvent(e){var t,i,r,o,n,a;if(2===this.mode)return;super.handleElementEvent(e);let s=e.type,l=this.isPictureInPicture(),c=this.isFullscreen(),d=e.isTrusted&&(l&&DO||c);if(s===aC.PLAYING&&d&&!this._isResettingSrcObject&&(this._log.warn("user resume in ".concat(c?"fullscreen":"pip")),this.emit(hx.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),s===aC.PAUSE&&(d&&(this._log.warn("user pause in ".concat(c?"fullscreen":"pip")),this.emit(hx.USER_PAUSE_IN_PIP_OR_FULL_SCREEN)),this.container&&!this.container.isConnected&&(this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(this.container.id)),PN(500).then(()=>{var e;null!=(e=this.container)&&e.isConnected&&(this._pausedRetryCount=ZC,this._log.info("view container ".concat(this.container.id," is in dom, reset pausedRetryCount")))})),this._pausedRetryCount>0&&!Vx()&&!this.isPausedByUserCall&&!d&&(this._log.info("[".concat(ZC-this._pausedRetryCount+1,"/").concat(ZC,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),gk&&!d&&(this._interval=ux.run("timeout",()=>{this.element&&"PAUSED"===this._state&&!this.isPausedByUserCall&&this.doResume()},{delay:3e3})),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let e=this.element.style.transform;s===aC.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):s===aC.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}s===aC.RESIZE&&(this._preSize.height!==(null==(t=this.element)?void 0:t.videoHeight)||this._preSize.width!==(null==(i=this.element)?void 0:i.videoWidth))&&(this._log.info("video size changed to ".concat(null==(r=this.element)?void 0:r.videoWidth,"x").concat(null==(o=this.element)?void 0:o.videoHeight)),this._preSize.height=(null==(n=this.element)?void 0:n.videoHeight)||0,this._preSize.width=(null==(a=this.element)?void 0:a.videoWidth)||0,this.emit(hx.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height})),s===aC.LEAVE_PICTURE_IN_PICTURE&&(this._log.warn("exit pip"),this.isPaused&&!this.isPausedByUserCall&&(this._log.warn("resume after exit pip"),this.doResume()),this.resetSrcObjectToReplay(),this.emit(hx.LEAVE_PICTURE_IN_PICTURE)),s===aC.ENTER_PICTURE_IN_PICTURE&&this.emit(hx.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){vk&&bO&&this.isPlayCalled&&this.element&&this.track&&!this.isPausedByUserCall&&(this._log.warn("reset srcObject to replay for android chromium"),this._isResettingSrcObject=!0,this.element.srcObject=new MediaStream([this.track]),this.element.play().catch(e=>{this._log.warn("play failed after reset srcObject",e)}).finally(()=>{this._isResettingSrcObject=!1}))}setCanvas(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;var i,r,o,n;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==(o=this.container)||o.appendChild(e)):this.element&&(null==(n=this.container)||n.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){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise(i=>{if(!this.element||(this._log.info("setPoster",e.slice(0,10)),""===e?this.element.removeAttribute("poster"):this.element.poster=e,!t||!DO&&!Ak))return i();if(""===e)return this.removePosterImg(),i();if(this.posterImg)return i();let r=document.createElement("img");r.src=e;let o=window.getComputedStyle(this.element).objectFit||this.objectFit;r.style="position:absolute;top:0;left:0;width:100%;height:100%;object-fit:".concat(o,";"),r.onload=()=>uw(this,null,function*(){var e;try{r.decode&&(yield r.decode()),this.container&&"static"===window.getComputedStyle(this.container).position&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=r,null==(e=this.container)||e.appendChild(r),Ek()&&xO<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(t){this._log.warn("decode poster image error",t)}return i()}),r.onerror=()=>(this._log.warn("load poster image error"),i())})}removePosterImg(){this.posterImg&&(Ek()&&xO<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this.container&&!eN(this._originContainerPosition)&&"relative"===this.container.style.position&&(this.container.style.position=this._originContainerPosition),delete this.posterImg)}get hasPoster(){var e;return!!this.posterImg||!(null==(e=this.element)||!e.getAttribute("poster"))}pause(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return uw(this,null,function*(){dw(e.prototype,this,"pause").call(this),!this.isPictureInPicture()&&!this.hasPoster&&(bO||t&&(Ak||DO))&&(yield this.setPoster(this.getVideoFrame(),!0))})}resume(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return super.resume(e).then(()=>{var e;(this.posterImg||null!=(e=this.element)&&e.poster)&&this.setPoster("",!0)})}doResume(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.isPaused&&e&&this.element&&this.track&&bO&&"video"===this.track.kind&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;this.isPictureInPicture()&&this.exitPictureInPicture().catch(e=>{}),this.isFullscreen()&&this.exitFullscreen().catch(e=>{}),this.element&&(this.element.removeEventListener(aC.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.removeEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.removeEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.removeEventListener("volumechange",this.handleVolumeChange)),super.stop(e),null==(t=this.canvas)||t.remove(),this.removePosterImg()}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(hx.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(WL()&&this.element&&this._calculateTimeout<0){let e=0,t=null,i=(r,o)=>{this.stat.width=o.width,this.stat.height=o.height,t&&(this.stat.fps=Math.round((o.presentedFrames-t.presentedFrames)/(r-e)*1e3)),e=r,t=o,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(Nw){this._log.warn("init stat failed",Nw)}}enterFullscreen(){return uw(this,null,function*(){let e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(gk&&this.isPictureInPicture()){this._log.info("exit pip before entering fullscreen");try{yield this.exitPictureInPicture()}catch(LC){this._log.warn("exit pip failed before fullscreen:",LC)}}try{if(e.requestFullscreen)yield e.requestFullscreen();else if(e.webkitRequestFullscreen)yield e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)yield e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)yield e.mozRequestFullScreen();else{if(!e.msRequestFullscreen)throw new Error("Fullscreen API not supported");yield e.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(LC){throw this._log.error("failed to enter fullscreen:",LC),LC}})}exitFullscreen(){return uw(this,null,function*(){try{if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Exit fullscreen API not supported");yield document.msExitFullscreen()}this._log.info("exited fullscreen mode")}catch(Nw){throw this._log.error("failed to exit fullscreen:",Nw),Nw}})}isFullscreen(){let e=this.elementToRender;return!!e&&(this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e)}toggleFullscreen(){return uw(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return uw(this,null,function*(){this.enterPIPPromise=this._enterPictureInPicture();try{return yield this.enterPIPPromise}finally{delete this.enterPIPPromise}})}_enterPictureInPicture(){return uw(this,null,function*(){var e;try{if(!this.element)throw new Error("No video element available for pip");if(this.canvas&&1!==this.mode)throw new Error("pip is not supported for canvas-only mode");let{element:t}=this;if(t.requestPictureInPicture){this._log.info("requestPictureInPicture");let i=yield t.requestPictureInPicture();return this.pipWindow=i,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),null==(e=this.container)||e.appendChild(this.element)),i}if(t.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield t.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered pip mode (webkit)"),{};throw new Error("pip API not supported")}catch(LC){throw this._log.error("failed to enter pip:",LC.name,LC.message),LC}})}exitPictureInPicture(){return uw(this,null,function*(){var e,t;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this.elementToRender===this.canvas&&(null==(e=this.element)||e.remove(),this._pausedRetryCount=ZC,null==(t=this.container)||t.appendChild(this.canvas)),this._log.info("exited pip mode");else{if(!this.element||!this.element.webkitSetPresentationMode)throw new Error("Exit pip API not supported or not in PiP mode");yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited pip mode (webkit)")}}catch(SM){throw this._log.error("failed to exit pip:",SM),SM}})}isPictureInPicture(){if(!this.element)return!1;let{element:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:!!e.webkitPresentationMode&&"picture-in-picture"===e.webkitPresentationMode}togglePictureInPicture(){return uw(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function qx(e,t){return uw(this,null,function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),fM.info("worklet addModule success")}catch(Nw){throw fM.info("worklet addModule catch error. ".concat(Nw.message)),Nw}})}"undefined"!=typeof AudioContext?zx=AudioContext:"undefined"!=typeof webkitAudioContext?zx=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(zx=mozAudioContext);var Yx,Jx=1500,Xx=-1,Qx=0,$x=-1,Zx=!1,eU=0,tU=-1,iU=-1;!function e(){try{if(Yx)return;(Yx=new zx({sampleRate:48e3})).onstatechange=()=>{fM.info("context state: ".concat(Yx.state).concat("running"!==Yx.state?" visibilityState: ".concat(document.visibilityState):"")),rU()},clearTimeout(Xx)}catch(XH){fM.error("initAudioContext failed: ".concat(XH," typeof AudioContextClass: ").concat(typeof zx)),Xx=setTimeout(e,1e3)}}();var rU=()=>{"suspended"===Yx.state?(Qx=mN(),-1===$x&&($x=setTimeout(()=>{"suspended"===Yx.state&&(Zx=!0,dM.emit("155",{isSuspended:!0}))},Jx)),aU(),document.addEventListener("click",rU)):"interrupted"===Yx.state?aU():(Qx&&(WP.addNumber({key:507800,value:mN()-Qx,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Qx=0),-1!==$x&&(clearTimeout($x),$x=-1,Zx&&(Zx=!1,dM.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",rU),document.removeEventListener("click",rU))},oU=0,nU=-1;function aU(){return new Promise((e,t)=>{if("running"===Yx.state)return e();Date.now()-oU<1e3?(clearTimeout(nU),nU=setTimeout(()=>{oU=Date.now(),Yx.resume().then(e,t)},1e3)):(clearTimeout(nU),oU=Date.now(),Yx.resume().then(e,t))}).catch(e=>{fM.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",rU)})}document.addEventListener("click",rU);var sU=e=>Yx,lU=class{constructor(e){this.name=e,cw(this,"node"),cw(this,"node2"),cw(this,"pre",new Set),cw(this,"next",new Set),cw(this,"context"),cw(this,"connectedNodes",new Set),cw(this,"nextInputChannelMap",new Map),cw(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(LC){fM.error(LC)}}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(),WP.addSuccessEvent({key:502701})}catch(SM){fM.error(SM),WP.addFailedEvent({key:502701,error:SM})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),WP.addSuccessEvent({key:502702})}catch(Nw){fM.error(Nw),WP.addFailedEvent({key:502702,error:Nw})}}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}},cU=class extends lU{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,cw(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 o=0;o<e.length;o++)i=e[o]/128*100/2,r+="L".concat(t,",").concat(i),t+=1;return r}},dU=class{constructor(){cw(this,"source",new lU),cw(this,"gain",new lU),cw(this,"destination",new lU)}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(sU().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){let t=mU(e);t&&this.source.replaceNode(t)}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}},uU=class extends dU{constructor(e){super(),this.context=e,cw(this,"aec",new lU("aec")),cw(this,"mixNode",new lU("mixNode")),cw(this,"silentNode",new lU("silentNode")),cw(this,"denoiser",new lU("denoiser")),cw(this,"voiceChanger",new lU("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()}},hU=class{constructor(){cw(this,"audioContext",sU()),cw(this,"destination",this.audioContext.createMediaStreamDestination()),cw(this,"inputs",new Set),cw(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]}},pU=new WeakMap;function mU(e){try{let t=pU.get(e);if(t)return t;let i=sU();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return pU.set(e,t),t}catch(AM){if(!(Ak&&AM instanceof Error&&"NotSupportedError"===AM.name))throw AM;fM.warn(AM)}}var fU=class e{constructor(e){cw(this,"_volume",0),cw(this,"_volumeDb",0),cw(this,"_log"),cw(this,"_scriptProcessorNode",null),cw(this,"_audioWorkletNode",null),cw(this,"_interval",200),cw(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=qx(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(AM){this._log.error("volumeMeter init audio worklet error: ".concat(AM)),gx.logFailedEvent({userId:this._log.userId,eventType:UC.LOAD_WORKLET,error:AM}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=sU().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(AM){this._log.error("volumeMeter init script processor error: ".concat(AM))}}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})}};cw(fU,"lastMessageTime",0),cw(fU,"audioContext",sU()),cw(fU,"workletReady");var _U=fU,gU=class extends lU{constructor(e){super(),cw(this,"_volumeMeter"),this._volumeMeter=new _U(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return uw(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()}}},EU=_U,vU=sw(hw(),1),yU=e=>t=>t.deviceId===e,TU=class{constructor(e,t){cw(this,"kind"),cw(this,"type"),cw(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&&SU(this.devices[0])||t&&(i.forEach(e=>{if(e.deviceId&&!this.devices.find(yU(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");fM.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}),this.devices.forEach(e=>{if(e.deviceId&&!i.find(yU(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");fM.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices=i}hasDevice(e){return!!this.devices.find(t=>t.deviceId===e)}},IU=class extends vU.EventEmitter{constructor(){super(),cw(this,"audioInputs",new TU(aC.AUDIO,"Input")),cw(this,"videoInputs",new TU(aC.VIDEO,"Input")),cw(this,"audioOutputs",new TU(aC.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||ux.run("interval",()=>{this.update()},{delay:1e4}))}init(){RU().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return uw(this,arguments,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield RU(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()})}hasBlueTooth(){var e;if(1e3*(null==(e=sU())?void 0:e.outputLatency)>150)return!0;let t=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(e=>t.some(t=>e.label.toLowerCase().includes(t)))||this.audioInputs.devices.some(e=>t.some(t=>e.label.toLowerCase().includes(t)))}},AU=Mw||Ow?null:new IU;function SU(e){return e.deviceId===e.groupId&&""===e.groupId}function RU(){return uw(this,arguments,function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(XP()||!YP())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach(e=>{SU(e)&&(e.kind===aC.AUDIO_INPUT?i.audio=!0:e.kind===aC.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&&aU()}catch(SM){fM.debug("capture before getDevices failed: ",SM)}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&&NU.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i})}()})}function bU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return AU.update(e?1:0).then(e=>e.audioInputs.devices)}function wU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return AU.update(e?2:0).then(e=>e.videoInputs.devices)}var CU=!1;function DU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return uw(this,null,function*(){return(gk||DO)&&(e=!1),AU.update(e?1:0).then(e=>e.audioOutputs.devices)})}var NU=new Set;function kU(e,t){return uw(this,null,function*(){let i=(yield bU()).find(e=>e.deviceId===eD);return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t})}var OU,MU=class extends dU{constructor(e){super(),this.log=e,cw(this,"volumeMeter"),cw(this,"volumeMeterAfter3A"),cw(this,"volumeDestination"),cw(this,"analyser",new cU),this.volumeMeter=new gU({log:this.log}),this.volumeMeterAfter3A=new gU({log:this.log}),this.volumeDestination=new lU,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},PU=class e extends yx{constructor(e){super(e,aC.AUDIO),cw(this,"_outputDeviceId"),cw(this,"_floatVolume",1),cw(this,"_destination"),cw(this,"pipeline"),cw(this,"volumeMeterMode","worklet"),cw(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new MU(this._log)}setTrack(e){}get duration(){var e;return Math.floor(1e3*((null==(e=this.element)?void 0:e.duration)||0))}get currentTime(){var e;return Math.floor(1e3*((null==(e=this.element)?void 0:e.currentTime)||0))}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(("15.2"===MO||"15.3"===MO||"15.4"===MO)&&this.muted)return void this._log.info("audioElement is muted.");let t=OU||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.url&&(t.crossOrigin="anonymous",t.src=this.url),this.element=t,this.setVolume(iN(e)?e/100:this._floatVolume),t===OU&&(OU=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(hx.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(t){return uw(this,null,function*(){if(this.track||this.url){try{!this.pipeline.source.node&&this.track&&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(sU().createAnalyser()),function(){uw(this,null,function*(){try{CU||(CU=!0,fM.info("speakers:".concat((yield DU()).map(e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label)))))}catch(e){}})}()}catch(LC){throw this._log.warn("audio play error: ".concat(LC)),LO(MO,"18.7",!0)&&this.bindAutoPlayEvent(),LC}return dw(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)}setVolume(e){this._floatVolume=e,this.element&&(this.element.volume=e)}setSinkId(e){return uw(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()}},LU=class extends PU{setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(hx.MEDIA_TRACK_CHANGED,e),e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]))))}},xU=class extends PU{constructor(e){super(e),cw(this,"_sourceElement"),cw(this,"_output",new lU),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(sU().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(hx.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){var t;let i=e<=1&&!Ek();if(this._floatVolume!==e||!(i&&(null==(t=this.element)?void 0:t.volume)===e||!i&&this.pipeline.volume===e))if(this._floatVolume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e));else if(i)this.element?(this._log.info("set element volume: ".concat(e)),this.element.volume=e):this._log.info("set element volume: no element");else{if(Ek()){if(!this.enableVolumeControlInIOS)return;!function(){if(!gk||-1!==iU)return;let e=()=>{mN()-eU<500||(Yx&&"running"===Yx.state&&Yx.currentTime===tU&&(fM.warn("context is fake running, auto resume"),Yx.suspend().catch(e=>{fM.warn("context suspend failed: ".concat(e))})),tU=Yx.currentTime,eU=mN())};iU=setInterval(()=>{e()},2e3),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&e()})}()}if(Ak&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this._destination||(this._destination=sU().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),_x(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(e=>{this.emit(hx.AUTOPLAY_FAILED,e)}))}}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&NO&&(OU=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},UU=class extends nx{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:o,PlayerClass:n=(1===r?xU:Kx)}=e;var a;super(),cw(this,"id",_M()),cw(this,"userId",""),cw(this,"isRemote"),cw(this,"mediaType"),cw(this,"room"),cw(this,"user"),cw(this,"_log"),cw(this,"_inputTrack"),cw(this,"_outputTrack"),cw(this,"isPlayCalled"),cw(this,"container",null),cw(this,"player"),cw(this,"subVideoPlayerMap"),cw(this,"muted",!1),cw(this,"abortCtrl"),cw(this,"objectFit","cover"),cw(this,"mirror"),cw(this,"rotation"),cw(this,"isScreen",!1),cw(this,"manager"),cw(this,"trackSettings"),cw(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=fM.createLogger({parent:null==o?void 0:o.getLogger(),id:"".concat(this.kind[0],"t"),userId:null==(a=o||this.room)?void 0:a.userId,remoteUserId:this instanceof TB?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof TB}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:null==o?void 0:o.enableVolumeControlInIOS}),this.player.on(hx.PLAYER_STATE_CHANGED,e=>{if(dM.emit(hM.PLAYER_STATE_CHANGED,rw({track:this},e)),this.emit("player-state-changed",e),"PLAYING"===e.state&&this.room){let e=!0;for(let{remoteAudioTrack:t,remoteVideoTrack:i,remoteAuxiliaryTrack:r}of[...this.room.remotePublishedUserMap.values()])if(t.isAvailable&&!t.player.isPlaying||i.isAvailable&&!i.player.isPlaying||r.isAvailable&&!r.player.isPlaying){e=!1;break}e&&Vx()&&Gx&&Gx.deleteDialog()}}),this.kind===aC.VIDEO&&(this.player.on(hx.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(hx.LOADED_DATA),dM.emit(hM.VIDEO_LOADED_DATA,{track:this})}),this.player.on(hx.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(hx.LOADED_META_DATA)}),this.player.on(hx.MEDIA_TRACK_CHANGED,e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach(t=>t.setTrack(e))}),this.player.on(hx.RESIZE,e=>{this.emitFirstVideoFrameEvent(hx.RESIZE),this.emit("video-size-changed",rw({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(hx.ERROR,this.onPlayerError.bind(this)),this.player.on(hx.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||fM}get kind(){return 1===this.mediaType?aC.AUDIO:aC.VIDEO}get isAudio(){return this.kind===aC.AUDIO}get strMediaType(){return 4===this.mediaType?aC.VIDEO:2===this.mediaType?aC.SCREEN:aC.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 uw(this,null,function*(){let i=nN(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!eN(t.muted)&&this.setPlayerMute(t.muted),t&&!eN(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof Kx&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(nN(e)&&e.length>=1&&this.container&&e.includes(this.container)&&this.container.contains(this.player.elementToRender)?(e.splice(e.indexOf(this.container),1),e.unshift(this.container)):(this.container=i,this.player.setContainer(i))),nN(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!eN(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===aC.VIDEO)&&this.setPlayerMute(!0),t&&!eN(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof Kx&&(this.player.setObjectFit(this.objectFit),t&&!eN(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof Kx&&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),nN(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(CM){throw this.handleAutoPlayFailed(CM),CM}}else this.log.info("play has not mediaTrack, abort")})}setMirror(e,t){if(this.isScreen||this.kind!==aC.VIDEO||eN(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(rN(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 uw(this,null,function*(){if(!this._outputTrack||this.kind===aC.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,o]of e.entries()){let e=this.subVideoPlayerMap.get(o);e?t&&(eN(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(o,new Kx({id:this.userId||this.id,track:this.playerMediaTrack,container:o,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.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(ik(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),this.container=null)}resume(){return uw(this,null,function*(){var e;this.isPlayCalled&&(yield null==(e=this.player)?void 0:e.resume())})}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}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){fx(e,e).add(aC.MUTE,this.onTrackMuted).add(aC.UNMUTE,this.onTrackUnmuted).add(aC.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===aC.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){_x(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,i,r;let o=this._outputTrack;null!=o&&o.canvas&&null!=(i=null==(t=o.canvas)?void 0:t.id)&&i.includes("trtc_mix")||e!==o&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(r=e.getSettings)?void 0:r.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){var t,i;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){if(ik(this)&&this.isAudio&&null!=(t=this.user)&&t.muteState.hasAudio&&null!=(i=this.user)&&i.muteState.audioMuted)return;return this.player.stop(ik(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){return uw(this,null,function*(){var t;this.log.warn("handleAutoPlayFailed",e);let i=()=>{this.resume().then(()=>{document.removeEventListener("click",i,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((Uk||Wk)&&(yield PN(100),null!=(t=this.player)&&t.isPlaying))return;jx()}else document.addEventListener("click",i,!0);dM.once(hM.LOCAL_TRACK_CAPTURE_SUCCESS,e=>{let{track:t}=e;"audio"===t.kind&&Vx()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&i()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof Kx?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var t,i,r;if(this.isFirstVideoFrameEmitted)return;let o=null==(t=this.mediaTrack)?void 0:t.getSettings(),n=(null==o?void 0:o.width)||(null==(i=this.player.element)?void 0:i.videoWidth)||0,a=(null==o?void 0:o.height)||(null==(r=this.player.element)?void 0:r.videoHeight)||0;e===hx.RESIZE&&!n&&!a||e===hx.LOADED_META_DATA&&!n&&!a||(e===hx.LOADED_DATA&&!n&&!a&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,FN(this.rotation)&&([n,a]=[a,n]),this.emit("first-video-frame",{width:n,height:a,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"))}};lw([ix([],nx.INIT,{sync:!0})],UU.prototype,"_toInitState",1);var VU=Object.prototype.hasOwnProperty;var FU=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(JD(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(VU.call(e,t))return!1;return!0}return!1},BU=ok({retryFunction:function(e){return uw(this,null,function*(){let t=function(e){return{audio:WU(e),video:GU(e)}}(e);fM.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],o=["label","deviceId","groupId"];if(t.audio&&(i=yield bU(),fM.info("microphones: ".concat(wN(i.map(e=>ow(rw({},e),{groupId:e.groupId.substring(0,8)})),{keysToInclude:o})))),t.video&&(r=yield wU(),fM.info("cameras: ".concat(wN(r,{keysToInclude:o}))),!rN(t.video)&&"user"===t.video.facingMode&&!t.video.deviceId)){let e=r.filter(e=>!e.label.includes("infrared")).find(e=>e.label.includes("facing front"));e&&(t.video.deviceId=e.deviceId,fM.info("exclude infrared camera: ".concat(JSON.stringify(t))))}try{let i=yield navigator.mediaDevices.getUserMedia(t);return CL&&i.getTracks().forEach(t=>{var i;let r=t.getCapabilities();fM.info("".concat(t.kind," capabilities: ").concat(wN(r,{keysToInclude:sD}))),!eN(e.echoCancellation)&&-1===(null==(i=r.echoCancellation)?void 0:i.indexOf(e.echoCancellation))&&fM.warn("Invalid argument for 'echoCancellation'. Expected one of [".concat(JSON.stringify(r.echoCancellation),"], but received '").concat(e.echoCancellation,"'"))}),t.audio&&aU(),i}catch(CM){let{message:o}=CM;throw"NotFoundError"===CM.name&&(e.video&&r&&0===r.length&&(o=NP({key:bP.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(o=NP({key:bP.MICROPHONE_NOT_FOUND}))),new yw({code:Ew.INITIALIZE_FAILED,name:CM.name,message:o,constraint:CM.constraint})}})},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,retryFuncArgs:o,retriedCount:n}=e,a=n+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name||"AbortError"===t.name?(1===a?(o[0].video&&(o[0].maxResolution=!1,(!DO||o[0].width*o[0].height<=2073600)&&o[0].frameRate&&(o[0].frameRate=o[0].frameRate>10?10:5)),o[0].retryWhenExactFailed&&o[0].useExactDeviceId&&(o[0].useExactDeviceId=!1)):2===a?o[0].useDeviceIdOnly=!0:3===a&&!o[0].useExactDeviceId&&(o[0].useTrueAsConstraint=!0),i()):r(t),o[0].microphoneId&&HU(o[0].microphoneId,!1),o[0].cameraId&&HU(o[0].cameraId,!0)},onRetrying:e=>{fM.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{gx.logFailedEvent({eventType:UC.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{gx.logSuccessEvent({eventType:UC.GET_USER_MEDIA_RETRY}),gx.uploadEvent({log:"stat-".concat(UC.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function HU(e,t){return uw(this,null,function*(){let i=(t?yield wU():yield bU()).find(t=>t.deviceId===e);i&&ZD(i.getCapabilities)&&fM.warn(wN(i.getCapabilities(),{keysToInclude:sD}))})}function WU(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!FU(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(iN(e.channelCount)&&(t.channelCount=e.channelCount),(rN(e.echoCancellation)||"remote-only"===e.echoCancellation||"all"===e.echoCancellation)&&(t.echoCancellation=e.echoCancellation),rN(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),rN(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!FU(t)||t)}function GU(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&&!FU(i)?i:(e.width&&(i.width={ideal:e.width},t&&!Ak&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!Ak&&(i.height.max=e.height)),Ak&&eO&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!FU(i)||i)}var jU=BU;function zU(e){return KU((t,i)=>function(){for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return uw(this,null,function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i})})}function KU(e){return function(t,i,r){return r.value=e(r.value,i),r}}var qU=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&fM.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",()=>{fM.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState}),e=!0)}})(),YU=0,JU=class{constructor(e){cw(this,"log"),cw(this,"isRunning",!1),cw(this,"queue",[]);let t="fq".concat(++YU);e&&(t+="|".concat(e)),this.log=fM.createLogger({id:t})}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 o=rw({},e),n=new Promise((e,t)=>{o.resolve=e,o.reject=t});return o.promise=n,t?this.length<=1?this.queue.push(o):null==(r=null==(i=this.lastQueueItem)?void 0:i.promise)||r.then(o.resolve,o.reject):this.queue.push(o),this.log.debug("push ".concat(this.length),e.funcName,e.args),this.isRunning||this.callNext(),n}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length),null==e?void 0:e.funcName,null==e?void 0:e.args),e}callNext(){if(this.isRunning||0===this.length)return;let{fn:e,args:t,context:i,resolve:r,reject:o,funcName:n}=this.queue[0];this.log.debug("callNext",this.length,n,t),this.isRunning=!0,e.apply(i,t).then(r,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},XU=new WeakMap,QU=new WeakMap;function $U(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return function(t,i,r){let o=r.value;return r.value=function(){let t=XU.get(this)||new JU;for(var r=arguments.length,n=new Array(r),a=0;a<r;a++)n[a]=arguments[a];return XU.set(this,t),t.push({fn:o,args:n,context:this,funcName:i},e)},r}}function ZU(e,t){return function(i,r,o){let n=o.value,a=t=>e(...t);return o.value=function(){for(var e=arguments.length,i=new Array(e),o=0;o<e;o++)i[o]=arguments[o];let s=QU.get(this)||new Map,l=s.get(a(i))||new JU(null==t?void 0:t(...i));return s.set(a(i),l),QU.set(this,s),l.push({fn:n,args:i,context:this,funcName:r})},o}}function eV(e,t){return KU((i,r)=>function(){let r=e;try{for(var o=arguments.length,n=new Array(o),a=0;a<o;a++)n[a]=arguments[a];let e=i.apply(this,n),s=mN();return lN(e)?e.then(e=>(t?WP.addSuccessEvent({key:r,cost:mN()-s}):WP.addSuccessEvent({key:r}),e)).catch(e=>{throw WP.addFailedEvent({key:r,error:e}),e}):(WP.addSuccessEvent({key:r}),e)}catch(kw){throw WP.addFailedEvent({key:r,error:kw}),kw}})}var tV={};function iV(){}aw(tV,{Events:()=>gV,Inspect:()=>lV,LastSink:()=>cV,Sink:()=>dV,Subscribe:()=>uV,TimeoutError:()=>EV,audit:()=>RF,bindCallback:()=>eF,bindNodeCallback:()=>tF,buffer:()=>kV,bufferCount:()=>NV,bufferTime:()=>lB,call:()=>rV,catchError:()=>dB,combineLatest:()=>bV,concat:()=>AV,concatMap:()=>XF,concatMapTo:()=>QF,count:()=>sF,create:()=>pV,debounce:()=>CF,debounceTime:()=>DF,defer:()=>PV,delay:()=>cB,deliver:()=>mV,dispose:()=>nV,elementAt:()=>NF,empty:()=>oF,every:()=>LF,exhaustMap:()=>oB,exhaustMapTo:()=>nB,expand:()=>hB,filter:()=>uF,find:()=>kF,findIndex:()=>OF,first:()=>MF,fromAnimationFrame:()=>$V,fromArray:()=>HV,fromEvent:()=>KV,fromEventPattern:()=>zV,fromFetch:()=>YV,fromIterable:()=>JV,fromPromise:()=>qV,fromReadableStream:()=>QV,fromReader:()=>XV,groupBy:()=>aB,identity:()=>oV,ignoreElements:()=>hF,iif:()=>RV,inspect:()=>aV,interval:()=>WV,last:()=>PF,map:()=>FF,mapTo:()=>BF,max:()=>lF,merge:()=>TV,mergeMap:()=>eB,mergeMapTo:()=>tB,min:()=>cF,never:()=>iF,nothing:()=>iV,of:()=>BV,pairwise:()=>UF,pipe:()=>hV,race:()=>IV,range:()=>ZV,reduce:()=>aF,retry:()=>EB,scan:()=>xF,setAsapScheduler:()=>VV,share:()=>yV,shareReplay:()=>SV,skip:()=>gF,skipUntil:()=>EF,skipWhile:()=>vF,startWith:()=>CV,subject:()=>MV,subscribe:()=>fB,sum:()=>dF,switchMap:()=>zF,switchMapTo:()=>qF,take:()=>pF,takeLast:()=>_F,takeUntil:()=>mF,takeWhile:()=>fF,tap:()=>_B,throttle:()=>AF,throwError:()=>rF,timeInterval:()=>sB,timeout:()=>gB,timer:()=>GV,toPromise:()=>pB,toReadableStream:()=>mB,withLatestFrom:()=>DV,zip:()=>wV});var rV=e=>e(),oV=e=>e;function nV(){this.dispose()}var aV=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,sV=1,lV=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new _V(e,this,this.streamId++);return gV.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},cV=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=iV,this.error=iV,this.next=iV,this.dispose=iV,this.subscribe=iV,this.doDefer()}subscribe(e){return e instanceof lV?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(rV),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}},dV=class extends cV{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)}},uV=class extends cV{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:iV,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:iV,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:iV;if(super(),this._next=t,this._error=i,this._complete=r,this.then=iV,e instanceof lV){let o={toString:()=>"subscribe",id:0,source:e};this.defer(()=>{gV.defer(o,0)}),gV.create(o),gV.pipe(o),this.sourceId=o.id,this.subscribe(e),gV.subscribe({id:o.id,end:!0}),t==iV?this._next=e=>gV.next(o,0,e):this.next=e=>{gV.next(o,0,e),t(e)},r==iV?this._complete=()=>gV.complete(o,0):this.complete=()=>{this.dispose(),gV.complete(o,0),r()},i==iV?this._error=e=>gV.complete(o,0,e):this.error=e=>{this.dispose(),gV.complete(o,0,e),i(e)}}else this.subscribe(e)}next(e){this._next(e)}complete(){this.dispose(),this._complete()}error(e){this.dispose(),this._error(e)}};function hV(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 pV(e,t,i){if(aV()){let r=Object.defineProperties(Object.setPrototypeOf(e,lV.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}});gV.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof lV&&gV.addSource(r,t)}return r}return e}function mV(e,t){return function(){for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return i=>{if(i instanceof lV){let o=pV(t=>{let n=new e(t,...r);n.sourceId=o.id,n.subscribe(i)},t,arguments);return o.source=i,gV.pipe(o),o}return t=>i(new e(t,...r))}}}function fV(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var _V=class extends dV{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer(()=>{gV.defer(this.source,this.id)})}next(e){gV.next(this.source,this.id,e),this.sink.next(e)}complete(){gV.complete(this.source,this.id),this.sink.complete()}error(e){gV.complete(this.source,this.id,e),this.sink.error(e)}},gV={addSource(e,t){fV("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){fV("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;fV("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){fV("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){fV("defer",{id:e.id,streamId:t})},pipe(e){fV("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){fV("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=sV++),fV("create",{name:e.toString(),id:e.id})}},EV=class extends Error{constructor(e){super("timeout after ".concat(e,"ms")),this.timeout=e}},vV=class extends cV{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 yV(){return e=>{let t=new vV(e);if(e instanceof lV){let i=pV(e=>{t.add(e)},"share",arguments);return t.sourceId=i.id,i.source=e,gV.pipe(i),i}return pV(t.add.bind(t),"share",arguments)}}function TV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return pV(e=>{let i=new dV(e),r=t.length;i.complete=()=>{0===--r&&e.complete()},t.forEach(i.bindSubscribe)},"merge",arguments)}function IV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return pV(e=>{let i=new Map;t.forEach(t=>{let r=new dV(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 AV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return pV(e=>{let i=0,r=t.length,o=new dV(e);o.complete=()=>{i<r&&!o.disposed?(o.doDefer(),o.subscribe(t[i++])):e.complete()},o.complete()},"concat",arguments)}function SV(e){return t=>{let i=new vV(t),r=[];return i.next=function(t){r.push(t),r.length>e&&r.shift(),this.sinks.forEach(e=>e.next(t))},pV(e=>{e.defer(()=>i.remove(e)),r.forEach(t=>e.next(t)),i.add(e)},"shareReplay",arguments)}}function RV(e,t,i){return pV(r=>e()?t(r):i(r),"iif",arguments)}function bV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return pV(e=>{let i=t.length,r=i,o=i,n=new Array(i),a=()=>{0===--o&&e.complete()};t.forEach((t,i)=>{let o=new dV(e);o.next=t=>{r--,o.next=t=>{n[i]=t,0===r&&e.next(n)},o.next(t)},o.complete=a,o.subscribe(t)})},"combineLatest",arguments)}function wV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return pV(e=>{let i=t.length,r=i,o=new Array(i),n=()=>{0===--r&&e.complete()};t.forEach((t,i)=>{let r=new dV(e),a=[];o[i]=a,r.next=t=>{a.push(t),o.every(e=>e.length)&&e.next(o.map(e=>e.shift()))},r.complete=n,r.subscribe(t)})},"zip",arguments)}function CV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>pV(function(i){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.length;for(;r<o&&!i.disposed;)i.next(t[r++]);i.disposed||i.subscribe(e)},"startWith",arguments)}var DV=mV(class extends dV{constructor(e){super(e);let t=new dV(this.sink);for(var i=arguments.length,r=new Array(i>1?i-1:0),o=1;o<i;o++)r[o-1]=arguments[o];t.next=e=>this.buffer=e,t.complete=iV,t.subscribe(bV(...r))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},"withLatestFrom"),NV=mV(class extends dV{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"),kV=mV(class extends dV{constructor(e,t){super(e),this.buffer=[];let i=new dV(e);i.next=t=>{e.next(this.buffer),this.buffer=[]},i.complete=iV,i.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),OV=function(e,t,i,r){return new(i||(i=Promise))(function(o,n){function a(e){try{l(r.next(e))}catch(t){n(t)}}function s(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){e.done?o(e.value):function(e){return e instanceof i?e:new i(function(t){t(e)})}(e.value).then(a,s)}l((r=r.apply(e,t||[])).next())})};function MV(e){let t=arguments,i=yV()(pV(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=iV,i.complete=iV,i.error=iV,i}function PV(e){return pV(t=>t.subscribe(e()),"defer",arguments)}var LV={promise:e=>{Promise.resolve().then(e)},setImmediate:"undefined"!=typeof setImmediate?e=>setImmediate(e):null,setTimeout:e=>setTimeout(e,0)},xV="undefined"!=typeof Promise?LV.promise:LV.setImmediate?LV.setImmediate:LV.setTimeout,UV=e=>t=>{xV(()=>e(t))},VV=e=>{"function"==typeof e?xV=e:LV[e]&&(xV=LV[e])},FV=e=>UV(t=>{for(let i=0;!t.disposed&&i<e.length;i++)t.next(e[i]);t.complete()});function BV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return pV(FV(t),"of",arguments)}function HV(e){return pV(FV(e),"fromArray",arguments)}function WV(e){return pV(t=>{let i=0,r=setInterval(()=>t.next(i++),e);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function GV(e,t){return pV(i=>{let r=0,o=setTimeout(()=>{if(i.removeDefer(n),i.next(r++),t){let e=setInterval(()=>i.next(r++),t);i.defer(()=>{clearInterval(e)})}else i.complete()},e),n=()=>clearTimeout(o);i.defer(n)},"timer",arguments)}function jV(e,t){return i=>{let r=e=>i.next(e);i.defer(()=>t(r)),e(r)}}function zV(e,t){return pV(jV(e,t),"fromEventPattern",arguments)}function KV(e,t){if("on"in e&&"off"in e)return pV(jV(i=>e.on(t,i),i=>e.off(t,i)),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return pV(jV(i=>e.addListener(t,i),i=>e.removeListener(t,i)),"fromEvent",arguments);if("addEventListener"in e)return pV(jV(i=>e.addEventListener(t,i),i=>e.removeEventListener(t,i)),"fromEvent",arguments);throw"target is not a EventDispachter"}function qV(e){return pV(t=>{e.then(e=>{t.next(e),t.complete()},t.error.bind(t))},"fromPromise",arguments)}function YV(e,t){return pV(PV(()=>qV(fetch(e,t))),"fromFetch",arguments)}function JV(e){return pV(UV(t=>{try{for(let i of e){if(t.disposed)return;t.next(i)}t.complete()}catch(Nw){t.error(Nw)}}),"fromIterable",arguments)}function XV(e){let t=i=>OV(this,void 0,void 0,function*(){try{if(i.disposed)return;let{done:r,value:o}=yield e.read();if(r)return void i.complete();i.next(o),t(i)}catch(LC){i.error(LC)}});return pV(e=>{t(e)},"fromReader",arguments)}function QV(e){return pV(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 $V(){return pV(e=>{let t=requestAnimationFrame(function i(r){e.disposed||(e.next(r),t=requestAnimationFrame(i))});e.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function ZV(e,t){return pV(function(i){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t+e;for(;r<o&&!i.disposed;)i.next(r++);return i.complete(),"range"},"range",arguments)}function eF(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),o=2;o<i;o++)r[o-2]=arguments[o];return pV(i=>{let o=r.concat(e=>(i.next(e),i.complete()));e.apply(t,o)},"bindCallback",arguments)}function tF(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),o=2;o<i;o++)r[o-2]=arguments[o];return pV(i=>{let o=r.concat((e,t)=>e?i.error(e):(i.next(t),i.complete()));e.apply(t,o)},"bindNodeCallback",arguments)}function iF(){return pV(()=>{},"never",arguments)}function rF(e){return pV(t=>t.error(e),"throwError",arguments)}function oF(){return pV(e=>e.complete(),"empty",arguments)}var nF=class extends dV{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)}},aF=mV(nF,"reduce"),sF=e=>mV(nF,"count")((t,i)=>e(i)?t+1:t,0),lF=()=>mV(nF,"max")(Math.max),cF=()=>mV(nF,"min")(Math.min),dF=()=>mV(nF,"sum")((e,t)=>e+t,0),uF=mV(class extends dV{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"),hF=mV(class extends dV{next(e){}},"ignoreElements"),pF=mV(class extends dV{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0===--this.count&&(this.doDefer(),this.complete())}},"take"),mF=mV(class extends dV{constructor(e,t){super(e);let i=new dV(e);i.next=()=>{i.doDefer(),e.complete()},i.complete=nV,i.subscribe(t)}},"takeUntil"),fF=mV(class extends dV{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):(this.doDefer(),this.complete())}},"takeWhile"),_F=e=>aF((t,i)=>(t.push(i),t.length>e&&t.shift(),t),[]),gF=mV(class extends dV{constructor(e,t){super(e),this.count=t}next(e){0===--this.count&&(this.next=super.next)}},"skip"),EF=mV(class extends dV{constructor(e,t){super(e),e.next=iV;let i=new dV(e);i.next=()=>{i.doDefer(),e.resetNext()},i.complete=nV,i.subscribe(t)}},"skipUntil"),vF=mV(class extends dV{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),yF={leading:!0,trailing:!1},TF=class extends dV{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)}},IF=class extends dV{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:yF;super(e),this.durationSelector=t,this.config=i,this._throttle=new TF(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=iV,this._throttle.complete(),super.complete()}},AF=mV(IF,"throttle"),SF={leading:!1,trailing:!0},RF=e=>mV(IF,"audit")(e,SF),bF=class extends dV{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},wF=class extends dV{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new bF(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()}},CF=mV(wF,"debounce"),DF=e=>mV(wF,"debounceTime")(t=>GV(e)),NF=mV(class extends dV{constructor(e,t,i){super(e),this.count=t,this.defaultValue=i}next(e){0===this.count--&&(this.defaultValue=e,this.doDefer(),this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("not enough elements in sequence"))}},"elementAt"),kF=e=>t=>pF(1)(vF(t=>!e(t))(t)),OF=mV(class extends dV{constructor(e,t){super(e),this.f=t,this.i=0}next(e){this.f(e)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},"findIndex"),MF=mV(class extends dV{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.doDefer(),this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"first"),PF=mV(class extends dV{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"),LF=mV(class extends dV{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.doDefer(),this.complete())}complete(){void 0!==this.result?(this.sink.next(this.result),super.complete()):this.error(new Error("no elements in sequence"))}},"every"),xF=mV(class extends dV{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"),UF=mV(class extends dV{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},"pairwise"),VF=class extends dV{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},FF=mV(VF,"map"),BF=e=>mV(VF,"mapTo")(t=>e),HF=class extends dV{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()}},WF=class e extends dV{constructor(e,t,i){super(e),this.makeSource=t,this.combineResults=i,this.index=0}subInner(t,i){let r=this.currentSink=new i(this.sink,t,this);this.complete===e.prototype.complete&&(this.complete=this.tryComplete),r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},GF=class extends HF{},jF=class extends WF{next(e){this.subInner(e,GF),this.next=e=>{this.currentSink.dispose(),this.subInner(e,GF)}}},zF=mV(jF,"switchMap");function KF(e){return(t,i)=>e(()=>t,i)}var qF=KF(mV(jF,"switchMapTo")),YF=class extends HF{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},JF=class extends WF{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(),YF),this.disposed&&0===this.sources.length&&this.currentSink.resetComplete()}tryComplete(){0===this.sources.length&&this.currentSink.resetComplete(),this.dispose()}},XF=mV(JF,"concatMap"),QF=KF(mV(JF,"concatMapTo")),$F=class extends HF{tryComplete(){this.context.inners.delete(this),super.dispose(),0===this.context.inners.size&&this.context.resetComplete()}},ZF=class extends WF{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,$F),this.inners.add(this.currentSink)}tryComplete(){1===this.inners.size?this.inners.forEach(e=>e.resetComplete()):this.dispose()}},eB=mV(ZF,"mergeMap"),tB=KF(mV(ZF,"mergeMapTo")),iB=class extends HF{dispose(){this.context.resetNext(),super.dispose()}},rB=class extends WF{next(e){this.next=iV,this.subInner(e,iB)}},oB=mV(rB,"exhaustMap"),nB=KF(mV(rB,"exhaustMapTo")),aB=mV(class extends dV{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=MV(),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"),sB=mV(class extends dV{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"),lB=mV(class extends dV{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"),cB=mV(class extends dV{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"),dB=mV(class extends dV{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),uB=class extends HF{tryComplete(){let e=this.context.inners.delete(this);super.dispose(),e&&this.context.checkComplete()}next(e){this.sink.next(e),this.context.expandValue(e)}},hB=mV(class extends WF{constructor(e,t){super(e,t),this.project=t,this.inners=new Set,this.sourceCompleted=!1}next(e){this.sink.next(e),this.expandValue(e)}expandValue(e){let t=new uB(this.sink,e,this);this.currentSink=t,this.complete=this.tryComplete,t.complete=t.tryComplete,this.inners.add(t),t.subscribe(this.makeSource(e,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&0===this.inners.size&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},"expand"),pB=()=>e=>new Promise((t,i)=>{let r;new uV(e,e=>r=e,i,()=>t(r))}),mB=()=>e=>{let t;return new ReadableStream({start(i){t=new uV(e,i.enqueue.bind(i),i.error.bind(i),i.close.bind(i))},cancel(){t.dispose()}})},fB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:iV,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:iV,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:iV;return r=>new uV(r,e,t,i)},_B=mV(class extends dV{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"),gB=mV(class extends dV{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout(()=>this.error(new EV(this.timeout)),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),EB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0;return t=>{if(t instanceof lV){let i=pV(r=>{let o=e,n=new dV(r);n.error=e=>{o-- >0?n.subscribe(t):r.error(e)},n.sourceId=i.id,n.subscribe(t)},"retry",[e]);return i.source=t,gV.pipe(i),i}return i=>{let r=e,o=new dV(i);o.error=e=>{r-- >0?t(o):i.error(e)},t(o)}}},vB=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(vB||{}),yB=class e extends UU{constructor(e,t){super({mediaType:e,PlayerClass:t}),cw(this,"isRemote",!1),cw(this,"deviceId"),cw(this,"groupId",""),cw(this,"label",""),cw(this,"sourceTrack"),cw(this,"enableAutoSwitchWhenRecapturing",!0),cw(this,"_isRecapturing",!1),cw(this,"_lastRecaptureTime",0),cw(this,"_onMuteTimeoutId",-1),cw(this,"_encodeCheckTimeoutId",-1),cw(this,"recaptureMode",0),cw(this,"profile"),cw(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return"publishing"===this.state.toString()}get isPublished(){return"publish"===this.state}get isUseCustomSource(){return!(!this.mediaTrack||this.sourceTrack===this.mediaTrack)}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(aC.MUTE,this.onTrackMuted),e.addEventListener(aC.UNMUTE,this.onTrackUnmuted),e.addEventListener(aC.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===aC.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(aC.MUTE,this.onTrackMuted),e.removeEventListener(aC.UNMUTE,this.onTrackUnmuted),e.removeEventListener(aC.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return uw(this,null,function*(){var i;let r=this.sourceTrack;try{let r,o=mN();dM.emit(hM.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(r=new MediaStream,r.addTrack(e.customSource)):(t||null==(i=this.sourceTrack)||i.stop(),r=yield jU(e));let n=r.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:mN()-o}),r}catch(kw){throw dM.emit(hM.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:kw}),this.log.error("getUserMedia error observed ".concat(kw)),kw}finally{t&&(null==r||r.stop())}})}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=vN((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 uw(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((t,i)=>uw(this,null,function*(){var r,o,n,a,s;let l=()=>i(new yw({code:Ew.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===nx.INIT||"ready"===this.state)&&l(),hV(KV(e,"local-publish-flag-changed"),uF(()=>this.hasFlag),mF(TV(KV(this,nx.INIT),KV(this,"ready"))),fB(t,i,l))),null!=(n=null==(o=null==(r=this.room)?void 0:r.networkQuality)?void 0:o.hadRecentBadUplink)&&n.call(o,2))return t();let c=e.heartbeatCount,d=(null==(s=null==(a=this.mediaTrack)?void 0:a.stats)?void 0:s.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>uw(this,null,function*(){var r,o,n,a,s,l,u,h;if(null!=(n=null==(o=null==(r=this.room)?void 0:r.networkQuality)?void 0:o.hadRecentBadUplink)&&n.call(o,2)||e.heartbeatCount-c<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if(null!=(a=this.mediaTrack)&&a.stats){let e=this.mediaTrack.stats.totalFrames||0;e-d===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",e)}let e=this.kind===aC.AUDIO,r=this.stat.bytesSent>0;if(WP[r?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),!e){let e={H264:513704,H265:513705,VP8:513706}[(null==(l=null==(s=this.room)?void 0:s.videoCodec)?void 0:l.toUpperCase())||"H264"];e&&WP[r?"addSuccessEvent":"addFailedEvent"]({key:e})}if(!r){if(WP.addEnum({key:e?503701:513703,value:oM()}),gx.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(eM()||aM()),userId:this.userId}),this.log.warn(e?"encode failed":"".concat(null==(h=null==(u=this.room)?void 0:u.videoCodec)?void 0:h.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield PN(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),i(new yw({message:"".concat(this.strMediaType," encode failed"),code:e?Ew.AUDIO_ENCODE_FAILED:Ew.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),dM.emit(hM.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return uw(this,null,function*(){if(this.sourceTrack&&wL){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:i}=this.sourceTrack;(yield function(e){return uw(this,arguments,function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:o,kind:n}=e;return function*(){return t===i&&(n!==aC.AUDIO||t!==eD||(yield kU(r,o)))}()})}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=i,t&&(this.groupId=t),RU().then(i=>{let r=i.find(i=>{let r=i.deviceId===e;return t&&(r=r&&i.groupId===t),r});r&&this.emit("2",r)}))}})}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===aC.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(aC.AUDIO_INPUT);return!!NU.has(i)}(this.sourceTrack)||this.kind===aC.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(aC.VIDEO_INPUT);return!!NU.has(i)}(this.sourceTrack)||this._isRecapturing||e&&eO&&DO)}onTrackMuted(){if(super.onTrackMuted(),qU(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<aD)return void setTimeout(()=>this.onTrackMuted(),aD);this._onMuteTimeoutId=setTimeout(()=>uw(this,null,function*(){var e;if(null!=(e=this.sourceTrack)&&e.muted){if((gk||vk)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return uw(this,null,function*(){if(dw(e.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&0===this.recaptureMode){if(Date.now()-this._lastRecaptureTime<aD)return void setTimeout(()=>this.onTrackEnded(),aD);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return uw(this,null,function*(){var i;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||null==(i=this.sourceTrack)||i.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let o={useExactDeviceId:!0};if("user"===e||"environment"===e)o.facingMode=e;else{let t;("audio"===this.kind?yield bU():yield wU()).find(t=>t.deviceId===e)&&(t=e),o.deviceId=t}return this.capture(o,t).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})}).finally(()=>{t&&(null==r||r.stop())})})}getRecoverCaptureDeviceId(){return uw(this,null,function*(){let e=this instanceof DB;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(IB.get(t)||0)+1;if(IB.set(t,i),i>=3&&this.enableAutoSwitchWhenRecapturing){let r=e?(yield wU()).find(e=>!IB.has(e.deviceId)):(yield bU()).find(e=>!IB.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)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),null==(e=this.manager)||e.removeInput(this),this._onMuteTimeoutId&&clearTimeout(this._onMuteTimeoutId)}close(){super.close(),this.stopCapture()}};lw([ix(nx.INIT,"ready",{ignoreError:!0,sync:!0})],yB.prototype,"setStateToReady",1),lw([$U()],yB.prototype,"capture",1),lw([ix("ready","publish",{ignoreError:!0,success(){dM.emit(hM.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var t;null==(t=this.room)||t.localTracks.delete(this);let i="error",r=e instanceof yw?e:e.cause instanceof yw?e.cause:e,o=!1;r instanceof yw&&(r.message.includes("timeout")?i="timeout":r.code===Ew.API_CALL_ABORTED&&(o=!0,i="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:r}),this.log[o?"info":"error"]("publish failed",r)}}),eV(521714,!1)],yB.prototype,"publish",1),lw([KU(e=>function(){return uw(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)})}),ix([],"ready",{sync:!0})],yB.prototype,"unpublish",1);var TB=yB,IB=new Map;dM.on(hM.SWITCH_DEVICE_SUCCESS,e=>{e.track.deviceId&&IB.delete(e.track.deviceId)});var AB=class e extends TB{constructor(e){super(1,LU),cw(this,"mediaType",1),cw(this,"volume",0),cw(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),cw(this,"playerMuted",!0),cw(this,"pipeline"),cw(this,"earMonitorGainNode",new lU),cw(this,"_output",new lU),cw(this,"codecPipeline",[]),cw(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),cw(this,"mixedAudioReferenceMap",new Map),cw(this,"isAudioContextLongSuspended",!1),cw(this,"after3aSilenceStartTime",0),cw(this,"_micMuted",!1),cw(this,"_volumeDetectionTrack",null),cw(this,"_volumeDetectionSource",new lU),this.manager=e,this.pipeline=new uU(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._volumeDetectionSource.pipeTo(this.player.pipeline.volumeMeter),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 EU.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.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){eN(e)||(0!==e||this.after3aSilenceStartTime?e>0&&(this.after3aSilenceStartTime=0):this.after3aSilenceStartTime=mN())}setInputMediaStreamTrack(t){return uw(this,null,function*(){let i=this.trackSettings||{};WP.addEnum({key:501701,value:i.channelCount||0,useUV:!1}),WP.addEnum({key:501702,value:i.sampleRate||0,useUV:!1}),WP.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:o}=i;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:r,channelCount:o}))),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(t),yield dw(e.prototype,this,"setInputMediaStreamTrack").call(this,t),this.updatePlayingState(!!t)})}capture(t){return uw(this,arguments,function(t){var i=this;let{deviceId:r,customSource:o,useExactDeviceId:n=!0,retryWhenExactFailed:a}=t,s=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){let t=yield dw(e.prototype,i,"capture").call(i,{video:!1,audio:!0,microphoneId:r,echoCancellation:i.profile.echoCancellation,autoGainControl:i.profile.autoGainControl,noiseSuppression:i.profile.noiseSuppression,sampleRate:i.profile.sampleRate,channelCount:i.profile.channelCount,useExactDeviceId:n,retryWhenExactFailed:a,customSource:o},s);return aU(),t}()})}switchDevice(e){return uw(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource){if(e!==eD)return;if(yield kU(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(LC){throw this.log.error("switch microphone failed ".concat(LC)),this.deviceId&&this.recapture(this.deviceId),LC}}})}listenDeviceChange(){AU&&!AU.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&AU.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return uw(this,null,function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(vB[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){_H(this.userId,{eventId:2003,param1:6,streamType:1});let e=yield bU();e[0]?this.recapture(e[0].deviceId):t=!0}t&&AU.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){1===this.recaptureMode&&e.deviceId!==this.deviceId||(AU.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}update3A(e){return uw(this,arguments,function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:o}=e;return function*(){let e=t.sourceTrack||t.mediaTrack;if(!e)return;let n=e.getConstraints(),a=!1;!eN(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,n.echoCancellation=i,a=!0),!eN(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,n.noiseSuppression=r,a=!0),!eN(o)&&o!==t.profile.autoGainControl&&(t.profile.autoGainControl=o,n.autoGainControl=o,a=!0),a&&(Ak||DO?yield e.applyConstraints(n).catch(e=>t._log.warn("update3A failed: ",e)):t.deviceId&&(yield t.recapture(t.deviceId,!0)))}()})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&WP.addEnum({key:502700,value:2})}setMute(e,t){var i;this._cleanupVolumeDetectionTrack(),"microphone"===e?(this._micMuted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),t&&this._setupVolumeDetectionTrack(),(null==(i=this.manager)?void 0:i.mixWeight)<=1?(this.muted=!0,this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),this.emit("mute",this),dM.emit(hM.TRACK_MUTED,{track:this})):this._outputTrack&&(this._outputTrack.enabled=!0)):!0===e?(this._micMuted=!1,this.muted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),t&&this._setupVolumeDetectionTrack(),this.emit("mute",this),dM.emit(hM.TRACK_MUTED,{track:this})):(this._micMuted=!1,this.muted=!1,this.sourceTrack&&(this.sourceTrack.enabled=!0),this._inputTrack&&(this._inputTrack.enabled=!0),this._outputTrack&&(this._outputTrack.enabled=!0),this.emit("unmute",this),dM.emit(hM.TRACK_UNMUTED,{track:this}))}_setupVolumeDetectionTrack(){let e=this.sourceTrack||this.mediaTrack;if(!e)return;this._volumeDetectionTrack=e.clone(),this._volumeDetectionTrack.enabled=!0;let t=mU(this._volumeDetectionTrack);t&&this._volumeDetectionSource.setNode(t)}_cleanupVolumeDetectionTrack(){this._volumeDetectionTrack&&(this._volumeDetectionTrack.stop(),this._volumeDetectionTrack=null),this._volumeDetectionSource.deleteNode()}get isMicMuted(){return this._micMuted}setAudioVolume(e){super.setAudioVolume(0),gk&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(sU().createGain()),this._output.setNode(sU().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!DO&&!gk)return this.update3A({echoCancellation:e})}addDenoiser(e){var t;RO<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(WP.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=mU(e);if(!i)return;let r=new lU,o=sU().createGain();o.gain.value=1;let n=new lU;r.pipeTo(n).pipeTo(this.pipeline.mixNode),r.setNode(i),n.setNode(o),this.mixedAudioReferenceMap.set(t,[r,n])}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._cleanupVolumeDetectionTrack(),this.mixedAudioReferenceMap.forEach(e=>{let[t,i]=e;t.deleteNode(),i.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),AU.off("audioInputAdded",this.handleMicrophoneAdded,this),AU.off("audioInputRemoved",this.handleMicrophoneRemoved,this),dM.off(hM.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(t){let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return uw(this,null,function*(){try{yield dw(e.prototype,this,"recapture").call(this,t,i)}catch(SM){let r=(yield bU()).find(e=>e.deviceId!==t);if(!r)throw SM;yield dw(e.prototype,this,"recapture").call(this,r.deviceId)}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((e,t)=>t?t({frame:e,ntp:Iw()}):e,e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(e=>e)}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}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(NO?"":", 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)}};function SB(e,t){return t+4<=e.byteLength&&0===e.getUint8(t)&&0===e.getUint8(t+1)&&0===e.getUint8(t+2)&&1===e.getUint8(t+3)?4:t+3<=e.byteLength&&0===e.getUint8(t)&&0===e.getUint8(t+1)&&1===e.getUint8(t+2)?3:0}function RB(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=new DataView(e),r=[],o=0;for(;o<i.byteLength;){let e=SB(i,o);if(0===e){o+=1;continue}let n=-1;for(let t=o+e;t<i.byteLength;t+=1)if(SB(i,t)>0){n=t;break}let a=-1===n?i.byteLength:n,s=a-o,l=new ArrayBuffer(s),c=new DataView(l);for(let t=0;t<s;t+=1)c.setUint8(t,i.getUint8(o+t));r.push(new bB(c,t)),o=a}return r}var bB=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{seiPayloadStartIndex:e}=this,t=this.dataView.byteLength-2,i=[],r=0;for(let n=e;n<=t;n++){let e=this.dataView.getInt8(n);switch(e){case 0:case 1:case 2:case 3:2===r&&(i.push(3),r=0),0===e?r+=1:r=0,i.push(e);break;default:r=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=o}removePreventionByte(){let{seiPayloadStartIndex:e}=this,t=this.dataView.byteLength-1,i=[],r=0;for(let n=e;n<=t;n++)switch(this.dataView.getInt8(n)){case 0:r++,i.push(this.dataView.getInt8(n));break;case 3:2!==r&&i.push(this.dataView.getInt8(n)),r=0;break;default:i.push(this.dataView.getInt8(n)),r=0}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=o}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e+=1,255===this.dataView.getUint8(t));t+=1);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+=1){let i=this.dataView.getUint8(n);if(t+=1,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),r=new DataView(i),o=t;for(let n=0;n<i.byteLength;n+=1)r.setInt8(n,this.dataView.getInt8(o+n));return r}get naluType(){let e=this.getStartCodeLength();return e>=this.dataView.byteLength?0:31&this.dataView.getUint8(e)}getStartCodeLength(){return this.dataView.byteLength>=4&&0===this.dataView.getUint8(0)&&0===this.dataView.getUint8(1)&&0===this.dataView.getUint8(2)&&1===this.dataView.getUint8(3)?4:this.dataView.byteLength>=3&&0===this.dataView.getUint8(0)&&0===this.dataView.getUint8(1)&&1===this.dataView.getUint8(2)?3:0}get isIDR(){return 5===this.naluType}get isSPS(){return 7===this.naluType}get isPPS(){return 8===this.naluType}get isSEI(){return 6===this.naluType}},wB=class{constructor(){cw(this,"_seiMessageList",[]),cw(this,"_smallSeiMessageList",[]),cw(this,"_seiPayloadType",243)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),r=t%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<i;a++)o.push(255);o.push(r);let n=new DataView(e);return o.push(...new Uint8Array(n.buffer)),o.push(128),new bB(new DataView(new Uint8Array(o).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 o=0;o<e.byteLength;o++)switch(r.getUint8(o)){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)),o=r.reduce((e,t)=>e+t.dataView.byteLength,0),n=new ArrayBuffer(o+e.data.byteLength),a=new DataView(n),s=new DataView(e.data),l=0;for(let e=0;e<r.length;e++)for(let t=0;t<r[e].dataView.byteLength;t++)a.setInt8(l++,r[e].dataView.getInt8(t));for(let i=0;i<e.data.byteLength;i++)a.setInt8(l++,s.getInt8(i));return e.data=n,r.length}return 0}},CB=class e extends TB{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,Kx),cw(this,"profile",rw({},rC)),cw(this,"avoidCropping",!1),cw(this,"_scaleResolutionDownBy"),cw(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0}),cw(this,"small"),cw(this,"isNeedToSetBandwidth"),cw(this,"muteImage"),cw(this,"manager"),cw(this,"_seiCodec",new wB),this.manager=e;let t=()=>{var e;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1});else{let t=MD((null==(e=this.room)?void 0:e.sdkAppId)||0)?jw:Gw;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(t)),this.setProfile(ow(rw({},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(wL&&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)}get hasSmall(){var e;return!(null==(e=this.manager)||!e.hasSmall)}setMute(t){return uw(this,null,function*(){var i,r,o;if(tN(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,fillVideo:!0}),this.muteImage=t,dw(e.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield null==(o=this.manager)?void 0:o.deleteWatermark("mute"),this.muteImage=void 0),dw(e.prototype,this,"setMute").call(this,t)})}capture(t){return uw(this,arguments,function(t){var i=this;let{deviceId:r,facingMode:o,useExactDeviceId:n=!0,customSource:a,retryWhenExactFailed:s=!0}=t;return function*(){let t={audio:!1,video:!0,facingMode:o||i.facingMode,cameraId:r,width:i.profile.width,height:i.profile.height,frameRate:i.profile.frameRate,useExactDeviceId:n,retryWhenExactFailed:s,customSource:a};if("environment"===t.facingMode){let e=yield i.getDeviceIdWhenUsingBackCamera();e&&(t.cameraId=e)}return dw(e.prototype,i,"capture").call(i,t)}()})}setProfile(e){var t;let i=this.fallbackProfile(e);if(i.bitrate&&(this.isNeedToSetBandwidth=i.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(i);else{let e=MD((null==(t=this.room)?void 0:t.sdkAppId)||0)?jw:Gw;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(e)),super.setProfile(ow(rw({},this.profile),{width:1920,height:1080}))}}applyProfile(){return uw(this,null,function*(){var e;if(!this.mediaTrack)return;let{width:t=0,height:i=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=t*i,o=this.settings,n=o.height!==this.profile.height||o.width!==this.profile.width||o.frameRate!==this.profile.frameRate;if(n&&(16===xO&&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 n&&i&&r&&i===r?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:aC.VIDEO,videoType:aC.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return wL&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:VN(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 uw(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};"user"===e||"environment"===e?t.facingMode=e: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(LC){throw this.log.error("switch camera failed ".concat(LC)),this.deviceId&&this.recapture(this.deviceId),LC}})}getDeviceIdWhenUsingBackCamera(){return uw(this,null,function*(){let e;try{if(cO&&!EO&&DL){let t=(yield wU(!0)).map(e=>{var t;return ow(rw({},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=t[0];t.forEach(e=>{var t,r,o,n;let{capabilities:a}=e;(null!=(t=a.width)&&t.max&&null!=(r=a.height)&&r.max?a.width.max*a.height.max:0)>(null!=(o=i.capabilities.width)&&o.max&&null!=(n=i.capabilities.height)&&n.max?i.capabilities.width.max*i.capabilities.height.max:0)&&(i=e)}),null!=i&&i.capabilities&&(this._log.info("use max resolution back camera",i),e=i.deviceId)}}catch(LC){this._log.warn("get max res camera failed",LC)}return e})}updateSmallConfig(e){return uw(this,null,function*(){var t,i;this._log.info("update small stream config: ".concat(JSON.stringify(e)));let r=!this.small;this.small=this.fallbackProfile(e,!0),yield null==(t=this.manager)?void 0:t.update(),r&&(yield null==(i=this.room)?void 0: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=rw({},e);return e.width*e.height<=19200&&vk&&IO&&(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&&FO&&(r.width=i?1280:720,r.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),PO(MO,"14.3")&&LO(MO,"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&&(IO||Ak)&&!KO()&&e.width*e.height<=230400&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,r.width=1280,r.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(){AU&&!AU.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&AU.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return uw(this,null,function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(vB[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){_H(this.userId,{eventId:2003,param1:7,streamType:2});let e=yield wU();e[0]?this.recapture(e[0].deviceId):t=!0}t&&AU.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return uw(this,null,function*(){1===this.recaptureMode&&e.deviceId!==this.deviceId||(AU.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 eN(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){AU.off("videoInputAdded",this.handleCameraAdded,this),AU.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return uw(this,null,function*(){try{yield dw(e.prototype,this,"recapture").call(this,t)}catch(LC){let r=(yield wU()).find(e=>e.deviceId!==t);if(!r)throw LC;yield dw(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||eN(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};lw([zU(function(e){this.setContentHint(e.contentHint||"motion")})],CB.prototype,"capture",1);var DB=CB,NB={};aw(NB,{REPORT_TYPE:()=>WN,buildSSOPackage:()=>GN,bytes2ms:()=>GD,calculateScaleResolutionDownNumber:()=>VN,concatArrayBuffers:()=>jN,convertObjectNumberToInt:()=>MN,copyProperties:()=>WD,deepClone:()=>AN,deepCloneBasic:()=>HN,deepMerge:()=>IN,delay:()=>PN,fibonacci:()=>XD,formatedTime:()=>bN,getConstructorName:()=>dN,getContainerFromElement:()=>RN,getEnv:()=>kD,getFirst16Bits:()=>KN,getInternalVersion:()=>_N,getLast16Bits:()=>zN,getLoggerUrl:()=>PD,getMediaStreamTrackInfo:()=>UN,getMuteStateFromFlag:()=>vN,getNetworkType:()=>xD,getNumNetworkType:()=>HD,getReconnectionTimeout:()=>QD,getStringByteLength:()=>DN,getTestSignalDomain:()=>OD,getTurnServer:()=>yN,getUint32Version:()=>ON,getValueType:()=>$D,getViewListFromView:()=>SN,glog:()=>qD,ipv4ToUint32:()=>TN,isArray:()=>nN,isAudioWorkletSupported:()=>uN,isBoolean:()=>rN,isConstructor:()=>cN,isEmpty:()=>EN,isFunction:()=>ZD,isLangChinese:()=>YD,isMediaStreamTrack:()=>aN,isNumber:()=>iN,isObject:()=>oN,isOverseaSdkAppId:()=>MD,isPlainObject:()=>JD,isPortrait:()=>NN,isPromise:()=>lN,isRemoteTrack:()=>sN,isRotate90Or270:()=>FN,isSetSinkIdSupported:()=>hN,isString:()=>tN,isUndefined:()=>eN,loadImage:()=>kN,loadVideo:()=>BN,ms2bytes:()=>zD,ms2samples:()=>KD,normalizeUrl:()=>xN,performanceNow:()=>mN,promiseAny:()=>pN,samples2ms:()=>jD,setNetworkTypeFromWebRTC:()=>BD,stringify:()=>wN,stringifyIncludeValue:()=>CN,throttlePromise:()=>LN});var kB=[-1,-1,1,-1,-1,1,1,1],OB=[0,0,1,0,0,1,1,1],MB=class e extends nx{constructor(e,t){if(super(),this.context=e,cw(this,"name"),cw(this,"input"),cw(this,"output"),cw(this,"texture"),cw(this,"ctx2d",null),cw(this,"fbo"),cw(this,"width",0),cw(this,"height",0),cw(this,"x",0),cw(this,"y",0),cw(this,"program"),cw(this,"vertexShader"),cw(this,"fragmentShader"),cw(this,"totalFrames",0),cw(this,"dropFrames",0),cw(this,"matchInputSize",!0),cw(this,"texCoordBuffer"),cw(this,"positionBuffer"),cw(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),cw(this,"cost",0),cw(this,"_canvas",null),cw(this,"_image"),cw(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 JB)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==xO?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(OB),this.positionBuffer=this.createBuffer(kB),!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.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(SM){this.context.destroy(new yw({code:Ew.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(SM.message||SM)}))}}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 YB&&this.render(e)||this.context instanceof JB&&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 YB){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,o,n,a,s,l,c){let d=!(eN(a)||eN(s)||eN(l)||eN(c));return!(!this.ctx2d||!t)&&(t instanceof ImageData?(d?this.ctx2d.putImageData(t,i,r,a,s,l,c):this.ctx2d.putImageData(t,i,r),this.emit(e.RENDER,this.ctx2d.canvas)):(d?this.ctx2d.drawImage(t,a,s,l,c,i,r,o,n):this.ctx2d.drawImage(t,i,r,o,n),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:o,height:n,name:a,cost:s}=this,l=Date.now(),c=(t-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:t,x:i,y:r,width:o,height:n,timestamp:l,fps:c,name:a,cost:s},rw({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.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};cw(MB,"RENDER","render"),lw([ix(nx.INIT,"connected",{sync:!0})],MB.prototype,"connect",1),lw([ix("connected",nx.INIT,{ignoreError:!0,sync:!0})],MB.prototype,"disconnect",1),lw([ix([],"closed",{sync:!0})],MB.prototype,"close",1);var PB=MB,LB=hV(WV(250),FF(()=>performance.now()),yV()),xB=e=>t=>{let i=performance.now();hV(LB,vF(t=>t-i<e),pF(1))(t)},UB=[0,1,1,1,0,0,1,0],VB=class extends PB{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),cw(this,"_intervalId",0),cw(this,"_sequence",0),cw(this,"checkGLError",!1),cw(this,"checkVisibilityChange"),e instanceof JB?this.ctx2d=e.ctx||null:e.available&&null!=t&&t.mirrorUpAndDown&&this.setTexBuffer(UB)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),ux.clearTask(this._intervalId),this._intervalId=ux.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(ux.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof YB){let e=this.context.ctx.getError();e&&this.context.destroy(new yw({code:Ew.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(PB.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;"closed"!==this.state&&(this._intervalId&&(ux.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),ux.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),ux.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},FB=class extends VB{constructor(e,t){super(e,t),cw(this,"_videoTrack"),cw(this,"_muteOb"),cw(this,"_closedOb",KV(this,"closed")),cw(this,"_subscription"),cw(this,"_canvasContainer"),Number(kO)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=KV(this._videoTrack,"mute"),hV(KV(this._videoTrack,"ended"),mF(this._closedOb),fB(()=>{this.context.destroy(new yw({code:Ew.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=hV(this._muteOb,mF(this._closedOb),qF(xB(5e3)),uF(()=>{var e;return!(null==(e=this._videoTrack)||!e.muted||document.hidden)}),fB(()=>{this.context.destroy(new yw({code:Ew.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()}},BB=class extends FB{render(e){var t;let i=!(null==(t=this.input)||!t.requestFrame(e));if(this.context._canvas2d){let e=this.context._canvas2d.getContext("2d");e.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),e.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height),this.emit(PB.RENDER,this.context._canvas2d)}else this.emit(PB.RENDER,this.context._canvas);return i}},HB=class extends FB{constructor(e,t,i){super(e,{name:"smallDestination",logger:i}),this.resolution=t}resize(e,t){let i,r=e*t,o=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>o?i=r/o:(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))}},WB=class extends PB{constructor(e,t){super(e,rw({name:"imageSource"},t)),cw(this,"_lastImage"),cw(this,"_totalFrames",0),cw(this,"_autoResize",!1),cw(this,"_canvasRendered"),cw(this,"videoCallbackId",0),cw(this,"waitingFirstFrame",!0),cw(this,"shouldUpdate",!0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===xO&&(this._canvasRendered=MV(),hV(this._canvasRendered,CV(this._image),zF(e=>e instanceof HTMLCanvasElement?KV(e,"rendered"):oF()),mF(KV(this,"closed")),fB(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),WL()&&!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:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),({videoWidth:r,videoHeight:o}=n),!r||!o)return!1;n.width=r,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if(({width:r,height:o}=n),n!==this._lastImage)this._lastImage=n;else if(r===this.width&&o===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?(({width:r,height:o}=n),this._lastImage=n):"undefined"!=typeof VideoFrame&&n instanceof VideoFrame&&(({displayWidth:r,displayHeight:o}=n),null==(i=this._lastImage)||i.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===o&&this.totalFrames){if(t){this.useTexture();let e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)}this.resize(r,o)}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)}},GB=class extends WB{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",hV(KV(this._player,hx.PLAYER_STATE_CHANGED),mF(KV(this,"closed")),uF(e=>{let{state:t}=e;return"PLAYING"===t}),fB(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},jB=class extends GB{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,t,i){super(e,new Kx({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()}},zB=class extends PB{constructor(e,t,i){super(e,ow(rw({name:"textSource"},i),{create2d:!0})),cw(this,"hasChange",!0),cw(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 o=this.font.match(/(\d+)px/),n=(o?parseInt(o[1],10):16)*i,a=this.content.split("\n");for(let s=0;s<a.length;s++)this.ctx2d.fillText(a[s],e,t+s*n)}},KB=class extends nx{constructor(e){super(),cw(this,"frameRate"),cw(this,"_canvas"),cw(this,"log"),cw(this,"hasAlpha",!1),cw(this,"name"),cw(this,"error"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}get canvas(){return this._canvas}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 jB(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new FB(this,e)}createVideoImageSource(e,t){return new WB(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new GB(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new zB(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};cw(KB,"_ids",0);var qB=class extends KB{constructor(){super(...arguments),cw(this,"defaultProgam"),cw(this,"defaultVShader"),cw(this,"defaultFShader"),cw(this,"ctx"),cw(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(KB._ids++)),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",dD),!this.ctx)throw new yw({code:Ew.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 yw({code:Ew.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,WP.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,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=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}};cw(qB,"UNAVAILABLE","unavailable"),lw([ix(nx.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),WP.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),WP.addSuccessEvent({key:512700})}})],qB.prototype,"create",1),lw([ix("created",nx.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(qB.UNAVAILABLE,e),this.removeAllListeners()}})],qB.prototype,"destroy",1);var YB=qB,JB=class extends KB{constructor(){super(...arguments),cw(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(KB._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new yw({code:Ew.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,WP.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(),WP.addSuccessEvent({key:512703})}};function XB(e,t,i,r,o){arguments.length>5&&void 0!==arguments[5]&&arguments[5]&&([i,r]=[r,i]);let n={sWidth:e,sHeight:t,dWidth:i,dHeight:r,sx:0,sy:0,dx:0,dy:0};if(0===e||0===t)return n;switch(o){case void 0:case"fill":break;case"contain":{let o=Math.min(i/e,r/t);n.dWidth=e*o,n.dHeight=t*o,n.dx=(i-n.dWidth)/2,n.dy=(r-n.dHeight)/2;break}case"cover":{let o=Math.max(i/e,r/t),a=i/o,s=r/o;n.sx=(e-a)/2,n.sy=(t-s)/2,n.sWidth=a,n.sHeight=s;break}}return n}lw([ix(nx.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),WP.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),WP.addSuccessEvent({key:512701})}})],JB.prototype,"create",1),lw([ix("created",nx.INIT,{ignoreError:!0,sync:!0})],JB.prototype,"destroy",1);var QB=class{constructor(e,t){this.node=e,this.layout=t,cw(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}},$B=class extends PB{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),cw(this,"inputs",[]),cw(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 o=new QB(e,t);this.inputs.splice(i,0,o)}changeInputLayout(e,t){let i=this.inputs.findIndex(t=>t.node===e);if(i<0)return;let{x:r,y:o,width:n,height:a,zIndex:s,fillMode:l,rotation:c,hidden:d}=t;if(!eN(s)&&this.inputs.some(t=>t.layout.zIndex===s&&t.node!==e))throw new Error("input already exists at zIndex ".concat(t.zIndex));let u=this.inputs[i];eN(r)||(u.layout.x=r),eN(o)||(u.layout.y=o),eN(n)||(u.layout.width=n),eN(a)||(u.layout.height=a),eN(c)||(u.layout.rotation=c),eN(d)||(u.layout.hidden=d),l&&(u.layout.fillMode=l),!eN(s)&&s!==u.layout.zIndex&&(u.layout.zIndex=s,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 YB&&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=XB(t.node.width,t.node.height,t.width,t.height,t.fillMode,FN(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 o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];this.ctx2d&&(o&&([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:o,name:n}=this,a=Date.now(),s=(e-this.lastInfo.totalFrames)/((a-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:i,width:r,height:o,timestamp:a,fps:s,name:n},rw({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 YB)try{null==(t=this.context.ctx)||t.deleteBuffer(e.positionBuffer)}catch(SM){}})}close(){super.close(),this.removeAllInputs()}},ZB=[1,0,0,0,1,1,0,1],eH=class extends PB{constructor(e,t,i,r){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t}),cw(this,"mirror",!1),cw(this,"rotation",0),i&&(this.mirror=i),r&&(this.rotation=r),e instanceof YB)try{this.setTexBuffer(ZB)}catch(kw){e.destroy(new yw({code:Ew.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(kw.message||kw)}))}}draw2d(e,t,i,r,o){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(o/r,r/o)):180===this.rotation?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):270===this.rotation&&(this.ctx2d.translate(0,o),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(o/r,r/o));let n=super.draw2d(e,t,i,r,o);return this.ctx2d.restore(),n}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){FN(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}},tH=class extends TB{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,Kx),cw(this,"inputLocalVideoTracks",new Map),cw(this,"inputLocalScreenTracks",new Map),cw(this,"cameraNodeMap",new Map),cw(this,"screenNodeMap",new Map),cw(this,"textNodeMap",new Map),cw(this,"imageNodeMap",new Map),cw(this,"videoNodeMap",new Map),cw(this,"endedIds",new Set),cw(this,"videoContext"),cw(this,"mixNode"),cw(this,"destination"),cw(this,"manager"),cw(this,"stat"),cw(this,"_checkId",0),cw(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(PB.RENDER,e=>{this.emit("render",e)}),this.mixNode=new $B(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=ux.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new JB({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 o of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])o.shouldUpdate=!1;let t=null,i=0,r=!0;for(let[o,n]of this.inputLocalVideoTracks)if(n.profile.frameRate>i){if(this.endedIds.has(o)){let e=this.cameraNodeMap.get(o);e&&e.image.cancelVideoFrameCallback(e.videoCallbackId);continue}i=n.profile.frameRate,t=o}for(let[o,n]of this.inputLocalScreenTracks)if(n.profile.frameRate>i){if(this.endedIds.has(o)){let e=this.screenNodeMap.get(o);e&&e.image.cancelVideoFrameCallback(e.videoCallbackId);continue}i=n.profile.frameRate,t=o,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 uw(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),NO&&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:o}=t;if(!o)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,fx(this,AU).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===xO&&o instanceof CanvasCaptureMediaStreamTrack?this.videoContext.createVideoImageSource(o.canvas,{name:"cameraCanvasSource",logger:this.log}):this.videoContext.createVideoTrackSource(o,"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 screenSource failed");t.on("output-media-track-changed",()=>{this.updateScreenSource(e,i,t.mediaTrack)});let o=this.videoContext.createVideoTrackSource(r,"screenNodeSource");o.resize(t.settings.width,t.settings.height),o.shouldUpdate=!1,this._connectMix(o,i),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,o),this.setFpsAuto()}addTextSource(e){let{id:t,content:i="",font:r,color:o,layout:n}=e;if(this.textNodeMap.has(t))throw new Error("There is already a textSource with the same ID: ".concat(t));let a=this.videoContext.createTextSource({content:i,font:r,color:o});a.resize(n.width,n.height),this._connectMix(a,n),this.textNodeMap.set(t,a)}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,o=this.cameraNodeMap.get(e);if(o){if(i){if(16===xO&&i instanceof CanvasCaptureMediaStreamTrack)if(o instanceof jB){let t=o.output;o.close(),o=this.videoContext.createVideoImageSource(i.canvas,{name:"cameraCanvasSource",logger:this.log}),o.connect(t),this.cameraNodeMap.set(e,o)}else o.image=i.canvas;else if(o instanceof jB)o.replaceTrack(i);else{let t=o.output;o.close(),o=this.videoContext.createVideoTrackSource(i,"cameraNodeSource"),o.connect(t),this.cameraNodeMap.set(e,o)}let{width:t,height:r}=i.getSettings();t&&r&&o.resize(t,r)}r&&o.resize(r.width,r.height),(r||i)&&this.setFpsAuto(),this._changeMixLayout(o,t)}}updateScreenSource(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=this.screenNodeMap.get(e);r&&(i&&r.replaceTrack(i),this._changeMixLayout(r,t))}updateTextSource(e){let{id:t,content:i,font:r,color:o,layout:n}=e,a=this.textNodeMap.get(t);a&&(eN(i)||(a.content=i),eN(r)||(a.font=r),eN(o)||(a.color=o),a.resize(n.width,n.height),this._changeMixLayout(a,n))}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:o}=t;e.disconnect();let n=new eH(this.videoContext,this.log,r,o);n=e.connect(n),t.fillMode||(t.fillMode=i),n.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:i,rotation:r}=t,o=e.output||e;o instanceof eH&&(eN(i)||(o.mirror=i),eN(r)||(o.rotation=r),o.resize(e.width,e.height)),this.mixNode.changeInputLayout(o,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 eH&&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 eH&&i.output.close(),i.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof eH&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof eH&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof eH&&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(),ux.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(),_x(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")}},iH=_M();if("undefined"!=typeof navigator&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:iH,exposeOrigin:!0,permittedOrigins:["*"]})}catch(XH){}var rH=function(e){return uw(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:DO?{max:e.width}:{ideal:e.width,max:e.width},height:DO?{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:o=!1}=e;t.audio={echoCancellation:i,noiseSuppression:r,autoGainControl:o,sampleRate:48e3}}return t}(e);fM.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(AO&&RO<74||DO||Ak)&&fM.warn("Your browser not support capture system audio");let o=r.getVideoTracks()[0];if(o){if(e.frameRate)try{yield o.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height})}catch(CM){fM.warn("screen applyConstraints failed: ".concat(CM))}e.captureElement&&(yield function(e,t){return uw(this,null,function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&ZD(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==iH)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){fM.warn("cropTo target failed ".concat(r))}})}(o,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 eN(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);fM.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r})},oH=class extends DB{constructor(e){super(e,2),cw(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),cw(this,"objectFit","contain"),cw(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}get isShareCurrentTab(){var e,t;try{return iH===(null==(t=null==(e=this.mediaTrack)?void 0:e.getCaptureHandle())?void 0:t.handle)}catch(SM){return}}capture(e){return uw(this,arguments,function(e){var t=this;let{systemAudio:i=!1,autoGainControl:r,echoCancellation:o,noiseSuppression:n,audioTrack:a,videoTrack:s,captureElement:l,preferDisplaySurface:c}=e;return function*(){try{let e,d=mN();return s||a?(e=new MediaStream,s&&e.addTrack(s),a&&e.addTrack(a)):(e=yield rH({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:r,echoCancellation:o,noiseSuppression:n,captureElement:l,preferDisplaySurface:c}),t.sourceTrack=e.getVideoTracks()[0]),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),dM.emit(hM.LOCAL_TRACK_CAPTURE_SUCCESS,{track:t,cost:mN()-d}),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof yw?e:new yw({code:Ew.INITIALIZE_FAILED,name:e.name,message:e.message})}}()})}switchDevice(e){return uw(this,null,function*(){throw new Error("Method not implemented.")})}};lw([zU(function(e){this.setContentHint(e.contentHint||"detail")})],oH.prototype,"capture",1);var nH,aH=class extends AB{constructor(e){super(e),this._log.id="s-".concat(this._log.id),this.isScreen=!0}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 sH(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 uw(this,null,function*(){let o=sU();nH||(nH=qx(o,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 nH;let n=o.sampleRate,a=new AudioWorkletNode(o,"dumper",{numberOfInputs:e.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:n,targetSampleRate:t}});return a.channelCountMode="explicit",a.channelCount=i,r&&a.port.postMessage({port:r},[r]),e.forEach((e,t)=>e.connect(a,0,t)),new ReadableStream({start(e){a.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach(e=>e.disconnect(a)),a.port.close()}})})}var lH=class extends hU{constructor(e){super(),this.room=e,cw(this,"_localAudioTrack"),cw(this,"_localScreenAudioTrack"),cw(this,"log"),cw(this,"denoiser"),cw(this,"voiceChanger"),cw(this,"mixChangedDebounce"),cw(this,"audioProcessor"),cw(this,"encodePipeline",[]),cw(this,"decodePipeline",[]),cw(this,"getPCMAbortCtrlMap",new Map),cw(this,"audioFrameEventConfigMap",new Map),cw(this,"audioReferenceMap",new Map),cw(this,"isLocalAudioNeedAudioProcess",!1),cw(this,"isScreenAudioNeedAudioProcess",!1),this.log=fM.createLogger({parent:null==e?void 0:e.getLogger(),id:"am",userId:null==e?void 0:e.userId,sdkAppId:null==e?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}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=[],o=[];null!=(t=this._localAudioPipline)&&t.source.node&&(r.push(this._localAudioPipline.source.node),o.push("mic")),null!=(i=this._localAudioPipline)&&i.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),o.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),o.push("mix")),this.log.info("dump audio track ".concat(o,", duration: ").concat(e));let n=new AbortController,a=[],s=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),n.abort("timeout")},1e3*e),l=()=>{for(let e=0;e<o.length;e++){let t=URL.createObjectURL(new Blob(a[e])),i=document.createElement("a");i.href=t,i.download="".concat(o[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(s),n.abort("download")},c=sH(r).then(e=>e.pipeTo(new WritableStream({write(e){e.forEach((e,t)=>a[t]=a[t]?a[t].concat(e[0]):[e[0]])}}),n).catch(e=>l));return{then:c.then.bind(c),download:l}}getPCM(e,t){var i,r,o;if("undefined"==typeof WritableStream)return void this.log.warn("getPCM failed: browser not support WritableStream");let{enable:n,sampleRate:a=48e3,channelCount:s=1,port:l}=(""===t?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!n)return;this.log.info("getPCM ".concat(t||"local"));let c,d,u=Math.floor(.04*a),h=new Float32Array(u),p=new Float32Array(u),m=0,f=new AbortController,_=""===t?null==(i=this._localAudioTrack)?void 0:i.mediaTrack:null==(o=null==(r=this.room)?void 0:r.remotePublishedUserMap.get(t))?void 0:o.remoteAudioTrack.mediaTrack;if(_)return sH([sU().createMediaStreamSource(new MediaStream([_]))],a,s,l).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),c=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):(c&&(h.set(c,m),m+=c.length,c=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:a,channelCount:s,data:1===s?h:[h,p]}),h=new Float32Array(u),p=new Float32Array(u)))}}),f).catch(e=>this.log.warn("stop getPCM reason:".concat(e)))),f;this.log.info("getPCM failed: ".concat(t||"local"," has no audio track"))}get hasScreenAudioTrack(){return!eN(this._localScreenAudioTrack)}get hasAudioTrack(){return!eN(this._localAudioTrack)}changeInput(e){var t,i;return e instanceof aH?(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 AB?(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 uH?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 aH?delete this._localScreenAudioTrack:e instanceof AB&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}addAudioProcessor(e,t,i,r){var o;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==(o=this._localScreenAudioTrack)||o.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 o=this.getPCM(e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)},"");this.getPCMAbortCtrlMap.set(i,o),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:o}=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||eN(o))return;this.setAudioReferenceVolume(r,o)}}};var cH=class e extends UU{constructor(t,i,r){super({userId:i.userId,sdkAppId:t.sdkAppId,mediaType:r,room:t}),this.room=t,this.user=i,cw(this,"tinyId"),cw(this,"isRemote",!0),cw(this,"jitterBufferDelay",0),cw(this,"availableState"),cw(this,"remotePublishState"),cw(this,"_triggerCheckDecodeSubject",MV(KV(this,e.STATE_SUBSCRIBE))),cw(this,"ignoreUpdatePlayingState"),this.tinyId=i.tinyId,this.availableState=new nx("".concat(i.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new nx("".concat(i.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),hV(TV(KV(this,nx.STATECHANGED),KV(this.remotePublishState,nx.STATECHANGED)),FF(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),fB(e=>{this.availableState.state!==(e?nx.ON:nx.OFF)&&(this.availableState.state=e?nx.ON:nx.OFF),(!this.isRemotePublished||!this.ignoreUpdatePlayingState)&&this.updatePlayingState(e)}));let o=hV(KV(this.player,hx.ERROR),uF(e=>e.code===MediaError.MEDIA_ERR_DECODE)),n=hV(GV(5e3),uF(()=>!!(!this.ignoreDecodeError&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived&&this.isRemotePublished)&&(!this.player.isPlaying&&!(this.kind===aC.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1)))),a=hV(IV(o,n),mF(KV(this,nx.INIT)));hV(this._triggerCheckDecodeSubject,uF(()=>!this.ignoreDecodeError),qF(a),fB(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,i,r;return null!=(r=null==(i=null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.hadRecentBadDownlink)?void 0:i.call(t,2))&&r||this.player.isInAutoPlayFailedState}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===e.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===nx.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var i,r;let o=this.kind===aC.AUDIO;if(WP[e?"addSuccessEvent":"addFailedEvent"]({key:o?504700:514702}),!o){let t=(null==(i=this.room)?void 0:i.downlinkVideoCodec.toUpperCase())||"H264";WP[e?"addSuccessEvent":"addFailedEvent"]({key:FP["DECODE_".concat(t,"_RESULT")]}),e||this.log.warn("".concat(null==(r=this.room)?void 0:r.downlinkVideoCodec," decode failed"))}e||(WP.addEnum({key:o?504701:514703,value:oM()}),gx.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(eM()||aM()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===aC.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),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?nx.ON:nx.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};cw(cH,"STATE_SUBSCRIBE","subscribe"),lw([function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return KU((i,r)=>function(){for(var o=arguments.length,n=new Array(o),a=0;a<o;a++)n[a]=arguments[a];return new Promise((o,a)=>{let s=setTimeout(()=>{let i=new yw({code:Ew.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});(this.log||this._log||fM).warn(i),2===t?a(i):1===t&&o()},1e3*e);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(s),i.apply(this,n).then(o,a).finally(()=>{clearTimeout(s),this._checkPendingPromiseSet&&s&&this._checkPendingPromiseSet.delete(s)})})})}(5,1)],cH.prototype,"waitHasMediaTrack",1),lw([ix(nx.INIT,cH.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),dM.emit(hM.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),eV(521716,!1)],cH.prototype,"subscribe",1),lw([ix(cH.STATE_SUBSCRIBE,nx.INIT,{sync:!0,success(){this.log.info("unsubscribed"),dM.emit(hM.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],cH.prototype,"unsubscribe",1);var dH=cH,uH=class extends dH{constructor(e,t){super(e,t,1),cw(this,"volume",0),cw(this,"mediaType",1),cw(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}get dbVolume(){return EU.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return!!this.manager&&(this.manager.decodePipeline.some(e=>e)||(null==(t=null==(e=this.player.element)?void 0:e.error)?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&PL().AudioDecoder&&NL)}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[i,r]of this.manager.decodePipeline.entries()){if(!r)continue;let o={frame:e,track:this};if(1===i&&this.isAvailable&&"audience"===this.room.role&&(o.onAudioFrameNTPTime=e=>{let{ntp:t,frame:i,hasLeavingTag:r}=e;this.emit("audio-frame-with-ntp",{ntp:t,frame:i,hasLeavingTag:r})}),t=r(o),!t)return}return t}getAudioLevel(){if(!this.isAvailable)return 0;let e=this.volume||super.getAudioLevel();return e>1?1:e}getInternalAudioLevel(){return this.isAvailable?super.getInternalAudioLevel():0}get isRemotePublished(){return this.user.muteState.audioAvailable}},hH=class extends PB{constructor(e,t,i,r,o){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t}),this.setContainer=r,cw(this,"initStat",{alphaStitchingType:1}),cw(this,"end",MV()),cw(this,"minSize",320),cw(this,"maxSize",1280),cw(this,"draggable",!1),cw(this,"startDragX",0),cw(this,"startDragY",0),cw(this,"left",0),cw(this,"top",0),cw(this,"baseWidth",320),cw(this,"baseRatio"),cw(this,"container"),this.initStat=o,this.draggable=i,this.bindDragEvents(),WP.addEnum({key:515700,value:1}),this.draggable&&WP.addEnum({key:515700,value:11})}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=mF(this.end);hV(KV(e,"mousedown"),_B(this.startDrag.bind(this)),zF(()=>hV(KV(window,"mousemove"),mF(KV(window,"mouseup")))),t,fB(this.doDrag.bind(this))),hV(KV(e,"dblclick"),t,fB(this.resetPosition.bind(this))),hV(KV(e,"wheel"),t,fB(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}startDrag(e){e.preventDefault(),0===e.button&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),e&&this.baseRatio&&this.draggable&&(e.style.setProperty("width","".concat(this.baseWidth,"px")),e.style.setProperty("height","".concat(this.baseWidth/this.baseRatio,"px")),e.style.setProperty("position","fixed"),e.style.setProperty("left","".concat(this.left,"px")),e.style.setProperty("top","".concat(this.top,"px")))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=e.deltaY,i=this.context._canvas;i&&(this.baseWidth||(this.baseWidth=i.offsetWidth),this.baseWidth=t<0?Math.min(1.1*this.baseWidth,this.maxSize):Math.max(.9*this.baseWidth,this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,i,r,o){var n;let{ctx2d:a}=this,s=this.context._canvas;if(!a||!s)return!1;let l=super.draw2d(e,t,i,r,o),c=a.getImageData(0,0,r,o),{data:d}=c,u=!1;if(1===this.initStat.alphaStitchingType){let e=Math.floor(r/2);for(let t=0;t<o;t++)for(let i=0;i<e;i++){let o=4*(t*r+i),n=4*(t*r+(i+e)),a=d[n];d[n+3]=0;let s=a>=100;d[o+3]=s?255:0}u=super.draw2d(c,0,0,0,0,e,o),s.width=e}else if(2===this.initStat.alphaStitchingType){let e=Math.floor(o/2);for(let t=0;t<e;t++)for(let i=0;i<r;i++){let o=4*(t*r+i),n=4*((t+e)*r+i),a=d[n];d[n+3]=0;let s=a>=100;d[o+3]=s?255:0}u=super.draw2d(c,0,0,0,0,r,e),s.height=e}return null==(n=this.context.ctx)||n.clearRect(0,0,r,o),l&&u}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};var pH=class extends dH{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),cw(this,"mediaType",4),cw(this,"source"),cw(this,"shouldRenderAlpha",!1),cw(this,"alphaNode"),cw(this,"shouldBeDraggable",!0),cw(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0,keyFramesDecoded:0}),cw(this,"_keyFrameCountLogged",!1),cw(this,"_keyFrameStartTimestamp",0),cw(this,"_keyFrameStartCount",0),cw(this,"_keyFrameIntervals",[]),cw(this,"_prevKeyFrameTimestamp",0),this.manager=e.videoManager,this.on("first-video-frame",e=>{this.room.emit("first-video-frame",e)})}isAlphaSei(e){if(this.userId!==e.userId||50!==e.seiPayloadType)return!1;let t=new Uint8Array(e.data);return t.length%3==0&&0===t[0]&&1===t[1]&&t}play(e,t){return null!=t&&t.canvasRender&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),dM.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(this.alphaNode){let e=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===e)return;this.alphaNode.initStat={alphaStitchingType:e};let i=this.player.getElement();if(i){let t=i.videoWidth/i.videoHeight;t&&(this.alphaNode.baseRatio=t*(1===e?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(e))}else this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2])}generateAlphaCanvasName(e){let t=RP[e];return"".concat("alpha","_").concat(t,"_").concat(this.userId)}useCanvasPlayer(e){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let t=new JB({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let i=new VB(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let r=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},o=new hH(t,this.log,this.shouldBeDraggable,r,{alphaStitchingType:e});this.source.connect(o),o.connect(i),this.alphaNode=o}else this.source.connect(i);WL()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),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;!iN(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),dM.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),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)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}updateKeyFramesDecoded(e){let t=this.stat.keyFramesDecoded||0;if(this.stat.keyFramesDecoded=e,this._keyFrameCountLogged)return;let i=Date.now();if(!this._keyFrameStartTimestamp)return this._keyFrameStartTimestamp=i,this._keyFrameStartCount=e,void(this._prevKeyFrameTimestamp=i);if(this._prevKeyFrameTimestamp&&e>t){let r=e-t,o=(i-this._prevKeyFrameTimestamp)/1e3/r;this._keyFrameIntervals.push(o)}this._prevKeyFrameTimestamp=i;let r=i-this._keyFrameStartTimestamp;if(r>=16e3){let t=e-this._keyFrameStartCount,i=t>0?r/1e3/t:0,o="".concat(t," keyframes in 16s ").concat(i," [").concat(this._keyFrameIntervals.map(e=>e.toFixed(1)).join(","),"] keyFramesDecoded ").concat(e),n=i<=2.5?"debug":"info";this.log[n](o),this._keyFrameCountLogged=!0}}},mH=class extends pH{constructor(e,t){super(e,t,2),cw(this,"mediaType",2),cw(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},fH=new Map;function _H(e,t){let i=ow(rw({},t),{timestamp:Iw()});fH.has(e)?fH.get(e).push(i):fH.set(e,[i])}function gH(e){if(fH.has(e)){let t=fH.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 fH.delete(e),t}return[]}function EH(e,t,i,r){try{if(nN(e))for(let o=0;o<e.length;o++)vH.call(this,{rule:e[o],value:t[o],key:e[o].name,fnName:i,className:r});else vH.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}catch(SM){throw fM.error(SM),SM}}function vH(e){let{rule:t,value:i,key:r,fnName:o,className:n}=e;if(eN(i)){if(t.required)throw new yw({code:Ew.INVALID_PARAMETER,message:NP({key:bP.INVALID_PARAMETER_REQUIRED,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(eN(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),ZD(t.type[r])&&i instanceof t.type[r]&&(e=!0),tN(t.type[r])&&$D(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new yw({code:Ew.INVALID_PARAMETER,message:NP({key:bP.INVALID_PARAMETER_TYPE,data:{key:r,rule:{type:t.type.map(e=>cN(e)?dN(e):tN(e)?e:$D(e))},fnName:o,value:i},link:{className:n,fnName:o}})})}else if(!eN(t.type)&&$D(i)!==t.type)throw new yw({code:Ew.INVALID_PARAMETER,message:NP({key:bP.INVALID_PARAMETER_TYPE,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(!1===t.allowEmpty){let e=iN(i)&&(0===i||Number.isNaN(i)),a=tN(i)&&""===i.trim();if(e||a)throw new yw({code:Ew.INVALID_PARAMETER,message:NP({key:bP.INVALID_PARAMETER_EMPTY,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})})}if(t.notLessThanZero&&iN(i)&&i<0)throw new yw({code:Ew.INVALID_PARAMETER,message:NP({key:bP.CANNOT_LESS_THAN_ZERO,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(!eN(t.min)&&iN(i)&&i<t.min)throw new yw({code:Ew.INVALID_PARAMETER,message:NP({key:bP.INVALID_PARAMETER_MIN,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(!eN(t.max)&&iN(i)&&i>t.max)throw new yw({code:Ew.INVALID_PARAMETER,message:NP({key:bP.INVALID_PARAMETER_MAX,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(tN(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new yw({code:Ew.INVALID_PARAMETER,message:NP({key:bP.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})})}else if(ZD(t.instanceOf)&&!(i instanceof t.instanceOf))throw new yw({code:Ew.INVALID_PARAMETER,message:NP({key:bP.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(t.values&&!t.values.includes(i))throw new yw({code:Ew.INVALID_PARAMETER,message:NP({key:bP.INVALID_PARAMETER_RANGE,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});let{properties:a}=t;JD(a)&&oN(i)&&Object.keys(a).forEach(e=>{vH.call(this,{rule:a[e],value:i&&i[e],key:"".concat(r,".").concat(e),fnName:o,className:n})});let{arrayItem:s}=t;JD(s)&&nN(i)&&i.forEach((e,t)=>{vH.call(this,{rule:s,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:o,className:n})}),ZD(t.validate)&&t.validate.call(this,i,r,o,n,this)}dM.on(hM.JOIN_SUCCESS,e=>{let{room:t}=e;_H(t.userId,{eventId:32788})}),dM.on(hM.LEAVE_START,e=>{let{room:t}=e;_H(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),_H(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),_H(t.room.userId,{eventId:e})}}),dM.on(hM.TRACK_MUTED,e=>{let{track:t}=e;t.room&&(t.kind===aC.AUDIO?_H(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):_H(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===aC.AUDIO?_H(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):_H(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&&_H(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&_H(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&_H(t.room.userId,{eventId:32803,remoteUserId:t.userId}))}),dM.on(hM.REMOTE_TRACK_UNSUBSCRIBED,e=>{let{track:t}=e;t.room&&(1===t.mediaType&&_H(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&_H(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&_H(t.room.userId,{eventId:32804,remoteUserId:t.userId}))}),dM.on(hM.SWITCH_DEVICE_SUCCESS,e=>{let{track:t}=e;t.room&&_H(t.room.userId,{eventId:t.kind===aC.VIDEO?32780:32781})}),dM.on(hM.LOCAL_TRACK_REPLACED,e=>{let{track:t}=e;t.room&&_H(t.room.userId,{eventId:t.kind===aC.VIDEO?32782:32783})}),dM.on(hM.SIGNAL_CONNECTION_STATE_CHANGED,e=>{let t,{room:i,prevState:r,state:o}=e;switch(o){case"CONNECTED":t="RECONNECTING"===r?32795:32791;break;case"DISCONNECTED":t="RECONNECTING"===r?32796:32790;break;case"RECONNECTING":t=32794}t&&_H(i.userId,{eventId:t})}),dM.on(hM.PEER_CONNECTION_STATE_CHANGED,e=>{let t,{room:i,prevState:r,state:o,remoteUserId:n}=e,a=!!n;switch(o){case"CONNECTED":t="RECONNECTING"===r?a?32801:32798:a?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===r&&(t=a?32802:32799);break;case"RECONNECTING":t=a?32800:32797}t&&_H(i.userId,{eventId:t,remoteUserId:n})}),dM.on(hM.VIDEO_CODEC_IMPLEMENTATION_CHANGED,e=>{let{implementation:t,userId:i,remoteUserId:r,codec:o,isHWCodec:n,prevImplementation:a,streamType:s}=e,l=n?1:0;a||(l=n?3:2);let c={H264:0,H265:1,VP8:2}[o.toUpperCase()],d={eventId:4004,param1:l,param2:c,streamType:s||2};r&&(d.remoteUserId=r,d.eventId=4005),_H(i,d),WP.addEnum({key:r?514701:513701,value:l}),WP.addEnum({key:r?514700:513700,value:c})}),dM.on(hM.LOCAL_TRACK_RECAPTURE,e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===aC.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),_H(t.userId,e)}}),sw(hw(),1),sw(hw(),1);var yH=Object.create,TH=Object.defineProperty,IH=Object.defineProperties,AH=Object.getOwnPropertyDescriptor,SH=Object.getOwnPropertyDescriptors,RH=Object.getOwnPropertyNames,bH=Object.getOwnPropertySymbols,wH=Object.getPrototypeOf,CH=Object.prototype.hasOwnProperty,DH=Object.prototype.propertyIsEnumerable,NH=(e,t,i)=>t in e?TH(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,kH=(e,t)=>{for(var i in t||(t={}))CH.call(t,i)&&NH(e,i,t[i]);if(bH)for(var i of bH(t))DH.call(t,i)&&NH(e,i,t[i]);return e},OH=(e,t)=>IH(e,SH(t)),MH=(e,t,i)=>(i=null!=e?yH(wH(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of RH(t))CH.call(e,o)||o===i||TH(e,o,{get:()=>t[o],enumerable:!(r=AH(t,o))||r.enumerable});return e})(!t&&e&&e.__esModule?i:TH(i,"default",{value:e,enumerable:!0}),e)),PH=(e,t,i,r)=>{for(var o,n=r>1?void 0:r?AH(t,i):t,a=e.length-1;a>=0;a--)(o=e[a])&&(n=(r?o(t,i,n):o(n))||n);return r&&n&&TH(t,i,n),n},LH=(e,t,i)=>NH(e,"symbol"!=typeof t?t+"":t,i),xH=((e,t)=>function(){return t||(0,e[RH(e)[0]])((t={exports:{}}).exports,t),t.exports})({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(e,t){var i=Object.prototype.hasOwnProperty,r="~";function o(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,i,o,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var s=new n(i,o||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],s]:e._events[l].push(s):(e._events[l]=s,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new o:delete e._events[t]}function l(){this._events=new o,this._eventsCount=0}Object.create&&(o.prototype=Object.create(null),(new o).__proto__||(r=!1)),l.prototype.eventNames=function(){var e,t,o=[];if(0===this._eventsCount)return o;for(t in e=this._events)i.call(e,t)&&o.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},l.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 o=0,n=i.length,a=new Array(n);o<n;o++)a[o]=i[o].fn;return a},l.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},l.prototype.emit=function(e,t,i,o,n,a){var s=r?r+e:e;if(!this._events[s])return!1;var l,c,d=this._events[s],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,o),!0;case 5:return d.fn.call(d.context,t,i,o,n),!0;case 6:return d.fn.call(d.context,t,i,o,n,a),!0}for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d.fn.apply(d.context,l)}else{var h,p=d.length;for(c=0;c<p;c++)switch(d[c].once&&this.removeListener(e,d[c].fn,void 0,!0),u){case 1:d[c].fn.call(d[c].context);break;case 2:d[c].fn.call(d[c].context,t);break;case 3:d[c].fn.call(d[c].context,t,i);break;case 4:d[c].fn.call(d[c].context,t,i,o);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d[c].fn.apply(d[c].context,l)}}return!0},l.prototype.on=function(e,t,i){return a(this,e,t,i,!1)},l.prototype.once=function(e,t,i){return a(this,e,t,i,!0)},l.prototype.removeListener=function(e,t,i,o){var n=r?r+e:e;if(!this._events[n])return this;if(!t)return s(this,n),this;var a=this._events[n];if(a.fn)a.fn!==t||o&&!a.once||i&&a.context!==i||s(this,n);else{for(var l=0,c=[],d=a.length;l<d;l++)(a[l].fn!==t||o&&!a[l].once||i&&a[l].context!==i)&&c.push(a[l]);c.length?this._events[n]=1===c.length?c[0]:c:s(this,n)}return this},l.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new o,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=r,l.EventEmitter=l,void 0!==t&&(t.exports=l)}}),UH=MH(xH(),1),VH=Symbol("instance"),FH=Symbol("cacheResult"),BH=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,zH.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},HH=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var WH=new Map;function GH(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,o,n)=>{let a=i.action||o;if(!i.context){let i=WH.get(r)||[];WH.has(r)||WH.set(r,i),i.push({from:e,to:t,action:a})}let s=n.value;n.value=function(){let r=this;for(var o=arguments.length,n=new Array(o),l=0;l<o;l++)n[l]=arguments[l];if(i.context&&(r=KH.get("function"==typeof i.context?i.context.call(this,...n):i.context)),r.state===t)return i.sync?r[FH]:Promise.resolve(r[FH]);r.state instanceof BH&&r.state.action==i.abortAction&&r.state.abort(r);let c=null;Array.isArray(e)?0==e.length?r.state instanceof BH&&r.state.abort(r):"string"==typeof r.state&&e.includes(r.state)||(c=new HH(r._state,"".concat(r.name," ").concat(a," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e.join("|")))):e!==r.state&&(c=new HH(r._state,"".concat(r.name," ").concat(a," 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(c)return d(c);let u=r.state,h=new BH(u,t,a);zH.call(r,h);let p=e=>{var o;return r[FH]=e,h.aborted||(zH.call(r,t),null===(o=i.success)||void 0===o||o.call(this,r[FH])),e},m=e=>(zH.call(r,u,e),d(e));try{let e=s.apply(this,n);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 HH(r._state,"".concat(r.name," ").concat(a," from ").concat(e," to ").concat(t," failed: ").concat(DM),DM instanceof Error?DM:new Error(String(DM))))}}}}var jH="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 zH(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(KH.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var KH=class e extends UH.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 o=r[VH];o?this.name=o.name+"-"+o.count++:r[VH]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=WH.get(e)||[],i=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(e);WH.has(a)&&(a.stateDiagram.forEach(e=>i.add(e)),a.allStates.forEach(e=>n.add(e))),t.forEach(e=>{let{from:t,to:i,action:n}=e;"string"==typeof t?r.push({from:t,to:i,action:n}):t.length?t.forEach(e=>{r.push({from:e,to:i,action:n})}):o.push({to:i,action:n})}),r.forEach(e=>{let{from:t,to:r,action:o}=e;n.add(t),n.add(r),n.add(o+"ing"),i.add("".concat(t," --\x3e ").concat(o,"ing : ").concat(o)),i.add("".concat(o,"ing --\x3e ").concat(r," : ").concat(o," 🟢")),i.add("".concat(o,"ing --\x3e ").concat(t," : ").concat(o," 🔴"))}),o.forEach(e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),n.forEach(e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))})});let s=[...i];return Object.defineProperties(e,{stateDiagram:{value:s},allStates:{value:n}}),s}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]:{};jH(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){zH.call(this,e)}};KH.STATECHANGED="stateChanged",KH.UPDATEAFSM="updateAFSM",KH.INIT="[*]",KH.ON="on",KH.OFF="off",KH.instances=new Map,KH.instances2=new WeakMap;var qH=class extends KH{constructor(){super(...arguments),LH(this,"decoder"),LH(this,"config")}initialize(){return uw(this,null,function*(){this.decoder=new VideoDecoder({output:e=>{this.emit("videoFrame",e)},error:e=>{this.close(),this.emit("error",e)}})})}configure(e){this.config=e,e.description||"av1"===e.codec||(this.config[e.codec]={format:"annexb"}),this.decoder.configure(OH(kH({},e),{codec:this.getCodec(e)}))}getCodec(e){switch(e.codec){case"hevc":return"hvc1.1.6.L0.12.34.56.78.9A.BC";case"av1":return"av01.0.05M.08";case"avc":return"avc1.420028";default:return e.codec}}decode(e){"configured"===this.decoder.state&&this.decoder.decode(new EncodedVideoChunk(e))}flush(){this.decoder.flush()}reset(){this.decoder.reset()}close(){"closed"!==this.decoder.state&&this.decoder.close()}};function YH(){var e;self.onmessage=t=>{if("init"===t.data.type){let{canvas:i,wasmScript:r,wasmBinary:o}=t.data,n=null==i?void 0:i.getContext("2d"),a=0,s=0,l={wasmBinary:o,postRun:()=>{e=new l.VideoDecoder({videoInfo(e,t){a=e,s=t,console.log("video info",e,t)},yuvData(e,t){let r=a*s,o=r>>2,c=l.HEAPU32[e>>2],d=l.HEAPU32[1+(e>>2)],u=l.HEAPU32[2+(e>>2)],h=l.HEAPU8.subarray(c,c+r),p=l.HEAPU8.subarray(d,d+o),m=l.HEAPU8.subarray(u,u+o),f=new Uint8Array(r+o+o);f.set(h),f.set(p,r),f.set(m,r+o);let _=new VideoFrame(f,{codedWidth:a,codedHeight:s,format:"I420",timestamp:t});i?(null==n||n.drawImage(_,0,0,i.width,i.height),null==n||n.commit()):self.postMessage({type:"yuvData",videoFrame:_},[_])}}),self.postMessage({type:"ready"})}};Function("var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;return "+r)()(l)}else if("decode"===t.data.type){let{packet:i}=t.data;null==e||e.decode(i.data,"key"==i.type,i.timestamp)}else if("setCodec"===t.data.type){let{codec:i,format:r,description:o}=t.data;null==e||e.setCodec(i,r,null!=o?o:"")}}}PH([GH([KH.INIT,"closed"],"initialized")],qH.prototype,"initialize",1),PH([GH("initialized","configured",{sync:!0})],qH.prototype,"configure",1),PH([function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return(e,i,r)=>{let o=r.value,n=i;r.value=function(){if(!t.includes(this.state.toString()))throw new HH(this.state,"".concat(this.name," ").concat(n," failed: current state ").concat(this.state," not in ").concat(t));for(var e=arguments.length,i=new Array(e),r=0;r<e;r++)i[r]=arguments[r];return o.apply(this,i)}}}("configured")],qH.prototype,"decode",1),PH([GH([],KH.INIT,{sync:!0})],qH.prototype,"reset",1),PH([GH([],"closed",{ignoreError:!0,sync:!0})],qH.prototype,"close",1);var JH=class extends KH{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0,o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];super(),this.createModule=e,this.wasmBinary=t,this.workerMode=i,this.canvas=r,this.yuvMode=o,LH(this,"worker"),LH(this,"decoder"),LH(this,"config"),LH(this,"module",{}),LH(this,"width",0),LH(this,"height",0)}initialize(e){return uw(this,null,function*(){var t;if(this.workerMode){let e=new RegExp("\\{(.+)\\}","s").exec(YH.toString())[1];this.worker=new Worker(URL.createObjectURL(new Blob([e],{type:"text/javascript"})));let i=null==(t=this.canvas)?void 0:t.transferControlToOffscreen(),r=yield this.wasmBinary;return console.warn("worker mode",r),this.worker.postMessage({type:"init",canvas:i,wasmScript:this.createModule.toString(),wasmBinary:r},i?[i,r]:[r]),new Promise(e=>{this.worker.onmessage=t=>{if("ready"===t.data.type)delete this.wasmBinary,e(),console.warn("worker mode initialize success");else if("yuvData"===t.data.type){let{videoFrame:e}=t.data;this.emit("videoFrame",e)}}})}let i=this.module;return this.wasmBinary&&(i.wasmBinary=yield this.wasmBinary),i.print=e=>console.log(e),i.printErr=e=>console.log("[JS] ERROR: ".concat(e)),i.onAbort=()=>console.log("[JS] FATAL: WASM ABORTED"),new Promise(t=>{i.postRun=e=>{this.decoder=new this.module.VideoDecoder(this),console.log("video soft decoder initialize success"),t()},e&&Object.assign(i,e),this.createModule(i)})})}configure(e){var t,i,r;this.config=e;let o=this.config.codec.startsWith("avc")?"avc":"hevc",n=this.config.description?"avc"==o?"avcc":"hvcc":"annexb";null==(i=this.decoder)||i.setCodec(o,n,null!=(t=this.config.description)?t:""),null==(r=this.worker)||r.postMessage({type:"setCodec",codec:o,format:n,description:this.config.description})}decode(e){var t,i;null==(t=this.decoder)||t.decode(e.data,"key"==e.type,e.timestamp),"configured"===this.state&&(null==(i=this.worker)||i.postMessage({type:"decode",packet:e}))}flush(){}reset(){this.config=void 0,this.decoder&&this.decoder.clear()}close(){this.removeAllListeners(),this.decoder&&(this.decoder.clear(),this.decoder.delete())}videoInfo(e,t){this.width=e,this.height=t;let i={width:e,height:t};this.emit("videoCodecInfo",i)}yuvData(e,t){if(!this.module)return;let i=this.width*this.height,r=i>>2,o=this.module.HEAPU32[e>>2],n=this.module.HEAPU32[1+(e>>2)],a=this.module.HEAPU32[2+(e>>2)],s=this.module.HEAPU8.subarray(o,o+i),l=this.module.HEAPU8.subarray(n,n+r),c=this.module.HEAPU8.subarray(a,a+r);if(this.yuvMode)return void this.emit("videoFrame",{y:s,u:l,v:c,timestamp:t});let d=new Uint8Array(i+r+r);d.set(s),d.set(l,i),d.set(c,i+r),this.emit("videoFrame",new VideoFrame(d,{codedWidth:this.width,codedHeight:this.height,format:"I420",timestamp:t}))}errorInfo(e){let t={errMsg:e};this.emit("error",t)}};PH([GH([KH.INIT,"closed"],"initialized")],JH.prototype,"initialize",1),PH([GH("initialized","configured",{sync:!0})],JH.prototype,"configure",1),PH([GH([],KH.INIT,{sync:!0})],JH.prototype,"reset",1),PH([GH([],"closed",{sync:!0})],JH.prototype,"close",1);var XH,QH=(XH="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0,function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t,i,r=e;r.ready=new Promise((e,r)=>{t=e,i=r});var o,n,a,s=Object.assign({},r),l="./this.program",c="object"==typeof window,d="function"==typeof importScripts,u=("object"==typeof process&&"object"==typeof process.versions&&process.versions.node,"");(c||d)&&(d?u=self.location.href:"undefined"!=typeof document&&document.currentScript&&(u=document.currentScript.src),XH&&(u=XH),u=0!==u.indexOf("blob:")?u.substr(0,u.replace(/[?#].*/,"").lastIndexOf("/")+1):"",o=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},d&&(a=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),n=(e,t,i)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):i()},r.onerror=i,r.send(null)});var h,p,m=r.print||console.log.bind(console),f=r.printErr||console.error.bind(console);Object.assign(r,s),s=null,r.arguments&&r.arguments,r.thisProgram&&(l=r.thisProgram),r.quit&&r.quit,r.wasmBinary&&(h=r.wasmBinary),r.noExitRuntime,"object"!=typeof WebAssembly&&F("no native wasm support detected");var _,g,E,v,y,T,I,A,S,R=!1,b=[],w=[],C=[];function D(e){b.unshift(e)}function N(e){C.unshift(e)}var k,O,M,P,L=0,x=null;function U(e){L++,r.monitorRunDependencies&&r.monitorRunDependencies(L)}function V(e){if(L--,r.monitorRunDependencies&&r.monitorRunDependencies(L),0==L&&x){var t=x;x=null,t()}}function F(e){r.onAbort&&r.onAbort(e),f(e="Aborted("+e+")"),R=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw i(t),t}function B(e){return e.startsWith("data:application/octet-stream;base64,")}function H(e){if(e==k&&h)return new Uint8Array(h);if(a)return a(e);throw"both async and sync fetching of the wasm failed"}function W(e,t,i){return(r=e,h||!c&&!d||"function"!=typeof fetch?Promise.resolve().then(()=>H(r)):fetch(r,{credentials:"same-origin"}).then(e=>{if(!e.ok)throw"failed to load wasm binary file at '"+r+"'";return e.arrayBuffer()}).catch(()=>H(r))).then(e=>WebAssembly.instantiate(e,t)).then(e=>e).then(i,e=>{f("failed to asynchronously prepare wasm: "+e),F(e)});var r}B(k="videodec.wasm")||(O=k,k=r.locateFile?r.locateFile(O,u):u+O);var G=e=>{for(;e.length>0;)e.shift()(r)};function j(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){T[this.ptr+4>>2]=e},this.get_type=function(){return T[this.ptr+4>>2]},this.set_destructor=function(e){T[this.ptr+8>>2]=e},this.get_destructor=function(){return T[this.ptr+8>>2]},this.set_caught=function(e){e=e?1:0,_[this.ptr+12|0]=e},this.get_caught=function(){return 0!=_[this.ptr+12|0]},this.set_rethrown=function(e){e=e?1:0,_[this.ptr+13|0]=e},this.get_rethrown=function(){return 0!=_[this.ptr+13|0]},this.init=function(e,t){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(t)},this.set_adjusted_ptr=function(e){T[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return T[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Ct(this.get_type()))return T[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var z={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var i=0,r=e.length-1;r>=0;r--){var o=e[r];"."===o?e.splice(r,1):".."===o?(e.splice(r,1),i++):i&&(e.splice(r,1),i--)}if(t)for(;i;i--)e.unshift("..");return e},normalize:e=>{var t=z.isAbs(e),i="/"===e.substr(-1);return(e=z.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||t||(e="."),e&&i&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=z.splitPath(e),i=t[0],r=t[1];return i||r?(r&&(r=r.substr(0,r.length-1)),i+r):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=z.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return z.normalize(e.join("/"))},join2:(e,t)=>z.normalize(e+"/"+t)},K=e=>(K=(()=>{if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues)return e=>crypto.getRandomValues(e);F("initRandomDevice")})())(e),q={resolve:function(){for(var e="",t=!1,i=arguments.length-1;i>=-1&&!t;i--){var r=i>=0?arguments[i]:ne.cwd();if("string"!=typeof r)throw new TypeError("Arguments to path.resolve must be strings");if(!r)return"";e=r+"/"+e,t=z.isAbs(r)}return(t?"/":"")+(e=z.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||"."},relative:(e,t)=>{function i(e){for(var t=0;t<e.length&&""===e[t];t++);for(var i=e.length-1;i>=0&&""===e[i];i--);return t>i?[]:e.slice(t,i-t+1)}e=q.resolve(e).substr(1),t=q.resolve(t).substr(1);for(var r=i(e.split("/")),o=i(t.split("/")),n=Math.min(r.length,o.length),a=n,s=0;s<n;s++)if(r[s]!==o[s]){a=s;break}var l=[];for(s=a;s<r.length;s++)l.push("..");return(l=l.concat(o.slice(a))).join("/")}},Y="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,J=(e,t,i)=>{for(var r=t+i,o=t;e[o]&&!(o>=r);)++o;if(o-t>16&&e.buffer&&Y)return Y.decode(e.subarray(t,o));for(var n="";t<o;){var a=e[t++];if(128&a){var s=63&e[t++];if(192!=(224&a)){var l=63&e[t++];if((a=224==(240&a)?(15&a)<<12|s<<6|l:(7&a)<<18|s<<12|l<<6|63&e[t++])<65536)n+=String.fromCharCode(a);else{var c=a-65536;n+=String.fromCharCode(55296|c>>10,56320|1023&c)}}else n+=String.fromCharCode((31&a)<<6|s)}else n+=String.fromCharCode(a)}return n},X=[],Q=e=>{for(var t=0,i=0;i<e.length;++i){var r=e.charCodeAt(i);r<=127?t++:r<=2047?t+=2:r>=55296&&r<=57343?(t+=4,++i):t+=3}return t},$=(e,t,i,r)=>{if(!(r>0))return 0;for(var o=i,n=i+r-1,a=0;a<e.length;++a){var s=e.charCodeAt(a);if(s>=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++a)),s<=127){if(i>=n)break;t[i++]=s}else if(s<=2047){if(i+1>=n)break;t[i++]=192|s>>6,t[i++]=128|63&s}else if(s<=65535){if(i+2>=n)break;t[i++]=224|s>>12,t[i++]=128|s>>6&63,t[i++]=128|63&s}else{if(i+3>=n)break;t[i++]=240|s>>18,t[i++]=128|s>>12&63,t[i++]=128|s>>6&63,t[i++]=128|63&s}}return t[i]=0,i-o};function Z(e,t,i){var r=i>0?i:Q(e)+1,o=new Array(r),n=$(e,o,0,o.length);return t&&(o.length=n),o}var ee={ttys:[],init:function(){},shutdown:function(){},register:function(e,t){ee.ttys[e]={input:[],output:[],ops:t},ne.registerDevice(e,ee.stream_ops)},stream_ops:{open:function(e){var t=ee.ttys[e.node.rdev];if(!t)throw new ne.ErrnoError(43);e.tty=t,e.seekable=!1},close:function(e){e.tty.ops.fsync(e.tty)},fsync:function(e){e.tty.ops.fsync(e.tty)},read:function(e,t,i,r,o){if(!e.tty||!e.tty.ops.get_char)throw new ne.ErrnoError(60);for(var n=0,a=0;a<r;a++){var s;try{s=e.tty.ops.get_char(e.tty)}catch(l){throw new ne.ErrnoError(29)}if(void 0===s&&0===n)throw new ne.ErrnoError(6);if(null==s)break;n++,t[i+a]=s}return n&&(e.node.timestamp=Date.now()),n},write:function(e,t,i,r,o){if(!e.tty||!e.tty.ops.put_char)throw new ne.ErrnoError(60);try{for(var n=0;n<r;n++)e.tty.ops.put_char(e.tty,t[i+n])}catch(a){throw new ne.ErrnoError(29)}return r&&(e.node.timestamp=Date.now()),n}},default_tty_ops:{get_char:function(e){return(()=>{if(!X.length){var e=null;if("undefined"!=typeof window&&"function"==typeof window.prompt?null!==(e=window.prompt("Input: "))&&(e+="\n"):"function"==typeof readline&&null!==(e=readline())&&(e+="\n"),!e)return null;X=Z(e,!0)}return X.shift()})()},put_char:function(e,t){null===t||10===t?(m(J(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync:function(e){e.output&&e.output.length>0&&(m(J(e.output,0)),e.output=[])},ioctl_tcgets:function(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(e,t,i){return 0},ioctl_tiocgwinsz:function(e){return[24,80]}},default_tty1_ops:{put_char:function(e,t){null===t||10===t?(f(J(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync:function(e){e.output&&e.output.length>0&&(f(J(e.output,0)),e.output=[])}}},te=e=>{F()},ie={ops_table:null,mount:e=>ie.createNode(null,"/",16895,0),createNode(e,t,i,r){if(ne.isBlkdev(i)||ne.isFIFO(i))throw new ne.ErrnoError(63);ie.ops_table||(ie.ops_table={dir:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr,lookup:ie.node_ops.lookup,mknod:ie.node_ops.mknod,rename:ie.node_ops.rename,unlink:ie.node_ops.unlink,rmdir:ie.node_ops.rmdir,readdir:ie.node_ops.readdir,symlink:ie.node_ops.symlink},stream:{llseek:ie.stream_ops.llseek}},file:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr},stream:{llseek:ie.stream_ops.llseek,read:ie.stream_ops.read,write:ie.stream_ops.write,allocate:ie.stream_ops.allocate,mmap:ie.stream_ops.mmap,msync:ie.stream_ops.msync}},link:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr,readlink:ie.node_ops.readlink},stream:{}},chrdev:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr},stream:ne.chrdev_stream_ops}});var o=ne.createNode(e,t,i,r);return ne.isDir(o.mode)?(o.node_ops=ie.ops_table.dir.node,o.stream_ops=ie.ops_table.dir.stream,o.contents={}):ne.isFile(o.mode)?(o.node_ops=ie.ops_table.file.node,o.stream_ops=ie.ops_table.file.stream,o.usedBytes=0,o.contents=null):ne.isLink(o.mode)?(o.node_ops=ie.ops_table.link.node,o.stream_ops=ie.ops_table.link.stream):ne.isChrdev(o.mode)&&(o.node_ops=ie.ops_table.chrdev.node,o.stream_ops=ie.ops_table.chrdev.stream),o.timestamp=Date.now(),e&&(e.contents[t]=o,e.timestamp=o.timestamp),o},getFileDataAsTypedArray:e=>e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0),expandFileStorage(e,t){var i=e.contents?e.contents.length:0;if(!(i>=t)){t=Math.max(t,i*(i<1048576?2:1.125)>>>0),0!=i&&(t=Math.max(t,256));var r=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(r.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var i=e.contents;e.contents=new Uint8Array(t),i&&e.contents.set(i.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr(e){var t={};return t.dev=ne.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,ne.isDir(e.mode)?t.size=4096:ne.isFile(e.mode)?t.size=e.usedBytes:ne.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&ie.resizeFileStorage(e,t.size)},lookup(e,t){throw ne.genericErrors[44]},mknod:(e,t,i,r)=>ie.createNode(e,t,i,r),rename(e,t,i){if(ne.isDir(e.mode)){var r;try{r=ne.lookupNode(t,i)}catch(n){}if(r)for(var o in r.contents)throw new ne.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=i,t.contents[i]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){var i=ne.lookupNode(e,t);for(var r in i.contents)throw new ne.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[".",".."];for(var i in e.contents)e.contents.hasOwnProperty(i)&&t.push(i);return t},symlink(e,t,i){var r=ie.createNode(e,t,41471,0);return r.link=i,r},readlink(e){if(!ne.isLink(e.mode))throw new ne.ErrnoError(28);return e.link}},stream_ops:{read(e,t,i,r,o){var n=e.node.contents;if(o>=e.node.usedBytes)return 0;var a=Math.min(e.node.usedBytes-o,r);if(a>8&&n.subarray)t.set(n.subarray(o,o+a),i);else for(var s=0;s<a;s++)t[i+s]=n[o+s];return a},write(e,t,i,r,o,n){if(!r)return 0;var a=e.node;if(a.timestamp=Date.now(),t.subarray&&(!a.contents||a.contents.subarray)){if(n)return a.contents=t.subarray(i,i+r),a.usedBytes=r,r;if(0===a.usedBytes&&0===o)return a.contents=t.slice(i,i+r),a.usedBytes=r,r;if(o+r<=a.usedBytes)return a.contents.set(t.subarray(i,i+r),o),r}if(ie.expandFileStorage(a,o+r),a.contents.subarray&&t.subarray)a.contents.set(t.subarray(i,i+r),o);else for(var s=0;s<r;s++)a.contents[o+s]=t[i+s];return a.usedBytes=Math.max(a.usedBytes,o+r),r},llseek(e,t,i){var r=t;if(1===i?r+=e.position:2===i&&ne.isFile(e.node.mode)&&(r+=e.node.usedBytes),r<0)throw new ne.ErrnoError(28);return r},allocate(e,t,i){ie.expandFileStorage(e.node,t+i),e.node.usedBytes=Math.max(e.node.usedBytes,t+i)},mmap(e,t,i,r,o){if(!ne.isFile(e.node.mode))throw new ne.ErrnoError(43);var n,a,s=e.node.contents;if(2&o||s.buffer!==_.buffer){if((i>0||i+t<s.length)&&(s=s.subarray?s.subarray(i,i+t):Array.prototype.slice.call(s,i,i+t)),a=!0,!(n=te()))throw new ne.ErrnoError(48);_.set(s,n)}else a=!1,n=s.byteOffset;return{ptr:n,allocated:a}},msync:(e,t,i,r,o)=>(ie.stream_ops.write(e,t,0,r,i,!1),0)}},re=r.preloadPlugins||[];function oe(e,t){var i=0;return e&&(i|=365),t&&(i|=146),i}var ne={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!(e=q.resolve(e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new ne.ErrnoError(32);for(var i=e.split("/").filter(e=>!!e),r=ne.root,o="/",n=0;n<i.length;n++){var a=n===i.length-1;if(a&&t.parent)break;if(r=ne.lookupNode(r,i[n]),o=z.join2(o,i[n]),ne.isMountpoint(r)&&(!a||a&&t.follow_mount)&&(r=r.mounted.root),!a||t.follow)for(var s=0;ne.isLink(r.mode);){var l=ne.readlink(o);if(o=q.resolve(z.dirname(o),l),r=ne.lookupPath(o,{recurse_count:t.recurse_count+1}).node,s++>40)throw new ne.ErrnoError(32)}}return{path:o,node:r}},getPath:e=>{for(var t;;){if(ne.isRoot(e)){var i=e.mount.mountpoint;return t?"/"!==i[i.length-1]?"".concat(i,"/").concat(t):i+t:i}t=t?"".concat(e.name,"/").concat(t):e.name,e=e.parent}},hashName:(e,t)=>{for(var i=0,r=0;r<t.length;r++)i=(i<<5)-i+t.charCodeAt(r)|0;return(e+i>>>0)%ne.nameTable.length},hashAddNode:e=>{var t=ne.hashName(e.parent.id,e.name);e.name_next=ne.nameTable[t],ne.nameTable[t]=e},hashRemoveNode:e=>{var t=ne.hashName(e.parent.id,e.name);if(ne.nameTable[t]===e)ne.nameTable[t]=e.name_next;else for(var i=ne.nameTable[t];i;){if(i.name_next===e){i.name_next=e.name_next;break}i=i.name_next}},lookupNode:(e,t)=>{var i=ne.mayLookup(e);if(i)throw new ne.ErrnoError(i,e);for(var r=ne.hashName(e.id,t),o=ne.nameTable[r];o;o=o.name_next){var n=o.name;if(o.parent.id===e.id&&n===t)return o}return ne.lookup(e,t)},createNode:(e,t,i,r)=>{var o=new ne.FSNode(e,t,i,r);return ne.hashAddNode(o),o},destroyNode:e=>{ne.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>!(49152&~e),flagsToPermissionString:e=>{var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>ne.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup:e=>ne.nodePermissions(e,"x")||(e.node_ops.lookup?0:2),mayCreate:(e,t)=>{try{return ne.lookupNode(e,t),20}catch(i){}return ne.nodePermissions(e,"wx")},mayDelete:(e,t,i)=>{var r;try{r=ne.lookupNode(e,t)}catch(n){return n.errno}var o=ne.nodePermissions(e,"wx");if(o)return o;if(i){if(!ne.isDir(r.mode))return 54;if(ne.isRoot(r)||ne.getPath(r)===ne.cwd())return 10}else if(ne.isDir(r.mode))return 31;return 0},mayOpen:(e,t)=>e?ne.isLink(e.mode)?32:ne.isDir(e.mode)&&("r"!==ne.flagsToPermissionString(t)||512&t)?31:ne.nodePermissions(e,ne.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd:()=>{for(var e=0;e<=ne.MAX_OPEN_FDS;e++)if(!ne.streams[e])return e;throw new ne.ErrnoError(33)},getStreamChecked:e=>{var t=ne.getStream(e);if(!t)throw new ne.ErrnoError(8);return t},getStream:e=>ne.streams[e],createStream:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return ne.FSStream||(ne.FSStream=function(){this.shared={}},ne.FSStream.prototype={},Object.defineProperties(ne.FSStream.prototype,{object:{get(){return this.node},set(e){this.node=e}},isRead:{get(){return 1!=(2097155&this.flags)}},isWrite:{get(){return!!(2097155&this.flags)}},isAppend:{get(){return 1024&this.flags}},flags:{get(){return this.shared.flags},set(e){this.shared.flags=e}},position:{get(){return this.shared.position},set(e){this.shared.position=e}}})),e=Object.assign(new ne.FSStream,e),-1==t&&(t=ne.nextfd()),e.fd=t,ne.streams[t]=e,e},closeStream:e=>{ne.streams[e]=null},chrdev_stream_ops:{open:e=>{var t=ne.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:()=>{throw new ne.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice:(e,t)=>{ne.devices[e]={stream_ops:t}},getDevice:e=>ne.devices[e],getMounts:e=>{for(var t=[],i=[e];i.length;){var r=i.pop();t.push(r),i.push.apply(i,r.mounts)}return t},syncfs:(e,t)=>{"function"==typeof e&&(t=e,e=!1),ne.syncFSRequests++,ne.syncFSRequests>1&&f("warning: ".concat(ne.syncFSRequests," FS.syncfs operations in flight at once, probably just doing extra work"));var i=ne.getMounts(ne.root.mount),r=0;function o(e){return ne.syncFSRequests--,t(e)}function n(e){if(e)return n.errored?void 0:(n.errored=!0,o(e));++r>=i.length&&o(null)}i.forEach(t=>{if(!t.type.syncfs)return n(null);t.type.syncfs(t,e,n)})},mount:(e,t,i)=>{var r,o="/"===i,n=!i;if(o&&ne.root)throw new ne.ErrnoError(10);if(!o&&!n){var a=ne.lookupPath(i,{follow_mount:!1});if(i=a.path,r=a.node,ne.isMountpoint(r))throw new ne.ErrnoError(10);if(!ne.isDir(r.mode))throw new ne.ErrnoError(54)}var s={type:e,opts:t,mountpoint:i,mounts:[]},l=e.mount(s);return l.mount=s,s.root=l,o?ne.root=l:r&&(r.mounted=s,r.mount&&r.mount.mounts.push(s)),l},unmount:e=>{var t=ne.lookupPath(e,{follow_mount:!1});if(!ne.isMountpoint(t.node))throw new ne.ErrnoError(28);var i=t.node,r=i.mounted,o=ne.getMounts(r);Object.keys(ne.nameTable).forEach(e=>{for(var t=ne.nameTable[e];t;){var i=t.name_next;o.includes(t.mount)&&ne.destroyNode(t),t=i}}),i.mounted=null;var n=i.mount.mounts.indexOf(r);i.mount.mounts.splice(n,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod:(e,t,i)=>{var r=ne.lookupPath(e,{parent:!0}).node,o=z.basename(e);if(!o||"."===o||".."===o)throw new ne.ErrnoError(28);var n=ne.mayCreate(r,o);if(n)throw new ne.ErrnoError(n);if(!r.node_ops.mknod)throw new ne.ErrnoError(63);return r.node_ops.mknod(r,o,t,i)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,ne.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,ne.mknod(e,t,0)),mkdirTree:(e,t)=>{for(var i=e.split("/"),r="",o=0;o<i.length;++o)if(i[o]){r+="/"+i[o];try{ne.mkdir(r,t)}catch(n){if(20!=n.errno)throw n}}},mkdev:(e,t,i)=>(void 0===i&&(i=t,t=438),t|=8192,ne.mknod(e,t,i)),symlink:(e,t)=>{if(!q.resolve(e))throw new ne.ErrnoError(44);var i=ne.lookupPath(t,{parent:!0}).node;if(!i)throw new ne.ErrnoError(44);var r=z.basename(t),o=ne.mayCreate(i,r);if(o)throw new ne.ErrnoError(o);if(!i.node_ops.symlink)throw new ne.ErrnoError(63);return i.node_ops.symlink(i,r,e)},rename:(e,t)=>{var i,r,o=z.dirname(e),n=z.dirname(t),a=z.basename(e),s=z.basename(t);if(i=ne.lookupPath(e,{parent:!0}).node,r=ne.lookupPath(t,{parent:!0}).node,!i||!r)throw new ne.ErrnoError(44);if(i.mount!==r.mount)throw new ne.ErrnoError(75);var l,c=ne.lookupNode(i,a),d=q.relative(e,n);if("."!==d.charAt(0))throw new ne.ErrnoError(28);if("."!==(d=q.relative(t,o)).charAt(0))throw new ne.ErrnoError(55);try{l=ne.lookupNode(r,s)}catch(p){}if(c!==l){var u=ne.isDir(c.mode),h=ne.mayDelete(i,a,u);if(h)throw new ne.ErrnoError(h);if(h=l?ne.mayDelete(r,s,u):ne.mayCreate(r,s))throw new ne.ErrnoError(h);if(!i.node_ops.rename)throw new ne.ErrnoError(63);if(ne.isMountpoint(c)||l&&ne.isMountpoint(l))throw new ne.ErrnoError(10);if(r!==i&&(h=ne.nodePermissions(i,"w")))throw new ne.ErrnoError(h);ne.hashRemoveNode(c);try{i.node_ops.rename(c,r,s)}catch(p){throw p}finally{ne.hashAddNode(c)}}},rmdir:e=>{var t=ne.lookupPath(e,{parent:!0}).node,i=z.basename(e),r=ne.lookupNode(t,i),o=ne.mayDelete(t,i,!0);if(o)throw new ne.ErrnoError(o);if(!t.node_ops.rmdir)throw new ne.ErrnoError(63);if(ne.isMountpoint(r))throw new ne.ErrnoError(10);t.node_ops.rmdir(t,i),ne.destroyNode(r)},readdir:e=>{var t=ne.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new ne.ErrnoError(54);return t.node_ops.readdir(t)},unlink:e=>{var t=ne.lookupPath(e,{parent:!0}).node;if(!t)throw new ne.ErrnoError(44);var i=z.basename(e),r=ne.lookupNode(t,i),o=ne.mayDelete(t,i,!1);if(o)throw new ne.ErrnoError(o);if(!t.node_ops.unlink)throw new ne.ErrnoError(63);if(ne.isMountpoint(r))throw new ne.ErrnoError(10);t.node_ops.unlink(t,i),ne.destroyNode(r)},readlink:e=>{var t=ne.lookupPath(e).node;if(!t)throw new ne.ErrnoError(44);if(!t.node_ops.readlink)throw new ne.ErrnoError(28);return q.resolve(ne.getPath(t.parent),t.node_ops.readlink(t))},stat:(e,t)=>{var i=ne.lookupPath(e,{follow:!t}).node;if(!i)throw new ne.ErrnoError(44);if(!i.node_ops.getattr)throw new ne.ErrnoError(63);return i.node_ops.getattr(i)},lstat:e=>ne.stat(e,!0),chmod:(e,t,i)=>{var r;if(!(r="string"==typeof e?ne.lookupPath(e,{follow:!i}).node:e).node_ops.setattr)throw new ne.ErrnoError(63);r.node_ops.setattr(r,{mode:4095&t|-4096&r.mode,timestamp:Date.now()})},lchmod:(e,t)=>{ne.chmod(e,t,!0)},fchmod:(e,t)=>{var i=ne.getStreamChecked(e);ne.chmod(i.node,t)},chown:(e,t,i,r)=>{var o;if(!(o="string"==typeof e?ne.lookupPath(e,{follow:!r}).node:e).node_ops.setattr)throw new ne.ErrnoError(63);o.node_ops.setattr(o,{timestamp:Date.now()})},lchown:(e,t,i)=>{ne.chown(e,t,i,!0)},fchown:(e,t,i)=>{var r=ne.getStreamChecked(e);ne.chown(r.node,t,i)},truncate:(e,t)=>{if(t<0)throw new ne.ErrnoError(28);var i;if(!(i="string"==typeof e?ne.lookupPath(e,{follow:!0}).node:e).node_ops.setattr)throw new ne.ErrnoError(63);if(ne.isDir(i.mode))throw new ne.ErrnoError(31);if(!ne.isFile(i.mode))throw new ne.ErrnoError(28);var r=ne.nodePermissions(i,"w");if(r)throw new ne.ErrnoError(r);i.node_ops.setattr(i,{size:t,timestamp:Date.now()})},ftruncate:(e,t)=>{var i=ne.getStreamChecked(e);if(!(2097155&i.flags))throw new ne.ErrnoError(28);ne.truncate(i.node,t)},utime:(e,t,i)=>{var r=ne.lookupPath(e,{follow:!0}).node;r.node_ops.setattr(r,{timestamp:Math.max(t,i)})},open:(e,t,i)=>{if(""===e)throw new ne.ErrnoError(44);var o;if(i=void 0===i?438:i,i=64&(t="string"==typeof t?function(e){var t={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[e];if(void 0===t)throw new Error("Unknown file open mode: ".concat(e));return t}(t):t)?4095&i|32768:0,"object"==typeof e)o=e;else{e=z.normalize(e);try{o=ne.lookupPath(e,{follow:!(131072&t)}).node}catch(l){}}var n=!1;if(64&t)if(o){if(128&t)throw new ne.ErrnoError(20)}else o=ne.mknod(e,i,0),n=!0;if(!o)throw new ne.ErrnoError(44);if(ne.isChrdev(o.mode)&&(t&=-513),65536&t&&!ne.isDir(o.mode))throw new ne.ErrnoError(54);if(!n){var a=ne.mayOpen(o,t);if(a)throw new ne.ErrnoError(a)}512&t&&!n&&ne.truncate(o,0),t&=-131713;var s=ne.createStream({node:o,path:ne.getPath(o),flags:t,seekable:!0,position:0,stream_ops:o.stream_ops,ungotten:[],error:!1});return s.stream_ops.open&&s.stream_ops.open(s),!r.logReadFiles||1&t||(ne.readFiles||(ne.readFiles={}),e in ne.readFiles||(ne.readFiles[e]=1)),s},close:e=>{if(ne.isClosed(e))throw new ne.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(t){throw t}finally{ne.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek:(e,t,i)=>{if(ne.isClosed(e))throw new ne.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new ne.ErrnoError(70);if(0!=i&&1!=i&&2!=i)throw new ne.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,i),e.ungotten=[],e.position},read:(e,t,i,r,o)=>{if(r<0||o<0)throw new ne.ErrnoError(28);if(ne.isClosed(e))throw new ne.ErrnoError(8);if(1==(2097155&e.flags))throw new ne.ErrnoError(8);if(ne.isDir(e.node.mode))throw new ne.ErrnoError(31);if(!e.stream_ops.read)throw new ne.ErrnoError(28);var n=void 0!==o;if(n){if(!e.seekable)throw new ne.ErrnoError(70)}else o=e.position;var a=e.stream_ops.read(e,t,i,r,o);return n||(e.position+=a),a},write:(e,t,i,r,o,n)=>{if(r<0||o<0)throw new ne.ErrnoError(28);if(ne.isClosed(e))throw new ne.ErrnoError(8);if(!(2097155&e.flags))throw new ne.ErrnoError(8);if(ne.isDir(e.node.mode))throw new ne.ErrnoError(31);if(!e.stream_ops.write)throw new ne.ErrnoError(28);e.seekable&&1024&e.flags&&ne.llseek(e,0,2);var a=void 0!==o;if(a){if(!e.seekable)throw new ne.ErrnoError(70)}else o=e.position;var s=e.stream_ops.write(e,t,i,r,o,n);return a||(e.position+=s),s},allocate:(e,t,i)=>{if(ne.isClosed(e))throw new ne.ErrnoError(8);if(t<0||i<=0)throw new ne.ErrnoError(28);if(!(2097155&e.flags))throw new ne.ErrnoError(8);if(!ne.isFile(e.node.mode)&&!ne.isDir(e.node.mode))throw new ne.ErrnoError(43);if(!e.stream_ops.allocate)throw new ne.ErrnoError(138);e.stream_ops.allocate(e,t,i)},mmap:(e,t,i,r,o)=>{if(2&r&&!(2&o)&&2!=(2097155&e.flags))throw new ne.ErrnoError(2);if(1==(2097155&e.flags))throw new ne.ErrnoError(2);if(!e.stream_ops.mmap)throw new ne.ErrnoError(43);return e.stream_ops.mmap(e,t,i,r,o)},msync:(e,t,i,r,o)=>e.stream_ops.msync?e.stream_ops.msync(e,t,i,r,o):0,munmap:e=>0,ioctl:(e,t,i)=>{if(!e.stream_ops.ioctl)throw new ne.ErrnoError(59);return e.stream_ops.ioctl(e,t,i)},readFile:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error('Invalid encoding type "'.concat(t.encoding,'"'));var i,r=ne.open(e,t.flags),o=ne.stat(e).size,n=new Uint8Array(o);return ne.read(r,n,0,o,0),"utf8"===t.encoding?i=J(n,0):"binary"===t.encoding&&(i=n),ne.close(r),i},writeFile:function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};i.flags=i.flags||577;var r=ne.open(e,i.flags,i.mode);if("string"==typeof t){var o=new Uint8Array(Q(t)+1),n=$(t,o,0,o.length);ne.write(r,o,0,n,void 0,i.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");ne.write(r,t,0,t.byteLength,void 0,i.canOwn)}ne.close(r)},cwd:()=>ne.currentPath,chdir:e=>{var t=ne.lookupPath(e,{follow:!0});if(null===t.node)throw new ne.ErrnoError(44);if(!ne.isDir(t.node.mode))throw new ne.ErrnoError(54);var i=ne.nodePermissions(t.node,"x");if(i)throw new ne.ErrnoError(i);ne.currentPath=t.path},createDefaultDirectories:()=>{ne.mkdir("/tmp"),ne.mkdir("/home"),ne.mkdir("/home/web_user")},createDefaultDevices:()=>{ne.mkdir("/dev"),ne.registerDevice(ne.makedev(1,3),{read:()=>0,write:(e,t,i,r,o)=>r}),ne.mkdev("/dev/null",ne.makedev(1,3)),ee.register(ne.makedev(5,0),ee.default_tty_ops),ee.register(ne.makedev(6,0),ee.default_tty1_ops),ne.mkdev("/dev/tty",ne.makedev(5,0)),ne.mkdev("/dev/tty1",ne.makedev(6,0));var e=new Uint8Array(1024),t=0,i=()=>(0===t&&(t=K(e).byteLength),e[--t]);ne.createDevice("/dev","random",i),ne.createDevice("/dev","urandom",i),ne.mkdir("/dev/shm"),ne.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{ne.mkdir("/proc");var e=ne.mkdir("/proc/self");ne.mkdir("/proc/self/fd"),ne.mount({mount:()=>{var t=ne.createNode(e,"fd",16895,73);return t.node_ops={lookup:(e,t)=>{var i=+t,r=ne.getStreamChecked(i),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>r.path}};return o.parent=o,o}},t}},{},"/proc/self/fd")},createStandardStreams:()=>{r.stdin?ne.createDevice("/dev","stdin",r.stdin):ne.symlink("/dev/tty","/dev/stdin"),r.stdout?ne.createDevice("/dev","stdout",null,r.stdout):ne.symlink("/dev/tty","/dev/stdout"),r.stderr?ne.createDevice("/dev","stderr",null,r.stderr):ne.symlink("/dev/tty1","/dev/stderr"),ne.open("/dev/stdin",0),ne.open("/dev/stdout",1),ne.open("/dev/stderr",1)},ensureErrnoError:()=>{ne.ErrnoError||(ne.ErrnoError=function(e,t){this.name="ErrnoError",this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},ne.ErrnoError.prototype=new Error,ne.ErrnoError.prototype.constructor=ne.ErrnoError,[44].forEach(e=>{ne.genericErrors[e]=new ne.ErrnoError(e),ne.genericErrors[e].stack="<generic error, no stack>"}))},staticInit:()=>{ne.ensureErrnoError(),ne.nameTable=new Array(4096),ne.mount(ie,{},"/"),ne.createDefaultDirectories(),ne.createDefaultDevices(),ne.createSpecialDirectories(),ne.filesystems={MEMFS:ie}},init:(e,t,i)=>{ne.init.initialized=!0,ne.ensureErrnoError(),r.stdin=e||r.stdin,r.stdout=t||r.stdout,r.stderr=i||r.stderr,ne.createStandardStreams()},quit:()=>{ne.init.initialized=!1;for(var e=0;e<ne.streams.length;e++){var t=ne.streams[e];t&&ne.close(t)}},findObject:(e,t)=>{var i=ne.analyzePath(e,t);return i.exists?i.object:null},analyzePath:(e,t)=>{try{e=(r=ne.lookupPath(e,{follow:!t})).path}catch(o){}var i={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var r=ne.lookupPath(e,{parent:!0});i.parentExists=!0,i.parentPath=r.path,i.parentObject=r.node,i.name=z.basename(e),r=ne.lookupPath(e,{follow:!t}),i.exists=!0,i.path=r.path,i.object=r.node,i.name=r.node.name,i.isRoot="/"===r.path}catch(o){i.error=o.errno}return i},createPath:(e,t,i,r)=>{e="string"==typeof e?e:ne.getPath(e);for(var o=t.split("/").reverse();o.length;){var n=o.pop();if(n){var a=z.join2(e,n);try{ne.mkdir(a)}catch(s){}e=a}}return a},createFile:(e,t,i,r,o)=>{var n=z.join2("string"==typeof e?e:ne.getPath(e),t),a=oe(r,o);return ne.create(n,a)},createDataFile:(e,t,i,r,o,n)=>{var a=t;e&&(e="string"==typeof e?e:ne.getPath(e),a=t?z.join2(e,t):e);var s=oe(r,o),l=ne.create(a,s);if(i){if("string"==typeof i){for(var c=new Array(i.length),d=0,u=i.length;d<u;++d)c[d]=i.charCodeAt(d);i=c}ne.chmod(l,146|s);var h=ne.open(l,577);ne.write(h,i,0,i.length,0,n),ne.close(h),ne.chmod(l,s)}return l},createDevice:(e,t,i,r)=>{var o=z.join2("string"==typeof e?e:ne.getPath(e),t),n=oe(!!i,!!r);ne.createDevice.major||(ne.createDevice.major=64);var a=ne.makedev(ne.createDevice.major++,0);return ne.registerDevice(a,{open:e=>{e.seekable=!1},close:e=>{r&&r.buffer&&r.buffer.length&&r(10)},read:(e,t,r,o,n)=>{for(var a=0,s=0;s<o;s++){var l;try{l=i()}catch(c){throw new ne.ErrnoError(29)}if(void 0===l&&0===a)throw new ne.ErrnoError(6);if(null==l)break;a++,t[r+s]=l}return a&&(e.node.timestamp=Date.now()),a},write:(e,t,i,o,n)=>{for(var a=0;a<o;a++)try{r(t[i+a])}catch(s){throw new ne.ErrnoError(29)}return o&&(e.node.timestamp=Date.now()),a}}),ne.mkdev(o,n,a)},forceLoadFile:e=>{if(e.isDevice||e.isFolder||e.link||e.contents)return!0;if("undefined"!=typeof XMLHttpRequest)throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");if(!o)throw new Error("Cannot load without read() or XMLHttpRequest.");try{e.contents=Z(o(e.url),!0),e.usedBytes=e.contents.length}catch(t){throw new ne.ErrnoError(29)}},createLazyFile:(e,t,i,r,o)=>{function n(){this.lengthKnown=!1,this.chunks=[]}if(n.prototype.get=function(e){if(!(e>this.length-1||e<0)){var t=e%this.chunkSize,i=e/this.chunkSize|0;return this.getter(i)[t]}},n.prototype.setDataGetter=function(e){this.getter=e},n.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",i,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+i+". Status: "+e.status);var t,r=Number(e.getResponseHeader("Content-length")),o=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,n=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,a=1048576;o||(a=r);var s=this;s.setDataGetter(e=>{var t=e*a,o=(e+1)*a-1;if(o=Math.min(o,r-1),void 0===s.chunks[e]&&(s.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>r-1)throw new Error("only "+r+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",i,!1),r!==a&&o.setRequestHeader("Range","bytes="+e+"-"+t),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+i+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):Z(o.responseText||"",!0)})(t,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]}),!n&&r||(a=r=1,r=this.getter(0).length,a=r,m("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=r,this._chunkSize=a,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!d)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var a=new n;Object.defineProperties(a,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var s={isDevice:!1,contents:a}}else s={isDevice:!1,url:i};var l=ne.createFile(e,t,s,r,o);s.contents?l.contents=s.contents:s.url&&(l.contents=null,l.url=s.url),Object.defineProperties(l,{usedBytes:{get:function(){return this.contents.length}}});var c={};function u(e,t,i,r,o){var n=e.node.contents;if(o>=n.length)return 0;var a=Math.min(n.length-o,r);if(n.slice)for(var s=0;s<a;s++)t[i+s]=n[o+s];else for(s=0;s<a;s++)t[i+s]=n.get(o+s);return a}return Object.keys(l.stream_ops).forEach(e=>{var t=l.stream_ops[e];c[e]=function(){return ne.forceLoadFile(l),t.apply(null,arguments)}}),c.read=(e,t,i,r,o)=>(ne.forceLoadFile(l),u(e,t,i,r,o)),c.mmap=(e,t,i,r,o)=>{ne.forceLoadFile(l);var n=te();if(!n)throw new ne.ErrnoError(48);return u(e,_,n,t,i),{ptr:n,allocated:!0}},l.stream_ops=c,l}},ae=(e,t)=>e?J(g,e,t):"",se={DEFAULT_POLLMASK:5,calculateAt:function(e,t,i){if(z.isAbs(t))return t;var r;if(r=-100===e?ne.cwd():se.getStreamFromFD(e).path,0==t.length){if(!i)throw new ne.ErrnoError(44);return r}return z.join2(r,t)},doStat:function(e,t,i){try{var r=e(t)}catch(s){if(s&&s.node&&z.normalize(t)!==z.normalize(ne.getPath(s.node)))return-54;throw s}y[i>>2]=r.dev,y[i+4>>2]=r.mode,T[i+8>>2]=r.nlink,y[i+12>>2]=r.uid,y[i+16>>2]=r.gid,y[i+20>>2]=r.rdev,P=[r.size>>>0,(M=r.size,+Math.abs(M)>=1?M>0?+Math.floor(M/4294967296)>>>0:~~+Math.ceil((M-+(~~M>>>0))/4294967296)>>>0:0)],y[i+24>>2]=P[0],y[i+28>>2]=P[1],y[i+32>>2]=4096,y[i+36>>2]=r.blocks;var o=r.atime.getTime(),n=r.mtime.getTime(),a=r.ctime.getTime();return P=[Math.floor(o/1e3)>>>0,(M=Math.floor(o/1e3),+Math.abs(M)>=1?M>0?+Math.floor(M/4294967296)>>>0:~~+Math.ceil((M-+(~~M>>>0))/4294967296)>>>0:0)],y[i+40>>2]=P[0],y[i+44>>2]=P[1],T[i+48>>2]=o%1e3*1e3,P=[Math.floor(n/1e3)>>>0,(M=Math.floor(n/1e3),+Math.abs(M)>=1?M>0?+Math.floor(M/4294967296)>>>0:~~+Math.ceil((M-+(~~M>>>0))/4294967296)>>>0:0)],y[i+56>>2]=P[0],y[i+60>>2]=P[1],T[i+64>>2]=n%1e3*1e3,P=[Math.floor(a/1e3)>>>0,(M=Math.floor(a/1e3),+Math.abs(M)>=1?M>0?+Math.floor(M/4294967296)>>>0:~~+Math.ceil((M-+(~~M>>>0))/4294967296)>>>0:0)],y[i+72>>2]=P[0],y[i+76>>2]=P[1],T[i+80>>2]=a%1e3*1e3,P=[r.ino>>>0,(M=r.ino,+Math.abs(M)>=1?M>0?+Math.floor(M/4294967296)>>>0:~~+Math.ceil((M-+(~~M>>>0))/4294967296)>>>0:0)],y[i+88>>2]=P[0],y[i+92>>2]=P[1],0},doMsync:function(e,t,i,r,o){if(!ne.isFile(t.node.mode))throw new ne.ErrnoError(43);if(2&r)return 0;var n=g.slice(e,e+i);ne.msync(t,n,o,i,r)},varargs:void 0,get:()=>(se.varargs+=4,y[se.varargs-4>>2]),getStr:e=>ae(e),getStreamFromFD:function(e){return ne.getStreamChecked(e)}};function le(e){switch(e){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: ".concat(e))}}var ce=void 0;function de(e){for(var t="",i=e;g[i];)t+=ce[g[i++]];return t}var ue={},he={},pe={},me=void 0;function fe(e){throw new me(e)}var _e=void 0;function ge(e){throw new _e(e)}function Ee(e,t,i){function r(t){var r=i(t);r.length!==e.length&&ge("Mismatched type converter count");for(var o=0;o<e.length;++o)ve(e[o],r[o])}e.forEach(function(e){pe[e]=t});var o=new Array(t.length),n=[],a=0;t.forEach((e,t)=>{he.hasOwnProperty(e)?o[t]=he[e]:(n.push(e),ue.hasOwnProperty(e)||(ue[e]=[]),ue[e].push(()=>{o[t]=he[e],++a===n.length&&r(o)}))}),0===n.length&&r(o)}function ve(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!("argPackAdvance"in t))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var r=t.name;if(e||fe('type "'.concat(r,'" must have a positive integer typeid pointer')),he.hasOwnProperty(e)){if(i.ignoreDuplicateRegistrations)return;fe("Cannot register type '".concat(r,"' twice"))}if(he[e]=t,delete pe[e],ue.hasOwnProperty(e)){var o=ue[e];delete ue[e],o.forEach(e=>e())}}(e,t,i)}function ye(e){fe(e.$$.ptrType.registeredClass.name+" instance already deleted")}var Te=!1;function Ie(e){}function Ae(e){var t;e.count.value-=1,0===e.count.value&&((t=e).smartPtr?t.smartPtrType.rawDestructor(t.smartPtr):t.ptrType.registeredClass.rawDestructor(t.ptr))}function Se(e,t,i){if(t===i)return e;if(void 0===i.baseClass)return null;var r=Se(e,t,i.baseClass);return null===r?null:i.downcast(r)}var Re={},be=[];function we(){for(;be.length;){var e=be.pop();e.$$.deleteScheduled=!1,e.delete()}}var Ce=void 0,De={};function Ne(e,t){return t.ptrType&&t.ptr||ge("makeClassHandle requires ptr and ptrType"),!!t.smartPtrType!=!!t.smartPtr&&ge("Both smartPtrType and smartPtr must be specified"),t.count={value:1},ke(Object.create(e,{$$:{value:t}}))}var ke=function(e){return"undefined"==typeof FinalizationRegistry?(ke=e=>e,e):(Te=new FinalizationRegistry(e=>{Ae(e.$$)}),Ie=e=>Te.unregister(e),(ke=e=>{var t=e.$$;if(t.smartPtr){var i={$$:t};Te.register(e,i,e)}return e})(e))};function Oe(){}function Me(e){if(void 0===e)return"_unknown";var t=(e=e.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return t>=48&&t<=57?"_".concat(e):e}function Pe(e,t){return e=Me(e),{[e]:function(){return t.apply(this,arguments)}}[e]}function Le(e,t,i){if(void 0===e[t].overloadTable){var r=e[t];e[t]=function(){return e[t].overloadTable.hasOwnProperty(arguments.length)||fe("Function '".concat(i,"' called with an invalid number of arguments (").concat(arguments.length,") - expects one of (").concat(e[t].overloadTable,")!")),e[t].overloadTable[arguments.length].apply(this,arguments)},e[t].overloadTable=[],e[t].overloadTable[r.argCount]=r}}function xe(e,t,i,r,o,n,a,s){this.name=e,this.constructor=t,this.instancePrototype=i,this.rawDestructor=r,this.baseClass=o,this.getActualType=n,this.upcast=a,this.downcast=s,this.pureVirtualFunctions=[]}function Ue(e,t,i){for(;t!==i;)t.upcast||fe("Expected null or instance of ".concat(i.name,", got an instance of ").concat(t.name)),e=t.upcast(e),t=t.baseClass;return e}function Ve(e,t){if(null===t)return this.isReference&&fe("null is not a valid ".concat(this.name)),0;t.$$||fe('Cannot pass "'.concat(rt(t),'" as a ').concat(this.name)),t.$$.ptr||fe("Cannot pass deleted object as a pointer of type ".concat(this.name));var i=t.$$.ptrType.registeredClass;return Ue(t.$$.ptr,i,this.registeredClass)}function Fe(e,t){var i;if(null===t)return this.isReference&&fe("null is not a valid ".concat(this.name)),this.isSmartPointer?(i=this.rawConstructor(),null!==e&&e.push(this.rawDestructor,i),i):0;t.$$||fe('Cannot pass "'.concat(rt(t),'" as a ').concat(this.name)),t.$$.ptr||fe("Cannot pass deleted object as a pointer of type ".concat(this.name)),!this.isConst&&t.$$.ptrType.isConst&&fe("Cannot convert argument of type ".concat(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name," to parameter type ").concat(this.name));var r=t.$$.ptrType.registeredClass;if(i=Ue(t.$$.ptr,r,this.registeredClass),this.isSmartPointer)switch(void 0===t.$$.smartPtr&&fe("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:t.$$.smartPtrType===this?i=t.$$.smartPtr:fe("Cannot convert argument of type ".concat(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name," to parameter type ").concat(this.name));break;case 1:i=t.$$.smartPtr;break;case 2:if(t.$$.smartPtrType===this)i=t.$$.smartPtr;else{var o=t.clone();i=this.rawShare(i,it.toHandle(function(){o.delete()})),null!==e&&e.push(this.rawDestructor,i)}break;default:fe("Unsupporting sharing policy")}return i}function Be(e,t){if(null===t)return this.isReference&&fe("null is not a valid ".concat(this.name)),0;t.$$||fe('Cannot pass "'.concat(rt(t),'" as a ').concat(this.name)),t.$$.ptr||fe("Cannot pass deleted object as a pointer of type ".concat(this.name)),t.$$.ptrType.isConst&&fe("Cannot convert argument of type ".concat(t.$$.ptrType.name," to parameter type ").concat(this.name));var i=t.$$.ptrType.registeredClass;return Ue(t.$$.ptr,i,this.registeredClass)}function He(e){return this.fromWireType(y[e>>2])}function We(e,t,i,r,o,n,a,s,l,c,d){this.name=e,this.registeredClass=t,this.isReference=i,this.isConst=r,this.isSmartPointer=o,this.pointeeType=n,this.sharingPolicy=a,this.rawGetPointee=s,this.rawConstructor=l,this.rawShare=c,this.rawDestructor=d,o||void 0!==t.baseClass?this.toWireType=Fe:r?(this.toWireType=Ve,this.destructorFunction=null):(this.toWireType=Be,this.destructorFunction=null)}var Ge=[],je=e=>{var t=Ge[e];return t||(e>=Ge.length&&(Ge.length=e+1),Ge[e]=t=S.get(e)),t};function ze(e,t){var i,o,n,a=(e=de(e)).includes("j")?(i=e,o=t,n=[],function(){return n.length=0,Object.assign(n,arguments),((e,t,i)=>{return e.includes("j")?(o=t,n=i,a=r["dynCall_"+e],n&&n.length?a.apply(null,[o].concat(n)):a.call(null,o)):je(t).apply(null,i);var o,n,a})(i,o,n)}):je(t);return"function"!=typeof a&&fe("unknown function pointer with signature ".concat(e,": ").concat(t)),a}var Ke=void 0;function qe(e){var t=wt(e),i=de(t);return Rt(t),i}function Ye(e,t){var i=[],r={};throw t.forEach(function e(t){r[t]||he[t]||(pe[t]?pe[t].forEach(e):(i.push(t),r[t]=!0))}),new Ke("".concat(e,": ")+i.map(qe).join([", "]))}function Je(e,t){for(var i=[],r=0;r<e;r++)i.push(T[t+4*r>>2]);return i}function Xe(e){for(;e.length;){var t=e.pop();e.pop()(t)}}function Qe(e,t){if(!(e instanceof Function))throw new TypeError("new_ called with constructor type ".concat(typeof e," which is not a function"));var i=Pe(e.name||"unknownFunctionName",function(){});i.prototype=e.prototype;var r=new i,o=e.apply(r,t);return o instanceof Object?o:r}function $e(e,t,i,r,o,n){var a=t.length;a<2&&fe("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var s=null!==t[1]&&null!==i,l=!1,c=1;c<t.length;++c)if(null!==t[c]&&void 0===t[c].destructorFunction){l=!0;break}var d="void"!==t[0].name,u="",h="";for(c=0;c<a-2;++c)u+=(0!==c?", ":"")+"arg"+c,h+=(0!==c?", ":"")+"arg"+c+"Wired";var p="\n return function ".concat(Me(e),"(").concat(u,") {\n if (arguments.length !== ").concat(a-2,") {\n throwBindingError('function ").concat(e," called with ").concat(arguments.length," arguments, expected ").concat(a-2," args!');\n }");l&&(p+="var destructors = [];\n");var m=l?"destructors":"null",f=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],_=[fe,r,o,Xe,t[0],t[1]];for(s&&(p+="var thisWired = classParam.toWireType("+m+", this);\n"),c=0;c<a-2;++c)p+="var arg"+c+"Wired = argType"+c+".toWireType("+m+", arg"+c+"); // "+t[c+2].name+"\n",f.push("argType"+c),_.push(t[c+2]);if(s&&(h="thisWired"+(h.length>0?", ":"")+h),p+=(d||n?"var rv = ":"")+"invoker(fn"+(h.length>0?", ":"")+h+");\n",l)p+="runDestructors(destructors);\n";else for(c=s?1:2;c<t.length;++c){var g=1===c?"thisWired":"arg"+(c-2)+"Wired";null!==t[c].destructorFunction&&(p+=g+"_dtor("+g+"); // "+t[c].name+"\n",f.push(g+"_dtor"),_.push(t[c].destructorFunction))}return d&&(p+="var ret = retType.fromWireType(rv);\nreturn ret;\n"),p+="}\n",f.push(p),Qe(Function,f).apply(null,_)}function Ze(){this.allocated=[void 0],this.freelist=[]}var et=new Ze;function tt(e){e>=et.reserved&&0===--et.get(e).refcount&&et.free(e)}var it={toValue:e=>(e||fe("Cannot use deleted val. handle = "+e),et.get(e).value),toHandle:e=>{switch(e){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return et.allocate({refcount:1,value:e})}}};function rt(e){if(null===e)return"null";var t=typeof e;return"object"===t||"array"===t||"function"===t?e.toString():""+e}function ot(e,t){switch(t){case 2:return function(e){return this.fromWireType(I[e>>2])};case 3:return function(e){return this.fromWireType(A[e>>3])};default:throw new TypeError("Unknown float type: "+e)}}function nt(e,t,i){switch(t){case 0:return i?function(e){return _[e]}:function(e){return g[e]};case 1:return i?function(e){return E[e>>1]}:function(e){return v[e>>1]};case 2:return i?function(e){return y[e>>2]}:function(e){return T[e>>2]};default:throw new TypeError("Unknown integer type: "+e)}}var at="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0,st=(e,t)=>{for(var i=e,r=i>>1,o=r+t/2;!(r>=o)&&v[r];)++r;if((i=r<<1)-e>32&&at)return at.decode(g.subarray(e,i));for(var n="",a=0;!(a>=t/2);++a){var s=E[e+2*a>>1];if(0==s)break;n+=String.fromCharCode(s)}return n},lt=(e,t,i)=>{if(void 0===i&&(i=2147483647),i<2)return 0;for(var r=t,o=(i-=2)<2*e.length?i/2:e.length,n=0;n<o;++n){var a=e.charCodeAt(n);E[t>>1]=a,t+=2}return E[t>>1]=0,t-r},ct=e=>2*e.length,dt=(e,t)=>{for(var i=0,r="";!(i>=t/4);){var o=y[e+4*i>>2];if(0==o)break;if(++i,o>=65536){var n=o-65536;r+=String.fromCharCode(55296|n>>10,56320|1023&n)}else r+=String.fromCharCode(o)}return r},ut=(e,t,i)=>{if(void 0===i&&(i=2147483647),i<4)return 0;for(var r=t,o=r+i-4,n=0;n<e.length;++n){var a=e.charCodeAt(n);if(a>=55296&&a<=57343&&(a=65536+((1023&a)<<10)|1023&e.charCodeAt(++n)),y[t>>2]=a,(t+=4)+4>o)break}return y[t>>2]=0,t-r},ht=e=>{for(var t=0,i=0;i<e.length;++i){var r=e.charCodeAt(i);r>=55296&&r<=57343&&++i,t+=4}return t},pt={},mt=[];function ft(e,t){var i=he[e];return void 0===i&&fe(t+" has unknown type "+qe(e)),i}var _t,gt,Et=[],vt={},yt=()=>{if(!yt.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:l||"./this.program"};for(var t in vt)void 0===vt[t]?delete e[t]:e[t]=vt[t];var i=[];for(var t in e)i.push("".concat(t,"=").concat(e[t]));yt.strings=i}return yt.strings},Tt=function(e,t,i,r){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=ne.nextInode++,this.name=t,this.mode=i,this.node_ops={},this.stream_ops={},this.rdev=r};Object.defineProperties(Tt.prototype,{read:{get:function(){return!(365&~this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return!(146&~this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}},isFolder:{get:function(){return ne.isDir(this.mode)}},isDevice:{get:function(){return ne.isChrdev(this.mode)}}}),ne.FSNode=Tt,ne.createPreloadedFile=function(e,t,i,r,o,a,s,l,c,d){var u=t?q.resolve(z.join2(e,t)):e;function h(i){function n(i){d&&d(),l||ne.createDataFile(e,t,i,r,o,c),a&&a(),V()}(function(e,t,i,r){"undefined"!=typeof Browser&&Browser.init();var o=!1;return re.forEach(function(n){o||n.canHandle(t)&&(n.handle(e,t,i,r),o=!0)}),o})(i,u,n,()=>{s&&s(),V()})||n(i)}U(),"string"==typeof i?((e,t,i,r)=>{var o=r?"":"al ".concat(e);n(e,i=>{var r;r='Loading data file "'.concat(e,'" failed (no arrayBuffer).'),i||F(r),t(new Uint8Array(i)),o&&V()},t=>{if(!i)throw'Loading data file "'.concat(e,'" failed.');i()}),o&&U()})(i,e=>h(e),s):h(i)},ne.staticInit(),function(){for(var e=new Array(256),t=0;t<256;++t)e[t]=String.fromCharCode(t);ce=e}(),me=r.BindingError=class extends Error{constructor(e){super(e),this.name="BindingError"}},_e=r.InternalError=class extends Error{constructor(e){super(e),this.name="InternalError"}},Oe.prototype.isAliasOf=function(e){if(!(this instanceof Oe&&e instanceof Oe))return!1;for(var t=this.$$.ptrType.registeredClass,i=this.$$.ptr,r=e.$$.ptrType.registeredClass,o=e.$$.ptr;t.baseClass;)i=t.upcast(i),t=t.baseClass;for(;r.baseClass;)o=r.upcast(o),r=r.baseClass;return t===r&&i===o},Oe.prototype.clone=function(){if(this.$$.ptr||ye(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var e,t=ke(Object.create(Object.getPrototypeOf(this),{$$:{value:(e=this.$$,{count:e.count,deleteScheduled:e.deleteScheduled,preservePointerOnDelete:e.preservePointerOnDelete,ptr:e.ptr,ptrType:e.ptrType,smartPtr:e.smartPtr,smartPtrType:e.smartPtrType})}}));return t.$$.count.value+=1,t.$$.deleteScheduled=!1,t},Oe.prototype.delete=function(){this.$$.ptr||ye(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&fe("Object already scheduled for deletion"),Ie(this),Ae(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},Oe.prototype.isDeleted=function(){return!this.$$.ptr},Oe.prototype.deleteLater=function(){return this.$$.ptr||ye(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&fe("Object already scheduled for deletion"),be.push(this),1===be.length&&Ce&&Ce(we),this.$$.deleteScheduled=!0,this},r.getInheritedInstanceCount=function(){return Object.keys(De).length},r.getLiveInheritedInstances=function(){var e=[];for(var t in De)De.hasOwnProperty(t)&&e.push(De[t]);return e},r.flushPendingDeletes=we,r.setDelayFunction=function(e){Ce=e,be.length&&Ce&&Ce(we)},We.prototype.getPointee=function(e){return this.rawGetPointee&&(e=this.rawGetPointee(e)),e},We.prototype.destructor=function(e){this.rawDestructor&&this.rawDestructor(e)},We.prototype.argPackAdvance=8,We.prototype.readValueFromPointer=He,We.prototype.deleteObject=function(e){null!==e&&e.delete()},We.prototype.fromWireType=function(e){var t=this.getPointee(e);if(!t)return this.destructor(e),null;var i=function(e,t){return t=function(e,t){for(void 0===t&&fe("ptr should not be undefined");e.baseClass;)t=e.upcast(t),e=e.baseClass;return t}(e,t),De[t]}(this.registeredClass,t);if(void 0!==i){if(0===i.$$.count.value)return i.$$.ptr=t,i.$$.smartPtr=e,i.clone();var r=i.clone();return this.destructor(e),r}function o(){return this.isSmartPointer?Ne(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:t,smartPtrType:this,smartPtr:e}):Ne(this.registeredClass.instancePrototype,{ptrType:this,ptr:e})}var n,a=this.registeredClass.getActualType(t),s=Re[a];if(!s)return o.call(this);n=this.isConst?s.constPointerType:s.pointerType;var l=Se(t,this.registeredClass,n.registeredClass);return null===l?o.call(this):this.isSmartPointer?Ne(n.registeredClass.instancePrototype,{ptrType:n,ptr:l,smartPtrType:this,smartPtr:e}):Ne(n.registeredClass.instancePrototype,{ptrType:n,ptr:l})},Ke=r.UnboundTypeError=(_t=Error,(gt=Pe("UnboundTypeError",function(e){this.name="UnboundTypeError",this.message=e;var t=new Error(e).stack;void 0!==t&&(this.stack=this.toString()+"\n"+t.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(_t.prototype),gt.prototype.constructor=gt,gt.prototype.toString=function(){return void 0===this.message?this.name:"".concat(this.name,": ").concat(this.message)},gt),Object.assign(Ze.prototype,{get(e){return this.allocated[e]},has(e){return void 0!==this.allocated[e]},allocate(e){var t=this.freelist.pop()||this.allocated.length;return this.allocated[t]=e,t},free(e){this.allocated[e]=void 0,this.freelist.push(e)}}),et.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),et.reserved=et.allocated.length,r.count_emval_handles=function(){for(var e=0,t=et.reserved;t<et.allocated.length;++t)void 0!==et.allocated[t]&&++e;return e};var It,At={p:function(e,t,i){throw new j(e).init(t,i),e},C:function(e,t,i){se.varargs=i;try{var r=se.getStreamFromFD(e);switch(t){case 0:return(o=se.get())<0?-28:ne.createStream(r,o).fd;case 1:case 2:case 6:case 7:return 0;case 3:return r.flags;case 4:var o=se.get();return r.flags|=o,0;case 5:return o=se.get(),E[o+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return y[bt()>>2]=28,-1}}catch(n){if(void 0===ne||"ErrnoError"!==n.name)throw n;return-n.errno}},w:function(e,t,i,r){se.varargs=r;try{t=se.getStr(t),t=se.calculateAt(e,t);var o=r?se.get():0;return ne.open(t,i,o).fd}catch(n){if(void 0===ne||"ErrnoError"!==n.name)throw n;return-n.errno}},t:function(e,t,i,r,o){},n:function(e,t,i,r,o){var n=le(i);ve(e,{name:t=de(t),fromWireType:function(e){return!!e},toWireType:function(e,t){return t?r:o},argPackAdvance:8,readValueFromPointer:function(e){var r;if(1===i)r=_;else if(2===i)r=E;else{if(4!==i)throw new TypeError("Unknown boolean type size: "+t);r=y}return this.fromWireType(r[e>>n])},destructorFunction:null})},r:function(e,t,i,o,n,a,s,l,c,d,u,h,p){u=de(u),a=ze(n,a),l&&(l=ze(s,l)),d&&(d=ze(c,d)),p=ze(h,p);var m,f,_,g=Me(u);m=g,f=function(){Ye("Cannot construct ".concat(u," due to unbound types"),[o])},r.hasOwnProperty(m)?(fe("Cannot register public name '".concat(m,"' twice")),Le(r,m,m),r.hasOwnProperty(_)&&fe("Cannot register multiple overloads of a function with the same number of arguments (".concat(_,")!")),r[m].overloadTable[_]=f):r[m]=f,Ee([e,t,i],o?[o]:[],function(t){var i,n;t=t[0],n=o?(i=t.registeredClass).instancePrototype:Oe.prototype;var s=Pe(g,function(){if(Object.getPrototypeOf(this)!==c)throw new me("Use 'new' to construct "+u);if(void 0===h.constructor_body)throw new me(u+" has no accessible constructor");var e=h.constructor_body[arguments.length];if(void 0===e)throw new me("Tried to invoke ctor of ".concat(u," with invalid number of parameters (").concat(arguments.length,") - expected (").concat(Object.keys(h.constructor_body).toString(),") parameters instead!"));return e.apply(this,arguments)}),c=Object.create(n,{constructor:{value:s}});s.prototype=c;var h=new xe(u,s,c,p,i,a,l,d);h.baseClass&&(void 0===h.baseClass.__derivedClasses&&(h.baseClass.__derivedClasses=[]),h.baseClass.__derivedClasses.push(h));var m,f,_,E=new We(u,h,!0,!1,!1),v=new We(u+"*",h,!1,!1,!1),y=new We(u+" const*",h,!1,!0,!1);return Re[e]={pointerType:v,constPointerType:y},m=g,f=s,r.hasOwnProperty(m)||ge("Replacing nonexistant public symbol"),r[m].overloadTable,r[m]=f,r[m].argCount=_,[E,v,y]})},q:function(e,t,i,r,o,n){var a=Je(t,i);o=ze(r,o),Ee([],[e],function(e){var i="constructor ".concat((e=e[0]).name);if(void 0===e.registeredClass.constructor_body&&(e.registeredClass.constructor_body=[]),void 0!==e.registeredClass.constructor_body[t-1])throw new me("Cannot register multiple constructors with identical number of parameters (".concat(t-1,") for class '").concat(e.name,"'! Overload resolution is currently only performed using the parameter count, not actual type info!"));return e.registeredClass.constructor_body[t-1]=()=>{Ye("Cannot construct ".concat(e.name," due to unbound types"),a)},Ee([],a,function(r){return r.splice(1,0,null),e.registeredClass.constructor_body[t-1]=$e(i,r,null,o,n),[]}),[]})},d:function(e,t,i,r,o,n,a,s,l){var c=Je(i,r);t=de(t),n=ze(o,n),Ee([],[e],function(e){var r="".concat((e=e[0]).name,".").concat(t);function o(){Ye("Cannot call ".concat(r," due to unbound types"),c)}t.startsWith("@@")&&(t=Symbol[t.substring(2)]),s&&e.registeredClass.pureVirtualFunctions.push(t);var d=e.registeredClass.instancePrototype,u=d[t];return void 0===u||void 0===u.overloadTable&&u.className!==e.name&&u.argCount===i-2?(o.argCount=i-2,o.className=e.name,d[t]=o):(Le(d,t,r),d[t].overloadTable[i-2]=o),Ee([],c,function(o){var s=$e(r,o,e,n,a,l);return void 0===d[t].overloadTable?(s.argCount=i-2,d[t]=s):d[t].overloadTable[i-2]=s,[]}),[]})},D:function(e,t){ve(e,{name:t=de(t),fromWireType:function(e){var t=it.toValue(e);return tt(e),t},toWireType:function(e,t){return it.toHandle(t)},argPackAdvance:8,readValueFromPointer:He,destructorFunction:null})},k:function(e,t,i){var r=le(i);ve(e,{name:t=de(t),fromWireType:function(e){return e},toWireType:function(e,t){return t},argPackAdvance:8,readValueFromPointer:ot(t,r),destructorFunction:null})},c:function(e,t,i,r,o){t=de(t);var n=le(i),a=e=>e;if(0===r){var s=32-8*i;a=e=>e<<s>>>s}var l=t.includes("unsigned");ve(e,{name:t,fromWireType:a,toWireType:l?function(e,t){return this.name,t>>>0}:function(e,t){return this.name,t},argPackAdvance:8,readValueFromPointer:nt(t,n,0!==r),destructorFunction:null})},b:function(e,t,i){var r=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t];function o(e){var t=T,i=t[e>>=2],o=t[e+1];return new r(t.buffer,o,i)}ve(e,{name:i=de(i),fromWireType:o,argPackAdvance:8,readValueFromPointer:o},{ignoreDuplicateRegistrations:!0})},j:function(e,t){var i="std::string"===(t=de(t));ve(e,{name:t,fromWireType:function(e){var t,r=T[e>>2],o=e+4;if(i)for(var n=o,a=0;a<=r;++a){var s=o+a;if(a==r||0==g[s]){var l=ae(n,s-n);void 0===t?t=l:(t+="\0",t+=l),n=s+1}}else{var c=new Array(r);for(a=0;a<r;++a)c[a]=String.fromCharCode(g[o+a]);t=c.join("")}return Rt(e),t},toWireType:function(e,t){var r;t instanceof ArrayBuffer&&(t=new Uint8Array(t));var o="string"==typeof t;o||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||fe("Cannot pass non-string to std::string"),r=i&&o?Q(t):t.length;var n=St(4+r+1),a=n+4;if(T[n>>2]=r,i&&o)$(t,g,a,r+1);else if(o)for(var s=0;s<r;++s){var l=t.charCodeAt(s);l>255&&(Rt(a),fe("String has UTF-16 code units that do not fit in 8 bits")),g[a+s]=l}else for(s=0;s<r;++s)g[a+s]=t[s];return null!==e&&e.push(Rt,n),n},argPackAdvance:8,readValueFromPointer:He,destructorFunction:function(e){Rt(e)}})},f:function(e,t,i){var r,o,n,a,s;i=de(i),2===t?(r=st,o=lt,a=ct,n=()=>v,s=1):4===t&&(r=dt,o=ut,a=ht,n=()=>T,s=2),ve(e,{name:i,fromWireType:function(e){for(var i,o=T[e>>2],a=n(),l=e+4,c=0;c<=o;++c){var d=e+4+c*t;if(c==o||0==a[d>>s]){var u=r(l,d-l);void 0===i?i=u:(i+="\0",i+=u),l=d+t}}return Rt(e),i},toWireType:function(e,r){"string"!=typeof r&&fe("Cannot pass non-string to C++ string type ".concat(i));var n=a(r),l=St(4+n+t);return T[l>>2]=n>>s,o(r,l+4,n+t),null!==e&&e.push(Rt,l),l},argPackAdvance:8,readValueFromPointer:He,destructorFunction:function(e){Rt(e)}})},o:function(e,t){ve(e,{isVoid:!0,name:t=de(t),argPackAdvance:0,fromWireType:function(){},toWireType:function(e,t){}})},g:function(e,t,i,r){var o,n;(e=mt[e])(t=it.toValue(t),i=void 0===(n=pt[o=i])?de(o):n,null,r)},m:tt,l:function(e,t){var i=function(e,t){for(var i=new Array(e),r=0;r<e;++r)i[r]=ft(T[t+4*r>>2],"parameter "+r);return i}(e,t),r=i[0],o=r.name+"_$"+i.slice(1).map(function(e){return e.name}).join("_")+"$",n=Et[o];if(void 0!==n)return n;for(var a=["retType"],s=[r],l="",c=0;c<e-1;++c)l+=(0!==c?", ":"")+"arg"+c,a.push("argType"+c),s.push(i[1+c]);var d,u,h="return function "+Me("methodCaller_"+o)+"(handle, name, destructors, args) {\n",p=0;for(c=0;c<e-1;++c)h+=" var arg"+c+" = argType"+c+".readValueFromPointer(args"+(p?"+"+p:"")+");\n",p+=i[c+1].argPackAdvance;for(h+=" var rv = handle[name]("+l+");\n",c=0;c<e-1;++c)i[c+1].deleteObject&&(h+=" argType"+c+".deleteObject(arg"+c+");\n");return r.isVoid||(h+=" return retType.toWireType(destructors, rv);\n"),h+="};\n",a.push(h),d=Qe(Function,a).apply(null,s),u=mt.length,mt.push(d),n=u,Et[o]=n,n},a:()=>{F("")},e:function(){return Date.now()},v:()=>g.length,A:(e,t,i)=>g.copyWithin(e,t,t+i),u:e=>{g.length,F("OOM")},y:(e,t)=>{var i=0;return yt().forEach(function(r,o){var n=t+i;T[e+4*o>>2]=n,((e,t)=>{for(var i=0;i<e.length;++i)_[0|t++]=e.charCodeAt(i);_[0|t]=0})(r,n),i+=r.length+1}),0},z:(e,t)=>{var i=yt();T[e>>2]=i.length;var r=0;return i.forEach(function(e){r+=e.length+1}),T[t>>2]=r,0},i:function(e){try{var t=se.getStreamFromFD(e);return ne.close(t),0}catch(i){if(void 0===ne||"ErrnoError"!==i.name)throw i;return i.errno}},x:function(e,t){try{var i=se.getStreamFromFD(e),r=i.tty?2:ne.isDir(i.mode)?3:ne.isLink(i.mode)?7:4;return _[0|t]=r,E[t+2>>1]=0,P=[0,(M=0,+Math.abs(M)>=1?M>0?+Math.floor(M/4294967296)>>>0:~~+Math.ceil((M-+(~~M>>>0))/4294967296)>>>0:0)],y[t+8>>2]=P[0],y[t+12>>2]=P[1],P=[0,(M=0,+Math.abs(M)>=1?M>0?+Math.floor(M/4294967296)>>>0:~~+Math.ceil((M-+(~~M>>>0))/4294967296)>>>0:0)],y[t+16>>2]=P[0],y[t+20>>2]=P[1],0}catch(o){if(void 0===ne||"ErrnoError"!==o.name)throw o;return o.errno}},B:function(e,t,i,r){try{var o=((e,t,i,r)=>{for(var o=0,n=0;n<i;n++){var a=T[t>>2],s=T[t+4>>2];t+=8;var l=ne.read(e,_,a,s,r);if(l<0)return-1;if(o+=l,l<s)break;void 0!==r&&(r+=l)}return o})(se.getStreamFromFD(e),t,i);return T[r>>2]=o,0}catch(n){if(void 0===ne||"ErrnoError"!==n.name)throw n;return n.errno}},s:function(e,t,i,r,o){var n,a,s=(a=i)+2097152>>>0<4194305-!!(n=t)?(n>>>0)+4294967296*a:NaN;try{if(isNaN(s))return 61;var l=se.getStreamFromFD(e);return ne.llseek(l,s,r),P=[l.position>>>0,(M=l.position,+Math.abs(M)>=1?M>0?+Math.floor(M/4294967296)>>>0:~~+Math.ceil((M-+(~~M>>>0))/4294967296)>>>0:0)],y[o>>2]=P[0],y[o+4>>2]=P[1],l.getdents&&0===s&&0===r&&(l.getdents=null),0}catch(c){if(void 0===ne||"ErrnoError"!==c.name)throw c;return c.errno}},h:function(e,t,i,r){try{var o=((e,t,i,r)=>{for(var o=0,n=0;n<i;n++){var a=T[t>>2],s=T[t+4>>2];t+=8;var l=ne.write(e,_,a,s,r);if(l<0)return-1;o+=l,void 0!==r&&(r+=l)}return o})(se.getStreamFromFD(e),t,i);return T[r>>2]=o,0}catch(n){if(void 0===ne||"ErrnoError"!==n.name)throw n;return n.errno}}},St=(function(){var e,t,o,n,a={a:At};function s(e,t){var i,o,n=e.exports;return i=(p=n).E.buffer,r.HEAP8=_=new Int8Array(i),r.HEAP16=E=new Int16Array(i),r.HEAP32=y=new Int32Array(i),r.HEAPU8=g=new Uint8Array(i),r.HEAPU16=v=new Uint16Array(i),r.HEAPU32=T=new Uint32Array(i),r.HEAPF32=I=new Float32Array(i),r.HEAPF64=A=new Float64Array(i),S=p.H,o=p.F,w.unshift(o),V(),n}if(U(),r.instantiateWasm)try{return r.instantiateWasm(a,s)}catch(l){f("Module.instantiateWasm callback failed with error: "+l),i(l)}(e=h,t=k,o=a,n=function(e){s(e.instance)},e||"function"!=typeof WebAssembly.instantiateStreaming||B(t)||"function"!=typeof fetch?W(t,o,n):fetch(t,{credentials:"same-origin"}).then(e=>WebAssembly.instantiateStreaming(e,o).then(n,function(e){return f("wasm streaming compile failed: "+e),f("falling back to ArrayBuffer instantiation"),W(t,o,n)}))).catch(i)}(),e=>(St=p.G)(e)),Rt=e=>(Rt=p.I)(e),bt=()=>(bt=p.J)(),wt=e=>(wt=p.K)(e),Ct=(r.__embind_initialize_bindings=()=>(r.__embind_initialize_bindings=p.L)(),e=>(Ct=p.M)(e));function Dt(){function e(){It||(It=!0,r.calledRun=!0,R||(r.noFSInit||ne.init.initialized||ne.init(),ne.ignorePermissions=!1,G(w),t(r),r.onRuntimeInitialized&&r.onRuntimeInitialized(),function(){if(r.postRun)for("function"==typeof r.postRun&&(r.postRun=[r.postRun]);r.postRun.length;)N(r.postRun.shift());G(C)}()))}L>0||(function(){if(r.preRun)for("function"==typeof r.preRun&&(r.preRun=[r.preRun]);r.preRun.length;)D(r.preRun.shift());G(b)}(),L>0||(r.setStatus?(r.setStatus("Running..."),setTimeout(function(){setTimeout(function(){r.setStatus("")},1),e()},1)):e()))}if(r.dynCall_jiji=(e,t,i,o,n)=>(r.dynCall_jiji=p.N)(e,t,i,o,n),r._ff_h264_cabac_tables=67061,x=function e(){It||Dt(),It||(x=e)},r.preInit)for("function"==typeof r.preInit&&(r.preInit=[r.preInit]);r.preInit.length>0;)r.preInit.pop()();return Dt(),e.ready}),$H=QH,ZH=class extends JH{constructor(e){super($H,null!=e&&e.wasmPath?fetch(null==e?void 0:e.wasmPath).then(e=>e.arrayBuffer()):void 0,null==e?void 0:e.workerMode,null==e?void 0:e.canvas,null==e?void 0:e.yuvMode)}};(()=>{var e="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0})();var eW=(e=>(e.ROOM_DESTROY="1",e.JOIN_START="21",e.JOIN_SCHEDULE_SUCCESS="22",e.JOIN_SIGNAL_CONNECTION_START="23",e.JOIN_SIGNAL_CONNECTION_END="24",e.JOIN_SEND_CMD="25",e.JOIN_RECEIVED_CMD_RES="26",e.JOIN_SUCCESS="27",e.JOIN_FAILED="28",e.LEAVE_START="51",e.LEAVE_SEND_CMD="52",e.LEAVE_SUCCESS="53",e.PUBLISH_START="61",e.SEND_FIRST_VIDEO_FRAME="62",e.PUBLISH_FAILED="63",e.SUBSCRIBE_START="81",e.SUBSCRIBE_SUCCESS="82",e.SUBSCRIBE_FAILED="84",e.UNSUBSCRIBE_SUCCESS="83",e.LOCAL_TRACK_CAPTURE_START="101",e.LOCAL_TRACK_CAPTURE_SUCCESS="102",e.LOCAL_TRACK_CAPTURE_FAILED="103",e.LOCAL_TRACK_PUBLISHED="104",e.LOCAL_TRACK_UNPUBLISHED="105",e.LOCAL_TRACK_REPLACED="106",e.SWITCH_DEVICE_SUCCESS="107",e.TRACK_MUTED="108",e.TRACK_UNMUTED="109",e.REMOTE_TRACK_SUBSCRIBED="110",e.REMOTE_TRACK_UNSUBSCRIBED="111",e.LOCAL_TRACK_RECAPTURE="112",e.LOCAL_AUDIO_STARTED="113",e.LOCAL_AUDIO_STOPPED="114",e.REMOTE_AUDIO_STARTED="115",e.REMOTE_AUDIO_STOPPED="116",e.PLAY_TRACK_START="151",e.PLAYER_STATE_CHANGED="152",e.VIDEO_LOADED_DATA="153",e.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",e.AUDIO_CONTEXT_LONG_SUSPENDED="155",e.REMOTE_VIDEO_PLAY_START="156",e.REMOTE_VIDEO_PLAY_FINISH="157",e.SIGNAL_CONNECTION_STATE_CHANGED="201",e.PEER_CONNECTION_STATE_CHANGED="202",e.SINGLE_CONNECTION_STAT="203",e.SPC_RECONNECTED="204",e.HEARTBEAT_REPORT="251",e.RECEIVED_PUBLISHED_USER_LIST="252",e.REMOTE_PUBLISH_STATE_CHANGED="253",e.AUDIO_LEVEL_INTERVAL="260",e.NETWORK_QUALITY="261",e.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",e.QUALITY_LIMITATION_CHANGED="263",e.LOG="264",e.AUDIO_PROCESSOR_DEBUG="265",e.SSO_SWITCH="266",e.SEI_MESSAGE="267",e.USER_PAUSE_IN_PIP="268",e.USER_RESUME_IN_PIP="269",e.ENTER_PICTURE_IN_PICTURE="270",e.LEAVE_PICTURE_IN_PICTURE="271",e.SWITCH_ROOM_START="401",e.SWITCH_ROOM_SUCCESS="407",e.SWITCH_ROOM_FAILED="408",e))(eW||{}),tW="undefined"!=typeof importScripts,iW="undefined"!=typeof registerProcessor,rW="jssdk_log",oW=(e=>(e[e.TRACE=0]="TRACE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(oW||{}),nW=Symbol(32),aW=Symbol(16),sW=Symbol(8),lW=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 function(e,t,i,r){return new(i||(i=Promise))(function(o,n){function a(e){try{l(r.next(e))}catch(t){n(t)}}function s(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}l((r=r.apply(e,t||[])).next())})}(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(nW)}readU16(){return this.read(aW)}readU8(){return this.read(sW)}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===nW){if(r(4))return;e=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===aW){if(r(2))return;e=t[0]<<8|t[1]}else if(this.need===sW){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}};lW.U32=nW,lW.U16=aW,lW.U8=sW;function cW(e){let t=new lW;for(;e>=128;)t.malloc(1)[0]=255&e|128,e>>>=7;return t.malloc(1)[0]=255&e,t.buffer||new Uint8Array(0)}function dW(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=new lW,r=t<<3;switch(typeof e){case"boolean":let o=i.malloc(2);o[0]=r,o[1]=e?1:0;break;case"number":i.malloc(1)[0]=r,i.write(cW(e));break;case"string":i.malloc(1)[0]=2|r;let n=(new TextEncoder).encode(e);i.write(cW(n.length));let a=i.malloc(n.length);for(let e=0;e<n.length;e++)a[e]=n[e];break;case"object":let s=new lW;if(Array.isArray(e))for(let t=0;t<e.length;t++){let i=dW(e[t],t+1);i&&s.write(i)}else{let t=1;for(let i in e){let r=dW(e[i],t++);r&&s.write(r)}}0===t?s.buffer&&i.write(s.buffer):(i.malloc(1)[0]=2|r,s.buffer&&(i.write(cW(s.buffer.length)),i.write(s.buffer)))}return i.buffer||new Uint8Array(0)}var uW=class{constructor(){LH(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 hW(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 pW(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function mW(e,t){return e[t]}function fW(e,t,i){return(new TextDecoder).decode(function(e,t,i){return e.slice(t,t+i)}(e,t,i))}var _W=0,gW=2654435769;function EW(e,t){let i=new uW,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,_W);_W=_W+1&2147483647,i.writeInt32(0),i.writeInt32(r.version),i.writeByte(r.encryption);let o=(new TextEncoder).encode(r.d2);i.writeInt32(o.length+4),o&&i.writeBytes(o),i.writeByte(r.uinType);let n=(new TextEncoder).encode(r.uin);i.writeInt32(n.length+4),n.length&&i.writeBytes(n);let a=new uW;a.writeInt32(0),a.writeInt32(r.reqHead.seqNumber),a.writeInt32(r.reqHead.appId),a.writeByte(r.reqHead.appId>>>24&255),a.writeByte(r.reqHead.appId>>>16&255),a.writeByte(r.reqHead.appId>>>8&255),a.writeByte(255&r.reqHead.appId);for(let E=4;E<16;E++)a.writeByte(0);let s=(new TextEncoder).encode(r.reqHead.a2);a.writeInt32(s.length+4),s.length&&a.writeBytes(s);let l=(new TextEncoder).encode(r.reqHead.serviceCmd);a.writeInt32(l.length+4),l.length&&a.writeBytes(l);let c=(new TextEncoder).encode(r.reqHead.cookie);a.writeInt32(c.length+4),c.length&&a.writeBytes(c);let d=(new TextEncoder).encode(r.reqHead.imei);a.writeInt32(d.length+4),d.length&&a.writeBytes(d);let u=(new TextEncoder).encode(r.reqHead.ksid);a.writeInt32(u.length+4),u.length&&a.writeBytes(u);let h=(new TextEncoder).encode(r.reqHead.clientVersionInfo);a.writeInt16(h.length+2),h.length&&a.writeBytes(h);let p=a.length;a.data[0]=p>>>24&255,a.data[1]=p>>>16&255,a.data[2]=p>>>8&255,a.data[3]=255&p,BG(e)&&(e=(new TextEncoder).encode(e)),a.writeInt32(e.length+4),e.length&&a.writeBytes(e);let m=new Uint8Array(a.data),f=null;1===r.encryption?f=(new TextEncoder).encode(r.uin):2===r.encryption&&(f=new Uint8Array(16)),f&&(m=function(e,t){let i=e.length,r=(i+1+2+7)%8;r&&(r=8-r);let o=new Uint8Array(i+1+2+7+r),n=0,a=new Uint8Array(8),s=new Uint8Array(8),l=new Uint8Array(8),c=0;a[0]=248&Math.floor(256*Math.random())|r,c=1;for(let u=0;u<r;u++)a[c]=255&Math.floor(256*Math.random()),c+=1;for(let u=0;u<2;)if(c<8&&(a[c]=255&Math.floor(256*Math.random()),c+=1,u+=1),8===c){vW(a,t,s,l,o,n),n+=8,c=0;for(let e=0;e<8;e++)l[e]=o[n-8+e]}let d=0;for(;d<i;)if(c<8&&(a[c]=e[d],c+=1,d+=1),8===c){vW(a,t,s,l,o,n),n+=8,c=0;for(let e=0;e<8;e++)l[e]=o[n-8+e]}for(let u=0;u<7;)if(c<8&&(a[c]=0,c+=1,u+=1),8===c){vW(a,t,s,l,o,n),n+=8,c=0;for(let e=0;e<8;e++)l[e]=o[n-8+e]}return o}(m,f)),i.writeBytes(m);let _=new Uint8Array(i.data),g=_.length;return _[0]=g>>>24&255,_[1]=g>>>16&255,_[2]=g>>>8&255,_[3]=255&g,_}function vW(e,t,i,r,o,n){for(let a=0;a<8;a++)e[a]^=r[a];!function(e,t,i,r){let o=pW(e,0),n=pW(e,4),a=[];for(let l=0;l<4;l++)a[l]=pW(t,4*l);let s=0;for(let l=0;l<16;l++)s+=gW,s>>>=0,o+=(n<<4)+a[0]^n+s^(n>>>5)+a[1],o>>>=0,n+=(o<<4)+a[2]^o+s^(o>>>5)+a[3],n>>>=0;hW(i,o,r),hW(i,n,r+4)}(e,t,o,n);for(let a=0;a<8;a++)o[n+a]^=i[a];for(let a=0;a<8;a++)i[a]=e[a]}var yW=function(){return Date.now()+0},TW=function(){let e=new Date;return e.setTime(yW()),e.toLocaleString()};function IW(e){let t=function(e){try{let t={},i=0;t.totalLength=pW(e,i),i+=4,t.version=pW(e,i),i+=4,t.encryption=mW(e,i),i+=1,t.uinType=mW(e,i),i+=1,t.uinLength=pW(e,i),i+=4,t.uin=t.uinLength>4?fW(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),o=AW(new Uint8Array(e.slice(0,8)),t),n=7&o[0],a=e.length-1-n-2-7,s=new Uint8Array(a),l=0,c=r,d=e.slice(0,8);i=8;let u=1;u+=n;for(let p=1;p<=2;)if(u<8)u++,p++;else if(8===u){let r=SW(e,i,c,d,o,t);c=r.ivPreCrypt,d=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,u=0}let h=a;for(;h>0;)if(u<8)s[l++]=o[u]^c[u],u++,h--;else if(8===u){let r=SW(e,i,c,d,o,t);c=r.ivPreCrypt,d=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,u=0}for(let p=1;p<=7;)if(u<8)o[u],c[u],u++,p++;else if(8===u){if(i>=e.length)break;let r=SW(e,i,c,d,o,t);if(!r.success)break;c=r.ivPreCrypt,d=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,u=0}return s}(r,new Uint8Array(16).fill(0)),t.decrypted=!0,i=0}else e=r,i=0;return t.rspHeadLength=pW(e,i),i+=4,t.seqNo=pW(e,i),i+=4,t.retCode=pW(e,i),i+=4,t.retStrLength=pW(e,i),i+=4,t.retStr=t.retStrLength?fW(e,i,t.retStrLength-4):"",i+=t.retStrLength-4,t.serviceCmdLength=pW(e,i),i+=4,t.serviceCmd=t.serviceCmdLength?fW(e,i,t.serviceCmdLength-4):"",i+=t.serviceCmdLength-4,t.cookieLength=pW(e,i),i+=4,t.cookie=t.cookieLength?fW(e,i,t.cookieLength-4):"",i+=t.cookieLength-4,t.flag=pW(e,i),i+=4,t.busiBuffLength=pW(e,i),i+=4,t.busiBuff=t.busiBuffLength?fW(e,i,t.busiBuffLength-4):"",i+=t.busiBuffLength-4,t}catch(t){}}(e);return null==t?void 0:t.busiBuff}function AW(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 o=16*gW>>>0;for(let n=0;n<16;n++)r-=(i<<4)+t[2]^i+o^(i>>>5)+t[3],r>>>=0,i-=(r<<4)+t[0]^r+o^(r>>>5)+t[1],i>>>=0,o-=gW,o>>>=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 SW(e,t,i,r,o,n){if(t+8>e.length)return{success:!1};let a=new Uint8Array(r),s=e.slice(t,t+8),l=new Uint8Array(8);for(let c=0;c<8;c++)l[c]=o[c]^s[c];return{success:!0,ivPreCrypt:a,ivCurCrypt:s,debiBuf:AW(l,n),bufPos:t+8}}var RW="undefined"!=typeof TextDecoder?new TextDecoder:void 0;var bW=Object.prototype.hasOwnProperty,wW=e=>"function"==typeof e,CW=e=>void 0===e;function DW(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(function(e){if(!e||"object"!=typeof e||"[object Object]"!=Object.prototype.toString.call(e))return!1;let t=Object.getPrototypeOf(e);if(null===t)return!0;let i=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof i&&i instanceof i&&Function.prototype.toString.call(i)===Function.prototype.toString.call(Object)}(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(let t in e)if(bW.call(e,t))return!1;return!0}return!1}var NW=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:o,onRetryFailed:n,onRetrySuccess:a,context:s}=e;return function(){for(var e=arguments.length,l=new Array(e),c=0;c<e;c++)l[c]=arguments[c];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,f=(e,i)=>uw(this,null,function*(){let c=s||this;try{let i=yield t.apply(c,l);h>0&&a&&a.call(this,h),h=0,e(i)}catch(_){let t=()=>{clearTimeout(p),h=0,m=2,i(_)},a=()=>{2!==m&&h<(wW(d)?d():d)?(h++,m=1,wW(o)&&o.call(this,h,t),p=window.setTimeout(()=>{p=-1,f(e,i)},wW(u)?u(h):u)):(t(),wW(n)&&n.call(this,_))};wW(r)?r.call(this,{error:_,retry:a,reject:i,retryFuncArgs:l,retriedCount:h}):a()}});return new Promise(f)}},kW=class e{constructor(e){LH(this,"_parentPath"),LH(this,"userId"),LH(this,"remoteUserId"),LH(this,"id"),LH(this,"sdkAppId"),LH(this,"type"),LH(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!(e=>"boolean"==typeof e)(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}getFullId(){return this._parentPath&&this.id?"".concat(this._parentPath,"-").concat(this.id):this._parentPath?this._parentPath:this.id}createChild(t){let i=new e({id:t.id,userId:CW(t.userId)?this.userId:t.userId,sdkAppId:CW(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:CW(t.type)?this.type:t.type,isLocal:CW(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:CW(t.remoteUserId)?this.remoteUserId:t.remoteUserId});return i.bindParent(this),i}bindParent(e){let t=e.getFullId();this._parentPath!==t&&(this.debug("bind logger parent: ".concat(e.id)),this._parentPath=t,this.userId=e.userId||this.userId,this.sdkAppId=e.sdkAppId||this.sdkAppId)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId,r=this.getFullId();t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(r).concat(i?"|".concat(i):"","]")),UG.log(e,t,CW(this.userId)||DW(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)}},OW="undefined"==typeof navigator?"":navigator.userAgent,MW=e=>new RegExp(e,"i").test(OW),PW=e=>{if(MW(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=OW.match(t);if(i&&i[1])return i[1]}return""},LW=e=>{if(MW(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=OW.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},xW=/AppleWebKit\/([\d.]+)/i.exec(OW);xW&&parseFloat(xW[1]);var UW=MW("iPad"),VW="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&MW("Macintosh"),FW=MW("iPhone")&&!UW,BW=MW("iPod"),HW=FW||UW||BW||VW,WW=MW("Android");!function(){if(WW){let e=OW.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}}}();WW&&MW("webkit");var GW=MW("Firefox"),jW=PW("Firefox");LW("Firefox");var zW=MW("Edge"),KW=PW("Edge"),qW=MW("Edg"),YW=PW("Edg");LW("Edg");var JW=MW("SogouMobileBrowser"),XW=PW("SogouMobileBrowser"),QW=MW("MetaSr\\s"),$W=PW("MetaSr\\s"),ZW=MW("TBS"),eG=PW("TBS"),tG=MW("XWEB"),iG=PW("XWEB");MW("MSIE\\s8\\.0");var rG=MW("MSIE\\/\\d+");!function(){if(rG){let e=/MSIE\s(\d+)\.\d/.exec(OW),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(OW)&&/rv:11.0/.test(OW)&&(t=11),t}}();var oG=MW("(micromessenger|webbrowser)"),nG=PW("MicroMessenger"),aG=!ZW&&MW("MQQBrowser")&&MW("COVC"),sG=!ZW&&MW("MQQBrowser")&&!MW("COVC"),lG=sG||aG?PW("MQQBrowser"):"",cG=!ZW&&MW(" QQBrowser"),dG=PW(" QQBrowser"),uG=!ZW&&MW("QQBrowserLite"),hG=PW("QQBrowserLite"),pG=!ZW&&MW("MQBHD"),mG=PW("MQBHD");MW("Windows"),!HW&&MW("MAC OS X"),!WW&&MW("Linux"),MW("CrOS"),MW("MicroMessenger"),MW("UCBrowser"),MW("Electron");var fG=MW("MiuiBrowser"),_G=PW("MiuiBrowser"),gG=MW("HuaweiBrowser");MW("Huawei")||MW("HUAWEI"),MW("Honor")||MW("HONOR");var EG=PW("HuaweiBrowser"),vG=MW("SamsungBrowser"),yG=PW("SamsungBrowser"),TG=MW("HeyTapBrowser"),IG=PW("HeyTapBrowser"),AG=MW("VivoBrowser"),SG=PW("VivoBrowser");MW("OpenHarmony"),PW("OpenHarmony");var RG=MW("CriOS"),bG=MW("Chrome"),wG=!zW&&!QW&&!JW&&!ZW&&!tG&&!qW&&!cG&&!fG&&!gG&&!vG&&!TG&&!AG&&bG,CG=MW("HeadlessChrome");LW("Chrome");var DG=PW("Chrome");LW("Electron");var NG=!bG&&!sG&&!aG&&!uG&&!pG&&MW("Safari"),kG=PW("Version");/Android.*(wv|.0.0.0)/.test(OW);var OG=(()=>{if(VW)return kG;if(HW){let e=OW.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})();Number(OG.split(".")[0]),(()=>{let e=Number(OG.split(".")[0])})(),function(){let e=new Map([[GW,["Firefox",jW]],[qW,["Edg",YW]],[wG,["Chrome",DG]],[RG,["ChiOS",PW("CriOS")]],[NG&&!RG,["Safari",kG]],[ZW,["TBS",eG]],[tG,["XWEB",iG]],[oG&&FW,["WeChat",nG]],[cG,["QQ(Win)",dG]],[sG,["QQ(Mobile)",lG]],[aG,["QQ(Mobile X5)",lG]],[uG,["QQ(Mac)",hG]],[pG,["QQ(iPad)",mG]],[fG,["MI",_G]],[gG,["HW",EG]],[vG,["Samsung",yG]],[TG,["OPPO",IG]],[AG,["VIVO",SG]],[zW,["EDGE",KW]],[JW,["SogouMobile",XW]],[QW,["Sogou",$W]]]),t="unknown",i="unknown";e.has(!0)&&([t,i]=e.get(!0))}();var MG=new(MH(xH(),1).default),PG=eW,LG=new class{constructor(){LH(this,"enable",!1),LH(this,"ssoFailCount",0),MG.on("22",e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.sso&&MG.emit("266",{enable:!0})}),MG.on("266",e=>{let{enable:t}=e;this.enable=t})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&MG.emit("266",{enable:!1})}},xG=class e{constructor(){LH(this,"_isEnableUploadLog",!0),LH(this,"_localJoinedUser",new Map),LH(this,"_queue",[]),LH(this,"_timeoutId",-1),LH(this,"_logLevel",1),LH(this,"_logLevelToUpload",2),tW||iW||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){MG.on(PG.JOIN_SCHEDULE_SUCCESS,e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.logLevelToUpload&&oW[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),MG.on(PG.JOIN_START,e=>{let{params:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),MG.on(PG.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:o}=t;e.map.has(r)?e.map.get(r).logs.push(i):e.map.set(r,{userId:r,sdkAppId:o,logs:[i]})});else if(BG(i.userId)&&HG(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 uw(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:o}=t[e],n={timestamp:TW(),sdkAppId:String(r),userId:i,version:"5.0.0",log:o.map(e=>e.log).join("\n")},a=JSON.stringify(n),s=LG.enable?WG(n,2002,r):a;yield this.uploadLogWithRetry(s,r,s instanceof Uint8Array,a),o.forEach(e=>e.uploaded=!0)}}catch(SM){}let i=t.filter(e=>!e.uploaded);i.length>0&&(this._queue=i.concat(this._queue))})}uploadLogWithRetry(e,t,i,r){return NW({retryFunction:()=>function(e){let{url:t,body:i,method:r="POST",timeout:o,priority:n}=e;return new Promise((e,a)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:n}).then(e=>e.clone().json().then(e=>({data:e}),()=>e.arrayBuffer().then(e=>({data:IW(new Uint8Array(e))||(RW?RW.decode(e):e)})))).then(e,a);let s=new XMLHttpRequest;s.onreadystatechange=()=>{if(4===s.readyState)if(s.status>=200&&s.status<300)try{let t=JSON.parse(s.response);e({data:t})}catch(wM){e({data:s.response})}else a({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=o||5e3,s.open(r,t,!0),s.send(i)})}({url:VG(t,rW),body:e,timeout:5e3,priority:"low"}).then(e=>{i&&"ok"!==e.data&&(LG.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(yW()),"[".concat(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)}(t),"] <").concat(oW[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){FG(oW[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(BG(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(Nw){return""}}addLogToQueue(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0,n={log:t.reduce((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim(),""),level:e,userId:r,sdkAppId:o,forAllJoinedClients:i};MG.emit(PG.LOG,{log:n}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(n)}log(t,i){let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],o=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;var a;if(i.unshift(this.getPrefix(t)),this.addLogToQueue(t,i,r,o,n),t<this._logLevel)return;let s=(null==(a=oW[t])?void 0:a.toLowerCase())||"info";e.PRINT_LOG_TAG?console[s]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...i):console[s](...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){if(e.parent instanceof kW){let t=e,{parent:i}=t,r=((e,t)=>{var i={};for(var r in e)CH.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&bH)for(var r of bH(e))t.indexOf(r)<0&&DH.call(e,r)&&(i[r]=e[r]);return i})(t,["parent"]),o=new kW(r);return o.bindParent(i),o}return new kW(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;oW[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};LH(xG,"PRINT_LOG_TAG",!(HW||WW||CG));var UG=new xG,VG=function(e,t){let i;return i=(e=>Number(e)<14e8)(e)?"https://apisgp.my-imcloud.com":"https://yun.tim.qq.com","".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(Math.floor(Math.random()*tw(2,31)),"&sdkappid=").concat(e,"&cmdtype=").concat(t)},FG=e=>void 0===e,BG=e=>"string"==typeof e,HG=e=>"number"==typeof e;function WG(e,t,i,r){try{let o=function(e,t,i,r){let o={data:e,random:Math.floor(2147483648*Math.random()),sdkAppId:i};return FG(r)||(o=OH(kH({},o),{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(o)}}}(e,t,i,r);return EW(dW(o),i)}catch(SM){return JSON.stringify(e)}}var GG=class e{constructor(e){this.core=e,LH(this,"contextMap",new Map),LH(this,"decodeProcessorMap",new WeakMap),this.addKVReportBeforeExitRoom=this.addKVReportBeforeExitRoom.bind(this),this.createDecoder=this.createDecoder.bind(this),this.core.innerEmitter.on("51",this.addKVReportBeforeExitRoom)}getAlias(){return"videoDecoder"}getGroup(e){return null!=e&&e.track?"".concat(e.track.userId).concat(e.track.streamType):"*"}getName(){return e.Name}getValidateRule(e){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(e,t){var i;switch(e){case"wasm":let e=(null==(i=this.core.assetsPath)?void 0:i.replace(/\/+$/,""))||".";return new ZH(OH(kH({},t),{wasmPath:"".concat(e,"/videodec.wasm")}));case"webCodecs":return new qH;case"mse":throw new Error("mse decoder not supported yet");default:throw new Error("Unsupported decoder type")}}start(e){this.decodeProcessorMap.set(e.track,this.decode(e)),this.core.room.videoManager.addDecodeProcessor({processor:e=>{let{frame:t,track:i}=e;var r;return(null==(r=this.decodeProcessorMap.get(i))?void 0:r({frame:t,track:i}))||t},type:3})}decode(e){let{pipe:t,take:i,subscribe:r}=this.core.rx;return o=>{let{frame:n,track:a}=o;if(a!==e.track||"empty"===n.type)return n;if(this.contextMap.has(a))return this.contextMap.get(a).decode(n);let s=this.core.room.videoManager.createDecodeContext(OH(kH({},e),{createDecoder:this.createDecoder}));return t(s.trackDoneOB,i(1),r(()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:a})})),this.contextMap.set(a,s),s.decode(n)}}stop(e){if(null!=e&&e.track){let t=this.contextMap.get(e.track);t&&(t.close("stop"),this.report(t,e.track),this.contextMap.delete(e.track))}else this.contextMap.forEach((e,t)=>{e.close("stop"),this.contextMap.delete(t)});0===this.contextMap.size&&this.core.room.videoManager.removeDecodeProcessor({type:3})}report(e,t){if(e.isReported)return;e.isReported=!0;let i=(performance&&performance.now?Math.floor(performance.now()):Date.now())-e.startPerformanceTime,{renderFreezeTotal:r,dataFreezeTotal:o}=this.getRemoteTrackFreezeDuration(t,e),n="report health data: ".concat(e.track.userId," ").concat(e.track.streamType," ").concat(e.type,"+").concat(e.renderer," goodType:").concat(e.goodType," ").concat(e.failedReason?"failedReason: ".concat(e.failedReason):"");i&&(this.core.kvStatManager.addNumber({key:514850,value:Math.floor(r/i*100),split:1,max:100}),n+=" RENDER_FREEZE_RATE: ".concat(Math.floor(r/i*100),"%")),i&&(this.core.kvStatManager.addNumber({key:514851,value:Math.floor(o/i*100),split:1,max:100}),n+=" DATA_FREEZE_RATE: ".concat(Math.floor(o/i*100),"%")),e.inputFrameCount&&(this.core.kvStatManager.addNumber({key:514852,value:Math.floor(e.decodedFrameCount/e.inputFrameCount*100),split:1,max:100}),n+=" VIDEO_CONSUME_RENDER_RATE: ".concat(Math.floor(e.decodedFrameCount/e.inputFrameCount*100),"%")),this.core.log.info(n)}addKVReportBeforeExitRoom(e){let{room:t}=e;t===this.core.room&&this.contextMap.forEach((e,t)=>{this.report(e,t)})}update(e){let t=this.contextMap.get(e.track);t&&("mock"!==e.type?(t.close("update"),this.contextMap.set(e.track,this.core.room.videoManager.createDecodeContext(OH(kH({},e),{createDecoder:this.createDecoder})))):t.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(e,t){let i=this.core.room.badCaseDetector.getDataFreezeMap().get("".concat(e.userId,"_").concat(e.streamType)),r=this.core.room.badCaseDetector.getRenderFreezeDuration("".concat(e.userId,"_").concat(e.streamType)),o=0;return i&&i.durationItemList.forEach(e=>{e.startTime>t.startPerformanceTime&&(o+=e.getDuration())}),{renderFreezeTotal:r,dataFreezeTotal:o}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};LH(GG,"Name","TRTCVideoDecoder");var jG=GG,zG=sw(hw());function KG(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return KU((e,o)=>{let n=new WeakMap;return dM.on(hM.ROOM_DESTROY,e=>{let{room:t}=e;return n.delete(t)}),function(){let a=n.get(this);for(var s=arguments.length,l=new Array(s),c=0;c<s;c++)l[c]=arguments[c];if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},n.set(this,a)),0===a.timestamp?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),r&&(a.totalSizeInSecond+=r(...l)),0!==a.timestamp&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=t||a.totalSizeInSecond>i))throw new yw({code:Ew.INVALID_OPERATION,message:NP({key:bP.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=t,isSize:a.totalSizeInSecond>i,name:o,timesInSecond:t,maxSizeInSecond:i}})});a.callCountInSecond++,e.call(this,...l)}})}var qG,YG=!0,JG={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"},XG={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},QG=((qG=QG||{})[qG.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",qG[qG.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",qG[qG.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",qG[qG.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",qG[qG.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",qG[qG.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",qG[qG.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",qG[qG.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",qG[qG.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",qG[qG.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",qG[qG.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",qG[qG.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",qG[qG.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",qG[qG.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",qG[qG.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",qG[qG.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",qG[qG.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",qG[qG.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",qG[qG.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",qG[qG.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",qG[qG.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",qG[qG.INVALID_OPERATION=5100]="INVALID_OPERATION",qG[qG.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",qG[qG.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",qG[qG.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",qG[qG.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",qG[qG.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",qG[qG.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",qG[qG.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",qG[qG.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",qG[qG.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",qG[qG.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",qG[qG.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",qG[qG.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",qG[qG.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",qG[qG.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",qG[qG.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",qG[qG.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",qG[qG.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",qG[qG.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",qG[qG.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",qG[qG.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",qG[qG.DEVICE_ERROR=5300]="DEVICE_ERROR",qG[qG.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",qG[qG.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",qG[qG.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",qG[qG.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",qG[qG.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",qG[qG.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",qG[qG.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",qG[qG.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",qG[qG.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",qG[qG.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",qG[qG.SERVER_ERROR=5400]="SERVER_ERROR",qG[qG.NEED_TO_BUY=5401]="NEED_TO_BUY",qG[qG.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",qG[qG.OPERATION_FAILED=5500]="OPERATION_FAILED",qG[qG.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",qG[qG.REJOIN_FAILED=5502]="REJOIN_FAILED",qG[qG.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",qG[qG.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",qG[qG.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",qG[qG.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",qG[qG.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",qG[qG.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",qG[qG.OPERATION_ABORT=5998]="OPERATION_ABORT",qG[qG.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",qG);var $G=ow(rw({},wP),{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:o}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(o,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:o}=e,n="".concat(t||i.name),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(n,"' must be type of ").concat(a," when calling ").concat(r,"(), received type: ").concat($D(o),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:o}=e;return"'".concat(t||i.name,"' cannot be '").concat(o,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:o}=e,n="".concat(t||i.name),a="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(n,"' must be instanceof ").concat(a," when calling ").concat(r,"(), received type: ").concat($D(o),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:o}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(o,".")},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=ZG(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=ZG(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=ZG(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=ZG(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=ZG(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=ZG(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=ZG(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 ZG(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var ej=class e extends Error{constructor(e){let{code:t,extraCode:i,message:r="",messageParams:o,fnName:n="",originError:a,data:s}=e;var l;let c;c=r||function(e){let t,{code:i,params:r,enableDocLink:o=!1}=e,a="",s=QG[i];try{t=$G[s]}catch(n){t=$G.UNKNOWN_ERROR}return ZD(t)?a=t(r):tN(t)&&(a=t),r.fnName&&!a.includes(r.fnName)&&("."!==a[a.length-1]&&(a+="."),a+=" thrown from ".concat(r.fnName,"()")),o&&(a+=" doc:"),a}({code:t===XG.SERVER_ERROR?t:i||t,params:rw({fnName:n,error:a},o)}),super(c),cw(this,"name","RtcError"),cw(this,"code"),cw(this,"extraCode"),cw(this,"functionName"),cw(this,"message"),cw(this,"data"),cw(this,"handler"),cw(this,"originError"),this.name=QG[t],this.code=t,this.extraCode=i,this.functionName=n,this.originError=a,this.message=c,this.data=s,5302===this.extraCode&&null!=(l=this.originError)&&l.message.includes("system")&&(this.handler=()=>{let e=document.createElement("a");Zk?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):eO&&(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 o=t;if(t instanceof yw){let{stack:n}=t,a={code:XG.UNKNOWN_ERROR,fnName:i,originError:t};switch(t.getCode()){case Ew.INVALID_PARAMETER:a.code=XG.INVALID_PARAMETER,a.message=t.message;break;case Ew.INVALID_OPERATION:a.code=XG.INVALID_OPERATION;break;case Ew.NOT_SUPPORTED:case Ew.NOT_SUPPORTED_H264:a.code=XG.ENV_NOT_SUPPORTED,t.getCode()===Ew.NOT_SUPPORTED_H264&&(a.extraCode=t.message.includes(wP.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Ew.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case Ew.SERVER_TIMEOUT:case Ew.SWITCH_ROLE_FAILED:case Ew.SWITCH_ROOM_FAILED:a.code=XG.SERVER_ERROR,a.extraCode=t.getExtraCode();break;case Ew.API_CALL_ABORTED:a.code=XG.OPERATION_ABORT;break;case Ew.DEVICE_NOT_FOUND:case Ew.DEVICE_AUTO_RECOVER_FAILED:case Ew.INITIALIZE_FAILED:a.code=5300,t.name&&(a.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 Ew.VIDEO_ENCODE_FAILED:a.extraCode=5505;case Ew.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=XG.OPERATION_FAILED;break;case Ew.UNKNOWN:break;default:a.code=XG.OPERATION_FAILED}o=new e(a),n&&(o.stack+=n.substr(n.indexOf("\n")))}else{if(t instanceof e)return t;o=new e({code:XG.UNKNOWN_ERROR,fnName:i,originError:t})}return o}};var tj=ej;function ij(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function rj(e){return e===JG.QOS_PREFERENCE_CLEAR?"detail":e===JG.QOS_PREFERENCE_SMOOTH?"motion":""}function oj(e,t){let i=t?oC:rC;return rk(e)?rw(rw({},i),e):iC[e]?iC[e]:i}var nj={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}}},aj={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}}},sj={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(tN(e)&&!document.getElementById(e))throw new tj({code:XG.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},lj={name:"userId",required:!0,type:"string"},cj={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function dj(e,t){if(!e)throw new tj({code:XG.INVALID_OPERATION,extraCode:5101,fnName:t})}function uj(e,t,i){if(!e)throw new tj({code:XG.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}function hj(e,t,i){if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new tj({code:XG.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:i}})}function pj(e,t,i){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new tj({code:XG.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:i}})}function mj(e){var t;if(null==(t=null==e?void 0:e.option)||!t.small)return;if(!fL())return fM.warn("small stream is not supported"),void delete e.option.small;let i=oj(e.option.profile),r=oj(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:(fM.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 fj={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 tj({code:XG.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(tN(e.roomId))throw new tj({code:XG.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});hj(e.roomId,i,t)}else{if(!e.strRoomId)throw new tj({code:XG.INVALID_PARAMETER,extraCode:5015,fnName:i});pj(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:sj,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:nj},validate(e){var t,i;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&XP())throw new tj({code:XG.ENV_NOT_SUPPORTED,extraCode:5201});null!=(i=null==e?void 0:e.option)&&i.small&&mj(e)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:ow(rw({},sj),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:nj},validate(e){var t;null!=(t=null==e?void 0:e.option)&&t.small&&mj(e)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:cj},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&XP())throw new tj({code:XG.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:cj}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:sj,publish:{type:"boolean"},option:aj},validate(e,t,i,r,o){var n;if(null==(n=null==e?void 0:e.option)||!n.videoTrack){if(XP())throw new tj({code:XG.ENV_NOT_SUPPORTED,extraCode:5201});if(!rL())throw new tj({code:XG.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:sj,publish:{type:"boolean"},option:aj}},muteRemoteAudio:[lj,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[lj,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:sj,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){dj(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(uj(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new tj({code:XG.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:ow(rw({},sj),{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){dj(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(uj(!!r,i,e),r){if("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary)throw new tj({code:XG.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}});if(e.option){let t="main"===e.streamType?r.remoteVideoTrack:r.remoteAuxiliaryTrack;if((e.option.pictureInPicture||e.option.fullScreen||e.option.fullScreen)&&(!t.isSubscribed||!t.player.isPlaying))throw new tj({code:XG.INVALID_OPERATION,message:"cannot set pictureInPicture or fullScreen when remote video is not playing"})}}}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(e,t,i){if("*"!==e.userId&&eN(e.streamType))throw new tj({code:XG.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){dj(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(!OL)throw new tj({code:XG.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new tj({code:XG.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new tj({code:XG.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new tj({code:XG.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});dj(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 tj({code:XG.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 tj({code:XG.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new tj({code:XG.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(dj(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new tj({code:XG.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(e,t,i){if(dj(this._room.isJoined,i),this._room.useStringRoomId&&e.strRoomId===this._room.roomId||!this._room.useStringRoomId&&e.roomId===Number(this._room.roomId))throw new tj({code:XG.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 tj({code:XG.INVALID_PARAMETER,extraCode:5019,fnName:i,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId)hj(e.roomId,i,t);else{if(!e.strRoomId)throw new tj({code:XG.INVALID_PARAMETER,extraCode:5015,fnName:i});pj(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}}}},_j={TRTC:fj},gj=class extends Error{};function Ej(e,t){let i=AN(e);for(let r=0;r<t.length;r++)IN(i[r],t[r]);return i}function vj(e){this._resolve=Promise.resolve(e)}function yj(e){this._reject=Promise.reject(e)}var Tj=class e{constructor(t,i){this.instance=t,this.group=i,cw(this,"started",!1),cw(this,"ops",[]),cw(this,"startSame",()=>!0),cw(this,"mergeUpdate",Ej);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),o=[];return r&&r.forEach((e,t)=>{i.test(t)&&o.push(e)}),o}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},o=t=>{var i,r;throw this.ops.shift(),0===e&&2===(null==(i=this.currentOp)?void 0:i.type)&&this.ops.shift().reject(new gj("start failed")),null==(r=this.currentOp)||r.action(),t},n={type:e,action:()=>t(...n.args).then(r,o),args:i,resolve:vj,reject:yj};try{switch(this.state){case 1:if(0===e)throw new gj("already started");break;case 4:if(2===e)throw new gj("not started");break;default:return this.cacheOp(n)}}catch(RM){return Promise.reject(RM)}return this.ops.push(n),n.promise=t(...n.args).then(r,o)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new gj("already start");break;case 3:switch(e.type){case 2:throw new gj("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new gj("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new gj("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 gj("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new gj("start not allowed after update");case 0:throw new gj("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new gj("keep start")),new gj("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}};cw(Tj,"instances",new WeakMap);var Ij=Tj,Aj=new WeakMap,Sj=(e,t)=>{if(t instanceof gj){let{stack:i}=t;t=new tj({code:XG.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function Rj(e,t){return KU((i,r)=>function(){for(var o=arguments.length,n=new Array(o),a=0;a<o;a++)n[a]=arguments[a];let s=Ij.get(this,"string"==typeof e?e:e.call(this,...n));return s?(t&&(s.startSame=t.bind(this)),s.action(0,i.bind(this),n).catch(Sj.bind(null,r))):i.apply(this,n)})}function bj(e,t){let{merge:i,debounce:r}=t||{};return KU((t,o)=>function(){for(var n=arguments.length,a=new Array(n),s=0;s<n;s++)a[s]=arguments[s];let l=Ij.get(this,"string"==typeof e?e:e.call(this,...a));if(!l)return t.apply(this,a);if(i&&(l.mergeUpdate=i.bind(this)),r&&r.isNeedToDebounce.apply(this,a)){let{delay:e,getKey:i}=r;return new Promise((r,n)=>{var s,c;let d=null==(s=Aj.get(this))?void 0:s.get(i(...a));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout(()=>{if(3===l.state||4===l.state)return r();l.action(2,t.bind(this),a).catch(Sj.bind(null,o)).then(r,n)},e);Aj.has(this)?null==(c=Aj.get(this))||c.set(i(...a),{timeoutId:u,resolve:r}):Aj.set(this,new Map([[i(...a),{timeoutId:u,resolve:r}]]))})}return l.action(2,t.bind(this),a).catch(Sj.bind(null,o))})}function wj(e){return KU((t,i)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];let a="function"==typeof e?e.call(this,...o):e;if(a instanceof RegExp)return Promise.all(Ij.gets(this,a).map(e=>e.action(3,()=>Promise.resolve(),o))).then(()=>t.call(this,...o));let s=Ij.get(this,a);return s?s.action(3,t.bind(this),o).catch(Sj.bind(null,i)):t.apply(this,o)})}function Cj(){return function(e,t,i){return e.prototype[t]=function(){let e=this._log||console,i='"'.concat(t,'" is a static method. Use TRTC.').concat(t,"() instead. See: ").concat(Hw,"/en/TRTC.html#.").concat(t);e.warn(i)},i}}var Dj={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",REALTIME_TRANSCRIBER_MESSAGE:"realtime-transcriber-message",REALTIME_TRANSCRIBER_STATE_CHANGED:"realtime-transcriber-state-changed",PICTURE_IN_PICTURE_STATE_CHANGED:"picture-in-picture-state-changed",FULL_SCREEN_STATE_CHANGED:"full-screen-state-changed"},Nj=new Set([Dj.AUDIO_VOLUME,Dj.AUDIO_FRAME,Dj.NETWORK_QUALITY,Dj.STATISTICS,Dj.SEI_MESSAGE,Dj.CUSTOM_MESSAGE,Dj.LAYER_DATA]),kj={};aw(kj,{ScheduleRequestType:()=>Bj,getAbilityConfig:()=>Wj,getScheduleDomain:()=>Gj,isNeedToSchedule:()=>Lj,scheduleProxy:()=>Vj,sendScheduleRequest:()=>Uj,setIsNeedToSchedule:()=>xj,setScheduleProxy:()=>Fj});var Oj=null,Mj=0,Pj=1728e5,Lj=!0;function xj(e){rN(e)&&e!==Lj&&(Lj=e,fM.info("setIsNeedToSchedule ".concat(e)),e||(Mj=Date.now()+Pj))}function Uj(e){return uw(this,arguments,function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:o,userSig:n,version:a,frameWorkType:s,role:l,latencyLevel:c}=e;return function*(){var e;if(!Lj&&Oj&&Mj>Date.now())return{isCached:!0,result:Oj};let d={delta:0,count:[1,1],msg:[],detail:[]};try{let u=new FormData;u.append("userId",String(t)),u.append("sdkAppId",String(i)),u.append("isStrGroupId",String(r)),u.append("groupId",String(o)),u.append("sdkVersion",a),u.append("userSig",String(n));let h=(null==(e=yield YO())?void 0:e.model)||tM();h&&u.append("model",h);let p=aM();p&&u.append("osString",p);let m=XO();m&&u.append("gpu",m),l&&u.append("role",String(l)),c&&u.append("latencyLevel",String(c)),s&&u.append("frameWorkType",String(s));let f=mN(),_=yield function(e,t,i){return new Promise((r,o)=>{let n=null;pN([zj(e=>t.count[0]=e+1,e=>{let{error:r,retry:o,retriedCount:a,retryFuncArgs:s}=e;t.msg[0]=r.message,n||(a>=1&&(s[0]=Hj(i,"config",aC.MAIN,!0)),o())})(Hj(i,"config",aC.MAIN),e,{get timeout(){return 1e3*XD(2+t.count[0])}}),zj(e=>t.count[1]=e+1,e=>{let{error:r,retry:o,retriedCount:a,retryFuncArgs:s}=e;t.msg[1]=r.message,n||(a>=2&&(s[0]=Hj(i,"config",aC.BACKUP,!0)),o())})(Hj(i,"config",aC.BACKUP),e,{get timeout(){return 1e3*XD(2+t.count[1])}})]).then(e=>{n=e,r(n)}).catch(o)})}(u,d,i);_.config&&(_.config.loggerDomain&&xw(_.config.loggerDomain),rN(_.config.scheduleCache)&&xj(!_.config.scheduleCache)),d.delta=mN()-f;let g=function(e,t,i){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let o=performance.getEntriesByType("resource"),n=Hj(e,"config",aC.MAIN),a=Hj(e,"config",aC.BACKUP);for(let e of o)if(e.startTime>=i&&(e.name===n||e.name===a)&&e.transferSize>0){let i=e.name===n?aC.MAIN:aC.BACKUP,o=Math.round(e.duration),a=Math.round(e.domainLookupStart-e.startTime),s=e.redirectStart>0?Math.round(e.redirectEnd-e.redirectStart):0,l=e.fetchStart>0?Math.round(e.domainLookupStart-e.fetchStart):0,c=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=[c,d,u,h,p];gx.uploadEvent({log:"stat-schedule-net:".concat(o,"(").concat(a,"(").concat(s,"->").concat(l,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=ow(rw({},r),{totalCost:o,local:a,dns:c,tcp:u,tls:d,request:h,response:p});break}}catch(n){fM.error("getScheduleDetailCost error",n)}return r}(Number(i),t,f);return Oj=_,{isCached:!1,result:_,detailCost:g}}catch(yM){let t=nN(yM)?yM[0]:yM,i=iN(t.code)?t.code:0,r="schedule failed".concat(t.message?": ".concat(t.message):""),o=new yw({code:Ew.SCHEDULE_FAILED,extraCode:i,message:NP({key:bP.JOIN_ROOM_FAILED,data:{error:r,code:i}})});throw fM.error(r,i),o}}()})}"undefined"!=typeof document&&document.head.insertAdjacentHTML("beforeend",Object.values(XC).map(e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">')).join("\r\n")),dM.on("28",()=>xj(!0)),dM.on("63",()=>xj(!0)),dM.on("84",()=>xj(!0)),dM.on("201",e=>{"RECONNECTING"===e.state&&xj(!0)}),dM.on("202",e=>{"RECONNECTING"===e.state&&xj(!0)});var Vj={main:"",backup:""};function Fj(e){nN(e)?(Vj.main=e[0],Vj.backup=e[1]):(Vj.main=e,Vj.backup=e)}var Bj=(e=>(e.CONFIG="config",e.TRTC_AUTO_CONF="trtcAutoConf",e.AUDIO_AI_AUTH="audioAiAuth",e))(Bj||{});function Hj(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:aC.MAIN,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return"https://".concat(Vj[i]||Gj(e,i,r),"/api/v1/").concat(t)}function Wj(e,t,i){let r=Hj(e,t),o=Hj(e,t,aC.BACKUP),n=new URLSearchParams(i).toString(),a=fetch("".concat(r,"?").concat(n)).then(e=>e.json()),s=fetch("".concat(o,"?").concat(n)).then(e=>e.json());return pN([a,s])}function Gj(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:aC.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=MD(e)?r?i===aC.MAIN?XC.MAIN_OVERSEA_BACKUP:XC.BACKUP_OVERSEA:i===aC.MAIN?XC.MAIN_OVERSEA:XC.BACKUP_OVERSEA:i===aC.MAIN?XC.MAIN:XC.BACKUP,t}function jj(e,t,i){return new Promise((r,o)=>{QN({url:e,body:t,timeout:i.timeout,priority:"high"}).then(e=>{0===e.data.code?r(e.data.data):o({code:e.data.code,message:e.data.msg})}).catch(o)})}var zj=(e,t)=>ok({retryFunction:jj,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var Kj=class{constructor(){cw(this,"_log"),this._log=fM.createLogger({id:"fd"})}download(e,t){return uw(this,null,function*(){let{type:i="blob"}=t||{};e=xN(e);try{let t,r=mN();if(t=ZD(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let o=mN()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(o,"ms")),WP.addSuccessEvent({key:522700,cost:mN()-r}),t.data}catch(SM){throw this._log.error("failed to download: ".concat(e,", error: ").concat(SM)),WP.addFailedEvent({key:522700,error:SM}),SM}})}downloadWithFetch(e,t){return uw(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(LC){throw LC}})}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise((i,r)=>{let o=new XMLHttpRequest;o.open("GET",e,!0),o.responseType=t,o.onload=()=>{if(200===o.status||0===o.status&&o.response)i({data:o.response});else{let e=new Error("XHR failed, status: ".concat(o.status));e.status=o.status,r(e)}},o.onerror=r,o.send(null)})}loadWasm(e,t){return uw(this,null,function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=mN(),r=null,o=null;if(ZD(WebAssembly.instantiateStreaming)&&!(e=>e.startsWith("data:application/octet-stream;base64,"))(e)&&!(e=>e.startsWith("file://"))(e)&&ZD(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(kw){o=kw}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(kw){o=kw}if(r){let t=mN()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),WP.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(o)),WP.addFailedEvent({key:522701,error:o}),o})}loadScript(e){this._log.info("loadScript ".concat(e));let t=mN();return new Promise((i,r)=>{let o=document.createElement("script");o.type="text/javascript",o.onload=()=>{this._log.info("loadedScript ".concat(e,", cost: ").concat(mN()-t,"ms")),WP.addSuccessEvent({key:522702,cost:mN()-t,split:1e3}),i(o)},o.onerror=t=>{this._log.error("failed to loadScript ".concat(e,", error: ").concat((null==t?void 0:t.message)||JSON.stringify(t))),WP.addFailedEvent({key:522702}),r(t)},o.crossOrigin="anonymous",o.src=e,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)})}};lw([vx({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))}})],Kj.prototype,"download",1),lw([vx({settings:{timeout:3e3,retries:3},onRetrying(e){this._log.warn("loadScript retrying: ".concat(e))}})],Kj.prototype,"loadScript",1);var qj=new Kj;function Yj(e){let[t,i]=e,r=i.byteLength,o=parseInt(String(r/255),10),n=r%255,a=[];a.push(0,0,0,1,6,t);for(let l=0;l<o;l++)a.push(255);a.push(n);let s=new DataView(i);return a.push(...new Uint8Array(s.buffer)),a.push(128),new bB(new DataView(new Uint8Array(a).buffer),!0)}function Jj(e){return"empty"===e.type||0===e.data.byteLength}function Xj(e){let t=new DataView(e),i=0;for(;i<t.byteLength;){let e=SB(t,i);if(0===e){i+=1;continue}let r=i+e;if(r<t.byteLength&&6==(31&t.getUint8(r)))return!0;i+=e+1}return!1}function Qj(e){let t=0,i=0,r=new DataView(e);for(let o=0;o<e.byteLength;o++)switch(r.getUint8(o)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}function $j(e){let{frame:t,seiMessageList:i}=e;if(!i||0===i.length||0===t.data.byteLength)return t;let r=9-Qj(t.data);if(r<=0)return t;let o=i.splice(0,r).reverse().map(Yj),n=o.reduce((e,t)=>e+t.dataView.byteLength,0),a=new ArrayBuffer(n+t.data.byteLength),s=new DataView(a),l=new DataView(t.data),c=0;for(let d=0;d<o.length;d++)for(let e=0;e<o[d].dataView.byteLength;e++)s.setInt8(c++,o[d].dataView.getInt8(e));for(let d=0;d<t.data.byteLength;d++)s.setInt8(c++,l.getInt8(d));return t.data=a,t}function Zj(e){let{frame:t,onSEI:i}=e;try{if(Jj(t)||!Xj(t.data))return t;let e=RB(t.data,!1).filter(e=>e.isSEI);null==i||i(e.reverse())}catch(Nw){}return t}function ez(e){let{seiMessageList:t,isAudio:i,getNtpTime:r,isMain:o}=e;return new TransformStream({transform(e,n){let a=e;i?audioEncodePipeline.forEach(e=>{a=e({frame:a,ntp:r(),onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:a.data,userId:""})}})}):videoEncodePipeline.forEach(e=>{a=e({frame:a,seiMessageList:t,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:a.data,userId:"",streamType:o?"main":"auxiliary"})}})}),n.enqueue(a)}})}function tz(e){let{userId:t,streamType:i,isAudio:r}=e;return new TransformStream({transform(e,o){let n=e;r?(audioDecodePipeline.forEach(e=>{n=e({frame:n,onAudioFrameNTPTime:e=>{self.postMessage({type:"audio-ntp",data:e,userId:t,streamType:i})},onDump:()=>{self.postMessage({type:"dump",isAudio:r,data:n.data,userId:t})}})}),o.enqueue(n)):videoDecodePipeline.forEach(e=>{n=e({frame:n,onSEI:e=>{e.forEach(e=>{self.postMessage({type:"sei",seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:t,streamType:i})})},onDump:()=>{self.postMessage({type:"dump",isAudio:r,data:n.data,userId:t,streamType:i})}})}),o.enqueue(n)}})}function iz(e){let t=[bB],i=[Qj,Jj,RB,Xj,Yj,ez,tz,zN,jN,SB],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(),"];"),o="(()=>{".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=[],r=0;self.onmessage=o=>{switch(o.data.type){case"sei":o.data.isMain?(e.push(o.data.data),o.data.small&&i.push(o.data.data)):t.push(o.data.data);break;case"ntp-offset":r=o.data.data}},self.onrtctransform=o=>{let{options:n}=o.transformer,a=n.isReceiver?tz({userId:n.userId,streamType:n.streamType,isAudio:n.isAudio}):ez({getNtpTime:()=>Date.now()+r,isAudio:n.isAudio,isMain:n.isMain,seiMessageList:n.isMain?n.small?i:e:t});o.transformer.readable.pipeThrough(a).pipeTo(o.transformer.writable)}},")();").concat(r,"})()"),n=new Blob([o],{type:"text/javascript"}),a=URL.createObjectURL(n),s=new Worker(a);return URL.revokeObjectURL(a),s}var rz,oz=class{constructor(e){cw(this,"audioPlayer"),cw(this,"videoPlayer"),cw(this,"log"),this.audioPlayer=e.audioPlayer,this.videoPlayer=e.videoPlayer,this.log=e.log.createChild({id:"pip"}),this.videoPlayer.on(hx.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.on(hx.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.on(hx.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(hx.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(hx.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.on(hx.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.on(hx.VOLUME_CHANGE,this.handleVolumeChange,this)}handleUserResumeInPIPOrFullScreen(){this.audioPlayer.isPaused&&(this.log.warn("resume audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doResume()),vk&&bO&&this.videoPlayer.resetSrcObjectToReplay()}handleUserPauseInPIPOrFullScreen(){this.audioPlayer.isPaused||(this.log.warn("pause audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doPause())}handleEnterPIPOrFullScreen(){this.videoPlayer.element&&this.audioPlayer.muted!==this.videoPlayer.element.muted&&(this.log.warn("sync video muted to ".concat(this.audioPlayer.muted," when enter ").concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.videoPlayer.element.muted=this.audioPlayer.muted)}handleLeavePIP(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume after leave pip"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave pip"),this.videoPlayer.doResume())}handleLeaveFullScreen(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume audio after leave fullscreen"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave fullscreen"),vk&&bO?this.videoPlayer.resetSrcObjectToReplay():this.videoPlayer.doResume())}handleVolumeChange(e){void 0!==e.muted&&this.audioPlayer.muted!==e.muted&&(this.log.warn("sync audio muted to ".concat(e.muted," in ").concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.setMuted(e.muted))}destroy(){this.videoPlayer.off(hx.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.off(hx.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.off(hx.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(hx.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(hx.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.off(hx.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.off(hx.VOLUME_CHANGE,this.handleVolumeChange,this)}},nz=!1;function az(e){var t=this;let{TRTC:i,room:r,errorModule:o,assetsPath:n}=e;return{TRTC:i,LocalMixVideoTrack:tH,LocalVideoTrack:DB,LocalScreenTrack:oH,room:r,assetsPath:n,fileDownloader:qj,innerEmitter:dM,INNER_EVENT:hM,constants:bw,environment:ak,utils:NB,eventLogger:gx,log:this.room.getLogger(),loggerManager:fM,errorModule:o,kvStatManager:WP,rtcDectection:EM,trtc:this,rx:tV,enums:vM,schedule:kj,getDevices:RU,initVisionTaskRegistry:function(e,i){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"/mediapipe/vision.js";return uw(t,null,function*(){!window.VisionTaskRegistry&&!nz&&(nz=!0,rz=qj.loadScript("".concat(e,"/").concat(r).replace(/([^:]\/)\/+/g,"$1"))),yield rz,yield(yield window.VisionTaskRegistry.getInstance(e)).preloadModels(i)})},audioContext:sU(),deviceDetector:AU,AudioPlayer:PU,RemoteAudioPlayer:xU,VideoPlayer:Kx,showAutoPlayDialog:jx,Timer:ux,clearStarted:(e,t)=>{let i=e.getAlias(),r=Ij.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:sH,createAudioNode:mU,getNetworkTimeOffset:Tw,validateSourceNode:()=>{var e;if(Ak&&(null==(e=this.room.audioManager._localAudioPipline)||!e.source.node))throw new tj({code:XG.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})},createScriptTransformWorker:iz,AVPlayerStateSyncManager:oz,PlayerEvent:hx}}var sz=new WeakMap;var lz="5.15.1-wasm.1";function cz(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return KU((e,i)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];try{uz.call(this,t,o,i,this._name)}catch(SM){return Promise.reject(SM)}return e.apply(this,o)})}function dz(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return KU((e,i)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];try{uz.call(this,t,o,i,this._name)}catch(SM){throw SM}return e.apply(this,o)})}function uz(e,t,i,r){if(nN(e))for(let o=0;o<e.length;o++)hz.call(this,{rule:e[o],value:t[o],key:e[o].name,fnName:i,className:r});else hz.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function hz(e){let{rule:t,value:i,key:r,fnName:o,className:n}=e;function a(e){return{code:XG.INVALID_PARAMETER,extraCode:e,fnName:o,messageParams:{key:r,rule:t,value:i}}}if(eN(i)){if(t.required)throw new tj(a(5001));if(eN(t.defaultValue))return void(ZD(t.validate)&&t.validate.call(this,i,r,o,n,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),ZD(t.type[r])&&i instanceof t.type[r]&&(e=!0),tN(t.type[r])&&$D(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new tj({code:XG.INVALID_PARAMETER,extraCode:5002,fnName:o,messageParams:{key:r,rule:{type:t.type.map(e=>cN(e)?dN(e):tN(e)?e:$D(e))},value:i}})}else if(!eN(t.type)&&$D(i)!==t.type)throw new tj(a(5002));if(!1===t.allowEmpty){let e=iN(i)&&(0===i||Number.isNaN(i)),t=tN(i)&&""===i.trim();if(e||t)throw new tj(a(5003))}if(t.notLessThanZero&&iN(i)&&i<0)throw new tj(a(5006));if(!eN(t.min)&&iN(i)&&i<t.min)throw new tj(a(5007));if(!eN(t.max)&&iN(i)&&i>t.max)throw new tj(a(5008));if(tN(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new tj(a(5004))}else if(ZD(t.instanceOf)&&!(i instanceof t.instanceOf))throw new tj(a(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new tj(a(5005));let{properties:s}=t;JD(s)&&oN(i)&&Object.keys(s).forEach(e=>{hz.call(this,{rule:s[e],value:i&&i[e],key:"".concat(e),fnName:o,className:n})});let{arrayItem:l}=t;JD(l)&&nN(i)&&i.forEach((e,t)=>{hz.call(this,{rule:l,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:o,className:n})}),ZD(t.validate)&&t.validate.call(this,i,r,o,n,this)}var pz=0;function mz(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:n}=e;return KU((e,a)=>function(){for(var s=arguments.length,l=new Array(s),c=0;c<s;c++)l[c]=arguments[c];var d,u,h;function p(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...l);if(l[e.argIndex]===t)return e.value}if(t===l||e in l)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat($D(t)):t instanceof MediaStreamTrack?UN(t):(JSON.stringify(t),t)}catch(o){return"type:".concat($D(t))}}let m=(null==this?void 0:this._log)||fM,f=++pz;if(null!=o&&o(...l))return e.apply(this,l);l.length>0?m.info("".concat(a,"() ").concat(f," ").concat(JSON.stringify(l,(e,t)=>p(e,t,["userSig","privateMapKey"])))):m.info("".concat(a,"() ").concat(f));let _=r?r(...l):LP[a],g=(null==n?void 0:n(...l))||!1;try{let i=e.apply(this,l),r=mN();if(lN(i)){let e="".concat(a.includes("Plugin")?"".concat((null==(u=(d=l[0]).getName)?void 0:u.call(d))||""," "):" ");return i.then(i=>(m.info("".concat(a,"() success ").concat(f," ").concat(e).concat(t.call(this,...l))),WP.addSuccessEvent({key:_,cost:mN()-r}),i)).catch(i=>{var r;let o=(i=tj.convertFrom.call(this,i,a,1===l.length?l[0]:l)).extraCode||i.code,n=null!=(r=i.message)&&r.includes(o)?"":" code:".concat(o),s=(null==i?void 0:i.code)===XG.OPERATION_ABORT;throw g||m[s?"warn":"error"]("".concat(a,"() failed ").concat(f," ").concat(e).concat(t.call(this,...l)," ").concat(i).concat(n," params: ").concat(JSON.stringify(l,p))),WP.addFailedEvent({key:_,error:i}),i})}return WP.addSuccessEvent({key:_}),i}catch(E){let e=(E=tj.convertFrom.call(this,E,a)).extraCode||E.code,t=null!=(h=E.message)&&h.includes(e)?"":" code:".concat(e),i=(null==E?void 0:E.code)===XG.OPERATION_ABORT;throw g||m[i?"warn":"error"]("".concat(a,"() failed ").concat(f," ").concat(E).concat(t," params: ").concat(JSON.stringify(l,p))),WP.addFailedEvent({key:_,error:E}),E}})}var fz,_z=e=>KU((t,i)=>function(r,o){return uw(this,null,function*(){let n=this._plugins.get(r);if(!n)throw this._log.error("plugin ".concat(String(r)," is not found")),new tj({code:XG.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(ZD(n.constructor.isSupported)&&!n.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new tj({code:XG.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return uz.call(this,n.getValidateRule(e),[o],i,"TRTC"),t.call(this,n,o)})}),gz=0,Ez=class e{constructor(e){this.core=e,cw(this,"log"),cw(this,"customAudioReferenceMap",new Map),cw(this,"audioRefId",0),cw(this,"audioContext",sU()),cw(this,"localAudioWorkletNode"),cw(this,"screenAudioWorkletNode"),cw(this,"mixNode"),cw(this,"silentNode"),gz+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(gz)}),this.log.info("created id=".concat(this.getAlias()).concat(gz)),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,o){if(!e.room.audioManager.hasAudioTrack&&!e.room.audioManager.hasScreenAudioTrack)throw new tj({code:XG.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return fz||(fz=this.doPreload(e)),fz}doPreload(e){return uw(this,null,function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield qx(this.audioContext,i)}catch(SM){this.log.error("preload audioProcessor failed. ".concat(SM))}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 uw(this,null,function*(){var t,i,r,o;let{room:n}=this.core,{sdkAppId:a,userId:s,userSig:l,assetsPath:c=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,!c)throw new tj({code:XG.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(c,"/audioProcessor-wasm.js")),p&&!this.localAudioWorkletNode){let{sign:e,status:t,timestamp:i}=yield this.getAuthData(a,s,l);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",a,s,i,e,t,n)}if(m&&!this.screenAudioWorkletNode){let{sign:e,status:t,timestamp:i}=yield this.getAuthData(a,s,l);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",a,s,i,e,t,n)}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"}),n.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),eN(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++)})}),eN(u)||null==(r=this.localAudioWorkletNode)||r.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:u}}),eN(h)||null==(o=this.localAudioWorkletNode)||o.port.postMessage({type:"dump",data:{enable:h}})})}update(e){return uw(this,null,function*(){var t,i,r;let{audioReference:o,enableDump:n,processLevel:a}=e;eN(o)||(this.customAudioReferenceMap.forEach((e,t)=>{this.customAudioReferenceMap.delete(t),this.core.room.audioManager.updateAudioReference({type:"remove",refId:e})}),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++)})})),eN(a)||null==(t=this.localAudioWorkletNode)||t.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),eN(n)||(null==(i=this.localAudioWorkletNode)||i.port.postMessage({type:"dump",data:{enable:n}}),null==(r=this.screenAudioWorkletNode)||r.port.postMessage({type:"dump",data:{enable:n}}))})}stop(){return uw(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 uw(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:s}=yield function(e){return uw(this,arguments,function(e){let{sdkAppId:t,userId:i,userSig:r,timestamp:o}=e;return function*(){let e="".concat(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:aC.MAIN;return"https://".concat(Vj[t]||Gj(e,t),"/api/v1/audioAiAuth")}(t),"?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(r,"×tamp=").concat(o),n=yield fetch(e),{data:{errCode:a,errMsg:s,sign:l,status:c}}=yield n.json();if("1"===c)return{auth:!0,sign:l,status:c,message:s};let d=MD(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(a){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:c,message:s?"".concat(u," Reason: ").concat(s,". ").concat(h):"".concat(u,", ").concat(h)}}()})}({sdkAppId:e,userSig:i,userId:t,timestamp:r});if(!o)throw this.log.info("audioProcessor: ".concat(t," auth result: ").concat(o,". Message: ").concat(s)),new tj({code:XG.INVALID_PARAMETER,message:s});return{sign:n,status:a,timestamp:r}})}initWorkletNode(e,t,i,r,o,n,a,s){e.port.postMessage({type:"init",data:{sdkAppId:String(i),userId:r,timestamp:o,sign:n,status:a}}),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(Sw(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:s,data:r.value,type:"localAudio"===t?"dump":"dump-screen-audio"});case"detectEcho":return void this.log.warn("".concat("localAudio"===t?"":"[".concat(t,"] "),"detect echo: ").concat(KO()?eM():aM()))}}}handleLocalAudioStarted(e){return uw(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(LC){this.log.warn("audio processor auto start failed, error: ".concat(LC))}})}handleLocalAudioStopped(e){return uw(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}};cw(Ez,"updateValidateRule",{type:"object"}),cw(Ez,"stopValidateRule",{type:"object"}),cw(Ez,"Name","AudioProcessor");var vz=Ez;var yz=0,Tz=class{constructor(e,t){cw(this,"audioObjectURL"),cw(this,"player"),cw(this,"publisher"),cw(this,"mixInput"),this.mixInput=new uU(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&&(eN(e.volume)||(this.volume=e.volume),eN(e.loop)||(this.loop=e.loop),eN(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)}}reload(e){return uw(this,null,function*(){if(e.url){let t=yield qj.download(e.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(t),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(e),this.updateSettings(e))}else this.mixInput.replaceSource(e.track)})}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 Promise.all([null==(e=this.player)?void 0:e.play(),null==(t=this.publisher)?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 Iz(e,t){if(t&&"function"!=typeof t)throw new tj({code:XG.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var Az=class e{constructor(e){this.core=e,cw(this,"log"),cw(this,"mixedMusicMap",new Map),cw(this,"cacheMusicMap",new Map),yz+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(yz)}),this.log.info("created id=".concat(this.getAlias()).concat(yz))}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 uw(this,null,function*(){let{room:t}=this.core;this.core.validateSourceNode(),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 o=this.cacheMusicMap.get(i);o?e.url?o.reset():(o.mixInput.replaceSource(e.track),o.mixInput.connect()):(o=new Tz(e,t.audioManager),this.cacheMusicMap.set(i,o)),o.updateListener(e),o.updateSettings(e);try{yield o.play()}catch(kw){yield this.handleAutoPlayFailed(o,e,kw)}this.mixedMusicMap.set(i,o),o.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o.mixInput.source.node,refId:"ax-".concat(i)}),this.log.info("start mix audio track ".concat(i," success.")),WP.addEnum({key:502700,value:3}),this.kvUpload(e)})}handleAutoPlayFailed(e,t,i){return uw(this,null,function*(){if("NotSupportedError"===i.name)this.log.error("play failed, try to reload source. error: ".concat(i)),yield e.reload(t),yield e.play();else{if("NotAllowedError"!==i.name)throw i;if(this.core.room.enableAutoPlayDialog){let t=()=>{var i;null==(i=e.play())||i.finally(()=>{dM.off("154",t,this)})};dM.on("154",t,this),jx()}else this.core.trtc.emit(Dj.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>uw(this,null,function*(){return e.play()})})}})}update(e){return uw(this,null,function*(){let{id:t,operation:i,seekFrom:r,playbackRate:o}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let n=this.mixedMusicMap.get(t);n?(n.updateSettings(e),n.updateListener(e),eN(i)||n.setOperation(i),eN(r)||n.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))})}stop(e){return uw(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:o,operation:n,seekFrom:a,onTimeUpdate:s,onDurationChange:l,onEnded:c}=e;t&&WP.addCount({key:502009}),i&&WP.addCount({key:502001}),r&&WP.addCount({key:502002}),o&&WP.addCount({key:502003}),n&&WP.addCount({key:502004}),a&&WP.addCount({key:502005}),"function"!=typeof s&&WP.addCount({key:502007}),"function"!=typeof c&&WP.addCount({key:502008}),"function"!=typeof l&&WP.addCount({key:502006})}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()}};cw(Az,"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"],o=t.split(".").pop(),n=r.indexOf(o)>=0,a=t.startsWith("blob"),s=t.startsWith("data");if(!(n||a||s))throw new tj({code:XG.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new tj({code:XG.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});Iz("onTimeUpdate",e.onTimeUpdate),Iz("onEnded",e.onEnded),Iz("onDurationChange",e.onDurationChange)}}),cw(Az,"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){Iz("onTimeUpdate",e.onTimeUpdate),Iz("onEnded",e.onEnded),Iz("onDurationChange",e.onDurationChange)}}),cw(Az,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),cw(Az,"Name","AudioMixer");var Sz,Rz=Az,bz=0,wz=class e{constructor(e){this.core=e,cw(this,"log"),cw(this,"audioContext",sU()),cw(this,"workletNode"),cw(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),bz+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(bz)}),this.log.info("created id=".concat(this.getAlias()).concat(bz))}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},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(t,i,r,o){if(!e.room.audioManager.hasAudioTrack)throw new tj({code:XG.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return Sz||(Sz=this.doPreload(e)),Sz}doPreload(e){return uw(this,null,function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield qx(this.audioContext,i)}catch(SM){throw this.log.error("load worklet failed",SM),SM}finally{URL.revokeObjectURL(i)}})}getName(){return e.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return e.startValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return uw(this,null,function*(){let{room:t,schedule:i}=this.core,{assetsPath:r=this.core.assetsPath}=e;if(!r)throw new tj({code:XG.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(r,"/denoiser-wasm").concat(UL()?"":"-nosimd",".js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:o,status:n,message:a}=yield function(e,t){return uw(this,arguments,function(e,t){let{sdkAppId:i,userId:r,userSig:n,timestamp:a}=t;return function*(){try{let{data:{errCode:t,errMsg:o,sign:s,status:l}}=yield e.getAbilityConfig(i,e.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:r,userSig:n,timestamp:a});if("1"===l)return{auth:!0,sign:s,status:l,message:o};let c=MD(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(c);break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: ".concat(c);break;case 5:u="Your packages is expired. Refer to: ".concat(c);break;case 6:u="Your version is not supported."}return{auth:!1,status:l,message:o?"".concat(d," Reason: ").concat(o,". ").concat(u):"".concat(d,", ").concat(u)}}catch(o){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(o)}}}()})}(i,ow(rw({},e),{timestamp:t}));if(!r)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(r,". Message: ").concat(a)),new tj({code:XG.INVALID_PARAMETER,message:a});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:o,status:n}}),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(Sw(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.updateConfig(e),this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})})}update(e){return uw(this,null,function*(){this.updateConfig(e)})}stop(){return uw(this,null,function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)})}updateConfig(e){if(!this.workletNode)return;let t=!1;eN(e.mode)||(0===e.mode?this.config.enableFarFieldReduce=!1:1===e.mode&&(this.config.enableFarFieldReduce=!0),t=!0),eN(e.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=e.farFieldReduceThreshold,t=!0),t&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};cw(wz,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),cw(wz,"stopValidateRule",{type:"object"}),cw(wz,"Name","AIDenoiser");var Cz=wz;var Dz=sw(hw(),1),Nz=class extends Dz.EventEmitter{constructor(){super(),cw(this,"observer"),cw(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 uw(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!vk&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(Nw){gx.uploadEvent({log:"stat-pressure-detector-start-failed",error:Nw})}})}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&fM.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(LC){gx.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:LC})}}},kz=new Nz,Oz=0,Mz=class e{constructor(e){this.core=e,cw(this,"log"),cw(this,"_seiMessageList",[]),cw(this,"_smallSeiMessageList",[]),cw(this,"_subStreamSeiMessageList",[]),Oz++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(Oz)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(Oz)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:t,mediaType:i}=e;try{return $j({frame:t,seiMessageList:8===i?this._smallSeiMessageList:2===i?this._subStreamSeiMessageList:this._seiMessageList})}catch(LC){this.log.warn(LC)}return t}decode(e){let{frame:t,track:i}=e;return Zj({frame:t,onSEI:e=>{e.forEach(e=>{null!=i&&i.userId?this.core.trtc.emit(Dj.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:i.userId,streamType:2===i.mediaType?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:e})})}})}destroy(){this.log.debug("destroy"),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:NL?this.encode:$j,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:NL?this.decode:Zj,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 o=[i.seiPayloadType,t],n=!!i.small;i.toSubStream?this._subStreamSeiMessageList.push(o):(this._seiMessageList.push(o),n&&this._smallSeiMessageList.push(o)),null==(r=this.core.room.scriptTransformWorker)||r.postMessage({type:"sei",data:o,isMain:!i.toSubStream,small:n})}getName(){return e.Name}getAlias(){return"sei"}getGroup(){return"sei"}};cw(Mz,"autoStart",!0),cw(Mz,"Name","SEI");var Pz,Lz=Mz,xz=0,Uz=class e{constructor(e){this.core=e,cw(this,"_core"),cw(this,"log"),cw(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++xz)}),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 uw(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())})}update(e){return uw(this,arguments,function(e){var t=this;let{visible:i}=e;return function*(){i?yield t.openDebugDiaLog():t.closeDebugDiaLog()}()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return uw(this,null,function*(){var e;if(!this.dialog)try{if(Pz)yield Pz;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(Cw,"/assets/debug-dialog.js");Pz=this._core.fileDownloader.loadScript(t),yield Pz}this.dialog=new TRTCDebugDialog(this._core,this.log),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(Nw){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(Nw))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};cw(Uz,"Name","Debug"),cw(Uz,"autoStart",!0);var Vz=Uz,Fz=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Bz=class{constructor(e,t,i){cw(this,"trackDoneOB"),cw(this,"startOB"),cw(this,"stopOB"),cw(this,"inputFrameCount",0),cw(this,"decodedFrameCount",0),cw(this,"type","auto"),cw(this,"config"),cw(this,"decoder"),cw(this,"_decodeSink");let{kvStatManager:r,trtc:o}=e;this.config=i.config,this.trackDoneOB=KV(t,nx.INIT),this.stopOB=MV(),this.startOB=MV(),"auto"===i.type?this.type="webCodecs":this.type=i.type;let n=MV();hV(this.startOB,CV(0),zF(e=>{let i=this.pipe(t);return n.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),hV(i,mF(this.stopOB),fB(()=>{},i=>{t.log.error(i),r.addFailedEvent({key:Fz(this.type),error:i}),e>4?this.startOB.error(i):this.startOB.next(e+1)})),hV(i,pF(1),dB(oF))}),mF(this.stopOB),fB(()=>{t.player.setOutput(),n.next("STARTED")},e=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:Fz(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 yV()(t=>uw(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(SM){e.log.error(SM),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"}))}},Hz={type:"object"},Wz=class e{constructor(e){this.core=e,cw(this,"log"),cw(this,"contextMap",new Map),cw(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 Hz}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 o=new Bz(this.core,r,e);return hV(o.trackDoneOB,pF(1),fB(()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:r})})),this.contextMap.set(r,o),o.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 Bz(this.core,e.track,e))}}};cw(Wz,"Name","TRTCAudioDecoder");var Gz=Wz,jz=class{constructor(){cw(this,"log"),this.log=fM.createLogger({id:"exp"})}call(e,t){return uw(this,null,function*(){return ZD(this[e])?this[e](t):Promise.reject(new yw({code:Ew.INVALID_PARAMETER,message:NP({key:bP.API_NOT_EXIST,data:{name:e}})}))})}enableAudioFrameEvent(e){return uw(this,null,function*(){let{trtcInstance:t,enable:i,userId:r,sampleRate:o=48e3,channelCount:n=1,port:a}=e,{audioManager:s}=t.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:c}=s;if(c.set(r,{enable:i,sampleRate:o,channelCount:n,port:a}),i)if("*"===r)t.room.remotePublishedUserMap.forEach(e=>{if(e.remoteAudioTrack.isAvailable){if(l.get(e.userId))return;let i=s.getPCM(e=>{t.emit(Dj.AUDIO_FRAME,e)},e.userId);l.set(e.userId,i)}});else{if(l.get(r))return;let e=s.getPCM(e=>{t.emit(Dj.AUDIO_FRAME,e)},r);l.set(r,e)}else if("*"===r)t.room.remotePublishedUserMap.forEach(e=>{if(e.remoteAudioTrack.isSubscribed){let{userId:t}=e,i=l.get(t);null==i||i.abort("disable"),l.delete(t)}});else{let e=l.get(r);null==e||e.abort("disable"),l.delete(r)}})}resumeRemotePlayer(e){return uw(this,null,function*(){if("*"===e.userId){let t=[];return e.trtcInstance.room.remotePublishedUserMap.forEach(i=>{let{remoteAudioTrack:r,remoteVideoTrack:o,remoteAuxiliaryTrack:n}=i;e.streamType?"main"===e.streamType?(r.isAvailable&&t.push(r.player.resume()),o.isAvailable&&t.push(o.player.resume())):n.isAvailable&&t.push(n.player.resume()):(r.isAvailable&&t.push(r.player.resume()),o.isAvailable&&t.push(o.player.resume()),n.isAvailable&&t.push(n.player.resume()))}),Promise.all(t)}let t=e.trtcInstance.room.remotePublishedUserMap.get(e.userId);if(t)return"main"===e.streamType?Promise.all([t.remoteAudioTrack.player.resume(),t.remoteVideoTrack.player.resume()]):t.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(e){if("*"===e.userId)e.trtcInstance.room.remotePublishedUserMap.forEach(t=>{let{remoteAudioTrack:i,remoteVideoTrack:r,remoteAuxiliaryTrack:o}=t;e.streamType?"main"===e.streamType?(i.isAvailable&&i.player.pause(),r.isAvailable&&r.player.pause(!1)):o.isAvailable&&o.player.pause(!1):(i.isAvailable&&i.player.pause(),r.isAvailable&&r.player.pause(!1),o.isAvailable&&o.player.pause(!1))});else{let t=e.trtcInstance.room.remotePublishedUserMap.get(e.userId);t&&("main"===e.streamType?(t.remoteAudioTrack.player.pause(),t.remoteVideoTrack.player.pause(!1)):t.remoteAuxiliaryTrack.player.pause(!1))}}};lw([function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return KU((e,i)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];return EH.call(this,t,o,i,this._name),e.apply(this,o)})}({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"}}})],jz.prototype,"enableAudioFrameEvent",1);var zz=new jz,Kz=sw(hw(),1),qz=class extends Kz.EventEmitter{constructor(){super(),cw(this,"states",{}),cw(this,"permissionChangeHandler"),cw(this,"log"),this.log=fM.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 uw(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 uw(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(LC){return this.log.error("get ".concat(e," permission failed, error: ").concat(LC instanceof Error?LC.message:LC)),null}})}destroy(){Object.values(this.states).forEach(e=>{null==e||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Yz=new qz,Jz=0,Xz=new Set,Qz=null;Dw(lz),gM.checkStorage();var $z=class e extends zG.EventEmitter{constructor(t,i){super(),cw(this,"_room"),cw(this,"_eventListened",new Set),cw(this,"_localVideoTrack",null),cw(this,"_localAudioTrack",null),cw(this,"_localScreenTrack",null),cw(this,"_localScreenAudioTrack",null),cw(this,"_localVideoConfig",null),cw(this,"_localScreenConfig",null),cw(this,"_localAudioConfig",null),cw(this,"_remoteVideoConfigMap",new Map),cw(this,"_remoteAudioConfigMap",new Map),cw(this,"_remoteAudioVolumeMap",new Map),cw(this,"_remoteAudioMuteMap",new Map),cw(this,"_mediaTrackMap",new WeakMap),cw(this,"_log",fM.createLogger({id:"t".concat(++Jz)})),cw(this,"_plugins",new Map),cw(this,"_networkQuality",null),cw(this,"_speakerId"),cw(this,"enterRoomParams"),cw(this,"_enableAutoSwitchWhenRecapturing",!0),cw(this,"_autoSubscribeDataChannel",!1),this._room=new t(rw({logger:this._log,frameWorkType:e.frameWorkType},i)),this._room.videoDecodeFallbackType=i.videoDecodeFallback,rN(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(Rz,i.assetsPath),this._use(vz,i.assetsPath),this._use(Cz,i.assetsPath),this._use(Gz,i.assetsPath),this._use(Vz),i.enableSEI&&OL&&this._use(Lz),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)}),i.enableDbVolume&&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(Dj.AUDIO_VOLUME,{result:e.sort((e,t)=>t.volume-e.volume)})}),this._room.videoManager.on("error",e=>{this._log.error(new tj({code:XG.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,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];try{return i.apply(e,o)}catch(SM){let i=NP({key:bP.CATCH_HANDLER_ERROR,data:{name:t,event:o[0]},addDocLink:!1});return fM.warn("".concat(i,"\n\n").concat(SM.stack)),!1}}})(this,"trtc")}static create(e){}static _create(t,i){!function(){var e;if(YG){YG=!1,5!==fM.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Hw,"/en/index.html")),console.info("* Changelog: ".concat(Hw,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),fM.info("TRTC Web SDK Version:",Cw),HO||fM.debug("Build Time:","2026-01-23 15:22:17");let t="UA: ".concat(navigator.userAgent," \nCPU core: ").concat(navigator.hardwareConcurrency,", GPU: ").concat(XO());if(gk&&window.screen&&(window.screen.width||window.screen.height)){let e="".concat(window.screen.width,"x").concat(window.screen.height,"@").concat(window.devicePixelRatio);t+=", screen: ".concat(e)}let i=navigator.deviceMemory;i&&(t+=", minRAM: ".concat(i,"GB")),fM.info(t),fM.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),YO().then(e=>{e&&fM.info(qO)})}}();let r=new e(t,i||{});return Xz.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){fx(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(Dj.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{let{userId:t,reason:i}=e;this.emit(Dj.REMOTE_USER_EXIT,{userId:t,reason:i})}).add("banned",e=>{xj(!0),this._exitRoom().finally(()=>{this.emit(Dj.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(Dj.ERROR,tj.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(Dj.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=ow(rw({},e),{uplinkRTT:Math.min(e.uplinkRTT,lD),downlinkRTT:Math.min(e.downlinkRTT,lD)});this.emit(Dj.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(t=>{fx(t,t).add("player-state-changed",i=>{let r=ow(rw({},i),{userId:e.userId});t.kind===aC.VIDEO&&(r.streamType=ij(t.streamType)),this.emit(t.kind===aC.AUDIO?Dj.AUDIO_PLAY_STATE_CHANGED:Dj.VIDEO_PLAY_STATE_CHANGED,r)}).add("error",e=>{e.getCode()===Ew.PLAY_NOT_ALLOWED&&this.emit(Dj.AUTOPLAY_FAILED,{userId:t.userId,mediaType:t.strMediaType,resume:()=>t.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(e=>{_x(e)})}).add("remote-publish-state-changed",e=>{let{prevMuteState:t,muteState:i}=e,{userId:r}=i,o=t.audioAvailable,n=t.videoAvailable,{audioAvailable:a,videoAvailable:s}=i;a||this._remoteAudioConfigMap.delete(r),s||this._removeRemoteVideoConfig(r,"main"),i.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==s&&(s?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(s?Dj.REMOTE_VIDEO_AVAILABLE:Dj.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),o!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i}),this.emit(a?Dj.REMOTE_AUDIO_AVAILABLE:Dj.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?Dj.REMOTE_VIDEO_AVAILABLE:Dj.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"})),t.hasDatachannel!==i.hasDatachannel&&i.hasDatachannel&&this._onDataChannelAvailable()}).add("sei-message",e=>{this.emit(Dj.SEI_MESSAGE,ow(rw({},e),{streamType:ij(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(Dj.ERROR,new tj({code:XG.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var t,i,r,o,n,a,s;let l={2:"big",3:"small",7:"sub"},c={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,lD),upLoss:(null==(o=this._networkQuality)?void 0:o.uplinkLoss)||0,downLoss:(null==(n=this._networkQuality)?void 0:n.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_level)||0)/uP},video:e.msg_up_stream_info.msg_video_status.filter(e=>l[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:l[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:l[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(Dj.STATISTICS,c)}).add("custom-message",e=>{this.emit(Dj.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(Dj.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(Dj.FIRST_VIDEO_FRAME,ow(rw({},e),{streamType:ij(e.streamType)}))}).add("audio-frame",e=>{this.emit(Dj.AUDIO_FRAME,e)}).add("data-channel-message",e=>{var t,i,r,o,n;let{data:a}=e;if(""===a.sender)return;let s={segmentId:null==(t=a.payload)?void 0:t.roundid,speakerUserId:a.sender,sourceText:null==(i=a.payload)?void 0:i.text,translationTexts:null==(r=a.payload)?void 0:r.translate_msg,timestamp:null==(o=a.payload)?void 0:o.start_utc_ms,isCompleted:null==(n=a.payload)?void 0:n.end,robotId:a.robotid};""!==s.sourceText&&this.emit(Dj.REALTIME_TRANSCRIBER_MESSAGE,s)}).add("asr-robot-peer-join",e=>{this.emit(Dj.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"started",roomId:this.room.roomId,transcriberRobotId:e.userId})}).add("asr-robot-peer-leave",e=>{this.emit(Dj.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"stopped",roomId:this.room.roomId,transcriberRobotId:e.userId})}),fx(this,AU).add("audioInputAdded",e=>{this.emit(Dj.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(Dj.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(Dj.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(Dj.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>uw(this,null,function*(){if(this.emit(Dj.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Qz&&Qz.deviceId===tD){let e=(yield DU()).find(e=>e.deviceId===tD);e&&Qz.groupId!==e.groupId&&(Qz=e,this.emit(Dj.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})).add("audioOutputRemoved",e=>uw(this,null,function*(){this.emit(Dj.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield DU())[0];if(!t||!Qz||Qz.groupId===t.groupId)return;let i=Qz.deviceId===e.deviceId,r=Qz.deviceId===tD&&Qz.deviceId===t.deviceId;(i||r)&&(Qz=t,this.emit(Dj.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})),fx(this,Yz).add("permission-state-change",e=>{this.emit(Dj.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(Dj.SEI_MESSAGE,e=>{var t;let i=null==(t=this.room.remotePublishedUserMap.get(e.userId))?void 0:t.remoteVideoTrack;i&&i.updateAlphaRenderInfo(e)})}getNetworkTime(){return Iw()}use(e){let t,i;return"plugin"in e?(t=e.plugin,i=e.assetsPath):t=e,"Chorus"===t.Name&&(this.room.enableChorus=!0),this._use(t,i)}_use(t,i){let r=this._plugins.get(t.Name);if(r)return this._log.warn("duplicate install plugin",t.Name),r;let o=new t(az.call(this,{TRTC:e,room:this._room,assetsPath:i,errorModule:{RtcError:tj,ErrorCode:XG,CoreErrorCode:Ew,ErrorCodeDictionary:QG}}));return this._plugins.set(t.Name,o),o.__v_skip=!0,t.autoStart&&this.startPlugin(t.Name),o}enterRoom(t){return uw(this,null,function*(){var i,r;this.enterRoomParams=t;let{scene:o="rtc",enableAutoPlayDialog:n=!0,autoReceiveAudio:a=!0,autoReceiveVideo:s=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!tN(t.proxy)&&t.proxy.turnServer&&(null==(r=(i=this._room).setTurnServer)||r.call(i,t.proxy.turnServer,t.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=n,this._room.autoReceiveAudio=a,this._room.autoReceiveVideo=s,rN(t.preferHW)&&(this._room.preferHW=t.preferHW),t.playoutDelay&&(this._room.playoutDelay=t.playoutDelay),t.jitterBufferDelay&&(this._room.jitterBufferDelay=t.jitterBufferDelay);let l={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,enableDataChannel:this._plugins.has("RealtimeTranscriber"),frameWorkType:t.frameWorkType,component:t.component,language:t.language,priority:t.priority,useVp8:t.useVp8,useH265:t.useH265||!1,keepAlive:t.keepAlive};t.strRoomId&&!t.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(l,o,e.frameWorkType),this._checkTrackToPublish(),kz.start()})}exitRoom(){return uw(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return uw(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(LC){if(!(LC instanceof vw)||LC.code!==Ew.API_CALL_TIMEOUT&&LC.code!==Ew.SWITCH_ROOM_FAILED)throw LC;this._log.warn("switchRoom ".concat(LC.code===Ew.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(e)}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return uw(this,null,function*(){yield this.exitRoom();let t=rw(rw({},this.enterRoomParams),e);yield this.enterRoom(t)})}_clearRemoteTracks(){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=sz.get(e);t&&(t.forEach(e=>clearTimeout(e)),sz.delete(e))}(this),this._room.remotePublishedUserMap.forEach(e=>{_x(e.remoteAudioTrack),_x(e.remoteVideoTrack),_x(e.remoteAuxiliaryTrack)})}switchRole(e,t){return uw(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(){this._plugins.forEach(e=>{var t;return null==(t=e.destroy)?void 0:t.call(e)}),this._plugins.clear(),_x(this),this.removeAllListeners(),this._room.destroy(),Xz.delete(this),0===Xz.size&&kz.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),dM.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return uw(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,muteKeepVolumeDetection:o,option:n}=t,a=new AB(e._room.audioManager),s={},l={muted:!0};n&&(eN(n.microphoneId)?eN(n.audioTrack)||(s.customSource=n.audioTrack):s.deviceId=n.microphoneId,n&&iN(n.captureVolume)&&a.setCaptureVolume(n.captureVolume),eN(n.profile)||(tN(n.profile)?tC[n.profile]&&a.setProfile(tC[n.profile]):a.setProfile(n.profile)),iN(n.earMonitorVolume)&&(l.muted=!(n.earMonitorVolume>0),l.volume=n.earMonitorVolume),eN(n.echoCancellation)||(a.profile.echoCancellation=n.echoCancellation),eN(n.noiseSuppression)||(a.profile.noiseSuppression=n.noiseSuppression),eN(n.autoGainControl)||(a.profile.autoGainControl=n.autoGainControl),rN(e._enableAutoSwitchWhenRecapturing)&&(a.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),a.on("5",t=>{e.emit(Dj.ERROR,new tj({code:XG.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))}),a.on("2",t=>{e.emit(Dj.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})}),a.on("4",t=>{let i;t.error&&(i=tj.convertFrom(t.error)),e.emit(Dj.PUBLISH_STATE_CHANGED,ow(rw({},t),{error:i}))}),a.on("6",()=>{}),e._listenOutputTrackChanged(a),e._speakerId&&a.setAudioOutput(e._speakerId),yield a.capture(s),eN(r)||a.setMute(r,o),fx(a,a).add("player-state-changed",t=>{e.emit(Dj.AUDIO_PLAY_STATE_CHANGED,ow(rw({},t),{userId:""}))}),i&&e._room.isJoined&&e._room.publish(a).catch(()=>{}),e._localAudioTrack=a,e._room.capturedLocalMainAudioTrack=a,e._localAudioConfig=ow(rw({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:l,track:a}),dM.emit("113",{userId:"",room:e.room})}()})}updateLocalAudio(e){return uw(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,muteKeepVolumeDetection:r,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):eN(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),eN(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),eN(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!eN(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),eN(i)||this._localAudioTrack.setMute(i,r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),IN(this._localAudioConfig,e)})}stopLocalAudio(){return uw(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),_x(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,delete this._room.capturedLocalMainAudioTrack)})}startLocalVideo(){return uw(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,r;if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:o,publish:n=!0,capture:a=!0,mute:s,option:l}=t,c=n,d=new DB(e._room.videoManager),u={},h={};l&&(rN(l.avoidCropping)&&(d.avoidCropping=l.avoidCropping),l.cameraId?u.deviceId=l.cameraId:eN(l.useFrontCamera)?eN(l.videoTrack)||(u.customSource=l.videoTrack):u.facingMode=l.useFrontCamera?aC.FACING_MODE_USER:aC.FACING_MODE_ENVIRONMENT,eN(l.retryWhenExactFailed)||(u.retryWhenExactFailed=l.retryWhenExactFailed),l.qosPreference&&(u.contentHint=rj(l.qosPreference)),eN(l.profile)||(tN(l.profile)?iC[l.profile]&&d.setProfile(iC[l.profile]):d.setProfile(l.profile)),eN(l.fillMode)||(h.objectFit=l.fillMode),eN(l.mirror)||(h.mirror=l.mirror),eN(l.small)||(eN(l.smallMode)||(e._room.smallMode=l.smallMode),rN(l.small)&&!1===l.small?d.stopSmall():d.updateSmallConfig(oj(l.small,!0))),eN(l.rotation)||d.setRotation(l.rotation),rN(e._enableAutoSwitchWhenRecapturing)&&(d.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),d.once("first-video-frame",t=>{e.emit(Dj.FIRST_VIDEO_FRAME,ow(rw({},t),{streamType:ij(t.streamType)}))}),d.on("5",t=>{e.emit(Dj.ERROR,new tj({code:XG.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))}),d.on("2",t=>{e.emit(Dj.DEVICE_CHANGED,{type:"camera",action:"active",device:t})}),d.on("4",t=>{let i;t.error&&(i=tj.convertFrom(t.error)),e.emit(Dj.PUBLISH_STATE_CHANGED,ow(rw({},t),{error:i}))}),d.on("6",()=>{}),e._listenOutputTrackChanged(d),a?yield d.capture(u):null==(i=d.manager)||i.changeInput(d),eN(s)||(yield d.setMute(s)),fx(d,d).add("player-state-changed",t=>{e.emit(Dj.VIDEO_PLAY_STATE_CHANGED,ow(rw({},t),{userId:"",streamType:"main"}))}).add("video-size-changed",t=>{e.emit(Dj.VIDEO_SIZE_CHANGED,ow(rw({},t),{streamType:ij(t.streamType)}))}),c&&e._room.isJoined&&(e._localScreenTrack&&(null==(r=e._localScreenConfig)?void 0:r.publish)&&"main"===e._localScreenConfig.streamType?(c=!1,e._log.warn("main stream is already published, local video track will not publish")):e._room.publish(d).catch(()=>{})),e._localVideoTrack=d,e._room.capturedLocalMainVideoTrack=d,e._localVideoConfig=ow(rw({},t),{view:o,publish:c,capture:a}),yield e._updateVideoPlayOption({view:o,playOption:h,track:d})}()})}updateLocalVideo(e){return uw(this,null,function*(){var t,i,r,o;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:n,publish:a=!0,mute:s,capture:l,option:c,forcePublish:d=!1}=e,u=a||d,h={};if(this._localVideoConfig.capture)!1!==l?null!=c&&c.cameraId?yield this._localVideoTrack.switchDevice(null==c?void 0:c.cameraId):eN(null==c?void 0:c.useFrontCamera)?eN(null==c?void 0:c.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(null==c?void 0:c.videoTrack)):yield this._localVideoTrack.switchDevice(null!=c&&c.useFrontCamera?aC.FACING_MODE_USER:aC.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(l){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?aC.FACING_MODE_USER:aC.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&&(eN(c.profile)||(tN(c.profile)?iC[c.profile]&&this._localVideoTrack.setProfile(iC[c.profile]):this._localVideoTrack.setProfile(c.profile),(!c.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(c.cameraId||c.useFrontCamera?aC.FACING_MODE_USER:aC.FACING_MODE_ENVIRONMENT))&&(yield this._localVideoTrack.applyProfile())),eN(c.fillMode)||(h.objectFit=c.fillMode),eN(c.mirror)||(h.mirror=c.mirror),eN(c.rotation)||this._localVideoTrack.setRotation(c.rotation),c.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(rj(c.qosPreference)),eN(c.small)||(rN(c.small)&&!c.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(oj(c.small,!0)))),this._room.isJoined&&eN(u)&&this._localVideoConfig.publish&&l&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((null!=u?u:this._localVideoConfig.publish)||d?this._localScreenTrack&&(null==(o=this._localScreenConfig)?void 0:o.publish)&&"main"===this._localScreenConfig.streamType&&!d?(u=!1,this._log.warn("main stream is already published, local video track will not publish")):this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),eN(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:n,playOption:h,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),IN(this._localVideoConfig,ow(rw({},e),{publish:u}))})}stopLocalVideo(){return uw(this,null,function*(){var e;this._localVideoTrack&&(this._room.isJoined&&null!=(e=this._localVideoConfig)&&e.publish&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),_x(this._localVideoTrack),this._localVideoTrack=null,delete this._room.capturedLocalMainVideoTrack,this._localVideoConfig=null)})}startScreenShare(){return uw(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,o;if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:n=null,publish:a=!0,muteSystemAudio:s,option:l}=t,c=a,d=new oH(e._room.videoManager);d.on("4",t=>{let i;t.error&&(i=tj.convertFrom(t.error)),e.emit(Dj.PUBLISH_STATE_CHANGED,ow(rw({},t),{error:i}))}),d.once("first-video-frame",t=>{e.emit(Dj.FIRST_VIDEO_FRAME,ow(rw({},t),{streamType:ij(t.streamType)}))}),e._listenOutputTrackChanged(d),"main"===t.streamType&&(d.mediaType=4);let u=null,h={},p={};l&&(eN(l.profile)||(tN(l.profile)?nC[l.profile]&&d.setProfile(nC[l.profile]):d.setProfile(l.profile)),l.systemAudio&&(h.systemAudio=!0,h.echoCancellation=l.echoCancellation,h.noiseSuppression=l.noiseSuppression,h.autoGainControl=l.autoGainControl),eN(l.fillMode)||(p.objectFit=l.fillMode),l.videoTrack&&(h.videoTrack=l.videoTrack),l.audioTrack&&(h.audioTrack=l.audioTrack),l.captureElement&&(h.captureElement=l.captureElement),l.preferDisplaySurface&&(h.preferDisplaySurface=l.preferDisplaySurface),l.qosPreference&&(h.contentHint=rj(l.qosPreference)));let m=yield d.capture(h);if(d.mediaTrack.addEventListener(aC.ENDED,()=>{e._stopScreenShare(),e.emit(Dj.SCREEN_SHARE_STOPPED)}),m.getAudioTracks()[0]){u=new aH(e._room.audioManager);let o=m.getAudioTracks()[0];null!=(i=t.option)&&i.systemAudio&&!(null!=(r=t.option)&&r.audioTrack)&&(u.sourceTrack=o),yield u.setInputMediaStreamTrack(o),rN(s)&&u.mediaTrack&&(u.mediaTrack.enabled=!s),e._speakerId&&u.setAudioOutput(e._speakerId)}if(fx(d,d).add("player-state-changed",t=>{e.emit(Dj.VIDEO_PLAY_STATE_CHANGED,ow(rw({},t),{userId:"",streamType:"sub"}))}),c&&e._room.isJoined){let i=e._localVideoTrack&&(null==(o=e._localVideoConfig)?void 0:o.publish);"main"===t.streamType&&i?(c=!1,e._log.warn("main stream is already published, screen share main will not publish")):e._room.publish(d).catch(()=>{}),u&&(e._checkScreenAudioEchoCancellation(d,u),e._room.publish(u).catch(()=>{}))}e._localScreenTrack=d,e._room.capturedLocalAuxVideoTrack=d,e._localScreenAudioTrack=u,e._localScreenConfig=ow(rw({},t),{view:n,publish:c}),yield e._updateVideoPlayOption({view:n,playOption:p,track:d})}()})}updateScreenShare(e){return uw(this,null,function*(){var t,i;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,muteSystemAudio:n,option:a}=e,s=o,l={};if(a){if(eN(a.fillMode)||(l.objectFit=a.fillMode),a.qosPreference){let e=rj(a.qosPreference);this._localScreenTrack.setContentHint(e)}a.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(a.videoTrack),a.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(a.audioTrack)}if(this._room.isJoined&&!eN(s)){if(s&&!this._localScreenConfig.publish){let e=this._localVideoTrack&&(null==(t=this._localVideoConfig)?void 0:t.publish);"main"===this._localScreenConfig.streamType&&e?(s=!1,this._log.warn("main stream is already published, screen share main will not publish")):this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})}if(this._localScreenConfig.publish&&!s){let e=[this._localScreenTrack];this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),e.forEach(e=>this._room.unpublish(e).catch(()=>{}))}}null!=(i=this._localScreenAudioTrack)&&i.mediaTrack&&rN(n)&&(this._localScreenAudioTrack.mediaTrack.enabled=!n),yield this._updateVideoPlayOption({view:r,playOption:l,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),IN(this._localScreenConfig,ow(rw({},e),{publish:s}))})}stopScreenShare(){return uw(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return uw(this,null,function*(){let{view:t,userId:i,streamType:r,option:o}=e,n="".concat(i,"_").concat(r);if(this._remoteVideoConfigMap.has(n))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(r));let a=this._room.remotePublishedUserMap.get(i);if(!a)return;let s={},l="main"===r?a.remoteVideoTrack:a.remoteAuxiliaryTrack,c=this._bindRemoteVideoTrackEvents(l);this._listenOutputTrackChanged(l),o&&(eN(o.fillMode)||(s.objectFit=o.fillMode),eN(o.mirror)||(s.mirror=o.mirror),eN(o.poster)||(s.poster=o.poster),s.canvasRender=o.canvasRender,"main"===r&&!eN(o.small)&&(!a.remoteVideoTrack.isSubscribing&&!a.remoteVideoTrack.isSubscribed&&a.remoteVideoTrack.setMediaType(o.small?8:4),this._room.changeType(o.small,l.user)),eN(o.draggable)||l.setDraggable(o.draggable)),yield this._room.subscribe(l),yield this._enableVideoDecodeFallback(l,r),yield this._updateVideoPlayOption({view:t,playOption:s,track:l}),this._emitTrackEvent(l),this._remoteVideoConfigMap.set(n,{config:e,handlers:c}),o&&!eN(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:null==o?void 0:o.viewRoot})})}updateRemoteVideo(e){return uw(this,null,function*(){var t,i;let{view:r,userId:o,streamType:n,option:a,mute:s}=e,l="".concat(o,"_").concat(n),c=this._remoteVideoConfigMap.get(l);if(!c||!this._room.remotePublishedUserMap.has(o))return;let d={};a&&(eN(a.fillMode)||(d.objectFit=a.fillMode),eN(a.mirror)||(d.mirror=a.mirror));let u=null,h=this._room.remotePublishedUserMap.get(o);if("main"===n&&null!=h&&h.muteState.hasVideo&&(u=h.remoteVideoTrack),"sub"===n&&null!=h&&h.muteState.hasAuxiliary&&(u=h.remoteAuxiliaryTrack),!u)return;let{config:p}=c;"main"===n&&a&&!eN(a.small)&&this._room.changeType(a.small,u.user),a&&!eN(a.draggable)&&u.setDraggable(a.draggable),a&&(rN(a.pictureInPicture)&&(a.pictureInPicture?yield u.player.enterPictureInPicture():yield u.player.exitPictureInPicture()),rN(a.fullScreen)&&(a.fullScreen?yield u.player.enterFullscreen():yield u.player.exitFullscreen())),rN(s)&&(u.ignoreUpdatePlayingState=!0,s?(yield u.player.pause(),yield this.room.unsubscribe(u)):(yield this.room.subscribe(u),yield u.player.resume(!0))),yield this._updateVideoPlayOption({view:r,playOption:d,track:u,prevConfig:p}),IN(p,e);let m=eN(null==a?void 0:a.receiveWhenViewVisible)?null==(t=p.option)?void 0:t.receiveWhenViewVisible:a.receiveWhenViewVisible,f=eN(r)?p.view:r,_=eN(null==a?void 0:a.viewRoot)?null==(i=p.option)?void 0:i.viewRoot:a.viewRoot;this._observeView({remoteTrack:u,view:f,receiveWhenViewVisible:m,viewRoot:_})})}stopRemoteVideo(e){return uw(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return uw(this,null,function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:o,remoteAuxiliaryTrack:n}=r;"main"===e.streamType&&(o.stop(),t.hasVideo&&i.push(o)),"sub"===e.streamType&&(n.stop(),t.hasAuxiliary&&i.push(n))}for(let e of i)t&&(delete e.ignoreUpdatePlayingState,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);if(r&&(r.observer&&r.observer.disconnect(),r.handlers)){let i=this._room.remotePublishedUserMap.get(e);if(i){let e="main"===t?i.remoteVideoTrack:i.remoteAuxiliaryTrack;this._unbindRemoteVideoTrackEvents(e,r.handlers)}}this._remoteVideoConfigMap.delete(i)}_bindRemoteVideoTrackEvents(e){let t={onEnterPIP:()=>uw(this,null,function*(){yield e.player.enterPIPPromise,this.emit(Dj.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:ij(e.streamType),userId:e.userId,isPictureInPicture:!0,pictureInPictureWindow:e.player.pipWindow})}),onLeavePIP:()=>{this.emit(Dj.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:ij(e.streamType),userId:e.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(Dj.FULL_SCREEN_STATE_CHANGED,{streamType:ij(e.streamType),userId:e.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(Dj.FULL_SCREEN_STATE_CHANGED,{streamType:ij(e.streamType),userId:e.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(Dj.ERROR,new tj({code:XG.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:e=>{this.emit(Dj.VIDEO_SIZE_CHANGED,ow(rw({},e),{streamType:ij(e.streamType)}))}};return e.player.on(hx.ENTER_PICTURE_IN_PICTURE,t.onEnterPIP),e.player.on(hx.LEAVE_PICTURE_IN_PICTURE,t.onLeavePIP),e.player.on(hx.ENTER_FULL_SCREEN,t.onEnterFullScreen),e.player.on(hx.LEAVE_FULL_SCREEN,t.onLeaveFullScreen),e.on("decode-failed",t.onDecodeFailed),e.on("video-size-changed",t.onVideoSizeChanged),t}_unbindRemoteVideoTrackEvents(e,t){e.player.off(hx.ENTER_PICTURE_IN_PICTURE,t.onEnterPIP),e.player.off(hx.LEAVE_PICTURE_IN_PICTURE,t.onLeavePIP),e.player.off(hx.ENTER_FULL_SCREEN,t.onEnterFullScreen),e.player.off(hx.LEAVE_FULL_SCREEN,t.onLeaveFullScreen),e.off("decode-failed",t.onDecodeFailed),e.off("video-size-changed",t.onVideoSizeChanged)}muteRemoteAudio(e,t){return uw(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)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):!this._remoteAudioConfigMap.has(e)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:e}))}catch(SM){throw SM.code!==XG.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),SM}})}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 uw(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return uw(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return uw(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(Dj.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"realtime-transcriber-message"===e&&this._room.subscribeDataChannel(),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{Nj.has(e)||this._log.debug("emit ".concat(e," ").concat(JSON.stringify(i)))}catch(SM){}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),("realtime-transcriber-message"===t||"*"===t)&&0===this.listeners("realtime-transcriber-message").length&&this._room.unsubscribeDataChannel(),(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",o=!1;if(tN(t)?e=t:(e=t.userId,o=!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?o&&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,o=null;if(""===t)"main"===i&&this._localVideoTrack&&(o=this._localVideoTrack),"sub"===i&&this._localScreenTrack&&(o=this._localScreenTrack);else{let e=this._room.remotePublishedUserMap.get(t);e&&(o="main"===i?e.remoteVideoTrack:e.remoteAuxiliaryTrack)}return o?r&&o.outMediaTrack&&o.outMediaTrack!==o.mediaTrack?o.outMediaTrack.clone():o.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 uw(this,null,function*(){(yield DU()).forEach(t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(Dj.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),Qz=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: '.concat(Hw,"/en/TRTC.html#.setCurrentSpeaker"))})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return uw(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 o={},n=r.remoteAudioTrack;n.on("decode-failed",e=>{this.emit(Dj.ERROR,new tj({code:XG.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let r=null!=(t=this._remoteAudioVolumeMap.get(i))?t:this._remoteAudioVolumeMap.get("*"),a=iN(r)?r:100;o.volume=a,this._remoteAudioConfigMap.set(i,e),yield this._room.subscribe(n),hV(KV(n,"decode-failed"),mF(KV(n,nx.INIT)),fB(()=>{this.startPlugin(Gz.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:o,track:n}),dM.emit("115",{userId:i,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:"ra-".concat(i)})}catch(wM){throw this._remoteAudioConfigMap.delete(i),wM}this._emitTrackEvent(n)})}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return uw(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),hV(KV(e,"decode-failed"),mF(KV(e,nx.INIT)),_B(()=>{"h265"!==this._room.downlinkVideoCodec&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),qF(KV(e,"decode-downgrade-state-changed")),fB(r=>{i=r.state,this.emit(Dj.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,ow(rw({},r),{streamType:t,userId:e.userId}))},t=>{e.log.error("fallback",t)},()=>{"STARTED"===i&&e.log.info("fallback complete")})))}_updateVideoPlayOption(e){return uw(this,arguments,function(e){let{view:t,playOption:i,track:r,prevConfig:o}=e;return function*(){if(r.setMirror(i.mirror),eN(t)&&o&&o.view&&!EN(i)){let e=SN(o.view);e.length>0&&(yield r.play(e,i))}if(!eN(t)){let e=SN(t);e.length>0?yield r.play(e,i):r.stop()}}()})}_updateAudioPlayOption(e){return uw(this,arguments,function(e){var t=this;let{playOption:i={},track:r,prevConfig:o}=e;return function*(){if(!r.isPlayCalled)try{yield r.play(null,i)}catch(kw){}if(eN(i.muted)||r.setPlayerMute(i.muted),eN(i.volume)||r.setAudioVolume(i.volume/100),r instanceof AB&&r.mediaTrack){let e=!1===i.muted&&!eN(i.volume)&&i.volume>0?"add":"remove";t.room.audioManager.updateAudioReference({type:e,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof uH){let e=i.muted?0:i.volume;if(eN(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(Dj.TRACK,{userId:i,streamType:ij(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 Promise.all(r.map(e=>this._room.publish(e).catch(()=>{})))}_observeView(e){let{remoteTrack:t,view:i,receiveWhenViewVisible:r,viewRoot:o}=e;if(eN(i)||eN(r))return;let n=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(ij(t.streamType)));if(!n)return;let a=n.observer||void 0;if(null===i||nN(i)&&0===i.length||!r)return null==a||a.disconnect(),void(t.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",t.userId,t.strMediaType),this._room.subscribe(t).catch(()=>{})));let s=n.visibleViewMap||new Map,l=-1;(!a||a.root!==o)&&(null==a||a.disconnect(),s.clear(),a=new IntersectionObserver(e=>{e.forEach(e=>{s.set(e.target,e.isIntersecting),t.log.info("view ".concat(e.target.id," is").concat(e.isIntersecting?"":" not"," visible"))}),clearTimeout(l),l=window.setTimeout(()=>{[...s.values()].find(e=>e)?t.isSubscribed||this._room.subscribe(t).catch(()=>{}):t.isSubscribed&&this._room.unsubscribe(t).catch(()=>{})},200)},{root:o}));let c=new Set(SN(i));s.forEach((e,t)=>{c.has(t)||(a.unobserve(t),s.delete(t))}),c.forEach(e=>{s.set(e,!0),a.observe(e)}),a.takeRecords().forEach(e=>{s.set(e.target,e.isIntersecting)}),n.visibleViewMap=s,n.observer=a}_exitRoom(){return uw(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return uw(this,null,function*(){var e,t;if(this._localScreenTrack){if(this._room.isJoined){let t=[];null!=(e=this._localScreenConfig)&&e.publish&&t.push(this._localScreenTrack),this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield Promise.all(t.map(e=>this._room.unpublish(e).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),_x(this._localScreenTrack),this._localScreenTrack=null,delete this._room.capturedLocalAuxVideoTrack,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,t){return uw(this,null,function*(){var i,r;if(!e||!t)return;let o=null==(i=e.trackSettings)?void 0:i.displaySurface;if(!1===(null==(r=t.trackSettings)?void 0:r.echoCancellation)&&("monitor"===o||"browser"===o&&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&&(!Qz||SU(Qz))&&(this._initActiveSpeaker(),dM.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return uw(this,null,function*(){if(Qz&&!SU(Qz))this.emit(Dj.DEVICE_CHANGED,{type:"speaker",action:"active",device:Qz});else{let e=yield DU();e[0]&&!SU(e[0])?(Qz=e[0],this.emit(Dj.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(()=>{})}_onDataChannelAvailable(){if(this.listeners("realtime-transcriber-message").length>0)return this._room.subscribeDataChannel()}sendSEIMessage(e,t){var i;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:ow(rw({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),WP.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),WP.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return uw(this,null,function*(){return this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(t),")")),zz.call(e,rw({trtcInstance:this},t))})}static setLogLevel(e,t){fM.setLogLevel(e),eN(t)||(t?fM.enableUploadLog():fM.disableUploadLog())}static isSupported(){return tL(e.frameWorkType)}static getPermissions(e){return uw(this,arguments,function(e){let{request:t=!0,types:i=["camera","microphone"]}=e;return function*(){t&&(yield Yz.request(i).catch(e=>{var t;return fM.error("getPermissions request failed, error: ".concat(null!=(t=null==e?void 0:e.message)?t:e))}));let[e,r]=yield Promise.all([Yz.get("camera"),Yz.get("microphone")]);return{camera:e,microphone:r}}()})}static getCameraList(){return wU(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return bU(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return DU(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(t){return uw(this,null,function*(){if(vk&&(t===JG.SPEAKER||t===JG.HEADSET)){let i=yield e.getMicrophoneList(),r="";if(i.forEach(e=>{e.label===t&&(r=e.deviceId)}),!r)return;return void Xz.forEach(e=>uw(null,null,function*(){e._localAudioTrack&&(yield e.updateLocalAudio({option:{microphoneId:r}}))}))}(yield DU()).forEach(e=>{e.deviceId===t&&(Xz.forEach(i=>{i._setCurrentSpeaker(t),i.emit(Dj.DEVICE_CHANGED,{type:"speaker",action:"active",device:e})}),Qz=e)})})}static _addKVStat(e){let{type:t,key:i,value:r,base:o,useUV:n,version:a,max:s}=e;switch(a&&(HP.version=a),t){case"count":HP.addCount({key:i,useUV:n});break;case"enum":HP.addEnum({key:i,value:r,useUV:n});break;case"number":HP.addNumber({key:i,value:r,split:o,max:s})}}get localVideoTrack(){return this._localVideoTrack}get localScreenTrack(){return this._localScreenTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}};cw($z,"VERSION",lz),cw($z,"_loggerManager",fM),cw($z,"EVENT",Dj),cw($z,"ERROR_CODE",XG),cw($z,"TYPE",JG),cw($z,"frameWorkType",30),lw([mz({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"}})})],$z.prototype,"use",1),lw([cz(_j.TRTC.enterRoom),Rj("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}),KU(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),mz()],$z.prototype,"enterRoom",1),lw([mz()],$z.prototype,"exitRoom",1),lw([cz(_j.TRTC.switchRoom),mz(),$U()],$z.prototype,"switchRoom",1),lw([cz(_j.TRTC.switchRole),bj("room",{merge:(e,t)=>t}),mz()],$z.prototype,"switchRole",1),lw([mz()],$z.prototype,"destroy",1),lw([cz(_j.TRTC.startLocalAudio),Rj("audio",(e,t)=>{let[i]=e,[r]=t;var o,n;return(null==(o=null==i?void 0:i.option)?void 0:o.microphoneId)===(null==(n=null==r?void 0:r.option)?void 0:n.microphoneId)}),mz()],$z.prototype,"startLocalAudio",1),lw([cz(_j.TRTC.updateLocalAudio),bj("audio",{debounce:{delay:200,getKey:()=>"".concat(Jz,"-localAudio"),isNeedToDebounce:e=>{var t;return!eN(null==(t=e.option)?void 0:t.captureVolume)}}}),mz()],$z.prototype,"updateLocalAudio",1),lw([wj("audio"),mz()],$z.prototype,"stopLocalAudio",1),lw([cz(_j.TRTC.startLocalVideo),Rj("video",(e,t)=>{let[i]=e,[r]=t;var o,n;return(null==(o=null==i?void 0:i.option)?void 0:o.cameraId)===(null==(n=null==r?void 0:r.option)?void 0:n.cameraId)}),mz()],$z.prototype,"startLocalVideo",1),lw([cz(_j.TRTC.updateLocalVideo),bj("video"),mz()],$z.prototype,"updateLocalVideo",1),lw([wj("video"),mz()],$z.prototype,"stopLocalVideo",1),lw([cz(_j.TRTC.startScreenShare),Rj("screen",()=>!0),mz()],$z.prototype,"startScreenShare",1),lw([cz(_j.TRTC.updateScreenShare),bj("screen"),mz()],$z.prototype,"updateScreenShare",1),lw([mz()],$z.prototype,"stopScreenShare",1),lw([cz(_j.TRTC.startRemoteVideo),Rj(e=>"v".concat(e.userId).concat(e.streamType),()=>!0),mz({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],$z.prototype,"startRemoteVideo",1),lw([cz(_j.TRTC.updateRemoteVideo),bj(e=>"v".concat(e.userId).concat(e.streamType)),mz({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],$z.prototype,"updateRemoteVideo",1),lw([cz(_j.TRTC.stopRemoteVideo),KU(e=>function(t){return uw(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)})}),mz({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],$z.prototype,"stopRemoteVideo",1),lw([wj(e=>"v".concat(e.userId).concat(e.streamType))],$z.prototype,"_stopRemoteVideo",1),lw([cz(..._j.TRTC.muteRemoteAudio),mz({getRemoteId:e=>e})],$z.prototype,"muteRemoteAudio",1),lw([dz(..._j.TRTC.setRemoteAudioVolume),function(e,t){return KU((i,r)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];let a=sz.get(this);a||(a=new Map,sz.set(this,a));let s=t(...o),l=a.get(s);if(!l||l<=0){i.apply(this,o);let t=setTimeout(()=>{var e;null==(e=sz.get(this))||e.delete(s)},e);a.set(s,t)}else{clearTimeout(l);let t=window.setTimeout(()=>{var e;i.apply(this,o),null==(e=sz.get(this))||e.delete(s)},e);a.set(s,t)}})}(200,e=>e),mz({getRemoteId:e=>e})],$z.prototype,"setRemoteAudioVolume",1),lw([_z("start"),zU(e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)}),Rj((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),mz({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>xP[e.getName()],ignoreLog:e=>"Debug"===e.getName(),ignoreErrorLog:e=>"AudioProcessor"===e.getName()})],$z.prototype,"startPlugin",1),lw([_z("update"),bj((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(IN(e[1],t[1]),e)}),mz({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>UP[e.getName()]})],$z.prototype,"updatePlugin",1),lw([_z("stop"),wj((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i}),mz({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>VP[e.getName()]})],$z.prototype,"stopPlugin",1),lw([dz(..._j.TRTC.enableAudioVolumeEvaluation)],$z.prototype,"enableAudioVolumeEvaluation",1),lw([mz()],$z.prototype,"getVideoSnapshot",1),lw([mz()],$z.prototype,"_setCurrentSpeaker",1),lw([Rj(e=>"a".concat(e.userId),()=>!0)],$z.prototype,"_startRemoteAudio",1),lw([KU(e=>function(t){return uw(this,null,function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(ow(rw({},t),{userId:e.userId})).catch(()=>{}))):e.call(this,t)})}),wj(e=>"a".concat(e.userId))],$z.prototype,"_stopRemoteAudio",1),lw([wj("room")],$z.prototype,"_exitRoom",1),lw([wj("screen")],$z.prototype,"_stopScreenShare",1),lw([cz(..._j.TRTC.sendSEIMessage),KG({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}})],$z.prototype,"sendSEIMessage",1),lw([cz(_j.TRTC.sendCustomMessage),KG({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],$z.prototype,"sendCustomMessage",1),lw([Cj()],$z,"create",1),lw([cz(_j.TRTC.create)],$z,"_create",1),lw([Cj()],$z,"setLogLevel",1),lw([Cj()],$z,"isSupported",1),lw([Cj(),mz()],$z,"getPermissions",1),lw([Cj()],$z,"getCameraList",1),lw([Cj()],$z,"getMicrophoneList",1),lw([Cj()],$z,"getSpeakerList",1);var Zz=$z,eK=class{constructor(e,t){cw(this,"_flag"),cw(this,"terminalType"),cw(this,"userId"),cw(this,"tinyId"),cw(this,"role"),cw(this,"remoteAudioTrack"),cw(this,"remoteVideoTrack"),cw(this,"remoteAuxiliaryTrack"),this.userId=t.userId||"",this.tinyId=t.tinyId||"",this.role=t.role||"audience",this.terminalType=t.terminalType,this.remoteAudioTrack=new uH(e,this),this.remoteVideoTrack=new pH(e,this),this.remoteAuxiliaryTrack=new mH(e,this),this.flag=t.flag||0}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 vN(this.flag,this.userId)}get flag(){return this._flag}set flag(e){if(e===this._flag)return;let t,i=this.muteState;this._flag=e;let r=this.muteState;for(t in r)i[t]!=r[t]&&console.log(this.userId,t,i[t],"->",r[t]);this.remoteAudioTrack.onFlagChanged(),this.remoteVideoTrack.onFlagChanged(),this.remoteAuxiliaryTrack.onFlagChanged()}},tK=class{constructor(){cw(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:o}=e;return"rtc"!==o.scene&&this._set.has(this.getKey(t,i,r,o.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 iK(){return uw(this,null,function*(){let e,t;try{let t=yield bU();e=t&&t.length}catch(p){}try{let e=yield wU();t=e&&e.length}catch(p){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:n,isVp8DecodeSupported:a,isH265EncodeSupported:s,isH265DecodeSupported:l}=this.checkSystemResult.detail,c=EM.basis(),d={webRTC:c.isWebRTCSupported,getUserMedia:c.isGetUserMediaSupported,webSocket:c.isWebSocketsSupported,screenShare:c.isScreenShareSupported,webAudio:c.isWebAudioSupported,h264Encode:r,h264Decode:n,vp8Encode:o,vp8Decode:a,h265Encode:s,h265Decode:l},u={browser:c.browser,os:c.os,trtc:d,devices:i},h={isWebCodecSupported:c.isWebCodecSupported,isMediaSessionSupported:c.isMediaSessionSupported,isWebTransportSupported:c.isWebTransportSupported};gx.uploadEvent({log:"trtcstats-".concat(JSON.stringify(u)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(u))),gx.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(h)),userId:this.userId}),KL()})}var rK=class{constructor(e){cw(this,"_frameWorkType"),cw(this,"_component"),cw(this,"_language"),cw(this,"connectionType"),cw(this,"_room"),cw(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0}),cw(this,"_keyPrefix"),cw(this,"_log"),cw(this,"_intervalId"),cw(this,"_firstPublishedUserList"),cw(this,"_networkQuality"),cw(this,"_basicInfo"),cw(this,"_pathJoinRoom"),cw(this,"_pathLeaveRoom"),cw(this,"_pathMainVideoMap"),cw(this,"_pathMainAudioMap"),cw(this,"_pathAuxiliaryMap"),cw(this,"_remoteStreamStatMap"),cw(this,"_localStreamStat"),cw(this,"_eventMap",new Map),cw(this,"_captureCostSum",0),cw(this,"_captureCostCount",0),cw(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=fM.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&ZD(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,r=new Array(e),o=0;o<e;o++)r[o]=arguments[o];let n=t.apply(i,r);return lN(n)?n.catch(e=>fM.error("".concat(t.name,"() error observed ").concat(e))):n}catch(LC){fM.error("".concat(t.name,"() error observed ").concat(LC))}}}({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:Cw,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,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,YO().then(()=>{this._basicInfo.string_os_version=aM(),this._basicInfo.string_device_name=eM()||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===aC.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 o=i.hasAudio||i.hasVideo||i.hasSmall,n=i.hasAuxiliary,a=r.hasAudio||r.hasVideo||r.hasSmall,s=r.hasAuxiliary;!o&&a&&this.handleRemoteStreamAdded(r.userId,"main"),!n&&s&&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(),ux.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&&(eN(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),eN(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),eN(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:o,tls:n,request:a,response:s}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=r,this._pathJoinRoom.int32_schedule_tcp=o,this._pathJoinRoom.int32_schedule_tls=n,this._pathJoinRoom.int32_schedule_request=a,this._pathJoinRoom.int32_schedule_response=s}}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 yw?Number(i.getExtraCode()||i.getCode()):Ew.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){var t;if(this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time){if(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;let e=null==(t=this._room.audioManager.localAudioTrack)?void 0:t.after3aSilenceStartTime;e&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=mN()-e)}else 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 yw?Number(i.getExtraCode()||i.getCode()):Ew.UNKNOWN)}}handleRemoteStreamAdded(e,t){var i;let r="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(r)){let o={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:ow(rw({},nK),{msg_user_info:new aK({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};o.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(r,o)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:r,subscribeState:o}=e;if(!this.hitTest(t))return;let{userId:n,tinyId:a,role:s}=i,l=new aK({userId:n,tinyId:a,role:"anchor"===s?20:21}),c=Date.now(),d="".concat(n,"_").concat(r),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=c),"main"===r?(i.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:l,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:n,sendSubscribeCMDTime:c}),i.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:l,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:n,sendSubscribeCMDTime:c})):i.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:c})}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),o=this._remoteStreamStatMap.get(t);if(o){let{statsToReport:t}=o;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,WP.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:o,audioDelay:n}=e,a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=t,a.totalLoss+=i,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let e,a,s,l;o&&(a=o,s=1),n&&(e=n,l=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:a,audioDelayCount:l,videoDelayCount:s})}}))}handleHeartbeatStats(e){var t;if(this.hitTest(e.room)){let{msg_device_info:i,msg_up_stream_info:r,msg_down_stream_info:o}=e.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:t,uint32_video_width:i,uint32_video_height:o}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=t,this._localStreamStat.totalVideoWidth+=i,this._localStreamStat.totalVideoHeight+=o,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:e}=r.msg_audio_status;Math.floor(e/uP*100)>0&&(this._localStreamStat.totalAudioLevel+=e/uP,this._localStreamStat.audioLevelCount++)}o.forEach(e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:r}=e,o=t.str_identifier,n=this._room.remotePublishedUserMap.get(o);if(r.forEach(e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,r="".concat(o,"_").concat(t?"main":"auxiliary"),a=this._remoteStreamStatMap.get(r);if(a&&(t&&null!=n&&n.remoteVideoTrack.isSubscribed||i&&null!=n&&n.remoteAuxiliaryTrack)){a.totalVideoFPS+=e.uint32_video_receive_fps,a.totalVideoBitrate+=e.uint32_video_codec_bitrate,a.videoCount++,0===a.statsToReport.uint32_video_width&&(a.statsToReport.uint32_video_width=e.uint32_video_width),0===a.statsToReport.uint32_video_height&&(a.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?n.remoteVideoTrack:n.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(a.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(a.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*tw(10,6)))}}),!EN(i)){let e="".concat(o,"_main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&null!=n&&n.remoteAudioTrack.isSubscribed&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,n.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=n.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/uP*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/uP,t.audioLevelCount++),i.uint32_audio_block_time&&(t.statsToReport.uint32_audio_block_time+=i.uint32_audio_block_time))}}),i.uint32_audio_capture_cost&&(this._captureCostSum+=i.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)),0===i.uint32_audio_capture_cost&&!1===(null==(t=this._room.audioManager.localAudioTrack)?void 0:t.muted)&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}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 yw?i.getExtraCode()||i.getCode():Ew.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&dC)>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&pC)>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&hC)>=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:o,videoDelayCount:n,totalAudioDelay:a,totalVideoDelay:s}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),o&&a&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(a/o),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),n&&s&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(s/n))}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:o}=this._room;o&&(e.statsToReport.uint32_audio_play_time=o.getDuration(t,aC.AUDIO),e.statsToReport.uint32_video_play_time=o.getDuration(t,aC.VIDEO)),e.statsToReport.uint32_video_render_first&&(e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,oK));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:s}=n.getDataFreezeDuration(t),{renderFreeze:l}=n.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=s,e.statsToReport.uint32_video_block_time=Math.min(a,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(l,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_audio_block_time=Math.min(e.statsToReport.uint32_audio_block_time,e.statsToReport.uint32_audio_play_time),n.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>oK&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+oK):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>oK&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+oK):this._pathMainVideoMap.delete(t)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>oK&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+oK)}getReportData(){this._basicInfo.uint32_networkType=HD();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new aK({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:TN(this._signalInfo.relayIp),uint32_client_ip:TN(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*tw(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:TN(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return MN(e),e}report(){return uw(this,null,function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(AM){this._log.warn(AM)}finally{this.isDestroyed&&(this._room=null)}})}upload(e){return uw(this,null,function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=pM.enable?GN(e,2001,t):yield $N(e),r=i instanceof ArrayBuffer,o="".concat(PD(t,Yw.KEY_POINT),"&gzip=").concat(+r),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,i));let a=[this.uploadKVStat(WP),this.uploadKVStat(HP)];n||a.push(QN({url:o,body:i,priority:"low"})),yield Promise.all(a)})}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return uw(this,arguments,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this._room.sdkAppId;return function*(){var r,o;let n=e.getReportData(null==(r=t._room)?void 0:r.userSig,null==(o=t._signalInfo)?void 0:o.reportToken);if(0===n.stats_count.length&&0===n.stats_distribution.length)return;n.msg_sdk_basic_info=ow(rw({},n.msg_sdk_basic_info),{bytes_device_name:t._basicInfo.string_device_name||"",bytes_os_version:t._basicInfo.string_os_version||"",uint32_framework:t._frameWorkType,uint32_network_type:t._basicInfo.uint32_networkType||0}),t._log.debug(n);let a=pM.enable?GN(n,2003,i):yield $N(n),s=a instanceof ArrayBuffer,l="".concat(PD(+i,Yw.KV_STAT),"&gzip=").concat(+s),c=!1;navigator.sendBeacon&&(c=navigator.sendBeacon(l,a)),c||QN({url:l,body:a})}()})}};lw([vx({settings:{timeout:500,retries:3}})],rK.prototype,"upload",1);var oK=5e3,nK={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},aK=class{constructor(e){cw(this,"str_identifier"),cw(this,"str_tinyid"),cw(this,"uint32_role"),this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},sK=rK,lK=class{constructor(){cw(this,"_startTime"),cw(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=mN())}stop(){0===this._endTime&&(this._endTime=mN())}getDuration(){return 0===this._endTime?mN()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},cK=class{constructor(e){cw(this,"_room",null),cw(this,"_durationMap"),cw(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 o;let{userId:n}=r;if(!this.hitTest(t))return;i.hasAudio&&!r.hasAudio&&this.stopDurationItem("".concat(n,"_main"),aC.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(n,"_main"),aC.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(n,"_auxiliary"),aC.VIDEO);let a=null==(o=this._room)?void 0:o.remotePublishedUserMap.get(n);a&&(!i.hasAudio&&r.hasAudio&&a.remoteAudioTrack.isSubscribed&&this.addDuractionItem(n,aC.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&a.remoteVideoTrack.isSubscribed&&this.addDuractionItem(n,aC.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&a.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(n,aC.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:o}=t;t.isSubscribed?this.addDuractionItem(i,o,r):this.stopDurationItem("".concat(i,"_").concat(r),o)}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),o=new lK,n=this._durationMap.get(r);n?this.isRecording(n[t])||n[t].push(o):this._durationMap.set(r,{userId:e,type:i,audio:t===aC.AUDIO?[o]:[],video:t===aC.AUDIO?[]:[o]})}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()}},dK=class{constructor(){cw(this,"renderFreezeMap",new Map),cw(this,"dataFreezeMap",new Map)}get(e,t){let i=this.renderFreezeMap.get(e),r=this.dataFreezeMap.get(e);return t?"data"===t?r:i:(DO||Ak)&&i&&r&&i.duration>r.duration?i:r}set(e,t,i){"data"===i?this.dataFreezeMap.set(e,t):this.renderFreezeMap.set(e,t)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},uK=class{constructor(e){cw(this,"_room"),cw(this,"_renderFreezeMap",new Map),cw(this,"_isVideoPlayingEventFiredMap",new Map),cw(this,"_dataFreezeMap",new Map),cw(this,"_monitorFreezeData",new dK),cw(this,"_eventMap",new Map),cw(this,"_videoEncodeFailedCount",0),cw(this,"_audioEncodeFailedCount",0),cw(this,"_encodeFailedThreshold",3),cw(this,"ABNORMAL_TIME_LOWER_LIMIT",3e3),cw(this,"ABNORMAL_TIME_UPPER_LIMIT",5e3),cw(this,"_videoAbnormalTimestampMap",new Map),cw(this,"_remoteVideoAbnormalTimestampMap",new Map),cw(this,"_audioAbnormalTimestampMap",new Map),cw(this,"eventListenerMap",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:o}=r,n="".concat(o,"_").concat(i);this.stopDataFreeze({key:n,userId:o,type:i})}).set(hM.REMOTE_PUBLISH_STATE_CHANGED,e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let{userId:o}=r;if(i.hasVideo&&!r.hasVideo){let e="main",t="".concat(r.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:o,type:e})}if(i.hasAuxiliary&&!r.hasAuxiliary){let e="auxiliary",t="".concat(r.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:o,type:e})}}).set(hM.PLAYER_STATE_CHANGED,e=>{let{track:t,state:i,reason:r,type:o}=e;if(t.isRemote&&t.room&&this.hitTest(t.room)&&o===aC.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===aC.MUTE?this.onVideoTrackMuted(t):r===aC.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(hM.HEARTBEAT_REPORT,this.onHearBeatReport).set(hM.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(hM.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),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),o=this._dataFreezeMap.get(r),n=new lK;o?o.durationItemList.push(n):this._dataFreezeMap.set(r,{userId:t,type:i,durationItemList:[n],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)&&(this.localMediaTrackDetector(i),this.remoteMediaTrackDetector(i))}remoteMediaTrackDetector(e){e.msg_down_stream_info.length>0&&e.msg_down_stream_info.forEach(e=>{var t;if(0===e.msg_video_status.length)return;let i=e.msg_user_info.str_identifier,r=null==(t=this._room.remotePublishedUserMap.get(i))?void 0:t.remoteVideoTrack;e.msg_video_status.forEach(e=>{let t=mN();if(void 0!==e.uint32_video_codec_bitrate&&e.uint32_video_codec_bitrate>0&&0===e.uint32_video_receive_fps&&null!=r&&r.muted)if(this._remoteVideoAbnormalTimestampMap.has("".concat(i,"-decode"))){let e=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-decode"));e&&t-e>this.ABNORMAL_TIME_LOWER_LIMIT&&t-e<this.ABNORMAL_TIME_UPPER_LIMIT&&gx.uploadEvent({userId:this._room.userId,log:"stat-".concat(UC.VIDEO_DECODE_FAILED_DURING_CALL)})}else this._remoteVideoAbnormalTimestampMap.set("".concat(i,"-decode"),t);else{let e=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-decode"));e&&t-e>=this.ABNORMAL_TIME_UPPER_LIMIT&&(gx.uploadEvent({userId:this._room.userId,log:"stat-".concat(UC.VIDEO_DECODE_RESUME_DURING_CALL)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(i,"-decode")))}if(void 0!==e.uint32_video_codec_bitrate&&e.uint32_video_codec_bitrate>5e5&&void 0!==e.uint32_video_dec_fps&&e.uint32_video_dec_fps<=5)if(this._remoteVideoAbnormalTimestampMap.has("".concat(i,"-hardware"))){let r=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-hardware"));if(r&&t-r>this.ABNORMAL_TIME_LOWER_LIMIT/2&&t-r<2*this.ABNORMAL_TIME_UPPER_LIMIT){gx.uploadEvent({userId:this._room.userId,log:"stat-".concat(UC.VIDEO_HARDWARE_DECODE_FAILED)});let t=this._room.remotePublishedUserMap.get(i);if(t){let i=2===e.uint32_video_stream_type?t.remoteVideoTrack:t.remoteAuxiliaryTrack;i&&(i.log.warn("decode failed during call"),i.emit("decode-failed-during-call"))}}}else this._remoteVideoAbnormalTimestampMap.set("".concat(i,"-hardware"),t);else{let e=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-hardware"));e&&t-e>=2*this.ABNORMAL_TIME_UPPER_LIMIT&&(gx.uploadEvent({userId:this._room.userId,log:"stat-".concat(UC.VIDEO_HARDWARE_DECODE_RESUME)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(i,"-hardware")))}})})}localMediaTrackDetector(e){if(e.msg_up_stream_info.msg_video_status){let t=e.msg_up_stream_info.msg_video_status,i=Array.from(this._room.localTracks).find(e=>"video"===e.kind&&!e.isScreen),r=(null==i?void 0:i.stat.bytesSent)||0;if(!1===(null==i?void 0:i.isMediaTrackActive)||r<=0||null!=i&&i.isUseCustomSource)return;t.forEach(e=>{let t=mN();if(2===e.uint32_video_stream_type)if(0!==e.uint32_video_capture_fps&&0===e.uint32_video_codec_bitrate&&0===e.uint32_video_enc_fps&&null!=i&&i.isPublished)if(this._videoAbnormalTimestampMap.has("local-encode")){let e=this._videoAbnormalTimestampMap.get("local-encode");e&&t-e>this.ABNORMAL_TIME_LOWER_LIMIT&&t-e<this.ABNORMAL_TIME_UPPER_LIMIT&&gx.uploadEvent({userId:this._room.userId,log:"stat-".concat(UC.VIDEO_ENCODE_FAILED_DURING_CALL)})}else this._videoAbnormalTimestampMap.set("local-encode",t);else{let e=this._videoAbnormalTimestampMap.get("local-encode");e&&t-e>=this.ABNORMAL_TIME_UPPER_LIMIT&&gx.uploadEvent({userId:this._room.userId,log:"stat-".concat(UC.VIDEO_ENCODE_RESUME_DURING_CALL)}),this._videoAbnormalTimestampMap.delete("local-encode")}})}if(e.msg_up_stream_info.msg_audio_status){let t=e.msg_up_stream_info.msg_audio_status,i=Array.from(this._room.localTracks).find(e=>"audio"===e.kind),r=(null==i?void 0:i.stat.bytesSent)||0;if(!1===(null==i?void 0:i.isMediaTrackActive)||r<=0||null!=i&&i.isUseCustomSource)return;let o=mN();if(0===t.uint32_audio_codec_bitrate&&null!=i&&i.isPublished)if(this._audioAbnormalTimestampMap.has("local-encode")){let e=this._audioAbnormalTimestampMap.get("local-encode");e&&o-e>this.ABNORMAL_TIME_LOWER_LIMIT&&o-e<this.ABNORMAL_TIME_UPPER_LIMIT&&gx.uploadEvent({userId:this._room.userId,log:"stat-".concat(UC.AUDIO_ENCODE_FAILED_DURING_CALL)})}else this._audioAbnormalTimestampMap.set("local-encode",o);else{let e=this._audioAbnormalTimestampMap.get("local-encode");e&&o-e>=this.ABNORMAL_TIME_UPPER_LIMIT&&gx.uploadEvent({userId:this._room.userId,log:"stat-".concat(UC.AUDIO_ENCODE_RESUME_DURING_CALL)}),this._audioAbnormalTimestampMap.delete("local-encode")}}}stopDataFreeze(e){let{key:t,userId:i,type:r}=e,o=this._dataFreezeMap.get(t);if(!o||!o.isFreezing())return;let n=o.durationItemList[o.durationItemList.length-1];n.stop();let a=n.getDuration();if(a>zC){let e=this._monitorFreezeData.get(t,"data");this._monitorFreezeData.set(t,{userId:i,type:r,duration:e?e.duration+a:a},"data")}else o.durationItemList.pop()}getTotalDuration(e){return e.reduce((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)},0)}onPlayTrackStart(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room)||t.kind!==aC.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()<zC&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){let t={renderFreeze:0,count:0},i=this._renderFreezeMap.get(e);return i&&(t.renderFreeze=i.totalDuration,t.count=i.count),t}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}onRemoteVideoPlayStart(e){let{track:t,player:i}=e;var r;if(!WL())return;let o=0,n=()=>{document.hidden||(o=0)};document.addEventListener("visibilitychange",n);let a=(e,r)=>{var n;if(o){let e=t.decodeFPS,i=e>0&&e<=5?600+1e3/e:600,n=r.presentationTime-o;if(n>i){n=Math.min(n,5e3);let e="".concat(t.userId,"_").concat(t.streamType),i=this._monitorFreezeData.get(e,"render");i?i.duration+=n:this._monitorFreezeData.set(e,{userId:t.userId,type:t.streamType,duration:n},"render");let r=this._renderFreezeMap.get(e);r?(r.totalDuration+=n,r.count+=1):this._renderFreezeMap.set(e,{userId:t.userId,type:t.streamType,totalDuration:n,count:1})}}o=r.presentationTime,null==(n=i.element)||n.requestVideoFrameCallback(a)};null==(r=i.element)||r.requestVideoFrameCallback(a),this.eventListenerMap.set("".concat(t.userId,"_").concat(t.streamType),{onVisibilityChange:n})}onRemoteVideoPlayEnd(e){let{track:t,player:i}=e,r="".concat(t.userId,"_").concat(t.streamType),o=this.eventListenerMap.get(r);o&&document.removeEventListener("visibilitychange",o.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},hK=sw(hw(),1),pK=class{constructor(e,t,i,r,o){let n=arguments.length>5&&void 0!==arguments[5]?arguments[5]:4/3;this.vbMode=e,this.faceDetectorHash=i,this.visionTaskRegistry=r,this.logger=o,cw(this,"animationState"),cw(this,"originalAspect"),cw(this,"totalOffsetX",0),cw(this,"totalOffsetY",0),cw(this,"defaultScaleRatio",.1),cw(this,"isRecovering",!1),cw(this,"boundaryY",280),cw(this,"lastActionTime",0),cw(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,this.visionTaskRegistry.setVideo(this.faceDetectorHash,t)}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?WP.addSuccessEvent({key:r.key}):WP.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,o=t.originX,n=t.originY,a=t.width,s=t.height;1===this.vbMode?this.dualStageCropping(i,r,o,n,a,s):2===this.vbMode&&this.movingPortrait(i,r,o,n,a,s)}catch(CM){this.logger.error(CM)}this.lastActionTime=t}calculateBoundary(e,t,i,r){let o,n;return e>t/2?(o=t-i-r,n=i-o):(o=i,n=0),{min:o,offset:n}}calculateTargetPosition(e,t,i,r,o,n){let a,s,l=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.4,c=e+i/2,d=t+r/2,{min:u,offset:h}=this.calculateBoundary(c,o,e,i),{min:p,offset:m}=this.calculateBoundary(d,n,t,r);return a=2*u+i,s=2*p+r,a/s>this.originalAspect?(a=s*this.originalAspect,h=c-a/2):(s=a/this.originalAspect,m=d-s/2),i/o>l&&(h=0,m=0,a=o,s=n),h=Math.max(0,Math.min(h,o-a)),m=Math.max(0,Math.min(m,n-s)),{sx:h,sy:m,cropWidth:a,cropHeight:s,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),o=this.positionDistance(this.animationState.current,e),n=this.animationState.current.cropWidth/t;r>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&o>this.animationState.movementThreshold*n&&(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=rw({},e),void(this.animationState.target=rw({},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)),iN(this.animationState.current.scaleOffsetX)&&iN(this.animationState.target.scaleOffsetX)&&iN(this.animationState.current.scaleOffsetY)&&iN(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(tw(e.sx-t.sx,2)+tw(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,o,n){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.3;if(this.isRecovering)return;let s=this.calculateTargetPosition(i,r,o,n,e,t);this.processFacePositionCrop(s,e,t),o*n/s.cropWidth/s.cropHeight>a&&this.recoverOriginal(e,t)}movingPortrait(e,t,i,r,o,n){var a,s,l,c,d,u,h,p,m,f,_,g;let E={sx:i+o/2+this.totalOffsetX,sy:r+n/2+this.totalOffsetY,cropWidth:e,cropHeight:t,scaleRatio:null!=(s=null==(a=this.animationState.current)?void 0:a.scaleRatio)?s:1,scaleOffsetX:null!=(c=null==(l=this.animationState.current)?void 0:l.scaleOffsetX)?c: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+n/2,cropWidth:e,cropHeight:t,scaleRatio:null!=(p=null==(h=this.animationState.target)?void 0:h.scaleRatio)?p:1,scaleOffsetX:null!=(f=null==(m=this.animationState.target)?void 0:m.scaleOffsetX)?f:0,scaleOffsetY:null!=(g=null==(_=this.animationState.target)?void 0:_.scaleOffsetY)?g:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(o*n/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}},mK=class extends jB{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}),cw(this,"_bgTexture"),cw(this,"_waterMarkTexture"),cw(this,"_lastMaskTexture"),cw(this,"_lastMaskFbo"),cw(this,"_textureValid",!1),cw(this,"_selfieTextureValid",!1),cw(this,"_selfieSegmentationHash"),cw(this,"wasm"),cw(this,"predictReady"),cw(this,"_color"),cw(this,"_prePrograme"),cw(this,"_segmentationMask"),cw(this,"_weixin",!1),cw(this,"_centerFace"),cw(this,"_textureMatrixLocation"),cw(this,"_offsetMatrixLocation"),cw(this,"_colorLocation"),cw(this,"_enableFaceCentering",!1),cw(this,"_enableEffectOptimization",!1),cw(this,"_mat4"),cw(this,"_postProcessing"),cw(this,"_onAbort"),cw(this,"_visionTaskRegistry"),cw(this,"resolvePreditReady"),this.init(t).catch(t=>{e.log.error(t),e.destroy(new yw({code:Ew.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(t.message||t)})),this.resolvePreditReady()})}init(e){return uw(this,null,function*(){var t,i,r;this.predictReady=new Promise(e=>{this.resolvePreditReady=e});let o=e.Wasm,n=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 o.AllIn1(n),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:o}=e.waterMark;this.wasm.setWaterMark(t,i,r,o)}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),n.uniform1i(n.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(n.uniform1i(n.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(n.uniform1i(n.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let a=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=n.getUniformLocation(this.program,"u_textureMatrix"),n.uniformMatrix4fv(this._textureMatrixLocation,!1,a),this._offsetMatrixLocation=n.getUniformLocation(this.program,"u_offsetMatrix"),n.uniformMatrix4fv(this._offsetMatrixLocation,!1,a),this._colorLocation=n.getUniformLocation(this.program,"u_color"),n.uniform1i(n.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(n.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\nuniform sampler2D u_texture;\nuniform sampler2D mask;\n\nin vec2 v_texCoord;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);\n}"),t=this.context.createShader(n.VERTEX_SHADER,"#version 300 es\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_texCoord;\nvoid main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n v_texCoord = a_texCoord;\n}");this._prePrograme=this.context.createProgram(t,e),n.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.uniform1i(n.getUniformLocation(this._prePrograme,"mask"),1)}!this._enableEffectOptimization||2!==this.wasm.vbMode&&3!==this.wasm.vbMode?this._postProcessing=void 0:KO()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):null==(r=this._postProcessing)||r.init(n,this.positionBuffer,this.texCoordBuffer,4/3),yield this.initVisionTasks(e)})}initVisionTasks(e){return uw(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._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),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 pK(this.wasm.vbMode,this.image,e,this._visionTaskRegistry,this.context.log)}catch(LC){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._postProcessing&&(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(),FN(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:o}=i;if(FN(this.wasm.rotation)&&!this._visionTaskRegistry&&([r,o]=[o,r]),0===r||0===o||!this.available)return!1;i.width=r,i.height=o;let n=!1;if(this.totalFrames)this.useTexture(),n=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),n=this._textureValid,this._textureValid=!0}if(this.width===r&&this.height===o&&n?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,i):(this.resize(r,o),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,o):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,r,o,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(wM){this._onAbort&&this._onAbort(wM)}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:o=1,scaleOffsetX:n=0,scaleOffsetY:a=0}=t;this._mat4.fromTranslation(r,[-i.offsetX/e.canvas.width+n,a,0]),this._mat4.scale(r,r,[o,o,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,r)}}drawImage(e,t,i,r){let o=this.context.ctx;if(!this._mat4)return;let{width:n,height:a}=o.canvas,s=this._mat4.create();this._mat4.fromTranslation(s,[e/n,1-(t+r)/a,0]),this._mat4.scale(s,s,[i/n,r/a,1]),o.uniformMatrix4fv(this._textureMatrixLocation,!1,s)}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()}},fK=class extends PB{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 }"}),cw(this,"yTextureRef"),cw(this,"uTextureRef"),cw(this,"vTextureRef"),cw(this,"Y"),cw(this,"U"),cw(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)}},_K=(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 gK=0,EK=class{constructor(e){cw(this,"id",gK++),cw(this,"trackDoneOB"),cw(this,"startOB"),cw(this,"stopOB"),cw(this,"decoder"),cw(this,"videoContext"),cw(this,"gop",0),cw(this,"gop_helper",0),cw(this,"waitFirstKeyFrame",!0),cw(this,"startTimestamp",0),cw(this,"startTime",0),cw(this,"startPerformanceTime",0),cw(this,"inputFrameCount",0),cw(this,"decodedFrameCount",0),cw(this,"decodeFrameCount",0),cw(this,"downgradeLevel",0),cw(this,"lastDowngradeTime",0),cw(this,"lastFrameDiff",0),cw(this,"lastDecodeFrameTimestamp",0),cw(this,"config"),cw(this,"gop_before_configure",[]),cw(this,"videoElement"),cw(this,"type","wasm"),cw(this,"goodType"),cw(this,"renderer","2d"),cw(this,"wasmOption"),cw(this,"createDecoder"),cw(this,"_decodeSink"),cw(this,"isReported",!1),cw(this,"track"),cw(this,"stateChangeOB"),cw(this,"failedReason");let{track:t,createDecoder:i}=e;if(this.stateChangeOB=MV(),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=KV(t.availableState,nx.OFF),this.stopOB=MV(),"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),hV(this.stateChangeOB,xF((e,i)=>(e!==i&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:e,state:i}),i),"INITIALIZED"),mF(this.stopOB),fB()),this.start()}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=hV(this.pipe(this.track),mF(this.stopOB),yV());hV(t,fB(()=>{this.track.stat.framesDecoded++},t=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(t," retryCount: ").concat(e)),WP.addFailedEvent({key:_K(this.type,this.renderer),error:t}),e>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),WP.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")),WP.addSuccessEvent({key:_K(this.type,this.renderer)}),WP.addSuccessEvent({key:514704})})),hV(t,pF(1),fB(()=>{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&&!QP()&&(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 o=new Uint8Array(e.data);if(!function(e){return 0===e[0]&&0===e[1]&&0===e[2]&&1===e[3]}(o)||o.length<5)return this.stateChangeOB.next("FAILED"),this.close("not h26x frame ".concat(o.subarray(0,5))),e;let n=!1;switch(31&o[4]){case 5:case 7:n=!0}if("configured"!==(null==(i=this.decoder)?void 0:i.state))return this.track.log.debug("not configured ".concat(this.inputFrameCount)),n&&(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(n?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!n)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(o.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=a,this.startTime=Date.now(),this.startPerformanceTime=mN()}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=>uw(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:o,type:n}=this;e.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(n){case"wasm":i=this.createDecoder(n,this.wasmOption);break;case"webCodecs":i=this.createDecoder(n);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"===n?4:8)}),yield i.initialize(this.videoElement),!this._decodeSink)return;if(i.configure(this.config),"wasm"===n&&"webgl"===o){this.videoContext=new YB({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(YB.UNAVAILABLE,i=>{e.log.error(i),t.error(7)});let r=new fK(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"===o){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 JB({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(o){delete this.goodType,e.log.error(o),t.error(11)}});let o=new VB(this.videoContext,{name:"remotePlayer",logger:e.log});r.connect(o),e.source=r,e.player.setCanvas(this.videoContext._canvas,2)}this.decoder=i}catch(RM){e.log.error(RM),t.error("webCodecs"===n?2:6)}})}},vK=Promise.resolve(),yK=class extends hK.EventEmitter{constructor(e){super(),this.room=e,cw(this,"videoContext"),cw(this,"_glVideoContext"),cw(this,"_2dVideoContext"),cw(this,"destination"),cw(this,"smallVideoContext"),cw(this,"smallDestination"),cw(this,"smallTrackSource"),cw(this,"smallImageSource"),cw(this,"_isMirror",!1),cw(this,"_rotation",0),cw(this,"cameraTrack"),cw(this,"cameraNode"),cw(this,"transformNode"),cw(this,"mixNode"),cw(this,"screenTrack"),cw(this,"screenNode"),cw(this,"selfModel",!1),cw(this,"blurRadius",3),cw(this,"arTrack"),cw(this,"_enableFaceCentering",!1),cw(this,"_enableEffectOptimization",!1),cw(this,"onAbort"),cw(this,"_color"),cw(this,"Wasm"),cw(this,"waterMarkNode"),cw(this,"_waterMarkOption"),cw(this,"watermarkImageList",[]),cw(this,"_beautyParams"),cw(this,"isUsingArTrack",!1),cw(this,"mixTrack"),cw(this,"_isMixScreen",!1),cw(this,"_virtualBackground"),cw(this,"_virtualBackgroundAbortCallback"),cw(this,"virtualBackgroundInstance"),cw(this,"_bgAssetPath"),cw(this,"log"),cw(this,"_mat4"),cw(this,"_postProcessing"),cw(this,"_checkId",0),cw(this,"_use2d",!1),cw(this,"_autoSwitchRenderMode",!0),cw(this,"encodePipeline",[]),cw(this,"decodePipeline",[]),cw(this,"updated",vK),cw(this,"_updateFlag",!1),this.log=fM.createLogger({parent:null==e?void 0:e.getLogger(),id:"vm",userId:null==e?void 0:e.userId,sdkAppId:null==e?void 0:e.sdkAppId}),this.smallVideoContext=new JB({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 FN(this._rotation)?{width:i,height:t}:{width:t,height:i}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new JB({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 YB({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(CO<=22),this._glVideoContext.on(YB.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(Nw){this.emit("error",Nw)}}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=ux.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(),ux.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(NO||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?WP.addFailedEvent({key:t,error:e}):WP.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 YB({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 HB(this.smallVideoContext,e,this.log),this.smallVideoContext.on(YB.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:o}=i;NO&&o.setCanvas(e);let n=e&&(null==(t=this.destination)?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),n=this.arTrack),this.log.info("set main output ".concat(n?n.label:"no output track")),this.setSmallVideo(r,e),i.setOutputMediaStreamTrack(n)}catch(SM){this.log.error("set main output failed",SM)}}update(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return uw(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(PB.RENDER,e=>{var t;null==(t=this.cameraTrack)||t.emit("render",e)})),16===xO?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof jB?(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 jB?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 BB(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(PB.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 mK(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 eH(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 $B(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,o,n;if(e instanceof oH)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof DB)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof pH){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 tH)return this.log.info("change mix input",null==(o=e.outMediaTrack)?void 0:o.label),this.setMixTrack(e);this.log.warn("change unknown input",null==(n=e.mediaTrack)?void 0:n.label)}removeInput(e){var t;e instanceof oH?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof DB?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 pH?e.source&&e.source.context.destroy():e instanceof tH&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return uw(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 uw(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 yw({code:Ew.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(i=>{let{image:o,x:n,y:a,width:s,height:l,fillVideo:c}=i,d=c&&e||s,u=c&&t||l,h=c?0:n,p=c?0:a;r.drawImage(o,h,p,d,u)}),kN(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&&t.fillVideo===e.fillVideo)||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter(e=>e.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return uw(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return uw(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return uw(this,null,function*(){let t;try{t=yield kN((null==e?void 0:e.imageElement)||e.imageUrl)}catch(yM){throw new yw({code:Ew.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:i=0,y:r=0,width:o=t.width,height:n=t.height,type:a="watermark",zIndex:s=2,fillVideo:l=!1}=e;this.watermarkImageList.some(e=>e.type===a)?(this.watermarkImageList=this.watermarkImageList.filter(e=>e.type!==a),this.pushWaterMarkImageList({x:i,y:r,width:o,height:n,image:t,zIndex:s,type:a,imageUrl:e.imageUrl,fillVideo:l}),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:o,height:n,image:t,zIndex:s,type:a,imageUrl:e.imageUrl,fillVideo:l}),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 uw(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 uw(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 uw(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 kN(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 yw({code:Ew.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 uw(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 EK(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}};lw([function(e){return KU((t,i)=>function(){for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return uw(this,null,function*(){try{return yield t.apply(this,r)}catch(SM){e.call(this,SM)}})})}(function(e){this.log.error("update failed",e)}),KU(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return uw(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield vK,this.updated=new Promise((t,r)=>{e.apply(this,i).then(t,r),setTimeout(r,5e3,new yw({code:Ew.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],yK.prototype,"update",1);var TK=0,IK=class extends nx{constructor(e){super("room"),cw(this,"seq",++TK),cw(this,"sdkAppId"),cw(this,"userId"),cw(this,"userSig"),cw(this,"privateMapKey"),cw(this,"latencyLevel"),cw(this,"tinyId"),cw(this,"scene"),cw(this,"roomId"),cw(this,"useStringRoomId"),cw(this,"role","anchor"),cw(this,"joinParams",null),cw(this,"localPublishFlag",0),cw(this,"localTracks",new Set),cw(this,"enableAutoPlayDialog",!0),cw(this,"autoReceiveAudio",!0),cw(this,"autoReceiveVideo",!0),cw(this,"proxy_ws"),cw(this,"proxy_wt"),cw(this,"proxy_unified"),cw(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}}),cw(this,"keyPointManager"),cw(this,"audioManager"),cw(this,"videoManager"),cw(this,"callDurationCalculator"),cw(this,"badCaseDetector"),cw(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),cw(this,"videoDecodeFallbackType"),cw(this,"smallMode","canvas"),cw(this,"enableChorus",!1),cw(this,"_isUsingCachedSchedule",!1),cw(this,"_log"),cw(this,"_joinedTimestamp",0),cw(this,"_sdkType"),cw(this,"heartbeatReport"),cw(this,"heartbeatCount",0),cw(this,"quality"),cw(this,"enableSEI"),cw(this,"isDestroyed",!1),this._log=fM.createLogger({parent:e.logger,id:"r".concat(this.seq)}),this.useStringRoomId=!!e.useStringRoomId,rN(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),rN(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),rN(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new sK({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new cK({room:this}),this.badCaseDetector=new uK({room:this}),this.audioManager=new lH(this),this.videoManager=new yK(this)}get videoCodec(){return"h264"}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 localMainAudioTrack(){for(let e of this.localTracks)if(1&e.mediaType)return e;return null}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}get publishState(){let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach(t=>{if(t.isPublished||t.isPublishing)switch(t.mediaType){case 1:e.audio=!0;break;case 4:e.bigVideo=!0,e.smallVideo=t.hasSmall;break;case 2:e.auxVideo=!0}}),e}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)}}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 uw(this,null,function*(){return this.publish(e)})}removeTrack(e){return uw(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return uw(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(tN(e))/^wss?:\/\//i.test(e)?this.proxy_ws=e:/^https?:\/\//i.test(e)&&(this.proxy_wt=e);else if(JD(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:r,scheduleProxy:o,unifiedProxy:n}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=n,n?(Fj([n,n]),xw("https://".concat(n))):(r&&xw(r),o&&Fj(o))}dM.once(hM.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Vj.main,sched_back_domain:Vj.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return uw(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return uw(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 uw(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 yw({code:Ew.INVALID_OPERATION,message:NP({key:bP.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(wP.INVALID_DESTROY),new yw({code:Ew.INVALID_OPERATION,message:NP({key:bP.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 uw(this,null,function*(){var i,r,o,n;let a=mN();try{let{isCached:s,result:l,detailCost:c}=yield Uj({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Cw,userSig:this.userSig,role:"live"===this.scene?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=s,this._log.info("schedule cache:".concat(+s," ").concat(wN(l,{keysToExclude:["username","credential"]}))),s&&dM.once(hM.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=rw(rw({},this.scheduleResult),l),iN(null==(i=l.config)?void 0:i.retryCount)&&MC(l.config.retryCount),tN(null==(r=l.config)?void 0:r.loggerDomain)&&xw(l.config.loggerDomain),this.videoDecodeFallbackType=(null==(o=l.config)?void 0:o.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=(null==(n=l.config)?void 0:n.smallMode)||this.smallMode,dM.emit(hM.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:c}),WP.addSuccessEvent({key:521700,cost:mN()-a})}catch(TM){throw WP.addFailedEvent({key:521700,error:TM}),TM}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};var AK={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},SK="__INLINE__WORKER__",RK="__INLINE__WASM__",{debug:bK}=console;AK.debug||(console.debug=()=>{});var wK,CK=!SK.startsWith("__"),DK=!RK.startsWith("__");function NK(){let e=xN("".concat(AK.assetsPath?"".concat(AK.assetsPath,"/"):"","worker.js"));return CK?URL.createObjectURL(new Blob([atob(SK)],{type:"application/javascript"})):e.startsWith("http")?fetch(e).then(e=>e.blob().then(e=>URL.createObjectURL(e))):e}function kK(){return uw(this,null,function*(){let e=AK.assetsPath?"".concat(AK.assetsPath,"/"):"";return wK||(wK=DK?(new TextEncoder).encode(atob(RK)).buffer:yield fetch(xN("".concat(e,"av_processing.wasm"))).then(e=>e.arrayBuffer()),wK)})}var OK=new class{constructor(){cw(this,"playPort"),cw(this,"playPortSent",!1),cw(this,"worklet"),cw(this,"workletPromise")}init(){return this.workletPromise||(this.workletPromise=this._init()),this.workletPromise}_init(){return uw(this,null,function*(){let e=sU(),t=NK();try{yield e.audioWorklet.addModule("string"==typeof t?t:yield t),fM.info("global audio player worklet addModule success",t)}catch(LC){throw fM.error("global audio player worklet addModule failed:",LC),LC}return this.worklet=new AudioWorkletNode(e,"global-audio-player",{processorOptions:{wasm:yield kK(),flag:AK},numberOfInputs:2}),fM.info("global audio player worklet created",e.state),this.playPort=this.worklet.port,this.playPort})}playAudio(e){return uw(this,null,function*(){var t;yield this.init();let i=new MessageChannel;null==(t=this.playPort)||t.postMessage(null,[i.port1]),e(i.port2)})}},MK="undefined"!=typeof self&&(!("top"in self)||self===top)&&"showOpenFilePicker"in self&&"showOpenFilePicker";MK?Promise.resolve().then(function(){return UK}):Promise.resolve().then(function(){return GK}),MK?Promise.resolve().then(function(){return HK}):Promise.resolve().then(function(){return jK});var PK=MK?Promise.resolve().then(function(){return WK}):Promise.resolve().then(function(){return zK});function LK(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return uw(this,null,function*(){return(yield PK).default(...t)})}var xK=e=>uw(null,null,function*(){let t=yield e.getFile();return t.handle=e,t}),UK={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return uw(null,[...t],function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[{}];return function*(){Array.isArray(e)||(e=[e]);let t=[];e.forEach((e,i)=>{t[i]={description:e.description||"Files",accept:{}},e.mimeTypes?e.mimeTypes.map(r=>{t[i].accept[r]=e.extensions||[]}):t[i].accept["*/*"]=e.extensions||[]});let i=yield window.showOpenFilePicker({id:e[0].id,startIn:e[0].startIn,types:t,multiple:e[0].multiple||!1,excludeAcceptAllOption:e[0].excludeAcceptAllOption||!1}),r=yield Promise.all(i.map(xK));return e[0].multiple?r:r[0]}()})}};function VK(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then(function(e){return{value:e,done:t}})}return VK=function(e){this.s=e,this.n=e.next},VK.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?Promise.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Promise.reject(e):t(i.apply(this.s,arguments))}},new VK(e)}var FK,BK=function(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),o=2;o<i;o++)r[o-2]=arguments[o];return uw(null,[e,t,...r],function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.name,r=arguments.length>3?arguments[3]:void 0;return function*(){let o=[],n=[];var a,s=!1,l=!1;try{for(var c,d=function(e){var t,i,r,o=2;for("undefined"!=typeof Symbol&&(i=Symbol.asyncIterator,r=Symbol.iterator);o--;){if(i&&null!=(t=e[i]))return t.call(e);if(r&&null!=(t=e[r]))return new VK(t.call(e));i="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}(e.values());s=!(c=yield d.next()).done;s=!1){let a=c.value,s="".concat(i,"/").concat(a.name);"file"===a.kind?n.push(a.getFile().then(t=>(t.directoryHandle=e,t.handle=a,Object.defineProperty(t,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>s})))):"directory"!==a.kind||!t||r&&r(a)||o.push(BK(a,t,s,r))}}catch(u){l=!0,a=u}finally{try{s&&null!=d.return&&(yield d.return())}finally{if(l)throw a}}return[...(yield Promise.all(o)).flat(),...yield Promise.all(n)]}()})},HK={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return uw(null,[...t],function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){e.recursive=e.recursive||!1,e.mode=e.mode||"read";let t=yield window.showDirectoryPicker({id:e.id,startIn:e.startIn,mode:e.mode});return BK(t,e.recursive,void 0,e.skipDirectory)}()})}},WK={__proto__:null,default:function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return uw(null,[e,...i],function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[{}],i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;return function*(){Array.isArray(t)||(t=[t]),t[0].fileName=t[0].fileName||"Untitled";let n=[],a=null;if(e instanceof Blob&&e.type?a=e.type:e.headers&&e.headers.get("content-type")&&(a=e.headers.get("content-type")),t.forEach((e,t)=>{n[t]={description:e.description||"Files",accept:{}},e.mimeTypes?(0===t&&a&&e.mimeTypes.push(a),e.mimeTypes.map(i=>{n[t].accept[i]=e.extensions||[]})):a?n[t].accept[a]=e.extensions||[]:n[t].accept["*/*"]=e.extensions||[]}),i)try{yield i.getFile()}catch(c){if(i=null,r)throw c}let s=i||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:n,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!i&&o&&o(s);let l=yield s.createWritable();return"stream"in e?(yield e.stream().pipeTo(l),s):"body"in e?(yield e.body.pipeTo(l),s):(yield l.write(yield e),yield l.close(),s)}()})}},GK={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return uw(null,[...t],function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[{}];return function*(){return Array.isArray(e)||(e=[e]),new Promise((t,i)=>{let r=document.createElement("input");r.type="file";let o=[...e.map(e=>e.mimeTypes||[]),...e.map(e=>e.extensions||[])].join();r.multiple=e[0].multiple||!1,r.accept=o||"",r.style.display="none",document.body.append(r);let n=e=>{"function"==typeof a&&a(),t(e)},a=e[0].legacySetup&&e[0].legacySetup(n,()=>a(i),r),s=()=>{window.removeEventListener("focus",s),r.remove()};r.addEventListener("click",()=>{window.addEventListener("focus",s)}),r.addEventListener("change",()=>{window.removeEventListener("focus",s),r.remove(),n(r.multiple?Array.from(r.files):r.files[0])}),"showPicker"in HTMLInputElement.prototype?r.showPicker():r.click()})}()})}},jK={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return uw(null,[...t],function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[{}];return function*(){return Array.isArray(e)||(e=[e]),e[0].recursive=e[0].recursive||!1,new Promise((t,i)=>{let r=document.createElement("input");r.type="file",r.webkitdirectory=!0;let o=e=>{"function"==typeof n&&n(),t(e)},n=e[0].legacySetup&&e[0].legacySetup(o,()=>n(i),r);r.addEventListener("change",()=>{let t=Array.from(r.files);e[0].recursive?e[0].recursive&&e[0].skipDirectory&&(t=t.filter(t=>t.webkitRelativePath.split("/").every(t=>!e[0].skipDirectory({name:t,kind:"directory"})))):t=t.filter(e=>2===e.webkitRelativePath.split("/").length),o(t)}),"showPicker"in HTMLInputElement.prototype?r.showPicker():r.click()})}()})}},zK={__proto__:null,default:function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return uw(null,[e,...i],function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){Array.isArray(t)&&(t=t[0]);let i=document.createElement("a"),r=e;"body"in e&&(r=yield function(e,t){return uw(this,null,function*(){let i=e.getReader(),r=new ReadableStream({start:e=>function t(){return uw(this,null,function*(){return i.read().then(i=>{let{done:r,value:o}=i;if(!r)return e.enqueue(o),t();e.close()})})}()}),o=new Response(r),n=yield o.blob();return i.releaseLock(),new Blob([n],{type:t})})}(e.body,e.headers.get("content-type"))),i.download=t.fileName||"Untitled",i.href=URL.createObjectURL(yield r);let o=()=>{"function"==typeof n&&n()},n=t.legacySetup&&t.legacySetup(o,()=>n(),i);return i.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(i.href),3e4),o()}),i.click(),null}()})}},KK=class{constructor(e){this.name=e,cw(this,"ready"),cw(this,"worker"),cw(this,"ports"),cw(this,"ids",1),cw(this,"transactions",new Map),cw(this,"log"),cw(this,"addTransaction",e=>(this.transactions.set(++this.ids,e),this.ids))}postMessage(e,t){var i;null==(i=this.worker)||i.postMessage(e,t)}create(e){return uw(this,null,function*(){if(this.ready)return this.ready;e||(e=this.name),console.time("createWorker_".concat(e));let t=NK(),i=new Worker("string"==typeof t?t:yield t,{name:e});return this.worker=i,this.ready=new Promise((t,r)=>uw(this,null,function*(){i.onmessage=i=>{let{data:{id:o,type:n,payload:a}}=i;var s;if(o)null==(s=this.transactions.get(o))||s(a),this.transactions.delete(o);else switch(n){case"error":console.timeEnd("createWorker_".concat(e)),console.warn("worker error:",a),r(a);break;case"ready":console.timeEnd("createWorker_".concat(e)),t(this);break;case"updateAFSM":if(a.value){let e="string"==typeof a.old?a.old:"".concat(a.old.action,"ing"),t="string"==typeof a.value?a.value:"".concat(a.value.action,"ing");console.log(bN(),a.group,a.name,e,"👉",t)}break;case"log":console.log(a);break;case"glog":window.dispatchEvent(new CustomEvent(n,{detail:a}))}},i.postMessage({wasm:yield kK(),flag:AK},this.ports)}))})}destroy(){var e;console.log("destroy worker",this.name),delete this.ready,null==(e=this.worker)||e.terminate()}},qK=class{constructor(e,t,i){this.worker=e,cw(this,"channel",new MessageChannel),cw(this,"ready"),this.ready=new Promise((e,i)=>{this.worker.postMessage({id:this.worker.addTransaction(e),payload:t},[this.channel.port2])}).then(e=>(0===e.err&&(this.worker.sessionCount++,this.channel.port1.onmessage=i),e))}postMessage(){this.channel.port1.postMessage(...arguments)}destroy(){0===--this.worker.sessionCount&&this.worker.destroy()}},YK=new class e extends KK{constructor(){super("main"),cw(this,"switchValue",new Map),cw(this,"extendChannel"),cw(this,"sessionCount",0)}setSwitchValue(e,t){var i;this.switchValue.set(e,t),null==(i=this.extendChannel)||i.port1.postMessage([e,t])}create(){return uw(this,null,function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield dw(e.prototype,this,"create").call(this),this.switchValue.forEach((e,t)=>{this.extendChannel.port1.postMessage([t,e])}),this)})}},JK=-1;function XK(e){return console.log(e),FK.push(e.slice()),FK.length>1e3&&FK.shift(),e}function QK(e){return uw(this,null,function*(){switch(JK){case 0:this.edpl.willDecodeAudio=XK;break;case 2:this.edpl.didEncodeAudio=XK}yield YK.create(),dM.emit(hM.JOIN_SEND_CMD,{room:this});let t=new qK(YK,e,e=>{let i=e.data;if("string"==typeof i)this.onWorkerEvent(i);else if(null==i)this.onWorkerEvent("client-banned",0),t.destroy();else{let{cmd:e,payload:t}=i;this.onWorkerEvent(e,t)}}),{err:i,data:r}=yield t.ready;if("number"==typeof i){if(dM.emit(hM.JOIN_RECEIVED_CMD_RES,{room:this,code:i}),0===i)return Object.assign(this,r,{session:t});throw new yw({code:Ew.JOIN_ROOM_FAILED,extraCode:Number(i),message:NP({key:bP.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:i,errorMsg:""}})})}throw i})}function $K(e){return uw(this,null,function*(){YK.setSwitchValue("useAINS",e)})}function ZK(e){return uw(this,null,function*(){YK.setSwitchValue("useV2",e)})}function eq(e){let t=new MediaStreamTrackGenerator({kind:"audio"});e.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:e.tinyId,writable:t.writable}},[t.writable])}function tq(e){return uw(this,null,function*(){var t;this._log.info("pull video",e);let i=Date.now(),r=0,o=new MessageChannel;this.postMessage({cmd:"pullVideo",payload:{mediaType:e.mediaType,tinyId:e.tinyId}},[o.port1]),(t=e.stat).framesReceived||(t.framesReceived=0),hV(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=Object.defineProperties(MV(),{postMessage:{value:e.postMessage.bind(e)},port:{get:()=>e,set(t){e.onmessage=iV,e.onmessageerror=iV,e=t,r()}}});function r(){e.onmessage=r=>{r.data?r.ports.length||t?i.next(r):i.next(r.data):(i.complete(),e.close())},e.onmessageerror=t=>{i.error(t),e.close()}}return r(),i}(o.port2),mF(KV(e,nx.INIT)),fB(t=>{let{data:o,packetsReceived:n}=t;e.stat.packetsReceived=n,e.stat.framesReceived++,r++;let a,s=31&o[4];if(r<=10){let e=Array.from(o.slice(0,10)).map(e=>e.toString(16).padStart(2,"0")).join(" ");this._log.info("Frame ".concat(r," - Size: ").concat(o.length," bytes, Type: ").concat(s,", Timestamp: ").concat(Date.now()-i,"ms First 10 bytes: ").concat(e))}switch(s){case 5:case 7:a="key";break;default:a="delta"}e.isAvailable?e.decodeFrame({data:o.buffer,type:a,timestamp:1e3*(Date.now()-i)}):console.warn("track is not available")},()=>{},()=>{o.port2.postMessage(null),o.port2.close()}))})}Object.defineProperties(window,{useAINS:{set:$K,writable:!0},useWt:{set:function(e){return uw(this,null,function*(){YK.setSwitchValue("useWt",e)})},writable:!0},enableDebug:{set(e){console.debug=e?bK:()=>{},YK.setSwitchValue("enableDebug",e)},writable:!0},useV2:{set:ZK,writable:!0},dump:{value(){if(JK=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,FK||(console.warn("dump audio will be activated at next time join room"),FK=[]),!FK.length)return void console.warn("no audio data to dump,try it later");let e=[];return FK.forEach(t=>{e.push(new Uint16Array([t.length])),e.push(t)}),LK(new Blob(e),{fileName:"audio dump hex",extensions:[".hex"]})},writable:!0},dumpAudio:{value(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"audio",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2e3,i=[],r=new Promise(r=>{let o=new MessageChannel;YK.extendChannel.port1.postMessage(["dump",e],[o.port1]),o.port2.onmessage=n=>{let{data:a}=n;console.log(a),i.push(a),i.length>t&&(o.port2.onmessage=null,YK.extendChannel.port1.postMessage(["dump",e]),o.port2.close(),r(new Blob(i)))}});return LK(r,{fileName:e,extensions:[".pcm"]})},writable:!0},hardDec:{set(e){switch(e){case!0:AK.useHardDecoder="prefer-hardware";break;case!1:AK.useHardDecoder="prefer-software";break;default:AK.useHardDecoder="no-preference"}},writable:!0}});var iq=[];function rq(e){var t;let i=MV();if("joined"!==this.state)throw new Error("Room is not joined");if("publish"===e.state)return;for(let c=0;c<=iq.length;c++)if(!iq[c]){iq[c]=this,this.index=c;break}let r=e.profile;this._log.info("start push audio",this.index,r);let o=new MessageChannel,n=e.enableEncryptFrame?new MessageChannel:null;null==(t=this.session)||t.postMessage({cmd:"pushAudio",payload:rw({index:this.index},r)},n?[o.port2,n.port2]:[o.port2]),o.port1.onmessage=t=>{null==t.data||("number"==typeof t.data?i.next(t.data):n&&n.port1.postMessage(ow(rw({},t.data),{data:new Uint8Array(e.encodeFrame({data:t.data.data.buffer,timestamp:t.data.timestamp}).data)})))};let a,s=new MediaStream,l=e=>{let t=s.getAudioTracks()[0];t&&(a.disconnect(),s.removeTrack(t)),s.addTrack(e),this._log.info("push audio track:",e.readyState,e.getSettings().deviceId),a=sU().createMediaStreamSource(s),a.connect(OK.worklet,0,this.index)};hV(KV(e,"output-media-track-changed"),mF(KV(e,"ready")),fB(l,console.error,()=>{this._log.info("stop push audio",r),e.volume=0,a.disconnect(),iq[this.index]=null,n&&n.port1.postMessage(null),o.port1.postMessage(null)})),hV(i,_B(t=>e.volume=t),qF(xB(1e3)),fB(()=>{e.volume=0})),l(e.outMediaTrack)}var oq=class{constructor(e,t,i,r){this.localTrack=e,this.type=t,this.config=i,this.port=r,cw(this,"track"),cw(this,"label"),cw(this,"insertKeyFrame",!0),cw(this,"session"),cw(this,"tsMap",new Map),cw(this,"startTime",0),cw(this,"startTimestamp",0),e._log.info("create Video Encoder",i)}trans(e,t,i){return uw(this,null,function*(){let r=yield this.recreate(i,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});t.signal.addEventListener("abort",()=>{r.encoder.close()});let o=0;return e.pipeThrough(new TransformStream({transform:(e,t)=>{"configured"===r.encoder.state&&(this.tsMap.set(o,Date.now()),this.encode(e),o++,t.enqueue(e))}}),t)})}encode(e){var t,i;null==(i=null==(t=this.session)?void 0:t.encoder)||i.encode(e,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(e,t,i){return uw(this,null,function*(){let r=yield this.recreate(i,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});this.session=r;let o=0;e.pipeTo(new WritableStream({write:e=>{let t=Date.now();"configured"===r.encoder.state&&(o<10&&this.localTrack.log.info("capture ".concat(this.label," track frame:"),o,Date.now(),e.timestamp,e.displayWidth,e.displayHeight),(e.displayWidth!==this.config.width||e.displayHeight!==this.config.height)&&(this.localTrack.log.info("resize video track frame:",e.displayWidth,e.displayHeight,this.config.width,this.config.height),this.configure({width:e.displayWidth,height:e.displayHeight},r)),126===RO?this.tsMap.set(o,mN()):0===o&&(this.startTime=t,this.startTimestamp=e.timestamp),this.encode(e),o<10&&this.localTrack.log.info("encode ".concat(this.label," track frame:"),o),o++,e.close())}}),t).catch(e=>{this.localTrack.log.warn(e),r.encoder.close()})})}recreate(e,t){return uw(this,null,function*(){let i=0,r=new VideoEncoder({output:r=>{let o=126===RO?this.tsMap.get(i):(this.startTime+(r.timestamp-this.startTimestamp)/1e3&4294967295)>>>0;if(126===RO&&this.tsMap.delete(i),i<10&&(0===i&&0===t.recreateCount&&dM.emit(hM.SEND_FIRST_VIDEO_FRAME,{room:e}),this.localTrack.log.info("encoded ".concat(this.label," track frame:"),i,Date.now(),r.timestamp)),i++,t.frameEncoded=i,!1===this.track.enabled)return;let n=null;if(this.localTrack.enableEncodeFrame){n=new Uint8Array(r.byteLength),r.copyTo(n);let e=this.localTrack.encodeFrame({data:n.buffer},3===this.type);n=new Uint8Array(e.data)}n?(this.localTrack.stat.bytesSent+=n.length,this.port.postMessage({chunk:{type:r.type,timestamp:r.timestamp,data:n,duration:r.duration},timestamp:o},[n.buffer])):(this.localTrack.stat.bytesSent+=r.byteLength,this.port.postMessage({chunk:r,timestamp:o}))},error:i=>{this.localTrack.log.warn(i,this.config),t.recreateCount++,setTimeout(()=>this.recreate(e,t),100)}});return t.encoder=r,yield this.configure(null,t),t})}configure(e,t){return uw(this,null,function*(){var i;e&&Object.assign(this.config,e),null==(i=t.encoder)||i.configure(this.config)})}close(){this.port.postMessage(null),this.port.close()}};function nq(e,t){return uw(this,null,function*(){let i=2===e.mediaType,r=i?"screen":"video",o={codec:"avc1.420028",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:AK.useHardEncoder,width:t.profile.width,height:t.profile.height,framerate:t.profile.frameRate,bitrate:1e3*t.profile.bitrate},n=new MessageChannel;this.postMessage({cmd:"pushVideo",payload:t},[n.port1]);let a=new oq(e,t.type,o,n.port2);return n.port2.onmessage=e=>{if(260===e.data)a.insertKeyFrame=!0;else if(!i){let{bitrate:t}=e.data;qD({configureBr:[e.data.bitrate,t]}),a.session&&a.configure({bitrate:t},a.session)}},this._log.info("start push",r,t),a})}function aq(e){return uw(this,null,function*(){var t;let i=2===e.mediaType,r=i?"screen":"video",o={type:i?7:2,profile:e.profile,trackType:i?"screen":"camera",crypto:!(null==(t=e.manager)||!t.encodePipeline[0])};!i&&e.outMediaTrack instanceof CanvasCaptureMediaStreamTrack&&(o.trackType="canvas");let{trackType:n}=o,{width:a,height:s}=e.outMediaTrack.getSettings();o.profile.width=a,o.profile.height=s;let l=yield nq.call(this,e,o);this._log.info("VideoEncoder created",o);let c,d=t=>uw(this,null,function*(){if(null==c||c.abort("track changed"),!t)return;c=new AbortController;let{width:i,height:o,displaySurface:a}=t.getSettings();i&&(l.config.width=i),o&&(l.config.height=o);let s,d=sk.match(/Chrome\/(\d+)/);"114"===(null==d?void 0:d[1])&&"browser"===a&&delete l.config.hardwareAcceleration,this._log.info("push",r,"track:",t.readyState,t.getSettings()),s="undefined"==typeof MediaStreamTrackProcessor||t instanceof CanvasCaptureMediaStreamTrack?new ReadableStream({start(t){e.on("render",i=>{if(0!==e.player.mode||document.hidden)try{t.enqueue(new VideoFrame(i,{timestamp:1e3*performance.now()}))}catch(r){console.warn(r)}})},pull(t){return uw(this,null,function*(){if(0===e.player.mode&&WL()&&e.player.element)return new Promise(i=>{e.player.element.requestVideoFrameCallback((r,o)=>{try{let i=new VideoFrame(e.player.element);t.enqueue(i)}catch(kP){console.warn(kP)}i()})})})}}):new MediaStreamTrackProcessor({track:t}).readable;let u="small"in e&&e.small;return u?(this.smallEncoder||(this.smallEncoder=yield nq.call(this,e,{profile:u,type:3,trackType:n})),this.smallEncoder.track=t,this.smallEncoder.label="small",s=yield this.smallEncoder.trans(s,c,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),l.track=t,l.label=r,l.start(s,c,this)});return hV(KV(e,"output-media-track-changed"),mF(KV(e,"ready")),fB(d,console.error,()=>{var e;this._log.info("stop push",r,o),c.abort("unpublish"),l.close(),null==(e=this.smallEncoder)||e.close()})),d(e.outMediaTrack)})}var sq=class e extends nx{constructor(t){var i,r;super(null!=(r=null==(i=t.roomid)?void 0:i.toString())?r:t.name,"volumeEvaluation"),this.room=t,cw(this,"enableInBackground",!1),cw(this,"interval",400),t.on("joined",()=>{this.emit(e.INTERVALCHANGED,this.interval)}),hV(KV(this,e.INTERVALCHANGED),zF(e=>"joined"===this.room.state?this.room.fromWorker("getAudioEnergy",e):hV((e=>t=>{let i=0,r=performance.now();hV(LB,FF(t=>(t-r)/e|0),uF(e=>e!=i&&(i=e,!0)))(t)})(e),FF(()=>[]))),fB(e=>{e.forEach(e=>{this.room.remotePublishedUserMap.has(e.userId)&&(this.room.remotePublishedUserMap.get(e.userId).remoteAudioTrack.volume=e.volume)}),(!document.hidden||this.enableInBackground)&&this.state==nx.ON&&this.room.emit("audio-volume",e)}))}start(t,i){this.interval=t,this.enableInBackground=i,this.emit(e.INTERVALCHANGED,this.interval)}stop(){}};cw(sq,"INTERVALCHANGED","intervalChanged"),lw([ix([nx.INIT,nx.OFF],nx.ON)],sq.prototype,"start",1),lw([ix([],nx.OFF)],sq.prototype,"stop",1);var lq=sq,cq=class extends IK{constructor(e){super(e),cw(this,"index",0),cw(this,"session"),cw(this,"tinyid"),cw(this,"roomid"),cw(this,"openid"),cw(this,"socketid"),cw(this,"relayip"),cw(this,"clientip"),cw(this,"remotePublishedUserMap",new Map),cw(this,"bussinessInfo"),cw(this,"token"),cw(this,"audioVolumeEvalution",new lq(this)),cw(this,"enableAIVoice",$K),cw(this,"AbilityOption",{AVLimit:{EncVideoCodec:"H265",EncVideoWidth:0,EncVideoHeight:0,EncVideoBr:"0",EncVideoFps:0,EncAudioCodec:"opus",EncAudioFS:0,EncAudioCh:0,EncAudioBr:"0"},GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:navigator.platform,uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:sM(),uint32_device_type:0,str_os_verion:lM(),uint32_link_type:1,str_client_version:Cw,uint32_net_type:Zw[Rw.getNetworkType()],ua:navigator.userAgent,version:""}}),cw(this,"joinAbortController",new AbortController),cw(this,"smallAbortCtrl"),cw(this,"smallEncoder"),e.tinyId&&(this.tinyId=e.tinyId,ZK(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return uw(this,null,function*(){})}getLogger(){return this._log}postMessage(e,t){this.session&&(e?"string"==typeof e?this.session.postMessage({cmd:e,payload:t}):this.session.postMessage(e,t):this.session.postMessage(null))}sendMessage(e,t){return new Promise((i,r)=>{"joined"!=this.state&&r("join room first");let o=new MessageChannel;this.postMessage({cmd:e,payload:t},[o.port1]),o.port2.onmessageerror=r,o.port2.onmessage=e=>{o.port2.close(),i(e.data)}})}fromWorker(e,t){if("joined"!=this.state)throw"join room first";return i=>{var r;let o=new MessageChannel;o.port2.onmessage=e=>{e.data?i.next(e.data):i.complete()},o.port2.onmessageerror=e=>i.error(e),i.defer(()=>{o.port2.postMessage(null),o.port2.close()}),null==(r=this.session)||r.postMessage({cmd:e,payload:t},[o.port1])}}switchRole(e){return uw(this,null,function*(){if(e!==this.role)return this._log.info("switchRole() => switch role to: ".concat(e)),"audience"==e&&this.unpublish(...this.localTracks),this.sendMessage("switchRole","audience"==e?21:20).then(t=>{this.role=e})})}join(e,t,i){return uw(this,null,function*(){var r;let o=Rw.getEnv(),n=zP(),a={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:i,params:e,proxy_wt:this.proxy_wt,proxy_ws:this.proxy_ws,proxy_cloud:null!=(r=this.scheduleResult.iceServers)&&r.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:o,osName:rM(),browserInfo:zP(),tinyId:this.tinyId,joinReq:{useStrRoomid:!!this.useStringRoomId,roomid:String(e.roomId||e.strRoomId),sdkAppID:String(e.sdkAppId),userSig:e.userSig,privMapEncrypt:e.privateMapKey||"",privMap:"",pstnBizType:0,role:"user",jsSdkVersion:Cw,browserVersion:n.browserName+n.browserVersion,closeLocalMedia:!0,trtcscene:"live"===t?2:1,trtcrole:e.role,bussinessInfo:e.businessInfo||this.bussinessInfo||"",isAuxUser:0,autoSubscribe:this.autoReceiveAudio&&this.autoReceiveVideo,AbilityOption:this.AbilityOption}};yield QK.call(this,a),console.log(this),OK.playAudio(e=>this.postMessage({cmd:"setAudioWorkletPort"},[e])),this.checkDestroy()})}leave(){return uw(this,null,function*(){this.remotePublishedUserMap.forEach(e=>{e.remoteAudioTrack.close(),e.remoteAuxiliaryTrack.close(),e.remoteVideoTrack.close()}),this.postMessage(null),this.remotePublishedUserMap.clear(),this.localTracks.forEach((e,t)=>t.unpublish()),this.localTracks.clear()})}getSignalInfo(){return{tinyId:this.tinyid,clientIp:this.clientip,signalIp:"",relayIp:this.relayip,relayInnerIp:"",relayPort:0}}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];e<=0?this.audioVolumeEvalution.stop():this.audioVolumeEvalution.start(e,t)}getLocalAudioStats(){return this.sendMessage("getLocalAudioStats")}getLocalVideoStats(){return this.sendMessage("getLocalVideoStats")}afterJoin(){return uw(this,null,function*(){let e=mF(KV(this,"left")),t=this.audioManager.decodePipeline.some(e=>e);hV(e=>uw(this,null,function*(){let i=new MessageChannel;i.port2.onmessage=t=>{t.data?e.next({data:t.data,port:i.port2}):e.complete()},i.port2.onmessageerror=t=>e.error(t),e.defer(()=>{i.port2.postMessage(null),i.port2.close()}),this.postMessage({cmd:"decodeAudio",payload:t},[i.port1])}),e,fB(e=>{let{data:t,port:i}=e;var r;let o={data:t.data.buffer};for(let[n,a]of this.audioManager.decodePipeline.entries())if(a&&(o=a({frame:o,track:null==(r=this.remotePublishedUserMap.get(t.userId))?void 0:r.remoteAudioTrack}),!o))return;i.postMessage(ow(rw({},t),{data:new Uint8Array(o.data)}),[o.data])}))})}onWorkerEvent(e,t){switch("network-quality"!==e&&console.info(this.userId,"onWorkerEvent",e,JSON.stringify(t)),e){case hM.RECEIVED_PUBLISHED_USER_LIST:return void dM.emit(e,rw({room:this},t));case"1":if(t.userId===this.userId)return;return void this.emit("peer-join",t);case"2":return void this.emit("peer-leave",t);case"3":let i=new eK(this,t);return this.remotePublishedUserMap.set(t.userId,i),void this.emit("remote-published",i);case"5":{let e=t,i=this.remotePublishedUserMap.get(e);i&&(i.remoteVideoTrack.close(),i.remoteAuxiliaryTrack.close(),i.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(e),this.emit("remote-unpublished",i))}return;case"banned":switch(t){case 8:return void this.emit("banned",{reason:"kick",message:""});case 2:case 6:case 4:return void this.emit("banned",{reason:"banned",message:""});case 7:case 5:return void this.emit("banned",{reason:"room_disband",message:""})}break;case"6":{let{prevMuteState:e,muteState:i,flag:r}=t,o=this.remotePublishedUserMap.get(i.userId);if(!o)return void this.emit("remote-publish-state-changed",t);o.flag=r}return dM.emit(hM.REMOTE_PUBLISH_STATE_CHANGED,rw({room:this},t)),void this.emit("remote-publish-state-changed",t);case"7":return void(this.localPublishFlag!==t.flag&&(this.localPublishFlag=t.flag,this.emit("local-publish-flag-changed",t.flag)));case"network-quality":this.quality=rw({},t);let{uplinkLoss:r,uplinkRTT:o,uplinkInfo:n,downlinkInfo:a,msg_down_stream_info:s}=t,l={str_sdk_version:Cw,uint64_datetime:Date.now(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyid},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Zw[xD()]},msg_event_msg:gH(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:n,msg_down_stream_info:s};dM.emit(hM.HEARTBEAT_REPORT,{room:this,report:l}),this.emit("heartbeat-report",l),dM.emit(hM.NETWORK_QUALITY,{room:this,uplink:{rtt:o,loss:r},downlinks:a}),delete t.downlinkInfo;break;case"signal-connection-state-changed":return void dM.emit(hM.SIGNAL_CONNECTION_STATE_CHANGED,rw({room:this},t))}this.emit(e,t)}sendStartPublishCDN(e,t){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,t&&(e.request_time=e.pushRequestTime),this.sendMessage("publishCdn",e)}sendStopPublishCDN(e,t){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,t&&(e.request_time=e.pushRequestTime),this.sendMessage("stopPublishCdn",e)}sendStartMixTranscode(e){return this.sendMessage("startMcuMix",e)}sendStopMixTranscode(e){return this.sendMessage("stopMcuMix",e)}publish(e){return uw(this,null,function*(){if(1===(yield this.sendMessage("publish",e.mediaType).then(e=>0!==e.err?Promise.reject(e.err):e),fx(e,e).add("mute",()=>{this.postMessage("mute",{mediaType:e.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:e.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),e.mediaType))yield OK.init(),rq.call(this,e);else yield aq.call(this,e);e.muted&&this.postMessage("mute",{mediaType:e.mediaType,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(e){return uw(this,null,function*(){_x(e)})}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return uw(this,null,function*(){let e=t.reduce((e,t)=>t.mediaType|e,0),{userId:i,tinyId:r,streamType:o}=t[0],n=this.remotePublishedUserMap.get(i),a=rw({},n.subscribeState),s=Object.assign(new pP,a);s.mediaType|=e,dM.emit(hM.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:n,subscribeState:s});let l=yield this.sendMessage("subscribe",{mediaType:s.mediaType,userId:i,srctinyid:r,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8,2].filter(e=>s.mediaType&e).map(e=>({mediaType:e,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",l),yield Promise.all(t.filter(e=>!e.isSubscribed).map(e=>1===e.mediaType?eq.call(this,e):tq.call(this,e))),dM.emit(hM.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:n})})}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return uw(this,null,function*(){let e=0;for(let i of t)e|=i.mediaType;if(t.length){let{userId:i,streamType:r,tinyId:o}=t[0];yield this.sendMessage("unSubscribe",{mediaType:e,srctinyid:o,userId:i});for(let e of t)e.unsubscribe();dM.emit(hM.UNSUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:this.remotePublishedUserMap.get(i)})}})}enableSmall(e){return uw(this,null,function*(){var t;if(e){if(this.videoManager.smallTrack){let e=this.videoManager.cameraTrack;this.smallEncoder=yield nq.call(this,e,{profile:e.small,type:3,trackType:"camera"});let t=new MediaStreamTrackProcessor({track:this.videoManager.smallTrack}).readable;this.smallEncoder.track=this.videoManager.smallTrack,this.smallEncoder.label="small",this.smallAbortCtrl=new AbortController,this.smallEncoder.start(t,this.smallAbortCtrl,this),this._log.info("push small")}}else null==(t=this.smallAbortCtrl)||t.abort("stop"),this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder)})}changeType(e,t){let i=this.remotePublishedUserMap.get(t.userId);if(!i)return;let r=e?8:4;if(i.remoteVideoTrack.mediaType===r)return;let o={srctinyid:i.tinyId,mediaType:r,userId:t.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter(e=>r&e).map(e=>({mediaType:e,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}};i.remoteVideoTrack.mediaType=o.mediaType,this.postMessage("changetype",o)}destroy(){this.isDestroyed||(super.destroy(),this.isDestroyed=!0,this.joinAbortController.abort("destroy"))}};lw([zU(cq.prototype.afterJoin),ix(["left",nx.INIT],"joined"),KU(e=>{let t=new tK;return function(i,r,o){return uw(this,null,function*(){let n=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 yw({code:Ew.INVALID_OPERATION,message:NP({key:bP.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new yw({code:Ew.INVALID_OPERATION,message:NP({key:bP.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:n}),this.role=21===i.role?"audience":"anchor",this._log.info("Join() => joining room: ".concat(n," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),dM.emit(hM.JOIN_START,{room:this,roomId:n,params:i});let a=Rw.getEnv();a||(a=Jw.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(lC.OLD_CLOUD_LADDER)?a=Jw.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(lC.WEBRTC)&&(a=Jw.WEBRTC))),gx.setConfig({env:a,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),EM.checkSystemRequirementsInternal(o).then(e=>{this.checkSystemResult=e,iK.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Rw.getEnv()&&(yield this.schedule(i,o));let t=yield e.call(this,i,r,o);return this.roomId=n,this._joinedTimestamp=Rw.performanceNow(),dM.emit(hM.JOIN_SUCCESS,{room:this}),30===o&&!i.component&&gx.uploadEvent({log:"stat-conv-".concat(Number(HO),"-").concat(location.hostname),userId:this.userId}),t}catch(RM){throw t.delete({room:this,roomId:n}),dM.emit(hM.JOIN_FAILED,{room:this,error:RM}),RM}})}})],cq.prototype,"join",1),lw([ix("joined","left",{ignoreError:!0}),KU(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return uw(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})})})],cq.prototype,"leave",1),lw([ZU(e=>e.mediaType),KU(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return uw(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)))})})],cq.prototype,"publish",1),lw([ZU(e=>e.mediaType),KU(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let o=e.apply(this,i);return i.forEach(e=>e.unpublish()),o})],cq.prototype,"unpublish",1),lw([ZU(function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}),KU(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let o=e.apply(this,i);return i.forEach(e=>!e.isSubscribed&&e.subscribe(o)),o})],cq.prototype,"subscribe",1);var dq=cq;return Zz.frameWorkType=37,Zz.create=function(e){let t=Zz._create.call(this,dq,e);return t._use(jG,null==e?void 0:e.assetsPath),null!=e&&e.assetsPath&&(AK.assetsPath=null==e?void 0:e.assetsPath),console.log("trtc wasm sdk:",Cw,"created",AK),t},Object.assign(Zz.prototype,{_setCurrentSpeaker(e){let t=sU();return null!=t&&t.setSinkId?t.setSinkId(e):Promise.reject("not support")},_enableVideoDecodeFallback(e,t){return uw(this,null,function*(){return this.startPlugin(jG.Name,{type:"webCodecs",renderer:"videoFrame",track:e,config:{codec:"avc1.640028",hardwareAcceleration:"prefer-software",optimizeForLatency:!0},fallback:"wasm"}),new Promise((t,i)=>{hV(KV(e,"decode-downgrade-state-changed"),uF(e=>"STARTED"===e.state),pF(1),gB(1e4),mF(KV(e,nx.INIT)),fB(t,i))})})}}),HL(37),Zz});
|