trtc-sdk-v5 5.10.2-beta.14 → 5.10.2-beta.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/assets/audioProcessor-wasm.js +1 -0
  2. package/assets/debug-dialog.js +2 -2
  3. package/index.d.ts +21 -38
  4. package/package.json +1 -1
  5. package/plugins/cdn-streaming/package.json +1 -1
  6. package/plugins/cross-room/package.json +1 -1
  7. package/plugins/custom-encryption/package.json +1 -1
  8. package/plugins/device-detector/package.json +1 -1
  9. package/plugins/small-stream-auto-switcher/package.json +1 -1
  10. package/plugins/small-stream-auto-switcher/small-stream-auto-switcher.esm.d.ts +0 -1
  11. package/plugins/small-stream-auto-switcher/small-stream-auto-switcher.esm.js +1 -1
  12. package/plugins/small-stream-auto-switcher/small-stream-auto-switcher.umd.js +1 -1
  13. package/plugins/video-decoder/package.json +1 -1
  14. package/plugins/video-decoder/video-decoder.esm.js +1 -1
  15. package/plugins/video-decoder/video-decoder.umd.js +1 -1
  16. package/plugins/video-effect/basic-beauty/basic-beauty.esm.js +1 -1
  17. package/plugins/video-effect/basic-beauty/basic-beauty.umd.js +1 -1
  18. package/plugins/video-effect/basic-beauty/package.json +1 -1
  19. package/plugins/video-effect/beauty/package.json +1 -1
  20. package/plugins/video-effect/virtual-background/package.json +1 -1
  21. package/plugins/video-effect/virtual-background/virtual-background.esm.js +1 -1
  22. package/plugins/video-effect/virtual-background/virtual-background.umd.js +1 -1
  23. package/plugins/video-effect/watermark/package.json +1 -1
  24. package/plugins/voice-changer/package.json +1 -1
  25. package/trtc.esm.js +59 -34
  26. package/trtc.js +17 -1
  27. package/assets/face_detection/blaze_face_short_range.tflite +0 -0
  28. package/assets/face_detection/vision_wasm_internal.gz +0 -0
  29. package/assets/face_detection/vision_wasm_internal.js +0 -20
  30. package/assets/face_detection/vision_wasm_nosimd_internal.gz +0 -0
  31. package/assets/face_detection/vision_wasm_nosimd_internal.js +0 -20
package/trtc.js CHANGED
@@ -1 +1,17 @@
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)}},R=I,A=R({}.toString),C=R("".slice),b=function(e){return C(A(e),8,-1)},k=s,D=b,N=Object,w=I("".split),O=k((function(){return!N("z").propertyIsEnumerable(0)}))?function(e){return"String"===D(e)?w(e,""):N(e)}:N,P=function(e){return null==e},M=P,L=TypeError,x=function(e){if(M(e))throw new L("Can't call method on "+e);return e},V=O,U=x,F=function(e){return V(U(e))},B="object"==typeof document&&document.all,H=void 0===B&&void 0!==B?function(e){return"function"==typeof e||e===B}:function(e){return"function"==typeof e},W=H,G=function(e){return"object"==typeof e?null!==e:W(e)},j=n,J=H,K=function(e,t){return arguments.length<2?(i=j[e],J(i)?i:void 0):j[e]&&j[e][t];var i},q=I({}.isPrototypeOf),Y=n.navigator,z=Y&&Y.userAgent,X=z?String(z):"",Q=n,Z=X,$=Q.process,ee=Q.Deno,te=$&&$.versions||ee&&ee.version,ie=te&&te.v8;ie&&(g=(f=ie.split("."))[0]>0&&f[0]<4?1:+(f[0]+f[1])),!g&&Z&&(!(f=Z.match(/Edge\/(\d+)/))||f[1]>=74)&&(f=Z.match(/Chrome\/(\d+)/))&&(g=+f[1]);var re=g,ne=re,oe=s,se=n.String,ae=!!Object.getOwnPropertySymbols&&!oe((function(){var e=Symbol("symbol detection");return!se(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),ce=ae&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,le=K,de=H,ue=q,he=Object,pe=ce?function(e){return"symbol"==typeof e}:function(e){var t=le("Symbol");return de(t)&&ue(t.prototype,he(e))},me=String,_e=function(e){try{return me(e)}catch(t){return"Object"}},fe=H,ge=_e,Ee=TypeError,Te=function(e){if(fe(e))return e;throw new Ee(ge(e)+" is not a function")},ve=Te,ye=P,Se=function(e,t){var i=e[t];return ye(i)?void 0:ve(i)},Ie=u,Re=H,Ae=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,Oe=Ne,Pe="__core-js_shared__",Me=be.exports=we[Pe]||Oe(Pe,{});(Me.versions||(Me.versions=[])).push({version:"3.40.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.40.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Le=be.exports,xe=Le,Ve=function(e,t){return xe[e]||(xe[e]=t||{})},Ue=x,Fe=Object,Be=function(e){return Fe(Ue(e))},He=Be,We=I({}.hasOwnProperty),Ge=Object.hasOwn||function(e,t){return We(He(e),t)},je=I,Je=0,Ke=Math.random(),qe=je(1..toString),Ye=function(e){return"Symbol("+(void 0===e?"":e)+")_"+qe(++Je+Ke,36)},ze=Ve,Xe=Ge,Qe=Ye,Ze=ae,$e=ce,et=n.Symbol,tt=ze("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&&Re(i=e.toString)&&!Ae(r=Ie(i,e)))return r;if(Re(i=e.valueOf)&&!Ae(r=Ie(i,e)))return r;if("string"!==t&&Re(i=e.toString)&&!Ae(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,Rt=E,At=F,Ct=mt,bt=Ge,kt=vt,Dt=Object.getOwnPropertyDescriptor;o.f=yt?Dt:function(e,t){if(e=At(e),t=Ct(t),kt)try{return Dt(e,t)}catch(i){}if(bt(e,t))return Rt(!St(It.f,e,t),e[t])};var Nt={},wt=a&&s((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Ot=G,Pt=String,Mt=TypeError,Lt=function(e){if(Ot(e))return e;throw new Mt(Pt(e)+" is not an object")},xt=a,Vt=vt,Ut=wt,Ft=Lt,Bt=mt,Ht=TypeError,Wt=Object.defineProperty,Gt=Object.getOwnPropertyDescriptor,jt="enumerable",Jt="configurable",Kt="writable";Nt.f=xt?Ut?function(e,t,i){if(Ft(e),t=Bt(t),Ft(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Kt in i&&!i[Kt]){var r=Gt(e,t);r&&r[Kt]&&(e[t]=i.value,i={configurable:Jt in i?i[Jt]:r[Jt],enumerable:jt in i?i[jt]:r[jt],writable:!1})}return Wt(e,t,i)}:Wt:function(e,t,i){if(Ft(e),t=Bt(t),Ft(i),Vt)try{return Wt(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Ht("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var qt=Nt,Yt=E,zt=a?function(e,t,i){return qt.f(e,t,Yt(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=Ye,mi=Ve("keys"),_i=function(e){return mi[e]||(mi[e]=pi(e))},fi={},gi=hi,Ei=n,Ti=G,vi=zt,yi=Ge,Si=Le,Ii=_i,Ri=fi,Ai="Object already initialized",Ci=Ei.TypeError,bi=Ei.WeakMap;if(gi||Si.state){var ki=Si.state||(Si.state=new bi);ki.get=ki.get,ki.has=ki.has,ki.set=ki.set,si=function(e,t){if(ki.has(e))throw new Ci(Ai);return t.facade=e,ki.set(e,t),t},ai=function(e){return ki.get(e)||{}},ci=function(e){return ki.has(e)}}else{var Di=Ii("state");Ri[Di]=!0,si=function(e,t){if(yi(e,Di))throw new Ci(Ai);return t.facade=e,vi(e,Di,t),t},ai=function(e){return yi(e,Di)?e[Di]:{}},ci=function(e){return yi(e,Di)}}var Ni={set: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,Oi=s,Pi=H,Mi=Ge,Li=a,xi=ii.CONFIGURABLE,Vi=li,Ui=Ni.enforce,Fi=Ni.get,Bi=String,Hi=Object.defineProperty,Wi=wi("".slice),Gi=wi("".replace),ji=wi([].join),Ji=Li&&!Oi((function(){return 8!==Hi((function(){}),"length",{value:8}).length})),Ki=String(String).split("String"),qi=Xt.exports=function(e,t,i){"Symbol("===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),Ji&&i&&Mi(i,"arity")&&e.length!==i.arity&&Hi(e,"length",{value:i.arity});try{i&&Mi(i,"constructor")&&i.constructor?Li&&Hi(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var r=Ui(e);return Mi(r,"source")||(r.source=ji(Ki,"string"==typeof t?t:"")),e};Function.prototype.toString=qi((function(){return Pi(this)&&Fi(this).source||Vi(this)}),"toString");var Yi=Xt.exports,zi=H,Xi=Nt,Qi=Yi,Zi=Ne,$i=function(e,t,i,r){r||(r={});var n=r.enumerable,o=void 0!==r.name?r.name:t;if(zi(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,Rr=I([].push),Ar=function(e,t){var i,r=yr(e),n=0,o=[];for(i in r)!vr(Ir,i)&&vr(r,i)&&Rr(o,i);for(;t.length>n;)vr(r,i=t[n++])&&(~Sr(o,i)||Rr(o,i));return o},Cr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],br=Ar,kr=Cr.concat("length","prototype");er.f=Object.getOwnPropertyNames||function(e){return br(e,kr)};var Dr={};Dr.f=Object.getOwnPropertySymbols;var Nr=K,wr=er,Or=Dr,Pr=Lt,Mr=I([].concat),Lr=Nr("Reflect","ownKeys")||function(e){var t=wr.f(Pr(e)),i=Or.f;return i?Mr(t,i(e)):t},xr=Ge,Vr=Lr,Ur=o,Fr=Nt,Br=function(e,t,i){for(var r=Vr(t),n=Fr.f,o=Ur.f,s=0;s<r.length;s++){var a=r[s];xr(e,a)||i&&xr(i,a)||n(e,a,o(t,a))}},Hr=s,Wr=H,Gr=/#|\.prototype\./,jr=function(e,t){var i=Kr[Jr(e)];return i===Yr||i!==qr&&(Wr(t)?Hr(t):!!t)},Jr=jr.normalize=function(e){return String(e).replace(Gr,".").toLowerCase()},Kr=jr.data={},qr=jr.NATIVE="N",Yr=jr.POLYFILL="P",zr=jr,Xr=n,Qr=o.f,Zr=zt,$r=$i,en=Ne,tn=Br,rn=zr,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=Yi,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,Rn=q,An=_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:An(arguments[0]),t=Rn(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 On="Symbol(description detection)"===String(kn("description detection")),Pn=yn(Dn.valueOf),Mn=yn(Dn.toString),Ln=/^Symbol\((.*)\)[^)]+$/,xn=yn("".replace),Vn=yn("".slice);Cn(Dn,"description",{configurable:!0,get:function(){var e=Pn(this);if(Sn(Nn,e))return"";var t=Mn(e),i=On?Vn(t,7,-1):xn(t,Ln,"$1");return""===i?void 0:i}}),Tn({global:!0,constructor:!0,forced:!0},{Symbol:wn})}var Un={},Fn=Ar,Bn=Cr,Hn=Object.keys||function(e){return Fn(e,Bn)},Wn=a,Gn=wt,jn=Nt,Jn=Lt,Kn=F,qn=Hn;Un.f=Wn&&!Gn?Object.defineProperties:function(e,t){Jn(e);for(var i,r=Kn(t),n=qn(t),o=n.length,s=0;o>s;)jn.f(e,i=n[s++],r[i]);return e};var Yn,zn=K("document","documentElement"),Xn=Lt,Qn=Un,Zn=Cr,$n=fi,eo=zn,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{Yn=new ActiveXObject("htmlfile")}catch(n){}var e,t,i;co="undefined"!=typeof document?document.domain&&Yn?ao(Yn):(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(Yn);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})),Ro=Ge,Ao=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(Ro(t,ko))return t[ko];var i=t.constructor;return Ao(i)&&t instanceof i?i.prototype:t instanceof Do?No:null},Oo=s,Po=H,Mo=G,Lo=wo,xo=$i,Vo=rt("iterator"),Uo=!1;[].keys&&("next"in(yo=[].keys())?(vo=Lo(Lo(yo)))!==Object.prototype&&(To=vo):Uo=!0);var Fo=!Mo(To)||Oo((function(){var e={};return To[Vo].call(e)!==e}));Fo&&(To={}),Po(To[Vo])||xo(To,Vo,(function(){return this}));var Bo={IteratorPrototype:To,BUGGY_SAFARI_ITERATORS:Uo},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})},Jo=Bo.IteratorPrototype,Ko=lo,qo=E,Yo=jo,zo=So,Xo=function(){return this},Qo=function(e,t,i,r){var n=t+" Iterator";return e.prototype=Ko(Jo,{next:qo(+!r,i)}),Yo(e,n,!1),zo[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=zt,gs=$i,Es=So,Ts=ii.PROPER,vs=ii.CONFIGURABLE,ys=Bo.IteratorPrototype,Ss=Bo.BUGGY_SAFARI_ITERATORS,Is=rt("iterator"),Rs="keys",As="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 Rs:case As: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===As&&m&&m.name!==As&&(vs?fs(p,"name",As):(h=!0,_=function(){return ds(m,this)})),n)if(c={values:d(As),keys:o?_:d(Rs),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,Os=So,Ps=Ni,Ms=Nt.f,Ls=ks,xs=Ds,Vs=a,Us="Array Iterator",Fs=Ps.set,Bs=Ps.getterFor(Us),Hs=Ls(Array,"Array",(function(e,t){Fs(this,{type:Us,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=Os.Arguments=Os.Array;if(ws("keys"),ws("values"),ws("entries"),Vs&&"values"!==Ws.name)try{Ms(Ws,"name",{value:"values"})}catch(uj){}var Gs=Te,js=Be,Js=O,Ks=mr,qs=TypeError,Ys="Reduce of empty array with no initial value",zs=function(e){return function(t,i,r,n){var o=js(t),s=Js(o),a=Ks(o);if(Gs(i),0===a&&r<2)throw new qs(Ys);var c=e?a-1:0,l=e?-1:1;if(r<2)for(;;){if(c in s){n=s[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw new qs(Ys)}for(;e?c>=0:a>c;c+=l)c in s&&(n=i(n,s[c],c,o));return n}},Xs={left:zs(!1),right:zs(!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+)\./),Ra=!!Ia&&+Ia[1],Aa=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,Oa=s,Pa=Ta,Ma=Zs,La=ya,xa=Sa,Va=re,Ua=Ra,Fa=[],Ba=Ca(Fa.sort),Ha=Ca(Fa.push),Wa=Oa((function(){Fa.sort(void 0)})),Ga=Oa((function(){Fa.sort(null)})),ja=Ma("sort"),Ja=!Oa((function(){if(Va)return Va<70;if(!(La&&La>3)){if(xa)return!0;if(Ua)return Ua<603;var e,t,i,r,n="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(r=0;r<47;r++)Fa.push({k:t+r,v:i})}for(Fa.sort((function(e,t){return t.v-e.v})),r=0;r<Fa.length;r++)t=Fa[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));Aa({target:"Array",proto:!0,forced:Wa||!Ga||!ja||!Ja},{sort:function(e){void 0!==e&&ba(e);var t=ka(this);if(Ja)return void 0===e?Ba(t):Ba(t,e);var i,r,n=[],o=Da(t);for(r=0;r<o;r++)r in t&&Ha(n,t[r]);for(Pa(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 Ka="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,qa=$i,Ya=function(e,t,i){for(var r in t)qa(e,r,t[r],i);return e},za=q,Xa=TypeError,Qa=function(e,t){if(za(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},Rc=n,Ac=I,Cc=a,bc=Ka,kc=zt,Dc=En,Nc=Ya,wc=s,Oc=Qa,Pc=or,Mc=hr,Lc=tc,xc=cc,Vc=_c,Uc=wo,Fc=cs,Bc=Tc,Hc=_a,Wc=Ic,Gc=Br,jc=jo,Jc=Ni,Kc=ii.PROPER,qc=ii.CONFIGURABLE,Yc="ArrayBuffer",zc="DataView",Xc="prototype",Qc="Wrong index",Zc=Jc.getterFor(Yc),$c=Jc.getterFor(zc),el=Jc.set,tl=Rc[Yc],il=tl,rl=il&&il[Xc],nl=Rc[zc],ol=nl&&nl[Xc],sl=Object.prototype,al=Rc.Array,cl=Rc.RangeError,ll=Ac(Bc),dl=Ac([].reverse),ul=Vc.pack,hl=Vc.unpack,pl=function(e){return[255&e]},ml=function(e){return[255&e,e>>8&255]},_l=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},fl=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},gl=function(e){return ul(xc(e),23,4)},El=function(e){return ul(e,52,8)},Tl=function(e,t,i){Dc(e[Xc],t,{configurable:!0,get:function(){return i(this)[t]}})},vl=function(e,t,i,r){var n=$c(e),o=Lc(i),s=!!r;if(o+t>n.byteLength)throw new cl(Qc);var a=n.bytes,c=o+n.byteOffset,l=Hc(a,c,c+t);return s?l:dl(l)},yl=function(e,t,i,r,n,o){var s=$c(e),a=Lc(i),c=r(+n),l=!!o;if(a+t>s.byteLength)throw new cl(Qc);for(var d=s.bytes,u=a+s.byteOffset,h=0;h<t;h++)d[u+h]=c[l?h:t-h-1]};if(bc){var Sl=Kc&&tl.name!==Yc;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&&!qc}))?Sl&&qc&&kc(tl,"name",Yc):((il=function(e){return Oc(this,rl),Wc(new tl(Lc(e)),this,il)})[Xc]=rl,rl.constructor=il,Gc(il,tl)),Fc&&Uc(ol)!==sl&&Fc(ol,sl);var Il=new nl(new il(2)),Rl=Ac(ol.setInt8);Il.setInt8(0,2147483648),Il.setInt8(1,2147483649),!Il.getInt8(0)&&Il.getInt8(1)||Nc(ol,{setInt8:function(e,t){Rl(this,e,t<<24>>24)},setUint8:function(e,t){Rl(this,e,t<<24>>24)}},{unsafe:!0})}else rl=(il=function(e){Oc(this,rl);var t=Lc(e);el(this,{type:Yc,bytes:ll(al(t),0),byteLength:t}),Cc||(this.byteLength=t,this.detached=!1)})[Xc],ol=(nl=function(e,t,i){Oc(this,ol),Oc(e,rl);var r=Zc(e),n=r.byteLength,o=Pc(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:zc,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,Yc),jc(nl,zc);var Al={ArrayBuffer:il,DataView:nl},Cl=K,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,Ol="ArrayBuffer",Pl=Al[Ol];nn({global:!0,constructor:!0,forced:n[Ol]!==Pl},{ArrayBuffer:Pl}),wl(Ol);var Ml=b,Ll=I,xl=function(e){if("Function"===Ml(e))return Ll(e)},Vl=nn,Ul=xl,Fl=s,Bl=Lt,Hl=lr,Wl=hr,Gl=Al.ArrayBuffer,jl=Al.DataView,Jl=jl.prototype,Kl=Ul(Gl.prototype.slice),ql=Ul(Jl.getUint8),Yl=Ul(Jl.setUint8);Vl({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:Fl((function(){return!new Gl(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(Kl&&void 0===t)return Kl(Bl(this),e);for(var i=Bl(this).byteLength,r=Hl(e,i),n=Hl(void 0===t?i:t,i),o=new Gl(Wl(n-r)),s=new jl(this),a=new jl(o),c=0;r<n;)Yl(a,c++,ql(s,r++));return o}});var zl=I,Xl=s,Ql=H,Zl=hn,$l=li,ed=function(){},td=K("Reflect","construct"),id=/^\s*(?:class|function)\b/,rd=zl(id.exec),nd=!id.test(ed),od=function(e){if(!Ql(e))return!1;try{return td(ed,[],e),!0}catch(uj){return!1}},sd=function(e){if(!Ql(e))return!1;switch(Zl(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return nd||!!rd(id,$l(e))}catch(uj){return!0}};sd.sham=!0;var ad,cd,ld,dd,ud=!td||Xl((function(){var e;return od(od.call)||!od(Object)||!od((function(){e=!0}))||e}))?sd:od,hd=ud,pd=_e,md=TypeError,_d=function(e){if(hd(e))return e;throw new md(pd(e)+" is not a constructor")},fd=Lt,gd=_d,Ed=P,Td=rt("species"),vd=function(e,t){var i,r=fd(e).constructor;return void 0===r||Ed(i=fd(r)[Td])?t:gd(i)},yd=c,Sd=Function.prototype,Id=Sd.apply,Rd=Sd.call,Ad="object"==typeof Reflect&&Reflect.apply||(yd?Rd.bind(Id):function(){return Rd.apply(Id,arguments)}),Cd=Te,bd=c,kd=xl(xl.bind),Dd=function(e,t){return Cd(e),void 0===t?e:bd?kd(e,t):function(){return e.apply(t,arguments)}},Nd=TypeError,wd=function(e,t){if(e<t)throw new Nd("Not enough arguments");return e},Od=/(?:ipad|iphone|ipod).*applewebkit/i.test(X),Pd=n,Md=Ad,Ld=Dd,xd=H,Vd=Ge,Ud=s,Fd=zn,Bd=_a,Hd=Et,Wd=wd,Gd=Od,jd=na,Jd=Pd.setImmediate,Kd=Pd.clearImmediate,qd=Pd.process,Yd=Pd.Dispatch,zd=Pd.Function,Xd=Pd.MessageChannel,Qd=Pd.String,Zd=0,$d={},eu="onreadystatechange";Ud((function(){ad=Pd.location}));var tu=function(e){if(Vd($d,e)){var t=$d[e];delete $d[e],t()}},iu=function(e){return function(){tu(e)}},ru=function(e){tu(e.data)},nu=function(e){Pd.postMessage(Qd(e),ad.protocol+"//"+ad.host)};Jd&&Kd||(Jd=function(e){Wd(arguments.length,1);var t=xd(e)?e:zd(e),i=Bd(arguments,1);return $d[++Zd]=function(){Md(t,void 0,i)},cd(Zd),Zd},Kd=function(e){delete $d[e]},jd?cd=function(e){qd.nextTick(iu(e))}:Yd&&Yd.now?cd=function(e){Yd.now(iu(e))}:Xd&&!Gd?(dd=(ld=new Xd).port2,ld.port1.onmessage=ru,cd=Ld(dd.postMessage,dd)):Pd.addEventListener&&xd(Pd.postMessage)&&!Pd.importScripts&&ad&&"file:"!==ad.protocol&&!Ud(nu)?(cd=nu,Pd.addEventListener("message",ru,!1)):cd=eu in Hd("script")?function(e){Fd.appendChild(Hd("script"))[eu]=function(){Fd.removeChild(this),tu(e)}}:function(e){setTimeout(iu(e),0)});var ou={set:Jd,clear:Kd},su=n,au=a,cu=Object.getOwnPropertyDescriptor,lu=function(e){if(!au)return su[e];var t=cu(su,e);return t&&t.value},du=function(){this.head=null,this.tail=null};du.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var uu,hu,pu,mu,_u,fu=du,gu=/ipad|iphone|ipod/i.test(X)&&"undefined"!=typeof Pebble,Eu=/web0s(?!.*chrome)/i.test(X),Tu=n,vu=lu,yu=Dd,Su=ou.set,Iu=fu,Ru=Od,Au=gu,Cu=Eu,bu=na,ku=Tu.MutationObserver||Tu.WebKitMutationObserver,Du=Tu.document,Nu=Tu.process,wu=Tu.Promise,Ou=vu("queueMicrotask");if(!Ou){var Pu=new Iu,Mu=function(){var e,t;for(bu&&(e=Nu.domain)&&e.exit();t=Pu.get();)try{t()}catch(uj){throw Pu.head&&uu(),uj}e&&e.enter()};Ru||bu||Cu||!ku||!Du?!Au&&wu&&wu.resolve?((mu=wu.resolve(void 0)).constructor=wu,_u=yu(mu.then,mu),uu=function(){_u(Mu)}):bu?uu=function(){Nu.nextTick(Mu)}:(Su=yu(Su,Tu),uu=function(){Su(Mu)}):(hu=!0,pu=Du.createTextNode(""),new ku(Mu).observe(pu,{characterData:!0}),uu=function(){pu.data=hu=!hu}),Ou=function(e){Pu.head||uu(),Pu.add(e)}}var Lu=Ou,xu=function(e){try{return{error:!1,value:e()}}catch(uj){return{error:!0,value:uj}}},Vu=n.Promise,Uu=n,Fu=Vu,Bu=H,Hu=zr,Wu=li,Gu=rt,ju=ra,Ju=re;Fu&&Fu.prototype;var Ku=Gu("species"),qu=!1,Yu=Bu(Uu.PromiseRejectionEvent),zu=Hu("Promise",(function(){var e=Wu(Fu),t=e!==String(Fu);if(!t&&66===Ju)return!0;if(!Ju||Ju<51||!/native code/.test(e)){var i=new Fu((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((i.constructor={})[Ku]=r,!(qu=i.then((function(){}))instanceof r))return!0}return!(t||"BROWSER"!==ju&&"DENO"!==ju||Yu)})),Xu={CONSTRUCTOR:zu,REJECTION_EVENT:Yu,SUBCLASSING:qu},Qu={},Zu=Te,$u=TypeError,eh=function(e){var t,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw new $u("Bad Promise constructor");t=e,i=r})),this.resolve=Zu(t),this.reject=Zu(i)};Qu.f=function(e){return new eh(e)};var th,ih,rh,nh=nn,oh=na,sh=n,ah=u,ch=$i,lh=cs,dh=jo,uh=Nl,hh=Te,ph=H,mh=G,_h=Qa,fh=vd,gh=ou.set,Eh=Lu,Th=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(uj){}},vh=xu,yh=fu,Sh=Ni,Ih=Vu,Rh=Qu,Ah="Promise",Ch=Xu.CONSTRUCTOR,bh=Xu.REJECTION_EVENT,kh=Xu.SUBCLASSING,Dh=Sh.getterFor(Ah),Nh=Sh.set,wh=Ih&&Ih.prototype,Oh=Ih,Ph=wh,Mh=sh.TypeError,Lh=sh.document,xh=sh.process,Vh=Rh.f,Uh=Vh,Fh=!!(Lh&&Lh.createEvent&&sh.dispatchEvent),Bh="unhandledrejection",Hh=function(e){var t;return!(!mh(e)||!ph(t=e.then))&&t},Wh=function(e,t){var i,r,n,o=t.value,s=1===t.state,a=s?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{a?(s||(2===t.rejection&&qh(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),n=!0)),i===e.promise?l(new Mh("Promise-chain cycle")):(r=Hh(i))?ah(r,i,c,l):c(i)):l(o)}catch(uj){d&&!n&&d.exit(),l(uj)}},Gh=function(e,t){e.notified||(e.notified=!0,Eh((function(){for(var i,r=e.reactions;i=r.get();)Wh(i,e);e.notified=!1,t&&!e.rejection&&Jh(e)})))},jh=function(e,t,i){var r,n;Fh?((r=Lh.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),sh.dispatchEvent(r)):r={promise:t,reason:i},!bh&&(n=sh["on"+e])?n(r):e===Bh&&Th("Unhandled promise rejection",i)},Jh=function(e){ah(gh,sh,(function(){var t,i=e.facade,r=e.value;if(Kh(e)&&(t=vh((function(){oh?xh.emit("unhandledRejection",r,i):jh(Bh,i,r)})),e.rejection=oh||Kh(e)?2:1,t.error))throw t.value}))},Kh=function(e){return 1!==e.rejection&&!e.parent},qh=function(e){ah(gh,sh,(function(){var t=e.facade;oh?xh.emit("rejectionHandled",t):jh("rejectionhandled",t,e.value)}))},Yh=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,Gh(e,!0))},Xh=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new Mh("Promise can't be resolved itself");var r=Hh(t);r?Eh((function(){var i={done:!1};try{ah(r,t,Yh(Xh,i,e),Yh(zh,i,e))}catch(uj){zh(i,uj,e)}})):(e.value=t,e.state=1,Gh(e,!1))}catch(uj){zh({done:!1},uj,e)}}};if(Ch&&(Ph=(Oh=function(e){_h(this,Ph),hh(e),ah(th,this);var t=Dh(this);try{e(Yh(Xh,t),Yh(zh,t))}catch(uj){zh(t,uj)}}).prototype,(th=function(e){Nh(this,{type:Ah,done:!1,notified:!1,parent:!1,reactions:new yh,rejection:!1,state:0,value:null})}).prototype=ch(Ph,"then",(function(e,t){var i=Dh(this),r=Vh(fh(this,Oh));return i.parent=!0,r.ok=!ph(e)||e,r.fail=ph(t)&&t,r.domain=oh?xh.domain:void 0,0===i.state?i.reactions.add(r):Eh((function(){Wh(r,i)})),r.promise})),ih=function(){var e=new th,t=Dh(e);this.promise=e,this.resolve=Yh(Xh,t),this.reject=Yh(zh,t)},Rh.f=Vh=function(e){return e===Oh||undefined===e?new ih(e):Uh(e)},ph(Ih)&&wh!==Object.prototype)){rh=wh.then,kh||ch(wh,"then",(function(e,t){var i=this;return new Oh((function(e,t){ah(rh,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete wh.constructor}catch(uj){}lh&&lh(wh,Ph)}nh({global:!0,constructor:!0,wrap:!0,forced:Ch},{Promise:Oh}),dh(Oh,Ah,!1),uh(Ah);var Qh=So,Zh=rt("iterator"),$h=Array.prototype,ep=function(e){return void 0!==e&&(Qh.Array===e||$h[Zh]===e)},tp=hn,ip=Se,rp=P,np=So,op=rt("iterator"),sp=function(e){if(!rp(e))return ip(e,op)||ip(e,"@@iterator")||np[tp(e)]},ap=u,cp=Te,lp=Lt,dp=_e,up=sp,hp=TypeError,pp=function(e,t){var i=arguments.length<2?up(e):t;if(cp(i))return lp(ap(i,e));throw new hp(dp(e)+" is not iterable")},mp=u,_p=Lt,fp=Se,gp=function(e,t,i){var r,n;_p(e);try{if(!(r=fp(e,"return"))){if("throw"===t)throw i;return i}r=mp(r,e)}catch(uj){n=!0,r=uj}if("throw"===t)throw i;if(n)throw r;return _p(r),i},Ep=Dd,Tp=u,vp=Lt,yp=_e,Sp=ep,Ip=mr,Rp=q,Ap=pp,Cp=sp,bp=gp,kp=TypeError,Dp=function(e,t){this.stopped=e,this.result=t},Np=Dp.prototype,wp=function(e,t,i){var r,n,o,s,a,c,l,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),_=Ep(t,d),f=function(e){return r&&bp(r,"normal",e),new Dp(!0,e)},g=function(e){return u?(vp(e),m?_(e[0],e[1],f):_(e[0],e[1])):m?_(e,f):_(e)};if(h)r=e.iterator;else if(p)r=e;else{if(!(n=Cp(e)))throw new kp(yp(e)+" is not iterable");if(Sp(n)){for(o=0,s=Ip(e);s>o;o++)if((a=g(e[o]))&&Rp(Np,a))return a;return new Dp(!1)}r=Ap(e,n)}for(c=h?e.next:r.next;!(l=Tp(c,r)).done;){try{a=g(l.value)}catch(uj){bp(r,"throw",uj)}if("object"==typeof a&&a&&Rp(Np,a))return a}return new Dp(!1)},Op=rt("iterator"),Pp=!1;try{var Mp=0,Lp={next:function(){return{done:!!Mp++}},return:function(){Pp=!0}};Lp[Op]=function(){return this},Array.from(Lp,(function(){throw 2}))}catch(uj){}var xp=function(e,t){try{if(!t&&!Pp)return!1}catch(uj){return!1}var i=!1;try{var r={};r[Op]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(uj){}return i},Vp=Vu,Up=Xu.CONSTRUCTOR||!xp((function(e){Vp.all(e).then(void 0,(function(){}))})),Fp=u,Bp=Te,Hp=Qu,Wp=xu,Gp=wp;nn({target:"Promise",stat:!0,forced:Up},{all:function(e){var t=this,i=Hp.f(t),r=i.resolve,n=i.reject,o=Wp((function(){var i=Bp(t.resolve),o=[],s=0,a=1;Gp(e,(function(e){var c=s++,l=!1;a++,Fp(i,t,e).then((function(e){l||(l=!0,o[c]=e,--a||r(o))}),n)})),--a||r(o)}));return o.error&&n(o.value),i.promise}});var jp=nn,Jp=Xu.CONSTRUCTOR,Kp=Vu,qp=K,Yp=H,zp=$i,Xp=Kp&&Kp.prototype;if(jp({target:"Promise",proto:!0,forced:Jp,real:!0},{catch:function(e){return this.then(void 0,e)}}),Yp(Kp)){var Qp=qp("Promise").prototype.catch;Xp.catch!==Qp&&zp(Xp,"catch",Qp,{unsafe:!0})}var Zp=u,$p=Te,em=Qu,tm=xu,im=wp;nn({target:"Promise",stat:!0,forced:Up},{race:function(e){var t=this,i=em.f(t),r=i.reject,n=tm((function(){var n=$p(t.resolve);im(e,(function(e){Zp(n,t,e).then(i.resolve,r)}))}));return n.error&&r(n.value),i.promise}});var rm=Qu;nn({target:"Promise",stat:!0,forced:Xu.CONSTRUCTOR},{reject:function(e){var t=rm.f(this);return(0,t.reject)(e),t.promise}});var nm=Lt,om=G,sm=Qu,am=function(e,t){if(nm(e),om(t)&&t.constructor===e)return t;var i=sm.f(e);return(0,i.resolve)(t),i.promise},cm=nn,lm=Xu.CONSTRUCTOR,dm=am;K("Promise"),cm({target:"Promise",stat:!0,forced:lm},{resolve:function(e){return dm(this,e)}});var um=nn,hm=Vu,pm=s,mm=K,_m=H,fm=vd,gm=am,Em=$i,Tm=hm&&hm.prototype;if(um({target:"Promise",proto:!0,real:!0,forced:!!hm&&pm((function(){Tm.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=fm(this,mm("Promise")),i=_m(e);return this.then(i?function(i){return gm(t,e()).then((function(){return i}))}:e,i?function(i){return gm(t,e()).then((function(){throw i}))}:e)}}),_m(hm)){var vm=mm("Promise").prototype.finally;Tm.finally!==vm&&Em(Tm,"finally",vm,{unsafe:!0})}var ym=G,Sm=b,Im=rt("match"),Rm=function(e){var t;return ym(e)&&(void 0!==(t=e[Im])?!!t:"RegExp"===Sm(e))},Am=Lt,Cm=function(){var e=Am(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},bm=u,km=Ge,Dm=q,Nm=Cm,wm=RegExp.prototype,Om=function(e){var t=e.flags;return void 0!==t||"flags"in wm||km(e,"flags")||!Dm(wm,e)?t:bm(Nm,e)},Pm=s,Mm=n.RegExp,Lm=Pm((function(){var e=Mm("a","y");return e.lastIndex=2,null!==e.exec("abcd")})),xm=Lm||Pm((function(){return!Mm("a","y").sticky})),Vm={BROKEN_CARET:Lm||Pm((function(){var e=Mm("^r","gy");return e.lastIndex=2,null!==e.exec("str")})),MISSED_STICKY:xm,UNSUPPORTED_Y:Lm},Um=Nt.f,Fm=s,Bm=n.RegExp,Hm=Fm((function(){var e=Bm(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)})),Wm=s,Gm=n.RegExp,jm=Wm((function(){var e=Gm("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Jm=a,Km=n,qm=I,Ym=zr,zm=Ic,Xm=zt,Qm=lo,Zm=er.f,$m=q,e_=Rm,t_=_n,i_=Om,r_=Vm,n_=function(e,t,i){i in e||Um(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},o_=$i,s_=s,a_=Ge,c_=Ni.enforce,l_=Nl,d_=Hm,u_=jm,h_=rt("match"),p_=Km.RegExp,m_=p_.prototype,__=Km.SyntaxError,f_=qm(m_.exec),g_=qm("".charAt),E_=qm("".replace),T_=qm("".indexOf),v_=qm("".slice),y_=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,S_=/a/g,I_=/a/g,R_=new p_(S_)!==S_,A_=r_.MISSED_STICKY,C_=r_.UNSUPPORTED_Y,b_=Jm&&(!R_||A_||d_||u_||s_((function(){return I_[h_]=!1,p_(S_)!==S_||p_(I_)===I_||"/a/i"!==String(p_(S_,"i"))})));if(Ym("RegExp",b_)){for(var k_=function(e,t){var i,r,n,o,s,a,c=$m(m_,this),l=e_(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===k_)return e;if((l||$m(m_,e))&&(e=e.source,d&&(t=i_(h))),e=void 0===e?"":t_(e),t=void 0===t?"":t_(t),h=e,d_&&"dotAll"in S_&&(r=!!t&&T_(t,"s")>-1)&&(t=E_(t,/s/g,"")),i=t,A_&&"sticky"in S_&&(n=!!t&&T_(t,"y")>-1)&&C_&&(t=E_(t,/y/g,"")),u_&&(o=function(e){for(var t,i=e.length,r=0,n="",o=[],s=Qm(null),a=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=g_(e,r)))t+=g_(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:if(n+=t,"?:"===v_(e,r+1,r+3))continue;f_(y_,v_(e,r+1))&&(r+=2,c=!0),l++;continue;case">"===t&&c:if(""===d||a_(s,d))throw new __("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=zm(p_(e,t),c?this:m_,k_),(r||n||u.length)&&(a=c_(s),r&&(a.dotAll=!0,a.raw=k_(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=g_(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+g_(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Xm(s,"source",""===h?"(?:)":h)}catch(uj){}return s},D_=Zm(p_),N_=0;D_.length>N_;)n_(k_,p_,D_[N_++]);m_.constructor=k_,k_.prototype=m_,o_(Km,"RegExp",k_,{constructor:!0})}l_("RegExp");var w_=u,O_=I,P_=_n,M_=Cm,L_=Vm,x_=lo,V_=Ni.get,U_=Hm,F_=jm,B_=Ve("native-string-replace",String.prototype.replace),H_=RegExp.prototype.exec,W_=H_,G_=O_("".charAt),j_=O_("".indexOf),J_=O_("".replace),K_=O_("".slice),q_=function(){var e=/a/,t=/b*/g;return w_(H_,e,"a"),w_(H_,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Y_=L_.BROKEN_CARET,z_=void 0!==/()??/.exec("")[1];(q_||z_||Y_||U_||F_)&&(W_=function(e){var t,i,r,n,o,s,a,c=this,l=V_(c),d=P_(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=w_(W_,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Y_&&c.sticky,m=w_(M_,c),_=c.source,f=0,g=d;if(p&&(m=J_(m,"y",""),-1===j_(m,"g")&&(m+="g"),g=K_(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==G_(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),z_&&(i=new RegExp("^"+_+"$(?!\\s)",m)),q_&&(r=c.lastIndex),n=w_(H_,p?i:c,g),p?n?(n.input=K_(n.input,f),n[0]=K_(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:q_&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),z_&&n&&n.length>1&&w_(B_,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=x_(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=n[a[1]];return n});var X_=W_;nn({target:"RegExp",proto:!0,forced:/./.exec!==X_},{exec:X_});var Q_=or,Z_=_n,$_=x,ef=RangeError,tf=I,rf=hr,nf=_n,of=function(e){var t=Z_($_(this)),i="",r=Q_(e);if(r<0||Infinity===r)throw new ef("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},sf=x,af=tf(of),cf=tf("".slice),lf=Math.ceil,df=function(e){return function(t,i,r){var n,o,s=nf(sf(t)),a=rf(i),c=s.length,l=void 0===r?" ":nf(r);return a<=c||""===l?s:((o=af(l,lf((n=a-c)/l.length))).length>n&&(o=cf(o,0,n)),e?s+o:o+s)}},uf={start:df(!1),end:df(!0)},hf=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(X),pf=uf.start;nn({target:"String",proto:!0,forced:hf},{padStart:function(e){return pf(this,e,arguments.length>1?arguments[1]:void 0)}});var mf=u,_f=$i,ff=X_,gf=s,Ef=rt,Tf=zt,vf=Ef("species"),yf=RegExp.prototype,Sf=I,If=or,Rf=_n,Af=x,Cf=Sf("".charAt),bf=Sf("".charCodeAt),kf=Sf("".slice),Df=function(e){return function(t,i){var r,n,o=Rf(Af(t)),s=If(i),a=o.length;return s<0||s>=a?e?"":void 0:(r=bf(o,s))<55296||r>56319||s+1===a||(n=bf(o,s+1))<56320||n>57343?e?Cf(o,s):r:e?kf(o,s,s+2):n-56320+(r-55296<<10)+65536}},Nf={codeAt:Df(!1),charAt:Df(!0)},wf=Nf.charAt,Of=I,Pf=Be,Mf=Math.floor,Lf=Of("".charAt),xf=Of("".replace),Vf=Of("".slice),Uf=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Ff=/\$([$&'`]|\d{1,2})/g,Bf=function(e,t,i,r,n,o){var s=i+e.length,a=r.length,c=Ff;return void 0!==n&&(n=Pf(n),c=Uf),xf(o,c,(function(o,c){var l;switch(Lf(c,0)){case"$":return"$";case"&":return e;case"`":return Vf(t,0,i);case"'":return Vf(t,s);case"<":l=n[Vf(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Mf(d/10);return 0===u?o:u<=a?void 0===r[u-1]?Lf(c,1):r[u-1]+Lf(c,1):o}l=r[d-1]}return void 0===l?"":l}))},Hf=u,Wf=Lt,Gf=H,jf=b,Jf=X_,Kf=TypeError,qf=Ad,Yf=u,zf=I,Xf=function(e,t,i,r){var n=Ef(e),o=!gf((function(){var t={};return t[n]=function(){return 7},7!==""[e](t)})),s=o&&!gf((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[vf]=function(){return i},i.flags="",i[n]=/./[n]),i.exec=function(){return t=!0,null},i[n](""),!t}));if(!o||!s||i){var a=/./[n],c=t(n,""[e],(function(e,t,i,r,n){var s=t.exec;return s===ff||s===yf.exec?o&&!n?{done:!0,value:mf(a,t,i,r)}:{done:!0,value:mf(e,i,t,r)}:{done:!1}}));_f(String.prototype,e,c[0]),_f(yf,n,c[1])}r&&Tf(yf[n],"sham",!0)},Qf=s,Zf=Lt,$f=H,eg=P,tg=or,ig=hr,rg=_n,ng=x,og=function(e,t,i){return t+(i?wf(e,t).length:1)},sg=Se,ag=Bf,cg=function(e,t){var i=e.exec;if(Gf(i)){var r=Hf(i,e,t);return null!==r&&Wf(r),r}if("RegExp"===jf(e))return Hf(Jf,e,t);throw new Kf("RegExp#exec called on incompatible receiver")},lg=rt("replace"),dg=Math.max,ug=Math.min,hg=zf([].concat),pg=zf([].push),mg=zf("".indexOf),_g=zf("".slice),fg=function(e){return void 0===e?e:String(e)},gg="$0"==="a".replace(/./,"$0"),Eg=!!/./[lg]&&""===/./[lg]("a","$0");Xf("replace",(function(e,t,i){var r=Eg?"$":"$0";return[function(e,i){var r=ng(this),n=eg(e)?void 0:sg(e,lg);return n?Yf(n,e,r,i):Yf(t,rg(r),e,i)},function(e,n){var o=Zf(this),s=rg(e);if("string"==typeof n&&-1===mg(n,r)&&-1===mg(n,"$<")){var a=i(t,o,s,n);if(a.done)return a.value}var c=$f(n);c||(n=rg(n));var l,d=o.global;d&&(l=o.unicode,o.lastIndex=0);for(var u,h=[];null!==(u=cg(o,s))&&(pg(h,u),d);){""===rg(u[0])&&(o.lastIndex=og(s,ig(o.lastIndex),l))}for(var p="",m=0,_=0;_<h.length;_++){for(var f,g=rg((u=h[_])[0]),E=dg(ug(tg(u.index),s.length),0),T=[],v=1;v<u.length;v++)pg(T,fg(u[v]));var y=u.groups;if(c){var S=hg([g],T,E,s);void 0!==y&&pg(S,y),f=rg(qf(n,void 0,S))}else f=ag(g,s,E,T,y,n);E>=m&&(p+=_g(s,m,E)+f,m=E+g.length)}return p+_g(s,m)}]}),!!Qf((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}))||!gg||Eg);var Tg="\t\n\v\f\r                 \u2028\u2029\ufeff",vg=x,yg=_n,Sg=Tg,Ig=I("".replace),Rg=RegExp("^["+Sg+"]+"),Ag=RegExp("(^|[^"+Sg+"])["+Sg+"]+$"),Cg=function(e){return function(t){var i=yg(vg(t));return 1&e&&(i=Ig(i,Rg,"")),2&e&&(i=Ig(i,Ag,"$1")),i}},bg={start:Cg(1),end:Cg(2),trim:Cg(3)},kg=ii.PROPER,Dg=s,Ng=Tg,wg=bg.trim;nn({target:"String",proto:!0,forced:function(e){return Dg((function(){return!!Ng[e]()||"​…᠎"!=="​…᠎"[e]()||kg&&Ng[e].name!==e}))}("trim")},{trim:function(){return wg(this)}});var Og,Pg,Mg,Lg={exports:{}},xg=Ka,Vg=a,Ug=n,Fg=H,Bg=G,Hg=Ge,Wg=hn,Gg=_e,jg=zt,Jg=$i,Kg=En,qg=q,Yg=wo,zg=cs,Xg=rt,Qg=Ye,Zg=Ni.enforce,$g=Ni.get,eE=Ug.Int8Array,tE=eE&&eE.prototype,iE=Ug.Uint8ClampedArray,rE=iE&&iE.prototype,nE=eE&&Yg(eE),oE=tE&&Yg(tE),sE=Object.prototype,aE=Ug.TypeError,cE=Xg("toStringTag"),lE=Qg("TYPED_ARRAY_TAG"),dE="TypedArrayConstructor",uE=xg&&!!zg&&"Opera"!==Wg(Ug.opera),hE=!1,pE={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},mE={BigInt64Array:8,BigUint64Array:8},_E=function(e){var t=Yg(e);if(Bg(t)){var i=$g(t);return i&&Hg(i,dE)?i[dE]:_E(t)}},fE=function(e){if(!Bg(e))return!1;var t=Wg(e);return Hg(pE,t)||Hg(mE,t)};for(Og in pE)(Mg=(Pg=Ug[Og])&&Pg.prototype)?Zg(Mg)[dE]=Pg:uE=!1;for(Og in mE)(Mg=(Pg=Ug[Og])&&Pg.prototype)&&(Zg(Mg)[dE]=Pg);if((!uE||!Fg(nE)||nE===Function.prototype)&&(nE=function(){throw new aE("Incorrect invocation")},uE))for(Og in pE)Ug[Og]&&zg(Ug[Og],nE);if((!uE||!oE||oE===sE)&&(oE=nE.prototype,uE))for(Og in pE)Ug[Og]&&zg(Ug[Og].prototype,oE);if(uE&&Yg(rE)!==oE&&zg(rE,oE),Vg&&!Hg(oE,cE))for(Og in hE=!0,Kg(oE,cE,{configurable:!0,get:function(){return Bg(this)?this[lE]:void 0}}),pE)Ug[Og]&&jg(Ug[Og],lE,Og);var gE={NATIVE_ARRAY_BUFFER_VIEWS:uE,TYPED_ARRAY_TAG:hE&&lE,aTypedArray:function(e){if(fE(e))return e;throw new aE("Target is not a typed array")},aTypedArrayConstructor:function(e){if(Fg(e)&&(!zg||qg(nE,e)))return e;throw new aE(Gg(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(Vg){if(i)for(var n in pE){var o=Ug[n];if(o&&Hg(o.prototype,e))try{delete o.prototype[e]}catch(uj){try{o.prototype[e]=t}catch(s){}}}oE[e]&&!i||Jg(oE,e,i?t:uE&&tE[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(Vg){if(zg){if(i)for(r in pE)if((n=Ug[r])&&Hg(n,e))try{delete n[e]}catch(uj){}if(nE[e]&&!i)return;try{return Jg(nE,e,i?t:uE&&nE[e]||t)}catch(uj){}}for(r in pE)!(n=Ug[r])||n[e]&&!i||Jg(n,e,t)}},getTypedArrayConstructor:_E,isView:function(e){if(!Bg(e))return!1;var t=Wg(e);return"DataView"===t||Hg(pE,t)||Hg(mE,t)},isTypedArray:fE,TypedArray:nE,TypedArrayPrototype:oE},EE=n,TE=s,vE=xp,yE=gE.NATIVE_ARRAY_BUFFER_VIEWS,SE=EE.ArrayBuffer,IE=EE.Int8Array,RE=!yE||!TE((function(){IE(1)}))||!TE((function(){new IE(-1)}))||!vE((function(e){new IE,new IE(null),new IE(1.5),new IE(e)}),!0)||TE((function(){return 1!==new IE(new SE(2),1,void 0).length})),AE=G,CE=Math.floor,bE=Number.isInteger||function(e){return!AE(e)&&isFinite(e)&&CE(e)===e},kE=or,DE=RangeError,NE=function(e){var t=kE(e);if(t<0)throw new DE("The argument can't be less than 0");return t},wE=RangeError,OE=function(e,t){var i=NE(e);if(i%t)throw new wE("Wrong offset");return i},PE=Math.round,ME=hn,LE=ut,xE=TypeError,VE=function(e){var t=LE(e,"number");if("number"==typeof t)throw new xE("Can't convert number to bigint");return BigInt(t)},UE=Dd,FE=u,BE=_d,HE=Be,WE=mr,GE=pp,jE=sp,JE=ep,KE=function(e){var t=ME(e);return"BigInt64Array"===t||"BigUint64Array"===t},qE=gE.aTypedArrayConstructor,YE=VE,zE=function(e){var t,i,r,n,o,s,a,c,l=BE(this),d=HE(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=jE(d);if(m&&!JE(m))for(c=(a=GE(d,m)).next,d=[];!(s=FE(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=UE(h,arguments[2])),i=WE(d),r=new(qE(l))(i),n=KE(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?YE(o):+o;return r},XE=ca,QE=ud,ZE=G,$E=rt("species"),eT=Array,tT=function(e){var t;return XE(e)&&(t=e.constructor,(QE(t)&&(t===eT||XE(t.prototype))||ZE(t)&&null===(t=t[$E]))&&(t=void 0)),void 0===t?eT:t},iT=Dd,rT=O,nT=Be,oT=mr,sT=function(e,t){return new(tT(e))(0===t?0:t)},aT=I([].push),cT=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=nT(c),_=rT(m),f=oT(_),g=iT(l,d),E=0,T=u||sT,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:aT(v,h)}else switch(e){case 4:return!1;case 7:aT(v,h)}return o?-1:r||n?n:v}},lT={forEach:cT(0),map:cT(1),filter:cT(2),some:cT(3),every:cT(4),find:cT(5),findIndex:cT(6),filterReject:cT(7)},dT=mr,uT=nn,hT=n,pT=u,mT=a,_T=RE,fT=gE,gT=Al,ET=Qa,TT=E,vT=zt,yT=bE,ST=hr,IT=tc,RT=OE,AT=function(e){var t=PE(e);return t<0?0:t>255?255:255&t},CT=mt,bT=Ge,kT=hn,DT=G,NT=pe,wT=lo,OT=q,PT=cs,MT=er.f,LT=zE,xT=lT.forEach,VT=Nl,UT=En,FT=Nt,BT=o,HT=function(e,t,i){for(var r=0,n=arguments.length>2?i:dT(t),o=new e(n);n>r;)o[r]=t[r++];return o},WT=Ic,GT=Ni.get,jT=Ni.set,JT=Ni.enforce,KT=FT.f,qT=BT.f,YT=hT.RangeError,zT=gT.ArrayBuffer,XT=zT.prototype,QT=gT.DataView,ZT=fT.NATIVE_ARRAY_BUFFER_VIEWS,$T=fT.TYPED_ARRAY_TAG,ev=fT.TypedArray,tv=fT.TypedArrayPrototype,iv=fT.isTypedArray,rv="BYTES_PER_ELEMENT",nv="Wrong length",ov=function(e,t){UT(e,t,{configurable:!0,get:function(){return GT(this)[t]}})},sv=function(e){var t;return OT(XT,e)||"ArrayBuffer"===(t=kT(e))||"SharedArrayBuffer"===t},av=function(e,t){return iv(e)&&!NT(t)&&t in e&&yT(+t)&&t>=0},cv=function(e,t){return t=CT(t),av(e,t)?TT(2,e[t]):qT(e,t)},lv=function(e,t,i){return t=CT(t),!(av(e,t)&&DT(i)&&bT(i,"value"))||bT(i,"get")||bT(i,"set")||i.configurable||bT(i,"writable")&&!i.writable||bT(i,"enumerable")&&!i.enumerable?KT(e,t,i):(e[t]=i.value,e)};mT?(ZT||(BT.f=cv,FT.f=lv,ov(tv,"buffer"),ov(tv,"byteOffset"),ov(tv,"byteLength"),ov(tv,"length")),uT({target:"Object",stat:!0,forced:!ZT},{getOwnPropertyDescriptor:cv,defineProperty:lv}),Lg.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=hT[n],c=a,l=c&&c.prototype,d={},u=function(e,t){KT(e,t,{get:function(){return function(e,t){var i=GT(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=GT(e);o.view[s](t*r+o.byteOffset,i?AT(n):n,!0)}(this,t,e)},enumerable:!0})};ZT?_T&&(c=t((function(e,t,i,n){return ET(e,l),WT(DT(t)?sv(t)?void 0!==n?new a(t,RT(i,r),n):void 0!==i?new a(t,RT(i,r)):new a(t):iv(t)?HT(c,t):pT(LT,c,t):new a(IT(t)),e,c)})),PT&&PT(c,ev),xT(MT(a),(function(e){e in c||vT(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,n){ET(e,l);var o,s,a,d=0,h=0;if(DT(t)){if(!sv(t))return iv(t)?HT(c,t):pT(LT,c,t);o=t,h=RT(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw new YT(nv);if((s=p-h)<0)throw new YT(nv)}else if((s=ST(n)*r)+h>p)throw new YT(nv);a=s/r}else a=IT(t),o=new zT(s=a*r);for(jT(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new QT(o)});d<a;)u(e,d++)})),PT&&PT(c,ev),l=c.prototype=wT(tv)),l.constructor!==c&&vT(l,"constructor",c),JT(l).TypedArrayConstructor=c,$T&&vT(l,$T,n);var h=c!==a;d[n]=c,uT({global:!0,constructor:!0,forced:h,sham:!ZT},d),rv in c||vT(c,rv,r),rv in l||vT(l,rv,r),VT(n)}):Lg.exports=function(){};var dv=Lg.exports;dv("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}})),dv("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var uv=Tc,hv=VE,pv=hn,mv=u,_v=s,fv=gE.aTypedArray,gv=gE.exportTypedArrayMethod,Ev=I("".slice);gv("fill",(function(e){var t=arguments.length;fv(this);var i="Big"===Ev(pv(this),0,3)?hv(e):+e;return mv(uv,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),_v((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e}))),(0,gE.exportTypedArrayStaticMethod)("from",zE,RE);var Tv=n,vv=u,yv=gE,Sv=mr,Iv=OE,Rv=Be,Av=s,Cv=Tv.RangeError,bv=Tv.Int8Array,kv=bv&&bv.prototype,Dv=kv&&kv.set,Nv=yv.aTypedArray,wv=yv.exportTypedArrayMethod,Ov=!Av((function(){var e=new Uint8ClampedArray(2);return vv(Dv,e,{length:1,0:3},1),3!==e[1]})),Pv=Ov&&yv.NATIVE_ARRAY_BUFFER_VIEWS&&Av((function(){var e=new bv(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));wv("set",(function(e){Nv(this);var t=Iv(arguments.length>1?arguments[1]:void 0,1),i=Rv(e);if(Ov)return vv(Dv,this,i,t);var r=this.length,n=Sv(i),o=0;if(n+t>r)throw new Cv("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!Ov||Pv);var Mv=xl,Lv=s,xv=Te,Vv=Ta,Uv=ya,Fv=Sa,Bv=re,Hv=Ra,Wv=gE.aTypedArray,Gv=gE.exportTypedArrayMethod,jv=n.Uint16Array,Jv=jv&&Mv(jv.prototype.sort),Kv=!(!Jv||Lv((function(){Jv(new jv(2),null)}))&&Lv((function(){Jv(new jv(2),{})}))),qv=!!Jv&&!Lv((function(){if(Bv)return Bv<74;if(Uv)return Uv<67;if(Fv)return!0;if(Hv)return Hv<602;var e,t,i=new jv(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(Jv(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));Gv("sort",(function(e){return void 0!==e&&xv(e),qv?Jv(this,e):Vv(Wv(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))}),!qv||Kv);var Yv=nn,zv=u,Xv=I,Qv=x,Zv=H,$v=P,ey=Rm,ty=_n,iy=Se,ry=Om,ny=Bf,oy=rt("replace"),sy=TypeError,ay=Xv("".indexOf);Xv("".replace);var cy=Xv("".slice),ly=Math.max;Yv({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,n,o,s,a,c,l,d,u=Qv(this),h=0,p="";if(!$v(e)){if(ey(e)&&(i=ty(Qv(ry(e))),!~ay(i,"g")))throw new sy("`.replaceAll` does not allow non-global regexes");if(r=iy(e,oy))return zv(r,e,u,t)}for(n=ty(u),o=ty(e),(s=Zv(t))||(t=ty(t)),a=o.length,c=ly(1,a),l=ay(n,o);-1!==l;)d=s?ty(t(o,l,n)):ny(o,n,l,[],void 0,t),p+=cy(n,h,l)+d,h=l+a,l=l+c>n.length?-1:ay(n,o,l+c);return h<n.length&&(p+=cy(n,h)),p}});var dy={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},uy=Et("span").classList,hy=uy&&uy.constructor&&uy.constructor.prototype,py=hy===Object.prototype?void 0:hy,my=lT.forEach,_y=Zs("forEach")?[].forEach:function(e){return my(this,e,arguments.length>1?arguments[1]:void 0)},fy=n,gy=dy,Ey=py,Ty=_y,vy=zt,yy=function(e){if(e&&e.forEach!==Ty)try{vy(e,"forEach",Ty)}catch(uj){e.forEach=Ty}};for(var Sy in gy)gy[Sy]&&yy(fy[Sy]&&fy[Sy].prototype);yy(Ey);var Iy=n,Ry=dy,Ay=py,Cy=Hs,by=zt,ky=jo,Dy=rt("iterator"),Ny=Cy.values,wy=function(e,t){if(e){if(e[Dy]!==Ny)try{by(e,Dy,Ny)}catch(uj){e[Dy]=Ny}if(ky(e,t,!0),Ry[t])for(var i in Cy)if(e[i]!==Cy[i])try{by(e,i,Cy[i])}catch(uj){e[i]=Cy[i]}}};for(var Oy in Ry)wy(Iy[Oy]&&Iy[Oy].prototype,Oy);wy(Ay,"DOMTokenList");var Py=Nf.charAt,My=_n,Ly=Ni,xy=ks,Vy=Ds,Uy="String Iterator",Fy=Ly.set,By=Ly.getterFor(Uy);xy(String,"String",(function(e){Fy(this,{type:Uy,string:My(e),index:0})}),(function(){var e,t=By(this),i=t.string,r=t.index;return r>=i.length?Vy(void 0,!0):(e=Py(i,r),t.index+=e.length,Vy(e,!1))}));var Hy=s,Wy=a,Gy=rt("iterator"),jy=!Hy((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&&!Wy||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[Gy]||"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})),Jy=a,Ky=I,qy=u,Yy=s,zy=Hn,Xy=Dr,Qy=h,Zy=Be,$y=O,eS=Object.assign,tS=Object.defineProperty,iS=Ky([].concat),rS=!eS||Yy((function(){if(Jy&&1!==eS({b:1},eS(tS({},"a",{enumerable:!0,get:function(){tS(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!==eS({},e)[i]||zy(eS({},t)).join("")!==r}))?function(e,t){for(var i=Zy(e),r=arguments.length,n=1,o=Xy.f,s=Qy.f;r>n;)for(var a,c=$y(arguments[n++]),l=o?iS(zy(c),o(c)):zy(c),d=l.length,u=0;d>u;)a=l[u++],Jy&&!qy(s,c,a)||(i[a]=c[a]);return i}:eS,nS=Lt,oS=gp,sS=a,aS=Nt,cS=E,lS=Dd,dS=u,uS=Be,hS=function(e,t,i,r){try{return r?t(nS(i)[0],i[1]):t(i)}catch(uj){oS(e,"throw",uj)}},pS=ep,mS=ud,_S=mr,fS=function(e,t,i){sS?aS.f(e,t,cS(0,i)):e[t]=i},gS=pp,ES=sp,TS=Array,vS=I,yS=2147483647,SS=/[^\0-\u007E]/,IS=/[.\u3002\uFF0E\uFF61]/g,RS="Overflow: input needs wider integers to process",AS=RangeError,CS=vS(IS.exec),bS=Math.floor,kS=String.fromCharCode,DS=vS("".charCodeAt),NS=vS([].join),wS=vS([].push),OS=vS("".replace),PS=vS("".split),MS=vS("".toLowerCase),LS=function(e){return e+22+75*(e<26)},xS=function(e,t,i){var r=0;for(e=i?bS(e/700):e>>1,e+=bS(e/t);e>455;)e=bS(e/35),r+=36;return bS(r+36*e/(e+38))},VS=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=DS(e,i++);if(n>=55296&&n<=56319&&i<r){var o=DS(e,i++);56320==(64512&o)?wS(t,((1023&n)<<10)+(1023&o)+65536):(wS(t,n),i--)}else wS(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&&wS(t,kS(r));var c=t.length,l=c;for(c&&wS(t,"-");l<n;){var d=yS;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>bS((yS-s)/u))throw new AS(RS);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++s>yS)throw new AS(RS);if(r===o){for(var h=s,p=36;;){var m=p<=a?1:p>=a+26?26:p-a;if(h<m)break;var _=h-m,f=36-m;wS(t,kS(LS(m+_%f))),h=bS(_/f),p+=36}wS(t,kS(LS(h))),a=xS(s,u,l===c),s=0,l++}}s++,o++}return NS(t,"")},US=nn,FS=I,BS=lr,HS=RangeError,WS=String.fromCharCode,GS=String.fromCodePoint,jS=FS([].join);US({target:"String",stat:!0,arity:1,forced:!!GS&&1!==GS.length},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,n=0;r>n;){if(t=+arguments[n++],BS(t,1114111)!==t)throw new HS(t+" is not a valid code point");i[n]=t<65536?WS(t):WS(55296+((t-=65536)>>10),t%1024+56320)}return jS(i,"")}});var JS=nn,KS=n,qS=lu,YS=K,zS=u,XS=I,QS=a,ZS=jy,$S=$i,eI=En,tI=Ya,iI=jo,rI=Qo,nI=Ni,oI=Qa,sI=H,aI=Ge,cI=Dd,lI=hn,dI=Lt,uI=G,hI=_n,pI=lo,mI=E,_I=pp,fI=sp,gI=Ds,EI=wd,TI=Ta,vI=rt("iterator"),yI="URLSearchParams",SI=yI+"Iterator",II=nI.set,RI=nI.getterFor(yI),AI=nI.getterFor(SI),CI=qS("fetch"),bI=qS("Request"),kI=qS("Headers"),DI=bI&&bI.prototype,NI=kI&&kI.prototype,wI=KS.TypeError,OI=KS.encodeURIComponent,PI=String.fromCharCode,MI=YS("String","fromCodePoint"),LI=parseInt,xI=XS("".charAt),VI=XS([].join),UI=XS([].push),FI=XS("".replace),BI=XS([].shift),HI=XS([].splice),WI=XS("".split),GI=XS("".slice),jI=XS(/./.exec),JI=/\+/g,KI=/^[0-9a-f]+$/i,qI=function(e,t){var i=GI(e,t,t+2);return jI(KI,i)?LI(i,16):NaN},YI=function(e){for(var t=0,i=128;i>0&&e&i;i>>=1)t++;return t},zI=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},XI=function(e){for(var t=(e=FI(e,JI," ")).length,i="",r=0;r<t;){var n=xI(e,r);if("%"===n){if("%"===xI(e,r+1)||r+3>t){i+="%",r++;continue}var o=qI(e,r+1);if(o!=o){i+=n,r++;continue}r+=2;var s=YI(o);if(0===s)n=PI(o);else{if(1===s||s>4){i+="�",r++;continue}for(var a=[o],c=1;c<s&&!(++r+3>t||"%"!==xI(e,r));){var l=qI(e,r+1);if(l!=l){r+=3;break}if(l>191||l<128)break;UI(a,l),r+=2,c++}if(a.length!==s){i+="�";continue}var d=zI(a);null===d?i+="�":n=MI(d)}}i+=n,r++}return i},QI=/[!'()~]|%20/g,ZI={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},$I=function(e){return ZI[e]},eR=function(e){return FI(OI(e),QI,$I)},tR=rI((function(e,t){II(this,{type:SI,target:RI(e).entries,index:0,kind:t})}),yI,(function(){var e=AI(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,gI(void 0,!0);var r=t[i];switch(e.kind){case"keys":return gI(r.key,!1);case"values":return gI(r.value,!1)}return gI([r.key,r.value],!1)}),!0),iR=function(e){this.entries=[],this.url=null,void 0!==e&&(uI(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===xI(e,0)?GI(e,1):e:hI(e)))};iR.prototype={type:yI,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,s,a,c=this.entries,l=fI(e);if(l)for(i=(t=_I(e,l)).next;!(r=zS(i,t)).done;){if(o=(n=_I(dI(r.value))).next,(s=zS(o,n)).done||(a=zS(o,n)).done||!zS(o,n).done)throw new wI("Expected sequence with length 2");UI(c,{key:hI(s.value),value:hI(a.value)})}else for(var d in e)aI(e,d)&&UI(c,{key:d,value:hI(e[d])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,n=WI(e,"&"),o=0;o<n.length;)(t=n[o++]).length&&(i=WI(t,"="),UI(r,{key:XI(BI(i)),value:XI(VI(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],UI(i,eR(e.key)+"="+eR(e.value));return VI(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var rR=function(){oI(this,nR);var e=II(this,new iR(arguments.length>0?arguments[0]:void 0));QS||(this.size=e.entries.length)},nR=rR.prototype;if(tI(nR,{append:function(e,t){var i=RI(this);EI(arguments.length,2),UI(i.entries,{key:hI(e),value:hI(t)}),QS||this.length++,i.updateURL()},delete:function(e){for(var t=RI(this),i=EI(arguments.length,1),r=t.entries,n=hI(e),o=i<2?void 0:arguments[1],s=void 0===o?o:hI(o),a=0;a<r.length;){var c=r[a];if(c.key!==n||void 0!==s&&c.value!==s)a++;else if(HI(r,a,1),void 0!==s)break}QS||(this.size=r.length),t.updateURL()},get:function(e){var t=RI(this).entries;EI(arguments.length,1);for(var i=hI(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=RI(this).entries;EI(arguments.length,1);for(var i=hI(e),r=[],n=0;n<t.length;n++)t[n].key===i&&UI(r,t[n].value);return r},has:function(e){for(var t=RI(this).entries,i=EI(arguments.length,1),r=hI(e),n=i<2?void 0:arguments[1],o=void 0===n?n:hI(n),s=0;s<t.length;){var a=t[s++];if(a.key===r&&(void 0===o||a.value===o))return!0}return!1},set:function(e,t){var i=RI(this);EI(arguments.length,1);for(var r,n=i.entries,o=!1,s=hI(e),a=hI(t),c=0;c<n.length;c++)(r=n[c]).key===s&&(o?HI(n,c--,1):(o=!0,r.value=a));o||UI(n,{key:s,value:a}),QS||(this.size=n.length),i.updateURL()},sort:function(){var e=RI(this);TI(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=RI(this).entries,r=cI(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 tR(this,"keys")},values:function(){return new tR(this,"values")},entries:function(){return new tR(this,"entries")}},{enumerable:!0}),$S(nR,vI,nR.entries,{name:"entries"}),$S(nR,"toString",(function(){return RI(this).serialize()}),{enumerable:!0}),QS&&eI(nR,"size",{get:function(){return RI(this).entries.length},configurable:!0,enumerable:!0}),iI(rR,yI),JS({global:!0,constructor:!0,forced:!ZS},{URLSearchParams:rR}),!ZS&&sI(kI)){var oR=XS(NI.has),sR=XS(NI.set),aR=function(e){if(uI(e)){var t,i=e.body;if(lI(i)===yI)return t=e.headers?new kI(e.headers):new kI,oR(t,"content-type")||sR(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),pI(e,{body:mI(0,hI(i)),headers:mI(0,t)})}return e};if(sI(CI)&&JS({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return CI(e,arguments.length>1?aR(arguments[1]):{})}}),sI(bI)){var cR=function(e){return oI(this,DI),new bI(e,arguments.length>1?aR(arguments[1]):{})};DI.constructor=cR,cR.prototype=DI,JS({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:cR})}}var lR,dR=nn,uR=a,hR=jy,pR=n,mR=Dd,_R=I,fR=$i,gR=En,ER=Qa,TR=Ge,vR=rS,yR=function(e){var t=uS(e),i=mS(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=lS(n,r>2?arguments[2]:void 0));var s,a,c,l,d,u,h=ES(t),p=0;if(!h||this===TS&&pS(h))for(s=_S(t),a=i?new this(s):TS(s);s>p;p++)u=o?n(t[p],p):t[p],fS(a,p,u);else for(a=i?new this:[],d=(l=gS(t,h)).next;!(c=dS(d,l)).done;p++)u=o?hS(l,n,[c.value,p],!0):c.value,fS(a,p,u);return a.length=p,a},SR=_a,IR=Nf.codeAt,RR=function(e){var t,i,r=[],n=PS(OS(MS(e),IS,"."),".");for(t=0;t<n.length;t++)i=n[t],wS(r,CS(SS,i)?"xn--"+VS(i):i);return NS(r,".")},AR=_n,CR=jo,bR=wd,kR={URLSearchParams:rR,getState:RI},DR=Ni,NR=DR.set,wR=DR.getterFor("URL"),OR=kR.URLSearchParams,PR=kR.getState,MR=pR.URL,LR=pR.TypeError,xR=pR.parseInt,VR=Math.floor,UR=Math.pow,FR=_R("".charAt),BR=_R(/./.exec),HR=_R([].join),WR=_R(1..toString),GR=_R([].pop),jR=_R([].push),JR=_R("".replace),KR=_R([].shift),qR=_R("".split),YR=_R("".slice),zR=_R("".toLowerCase),XR=_R([].unshift),QR="Invalid scheme",ZR="Invalid host",$R="Invalid port",eA=/[a-z]/i,tA=/[\d+-.a-z]/i,iA=/\d/,rA=/^0x/i,nA=/^[0-7]+$/,oA=/^\d+$/,sA=/^[\da-f]+$/i,aA=/[\0\t\n\r #%/:<>?@[\\\]^|]/,cA=/[\0\t\n\r #/:<>?@[\\\]^|]/,lA=/^[\u0000-\u0020]+/,dA=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,uA=/[\t\n\r]/g,hA=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)XR(t,e%256),e=VR(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+=WR(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},pA={},mA=vR({},pA,{" ":1,'"':1,"<":1,">":1,"`":1}),_A=vR({},mA,{"#":1,"?":1,"{":1,"}":1}),fA=vR({},_A,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),gA=function(e,t){var i=IR(e,0);return i>32&&i<127&&!TR(t,e)?e:encodeURIComponent(e)},EA={ftp:21,file:null,http:80,https:443,ws:80,wss:443},TA=function(e,t){var i;return 2===e.length&&BR(eA,FR(e,0))&&(":"===(i=FR(e,1))||!t&&"|"===i)},vA=function(e){var t;return e.length>1&&TA(YR(e,0,2))&&(2===e.length||"/"===(t=FR(e,2))||"\\"===t||"?"===t||"#"===t)},yA=function(e){return"."===e||"%2e"===zR(e)},SA={},IA={},RA={},AA={},CA={},bA={},kA={},DA={},NA={},wA={},OA={},PA={},MA={},LA={},xA={},VA={},UA={},FA={},BA={},HA={},WA={},GA=function(e,t,i){var r,n,o,s=AR(e);if(t){if(n=this.parse(s))throw new LR(n);this.searchParams=null}else{if(void 0!==i&&(r=new GA(i,!0)),n=this.parse(s,null,r))throw new LR(n);(o=PR(new OR)).bindURL(this),this.searchParams=o}};GA.prototype={type:"URL",parse:function(e,t,i){var r,n,o,s,a,c=this,l=t||SA,d=0,u="",h=!1,p=!1,m=!1;for(e=AR(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=JR(e,lA,""),e=JR(e,dA,"$1")),e=JR(e,uA,""),r=yR(e);d<=r.length;){switch(n=r[d],l){case SA:if(!n||!BR(eA,n)){if(t)return QR;l=RA;continue}u+=zR(n),l=IA;break;case IA:if(n&&(BR(tA,n)||"+"===n||"-"===n||"."===n))u+=zR(n);else{if(":"!==n){if(t)return QR;u="",l=RA,d=0;continue}if(t&&(c.isSpecial()!==TR(EA,u)||"file"===u&&(c.includesCredentials()||null!==c.port)||"file"===c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&EA[c.scheme]===c.port&&(c.port=null));u="","file"===c.scheme?l=LA:c.isSpecial()&&i&&i.scheme===c.scheme?l=AA:c.isSpecial()?l=DA:"/"===r[d+1]?(l=CA,d++):(c.cannotBeABaseURL=!0,jR(c.path,""),l=BA)}break;case RA:if(!i||i.cannotBeABaseURL&&"#"!==n)return QR;if(i.cannotBeABaseURL&&"#"===n){c.scheme=i.scheme,c.path=SR(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=WA;break}l="file"===i.scheme?LA:bA;continue;case AA:if("/"!==n||"/"!==r[d+1]){l=bA;continue}l=NA,d++;break;case CA:if("/"===n){l=wA;break}l=FA;continue;case bA:if(c.scheme=i.scheme,n===lR)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=SR(i.path),c.query=i.query;else if("/"===n||"\\"===n&&c.isSpecial())l=kA;else if("?"===n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=SR(i.path),c.query="",l=HA;else{if("#"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=SR(i.path),c.path.length--,l=FA;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=SR(i.path),c.query=i.query,c.fragment="",l=WA}break;case kA:if(!c.isSpecial()||"/"!==n&&"\\"!==n){if("/"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=FA;continue}l=wA}else l=NA;break;case DA:if(l=NA,"/"!==n||"/"!==FR(u,d+1))continue;d++;break;case NA:if("/"!==n&&"\\"!==n){l=wA;continue}break;case wA:if("@"===n){h&&(u="%40"+u),h=!0,o=yR(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!==f||m){var g=gA(f,fA);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n===lR||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(h&&""===u)return"Invalid authority";d-=yR(u).length+1,u="",l=OA}else u+=n;break;case OA:case PA:if(t&&"file"===c.scheme){l=VA;continue}if(":"!==n||p){if(n===lR||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(c.isSpecial()&&""===u)return ZR;if(t&&""===u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=UA,t)return;continue}"["===n?p=!0:"]"===n&&(p=!1),u+=n}else{if(""===u)return ZR;if(s=c.parseHost(u))return s;if(u="",l=MA,t===PA)return}break;case MA:if(!BR(iA,n)){if(n===lR||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()||t){if(""!==u){var E=xR(u,10);if(E>65535)return $R;c.port=c.isSpecial()&&E===EA[c.scheme]?null:E,u=""}if(t)return;l=UA;continue}return $R}u+=n;break;case LA:if(c.scheme="file","/"===n||"\\"===n)l=xA;else{if(!i||"file"!==i.scheme){l=FA;continue}switch(n){case lR:c.host=i.host,c.path=SR(i.path),c.query=i.query;break;case"?":c.host=i.host,c.path=SR(i.path),c.query="",l=HA;break;case"#":c.host=i.host,c.path=SR(i.path),c.query=i.query,c.fragment="",l=WA;break;default:vA(HR(SR(r,d),""))||(c.host=i.host,c.path=SR(i.path),c.shortenPath()),l=FA;continue}}break;case xA:if("/"===n||"\\"===n){l=VA;break}i&&"file"===i.scheme&&!vA(HR(SR(r,d),""))&&(TA(i.path[0],!0)?jR(c.path,i.path[0]):c.host=i.host),l=FA;continue;case VA:if(n===lR||"/"===n||"\\"===n||"?"===n||"#"===n){if(!t&&TA(u))l=FA;else if(""===u){if(c.host="",t)return;l=UA}else{if(s=c.parseHost(u))return s;if("localhost"===c.host&&(c.host=""),t)return;u="",l=UA}continue}u+=n;break;case UA:if(c.isSpecial()){if(l=FA,"/"!==n&&"\\"!==n)continue}else if(t||"?"!==n)if(t||"#"!==n){if(n!==lR&&(l=FA,"/"!==n))continue}else c.fragment="",l=WA;else c.query="",l=HA;break;case FA:if(n===lR||"/"===n||"\\"===n&&c.isSpecial()||!t&&("?"===n||"#"===n)){if(".."===(a=zR(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"===n||"\\"===n&&c.isSpecial()||jR(c.path,"")):yA(u)?"/"===n||"\\"===n&&c.isSpecial()||jR(c.path,""):("file"===c.scheme&&!c.path.length&&TA(u)&&(c.host&&(c.host=""),u=FR(u,0)+":"),jR(c.path,u)),u="","file"===c.scheme&&(n===lR||"?"===n||"#"===n))for(;c.path.length>1&&""===c.path[0];)KR(c.path);"?"===n?(c.query="",l=HA):"#"===n&&(c.fragment="",l=WA)}else u+=gA(n,_A);break;case BA:"?"===n?(c.query="",l=HA):"#"===n?(c.fragment="",l=WA):n!==lR&&(c.path[0]+=gA(n,pA));break;case HA:t||"#"!==n?n!==lR&&("'"===n&&c.isSpecial()?c.query+="%27":c.query+="#"===n?"%23":gA(n,pA)):(c.fragment="",l=WA);break;case WA:n!==lR&&(c.fragment+=gA(n,mA))}d++}},parseHost:function(e){var t,i,r;if("["===FR(e,0)){if("]"!==FR(e,e.length-1))return ZR;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 FR(e,u)};if(":"===h()){if(":"!==FR(e,1))return;u+=2,d=++l}for(;h();){if(8===l)return;if(":"!==h()){for(t=i=0;i<4&&BR(sA,h());)t=16*t+xR(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(!BR(iA,h()))return;for(;BR(iA,h());){if(o=xR(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}(YR(e,1,-1)),!t)return ZR;this.host=t}else if(this.isSpecial()){if(e=RR(e),BR(aA,e))return ZR;if(t=function(e){var t,i,r,n,o,s,a,c=qR(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"===FR(n,0)&&(o=BR(rA,n)?16:8,n=YR(n,8===o?1:2)),""===n)s=0;else{if(!BR(10===o?oA:8===o?nA:sA,n))return e;s=xR(n,o)}jR(i,s)}for(r=0;r<t;r++)if(s=i[r],r===t-1){if(s>=UR(256,5-t))return null}else if(s>255)return null;for(a=GR(i),r=0;r<i.length;r++)a+=i[r]*UR(256,3-r);return a}(e),null===t)return ZR;this.host=t}else{if(BR(cA,e))return ZR;for(t="",i=yR(e),r=0;r<i.length;r++)t+=gA(i[r],pA);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return TR(EA,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&TA(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+=hA(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 LR(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new jA(e.path[0]).origin}catch(uj){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+hA(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(AR(e)+":",SA)},getUsername:function(){return this.username},setUsername:function(e){var t=yR(AR(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=gA(t[i],fA)}},getPassword:function(){return this.password},setPassword:function(e){var t=yR(AR(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=gA(t[i],fA)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?hA(e):hA(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,OA)},getHostname:function(){var e=this.host;return null===e?"":hA(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,PA)},getPort:function(){var e=this.port;return null===e?"":AR(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=AR(e))?this.port=null:this.parse(e,MA))},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,UA))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=AR(e))?this.query=null:("?"===FR(e,0)&&(e=YR(e,1)),this.query="",this.parse(e,HA)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=AR(e))?("#"===FR(e,0)&&(e=YR(e,1)),this.fragment="",this.parse(e,WA)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var jA=function(e){var t=ER(this,JA),i=bR(arguments.length,1)>1?arguments[1]:void 0,r=NR(t,new GA(e,!1,i));uR||(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())},JA=jA.prototype,KA=function(e,t){return{get:function(){return wR(this)[e]()},set:t&&function(e){return wR(this)[t](e)},configurable:!0,enumerable:!0}};if(uR&&(gR(JA,"href",KA("serialize","setHref")),gR(JA,"origin",KA("getOrigin")),gR(JA,"protocol",KA("getProtocol","setProtocol")),gR(JA,"username",KA("getUsername","setUsername")),gR(JA,"password",KA("getPassword","setPassword")),gR(JA,"host",KA("getHost","setHost")),gR(JA,"hostname",KA("getHostname","setHostname")),gR(JA,"port",KA("getPort","setPort")),gR(JA,"pathname",KA("getPathname","setPathname")),gR(JA,"search",KA("getSearch","setSearch")),gR(JA,"searchParams",KA("getSearchParams")),gR(JA,"hash",KA("getHash","setHash"))),fR(JA,"toJSON",(function(){return wR(this).serialize()}),{enumerable:!0}),fR(JA,"toString",(function(){return wR(this).serialize()}),{enumerable:!0}),MR){var qA=MR.createObjectURL,YA=MR.revokeObjectURL;qA&&fR(jA,"createObjectURL",mR(qA,MR)),YA&&fR(jA,"revokeObjectURL",mR(YA,MR))}CR(jA,"URL"),dR({global:!0,constructor:!0,forced:!hR,sham:!uR},{URL:jA});var zA=u;nn({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return zA(URL.prototype.toString,this)}});let XA=!0,QA=!0;function ZA(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function $A(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 eC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(XA=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function tC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(QA=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function iC(){if("object"==typeof window){if(XA)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function rC(e,t){QA&&console.warn(e+" is deprecated, please use "+t+" instead.")}function nC(e){return"[object Object]"===Object.prototype.toString.call(e)}function oC(e){return nC(e)?Object.keys(e).reduce((function(t,i){const r=nC(e[i]),n=r?oC(e[i]):e[i],o=r&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[i]:n})}),{}):e}function sC(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?sC(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{sC(e,e.get(t),i)}))})))}function aC(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&&sC(e,i,n)}))})),n}const cC=iC;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),cC("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return cC("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 dC(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 $A(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function hC(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 pC(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 mC(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=>aC(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}),$A(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>aC(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 _C(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 fC(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return _C(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 EC(e,t){$A(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var TC=Object.freeze({__proto__:null,shimMediaStream:dC,shimOnTrack:uC,shimGetSendersWithDtmf:hC,shimGetStats:pC,shimSenderReceiverGetStats:mC,shimAddTrackRemoveTrackWithNative:_C,shimAddTrackRemoveTrack:fC,shimPeerConnection:gC,fixNegotiationNeeded:EC,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 vC(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){rC("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 yC(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function SC(e,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(qb){if("TypeError"!==qb.name)throw qb;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,o)}}function IC(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function RC(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),$A(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function AC(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){rC("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function CC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function bC(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 kC(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 DC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function NC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var wC=Object.freeze({__proto__:null,shimOnTrack:yC,shimPeerConnection:SC,shimSenderGetStats:IC,shimReceiverGetStats:RC,shimRemoveStream:AC,shimRTCDataChannel:CC,shimAddTransceiver:bC,shimGetParameters:kC,shimCreateOffer:DC,shimCreateAnswer:NC,shimGetUserMedia:vC,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 OC(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function PC(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function MC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,i){const r=n.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r};t.setLocalDescription=a,a=function(e,t,i){const r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.setRemoteDescription=a,a=function(e,t,i){const r=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.addIceCandidate=a}function LC(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(xC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function xC(e){return e&&void 0!==e.video?Object.assign({},e,{video:oC(e.video)}):e}function VC(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let r=e.iceServers[i];void 0===r.urls&&r.url?(rC("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 UC(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 FC(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 BC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var HC=Object.freeze({__proto__:null,shimLocalStreamsAPI:OC,shimRemoteStreamsAPI:PC,shimCallbacksAPI:MC,shimGetUserMedia:LC,shimConstraints:xC,shimRTCIceServerUrls:VC,shimTrackEventTransceiver:UC,shimCreateOfferLegacy:FC,shimAudioContext:BC}),WC={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}(WC);var GC=WC.exports,jC=i(GC),JC=e({__proto__:null,default:jC},[GC]);function KC(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),r=jC.parseCandidate(e.candidate);for(const e in r)e in i||Object.defineProperty(i,e,{value:r[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,$A(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function qC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||$A(e,"icecandidate",(e=>{if(e.candidate){const t=jC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function YC(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=jC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=jC.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),r=function(e,i){let r=65536;"firefox"===t.browser&&57===t.version&&(r=65535);const n=jC.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?r=parseInt(n[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(r=2147483637),r}(arguments[0],e);let n;n=0===i&&0===r?Number.POSITIVE_INFINITY:0===i||0===r?Math.max(i,r):Math.min(i,r);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>n}),this._sctp=o}return i.apply(this,arguments)}}function zC(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},$A(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function XC(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 QC(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function ZC(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 $C(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 eb=Object.freeze({__proto__:null,shimRTCIceCandidate:KC,shimRTCIceCandidateRelayProtocol:qC,shimMaxMessageSize:YC,shimSendThrowTypeError:zC,shimConnectionState:XC,removeExtmapAllowMixed:QC,shimAddIceCandidateNullOrEmpty:ZC,shimParameterlessSetLocalDescription:$C});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=iC,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=ZA(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=ZA(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=ZA(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:eb,extractVersion:ZA,disableLog:eC,disableWarnings:tC,sdp:JC};switch(r.browser){case"chrome":if(!TC||!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=TC,ZC(e,r),$C(e),lC(e,r),dC(e),gC(e,r),uC(e),fC(e,r),hC(e),pC(e),mC(e),EC(e,r),KC(e),qC(e),XC(e),YC(e,r),zC(e),QC(e,r);break;case"firefox":if(!wC||!SC||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=wC,ZC(e,r),$C(e),vC(e,r),SC(e,r),yC(e),AC(e),IC(e),RC(e),CC(e),bC(e),kC(e),DC(e),NC(e),KC(e),XC(e),YC(e,r),zC(e);break;case"safari":if(!HC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=HC,ZC(e,r),$C(e),VC(e),FC(e),MC(e),OC(e),PC(e),UC(e),LC(e),BC(e),KC(e),qC(e),YC(e,r),zC(e),QC(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var tb,ib=Object.create,rb=Object.defineProperty,nb=Object.defineProperties,ob=Object.getOwnPropertyDescriptor,sb=Object.getOwnPropertyDescriptors,ab=Object.getOwnPropertyNames,cb=Object.getOwnPropertySymbols,lb=Object.getPrototypeOf,db=Object.prototype.hasOwnProperty,ub=Object.prototype.propertyIsEnumerable,hb=Reflect.get,pb=Math.pow,mb=(e,t,i)=>t in e?rb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,_b=(e,t)=>{for(var i in t||(t={}))db.call(t,i)&&mb(e,i,t[i]);if(cb)for(var i of cb(t))ub.call(t,i)&&mb(e,i,t[i]);return e},fb=(e,t)=>nb(e,sb(t)),gb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Eb=(e,t)=>{for(var i in t)rb(e,i,{get:t[i],enumerable:!0})},Tb=(e,t,i)=>(i=null!=e?ib(lb(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of ab(t))!db.call(e,n)&&n!==i&&rb(e,n,{get:()=>t[n],enumerable:!(r=ob(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:rb(i,"default",{value:e,enumerable:!0}),e)),vb=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?ob(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&&rb(t,i,o),o},yb=(e,t,i)=>mb(e,"symbol"!=typeof t?t+"":t,i),Sb=(e,t,i)=>hb(lb(e),i,t),Ib=(e,t,i)=>new Promise(((r,n)=>{var o=e=>{try{a(i.next(e))}catch(WO){n(WO)}},s=e=>{try{a(i.throw(e))}catch(WO){n(WO)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),Rb=gb(((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)})),Ab=gb(((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")}))}))})),Cb=gb((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=Ab(),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}}))}))}})),bb=gb(((e,t)=>{var i=Ab(),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"}})),kb=gb((e=>{var t=Cb(),i=bb(),r=Ab();e.grammar=r,e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),Db=gb(((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),Nb=gb((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var n=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:n&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=Db(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),wb=gb(((e,t)=>{var i=Db(),r=/%[sdv%]/g,n=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},o=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||s,n=t.innerOrder||a,c=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),Ob=gb((e=>{var t=Nb(),i=wb();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),Pb=Tb(Rb()),Mb=((tb=Mb||{})[tb.INVALID_PARAMETER=4096]="INVALID_PARAMETER",tb[tb.INVALID_OPERATION=4097]="INVALID_OPERATION",tb[tb.NOT_SUPPORTED=4098]="NOT_SUPPORTED",tb[tb.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",tb[tb.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",tb[tb.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",tb[tb.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",tb[tb.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",tb[tb.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",tb[tb.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",tb[tb.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",tb[tb.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",tb[tb.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",tb[tb.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",tb[tb.CLIENT_BANNED=16448]="CLIENT_BANNED",tb[tb.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",tb[tb.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",tb[tb.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",tb[tb.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",tb[tb.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",tb[tb.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",tb[tb.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",tb[tb.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",tb[tb.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",tb[tb.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",tb[tb.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",tb[tb.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",tb[tb.API_CALL_ABORTED=16461]="API_CALL_ABORTED",tb[tb.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",tb[tb.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",tb[tb.UNKNOWN=65535]="UNKNOWN",tb),Lb=Mb,xb=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=Lb.UNKNOWN,extraCode:n=0,constraint:o}=e,s="<".concat(function(e){for(let t in Lb)if(Lb[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),yb(this,"code"),yb(this,"extraCode"),yb(this,"message"),yb(this,"originMessage"),yb(this,"name"),yb(this,"constraint"),this.code=r,this.extraCode=n,this.name=t,this.message=a,this.constraint=o,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},Vb=xb,Ub=((new Date).getTime(),0),Fb=function(){return(new Date).getTime()+Ub},Bb=function(){let e=new Date;return e.setTime(Fb()),e.toLocaleString()},Hb=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)},Wb={};Eb(Wb,{bytes2ms:()=>PD,calculateScaleResolutionDownNumber:()=>bN,convertObjectNumberToInt:()=>SN,copyProperties:()=>OD,deepClone:()=>hN,deepMerge:()=>uN,delay:()=>IN,fibonacci:()=>BD,formatedTime:()=>_N,getConstructorName:()=>eN,getContainerFromElement:()=>mN,getEnv:()=>RD,getInternalVersion:()=>oN,getLoggerUrl:()=>CD,getMediaStreamTrackInfo:()=>CN,getMuteStateFromFlag:()=>cN,getNetworkType:()=>kD,getNumNetworkType:()=>wD,getReconnectionTimeout:()=>HD,getStringByteLength:()=>EN,getTurnServer:()=>lN,getUint32Version:()=>yN,getValueType:()=>WD,getViewListFromView:()=>pN,glog:()=>VD,ipv4ToUint32:()=>dN,isArray:()=>zD,isAudioWorkletSupported:()=>tN,isBoolean:()=>qD,isConstructor:()=>$D,isEmpty:()=>aN,isFunction:()=>GD,isLangChinese:()=>UD,isMediaStreamTrack:()=>XD,isNumber:()=>KD,isObject:()=>YD,isOverseaSdkAppId:()=>AD,isPlainObject:()=>FD,isPortrait:()=>TN,isPromise:()=>ZD,isRemoteTrack:()=>QD,isString:()=>JD,isUndefined:()=>jD,loadImage:()=>vN,ms2bytes:()=>LD,ms2samples:()=>xD,normalizeUrl:()=>AN,performanceNow:()=>rN,promiseAny:()=>iN,samples2ms:()=>MD,setNetworkType:()=>ND,stringify:()=>fN,stringifyIncludeValue:()=>gN,throttlePromise:()=>RN});var Gb={};Eb(Gb,{AUDIO_MUTE_BIT:()=>Nk,AUDIO_STAT_BIT:()=>Dk,AUX_STAT_BIT:()=>kk,AUX_STREAM_MSID:()=>Lk,BACKEND_ENV:()=>Rk,BASE_DOC_URL:()=>nk,BASE_HOST:()=>ek,CAPABILITIES_KEYS:()=>SD,CLASS_NAME:()=>pD,CLOUD_CONSOLE_URL:()=>rk,CROSS_ROOM_BIT:()=>Pk,DATA_FREEZE_TIMING:()=>sD,DEFAULT_ASSETS_URL:()=>ok,DOC_URL:()=>sk,DTLS_STATE_UNKNOWN:()=>Jk,ENV_NAME:()=>uk,EXCHANGE_SDP_TIMEOUT:()=>tD,IS_WORKER:()=>zb,IS_WORKLET:()=>Xb,KIBANA_EVENT:()=>Zk,LOCAL_STREAM_PUBLISH_STATE:()=>oD,LOGGER_CMD_TYPE:()=>dk,LOGGER_DOMAIN:()=>ak,LOGGER_DOMAIN_OVERSEA:()=>ck,LOG_LEVEL:()=>hk,LOG_LEVEL_NAME:()=>ED,MAIN_STREAM_MSID:()=>Mk,MAX_RTT:()=>ID,MICROPHONE_COMMUNICATIONS:()=>gD,MICROPHONE_DEFAULT:()=>_D,MUTE_ALL_BIT:()=>Ok,NAME:()=>Sk,NETWORK_TYPE:()=>_k,NOT_SUPPORTED_H264:()=>nD,PAUSED_RETRY_COUNT:()=>mD,PEERCONNECTION_CONNECTING_TIMEOUT:()=>dD,PEER_CONNECTION_STATE:()=>Kk,PEER_LEAVE_REASON:()=>TD,RECOVER_CAPTURE_INTERVAL:()=>yD,REMOTE_STREAM_TYPE_AUX:()=>Vk,REMOTE_STREAM_TYPE_MAIN:()=>xk,RENDER_FREEZE_TIMING:()=>aD,SCHEDULE_DOMAIN:()=>uD,SCHEDULE_TIMEOUT:()=>hD,SDP_SEMANTICS_PLAN_B:()=>rD,SDP_SEMANTICS_UNIFIED_PLAN:()=>iD,SECOND_HOST:()=>tk,SIGNAL_PING_PONG_INTERVAL:()=>mk,SIGNAL_PING_TIMEOUT:()=>pk,SIGNAL_RECONNECTION_COUNT:()=>Qk,SMALL_STAT_BIT:()=>bk,SPEAKER_DEFAULT:()=>fD,STORAGE_EXPIRES_TIME:()=>fk,STREAM_TYPE_BIG:()=>cD,STREAM_TYPE_SMALL:()=>lD,SUBSCRIBE_SMALL_RETRY_COUNT:()=>vD,SYNC_USER_LIST_INTERVAL:()=>$k,Scene:()=>Ak,THIRD_HOST:()=>ik,TRANSPORT_DIRECTION:()=>Ik,TRTC_ERROR_ASSISTANCE:()=>lk,TRTC_QUALITY_BAD:()=>Wk,TRTC_QUALITY_DISCONNECTED:()=>jk,TRTC_QUALITY_EXCELLENT:()=>Fk,TRTC_QUALITY_GOOD:()=>Bk,TRTC_QUALITY_POOR:()=>Hk,TRTC_QUALITY_UNKNOWN:()=>Uk,TRTC_QUALITY_VERY_BAD:()=>Gk,UPDATE_OFFER_TIMEOUT:()=>eD,VIDEO_MUTE_BIT:()=>wk,VIDEO_STAT_BIT:()=>Ck,audioProfileMap:()=>gk,defaultBigVideoProfile:()=>Tk,defaultSmallVideoProfile:()=>vk,getRetryCount:()=>zk,getScriptDir:()=>Qb,innerVersion:()=>jb,loggerProxy:()=>Zb,screenProfileMap:()=>yk,setLoggerProxy:()=>$b,setRetryCount:()=>Yk,setVersion:()=>Kb,version:()=>Jb,videoProfileMap:()=>Ek});var jb="4.15.00.1600",Jb="5.0.0";function Kb(e){Jb=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));jb="".concat(t,".").concat(Math.min(15,i),".").concat(Math.min(15,r),".").concat(i.toString().padStart(2,"0")).concat(r.toString().padStart(2,"0"))}var qb,Yb,zb="undefined"!=typeof importScripts,Xb="undefined"!=typeof registerProcessor,Qb=()=>{let e=zb?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Zb="",$b=e=>Zb=e,ek="web.sdk.qcloud.com",tk="web.sdk.tencent.cn",ik="web.sdk.cloud.tencent.cn",rk="https://console.cloud.tencent.com/trtc",nk="https://".concat(ek,"/trtc/webrtc/v5/doc"),ok="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",sk="".concat(nk,"/zh-cn/"),ak="https://yun.tim.qq.com",ck="https://apisgp.my-imcloud.com",lk="trtc_error_assistance",dk={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},uk={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},hk=((Yb=hk||{})[Yb.TRACE=0]="TRACE",Yb[Yb.DEBUG=1]="DEBUG",Yb[Yb.INFO=2]="INFO",Yb[Yb.WARN=3]="WARN",Yb[Yb.ERROR=4]="ERROR",Yb[Yb.NONE=5]="NONE",Yb),pk=18e3,mk=2e3,_k={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},fk=6048e5,gk={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},Ek={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},Tk=Ek["480p_2"],vk=Ek["120p_2"],yk={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},Sk={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},Ik={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Rk={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Ak=((qb=Ak||{}).LIVE="live",qb.RTC="rtc",qb),Ck=1,bk=2,kk=4,Dk=8,Nk=64,wk=16,Ok=112,Pk=128,Mk="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Lk="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",xk=Sk.MAIN,Vk=Sk.AUXILIARY,Uk=0,Fk=1,Bk=2,Hk=3,Wk=4,Gk=5,jk=6,Jk="unknown",Kk={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},qk=1/0;function Yk(e){qk=e}function zk(){return qk}var Xk,Qk=30,Zk={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},$k=1e4,eD=1e4,tD=1e4,iD="unified-plan",rD="plan-b",nD=1028,oD=((Xk=oD||{})[Xk.UNPUBLISH=-1]="UNPUBLISH",Xk[Xk.PUBLISHING=0]="PUBLISHING",Xk[Xk.PUBLISHED=1]="PUBLISHED",Xk),sD=500,aD=1e3,cD=Sk.BIG,lD=Sk.SMALL,dD=1e4,uD={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},hD=2e3,pD={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},mD=5,_D="default",fD=_D,gD="communications",ED=Object.keys(hk),TD=["normal leave","timeout leave","kick","role change"],vD=10,yD=2e3,SD=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],ID=1e4,RD=function(){return new URLSearchParams(location.search).get("trtc_env")||""},AD=e=>Number(e)<14e8,CD=function(e,t){let i;i=Zb||(AD(e)?ck:ak);let r=Math.floor(Math.random()*pb(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},bD="unknown";function kD(){if("unknown"!==bD)return bD;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&&(bD=DD(r,n)),bD}function DD(e,t){if(_k[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function ND(e){bD=DD(e)}function wD(){return _k[kD()]}function OD(e,t){for(let i of Reflect.ownKeys(t))if("constructor"!==i&&"prototype"!==i&&"name"!==i){let r=Object.getOwnPropertyDescriptor(t,i)||"";Object.defineProperty(e,i,r)}return e}function PD(e){return MD(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function MD(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function LD(e){return 4*xD(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function xD(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var VD="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},UD=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},FD=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 BD(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:BD(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function HD(e){return e>8?3e4:1e3*BD(e)}function WD(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var GD=e=>"function"==typeof e,jD=e=>void 0===e,JD=e=>"string"==typeof e,KD=e=>"number"==typeof e,qD=e=>"boolean"==typeof e,YD=e=>"object"===WD(e),zD=e=>"array"===WD(e),XD=e=>WD(e)==="MediaStreamTrack".toLowerCase(),QD=e=>e.isRemote,ZD=e=>"promise"===WD(e),$D=e=>GD(e)&&e.prototype.constructor===e,eN=e=>$D(e)?e.prototype.constructor.name:"",tN="undefined"!=typeof AudioWorkletNode;function iN(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 rN(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var nN=e=>+e<10?"0".concat(e):e,oN=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=nN(i[1])+nN(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},sN=Object.prototype.hasOwnProperty;function aN(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(FD(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(let t in e)if(sN.call(e,t))return!1;return!0}return!1}function cN(e,t){return{userId:t,hasAudio:!!(e&Dk),hasVideo:!!(e&Ck),hasAuxiliary:!!(e&kk),hasSmall:!!(e&bk),audioMuted:!!(e&Nk),videoMuted:!!(e&wk),audioAvailable:!(!(e&Dk)||e&Nk),videoAvailable:!(!(e&Ck)||e&wk)}}function lN(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!jD(e.username)&&!jD(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",jD(e.credentialType)||(t.credentialType=e.credentialType)),t}function dN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!JD(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 uN=function(e,t,i,r){if(!YD(e)||!YD(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],!(jD(t[n])||i&&i.includes(n)))if(YD(e[n])&&YD(t[n]))o+=uN(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=hN(t[n]),o+=1)}return o};function hN(e){if(zD(e)){let t=[];return e.forEach(((e,i)=>{t[i]=hN(e)})),t}if(YD(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=hN(e[i])})),t}return e}var pN=e=>{let t=[];if(zD(e))t=[...e];else if(JD(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},mN=e=>JD(e)?document.getElementById(e):e,_N=()=>(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 fN(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(zD(e))return"[".concat(e.map((e=>fN(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!FD(e)||!zD(i)&&!zD(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]=FD(e[s])||zD(e[s])?JSON.parse(fN(e[s],{keysToExclude:r,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(Xk){return"{}"}}function gN(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)})),fN(e,{keysToInclude:i})}function EN(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var TN=()=>{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},vN=e=>Ib(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(JD(e))r=new Image,r.crossOrigin="anonymous",r.src=e;else if(r=e,r.complete)return void t(r);r.onload=()=>t(r),r.onerror=()=>{i(new Vb({code:Lb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}}))})),yN=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},SN=e=>(Object.keys(e).forEach((t=>{KD(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(FD(e[t])||zD(e[t]))&&SN(e[t])})),e);function IN(e,t){return new Promise((i=>{let r=setTimeout(i,e);t&&t(r)}))}function RN(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 AN(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function CN(e){var t;try{let{width:i,height:r,frameRate:n,sampleRate:o,sampleSize:s,channelCount:a}=null==(t=e.getSettings)?void 0:t.call(e),c=e.kind===Sk.AUDIO?"".concat(o,"x").concat(s,"@").concat(a):"".concat(i,"x").concat(r,"@").concat(n),l=e.stats?" stats: ".concat(JSON.stringify(e.stats).replaceAll('"',"")):"";return"".concat(e.id," ").concat(e.readyState," muted:").concat(e.muted," ").concat(e.kind," ").concat(e.label," ").concat(c).concat(l)}catch(qb){return""}}function bN(e,t){return e.width*e.height==t.width*t.height?1:TN()&&e.width>e.height&&t.height>t.width?Math.max(t.width/e.height,t.height/e.width,1):Math.max(e.width/t.width,e.height/t.height,1)}function kN(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.text())).then((t=>{try{e({data:JSON.parse(t)})}catch(WO){e({data:t})}}),s);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(4===a.readyState)if(a.status>=200&&a.status<300)try{let t=JSON.parse(a.response);e({data:t})}catch(t){e({data:a.response})}else s({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=n||5e3,a.open(r,t,!0),a.send(i)}))}function DN(e){return Ib(this,null,(function*(){let t=rN(),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 xO.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(rN()-t,"ms")),r}catch(Xk){return i}}))}var NN=Object.prototype.hasOwnProperty,wN=e=>"function"==typeof e,ON=e=>void 0===e,PN=e=>"boolean"==typeof e,MN=e=>e.isRemote,LN=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 xN=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:n,onRetryFailed:o,onRetrySuccess:s,context:a}=e;return function(){for(var e=arguments.length,c=new Array(e),l=0;l<e;l++)c[l]=arguments[l];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,_=(e,i)=>Ib(this,null,(function*(){let l=a||this;try{let i=yield t.apply(l,c);h>0&&s&&s.call(this,h),h=0,e(i)}catch(f){let t=()=>{clearTimeout(p),h=0,m=2,i(f)},s=()=>{2!==m&&h<(wN(d)?d():d)?(h++,m=1,wN(n)&&n.call(this,h,t),p=window.setTimeout((()=>{p=-1,_(e,i)}),wN(u)?u(h):u)):(t(),wN(o)&&o.call(this,f))};wN(r)?r.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(_)}},VN=class{constructor(e){yb(this,"userId"),yb(this,"remoteUserId"),yb(this,"id"),yb(this,"sdkAppId"),yb(this,"type"),yb(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!PN(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}createChild(e){return Object.setPrototypeOf(e,this)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId;t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(this.id).concat(i?"|".concat(i):"","]")),xO.log(e,t,ON(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(LN(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(let t in e)if(NN.call(e,t))return!1;return!0}return!1}(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)}},UN={};Eb(UN,{ANDROID_VERSION:()=>QN,CHROME_MAJOR_VERSION:()=>tO,CHROME_VERSION:()=>iO,EDGE_VERSION:()=>nw,EDG_MAJOR_VERSION:()=>aw,EDG_VERSION:()=>sw,FIREFOX_MAJOR_VERSION:()=>iw,FIREFOX_VERSION:()=>tw,HUAWEI_VERSION:()=>Ww,IE_VERSION:()=>Ew,IOS_MAIN_VERSION:()=>lO,IOS_VERSION:()=>aO,IPADQQB_VERSION:()=>Dw,IS_ANDROID:()=>XN,IS_ANDROID_WEBVIEW:()=>sO,IS_ANY_SAFARI:()=>nO,IS_CHROME:()=>$w,IS_CHROME_OS:()=>Pw,IS_CHROMIUM_BASE:()=>Zw,IS_DESKTOP_IOS_CHROME:()=>mO,IS_EDG:()=>ow,IS_EDGE:()=>rw,IS_ELECTRON:()=>xw,IS_FIREFOX:()=>ew,IS_HEADLESS_CHROME:()=>eO,IS_HONOR:()=>Hw,IS_HUAWEI:()=>Bw,IS_HUAWEIBROWSER:()=>Fw,IS_IE:()=>gw,IS_IE8:()=>fw,IS_IOS:()=>zN,IS_IOS_13_OR_14:()=>hO,IS_IOS_15_1:()=>uO,IS_IOS_CHROME:()=>pO,IS_IPAD:()=>JN,IS_IPADQQB:()=>kw,IS_IPAD_PRO:()=>KN,IS_IPHONE:()=>qN,IS_IPOD:()=>YN,IS_LINUX:()=>Ow,IS_LOCAL:()=>_O,IS_MAC:()=>ww,IS_MACQQB:()=>Cw,IS_MIBROWSER:()=>Vw,IS_MQQB:()=>Sw,IS_NATIVE_ANDROID:()=>$N,IS_OLD_ANDROID:()=>ZN,IS_OPENHARMONY:()=>zw,IS_OPPOBROWSER:()=>Jw,IS_SAFARI:()=>rO,IS_SAFARI_15_1:()=>dO,IS_SAMSUNGBROWSER:()=>Gw,IS_SOGOU:()=>dw,IS_SOGOUM:()=>cw,IS_TBS:()=>hw,IS_UCBROWSER:()=>Lw,IS_VIVOBROWSER:()=>qw,IS_WECHAT:()=>Tw,IS_WIN:()=>Nw,IS_WQQB:()=>Rw,IS_WX:()=>Mw,IS_X5MQQB:()=>yw,IS_XWEB:()=>mw,MACQQB_VERSION:()=>bw,MI_VERSION:()=>Uw,MQQB_VERSION:()=>Iw,OPENHARMONY_VERSION:()=>Xw,OPPO_VERSION:()=>Kw,SAFARI_VERSION:()=>oO,SAMSUNG_VERSION:()=>jw,SOGOUM_VERSION:()=>lw,SOGOU_VERSION:()=>uw,TBS_VERSION:()=>pw,UA_DATA_STRING:()=>yO,USER_AGENT:()=>FN,VIVO_VERSION:()=>Yw,WECHAT_VERSION:()=>vw,WQQB_VERSION:()=>Aw,XWEB_VERSION:()=>_w,browserInfo:()=>gO,getBrowserInfo:()=>EO,getChromeMajorVersion:()=>Qw,getDeviceModel:()=>RO,getGPUInfo:()=>IO,getOSName:()=>CO,getOSNumber:()=>bO,getOSString:()=>kO,getOSType:()=>NO,getTerminalType:()=>DO,getUserAgentData:()=>SO,isLocalStorageEnabled:()=>fO,isMobile:()=>vO,isVersionSmallerThan:()=>cO});var FN="undefined"==typeof navigator?"":navigator.userAgent,BN=e=>new RegExp(e,"i").test(FN),HN=e=>{if(BN(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=FN.match(t);if(i&&i[1])return i[1]}return""},WN=e=>{if(BN(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=FN.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},GN=/AppleWebKit\/([\d.]+)/i.exec(FN),jN=GN?parseFloat(GN[1]):NaN,JN=BN("iPad"),KN="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&BN("Macintosh"),qN=BN("iPhone")&&!JN,YN=BN("iPod"),zN=qN||JN||YN||KN,XN=BN("Android"),QN=function(){if(XN){let e=FN.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}(),ZN=XN&&BN("webkit")&&QN<2.3,$N=XN&&QN<5&&jN<537,ew=BN("Firefox"),tw=HN("Firefox"),iw=WN("Firefox"),rw=BN("Edge"),nw=HN("Edge"),ow=BN("Edg"),sw=HN("Edg"),aw=WN("Edg"),cw=BN("SogouMobileBrowser"),lw=HN("SogouMobileBrowser"),dw=BN("MetaSr\\s"),uw=HN("MetaSr\\s"),hw=BN("TBS"),pw=HN("TBS"),mw=BN("XWEB"),_w=HN("XWEB"),fw=BN("MSIE\\s8\\.0"),gw=BN("MSIE\\/\\d+"),Ew=function(){if(gw){let e=/MSIE\s(\d+)\.\d/.exec(FN),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(FN)&&/rv:11.0/.test(FN)&&(t=11),t}return NaN}(),Tw=BN("(micromessenger|webbrowser)"),vw=HN("MicroMessenger"),yw=!hw&&BN("MQQBrowser")&&BN("COVC"),Sw=!hw&&BN("MQQBrowser")&&!BN("COVC"),Iw=Sw||yw?HN("MQQBrowser"):"",Rw=!hw&&BN(" QQBrowser"),Aw=HN(" QQBrowser"),Cw=!hw&&BN("QQBrowserLite"),bw=HN("QQBrowserLite"),kw=!hw&&BN("MQBHD"),Dw=HN("MQBHD"),Nw=BN("Windows"),ww=!zN&&BN("MAC OS X"),Ow=!XN&&BN("Linux"),Pw=BN("CrOS"),Mw=BN("MicroMessenger"),Lw=BN("UCBrowser"),xw=BN("Electron"),Vw=BN("MiuiBrowser"),Uw=HN("MiuiBrowser"),Fw=BN("HuaweiBrowser"),Bw=BN("Huawei")||BN("HUAWEI"),Hw=BN("Honor")||BN("HONOR"),Ww=HN("HuaweiBrowser"),Gw=BN("SamsungBrowser"),jw=HN("SamsungBrowser"),Jw=BN("HeyTapBrowser"),Kw=HN("HeyTapBrowser"),qw=BN("VivoBrowser"),Yw=HN("VivoBrowser"),zw=BN("OpenHarmony"),Xw=HN("OpenHarmony"),Qw=()=>WN("Chrome"),Zw=BN("Chrome"),$w=!rw&&!dw&&!cw&&!hw&&!mw&&!ow&&!Rw&&!Vw&&!Fw&&!Gw&&!Jw&&!qw&&Zw,eO=BN("HeadlessChrome"),tO=Qw(),iO=HN("Chrome"),rO=!Zw&&!Sw&&!yw&&!Cw&&!kw&&BN("Safari"),nO=rO||zN,oO=HN("Version"),sO=/Android.*(wv|.0.0.0)/.test(FN),aO=(()=>{if(KN)return oO;if(zN){let e=FN.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})();function cO(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}var lO=Number(aO.split(".")[0]),dO="15.1"===oO,uO="15.1"===aO,hO=(()=>{let e=Number(aO.split(".")[0]);return 14===e||13===e})(),pO=BN("CriOS"),mO=pO&&"11.1.1"===oO,_O="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),fO=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(jO){e=!1}return e}})(),gO=EO();function EO(){let e=new Map([[ew,["Firefox",tw]],[ow,["Edg",sw]],[$w,["Chrome",iO]],[rO,["Safari",oO]],[hw,["TBS",pw]],[mw,["XWEB",_w]],[Tw&&qN,["WeChat",vw]],[Rw,["QQ(Win)",Aw]],[Sw,["QQ(Mobile)",Iw]],[yw,["QQ(Mobile X5)",Iw]],[Cw,["QQ(Mac)",bw]],[kw,["QQ(iPad)",Dw]],[Vw,["MI",Uw]],[Fw,["HW",Ww]],[Gw,["Samsung",jw]],[Jw,["OPPO",Kw]],[qw,["VIVO",Yw]],[rw,["EDGE",nw]],[cw,["SogouMobile",lw]],[dw,["Sogou",uw]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var TO=null;function vO(){return TO&&"boolean"==typeof TO.mobile?TO.mobile:XN||zN||qN||JN||zw}var yO="";function SO(){return Ib(this,null,(function*(){if(TO)return TO;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(TO=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!yO&&(yO="UAData: ".concat(TO.platform,"/").concat(TO.platformVersion),TO.architecture&&TO.bitness&&(yO+=" ".concat(TO.architecture,"/").concat(TO.bitness)),TO.mobile&&(yO+=" mobile"),TO.model&&(yO+=" model: ".concat(TO.model.replace(/\s+/g,"/"))),TO.fullVersionList&&(yO+=" ".concat(TO.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),TO}catch(nj){return null}}))}function IO(){try{let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"";let i=t.getExtension("WEBGL_debug_renderer_info");if(i){let e=t.getParameter(i.UNMASKED_VENDOR_WEBGL),r=t.getParameter(i.UNMASKED_RENDERER_WEBGL);return"".concat(e," ").concat(r)}return""}catch(nj){return""}}function RO(){return(null==TO?void 0:TO.model)||""}var AO=new Map([[XN,"Android"],[zN,"iOS"],[Nw,"Windows"],[ww,"MacOS"],[Ow,"Linux"],[Pw,"ChromeOS"]]),CO=function(){return AO.get(!0)?AO.get(!0):TO?TO.platform:"unknown"};function bO(){return Nw?1:XN?2:ww?3:zN?4:Ow?5:Pw?6:0}var kO=()=>{let e=CO();return e+="/".concat(gO.name,"/").concat(rO?gO.version:gO.version.split(".")[0]),null!=TO&&TO.platformVersion&&(e+="/".concat(TO.platformVersion)),null!=TO&&TO.architecture&&(e+="/".concat(TO.architecture)),e};function DO(){return XN?4:qN?2:JN?3:ww?12:Nw?5:Ow?13:zw?22:1}function NO(){return XN?"Android":qN?"iPhone":JN?"iPad":ww?"Mac":Nw?"Windows":Ow?"Linux":"unknown"}var wO,OO=new(Tb(Rb(),1).default),PO=((wO=PO||{}).ROOM_DESTROY="1",wO.JOIN_START="21",wO.JOIN_SCHEDULE_SUCCESS="22",wO.JOIN_SIGNAL_CONNECTION_START="23",wO.JOIN_SIGNAL_CONNECTION_END="24",wO.JOIN_SEND_CMD="25",wO.JOIN_RECEIVED_CMD_RES="26",wO.JOIN_SUCCESS="27",wO.JOIN_FAILED="28",wO.LEAVE_START="51",wO.LEAVE_SEND_CMD="52",wO.LEAVE_SUCCESS="53",wO.PUBLISH_START="61",wO.SEND_FIRST_VIDEO_FRAME="62",wO.PUBLISH_FAILED="63",wO.SUBSCRIBE_START="81",wO.SUBSCRIBE_SUCCESS="82",wO.SUBSCRIBE_FAILED="84",wO.UNSUBSCRIBE_SUCCESS="83",wO.LOCAL_TRACK_CAPTURE_START="101",wO.LOCAL_TRACK_CAPTURE_SUCCESS="102",wO.LOCAL_TRACK_CAPTURE_FAILED="103",wO.LOCAL_TRACK_PUBLISHED="104",wO.LOCAL_TRACK_UNPUBLISHED="105",wO.LOCAL_TRACK_REPLACED="106",wO.SWITCH_DEVICE_SUCCESS="107",wO.TRACK_MUTED="108",wO.TRACK_UNMUTED="109",wO.REMOTE_TRACK_SUBSCRIBED="110",wO.REMOTE_TRACK_UNSUBSCRIBED="111",wO.LOCAL_TRACK_RECAPTURE="112",wO.LOCAL_AUDIO_STARTED="113",wO.LOCAL_AUDIO_STOPPED="114",wO.REMOTE_AUDIO_STARTED="115",wO.REMOTE_AUDIO_STOPPED="116",wO.PLAY_TRACK_START="151",wO.PLAYER_STATE_CHANGED="152",wO.VIDEO_LOADED_DATA="153",wO.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",wO.SIGNAL_CONNECTION_STATE_CHANGED="201",wO.PEER_CONNECTION_STATE_CHANGED="202",wO.SINGLE_CONNECTION_STAT="203",wO.SPC_RECONNECTED="204",wO.HEARTBEAT_REPORT="251",wO.RECEIVED_PUBLISHED_USER_LIST="252",wO.REMOTE_PUBLISH_STATE_CHANGED="253",wO.AUDIO_LEVEL_INTERVAL="260",wO.NETWORK_QUALITY="261",wO.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",wO.QUALITY_LIMITATION_CHANGED="263",wO.LOG="264",wO),MO=PO,LO=class e{constructor(){yb(this,"_isEnableUploadLog",!0),yb(this,"_localJoinedUser",new Map),yb(this,"_queue",[]),yb(this,"_timeoutId",-1),yb(this,"_logLevel",1),yb(this,"_logLevelToUpload",2),!zb&&!Xb&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){OO.on(MO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.logLevelToUpload&&hk[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),OO.on(MO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),OO.once(MO.JOIN_FAILED,(()=>{this.startUpload()})),OO.on(MO.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(JD(i.userId)&&KD(i.sdkAppId)){let{userId:t,sdkAppId:r}=i;e.map.has(t)?e.map.get(t).logs.push(i):e.map.set(t,{userId:t,sdkAppId:r,logs:[i]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e}upload(){return Ib(this,null,(function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;e<t.length;e++){let{userId:i,sdkAppId:r,logs:n}=t[e];yield this.uploadLogWithRetry(JSON.stringify({timestamp:Bb(),sdkAppId:String(r),userId:i,version:Jb,log:n.map((e=>e.log)).join("\n")}),r),n.forEach((e=>e.uploaded=!0))}}catch(JO){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return xN({retryFunction:()=>kN({url:CD(t,dk.LOG),body:e,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;return t.setTime(Fb()),"[".concat(Hb(t),"] <").concat(hk[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){jD(hk[e])||(this._logLevel!==e&&this.info("setLogLevel",e),this._logLevel=e)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(e){if(JD(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(qb){return""}}log(t,i){let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0;var s;i.unshift(this.getPrefix(t));let a={log:i.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:t,userId:n,sdkAppId:o,forAllJoinedClients:r};if(OO.emit(MO.LOG,{log:a}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(a),t<this._logLevel)return;let c=(null==(s=hk[t])?void 0:s.toLowerCase())||"info";e.PRINT_LOG_TAG?console[c]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...i):console[c](...i)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}createLogger(e){return new VN(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;hk[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};yb(LO,"PRINT_LOG_TAG",!(zN||XN||eO));var xO=new LO,VO=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)}))},UO=new class{constructor(){yb(this,"_prefix","TRTC"),yb(this,"_queue",new Map)}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){fO()&&(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(JO){return!1}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(fO())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(jO){xO.warn(jO)}}getItem(e){if(!fO())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(qb){xO.warn(qb)}}setItem(e,t){if(fO())try{let i={expiresIn:Date.now()+fk,value:t};this._queue.set(this.getRealKey(e),i)}catch(Xk){xO.warn(Xk)}}deleteItem(e){if(!fO())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(qb){return xO.warn(qb),!1}}clear(){if(fO())try{localStorage.clear()}catch(jO){xO.warn(jO)}}},FO={};Eb(FO,{HTTPS_API:()=>EM,IS_GET_CAPABILITIES_SUPPORTED:()=>VM,IS_GET_SETTINGS_SUPPORTED:()=>xM,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>LM,IS_INSERTABLE_STREAM_SUPPORTED:()=>UM,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>XM,IS_RTC_RTP_SENDER_SUPPORTED:()=>OM,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>FM,IS_SEI_SUPPORTED:()=>BM,IS_SPC_SUPPORTED:()=>NM,basis:()=>KM,capabilityCheck:()=>YM,checkSystemRequirementsInternal:()=>mM,decodeSupportStatus:()=>pM,encodeSupportStatus:()=>hM,getBrowserInfo:()=>oM,getDisplayResolution:()=>vM,isAddTransceiverSupported:()=>DM,isBrowserSupported:()=>sM,isGetReceiversSupported:()=>CM,isGetSendersSupported:()=>bM,isGetTransceiversSupported:()=>kM,isGetUserMediaSupported:()=>yM,isMediaDevicesSupported:()=>cM,isMediaSessionSupported:()=>GM,isMediaStreamTrackProcessorSupported:()=>uM,isReplaceTrackSupported:()=>PM,isRequestVideoFrameCallbackSupported:()=>zM,isSIMDSupported:()=>JM,isScreenCaptureApiAvailable:()=>fM,isSelectedCandidatePair:()=>TM,isSetParametersSupported:()=>MM,isSmallStreamAPISupported:()=>IM,isSmallStreamSupported:()=>RM,isStopTransceiverSupported:()=>wM,isTRTCSupported:()=>_M,isUnifiedPlanDefault:()=>AM,isUsedInHttpProtocol:()=>dM,isWebAudioSupported:()=>SM,isWebCodecSupported:()=>WM,isWebCodecsSupported:()=>aM,isWebRTCSupported:()=>HM,isWebTransportSupported:()=>jM});var BO={};Eb(BO,{AUDIO_LEVEL_SCALE:()=>NP,AudioCodecPipelineType:()=>LP,AudioDecoderDowngradeState:()=>uP,AudioPlayerMode:()=>bP,AudioType:()=>gP,BASIC_TYPE:()=>OP,BannedReason:()=>kP,CONNECTION_CLOSED_REASON:()=>ZO,ClientEvent:()=>$O,CodecType:()=>xP,ConnectionEvent:()=>QO,ConnectionState:()=>dP,DECODE_FAILED_ERROR_CODE:()=>VP,FacingMode:()=>AP,LeaveReason:()=>DP,LocalTrackEvent:()=>tP,MULTI_VIDEO_DATA_TYPE:()=>yP,MediaType:()=>_P,MediaTypeLabel:()=>fP,MonitorEventId:()=>SP,MutedFlag:()=>sP,NetworkQualityValue:()=>IP,PlayerState:()=>iP,ReceiveMode:()=>RP,RemoteStreamType:()=>vP,RemoteTrackEvent:()=>oP,RoomEvent:()=>rP,SMALL_MODE:()=>BP,SceneNumber:()=>aP,StreamEvent:()=>eP,StreamType:()=>TP,SubscribeMediaType:()=>wP,TIMER_TYPE:()=>FP,TRACK_ACTION:()=>mP,TRACK_KIND:()=>pP,TrackEvent:()=>nP,UserRole:()=>lP,UserRoleNumber:()=>cP,VideoCodec:()=>PP,VideoCodecPipelineType:()=>MP,VideoContentHint:()=>UP,VideoDecoderDowngradeState:()=>hP,VideoPlayerMode:()=>CP,VideoType:()=>EP});var HO,WO,GO,jO,JO,KO,qO,YO,zO,XO,QO=((XO=QO||{}).TRACK_ADDED="track-added",XO.TRACK_UPDATED="track-updated",XO.TRACK_SUBSCRIBED="track-subscribed",XO.STREAM_ADDED="stream-added",XO.STREAM_REMOVED="stream-removed",XO.STREAM_UPDATED="stream-updated",XO.STREAM_PUBLISHED="stream-published",XO.STREAM_SUBSCRIBED="stream-subscribed",XO.STREAM_UNSUBSCRIBED="stream-unsubscribed",XO.STATE_CHANGED="state-changed",XO.ERROR="error",XO.CONNECTION_STATE_CHANGED="connection-state-changed",XO.FIREWALL_RESTRICTION="firewall-restriction",XO.SEI_MESSAGE="sei-message",XO.CLOSED="closed",XO),ZO=(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))(ZO||{}),$O=((zO=$O||{}).STREAM_ADDED="stream-added",zO.STREAM_REMOVED="stream-removed",zO.STREAM_UPDATED="stream-updated",zO.STREAM_SUBSCRIBED="stream-subscribed",zO.CONNECTION_STATE_CHANGED="connection-state-changed",zO.PEER_JOIN="peer-join",zO.PEER_LEAVE="peer-leave",zO.MUTE_AUDIO="mute-audio",zO.MUTE_VIDEO="mute-video",zO.UNMUTE_AUDIO="unmute-audio",zO.UNMUTE_VIDEO="unmute-video",zO.CLIENT_BANNED="client-banned",zO.NETWORK_QUALITY="network-quality",zO.AUDIO_VOLUME="audio-volume",zO.SEI_MESSAGE="sei-message",zO.ERROR="error",zO),eP=((YO=eP||{}).PLAYER_STATE_CHANGED="player-state-changed",YO.SCREEN_SHARING_STOPPED="screen-sharing-stopped",YO.CONNECTION_STATE_CHANGED="connection-state-changed",YO.DEVICE_AUTO_RECOVERED="device-auto-recovered",YO.ERROR="error",YO),tP=(e=>(e.DEVICE_AUTO_RECOVERED="1",e.DEVICE_RECOVER_FAILED="5",e.DEVICE_CHANGED="2",e.ERROR="3",e.PUBLISH_STATE_CHANGED="4",e.ENCODE_FAILED="6",e))(tP||{}),iP=(e=>(e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e))(iP||{}),rP=((qO=rP||{}).PEER_JOIN="peer-join",qO.PEER_LEAVE="peer-leave",qO.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",qO.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",qO.BANNED="banned",qO.NETWORK_QUALITY="network-quality",qO.AUDIO_VOLUME="audio-volume",qO.SEI_MESSAGE="sei-message",qO.ERROR="error",qO.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",qO.REMOTE_PUBLISHED="remote-published",qO.REMOTE_UNPUBLISHED="remote-unpublished",qO.FIREWALL_RESTRICTION="firewall-restriction",qO.HEARTBEAT_REPORT="heartbeat-report",qO.CUSTOM_MESSAGE="custom-message",qO.LAYER_DATA="layerData",qO.FIRST_VIDEO_FRAME="first-video-frame",qO.DUMP="dump",qO.AUDIO_FRAME="audio-frame",qO.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",qO),nP=((KO=nP||{}).PLAYER_STATE_CHANGED="player-state-changed",KO.MUTE="mute",KO.UNMUTE="unmute",KO.ERROR="error",KO.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",KO.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",KO.FIRST_VIDEO_FRAME="first-video-frame",KO),oP=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(oP||{}),sP=(e=>(e[e.VIDEO=1]="VIDEO",e[e.SMALL=2]="SMALL",e[e.AUX=4]="AUX",e[e.AUDIO=8]="AUDIO",e[e.VIDEO_MUTE=16]="VIDEO_MUTE",e[e.AUX_MUTE=32]="AUX_MUTE",e[e.AUDIO_MUTE=64]="AUDIO_MUTE",e))(sP||{}),aP=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(aP||{}),cP=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(cP||{}),lP=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(lP||{}),dP=(e=>(e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e))(dP||{}),uP=((JO=uP||{}).INITIALIZED="INITIALIZED",JO.STARTING="STARTING",JO.STARTED="STARTED",JO.FAILED="FAILED",JO),hP=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(hP||{}),pP=(e=>(e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e))(pP||{}),mP=(e=>(e.ADD="add",e.REMOVE="remove",e))(mP||{}),_P=(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))(_P||{}),fP={1:"audio",2:"auxVideo",4:"video"},gP=((jO=gP||{})[jO.opus=111]="opus",jO),EP=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(EP||{}),TP=(e=>(e.Big="big",e.Small="small",e))(TP||{}),vP=(e=>(e.Main="main",e.Aux="auxiliary",e))(vP||{}),yP=(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))(yP||{}),SP=((GO=SP||{})[GO.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",GO[GO.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",GO[GO.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",GO[GO.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",GO[GO.MUTE_AUDIO=32772]="MUTE_AUDIO",GO[GO.MUTE_VIDEO=32773]="MUTE_VIDEO",GO[GO.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",GO[GO.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",GO[GO.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",GO[GO.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",GO[GO.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",GO[GO.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",GO[GO.SWITCH_CAMERA=32780]="SWITCH_CAMERA",GO[GO.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",GO[GO.REPLACE_VIDEO=32782]="REPLACE_VIDEO",GO[GO.REPLACE_AUDIO=32783]="REPLACE_AUDIO",GO[GO.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",GO[GO.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",GO[GO.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",GO[GO.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",GO[GO.JOIN=32788]="JOIN",GO[GO.LEAVE=32789]="LEAVE",GO[GO.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",GO[GO.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",GO[GO.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",GO[GO.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",GO[GO.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",GO[GO.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",GO[GO.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",GO[GO.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",GO[GO.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",GO[GO.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",GO[GO.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",GO[GO.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",GO[GO.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",GO[GO.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",GO[GO.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",GO[GO.PUBLISH_AUX=32805]="PUBLISH_AUX",GO[GO.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",GO[GO.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",GO[GO.VIDEO_ENCODER=4004]="VIDEO_ENCODER",GO[GO.VIDEO_DECODER=4005]="VIDEO_DECODER",GO),IP=(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))(IP||{}),RP=(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))(RP||{}),AP=(e=>(e.user="user",e.environment="environment",e))(AP||{}),CP=(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))(CP||{}),bP=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(bP||{}),kP=(e=>(e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e))(kP||{}),DP=((WO=DP||{})[WO.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",WO[WO.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",WO[WO.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",WO[WO.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",WO[WO.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",WO[WO.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",WO[WO.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",WO[WO.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",WO[WO.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",WO),NP=1e8,wP=class{constructor(){yb(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)}},OP=(e=>(e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e))(OP||{}),PP=(e=>(e.H264="h264",e.H265="h265",e.VP8="vp8",e))(PP||{}),MP=(e=>(e[e.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",e[e.DUMP=1]="DUMP",e[e.SEI=2]="SEI",e[e.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",e))(MP||{}),LP=(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))(LP||{}),xP=(e=>(e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e))(xP||{}),VP=((HO=VP||{})[HO.SUCCESS=0]="SUCCESS",HO[HO.FAILED=1]="FAILED",HO[HO.WEBCODEC_INIT=2]="WEBCODEC_INIT",HO[HO.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",HO[HO.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",HO[HO.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",HO[HO.WASM_INIT=6]="WASM_INIT",HO[HO.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",HO[HO.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",HO[HO.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",HO[HO.TEST=10]="TEST",HO[HO.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",HO),UP=(e=>(e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e))(UP||{}),FP=(e=>(e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e))(FP||{}),BP=(e=>(e.CANVAS="canvas",e.API="api",e))(BP||{}),HP={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: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(WD(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(WD(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,"()")},GP=(e,t)=>t?"".concat(nk,"/").concat(e,"/").concat(t):"".concat(nk,"/").concat(e,"/index.html"),jP=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let e=null==localStorage?void 0:localStorage.getItem(lk);if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let i=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:r}}return{}};function JP(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",s="",a="";GD(WP[t])?o=WP[t](i):JD(WP[t])&&(o=WP[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=jP();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(GD(l[t])?a=l[t](i):JD(l[t])&&(a=l[t]));let d=o;return UD()&&(c&&c[t]&&(GD(c[t])?s=c[t](i):JD(c[t])&&(s=c[t])),s&&(d=n?"".concat(s,"\n请查看文档: ").concat(GP("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(GP("en",a),"\n")),d}var KP,qP,YP=Tb(kb(),1),zP=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];yb(this,"countMap",new Map),yb(this,"distributionMap",new Map),yb(this,"version"),yb(this,"log",xO.createLogger({id:"kv"})),e&&(OO.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===Sk.AUDIO?501700:511700,cost:i})})),OO.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===Sk.AUDIO?501700:511700,error:i})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:yN(this.version||Jb),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,uint32_count:i}})),stats_distribution:[...this.distributionMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,distribution_items:[...i.entries()].map((e=>{let[t,i]=e;return{uint32_item_key:t,uint32_item_value:i}}))}}))};return this.countMap.clear(),this.distributionMap.clear(),e}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){let t=+String(e).slice(-3);return t>=700&&t<799}isErrorCodeKey(e){let t=+String(e).slice(-3);return t>=600&&t<699}isCountKey(e){let t=+String(e).slice(-3);return t>=0&&t<599}isNumberKey(e){let t=+String(e).slice(-3);return t>=800&&t<899}addCount(e){let{key:t,useUV:i=!1}=e;this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}addEnum(e){let{key:t,value:i,useUV:r=!0}=e;var n;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=(null==(n=this.distributionMap)?void 0:n.get(t))||new Map;o.set(i,(o.get(i)||0)+1),this.distributionMap.set(t,o)}addNumber(e){let{key:t,value:i,split:r=100,useUV:n=!1,max:o=5e3}=e;var s;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(n&&this.countMap.has(t))return;i>o&&(i=o),this.countMap.set(t,(this.countMap.get(t)||0)+1);let a=(null==(s=this.distributionMap)?void 0:s.get(t))||new Map,c=0;if(KD(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=Lb.UNKNOWN;i&&(KD(i)?r=i:(!jD(i.extraCode)||!jD(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})}},XP=((qP=XP||{})[qP.enterRoom=500700]="enterRoom",qP[qP.exitRoom=500701]="exitRoom",qP[qP.switchRole=500702]="switchRole",qP[qP.destroy=500703]="destroy",qP[qP.startLocalAudio=500704]="startLocalAudio",qP[qP.updateLocalAudio=500705]="updateLocalAudio",qP[qP.stopLocalAudio=500706]="stopLocalAudio",qP[qP.startLocalVideo=500707]="startLocalVideo",qP[qP.updateLocalVideo=500708]="updateLocalVideo",qP[qP.stopLocalVideo=500709]="stopLocalVideo",qP[qP.startScreenShare=500710]="startScreenShare",qP[qP.updateScreenShare=500711]="updateScreenShare",qP[qP.stopScreenShare=500712]="stopScreenShare",qP[qP.startRemoteVideo=500713]="startRemoteVideo",qP[qP.updateRemoteVideo=500714]="updateRemoteVideo",qP[qP.stopRemoteVideo=500715]="stopRemoteVideo",qP[qP.muteRemoteAudio=500716]="muteRemoteAudio",qP[qP.setRemoteAudioVolume=500717]="setRemoteAudioVolume",qP[qP.use=500718]="use",qP[qP.sendSEIMessage=5e5]="sendSEIMessage",qP[qP.sendCustomMessage=500001]="sendCustomMessage",qP),QP=((KP=QP||{})[KP.AudioMixer=550700]="AudioMixer",KP[KP.AIDenoiser=551700]="AIDenoiser",KP[KP.VirtualBackground=570700]="VirtualBackground",KP[KP.Beauty=571700]="Beauty",KP[KP.Watermark=572700]="Watermark",KP[KP.BasicBeauty=574700]="BasicBeauty",KP[KP.CDNStreaming=590700]="CDNStreaming",KP[KP.DeviceDetector=591700]="DeviceDetector",KP[KP.Debug=592700]="Debug",KP[KP.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",KP),ZP=(e=>(e[e.AudioMixer=550701]="AudioMixer",e[e.AIDenoiser=551701]="AIDenoiser",e[e.VirtualBackground=570701]="VirtualBackground",e[e.Beauty=571701]="Beauty",e[e.Watermark=572701]="Watermark",e[e.BasicBeauty=574701]="BasicBeauty",e[e.CDNStreaming=590701]="CDNStreaming",e[e.DeviceDetector=591701]="DeviceDetector",e[e.Debug=592701]="Debug",e[e.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",e))(ZP||{}),$P=(e=>(e[e.AudioMixer=550702]="AudioMixer",e[e.AIDenoiser=551702]="AIDenoiser",e[e.VirtualBackground=570702]="VirtualBackground",e[e.Beauty=571702]="Beauty",e[e.Watermark=572702]="Watermark",e[e.BasicBeauty=574702]="BasicBeauty",e[e.CDNStreaming=590702]="CDNStreaming",e[e.DeviceDetector=591702]="DeviceDetector",e[e.Debug=592702]="Debug",e[e.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",e))($P||{}),eM=new zP(!0),tM=new zP(!1),iM=eM,rM={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},nM=new Map([[ew,["Firefox",tw]],[ow,["Edg",sw]],[$w,["Chrome",iO]],[rO,["Safari",oO]],[hw,["TBS",pw]],[mw,["XWEB",_w]],[Tw&&qN,["WeChat",vw]],[Rw,["QQ(Win)",Aw]],[Sw,["QQ(Mobile)",Iw]],[yw,["QQ(Mobile X5)",Iw]],[Cw,["QQ(Mac)",bw]],[kw,["QQ(iPad)",Dw]],[Vw,["MI",Uw]],[Fw,["HW",Ww]],[Gw,["Samsung",jw]],[Jw,["OPPO",Kw]],[qw,["VIVO",Yw]],[rw,["EDGE",nw]],[cw,["SogouMobile",lw]],[dw,["Sogou",uw]]]);function oM(){let e=nM.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var sM=function(){return!(Lw||rw||ow&&aw<80||ew&&iw<56)},aM=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},cM=function(){if(!navigator.mediaDevices)return dM()||xO.error(WP.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},lM=!1;function dM(){return"http:"===location.protocol&&!_O&&(lM||xO.error(JP({key:HP.NOT_SUPPORTED_HTTP})),lM=!0,!0)}var uM=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},hM=function(){return Ib(this,null,(function*(){if(rM.detail.isH264EncodeSupported&&rM.detail.isVp8EncodeSupported)return{isH264EncodeSupported:rM.detail.isH264EncodeSupported,isVp8EncodeSupported:rM.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection,n=document.createElement(Sk.CANVAS);n.getContext("2d");let o=n.captureStream(0);return r.addTrack(o.getVideoTracks()[0],o),e=yield r.createOffer(),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),rM.detail.isH264EncodeSupported=t,rM.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:rM.detail.isH264EncodeSupported,isVp8EncodeSupported:rM.detail.isVp8EncodeSupported}}catch(Xk){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},pM=function(){return Ib(this,null,(function*(){if(rM.detail.isH264DecodeSupported&&rM.detail.isVp8DecodeSupported)return{isH264DecodeSupported:rM.detail.isH264DecodeSupported,isVp8DecodeSupported:rM.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection;return e=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch(Xk){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},mM=RN((()=>Ib(void 0,null,(function*(){if(rM.result&&rM.detail.isH264EncodeSupported&&rM.detail.isVp8EncodeSupported&&rM.detail.isH264DecodeSupported&&rM.detail.isVp8DecodeSupported)return rM;let e=Date.now(),t=sM(),i=HM(),r=aM(),n=cM(),{isH264EncodeSupported:o,isVp8EncodeSupported:s}=yield hM(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield pM();if(!o||!s){let e=yield hM();xO.warn("detect encode again h264:".concat(o," vp8:").concat(s," result: ").concat(JSON.stringify(e))),o=e.isH264EncodeSupported,s=e.isVp8EncodeSupported}if(o&&a&&XN&&Zw&&!mw&&!hw){let{encode:e,decode:t}=yield function(){return Ib(this,null,(function*(){return gM||(gM=new Promise((e=>Ib(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{let r=document.createElement("canvas"),n=r.getContext("2d");r.width=320,r.height=240;let o=setInterval((()=>{n.fillText("test",Math.floor(320*Math.random()),Math.floor(240*Math.random()))}),66),s=-1,a=-1;i=()=>{clearInterval(s),clearInterval(o),clearTimeout(a),l.close(),d.close(),c.getTracks().forEach((e=>e.stop()))},a=setTimeout((()=>{i(),e(t)}),2e3);let c=r.captureStream(),l=new RTCPeerConnection({}),d=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",(e=>d.addIceCandidate(e.candidate))),d.addEventListener("icecandidate",(e=>l.addIceCandidate(e.candidate))),l.addTrack(c.getVideoTracks()[0],c);let u=yield l.createOffer();yield l.setLocalDescription(u),yield d.setRemoteDescription(u);let h=yield d.createAnswer(),p=YP.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=YP.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval((()=>Ib(this,null,(function*(){t.encode&&t.decode&&(i(),e(t));let[r,n]=yield Promise.all([l.getSenders()[0].getStats(),d.getReceivers()[0].getStats()]);t.encode||r.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===Sk.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===Sk.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(r){i(),xO.warn("detectH264Supported failed",r),e({encode:!0,decode:!0})}})))).then((e=>(e.encode||(e.decode=!0),(!e.encode||!e.decode)&&xO.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(yO)),e))),gM)}))}();o=e,a=t}return rM.result=t&&i&&n&&(o||s)&&(a||c),rM.detail.isBrowserSupported=t,rM.detail.isWebRTCSupported=i,rM.detail.isWebCodecsSupported=r,rM.detail.isMediaDevicesSupported=n,rM.detail.isScreenShareSupported=fM(),rM.detail.isSmallStreamSupported=RM(),rM.detail.isH264EncodeSupported=o,rM.detail.isVp8EncodeSupported=s,rM.detail.isH264DecodeSupported=a,rM.detail.isVp8DecodeSupported=c,rM.result||xO.error("".concat(navigator.userAgent," ").concat(gN(rM.detail,!1))),UO.setItem(qM,{ua:navigator.userAgent,checkResult:rM}),iM.addNumber({key:523800,value:Date.now()-e}),rM})))),_M=function(){return rM.result},fM=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},gM=null;var EM=(e,t,i)=>{"http:"===location.protocol&&!_O&&(e[t]=()=>{throw new Vb({code:Lb.INVALID_OPERATION,message:WP.NOT_SUPPORTED_HTTP})})},TM=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(qD(e.selected)&&!e.selected)};function vM(){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 yM(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function SM(){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 IM(){return"captureStream"in HTMLCanvasElement.prototype}function RM(){return!(Tw||zN||tO&&tO<63)&&!(!sM()||!IM())}var AM=function(){if(jD(window.RTCRtpTransceiver)||!DM()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:iD}),e.addTransceiver(Sk.AUDIO),t=!0}catch(qb){}return null==e||e.close(),t};function CM(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function bM(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function kM(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function DM(){return!(11===lO&&!mO)&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var NM=!(!DM()||Zw&&tO<86);function wM(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var OM="RTCRtpSender"in window;function PM(){return OM&&"replaceTrack"in window.RTCRtpSender.prototype}function MM(){return OM&&"setParameters"in window.RTCRtpSender.prototype&&bM()}var LM="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,xM=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,VM=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,UM=OM&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Qw()>=86,FM="RTCRtpScriptTransform"in window,BM=OM&&(UM||FM),HM=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function WM(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return jD(window.AudioDecoder)||(e.AudioDecoder=!0),jD(window.AudioEncoder)||(e.AudioEncoder=!0),jD(window.VideoDecoder)||(e.VideoDecoder=!0),jD(window.VideoEncoder)||(e.VideoEncoder=!0),jD(window.ImageDecoder)||(e.ImageDecoder=!0),e}function GM(){return"mediaSession"in navigator&&!jD(navigator.mediaSession.setActionHandler)}function jM(){return!jD(window.WebTransport)}function JM(){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 KM(){let e={browser:"".concat(gO.name,"/").concat(gO.version),os:CO(),displayResolution:vM(),isScreenShareSupported:fM(),isWebRTCSupported:HM(),isGetUserMediaSupported:yM(),isWebAudioSupported:SM(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:WM(),isMediaSessionSupported:GM(),isWebTransportSupported:jM()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var qM="checkResult";function YM(){dM();let e=UO.getItem(qM);e&&e.ua===navigator.userAgent&&(rM=e.checkResult),mM()}function zM(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var XM="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype,QM=Tb(Rb(),1),ZM=Symbol("instance"),$M=Symbol("cacheResult"),eL=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,oL.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},tL=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var iL=new Map;function rL(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=iL.get(r)||[];iL.has(r)||iL.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=sL.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return i.sync?r[$M]:Promise.resolve(r[$M]);r.state instanceof eL&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof eL&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new tL(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 tL(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 eL(u,t,s);oL.call(r,h);let p=e=>{var n;return r[$M]=e,h.aborted||(oL.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[$M])),e},m=e=>(oL.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(zO){return m(new tL(r._state,"".concat(r.name," ").concat(s," from ").concat(e," to ").concat(t," failed: ").concat(zO),zO instanceof Error?zO:new Error(String(zO))))}}}}var nL="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 oL(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(sL.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var sL=class e extends QM.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[ZM];n?this.name=n.name+"-"+n.count++:r[ZM]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=iL.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);iL.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]:{};nL(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){oL.call(this,e)}};sL.STATECHANGED="stateChanged",sL.UPDATEAFSM="updateAFSM",sL.INIT="[*]",sL.ON="on",sL.OFF="off",sL.instances=new Map,sL.instances2=new WeakMap;var aL="undefined"!=typeof window,cL=aL&&window.requestIdleCallback||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},lL=aL&&window.cancelIdleCallback||function(e){clearTimeout(e)},dL=aL&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),uL=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=_b("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=fb(_b({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=rN(),n=()=>{if(i=rN()-r,i>=t.delay&&(r=rN()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!e.isBreakLoop(t))return t.ricID=cL(n,{timeout:t.delay})};return t.ricID=cL(n,{timeout:t.delay})}static raf(t){let i,r=rN(),n=()=>document.hidden&&t.backgroundTask?(i=rN()-r,r=rN(),t.callback(),t.loopCount+=1,e.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(n,t.delay-Math.floor(i%t.delay))):(i=rN()-r,i>=t.delay&&(r=rN()-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=rN()-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&&dL&&dL(r),n&&lL(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)}};yb(uL,"taskMap",new Map),yb(uL,"currentTaskID",1),yb(uL,"sharedWorker",null),yb(uL,"workerTasks",new Map);var hL=uL;Sk.SEI_MESSAGE;var pL={LOADED_DATA:Sk.LOADEDDATA,LOADED_META_DATA:Sk.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},mL={};Eb(mL,{create:()=>fL,remove:()=>gL});var _L=new WeakMap;function fL(e,t){_L.has(e)||_L.set(e,[]);let i=_L.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 gL(e){let t=_L.get(e);t&&(t.forEach((e=>e())),_L.delete(e))}var EL=new class{constructor(){yb(this,"_roomIdMap",new Map),yb(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:Jb,env:uk.QCLOUD,browserVersion:gO.name+gO.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){_O||!xO.isAbleToUpload||this._configs.env===uk.QCLOUD&&this.uploadEventToKibana(fb(_b({},e),{result:"success"}))}logFailedEvent(e){if(_O||!xO.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)||Lb.UNKNOWN};this._configs.env===uk.QCLOUD&&this.uploadEventToKibana(fb(_b({},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:Bb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:Jb,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+="\n".concat(r.stack))),this.sendRequest(CD(this._configs.sdkAppId,dk.LOG),n)}sendRequest(e,t){setTimeout((()=>kN({url:e,body:JSON.stringify(t),priority:"low"}).catch((()=>{}))),2e3)}},TL=new WeakMap;function vL(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,s){let a=xN({retryFunction:s.value,settings:t,onError(t){let{error:r,retry:n,reject:s,retryFuncArgs:a}=t;var c;i?i.call(this,r,(()=>{var t;null!=(t=TL.get(e))&&t.has(o)?n():s(r)}),s,a):null!=(c=TL.get(e))&&c.has(o)?n():s(r)},onRetrying(t,i){var n;wN(r)&&r.call(this,t,i),null!=(n=TL.get(e))&&n.has(o)&&(TL.get(e).get(o).stopRetry=i)},onRetryFailed:n});return s.value=function(){let t=TL.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}):TL.set(e,new Map([[o,{args:r}]])),a.apply(this,r).finally((()=>{var t;return null==(t=TL.get(e))?void 0:t.delete(o)}))},s}}function yL(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=TL.get(e))&&n.has(t)){let{stopRetry:n,args:s}=TL.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=TL.get(e))||o.delete(t))}return s.apply(this,c)},o}}var SL=class extends sL{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,yb(this,"id"),yb(this,"element",null),yb(this,"track"),yb(this,"url"),yb(this,"attr"),yb(this,"mode"),yb(this,"muted"),yb(this,"_log"),yb(this,"_pausedRetryCount"),yb(this,"_isElementPlayingFired",!1),yb(this,"_interval"),yb(this,"_delayDestroyTimeoutId",0),yb(this,"_playSuccessResolve"),yb(this,"_isReplayByRecreateMediaStreamCalled",!1),yb(this,"isInAutoPlayFailedState",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=mD,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){var e;return"PLAYING"===this._state&&!1===(null==(e=this.element)?void 0:e.paused)}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,null!==e&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return Ib(this,null,(function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise(((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)}))}catch(qb){let t=JP({key:HP.PLAY_FAILED,data:{media:this.kind,error:qb}});if(this.track&&!this.track.muted&&this._log.warn(qb),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new Vb({code:Lb.PLAY_NOT_ALLOWED,message:t})}}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!nO?this._delayDestroyTimeoutId||(this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout((()=>this.destroyElement()),3*e)):this.destroyElement(),this.handleStopped(Sk.ENDED),this._interval>0&&hL.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():uO?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 fL(this.element,this.element).add(Sk.PLAYING,e).add(Sk.ENDED,e).add(Sk.PAUSE,e).add(Sk.ERROR,e).add(Sk.LOADEDDATA,e).add(Sk.LOADEDMETADATA,e)}}bindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;if(e){let t=this.handleTrackEvent.bind(this);null==mL||mL.create(e,e).add(Sk.ENDED,t).add(Sk.MUTE,t).add(Sk.UNMUTE,t),e.readyState===Sk.ENDED&&this.handleTrackEvent({type:Sk.ENDED}),e.muted&&this.handleTrackEvent({type:Sk.MUTE})}}bindAutoPlayEvent(){OO.on(MO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;e&&gL(e)}unbindEvents(){this.element&&gL(this.element),this.unbindTrackEvents(),OO.off(MO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case Sk.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(Sk.PLAYING),this._interval&&(hL.clearTask(this._interval),this._interval=-1);break;case Sk.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(Sk.ENDED);break;case Sk.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(Sk.PAUSE),zN&&(this._interval=hL.run("timeout",(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case Sk.ERROR:if(this.element&&this.element.error){this.handlePaused(Sk.ERROR);let{code:e,message:t}=this.element.error;this._log.error("".concat(this.kind," ").concat(this._log.isLocal?"local":"remote"," MediaError code: ").concat(e," message: ").concat(t," userAgent: ").concat(navigator.userAgent)),EL.uploadEvent({log:"stat-".concat(this.kind,"-").concat(Zk.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),Hw||Bw?this.emit(pL.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case Sk.LOADEDDATA:this.kind===Sk.VIDEO&&this.emit(pL.LOADED_DATA);break;case Sk.LOADEDMETADATA:this.kind===Sk.VIDEO&&this.emit(pL.LOADED_META_DATA)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),EL.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),iM.addSuccessEvent({key:this.kind===Sk.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),EL.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),iM.addFailedEvent({key:this.kind===Sk.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(pL.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,i)=>{IN(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)}),IN(5e3).then((()=>{var e,r;(!this.isPlaying||null!=(e=this.element)&&e.error)&&i(null==(r=this.element)?void 0:r.error),t()}))}))})).finally((()=>{this.element&&(this.element.onerror=null)}))}handleTrackEvent(e){switch(e.type){case Sk.ENDED:this.handleStopped(Sk.ENDED);break;case Sk.MUTE:this.handlePaused(Sk.MUTE);break;case Sk.UNMUTE:this._isElementPlayingFired?this.handlePlaying(Sk.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString())}}handlePlaying(e){var t;null==(t=this._playSuccessResolve)||t.call(this,e),this.emit(pL.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(pL.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(pL.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};vb([vL({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],SL.prototype,"doReplayByRecreateMediaStream",1),vb([rL([],"PLAYING",{sync:!0})],SL.prototype,"handlePlaying",1),vb([rL("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],SL.prototype,"handlePaused",1),vb([rL([],"STOPPED",{sync:!0})],SL.prototype,"handleStopped",1);var IL,RL="trtc_autoplay",AL="".concat(RL,"_mask"),CL="".concat(RL,"_wrapper"),bL="".concat(RL,"_header"),kL="".concat(RL,"_content"),DL="".concat(RL,"_action_wrapper"),NL="".concat(RL,"_question"),wL="".concat(RL,"_collapse"),OL="".concat(RL,"_action_confirm"),PL="".concat(RL,"_detail"),ML="#2473E8",LL="dialog",xL="".concat(LL,"-show"),VL="".concat(LL,"-1"),UL="".concat(LL,"-2"),FL=!1,BL=()=>!!document.querySelector(".".concat(CL)),HL="".concat(nk,"/").concat(UD()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),WL="<br><a href='".concat(HL,"' target='_blank'>").concat(UD()?"其他方案?":"Any other solution?","</a>"),GL="".concat(UD()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(WL):"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(WL)),jL=class{constructor(){if(yb(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),yb(this,"_dialogNode",null),yb(this,"_bodyPosition",""),yb(this,"_showDetail",!1),yb(this,"_isCollapseClicked",!1),yb(this,"_isQuestionClicked",!1),UD()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!FL){let e=document.createElement("style");e.innerHTML=".".concat(AL,"{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(AL," div:not(.").concat(DL,"){display:block !important;}.").concat(CL,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(CL," a{color:").concat(ML,";}.").concat(bL,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(kL,"{margin:8px 0;}.").concat(DL,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(wL,"{margin-right:auto;cursor:pointer}.").concat(NL,"{height:100%;line-height:16px;cursor:pointer;}.").concat(OL,"{margin-left:8px;color:#fff;background:").concat(ML,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(OL,":hover{opacity:0.9;}.").concat(wL,",.").concat(OL,",.").concat(kL,",.").concat(NL,"{font-size:14px;}@media screen and (max-width:750px){.").concat(CL,"{width:80vw;}}"),document.head.appendChild(e),FL=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(AL,"\"><div class='").concat(CL,"'><div class='").concat(bL,"'>").concat(location.host,"</div><div class='").concat(kL,"'>").concat(this.content,"</div><div class='").concat(PL,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(GL,"</div><div class='").concat(DL,"'></div></div></div>").trim();let t=document.createElement("button");t.className=OL,t.innerText=UD()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=NL,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=wL,r.innerText="".concat(UD()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(DL));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){BL()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(CL)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",xO.info("show autoplay dialog"),EL.uploadEvent({log:xL}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){xO.warn("confirm clicked, try resume stream"),OO.emit(MO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(PL));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||EL.uploadEvent({log:VL}),this._isCollapseClicked=!0}onQuestionClick(){window.open(HL,"_blank"),this._isQuestionClicked||EL.uploadEvent({log:UL}),this._isQuestionClicked=!0}},JL=class extends SL{constructor(e){super(e,Sk.VIDEO),yb(this,"stat",{}),yb(this,"_calculateTimeout",-1),yb(this,"viewMirror",!1),yb(this,"objectFit"),yb(this,"container"),yb(this,"canvas"),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,jD(e.viewMirror)||(this.viewMirror=e.viewMirror),jD(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return!("PLAYING"!==this._state||this.element&&this.element.paused)&&("live"===(null==(e=this.track)?void 0:e.readyState)&&!this.track.muted)}initializeElement(){var e;let t=document.createElement(Sk.VIDEO);this.track&&2!==this.mode&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(Sk.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(Sk.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;super.handleTrackEvent(e),e.type===Sk.MUTE&&null!=(t=this.stat)&&t.fps&&(this.stat.fps=0)}handleElementEvent(e){var t,i;if(2===this.mode)return;super.handleElementEvent(e);let r=e.type;if(r===Sk.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id)),this.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=mD,this._log.info("view container ".concat(null==(i=this.container)?void 0:i.id," is recreated"))),this._pausedRetryCount>0&&!BL()&&(this._log.info("[".concat(mD-this._pausedRetryCount+1,"/").concat(mD,"] ").concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let e=this.element.style.transform;r===Sk.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):r===Sk.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}}setCanvas(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;var i,r,n,o;this.canvas!==e&&(null==(i=this.canvas)||i.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,2===this.mode&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?(null==(r=this.element)||r.remove(),null==(n=this.container)||n.appendChild(e)):this.element&&(null==(o=this.container)||o.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(t,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}setPoster(e){this.element&&(this.element.poster=e)}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;super.stop(e),null==(t=this.canvas)||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),2===this.mode?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(pL.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(zM()&&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(qb){this._log.warn("init stat failed",qb)}}};function KL(e,t){return Ib(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),xO.info("worklet addModule success")}catch(qb){throw xO.info("worklet addModule catch error. ".concat(qb.message)),qb}}))}"undefined"!=typeof AudioContext?IL=AudioContext:"undefined"!=typeof webkitAudioContext?IL=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(IL=mozAudioContext);var qL,YL=-1;!function e(){try{if(qL)return;(qL=new IL({sampleRate:48e3})).onstatechange=()=>{xO.info("context state: ".concat(qL.state).concat("running"!==qL.state?" visibilityState: ".concat(document.visibilityState):"")),zL()},clearTimeout(YL)}catch(nj){xO.error("initAudioContext failed: ".concat(nj," typeof AudioContextClass: ").concat(typeof IL)),YL=setTimeout(e,1e3)}}();var zL=()=>{"suspended"===qL.state?(ZL(),document.addEventListener("click",zL)):"interrupted"===qL.state?ZL():(document.removeEventListener("visibilitychange",zL),document.removeEventListener("click",zL))},XL=0,QL=-1;function ZL(){return new Promise(((e,t)=>{if("running"===qL.state)return e();Date.now()-XL<1e3?(clearTimeout(QL),QL=setTimeout((()=>{XL=Date.now(),qL.resume().then(e,t)}),1e3)):(clearTimeout(QL),XL=Date.now(),qL.resume().then(e,t))})).catch((e=>{xO.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",zL)}))}document.addEventListener("click",zL);var $L=e=>qL,ex=class{constructor(){yb(this,"node"),yb(this,"node2"),yb(this,"pre",new Set),yb(this,"next",new Set),yb(this,"context"),yb(this,"connectedNodes",new Set),yb(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(e){this._channelCount=e,this.setChannelCount(this.node,e),this.setChannelCount(this.node2,e),this.next.forEach((t=>t.channelCount=e))}setChannelCount(e,t){!e||e instanceof ScriptProcessorNode||(e.channelCountMode="explicit",e.channelCount=t||this.channelCount||1)}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&(null==(e=this.context)||e.reduceMixWeight()),delete this.context}replaceNode(e){var t;if(e!==this.node)try{this.node?this._disconnect():null==(t=this.context)||t.addMixWeight(),this.node=e,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(Xk){xO.error(Xk)}}setNode(e,t){var i;if(!this.node)try{null==(i=this.context)||i.addMixWeight(),this.node=e,this.setChannelCount(this.node),t&&(this.node2=t,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),iM.addSuccessEvent({key:502701})}catch(JO){xO.error(JO),iM.addFailedEvent({key:502701,error:JO})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),iM.addSuccessEvent({key:502702})}catch(qb){xO.error(qb),iM.addFailedEvent({key:502702,error:qb})}}preNodeReconnect(){this.pre.forEach((e=>{e.node?e.reconnect():e.preNodeReconnect()}))}connectNext(e){this.next.forEach((t=>{e._connect(t.node)||t.connectNext(e)}))}_connect(e){return!(!this.node||!e)&&((this.node2||this.node).connect(e),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach((e=>{var t;return null==(t=this.node2||this.node)?void 0:t.disconnect(e)})),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t.forEach((e=>{this.next.add(e),e.pre.add(this)})),this}},tx=class extends ex{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,yb(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}},ix=class{constructor(){yb(this,"source",new ex),yb(this,"gain",new ex),yb(this,"destination",new ex)}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($L().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.replaceNode(sx(e))}get track(){var e;return null==(e=this.stream)?void 0:e.getAudioTracks()[0]}get stream(){var e;return null==(e=this.destination.node)?void 0:e.stream}},rx=class extends ix{constructor(e){super(),this.context=e,yb(this,"denoiser",new ex),yb(this,"voiceChanger",new ex),this.source.pipeTo(this.denoiser.pipeTo(this.voiceChanger.pipeTo(this.gain.pipeTo(this.destination))))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){1!==e?(this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}},nx=class{constructor(){yb(this,"audioContext",$L()),yb(this,"destination",this.audioContext.createMediaStreamDestination()),yb(this,"inputs",new Set),yb(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]}},ox=new WeakMap;function sx(e){let t=ox.get(e);if(t)return t;let i=$L();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return ox.set(e,t),t}var ax=class e{constructor(e){yb(this,"_volume",0),yb(this,"_volumeDb",0),yb(this,"_log"),yb(this,"_scriptProcessorNode",null),yb(this,"_audioWorkletNode",null),yb(this,"_interval",200),yb(this,"ready",this.preload());let{log:t}=e;this._log=t,OO.on(MO.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=KL(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(jO){this._log.error("volumeMeter init audio worklet error: ".concat(jO)),EL.logFailedEvent({userId:this._log.userId,eventType:Zk.LOAD_WORKLET,error:jO}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=$L().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(jO){this._log.error("volumeMeter init script processor error: ".concat(jO))}}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,OO.off(MO.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})}};yb(ax,"lastMessageTime",0),yb(ax,"audioContext",$L()),yb(ax,"workletReady");var cx=ax,lx=class extends ex{constructor(e){super(),yb(this,"_volumeMeter"),this._volumeMeter=new cx(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return Ib(this,null,(function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)}))}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}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()}}},dx=cx,ux=Tb(Rb(),1),hx=e=>t=>t.deviceId===e,px=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";yb(this,"kind"),yb(this,"type"),yb(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&&fx(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(hx(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");xO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(hx(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");xO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},mx=class extends ux.EventEmitter{constructor(){super(),yb(this,"audioInputs",new px(Sk.AUDIO)),yb(this,"videoInputs",new px(Sk.VIDEO)),yb(this,"audioOutputs",new px(Sk.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||hL.run("interval",(()=>{this.update()}),{delay:1e4}))}init(){gx().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return Ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield gx(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},_x=Xb||zb?null:new mx;function fx(e){return e.deviceId===e.groupId&&""===e.groupId}function gx(){return Ib(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(dM()||!cM())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{fx(e)&&(e.kind===Sk.AUDIO_INPUT?i.audio=!0:e.kind===Sk.VIDEO_INPUT&&(i.video=!0))})),2===e&&(i.audio=!1),1===e&&(i.video=!1),i.audio||i.video){let e;try{e=yield navigator.mediaDevices.getUserMedia(i),i.audio&&ZL()}catch(JO){xO.debug("capture before getDevices failed: ",JO)}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&&Sx.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function Ex(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return _x.update(e?1:0).then((e=>e.audioInputs.devices))}function Tx(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return _x.update(e?2:0).then((e=>e.videoInputs.devices))}var vx=!1;function yx(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Ib(this,null,(function*(){return(zN||rO)&&(e=!1),_x.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var Sx=new Set;function Ix(e,t){return Ib(this,null,(function*(){let i=(yield Ex()).find((e=>e.deviceId===_D));return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t}))}var Rx,Ax=class extends ix{constructor(e){super(),this.log=e,yb(this,"volumeMeter"),yb(this,"volumeDestination"),yb(this,"analyser",new tx),this.volumeMeter=new lx({log:this.log}),this.volumeDestination=new ex,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Cx=class e extends SL{constructor(e){super(e,Sk.AUDIO),yb(this,"_outputDeviceId"),yb(this,"_volume",1),yb(this,"_destination",$L().createMediaStreamDestination()),yb(this,"pipeline"),yb(this,"volumeMeterMode","worklet"),this.mode=0,this.pipeline=new Ax(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(("15.2"===aO||"15.3"===aO||"15.4"===aO)&&this.muted)return void this._log.info("audioElement is muted.");let t=Rx||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,KD(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),t===Rx&&(Rx=void 0),this.bindElementEvents()}play(t){return Ib(this,null,(function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(null==t?void 0:t.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode($L().createAnalyser()),function(){Ib(this,null,(function*(){try{vx||(vx=!0,xO.info("speakers:".concat((yield yx()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(e){}}))}(),Sb(e.prototype,this,"play").call(this)}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy(),super.stop(e)}setSinkId(e){return Ib(this,null,(function*(){var t,i;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield null==(i=(t=this.element).setSinkId)?void 0:i.call(t,e))}))}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},bx=class extends Cx{setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(pL.MEDIA_TRACK_CHANGED,e),e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]))))}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}},kx=class extends Cx{constructor(e){super(e),yb(this,"_sourceElement"),yb(this,"_output",new ex),this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode($L().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(pL.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=(null==(r=e.getSettings())?void 0:r.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?this.element?(this._log.info("set element volume: ".concat(e)),this.element.volume=e):this._log.info("set element volume: no element"):zN||(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),gL(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&nO&&(Rx=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},Dx=class extends sL{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:o=(1===r?kx:JL)}=e;var s;super(),yb(this,"id",VO()),yb(this,"userId",""),yb(this,"isRemote"),yb(this,"mediaType"),yb(this,"room"),yb(this,"user"),yb(this,"_log"),yb(this,"_inputTrack"),yb(this,"_outputTrack"),yb(this,"isPlayCalled"),yb(this,"container",null),yb(this,"player"),yb(this,"subVideoPlayerMap"),yb(this,"muted",!1),yb(this,"abortCtrl"),yb(this,"objectFit","cover"),yb(this,"mirror"),yb(this,"isScreen",!1),yb(this,"manager"),yb(this,"trackSettings"),yb(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=xO.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=n||this.room)?void 0:s.userId,remoteUserId:this instanceof Qx?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof Qx}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(pL.PLAYER_STATE_CHANGED,(e=>{OO.emit(MO.PLAYER_STATE_CHANGED,_b({track:this},e)),this.emit("player-state-changed",e)})),this.kind===Sk.VIDEO&&(this.player.on(pL.LOADED_DATA,(()=>{this.emitFirstVideoFrameEvent(pL.LOADED_DATA),OO.emit(MO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(pL.LOADED_META_DATA,(()=>{this.emitFirstVideoFrameEvent(pL.LOADED_META_DATA)})),this.player.on(pL.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))}))),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(pL.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||xO}get kind(){return 1===this.mediaType?Sk.AUDIO:Sk.VIDEO}get strMediaType(){return 4===this.mediaType?Sk.VIDEO:2===this.mediaType?Sk.SCREEN:Sk.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&(!this.mediaTrack.muted&&"live"===this.mediaTrack.readyState&&this.mediaTrack.enabled)}play(e,t){return Ib(this,null,(function*(){let i=zD(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!jD(t.muted)&&this.setPlayerMute(t.muted),t&&!jD(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof JL&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),zD(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!jD(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===Sk.VIDEO)&&this.setPlayerMute(!0),t&&!jD(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof JL&&(this.player.setObjectFit(this.objectFit),t&&!jD(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof JL&&this.player.setContainer(i)),OO.emit(MO.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),zD(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(YO){throw this.handleAutoPlayFailed(YO),YO}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==Sk.VIDEO||jD(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(qD(this.mirror))return i.setViewMirror(this.mirror),void(r&&(r.mirror=!1));switch(this.mirror){case"view":r&&(r.mirror=!1),i.setViewMirror(!0);break;case"publish":r&&(r.mirror=!0),i.setViewMirror(!0);break;case"both":r&&(r.mirror=!0),i.setViewMirror(!1)}}playSubContainer(e,t){return Ib(this,null,(function*(){if(!this._outputTrack||this.kind===Sk.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,i)=>{var r;e.find((e=>i===e))||(t.stop(),null==(r=this.subVideoPlayerMap)||r.delete(i))}));for(let[r,n]of e.entries()){let e=this.subVideoPlayerMap.get(n);e?t&&(jD(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new JL({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(r+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let e of i)e.setViewMirror(this.player.mirror),yield e.play()}))}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return(null==(e=this.player)?void 0:e.getInternalAudioLevel())||0}stop(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(MN(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return Ib(this,null,(function*(){var e;this.isPlayCalled&&(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),OO.emit(e?MO.TRACK_MUTED:MO.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){fL(e,e).add(Sk.MUTE,this.onTrackMuted).add(Sk.UNMUTE,this.onTrackUnmuted).add(Sk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Sk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){gL(e)}setInputMediaStreamTrack(e){var t;let i=this._inputTrack;if(e!==i)return this._inputTrack=e,this.trackSettings=null==(t=e.getSettings)?void 0:t.call(e),e.enabled=!this.muted,i&&this.uninstallTrackEvent(i),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,i||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(t=e.getSettings)?void 0:t.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled)if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch((e=>this.handleAutoPlayFailed(e))),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(MN(this)?this.jitterBufferDelay:0),void this.log.info("playing state updated, stop ".concat(this.kind));this.log.debug("updatePlayingState abort ".concat(this.isPlayCalled," ").concat(e," ").concat(this.player.isStopped))}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new jL;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof JL?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===pL.LOADED_META_DATA&&!o&&!s||(e===pL.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,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"))}};vb([rL([],sL.INIT,{sync:!0})],Dx.prototype,"close",1);var Nx=Object.prototype.hasOwnProperty;var wx=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(FD(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(Nx.call(e,t))return!1;return!0}return!1},Ox=xN({retryFunction:function(e){return Ib(this,null,(function*(){let t=function(e){return{audio:Mx(e),video:Lx(e)}}(e);xO.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId","groupId"];t.audio&&(i=yield Ex(),xO.info("microphones: ".concat(fN(i.map((e=>fb(_b({},e),{groupId:e.groupId.substring(0,8)}))),{keysToInclude:n})))),t.video&&(r=yield Tx(),xO.info("cameras: ".concat(fN(r,{keysToInclude:n}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return VM&&e.getTracks().forEach((e=>{xO.info("".concat(e.kind," capabilities: ").concat(fN(e.getCapabilities(),{keysToInclude:SD})))})),t.audio&&ZL(),e}catch(YO){let{message:n}=YO;throw"NotFoundError"===YO.name&&(e.video&&r&&0===r.length&&(n=JP({key:HP.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(n=JP({key:HP.MICROPHONE_NOT_FOUND}))),new Vb({code:Lb.INITIALIZE_FAILED,name:YO.name,message:n,constraint:YO.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,retryFuncArgs:n,retriedCount:o}=e,s=o+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===s?(n[0].video&&(n[0].maxResolution=!1,(!rO||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&&Px(n[0].microphoneId,!1),n[0].cameraId&&Px(n[0].cameraId,!0)},onRetrying:e=>{xO.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{EL.logFailedEvent({eventType:Zk.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{EL.logSuccessEvent({eventType:Zk.GET_USER_MEDIA_RETRY}),EL.uploadEvent({log:"stat-".concat(Zk.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function Px(e,t){return Ib(this,null,(function*(){let i=(t?yield Tx():yield Ex()).find((t=>t.deviceId===e));i&&GD(i.getCapabilities)&&xO.warn(fN(i.getCapabilities(),{keysToInclude:SD}))}))}function Mx(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!wx(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(KD(e.channelCount)&&(t.channelCount=e.channelCount),qD(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),qD(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),qD(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!wx(t)||t)}function Lx(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&&!wx(i)?i:(e.width&&(i.width={ideal:e.width},t&&!ew&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!ew&&(i.height.max=e.height)),ew&&ww&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!wx(i)||i)}var xx=Ox;function Vx(e){return Bx(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Ib(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function Ux(e){return Bx(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Ib(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function Fx(e){return Bx(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Ib(this,null,(function*(){try{return yield t.apply(this,r)}catch(JO){e.call(this,JO)}}))}))}function Bx(e){return function(t,i,r){return r.value=e(r.value,i),r}}var Hx=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&xO.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{xO.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),Wx=0,Gx=class{constructor(){yb(this,"log",xO.createLogger({id:"fq".concat(++Wx)})),yb(this,"isRunning",!1),yb(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return 0===this.length?null:this.queue[this.length-1]}push(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i,r;let n=_b({},e),o=new Promise(((e,t)=>{n.resolve=e,n.reject=t}));return n.promise=o,t?this.length<=1?this.queue.push(n):null==(r=null==(i=this.lastQueueItem)?void 0:i.promise)||r.then(n.resolve,n.reject):this.queue.push(n),this.log.debug("push ".concat(this.length)),this.isRunning||this.callNext(),o}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length)),e}callNext(){if(this.isRunning||0===this.length)return;this.log.debug("callNext ",this.length);let{fn:e,args:t,context:i,resolve:r,reject:n}=this.queue[0];this.isRunning=!0,e.apply(i,t).then(r,n).finally((()=>{this.isRunning=!1,this.shift(),this.callNext()}))}},jx=new WeakMap,Jx=new WeakMap;function Kx(){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=jx.get(this)||new Gx;for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return jx.set(this,t),t.push({fn:n,args:r,context:this},e)},r}}function qx(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=jx.get(this))?void 0:t.queue)||i.forEach((e=>o.push(e))),null==(r=Jx.get(this))||r.forEach((e=>null==e?void 0:e.queue.forEach((e=>o.push(e))))),o.forEach((t=>{t.reject(new Vb({code:Lb.API_CALL_ABORTED,message:e}))})),jx.delete(this),Jx.delete(this),n.apply(this,a)},r}}function Yx(e){return function(t,i,r){let n=r.value,o=t=>e(...t);return r.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=Jx.get(this)||new Map,s=r.get(o(t))||new Gx;return r.set(o(t),s),Jx.set(this,r),s.push({fn:n,args:t,context:this})},r}}function zx(e,t){return Bx(((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=rN();return ZD(e)?e.then((e=>(t?iM.addSuccessEvent({key:r,cost:rN()-a}):iM.addSuccessEvent({key:r}),e))).catch((e=>{throw iM.addFailedEvent({key:r,error:e}),e})):(iM.addSuccessEvent({key:r}),e)}catch(Yb){throw iM.addFailedEvent({key:r,error:Yb}),Yb}}))}var Xx=class e extends Dx{constructor(e,t){super({mediaType:e,PlayerClass:t}),yb(this,"isRemote",!1),yb(this,"deviceId"),yb(this,"groupId",""),yb(this,"label",""),yb(this,"sourceTrack"),yb(this,"_isRecapturing",!1),yb(this,"_lastRecaptureTime",0),yb(this,"_onMuteTimeoutId",-1),yb(this,"_encodeCheckTimeoutId",-1),yb(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return"publishing"===this.state.toString()}get isPublished(){return"publish"===this.state}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){fL(e,e).add(Sk.MUTE,this.onTrackMuted).add(Sk.UNMUTE,this.onTrackUnmuted).add(Sk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Sk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){gL(e)}setStateToReady(){}capture(e){return Ib(this,null,(function*(){var t;try{let i,r=rN();OO.emit(MO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield xx(e));let n=i.getTracks()[0];return this.sourceTrack=n,yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),OO.emit(MO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:rN()-r}),i}catch(JO){throw OO.emit(MO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:JO}),this.log.error("getUserMedia error observed ".concat(JO)),JO}}))}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return null==(t=this.room)?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),OO.emit(MO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return Ib(this,null,(function*(){if(this.mediaTrack&&xM){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return Ib(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==Sk.AUDIO||t!==_D||(yield Ix(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),gx().then((t=>{let i=t.find((t=>t.deviceId===e));i&&this.emit("2",i)})))}}))}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return!(!this.deviceId||!this.mediaTrack||this.kind===Sk.AUDIO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("麦克风"))return!0;let i="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(Sk.AUDIO_INPUT);return!!Sx.has(i)}(this.mediaTrack)||this.kind===Sk.VIDEO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let i="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(Sk.VIDEO_INPUT);return!!Sx.has(i)}(this.mediaTrack)||this._isRecapturing||e&&ww&&rO)}onTrackMuted(){if(super.onTrackMuted(),Hx(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<yD)return void setTimeout((()=>this.onTrackMuted()),yD);this._onMuteTimeoutId=setTimeout((()=>Ib(this,null,(function*(){var e;if(null!=(e=this.mediaTrack)&&e.muted){if((zN||XN)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return Ib(this,null,(function*(){if(Sb(e.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<yD)return void setTimeout((()=>this.onTrackEnded()),yD);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return Ib(this,null,(function*(){var t;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),null==(t=this._inputTrack)||t.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let i={useExactDeviceId:!0};if("user"===e||"environment"===e)i.facingMode=e;else{let t;("audio"===this.kind?yield Ex():yield Tx()).find((t=>t.deviceId===e))&&(t=e),i.deviceId=t}return this.capture(i).then((()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),OO.emit(MO.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),OO.emit(MO.LOCAL_TRACK_RECAPTURE,{track:this,error:e})}))}))}getRecoverCaptureDeviceId(){return Ib(this,null,(function*(){let e=this instanceof rV;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(Zx.get(t)||0)+1;if(Zx.set(t,i),i>=3){let r=e?(yield Tx()).find((e=>!Zx.has(e.deviceId))):(yield Ex()).find((e=>!Zx.has(e.deviceId)));r&&(this.log.warn("".concat(t," capture fail ").concat(i," times, change new ").concat(r.deviceId)),t=r.deviceId)}}return t}))}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),null==(e=this.manager)||e.removeInput(this)}};vb([rL(sL.INIT,"ready",{ignoreError:!0,sync:!0})],Xx.prototype,"setStateToReady",1),vb([Kx()],Xx.prototype,"capture",1),vb([rL("ready","publish",{ignoreError:!0,success(){var e,t;this.room.localTracks.add(this),OO.emit(MO.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout((()=>{var e,t;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let e=this.kind===Sk.AUDIO,t=this.stat.bytesSent>0;iM[t?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),t||(iM.addEnum({key:e?503701:513703,value:bO()}),EL.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(RO()||kO()),userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}}),5e3))},fail(e){let t="error";if(e.cause instanceof RTCError){let i=e.cause;i.message.includes("timeout")?t="timeout":i.code===Lb.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),zx(521714,!1)],Xx.prototype,"publish",1),vb([Bx((e=>function(){return Ib(this,null,(function*(){let t="publish"===this.state?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)}))})),rL([],"ready",{sync:!0})],Xx.prototype,"unpublish",1);var Qx=Xx,Zx=new Map;OO.on(MO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&Zx.delete(e.track.deviceId)}));var $x=class e extends Qx{constructor(e){super(1,bx),yb(this,"mediaType",1),yb(this,"volume",0),yb(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),yb(this,"playerMuted",!0),yb(this,"pipeline"),yb(this,"earMonitorGainNode",new ex),yb(this,"_output",new ex),yb(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),this.manager=e,this.pipeline=new rx(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode.pipeTo(this._output),this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return dx.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}setInputMediaStreamTrack(t){return Ib(this,null,(function*(){let i=this.trackSettings||{};iM.addEnum({key:501701,value:i.channelCount||0,useUV:!1}),iM.addEnum({key:501702,value:i.sampleRate||0,useUV:!1}),iM.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 Sb(e.prototype,this,"setInputMediaStreamTrack").call(this,t),this.updatePlayingState(!!t)}))}capture(e){let{deviceId:t,customSource:i,useExactDeviceId:r=!0,retryWhenExactFailed:n=!0}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:n,customSource:i})}switchDevice(e){return Ib(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==_D)return;if(yield Ix(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),OO.emit(MO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(Xk){throw this.log.error("switch microphone failed ".concat(Xk)),this.deviceId&&this.recapture(this.deviceId),Xk}}}))}listenDeviceChange(){_x&&!_x.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&_x.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return Ib(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e))),YF(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield Ex();t[0]?this.recapture(t[0].deviceId):_x.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return Ib(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:n}=e;return function*(){let e=t.sourceTrack||t.mediaTrack;if(!e)return;let o=e.getConstraints(),s=!1;!jD(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,o.echoCancellation=i,s=!0),!jD(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,o.noiseSuppression=r,s=!0),!jD(n)&&n!==t.profile.autoGainControl&&(t.profile.autoGainControl=n,o.autoGainControl=n,s=!0),s&&(ew||rO?yield e.applyConstraints(o).catch((e=>t._log.warn("update3A failed: ",e))):t.deviceId&&(yield t.recapture(t.deviceId)))}()}))}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&iM.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),zN&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode($L().createGain()),this._output.setNode($L().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}addDenoiser(e){var t;tO<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(iM.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1))}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}close(){this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),_x.off("audioInputAdded",this.handleMicrophoneAdded,this),_x.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(t){return Ib(this,null,(function*(){try{yield Sb(e.prototype,this,"recapture").call(this,t)}catch(Xk){let r=(yield Ex()).find((e=>e.deviceId!==t));if(!r)throw Xk;yield Sb(e.prototype,this,"recapture").call(this,r.deviceId)}}))}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight(((e,t)=>t?t({frame:e}):e),e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}},eV=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,i=[],r=0;for(let o=e;o<=t;o++){let e=this.dataView.getInt8(o);switch(e){case 0:case 1:case 2:case 3:2===r&&(i.push(3),r=0),0==e?r++:r=0,i.push(e);break;default:r=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],r=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:r++,i.push(this.dataView.getInt8(o));break;case 3:2!==r&&i.push(this.dataView.getInt8(o)),r=0;break;default:i.push(this.dataView.getInt8(o)),r=0}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}get isSEI(){return 6===this.dataView.getUint8(4)}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let n=6;n<this.dataView.buffer.byteLength;n++){let i=this.dataView.getUint8(n);if(t++,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),r=new DataView(i);for(let n=0;n<i.byteLength;n++,t++)r.setInt8(n,this.dataView.getInt8(t));return r}},tV=class{constructor(){yb(this,"_seiMessageList",[]),yb(this,"_smallSeiMessageList",[]),yb(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 eV(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}},iV=class e extends Qx{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,JL),yb(this,"profile",_b({},Tk)),yb(this,"avoidCropping",!1),yb(this,"_scaleResolutionDownBy"),yb(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0}),yb(this,"small"),yb(this,"isNeedToSetBandwidth"),yb(this,"muteImage"),yb(this,"manager"),yb(this,"_seiCodec",new tV),this.manager=e;let t=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(fb(_b({},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(xM&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return(null==(e=this._inputTrack)?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}setMute(t){return Ib(this,null,(function*(){var i,r,n;if(JD(t)){if(this.muteImage===t)return;yield null==(i=this.manager)?void 0:i.deleteWatermark("mute"),yield null==(r=this.manager)?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:t}),this.muteImage=t,Sb(e.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield null==(n=this.manager)?void 0:n.deleteWatermark("mute"),this.muteImage=void 0),Sb(e.prototype,this,"setMute").call(this,t)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:r=!0,customSource:n,retryWhenExactFailed:o=!0}=e;return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:o,customSource:n})}setProfile(e){let t=_b({},e),i=t.width>t.height;t.width*t.height<=19200&&XN&&Zw&&(this.log.warn("resolution is ".concat(t.width,"*").concat(t.height,", fallback to 240*180")),t.width=i?240:180,t.height=i?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&hO&&(t.width=i?1280:720,t.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),this.avoidCropping&&(Zw||ew)&&!vO()&&t.width*t.height<=230400&&t.width/t.height==16/9&&(this._scaleResolutionDownBy=1280/t.width,t.width=1280,t.height=720,this.log.warn("capture 720p, scale: ".concat(this._scaleResolutionDownBy))),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(fb(_b({},this.profile),{width:1920,height:1080})))}applyProfile(){return Ib(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;if((n.height!==this.profile.height||n.width!==this.profile.width||n.frameRate!==this.profile.frameRate)&&this.deviceId&&(16===lO?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 i&&r&&i===r?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:Sk.VIDEO,videoType:Sk.BIG})}}))}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return xM&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:bN(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 Ib(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),OO.emit(MO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(Xk){throw this.log.error("switch camera failed ".concat(Xk)),this.deviceId&&this.recapture(this.deviceId),Xk}}))}updateSmallConfig(e){var t,i;this._log.info("update small stream config: ".concat(JSON.stringify(e)));let r=!this.small;this.small=e,null==(t=this.manager)||t.update(),r&&(null==(i=this.room)||i.enableSmall(!0)),this.log.info("update small stream config success")}stopSmall(){var e,t;this.small&&(delete this.small,null==(e=this.manager)||e.update(),null==(t=this.room)||t.enableSmall(!1))}listenDeviceChange(){_x&&!_x.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&_x.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return Ib(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e))),YF(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield Tx();t[0]?this.recapture(t[0].deviceId):_x.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return Ib(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}encodeFrame(e,t){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 jD(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){_x.off("videoInputAdded",this.handleCameraAdded,this),_x.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return Ib(this,null,(function*(){try{yield Sb(e.prototype,this,"recapture").call(this,t)}catch(Xk){let r=(yield Tx()).find((e=>e.deviceId!==t));if(!r)throw Xk;yield Sb(e.prototype,this,"recapture").call(this,r.deviceId)}}))}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info("setContentHint ".concat(e)),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}};vb([Ux((function(e){this.setContentHint(e.contentHint||"motion")}))],iV.prototype,"capture",1);var rV=iV,nV=VO();if("undefined"!=typeof navigator&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:nV,exposeOrigin:!0,permittedOrigins:["*"]})}catch(nj){}var oV=function(e){return Ib(this,null,(function*(){let t=null,i=function(e){let t={preferCurrentTab:"current-tab"===e.preferDisplaySurface||!!e.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:rO?{max:e.width}:{ideal:e.width,max:e.width},height:rO?{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);xO.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&($w&&tO<74||rO||ew)&&xO.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(YO){xO.warn("screen applyConstraints failed: ".concat(YO))}e.captureElement&&(yield function(e,t){return Ib(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&GD(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==nV)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){xO.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 jD(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);xO.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},sV=class extends rV{constructor(e){super(e,2),yb(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),yb(this,"objectFit","contain"),yb(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return Ib(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:r,echoCancellation:n,noiseSuppression:o,audioTrack:s,videoTrack:a,captureElement:c,preferDisplaySurface:l}=e;return function*(){try{let e;return a||s?(e=new MediaStream,a&&e.addTrack(a),s&&e.addTrack(s)):e=yield oV({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:r,echoCancellation:n,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof Vb?e:new Vb({code:Lb.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return Ib(this,null,(function*(){throw new Error("Method not implemented.")}))}};vb([Ux((function(e){this.setContentHint(e.contentHint||"detail")}))],sV.prototype,"capture",1);var aV,cV=class extends $x{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}};function lV(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3,i=arguments.length>2?arguments[2]:void 0;return Ib(this,null,(function*(){let r=$L();aV||(aV=KL(r,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 aV;let n=r.sampleRate,o=new AudioWorkletNode(r,"dumper",{numberOfInputs:e.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:n,targetSampleRate:t}});return i&&o.port.postMessage({port:i},[i]),e.forEach(((e,t)=>e.connect(o,0,t))),new ReadableStream({start(e){o.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach((e=>e.disconnect(o))),o.port.close()}})}))}var dV=class extends nx{constructor(e){super(),this.room=e,yb(this,"_localAudioTrack"),yb(this,"_localScreenAudioTrack"),yb(this,"log",xO.createLogger({id:"am"})),yb(this,"denoiser"),yb(this,"voiceChanger"),yb(this,"mixChangedDebounce"),yb(this,"encodePipeline",[]),yb(this,"decodePipeline",[]),yb(this,"getPCMAbortCtrlMap",new Map),yb(this,"audioFrameEventConfigMap",new Map),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.installEvent()}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}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=lV(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(jD(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 lV([$L().createMediaStreamSource(new MediaStream([f]))],s,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),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),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 null!==this._localScreenAudioTrack}get hasAudioTrack(){return!jD(this._localAudioTrack)}changeInput(e){return e instanceof cV?(this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange()):e instanceof $x?(this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange()):e instanceof bF?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then((()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([null==(e=this._localAudioTrack)?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),null==(t=this._localScreenAudioTrack)?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])}))),this.mixChangedDebounce}removeInput(e){e instanceof cV?delete this._localScreenAudioTrack:e instanceof $x&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,null==(t=this._localAudioTrack)||t.removeDenoiser(e)}addVoiceChanger(e,t){var i;this.voiceChanger=[e,t],null==(i=this._localAudioTrack)||i.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,null==(e=this._localAudioTrack)||e.pipeline.voiceChanger.deleteNode()}destroy(){this.close(),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(){OO.on("113",this.handleLocalTrackStarted,this),OO.on("114",this.handleLocalTrackStopped,this),OO.on("115",this.handleRemoteTrackStarted,this),OO.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){OO.off("113",this.handleLocalTrackStarted),OO.off("114",this.handleLocalTrackStopped),OO.off("115",this.handleRemoteTrackStarted),OO.off("116",this.handleRemoteTrackStopped)}};function uV(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return Bx(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];return new Promise(((n,s)=>{let a=setTimeout((()=>{let i=new Vb({code:Lb.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});xO.warn(i),2===t?s(i):1===t&&n()}),1e3*e);i.apply(this,o).then(n,s).finally((()=>{clearTimeout(a)}))}))}))}var hV={};function pV(){}Eb(hV,{Events:()=>kV,Inspect:()=>TV,LastSink:()=>vV,Sink:()=>yV,Subscribe:()=>SV,TimeoutError:()=>DV,audit:()=>PU,bindCallback:()=>cU,bindNodeCallback:()=>lU,buffer:()=>WV,bufferCount:()=>HV,bufferTime:()=>fF,call:()=>mV,catchError:()=>EF,combineLatest:()=>VV,concat:()=>MV,concatMap:()=>nF,concatMapTo:()=>oF,count:()=>_U,create:()=>RV,debounce:()=>xU,debounceTime:()=>VU,defer:()=>JV,delay:()=>gF,deliver:()=>AV,dispose:()=>fV,elementAt:()=>UU,empty:()=>hU,every:()=>GU,exhaustMap:()=>hF,exhaustMapTo:()=>pF,filter:()=>TU,find:()=>FU,findIndex:()=>BU,first:()=>HU,fromAnimationFrame:()=>sU,fromArray:()=>zV,fromEvent:()=>eU,fromEventPattern:()=>$V,fromFetch:()=>iU,fromIterable:()=>rU,fromPromise:()=>tU,fromReadableStream:()=>oU,fromReader:()=>nU,groupBy:()=>mF,identity:()=>_V,ignoreElements:()=>vU,iif:()=>xV,inspect:()=>gV,interval:()=>XV,last:()=>WU,map:()=>qU,mapTo:()=>YU,max:()=>fU,merge:()=>OV,mergeMap:()=>cF,mergeMapTo:()=>lF,min:()=>gU,never:()=>dU,nothing:()=>pV,of:()=>YV,pairwise:()=>JU,pipe:()=>IV,race:()=>PV,range:()=>aU,reduce:()=>mU,retry:()=>RF,scan:()=>jU,share:()=>wV,shareReplay:()=>LV,skip:()=>AU,skipUntil:()=>CU,skipWhile:()=>bU,startWith:()=>FV,subject:()=>jV,subscribe:()=>yF,sum:()=>EU,switchMap:()=>$U,switchMapTo:()=>tF,take:()=>yU,takeLast:()=>RU,takeUntil:()=>SU,takeWhile:()=>IU,tap:()=>SF,throttle:()=>wU,throwError:()=>uU,timeInterval:()=>_F,timeout:()=>IF,timer:()=>QV,toPromise:()=>TF,toReadableStream:()=>vF,withLatestFrom:()=>BV,zip:()=>UV});var mV=e=>e(),_V=e=>e;function fV(){this.dispose()}var gV=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,EV=1,TV=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new bV(e,this,this.streamId++);return kV.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},vV=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=pV,this.error=pV,this.next=pV,this.dispose=pV,this.subscribe=pV,this.doDefer()}subscribe(e){return e instanceof TV?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(mV),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}},yV=class extends vV{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)}},SV=class extends vV{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:pV,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:pV,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:pV;if(super(),this._next=t,this._error=i,this._complete=r,this.then=pV,e instanceof TV){let n={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{kV.defer(n,0)})),kV.create(n),kV.pipe(n),this.sourceId=n.id,this.subscribe(e),kV.subscribe({id:n.id,end:!0}),t==pV?this._next=e=>kV.next(n,0,e):this.next=e=>{kV.next(n,0,e),t(e)},r==pV?this._complete=()=>kV.complete(n,0):this.complete=()=>{this.dispose(),kV.complete(n,0),r()},i==pV?this._error=e=>kV.complete(n,0,e):this.error=e=>{this.dispose(),kV.complete(n,0,e),i()}}else this.subscribe(e)}next(e){this._next(e)}complete(){this.dispose(),this._complete()}error(e){this.dispose(),this._error(e)}};function IV(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 RV(e,t,i){if(gV()){let r=Object.defineProperties(Object.setPrototypeOf(e,TV.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}});kV.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof TV&&kV.addSource(r,t)}return r}return e}function AV(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 TV){let n=RV((t=>{let o=new e(t,...r);o.sourceId=n.id,o.subscribe(i)}),t,arguments);return n.source=i,kV.pipe(n),n}return t=>i(new e(t,...r))}}}function CV(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var bV=class extends yV{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{kV.defer(this.source,this.id)}))}next(e){kV.next(this.source,this.id,e),this.sink.next(e)}complete(){kV.complete(this.source,this.id),this.sink.complete()}error(e){kV.complete(this.source,this.id,e),this.sink.error(e)}},kV={addSource(e,t){CV("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){CV("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;CV("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){CV("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){CV("defer",{id:e.id,streamId:t})},pipe(e){CV("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){CV("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=EV++),CV("create",{name:e.toString(),id:e.id})}},DV=class extends Error{constructor(e){super("timeout after ".concat(e,"ms")),this.timeout=e}},NV=class extends vV{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 wV(){return e=>{let t=new NV(e);if(e instanceof TV){let i=RV((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,kV.pipe(i),i}return RV(t.add.bind(t),"share",arguments)}}function OV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return RV((e=>{let i=new yV(e),r=t.length;i.complete=()=>{0==--r&&e.complete()},t.forEach(i.bindSubscribe)}),"merge",arguments)}function PV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return RV((e=>{let i=new Map;t.forEach((t=>{let r=new yV(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 MV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return RV((e=>{let i=0,r=t.length,n=new yV(e);n.complete=()=>{i<r&&!n.disposed?(n.doDefer(),n.subscribe(t[i++])):e.complete()},n.complete()}),"concat",arguments)}function LV(e){return t=>{let i=new NV(t),r=[];return i.next=function(t){r.push(t),r.length>e&&r.shift(),this.sinks.forEach((e=>e.next(t)))},RV((e=>{e.defer((()=>i.remove(e))),r.forEach((t=>e.next(t))),i.add(e)}),"shareReplay",arguments)}}function xV(e,t,i){return RV((r=>e()?t(r):i(r)),"iif",arguments)}function VV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return RV((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 yV(e);n.next=t=>{0==--r?(n.next=t=>{o[i]=t,e.next(o)},n.next(t)):o[i]=t},n.complete=s,n.subscribe(t)}))}),"combineLatest",arguments)}function UV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return RV((e=>{let i=t.length,r=i,n=new Array(i),o=()=>{0==--r&&e.complete()};t.forEach(((t,i)=>{let r=new yV(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 FV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>RV((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 BV=AV(class extends yV{constructor(e){super(e);let t=new yV(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=pV,t.subscribe(VV(...r))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},"withLatestFrom"),HV=AV(class extends yV{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"),WV=AV(class extends yV{constructor(e,t){super(e),this.buffer=[];let i=new yV(e);i.next=t=>{e.next(this.buffer),this.buffer=[]},i.complete=pV,i.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),GV=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 jV(e){let t=arguments,i=wV()(RV((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=pV,i.complete=pV,i.error=pV,i}function JV(e){return RV((t=>t.subscribe(e())),"defer",arguments)}var KV=e=>t=>{setTimeout((()=>e(t)))},qV=e=>KV((t=>{for(let i=0;!t.disposed&&i<e.length;i++)t.next(e[i]);t.complete()}));function YV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return RV(qV(t),"of",arguments)}function zV(e){return RV(qV(e),"fromArray",arguments)}function XV(e){return RV((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}function QV(e,t){return RV((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 ZV(e,t){return i=>{let r=e=>i.next(e);i.defer((()=>t(r))),e(r)}}function $V(e,t){return RV(ZV(e,t),"fromEventPattern",arguments)}function eU(e,t){if("on"in e&&"off"in e)return RV(ZV((i=>e.on(t,i)),(i=>e.off(t,i))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return RV(ZV((i=>e.addListener(t,i)),(i=>e.removeListener(t,i))),"fromEvent",arguments);if("addEventListener"in e)return RV(ZV((i=>e.addEventListener(t,i)),(i=>e.removeEventListener(t,i))),"fromEvent",arguments);throw"target is not a EventDispachter"}function tU(e){return RV((t=>{e.then(t.next.bind(t),t.error.bind(t))}),"fromPromise",arguments)}function iU(e,t){return RV(JV((()=>tU(fetch(e,t)))),"fromFetch",arguments)}function rU(e){return RV(KV((t=>{try{for(let i of e){if(t.disposed)return;t.next(i)}t.complete()}catch(qb){t.error(qb)}})),"fromIterable",arguments)}function nU(e){let t=i=>GV(this,void 0,void 0,(function*(){if(i.disposed)return;let{done:r,value:n}=yield e.read();r?i.complete():(i.next(n),t(i))}));return RV((e=>{t(e)}),"fromReader",arguments)}function oU(e){return RV((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 sU(){return RV((e=>{let t=requestAnimationFrame((function i(r){e.disposed||(e.next(r),t=requestAnimationFrame(i))}));e.defer((()=>cancelAnimationFrame(t)))}),"fromAnimationFrame",arguments)}function aU(e,t){return RV((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 cU(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 RV((i=>{let n=r.concat((e=>(i.next(e),i.complete())));e.apply(t,n)}),"bindCallback",arguments)}function lU(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 RV((i=>{let n=r.concat(((e,t)=>e?i.error(e):(i.next(t),i.complete())));e.apply(t,n)}),"bindNodeCallback",arguments)}function dU(){return RV((()=>{}),"never",arguments)}function uU(e){return RV((t=>t.error(e)),"throwError",arguments)}function hU(){return RV((e=>e.complete()),"empty",arguments)}var pU=class extends yV{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)}},mU=AV(pU,"reduce"),_U=e=>AV(pU,"count")(((t,i)=>e(i)?t+1:t),0),fU=()=>AV(pU,"max")(Math.max),gU=()=>AV(pU,"min")(Math.min),EU=()=>AV(pU,"sum")(((e,t)=>e+t),0),TU=AV(class extends yV{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"),vU=AV(class extends yV{next(e){}},"ignoreElements"),yU=AV(class extends yV{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&this.complete()}},"take"),SU=AV(class extends yV{constructor(e,t){super(e);let i=new yV(e);i.next=()=>e.complete(),i.complete=fV,i.subscribe(t)}},"takeUntil"),IU=AV(class extends yV{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):this.complete()}},"takeWhile"),RU=e=>mU(((t,i)=>(t.push(i),t.length>e&&t.shift(),t)),[]),AU=AV(class extends yV{constructor(e,t){super(e),this.count=t}next(e){0==--this.count&&(this.next=super.next)}},"skip"),CU=AV(class extends yV{constructor(e,t){super(e),e.next=pV;let i=new yV(e);i.next=()=>{i.dispose(),e.resetNext()},i.complete=fV,i.subscribe(t)}},"skipUntil"),bU=AV(class extends yV{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),kU={leading:!0,trailing:!1},DU=class extends yV{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)}},NU=class extends yV{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:kU;super(e),this.durationSelector=t,this.config=i,this._throttle=new DU(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=pV,this._throttle.complete(),super.complete()}},wU=AV(NU,"throttle"),OU={leading:!1,trailing:!0},PU=e=>AV(NU,"audit")(e,OU),MU=class extends yV{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},LU=class extends yV{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new MU(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()}},xU=AV(LU,"debounce"),VU=e=>AV(LU,"debounceTime")((t=>QV(e))),UU=AV(class extends yV{constructor(e,t,i){super(e),this.count=t,this.defaultValue=i}next(e){0==this.count--&&(this.defaultValue=e,this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("not enough elements in sequence"))}},"elementAt"),FU=e=>t=>yU(1)(bU((t=>!e(t)))(t)),BU=AV(class extends yV{constructor(e,t){super(e),this.f=t,this.i=0}next(e){this.f(e)?(this.sink.next(this.i++),this.complete()):++this.i}},"findIndex"),HU=AV(class extends yV{constructor(e,t,i){super(e),this.f=t,this.defaultValue=i,this.index=0}next(e){(!this.f||this.f(e,this.index++))&&(this.defaultValue=e,this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"first"),WU=AV(class extends yV{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"),GU=AV(class extends yV{constructor(e,t){super(e),this.predicate=t,this.index=0}next(e){this.predicate(e,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){void 0!==this.result?(this.sink.next(this.result),super.complete()):this.error(new Error("no elements in sequence"))}},"every"),jU=AV(class extends yV{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"),JU=AV(class extends yV{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},"pairwise"),KU=class extends yV{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},qU=AV(KU,"map"),YU=e=>AV(KU,"mapTo")((t=>e)),zU=class extends yV{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()}},XU=class extends yV{constructor(e,t,i){super(e),this.makeSource=t,this.combineResults=i,this.index=0}subInner(e,t){let i=this.currentSink=new t(this.sink,e,this);this.complete=this.tryComplete,i.complete=i.tryComplete,i.subscribe(this.makeSource(e,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},QU=class extends zU{},ZU=class extends XU{next(e){this.subInner(e,QU),this.next=e=>{this.currentSink.dispose(),this.subInner(e,QU)}}},$U=AV(ZU,"switchMap");function eF(e){return(t,i)=>e((()=>t),i)}var tF=eF(AV(ZU,"switchMapTo")),iF=class extends zU{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},rF=class extends XU{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(),iF),this.disposed&&0===this.sources.length&&this.currentSink.resetComplete()}tryComplete(){0===this.sources.length&&this.currentSink.resetComplete(),this.dispose()}},nF=AV(rF,"concatMap"),oF=eF(AV(rF,"concatMapTo")),sF=class extends zU{tryComplete(){this.context.inners.delete(this),super.dispose(),0===this.context.inners.size&&this.context.resetComplete()}},aF=class extends XU{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,sF),this.inners.add(this.currentSink)}tryComplete(){1===this.inners.size?this.inners.forEach((e=>e.resetComplete())):this.dispose()}},cF=AV(aF,"mergeMap"),lF=eF(AV(aF,"mergeMapTo")),dF=class extends zU{dispose(){this.context.resetNext(),super.dispose()}},uF=class extends XU{next(e){this.next=pV,this.subInner(e,dF)}},hF=AV(uF,"exhaustMap"),pF=eF(AV(uF,"exhaustMapTo")),mF=AV(class extends yV{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=jV(),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"),_F=AV(class extends yV{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"),fF=AV(class extends yV{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"),gF=AV(class extends yV{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"),EF=AV(class extends yV{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),TF=()=>e=>new Promise(((t,i)=>{let r;new SV(e,(e=>r=e),i,(()=>t(r)))})),vF=()=>e=>{let t;return new ReadableStream({start(i){t=new SV(e,i.enqueue.bind(i),i.error.bind(i),i.close.bind(i))},cancel(){t.dispose()}})},yF=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:pV,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:pV,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:pV;return r=>new SV(r,e,t,i)},SF=AV(class extends yV{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"),IF=AV(class extends yV{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout((()=>this.error(new DV(this.timeout))),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),RF=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0;return t=>{if(t instanceof TV){let i=RV((r=>{let n=e,o=new yV(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,kV.pipe(i),i}return i=>{let r=e,n=new yV(i);n.error=e=>{r-- >0?t(n):i.error(e)},t(n)}}},AF=class e extends Dx{constructor(t,i,r){super({userId:i.userId,sdkAppId:t.sdkAppId,mediaType:r,room:t}),this.room=t,this.user=i,yb(this,"tinyId"),yb(this,"isRemote",!0),yb(this,"jitterBufferDelay",0),yb(this,"availableState"),yb(this,"remotePublishState"),yb(this,"_triggerCheckDecodeSubject",jV(eU(this,e.STATE_SUBSCRIBE))),this.tinyId=i.tinyId,this.availableState=new sL("".concat(i.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new sL("".concat(i.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),IV(OV(eU(this,sL.STATECHANGED),eU(this.remotePublishState,sL.STATECHANGED)),qU((()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing))),yF((e=>{this.availableState.state!==(e?sL.ON:sL.OFF)&&(this.availableState.state=e?sL.ON:sL.OFF),this.updatePlayingState(e)})));let n=IV(eU(this.player,pL.ERROR),TU((e=>e.code===MediaError.MEDIA_ERR_DECODE))),o=IV(QV(5e3),TU((()=>!(this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived)&&(!this.player.isPlaying&&!(this.kind===Sk.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1))))),s=IV(PV(n,o),SU(eU(this,sL.INIT)));IV(this._triggerCheckDecodeSubject,TU((()=>!this.ignoreDecodeError)),tF(s),yF((e=>{this.reportDecodeResult(!1,e)})))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)}))}get ignoreDecodeError(){var e,t;return((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===e.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===sL.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){let i=this.kind===Sk.AUDIO;iM[e?"addSuccessEvent":"addFailedEvent"]({key:i?504700:514702}),e||(iM.addEnum({key:i?504701:514703,value:bO()}),EL.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(RO()||kO()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===Sk.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," isAvailable: ").concat(this.isRemotePublished," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?sL.ON:sL.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};yb(AF,"STATE_SUBSCRIBE","subscribe"),vb([uV(5,1)],AF.prototype,"waitHasMediaTrack",1),vb([rL(sL.INIT,AF.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),OO.emit(MO.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),zx(521716,!1)],AF.prototype,"subscribe",1),vb([rL(AF.STATE_SUBSCRIBE,sL.INIT,{sync:!0,success(){this.log.info("unsubscribed"),OO.emit(MO.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],AF.prototype,"unsubscribe",1);var CF=AF,bF=class extends CF{constructor(e,t){super(e,t,1),yb(this,"volume",0),yb(this,"mediaType",1),yb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}get dbVolume(){return dx.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let t=e;for(let i of this.manager.decodePipeline)if(i&&(t=i({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}},kF=[-1,-1,1,-1,-1,1,1,1],DF=[0,0,1,0,0,1,1,1],NF=class extends sL{constructor(e,t){if(super(),this.context=e,yb(this,"name"),yb(this,"input"),yb(this,"output"),yb(this,"texture"),yb(this,"ctx2d",null),yb(this,"fbo"),yb(this,"width",0),yb(this,"height",0),yb(this,"x",0),yb(this,"y",0),yb(this,"program"),yb(this,"vertexShader"),yb(this,"fragmentShader"),yb(this,"totalFrames",0),yb(this,"dropFrames",0),yb(this,"matchInputSize",!0),yb(this,"texCoordBuffer"),yb(this,"positionBuffer"),yb(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),yb(this,"cost",0),yb(this,"_canvas",null),yb(this,"_image"),yb(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 jF)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==lO?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(DF),this.positionBuffer=this.createBuffer(kF),!1!==t.createTexture&&(this.texture=i.createTexture(),this.useTexture(),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.pixelStorei(i.PACK_ALIGNMENT,1),i.pixelStorei(i.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=i.createFramebuffer(),this.useBufferFrame(),this.useTexture(),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(i.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(i.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(JO){this.context.destroy(new Vb({code:Lb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(JO.message||JO)}))}}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 GF&&this.render(e)||this.context instanceof jF&&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 GF){let e=this.context.ctx;e.deleteBuffer(this.texCoordBuffer),e.deleteBuffer(this.positionBuffer),this.fbo&&e.deleteFramebuffer(this.fbo),this.texture&&e.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&e.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&e.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&e.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures(null==(e=this.input)?void 0:e.texture)}useTextures(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];i.forEach(((t,i)=>{t&&(e.activeTexture(e.TEXTURE0+i),e.bindTexture(e.TEXTURE_2D,t))}))}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),i}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let i=this.context.ctx;i.bindBuffer(i.ARRAY_BUFFER,e),i.bufferData(i.ARRAY_BUFFER,new Float32Array(t),i.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];i.forEach(((t,i)=>{e.enableVertexAttribArray(i),e.bindBuffer(e.ARRAY_BUFFER,t),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0)}))}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(this.width!==e||this.height!==t){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let i=this.context.ctx;i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let i=this.context.ctx;i.drawArrays(i.TRIANGLE_STRIP,0,4)}draw2d(e,t,i,r,n){return!(!this.ctx2d||!e)&&(e instanceof ImageData?this.ctx2d.putImageData(e,t,i):(this.ctx2d.drawImage(e,t,i,r,n),"undefined"!=typeof VideoFrame&&e instanceof VideoFrame&&e.close()),!0)}getInfo(){var e;let{totalFrames:t,x:i,y:r,width:n,height: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},_b({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,i=t.createTexture();return this.useTextures(i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};vb([rL(sL.INIT,"connected",{sync:!0})],NF.prototype,"connect",1),vb([rL("connected",sL.INIT,{ignoreError:!0,sync:!0})],NF.prototype,"disconnect",1),vb([rL([],"closed",{sync:!0})],NF.prototype,"close",1);var wF=IV(XV(250),qU((()=>performance.now())),wV()),OF=[0,1,1,1,0,0,1,0],PF=class extends NF{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),yb(this,"_intervalId",0),yb(this,"_sequence",0),yb(this,"checkGLError",!1),yb(this,"checkVisibilityChange"),e instanceof jF?this.ctx2d=e.ctx||null:e.available&&null!=t&&t.mirrorUpAndDown&&this.setTexBuffer(OF)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),hL.clearTask(this._intervalId),this._intervalId=hL.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(hL.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof GF){let e=this.context.ctx.getError();e&&this.context.destroy(new Vb({code:Lb.VIDEO_MANAGER_ERROR,extraCode:5,message:"".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)}))}}),{fps:this.context.frameRate})}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];super.addInput(e,...i),this.start(this.context.frameRate)}update(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(this._intervalId&&(hL.clearTask(this._intervalId),this._intervalId=0,1===e)){this.log.info("".concat(this.name," use requestVideoFrameCallback"));let e=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",e))};document.addEventListener("visibilitychange",e)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),hL.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),hL.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},MF=class extends PF{constructor(e,t){super(e,t),yb(this,"_videoTrack"),yb(this,"_muteOb"),yb(this,"_closedOb",eU(this,"closed")),yb(this,"_subscription"),yb(this,"_canvasContainer"),Number(oO)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=eU(this._videoTrack,"mute"),IV(eU(this._videoTrack,"ended"),SU(this._closedOb),yF((()=>{this.context.destroy(new Vb({code:Lb.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){var e;this._subscription=IV(this._muteOb,SU(this._closedOb),tF((e=5e3,t=>{let i=performance.now();IV(wF,bU((t=>t-i<e)),yU(1))(t)})),TU((()=>{var e;return!(null==(e=this._videoTrack)||!e.muted||document.hidden)})),yF((()=>{this.context.destroy(new Vb({code:Lb.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()}},LF=class extends MF{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},xF=class extends MF{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))}},VF=class extends NF{constructor(e,t){super(e,_b({name:"imageSource"},t)),yb(this,"_lastImage"),yb(this,"_totalFrames",0),yb(this,"_autoResize",!1),yb(this,"_canvasRendered"),yb(this,"_videoCallbackId",0),yb(this,"waitingFirstFrame",!0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===lO&&(this._canvasRendered=jV(),IV(this._canvasRendered,FV(this._image),$U((e=>e instanceof HTMLCanvasElement?eU(e,"rendered"):hU())),SU(eU(this,"closed")),yF((()=>{this.update()}))))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){let e=this.image;this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),zM()&&!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!1}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)}},UF=class extends VF{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",IV(eU(this._player,pL.PLAYER_STATE_CHANGED),SU(eU(this,"closed")),TU((e=>{let{state:t}=e;return"PLAYING"===t})),yF((()=>{this.tryVideoFrameCallback()})))}get image(){return this._player.element}},FF=class extends UF{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,t,i){super(e,new JL({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()}},BF=class extends sL{constructor(e){super(),yb(this,"frameRate"),yb(this,"_canvas"),yb(this,"log"),yb(this,"hasAlpha",!1),yb(this,"name"),yb(this,"error"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new FF(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new MF(this,e)}createVideoImageSource(e,t){return new VF(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new UF(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};yb(BF,"_ids",0);var HF={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},WF=class extends BF{constructor(){super(...arguments),yb(this,"defaultProgam"),yb(this,"defaultVShader"),yb(this,"defaultFShader"),yb(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(BF._ids++)),this.ctx=this._canvas.getContext("webgl2",HF),!this.ctx)throw new Vb({code:Lb.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,"\n// 顶点着色器\nattribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main() {\n gl_Position = a_position;\n v_texCoord = a_texCoord;\n}\n"),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,"\n// 片元着色器\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\n\nvoid main() {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n} "),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",(()=>{this.destroy(new Vb({code:Lb.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}))}destroy(e){let t="";return e&&(t=e.message,this.error=e,iM.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info("video context destroy".concat(t)?": ".concat(t):""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;null==(t=this.ctx)||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let i=this.ctx,r=i.createShader(e);return i.shaderSource(r,t),i.compileShader(r),r}createProgram(e,t){let i=this.ctx,r=i.createProgram();return i.attachShader(r,e),i.attachShader(r,t),i.linkProgram(r),i.getProgramParameter(r,i.LINK_STATUS)||this.log.error(i.getProgramInfoLog(r)),r}};yb(WF,"UNAVAILABLE","unavailable"),vb([rL(sL.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),iM.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),iM.addSuccessEvent({key:512700})}})],WF.prototype,"create",1),vb([rL("created",sL.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(WF.UNAVAILABLE,e),this.removeAllListeners()}})],WF.prototype,"destroy",1);var GF=WF,jF=class extends BF{constructor(){super(...arguments),yb(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(BF._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new Vb({code:Lb.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,iM.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(),iM.addSuccessEvent({key:512703})}};vb([rL(sL.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),iM.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),iM.addSuccessEvent({key:512701})}})],jF.prototype,"create",1),vb([rL("created",sL.INIT,{ignoreError:!0,sync:!0})],jF.prototype,"destroy",1);var JF=class extends CF{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),yb(this,"mediaType",4),yb(this,"source"),yb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager,this.once("first-video-frame",(e=>{this.room.emit("first-video-frame",e)}))}play(e,t){return(qD(null==t?void 0:t.canvasRender)?t.canvasRender:17===lO)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then((()=>{this.player.calculateStat()}))}useCanvasPlayer(){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let e=new jF({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new PF(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),zM()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,i=(r=t,[15,30,45,60].reduce(((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)));var r;!KD(t)||t<=0?this.log.debug("updateCanvasPlayerFPS() ignore decoder: ".concat(t," ")):i!==e.frameRate?(this.log.info("updateCanvasPlayerFPS() decoder: ".concat(t,", closest: ").concat(i,", current: ").concat(e.frameRate)),e.frameRate=i):this.log.debug("updateCanvasPlayerFPS() ignore ClosestFPS ".concat(i," == ").concat(e.frameRate))}get decodeFPS(){var e;let{msg_video_status:t}=(null==(e=this.room.heartbeatReport)?void 0:e.msg_down_stream_info.find((e=>e.msg_user_info.str_identifier===this.userId)))||{},i=2===this.mediaType?7:this.isSmall?3:2;if(!t||0===t.length)return 0;let r=t.find((e=>e.uint32_video_stream_type===i));return(null==r?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&!(e=t({frame:e,track:this})))return;return e}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},KF=class extends JF{constructor(e,t){super(e,t,2),yb(this,"mediaType",2),yb(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},qF=new Map;function YF(e,t){let i=fb(_b({},t),{timestamp:Fb()});qF.has(e)?qF.get(e).push(i):qF.set(e,[i])}function zF(e,t,i,r){try{if(zD(e))for(let n=0;n<e.length;n++)XF.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else XF.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}catch(JO){throw xO.error(JO),JO}}function XF(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;if(jD(i)){if(t.required)throw new Vb({code:Lb.INVALID_PARAMETER,message:JP({key:HP.INVALID_PARAMETER_REQUIRED,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(jD(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),GD(t.type[r])&&i instanceof t.type[r]&&(e=!0),JD(t.type[r])&&WD(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new Vb({code:Lb.INVALID_PARAMETER,message:JP({key:HP.INVALID_PARAMETER_TYPE,data:{key:r,rule:{type:t.type.map((e=>$D(e)?eN(e):JD(e)?e:WD(e)))},fnName:n,value:i},link:{className:o,fnName:n}})})}else if(!jD(t.type)&&WD(i)!==t.type)throw new Vb({code:Lb.INVALID_PARAMETER,message:JP({key:HP.INVALID_PARAMETER_TYPE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!1===t.allowEmpty){let e=KD(i)&&(0===i||Number.isNaN(i)),s=JD(i)&&""===i.trim();if(e||s)throw new Vb({code:Lb.INVALID_PARAMETER,message:JP({key:HP.INVALID_PARAMETER_EMPTY,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})})}if(t.notLessThanZero&&KD(i)&&i<0)throw new Vb({code:Lb.INVALID_PARAMETER,message:JP({key:HP.CANNOT_LESS_THAN_ZERO,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!jD(t.min)&&KD(i)&&i<t.min)throw new Vb({code:Lb.INVALID_PARAMETER,message:JP({key:HP.INVALID_PARAMETER_MIN,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!jD(t.max)&&KD(i)&&i>t.max)throw new Vb({code:Lb.INVALID_PARAMETER,message:JP({key:HP.INVALID_PARAMETER_MAX,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(JD(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new Vb({code:Lb.INVALID_PARAMETER,message:JP({key:HP.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})})}else if(GD(t.instanceOf)&&!(i instanceof t.instanceOf))throw new Vb({code:Lb.INVALID_PARAMETER,message:JP({key:HP.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 Vb({code:Lb.INVALID_PARAMETER,message:JP({key:HP.INVALID_PARAMETER_RANGE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});let{properties:s}=t;FD(s)&&YD(i)&&Object.keys(s).forEach((e=>{XF.call(this,{rule:s[e],value:i&&i[e],key:"".concat(r,".").concat(e),fnName:n,className:o})}));let{arrayItem:a}=t;FD(a)&&zD(i)&&i.forEach(((e,t)=>{XF.call(this,{rule:a,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),GD(t.validate)&&t.validate.call(this,i,r,n,o,this)}OO.on(MO.JOIN_SUCCESS,(e=>{let{room:t}=e;YF(t.userId,{eventId:32788})})),OO.on(MO.LEAVE_START,(e=>{let{room:t}=e;YF(t.userId,{eventId:32789})})),OO.on(MO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),YF(t.room.userId,{eventId:e})}})),OO.on(MO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),YF(t.room.userId,{eventId:e})}})),OO.on(MO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Sk.AUDIO?YF(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):YF(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),OO.on(MO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Sk.AUDIO?YF(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):YF(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),OO.on(MO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&YF(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&YF(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&YF(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),OO.on(MO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&YF(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&YF(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&YF(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),OO.on(MO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&YF(t.room.userId,{eventId:t.kind===Sk.VIDEO?32780:32781})})),OO.on(MO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&YF(t.room.userId,{eventId:t.kind===Sk.VIDEO?32782:32783})})),OO.on(MO.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&&YF(i.userId,{eventId:t})})),OO.on(MO.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&&YF(i.userId,{eventId:t,remoteUserId:o})})),OO.on(MO.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"===n?0:2,d={eventId:4004,param1:c,param2:l,streamType:a||2};r&&(d.remoteUserId=r,d.eventId=4005),YF(i,d),iM.addEnum({key:r?514701:513701,value:c}),iM.addEnum({key:r?514700:513700,value:l})})),OO.on(MO.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===Sk.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),YF(t.userId,e)}}));var QF=Tb(Rb(),1),ZF=class extends QF.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,yb(this,"userMap",new Map),yb(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find((e=>e.isRobot))}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:r,role:n}=e;if(this.userMap.has(t))return;let o={userId:i,tinyId:r,role:20===n?"anchor":"audience"};this.userMap.set(t,o),this.emit("1",o)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let r="peer leave [".concat(e,"]");jD(t)||(r+=":".concat(TD[t])),this._log.info(r);let n=this.remotePublishedUserMap.get(e);if(n){let t=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:t,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",i.userId)}setUserList(e){this.userMap.forEach((t=>{e.findIndex((e=>e[this.key]===t[this.key]))<0&&this.deleteUser(t[this.key],0)})),e.forEach((e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)}))}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach((t=>{let i=t[this.key];if(e.findIndex((e=>e[this.key]===t[this.key]))<0){this._log.info("remote [".concat(i,"] unpublish"));let e=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(i),this.emit("6",{prevMuteState:e,muteState:t.muteState,flag:0})}})),e.forEach((e=>{var t;let i=e[this.key];if(i===this.mySelfId)return;let{flag:r,userId:n,tinyId:o}=e,s=cN(r,n),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==r&&(e.flag=r,this._log.info("remote publish updated: ".concat(JSON.stringify(e.muteState))),this.emit("6",{prevMuteState:a,muteState:s,flag:r}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(s))),this.addUser({userId:n,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:cN(0,n),muteState:s,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function $F(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return Bx(((e,n)=>{let o=new WeakMap;return OO.on(MO.ROOM_DESTROY,(e=>{let{room:t}=e;return o.delete(t)})),function(){let s=o.get(this);for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(s||(s={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,s)),0===s.timestamp?s.timestamp=Date.now():Date.now()-s.timestamp>1e3&&(s.timestamp=Date.now(),s.callCountInSecond=0,s.totalSizeInSecond=0),r&&(s.totalSizeInSecond+=r(...c)),0!==s.timestamp&&Date.now()-s.timestamp<1e3&&(s.callCountInSecond>=t||s.totalSizeInSecond>i))throw new Vb({code:Lb.INVALID_OPERATION,message:JP({key:HP.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 eB,tB=!0,iB={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"},rB={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},nB=((eB=nB||{})[eB.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",eB[eB.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",eB[eB.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",eB[eB.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",eB[eB.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",eB[eB.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",eB[eB.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",eB[eB.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",eB[eB.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",eB[eB.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",eB[eB.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",eB[eB.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",eB[eB.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",eB[eB.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",eB[eB.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",eB[eB.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",eB[eB.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",eB[eB.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",eB[eB.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",eB[eB.INVALID_OPERATION=5100]="INVALID_OPERATION",eB[eB.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",eB[eB.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",eB[eB.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",eB[eB.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",eB[eB.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",eB[eB.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",eB[eB.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",eB[eB.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",eB[eB.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",eB[eB.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",eB[eB.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",eB[eB.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",eB[eB.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",eB[eB.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",eB[eB.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",eB[eB.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",eB[eB.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",eB[eB.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",eB[eB.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",eB[eB.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",eB[eB.DEVICE_ERROR=5300]="DEVICE_ERROR",eB[eB.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",eB[eB.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",eB[eB.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",eB[eB.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",eB[eB.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",eB[eB.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",eB[eB.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",eB[eB.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",eB[eB.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",eB[eB.SERVER_ERROR=5400]="SERVER_ERROR",eB[eB.NEED_TO_BUY=5401]="NEED_TO_BUY",eB[eB.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",eB[eB.OPERATION_FAILED=5500]="OPERATION_FAILED",eB[eB.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",eB[eB.REJOIN_FAILED=5502]="REJOIN_FAILED",eB[eB.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",eB[eB.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",eB[eB.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",eB[eB.OPERATION_ABORT=5998]="OPERATION_ABORT",eB[eB.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",eB);var oB=fb(_b({},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: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(WD(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(WD(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,value:r}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(r,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,value:r}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(r,".")},INVALID_ELEMENT_ID(e){let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE(e){let{key:t,fnName:i,type:r}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(r,".")},INVALID_STREAM_ID(e){let{key:t}=e;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(e){let{key:t}=e;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(e){let{key:t}=e;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(e){let{fnName:t}=e;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(e){let{fnName:t}=e;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing ").concat(i.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(e){let{fnName:t}=e;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the microphone is not turned on.")},INVALID_BUFFER_EMPTY:e=>{let{key:t}=e;return"the buffer size of paramerter '".concat(t,"' cannot be empty")},INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:e=>{let{fnName:t}=e;return"you need to call ".concat(t,"() after publish stream.")},ENV_NOT_SUPPORTED(e){let{fnName:t}=e;return"the current browser does not support the capability of the function '".concat(t,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(e){let{fnName:t}=e;return"cannot call ".concat(t," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got device exception").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:i=sB(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=sB(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=sB(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=sB(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=sB(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=sB(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=sB(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 sB(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var aB=class e extends Error{constructor(e){let{code:t,extraCode:i,message:r="",messageParams:n,fnName:o="",originError:s}=e;var a;let c;c=r||function(e){let t,{code:i,params:r,enableDocLink:n=!1}=e,s="",a=nB[i];try{t=oB[a]}catch(o){t=oB.UNKNOWN_ERROR}return GD(t)?s=t(r):JD(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===rB.SERVER_ERROR?t:i||t,params:_b({fnName:o,error:s},n)}),super(c),yb(this,"name","RtcError"),yb(this,"code"),yb(this,"extraCode"),yb(this,"functionName"),yb(this,"message"),yb(this,"handler"),yb(this,"originError"),this.name=nB[t],this.code=t,this.extraCode=i,this.functionName=o,this.originError=s,this.message=c,5302===this.extraCode&&null!=(a=this.originError)&&a.message.includes("system")&&(this.handler=()=>{let e=document.createElement("a");Nw?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):ww&&(e.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),e.href.length>0&&e.click()})}static convertFrom(t,i,r){let n=t;if(t instanceof Vb){let{stack:o}=t,s={code:rB.UNKNOWN_ERROR,fnName:i,originError:t};switch(t.getCode()){case Lb.INVALID_PARAMETER:s.code=rB.INVALID_PARAMETER,s.message=t.message;break;case Lb.INVALID_OPERATION:s.code=rB.INVALID_OPERATION;break;case Lb.NOT_SUPPORTED:case Lb.NOT_SUPPORTED_H264:s.code=rB.ENV_NOT_SUPPORTED,t.getCode()===Lb.NOT_SUPPORTED_H264&&(s.extraCode=t.message.includes(WP.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Lb.JOIN_ROOM_FAILED:s.messageParams={fnParams:r};case Lb.SERVER_TIMEOUT:case Lb.SWITCH_ROLE_FAILED:s.code=rB.SERVER_ERROR,s.extraCode=t.getExtraCode();break;case Lb.API_CALL_ABORTED:s.code=rB.OPERATION_ABORT;break;case Lb.DEVICE_NOT_FOUND:case Lb.DEVICE_AUTO_RECOVER_FAILED:case Lb.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 Lb.UNKNOWN:break;default:s.code=rB.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:rB.UNKNOWN_ERROR,fnName:i,originError:t})}return n}};var cB=aB;function lB(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function dB(e){return e===iB.QOS_PREFERENCE_CLEAR?"detail":e===iB.QOS_PREFERENCE_SMOOTH?"motion":""}function uB(e,t){let i=t?vk:Tk;return LN(e)?_b(_b({},i),e):Ek[e]?Ek[e]:i}var hB={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}}},pB={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}}},mB={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(JD(e)&&!document.getElementById(e))throw new cB({code:rB.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},_B={name:"userId",required:!0,type:"string"},fB={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[iB.AUDIO_PROFILE_STANDARD,iB.AUDIO_PROFILE_STANDARD_STEREO,iB.AUDIO_PROFILE_HIGH,iB.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function gB(e,t){if(!e)throw new cB({code:rB.INVALID_OPERATION,extraCode:5101,fnName:t})}function EB(e,t,i){if(!e)throw new cB({code:rB.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}function TB(e){var t;if(null==(t=null==e?void 0:e.option)||!t.small)return;if(!RM())return xO.warn("small stream is not supported"),void delete e.option.small;let i=uB(e.option.profile),r=uB(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:(xO.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 vB={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 cB({code:rB.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(JD(e.roomId))throw new cB({code:rB.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new cB({code:rB.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new cB({code:rB.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new cB({code:rB.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}})}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},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:mB,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:hB},validate(e){var t,i;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&dM())throw new cB({code:rB.ENV_NOT_SUPPORTED,extraCode:5201});null!=(i=null==e?void 0:e.option)&&i.small&&TB(e)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:fb(_b({},mB),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:hB},validate(e){var t;null!=(t=null==e?void 0:e.option)&&t.small&&TB(e)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:fB},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&dM())throw new cB({code:rB.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:fB}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:mB,publish:{type:"boolean"},option:pB},validate(e,t,i,r,n){var o;if(null==(o=null==e?void 0:e.option)||!o.videoTrack){if(dM())throw new cB({code:rB.ENV_NOT_SUPPORTED,extraCode:5201});if(!fM())throw new cB({code:rB.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:mB,publish:{type:"boolean"},option:pB}},muteRemoteAudio:[_B,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[_B,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:mB,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){gB(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(EB(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new cB({code:rB.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:fb(_b({},mB),{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){gB(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(EB(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new cB({code:rB.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(e,t,i){if("*"!==e.userId&&jD(e.streamType))throw new cB({code:rB.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){gB(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(!BM)throw new cB({code:rB.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new cB({code:rB.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new cB({code:rB.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new cB({code:rB.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});gB(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 cB({code:rB.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 cB({code:rB.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new cB({code:rB.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(gB(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new cB({code:rB.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}}},yB={TRTC:vB},SB=class extends Error{};function IB(e,t){let i=hN(e);for(let r=0;r<t.length;r++)uN(i[r],t[r]);return i}function RB(e){this._resolve=Promise.resolve(e)}function AB(e){this._reject=Promise.reject(e)}var CB=class e{constructor(t,i){this.instance=t,this.group=i,yb(this,"started",!1),yb(this,"ops",[]),yb(this,"startSame",(()=>!0)),yb(this,"mergeUpdate",IB);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 SB("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:RB,reject:AB};try{switch(this.state){case 1:if(0===e)throw new SB("already started");break;case 4:if(2===e)throw new SB("not started");break;default:return this.cacheOp(o)}}catch(KO){return Promise.reject(KO)}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 SB("already start");break;case 3:switch(e.type){case 2:throw new SB("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new SB("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new SB("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 SB("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new SB("start not allowed after update");case 0:throw new SB("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new SB("keep start")),new SB("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}};yb(CB,"instances",new WeakMap);var bB=CB,kB=new WeakMap,DB=(e,t)=>{if(t instanceof SB){let{stack:i}=t;t=new cB({code:rB.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function NB(e,t){return Bx(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let a=bB.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(DB.bind(null,r))):i.apply(this,o)}))}function wB(e,t){let{merge:i,debounce:r}=t||{};return Bx(((t,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=bB.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=kB.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(DB.bind(null,n)).then(r,o)}),e);kB.has(this)?null==(l=kB.get(this))||l.set(i(...s),{timeoutId:u,resolve:r}):kB.set(this,new Map([[i(...s),{timeoutId:u,resolve:r}]]))}))}return c.action(2,t.bind(this),s).catch(DB.bind(null,n))}))}function OB(e){return Bx(((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(bB.gets(this,s).map((e=>e.action(3,(()=>Promise.resolve()),n)))).then((()=>t.call(this,...n)));let a=bB.get(this,s);return a?a.action(3,t.bind(this),n).catch(DB.bind(null,i)):t.apply(this,n)}))}var PB={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"},MB=new Set([PB.ERROR,PB.AUTOPLAY_FAILED,PB.KICKED_OUT,PB.REMOTE_USER_ENTER,PB.REMOTE_USER_EXIT,PB.REMOTE_AUDIO_AVAILABLE,PB.REMOTE_AUDIO_UNAVAILABLE,PB.REMOTE_VIDEO_AVAILABLE,PB.REMOTE_VIDEO_UNAVAILABLE,PB.CONNECTION_STATE_CHANGED,PB.PUBLISH_STATE_CHANGED,PB.SCREEN_SHARE_STOPPED,PB.DEVICE_CHANGED,PB.FIRST_VIDEO_FRAME]),LB={};Eb(LB,{bytes2ms:()=>PD,calculateScaleResolutionDownNumber:()=>bN,convertObjectNumberToInt:()=>SN,copyProperties:()=>OD,deepClone:()=>hN,deepMerge:()=>uN,delay:()=>IN,fibonacci:()=>BD,formatedTime:()=>_N,getConstructorName:()=>eN,getContainerFromElement:()=>mN,getEnv:()=>RD,getInternalVersion:()=>oN,getLoggerUrl:()=>CD,getMediaStreamTrackInfo:()=>CN,getMuteStateFromFlag:()=>cN,getNetworkType:()=>kD,getNumNetworkType:()=>wD,getReconnectionTimeout:()=>HD,getStringByteLength:()=>EN,getTurnServer:()=>lN,getUint32Version:()=>yN,getValueType:()=>WD,getViewListFromView:()=>pN,glog:()=>VD,ipv4ToUint32:()=>dN,isArray:()=>zD,isAudioWorkletSupported:()=>tN,isBoolean:()=>qD,isConstructor:()=>$D,isEmpty:()=>aN,isFunction:()=>GD,isLangChinese:()=>UD,isMediaStreamTrack:()=>XD,isNumber:()=>KD,isObject:()=>YD,isOverseaSdkAppId:()=>AD,isPlainObject:()=>FD,isPortrait:()=>TN,isPromise:()=>ZD,isRemoteTrack:()=>QD,isString:()=>JD,isUndefined:()=>jD,loadImage:()=>vN,ms2bytes:()=>LD,ms2samples:()=>xD,normalizeUrl:()=>AN,performanceNow:()=>rN,promiseAny:()=>iN,samples2ms:()=>MD,setNetworkType:()=>ND,stringify:()=>fN,stringifyIncludeValue:()=>gN,throttlePromise:()=>RN});var xB={};Eb(xB,{ScheduleRequestType:()=>GB,getAbilityConfig:()=>JB,getScheduleDomain:()=>KB,isNeedToSchedule:()=>UB,scheduleProxy:()=>HB,sendScheduleRequest:()=>BB,setIsNeedToSchedule:()=>FB,setScheduleProxy:()=>WB});var VB=null,UB=!0;function FB(e){qD(e)&&e!==UB&&(UB=e,xO.info("setIsNeedToSchedule ".concat(e)))}function BB(e){return Ib(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:n,userSig:o,version:s,frameWorkType:a,role:c,latencyLevel:l}=e;return function*(){if(!UB&&VB)return{isCached:!0,result:VB};let e={delta:0,count:[1,1],msg:[],detail:[]};try{let d=new FormData;d.append("userId",String(t)),d.append("sdkAppId",String(i)),d.append("isStrGroupId",String(r)),d.append("groupId",String(n)),d.append("sdkVersion",s),d.append("userSig",String(o)),c&&d.append("role",String(c)),l&&d.append("latencyLevel",String(l)),a&&d.append("frameWorkType",String(a));let u=rN(),h=yield function(e,t,i){return new Promise(((r,n)=>{let o=null;iN([YB((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]=jB(i,"config",Sk.MAIN,!0)),n())}))(jB(i,"config",Sk.MAIN),e,{get timeout(){return 1e3*BD(2+t.count[0])}}),YB((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]=jB(i,"config",Sk.BACKUP,!0)),n())}))(jB(i,"config",Sk.BACKUP),e,{get timeout(){return 1e3*BD(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}(d,e,i);h.config&&(h.config.loggerDomain&&$b(h.config.loggerDomain),qD(h.config.scheduleCache)&&FB(!h.config.scheduleCache)),e.delta=rN()-u;let p=function(e,t,i){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let n=performance.getEntriesByType("resource"),o=jB(e,"config",Sk.MAIN),s=jB(e,"config",Sk.BACKUP);for(let e of n)if(e.startTime>=i&&(e.name===o||e.name===s)&&e.transferSize>0){let i=e.name===o?Sk.MAIN:Sk.BACKUP,n=Math.round(e.duration),s=Math.round(e.domainLookupStart-e.startTime),a=e.redirectStart>0?Math.round(e.redirectEnd-e.redirectStart):0,c=e.fetchStart>0?Math.round(e.domainLookupStart-e.fetchStart):0,l=Math.round(e.domainLookupEnd-e.domainLookupStart),d=Math.round(e.requestStart-e.secureConnectionStart),u=Math.round(e.secureConnectionStart-e.connectStart),h=Math.round(e.responseStart-e.requestStart),p=Math.round(e.responseEnd-e.responseStart),m=[l,d,u,h,p];EL.uploadEvent({log:"stat-schedule-net:".concat(n,"(").concat(s,"(").concat(a,"->").concat(c,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=fb(_b({},r),{totalCost:n,local:s,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(o){xO.error("getScheduleDetailCost error",o)}return r}(Number(i),t,u);return VB=h,{isCached:!1,result:h,detailCost:p}}catch(d){let e=zD(d)?d[0]:d,t=KD(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),r=new Vb({code:Lb.SCHEDULE_FAILED,extraCode:t,message:JP({key:HP.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw xO.error(i,t),r}}()}))}"undefined"!=typeof document&&document.head.insertAdjacentHTML("beforeend",Object.values(uD).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),OO.on("28",(()=>FB(!0))),OO.on("63",(()=>FB(!0))),OO.on("84",(()=>FB(!0))),OO.on("201",(e=>{"RECONNECTING"===e.state&&FB(!0)})),OO.on("202",(e=>{"RECONNECTING"===e.state&&FB(!0)}));var HB={main:"",backup:""};function WB(e){zD(e)?(HB.main=e[0],HB.backup=e[1]):HB.main=e}var GB=(e=>(e.CONFIG="config",e.TRTC_AUTO_CONF="trtcAutoConf",e.AUDIO_AI_AUTH="audioAiAuth",e))(GB||{});function jB(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Sk.MAIN,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return"https://".concat(HB[i]||KB(e,i,r),"/api/v1/").concat(t)}function JB(e,t,i){let r=jB(e,t),n=jB(e,t,Sk.BACKUP),o=new URLSearchParams(i).toString();return iN([fetch("".concat(r,"?").concat(o)).then((e=>e.json())),fetch("".concat(n,"?").concat(o)).then((e=>e.json()))])}function KB(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Sk.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=AD(e)?r?i===Sk.MAIN?uD.MAIN_OVERSEA_BACKUP:uD.BACKUP_OVERSEA:i===Sk.MAIN?uD.MAIN_OVERSEA:uD.BACKUP_OVERSEA:i===Sk.MAIN?uD.MAIN:uD.BACKUP,t}function qB(e,t,i){return new Promise(((r,n)=>{kN({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 YB=(e,t)=>xN({retryFunction:qB,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var zB=class{constructor(){yb(this,"_log"),this._log=xO.createLogger({id:"fd"})}download(e,t){return Ib(this,null,(function*(){let{type:i="blob"}=t||{};e=AN(e);try{let t,r=rN();if(t=GD(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let n=rN()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(n,"ms")),iM.addSuccessEvent({key:522700,cost:rN()-r}),t.data}catch(JO){throw this._log.error("failed to download: ".concat(e,", error: ").concat(JO)),iM.addFailedEvent({key:522700,error:JO}),JO}}))}downloadWithFetch(e,t){return Ib(this,null,(function*(){this._log.info("download with fetch: ".concat(e,", return type: ").concat(t));try{let i,r=yield fetch(e);if(!r.ok)throw new Error("network response was not ok");return i="arraybuffer"===t?yield r.arrayBuffer():yield r.blob(),{data:i}}catch(Xk){throw Xk}}))}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType=t,n.onload=()=>{200===n.status||0===n.status&&n.response?i({data:n.response}):r(new Error("XHR failed"))},n.onerror=r,n.send(null)}))}loadWasm(e,t){return Ib(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=rN(),r=null,n=null;if(GD(WebAssembly.instantiateStreaming)&&!e.startsWith("data:application/octet-stream;base64,")&&!(e=>e.startsWith("file://"))(e)&&GD(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(Yb){n=Yb}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(Yb){n=Yb}if(r){let t=rN()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),iM.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),iM.addFailedEvent({key:522701,error:n}),n}))}loadScript(e){this._log.info("loadScript ".concat(e));let t=rN();return new Promise(((i,r)=>{let n=document.createElement("script");n.type="text/javascript",n.onload=()=>{this._log.info("loadedScript ".concat(e,", cost: ").concat(rN()-t,"ms")),iM.addSuccessEvent({key:522702,cost:rN()-t,split:1e3}),i(n)},n.onerror=t=>{this._log.error("failed to loadScript ".concat(e,", error: ").concat(t)),iM.addFailedEvent({key:522702}),r(t)},n.crossOrigin="anonymous",n.src=e,document.head.append?document.head.append(n):document.getElementsByTagName("head")[0].appendChild(n)}))}};vb([vL({settings:{timeout:0,retries:3},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],zB.prototype,"download",1),vb([vL({settings:{timeout:3e3,retries:3},onRetrying(e){this._log.warn("loadScript retrying: ".concat(e))}})],zB.prototype,"loadScript",1);var XB=new zB;function QB(e){let{TRTC:t,room:i,errorModule:r,assetsPath:n}=e;return{TRTC:t,room:i,assetsPath:n,fileDownloader:XB,innerEmitter:OO,constants:Gb,environment:UN,utils:LB,eventLogger:EL,log:this.room.getLogger(),loggerManager:xO,errorModule:r,kvStatManager:iM,rtcDectection:FO,trtc:this,rx:hV,enums:BO,schedule:xB,clearStarted:(e,t)=>{let i=e.getAlias(),r=bB.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:lV,createAudioNode:sx}}var ZB=new WeakMap;function $B(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Bx(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{tH.call(this,t,n,i,this._name)}catch(JO){return Promise.reject(JO)}return e.apply(this,n)}))}function eH(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Bx(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{tH.call(this,t,n,i,this._name)}catch(JO){throw JO}return e.apply(this,n)}))}function tH(e,t,i,r){if(zD(e))for(let n=0;n<e.length;n++)iH.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else iH.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function iH(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function s(e){return{code:rB.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(jD(i)){if(t.required)throw new cB(s(5001));if(jD(t.defaultValue))return void(GD(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),GD(t.type[r])&&i instanceof t.type[r]&&(e=!0),JD(t.type[r])&&WD(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new cB({code:rB.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>$D(e)?eN(e):JD(e)?e:WD(e)))},value:i}})}else if(!jD(t.type)&&WD(i)!==t.type)throw new cB(s(5002));if(!1===t.allowEmpty){let e=KD(i)&&(0===i||Number.isNaN(i)),t=JD(i)&&""===i.trim();if(e||t)throw new cB(s(5003))}if(t.notLessThanZero&&KD(i)&&i<0)throw new cB(s(5006));if(!jD(t.min)&&KD(i)&&i<t.min)throw new cB(s(5007));if(!jD(t.max)&&KD(i)&&i>t.max)throw new cB(s(5008));if(JD(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new cB(s(5004))}else if(GD(t.instanceOf)&&!(i instanceof t.instanceOf))throw new cB(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new cB(s(5005));let{properties:a}=t;FD(a)&&YD(i)&&Object.keys(a).forEach((e=>{iH.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;FD(c)&&zD(i)&&i.forEach(((e,t)=>{iH.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),GD(t.validate)&&t.validate.call(this,i,r,n,o,this)}function rH(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r,ignoreLog:n}=e;return Bx(((e,o)=>function(){for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];var l,d,u;function h(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...a);if(a[e.argIndex]===t)return e.value}if(t===a||e in a)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(WD(t)):t instanceof MediaStreamTrack?CN(t):(JSON.stringify(t),t)}catch(n){return"type:".concat(WD(t))}}let p=this._log||xO;if(null!=n&&n(...a))return e.apply(this,a);a.length>0?p.info("".concat(o,"() ").concat(JSON.stringify(a,((e,t)=>h(e,t,["userSig","privateMapKey"]))))):p.info("".concat(o,"()"));let m=r?r(...a):XP[o];try{let i=e.apply(this,a),r=rN();if(ZD(i)){let e="".concat(o.includes("Plugin")?"".concat((null==(d=(l=a[0]).getName)?void 0:d.call(l))||""," "):" ");return i.then((i=>(p.info("".concat(o,"() success ").concat(e).concat(t.call(this,...a))),iM.addSuccessEvent({key:m,cost:rN()-r}),i))).catch((i=>{var r;let n=(i=cB.convertFrom.call(this,i,o,1===a.length?a[0]:a)).extraCode||i.code,s=null!=(r=i.message)&&r.includes(n)?"":" code:".concat(n);throw p.error("".concat(o,"() failed ").concat(e).concat(t.call(this,...a)," ").concat(i).concat(s," params: ").concat(JSON.stringify(a,h))),iM.addFailedEvent({key:m,error:i}),i}))}return iM.addSuccessEvent({key:m}),i}catch(_){let e=(_=cB.convertFrom.call(this,_,o)).extraCode||_.code,t=null!=(u=_.message)&&u.includes(e)?"":" code:".concat(e);throw p.error("".concat(o,"() failed ").concat(_).concat(t," params: ").concat(JSON.stringify(a,h))),iM.addFailedEvent({key:m,error:_}),_}}))}var nH=e=>Bx(((t,i)=>function(r,n){return Ib(this,null,(function*(){let o=this._plugins.get(r);if(!o)throw this._log.error("plugin ".concat(String(r)," is not found")),new cB({code:rB.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(GD(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new cB({code:rB.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return tH.call(this,o.getValidateRule(e),[n],i,"TRTC"),t.call(this,o,n)}))})),oH=0,sH=class{constructor(e,t){yb(this,"player"),yb(this,"publisher"),yb(this,"mixInput"),this.mixInput=new rx(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&&(jD(e.volume)||(this.volume=e.volume),jD(e.loop)||(this.loop=e.loop),jD(e.playbackRate)||(this.playbackRate=e.playbackRate))}updateListener(e){if(this.player){if(e.onDurationChange){let{onDurationChange:t}=e;this.player.ondurationchange=e=>{t(e.target.duration)}}if(e.onTimeUpdate){let t=e.onTimeUpdate,{player:i}=this;i.ontimeupdate=()=>{t(i.currentTime,i.duration)}}e.onEnded&&(this.player.onended=e.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(e){this.player&&(e<0&&e>this.player.duration||(this.player.currentTime=e,this.publisher.currentTime=e))}play(){var e,t;return null==(e=this.publisher)||e.play(),null==(t=this.player)?void 0:t.play()}pause(){var e,t;null==(e=this.player)||e.pause(),null==(t=this.publisher)||t.pause()}stop(){var e;null==(e=this.player)||e.pause(),this.mixInput.disconnect()}setOperation(e){"pause"===e&&this.pause(),"resume"===e&&(this.pause(),this.play()),"stop"===e&&(this.pause(),this.seek(0))}set volume(e){!this.player||!this.publisher||(this.player.volume=e,this.publisher.volume=e)}set loop(e){!this.player||!this.publisher||(this.player.loop=e,this.publisher.loop=e)}set playbackRate(e){!this.player||!this.publisher||(this.player.playbackRate=e,this.publisher.playbackRate=e)}};function aH(e,t){if(t&&"function"!=typeof t)throw new cB({code:rB.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var cH=class e{constructor(e){this.core=e,yb(this,"log"),yb(this,"mixedMusicMap",new Map),yb(this,"cacheMusicMap",new Map),oH+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(oH)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat(oH))}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 Ib(this,null,(function*(){let{room:t}=this.core;this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:i,url:r}=e;if(this.mixedMusicMap.has(i))return;let n=this.cacheMusicMap.get(i);n?e.url?n.reset():(n.mixInput.replaceSource(e.track),n.mixInput.connect()):(n=new sH(e,t.audioManager),this.cacheMusicMap.set(i,n)),n.updateListener(e),n.updateSettings(e),yield n.play(),this.mixedMusicMap.set(i,n),this.log.info("start mix audio track ".concat(i," success.")),iM.addEnum({key:502700,value:3}),this.kvUpload(e)}))}update(e){return Ib(this,null,(function*(){let{id:t,operation:i,seekFrom:r,playbackRate:n}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let o=this.mixedMusicMap.get(t);o?(o.updateSettings(e),o.updateListener(e),jD(i)||o.setOperation(i),jD(r)||o.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return Ib(this,arguments,(function(e){var t=this;let{id:i}=e;return function*(){var e;t.mixedMusicMap.has(i)&&(t.log.info("remove music source, music id: ".concat(i)),null==(e=t.mixedMusicMap.get(i))||e.stop(),t.mixedMusicMap.delete(i)),"*"===i&&t.destroyAllMusic()}()}))}kvUpload(e){let{track:t,loop:i,volume:r,playbackRate:n,operation:o,seekFrom:s,onTimeUpdate:a,onDurationChange:c,onEnded:l}=e;t&&iM.addCount({key:502711}),i&&iM.addCount({key:502703}),r&&iM.addCount({key:502704}),n&&iM.addCount({key:502705}),o&&iM.addCount({key:502706}),s&&iM.addCount({key:502707}),"function"!=typeof a&&iM.addCount({key:502709}),"function"!=typeof l&&iM.addCount({key:502710}),"function"!=typeof c&&iM.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>this.stop({id:t})))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};yb(cH,"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 cB({code:rB.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new cB({code:rB.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});aH("onTimeUpdate",e.onTimeUpdate),aH("onEnded",e.onEnded),aH("onDurationChange",e.onDurationChange)}}),yb(cH,"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){aH("onTimeUpdate",e.onTimeUpdate),aH("onEnded",e.onEnded),aH("onDurationChange",e.onDurationChange)}}),yb(cH,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),yb(cH,"Name","AudioMixer");var lH,dH=cH,uH=0,hH=class e{constructor(e){this.core=e,yb(this,"log"),yb(this,"audioContext",$L()),yb(this,"workletNode"),uH+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(uH)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(uH)),e.assetsPath&&this.preload("".concat(e.assetsPath,"/denoiser-wasm.js")).catch((e=>{}))}static startValidateRule(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(t,i,r,n){if(!e.room.audioManager.hasAudioTrack)throw new cB({code:rB.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return lH||(lH=this.doPreload(e)),lH}doPreload(e){return Ib(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield KL(this.audioContext,i)}catch(JO){throw this.log.error("load worklet failed",JO),JO}finally{URL.revokeObjectURL(i)}}))}getName(){return e.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(t){switch(t){case"start":return e.startValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return Ib(this,null,(function*(){let{room:t,schedule:i}=this.core;if(yield this.preload("".concat(e.assetsPath,"/denoiser-wasm.js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:n,status:o,message:s}=yield function(e,t){return Ib(this,arguments,(function(e,t){let{sdkAppId:i,userId:r,userSig:n,timestamp:s}=t;return function*(){try{let{data:{errCode:t,errMsg:o,sign:a,status:c}}=yield e.getAbilityConfig(i,e.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:r,userSig:n,timestamp:s});if("1"===c)return{auth:!0,sign:a,status:c,message:o};let l="Init RTCAIDenoiser failed.",d="";switch(t){case 1:d="Please check your params.";break;case 2:d="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:d="Server is invalid. Please contact our engineer. ";break;case 4:d="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:d="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:d="Your version is not supported."}return{auth:!1,status:c,message:o?"".concat(l," Reason: ").concat(o,". ").concat(d):"".concat(l,", ").concat(d)}}catch(o){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(o)}}}()}))}(i,fb(_b({},e),{timestamp:t}));if(!r)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(r,". Message: ").concat(s)),new cB({code:rB.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(Hb(new Date(null==i?void 0:i.maxCostTimestamp)),") hist: ").concat(null==(t=null==i?void 0:i.hist)?void 0:t.join(" ")))}else"log"===i.type&&this.log[i.logLevel]("".concat(i.value))}}this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})}))}update(){return Ib(this,null,(function*(){}))}stop(){return Ib(this,null,(function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)}))}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};yb(hH,"updateValidateRule",{type:"object"}),yb(hH,"stopValidateRule",{type:"object"}),yb(hH,"Name","AIDenoiser");var pH=hH;var mH=Tb(Rb(),1),_H=class extends mH.EventEmitter{constructor(){super(),yb(this,"observer"),yb(this,"state","nominal"),this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return Ib(this,null,(function*(){if(!this.observer)try{"PressureObserver"in window&&!XN&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(qb){EL.uploadEvent({log:"stat-pressure-detector-start-failed",error:qb})}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&xO.info("".concat(i.source,": ").concat(i.state)),this.emit("state-changed",{type:i.source,state:this.state})}destroy(){var e;try{null==(e=this.observer)||e.disconnect(),this.observer=null}catch(Xk){EL.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:Xk})}}},fH=new _H;function gH(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 eV(new DataView(new Uint8Array(s).buffer),!0)}function EH(e){return"empty"===e.type||0===e.data.byteLength}function TH(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}function vH(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 yH(e){let{frame:t,seiMessageList:i}=e;if(!i||0===i.length||0===t.data.byteLength)return t;let r=9-vH(t.data);if(r<=0)return t;let n=i.splice(0,r).reverse().map(gH),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 SH(e){let{frame:t,onSEI:i}=e;try{let e=new DataView(t.data);if(EH(t)||!TH(e))return t;let r=[],n=0,o=-1,s=-1;for(let i=0;i<t.data.byteLength;i++){let a=e.getUint8(i);if(0===a)n++;else if(1===a){if(2===n||3===n){let a=i-n;if(-1===o?o=a:-1===s&&(s=a,r.push(new eV(new DataView(e.buffer.slice(o,s)))),o=a,s=-1),6!==e.getUint8(i+1)){t.data=e.buffer.slice(a);break}}n=0}else n=0}null==i||i(r.reverse())}catch(qb){}return t}var IH=0,RH=class e{constructor(e){this.core=e,yb(this,"log"),yb(this,"_seiMessageList",[]),yb(this,"_smallSeiMessageList",[]),yb(this,"_subStreamSeiMessageList",[]),IH++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(IH)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(IH)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:t,mediaType:i}=e;try{return yH({frame:t,seiMessageList:8===i?this._smallSeiMessageList:2===i?this._subStreamSeiMessageList:this._seiMessageList})}catch(Xk){this.log.warn(Xk)}return t}decode(e){let{frame:t,track:i}=e;return SH({frame:t,onSEI:e=>{e.forEach((e=>{this.core.trtc.emit(PB.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:i.userId,streamType:2===i.mediaType?"sub":"main"})}))}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:UM?this.encode:yH,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:UM?this.decode:SH,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"}};yb(RH,"autoStart",!0),yb(RH,"Name","SEI");var AH=RH;function CH(e){let{frame:t,onDump:i}=e;return null==i||i(),t}function bH(e){let{frame:t,onDump:i}=e;return null==i||i(),t}var kH={"play() error: NotAllowedError:":{tips:e=>e.includes("main <video>")||e.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:e=>e.includes("↓")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:e=>e.includes("↓")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:"The remote stream audio playback is paused, which usually has two possibilities:\n 1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.\n 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.",color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:"The remote stream video playback is paused, which usually has two possibilities:\n 1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.\n 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.",color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach((e=>{kH["".concat(e,"()")]={tips:"Call trtc.".concat(e),color:"blue",class:"blue",textColor:"#fff"}}));var DH,NH=0,wH=class e{constructor(e){this.core=e,yb(this,"_core"),yb(this,"log"),yb(this,"dumpLocalVideoMap",{}),yb(this,"dumpRemoteVideoMap",{}),yb(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++NH)}),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 Ib(this,null,(function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&"true"!==(null==(e=window.sessionStorage)?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))||(yield this.openDebugDiaLog(),this.addVideoProcessor())}))}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return Ib(this,null,(function*(){var e;try{if(DH)yield DH;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(Jb,"/assets/debug-dialog.js");DH=this._core.fileDownloader.loadScript(t),yield DH}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(qb){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(qb))}}))}closeDebugDiaLog(){var e;null==(e=this.dialog)||e.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):CH,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):bH,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo(e){let{frame:t,mediaType:i}=e;return CH({frame:t,onDump:()=>{if(!i)return;let e=2===i?"sub":"main",r=this.dumpLocalVideoMap[e];r&&(r.data.push(t.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>1e3*r.duration&&r.onDumpEnd())}})}decodeVideo(e){let{frame:t,track:i}=e;return bH({frame:t,onDump:()=>{if(!i)return;let e=this.dumpRemoteVideoMap["".concat(i.userId,"-").concat(i.streamType)];e&&(e.data.push(t.data.slice(0)),e.duration>0&&Date.now()-e.startTimestamp>1e3*e.duration&&e.onDumpEnd())}})}};yb(wH,"Name","Debug"),yb(wH,"autoStart",!0);var OH=wH,PH=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},MH=class{constructor(e,t,i){yb(this,"trackDoneOB"),yb(this,"startOB"),yb(this,"stopOB"),yb(this,"inputFrameCount",0),yb(this,"decodedFrameCount",0),yb(this,"type","auto"),yb(this,"config"),yb(this,"decoder"),yb(this,"_decodeSink");let{kvStatManager:r,trtc:n}=e;this.config=i.config,this.trackDoneOB=eU(t,sL.INIT),this.stopOB=jV(),this.startOB=jV(),"auto"===i.type?this.type="webCodecs":this.type=i.type;let o=jV();IV(this.startOB,FV(0),$U((e=>{let i=this.pipe(t);return o.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),IV(i,SU(this.stopOB),yF((()=>{}),(i=>{t.log.error(i),r.addFailedEvent({key:PH(this.type),error:i}),e>4?this.startOB.error(i):this.startOB.next(e+1)}))),IV(i,yU(1),EF(hU))})),SU(this.stopOB),yF((()=>{t.player.setOutput(),o.next("STARTED")}),(e=>{o.next("FAILED")}),(()=>{r.addSuccessEvent({key:PH(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 wV()((t=>Ib(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(JO){e.log.error(JO),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"}))}},LH={type:"object"},xH=class e{constructor(e){this.core=e,yb(this,"log"),yb(this,"contextMap",new Map),yb(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 LH}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 MH(this.core,r,e);return IV(n.trackDoneOB,yU(1),yF((()=>{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 MH(this.core,e.track,e))}}};yb(xH,"Name","TRTCAudioDecoder");var VH=xH,UH=class{constructor(){yb(this,"log"),this.log=xO.createLogger({id:"exp"})}call(e,t){return Ib(this,null,(function*(){return GD(this[e])?this[e](t):Promise.reject(new Vb({code:Lb.INVALID_PARAMETER,message:JP({key:HP.API_NOT_EXIST,data:{name:e}})}))}))}enableAudioFrameEvent(e){return Ib(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}),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(PB.AUDIO_FRAME,e)}),e.userId);c.set(e.userId,i)}}));else{if(c.get(r))return;let e=a.getPCM((e=>{t.emit(PB.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)}}))}};vb([function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Bx(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return zF.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"}}})],UH.prototype,"enableAudioFrameEvent",1);var FH=new UH,BH=0,HH=new Set,WH=null;Kb("5.10.2-beta.14"),UO.checkStorage(),YM();var GH={RtcError:cB,ErrorCode:rB,ErrorCodeDictionary:nB},jH=class e extends Pb.EventEmitter{constructor(t,i){super(),yb(this,"_room"),yb(this,"_eventListened",new Set),yb(this,"_localVideoTrack",null),yb(this,"_localAudioTrack",null),yb(this,"_localScreenTrack",null),yb(this,"_localScreenAudioTrack",null),yb(this,"_localVideoConfig",null),yb(this,"_localScreenConfig",null),yb(this,"_localAudioConfig",null),yb(this,"_remoteVideoConfigMap",new Map),yb(this,"_remoteAudioConfigMap",new Map),yb(this,"_remoteAudioVolumeMap",new Map),yb(this,"_remoteAudioMuteMap",new Map),yb(this,"_mediaTrackMap",new WeakMap),yb(this,"_log",xO.createLogger({id:"t".concat(++BH)})),yb(this,"_plugins",new Map),yb(this,"_networkQuality",null),yb(this,"_speakerId"),this._room=new t(_b({logger:this._log,frameWorkType:e.frameWorkType},i)),this._room.videoDecodeFallbackType=i.videoDecodeFallback,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(dH,i.assetsPath),this._use(pH,i.assetsPath),this._use(VH,i.assetsPath||ok),this._use(OH),i.enableSEI&&BM&&this._use(AH),this._room.on("audio-volume",(e=>{!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*this._localAudioTrack.getAudioLevel())}),1===i.volumeType&&e.forEach((e=>{var t;let i=""===e.userId?this._localAudioTrack:null==(t=this.room.remotePublishedUserMap.get(e.userId))?void 0:t.remoteAudioTrack;i&&(e.volume=i.dbVolume)})),this.emit(PB.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{this._log.error(new cB({code:rB.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(JO){let i=JP({key:HP.CATCH_HANDLER_ERROR,data:{name:t,event:n[0]},addDocLink:!1});return xO.warn("".concat(i,"\n\n").concat(JO.stack)),!1}}})(this,"trtc")}static create(e){}static _create(t,i){!function(){var e;if(tB){tB=!1,5!==xO.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(nk,"/en/index.html")),console.info("* Changelog: ".concat(nk,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),xO.info("TRTC Web SDK Version:",Jb),_O||xO.debug("Build Time:","2025-06-04 15:58:04");let t="UA: ".concat(navigator.userAgent," \nCPU core: ").concat(navigator.hardwareConcurrency,", GPU: ").concat(IO()),i=navigator.deviceMemory;i&&(t+=", minRAM: ".concat(i,"GB")),xO.info(t),xO.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),SO().then((e=>{e&&xO.info(yO)}))}}();let r=new e(t,i||{});return HH.add(r),r}get room(){return this._room}_listenEvents(){fL(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(PB.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(PB.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)})).add("banned",(e=>{this._exitRoom().finally((()=>{this.emit(PB.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().finally((()=>{this.emit(PB.ERROR,cB.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(PB.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e;let t=fb(_b({},e),{uplinkRTT:Math.min(e.uplinkRTT,ID),downlinkRTT:Math.min(e.downlinkRTT,ID)});this.emit(PB.NETWORK_QUALITY,t)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{fL(t,t).add("player-state-changed",(i=>{let r=fb(_b({},i),{userId:e.userId});t.kind===Sk.VIDEO&&(r.streamType=lB(t.streamType)),this.emit(t.kind===Sk.AUDIO?PB.AUDIO_PLAY_STATE_CHANGED:PB.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===Lb.PLAY_NOT_ALLOWED&&this.emit(PB.AUTOPLAY_FAILED,{userId:t.userId,mediaType:t.strMediaType,resume:()=>t.player.resume()})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{gL(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?PB.REMOTE_VIDEO_AVAILABLE:PB.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),n!==s&&(s?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i}),this.emit(s?PB.REMOTE_AUDIO_AVAILABLE:PB.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?PB.REMOTE_VIDEO_AVAILABLE:PB.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))})).add("sei-message",(e=>{this.emit(PB.SEI_MESSAGE,fb(_b({},e),{streamType:lB(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(PB.ERROR,new cB({code:rB.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,i,r,n,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(r=this._networkQuality)?void 0:r.downlinkRTT)||0,ID),upLoss:(null==(n=this._networkQuality)?void 0:n.uplinkLoss)||0,downLoss:(null==(o=this._networkQuality)?void 0:o.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/NP},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)/NP,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})))})))};this.emit(PB.STATISTICS,l)})).add("custom-message",(e=>{this.emit(PB.CUSTOM_MESSAGE,e)})).add("layerData",(e=>this.emit(PB.LAYER_DATA,e))).add("first-video-frame",(e=>{this.emit(PB.FIRST_VIDEO_FRAME,fb(_b({},e),{streamType:lB(e.streamType)}))})).add("audio-frame",(e=>{this.emit(PB.AUDIO_FRAME,e)})),fL(this,_x).add("audioInputAdded",(e=>{this.emit(PB.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(PB.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(PB.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(PB.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>Ib(this,null,(function*(){if(this.emit(PB.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),WH&&WH.deviceId===fD){let e=(yield yx()).find((e=>e.deviceId===fD));e&&WH.groupId!==e.groupId&&(WH=e,this.emit(PB.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>Ib(this,null,(function*(){this.emit(PB.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield yx())[0];if(!t||!WH||WH.groupId===t.groupId)return;let i=WH.deviceId===e.deviceId,r=WH.deviceId===fD&&WH.deviceId===t.deviceId;(i||r)&&(WH=t,this.emit(PB.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))))}use(e){let t,i;"plugin"in e?(t=e.plugin,i=e.assetsPath):t=e,this._use(t,i||ok)}_use(t,i){if(this._plugins.get(t.Name))return void this._log.warn("duplicate install plugin",t.Name);let r=new t(QB.call(this,{TRTC:e,room:this._room,errorModule:GH,assetsPath:i}));this._plugins.set(t.Name,r),t.autoStart&&this.startPlugin(t.Name)}enterRoom(t){return Ib(this,null,(function*(){var i,r;let{scene:n="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:a=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!JD(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,qD(t.preferHW)&&(this._room.preferHW=t.preferHW),t.playoutDelay&&(this._room.playoutDelay=t.playoutDelay),t.jitterBufferDelay&&(this._room.jitterBufferDelay=t.jitterBufferDelay);let c={sdkAppId:t.sdkAppId,userId:t.userId,userSig:t.userSig,privateMapKey:t.privateMapKey||null,latencyLevel:t.latencyLevel,role:"audience"===t.role?21:20,roomId:t.roomId||0,strRoomId:t.strRoomId||"",businessInfo:t.businessInfo||null,streamId:null,userDefineRecordId:t.userDefineRecordId||null,frameWorkType:t.frameWorkType,component:t.component,language:t.language,priority:t.priority,useVp8:t.useVp8,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(),fH.start()}))}exitRoom(){return Ib(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return Ib(this,null,(function*(){null!=t&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),null!=t&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),"anchor"===e&&this._checkTrackToPublish()}))}destroy(){gL(this),this.removeAllListeners(),this._room.destroy(),HH.delete(this),0===HH.size&&fH.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach((e=>{var t;return null==(t=e.destroy)?void 0:t.call(e)})),this._plugins.clear(),OO.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return Ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:i=!0,mute:r,option:n}=t,o=new $x(e._room.audioManager),s={},a={muted:!0};n&&(jD(n.microphoneId)?jD(n.audioTrack)||(s.customSource=n.audioTrack):s.deviceId=n.microphoneId,n&&KD(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),jD(n.profile)||(JD(n.profile)?gk[n.profile]&&o.setProfile(gk[n.profile]):o.setProfile(n.profile)),KD(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),jD(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),jD(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),jD(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",(t=>{e.emit(PB.ERROR,new cB({code:rB.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(PB.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=cB.convertFrom(t.error)),e.emit(PB.PUBLISH_STATE_CHANGED,fb(_b({},t),{error:i}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),jD(r)||o.setMute(r),fL(o,o).add("player-state-changed",(t=>{e.emit(PB.AUDIO_PLAY_STATE_CHANGED,fb(_b({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localAudioTrack=o,e._localAudioConfig=fb(_b({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:a,track:o}),OO.emit("113",{userId:"",room:e.room})}()}))}updateLocalAudio(e){return Ib(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:r}=e,n={};r&&(r.microphoneId?yield this._localAudioTrack.switchDevice(r.microphoneId):jD(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),jD(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),jD(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!jD(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),jD(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),uN(this._localAudioConfig,e)}))}stopLocalAudio(){return Ib(this,null,(function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),OO.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),gL(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return Ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:i,publish:r=!0,mute:n,option:o}=t,s=new rV(e._room.videoManager),a={},c={};qD(null==o?void 0:o.avoidCropping)&&(s.avoidCropping=o.avoidCropping),o&&(o.cameraId?a.deviceId=o.cameraId:jD(o.useFrontCamera)?jD(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?Sk.FACING_MODE_USER:Sk.FACING_MODE_ENVIRONMENT,jD(o.retryWhenExactFailed)||(a.retryWhenExactFailed=o.retryWhenExactFailed),o.qosPreference&&(a.contentHint=dB(o.qosPreference)),jD(o.profile)||(JD(o.profile)?Ek[o.profile]&&s.setProfile(Ek[o.profile]):s.setProfile(o.profile)),jD(o.fillMode)||(c.objectFit=o.fillMode),jD(o.mirror)||(c.mirror=o.mirror),jD(o.small)||(jD(o.smallMode)||(e._room.smallMode=o.smallMode),qD(o.small)&&!1===o.small?s.stopSmall():s.updateSmallConfig(uB(o.small,!0)))),s.once("first-video-frame",(t=>{e.emit(PB.FIRST_VIDEO_FRAME,fb(_b({},t),{streamType:lB(t.streamType)}))})),s.on("5",(t=>{e.emit(PB.ERROR,new cB({code:rB.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),s.on("2",(t=>{e.emit(PB.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),s.on("4",(t=>{let i;t.error&&(i=cB.convertFrom(t.error)),e.emit(PB.PUBLISH_STATE_CHANGED,fb(_b({},t),{error:i}))})),e._listenOutputTrackChanged(s),yield s.capture(a),jD(n)||(yield s.setMute(n)),fL(s,s).add("player-state-changed",(t=>{e.emit(PB.VIDEO_PLAY_STATE_CHANGED,fb(_b({},t),{userId:"",streamType:"main"}))})),r&&e._room.isJoined&&e._room.publish(s).catch((()=>{})),e._localVideoTrack=s,e._localVideoConfig=fb(_b({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:s})}()}))}updateLocalVideo(e){return Ib(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:r,option:n}=e,o={};n&&(jD(n.profile)||(JD(n.profile)?Ek[n.profile]&&this._localVideoTrack.setProfile(Ek[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&jD(n.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):jD(n.useFrontCamera)?jD(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?Sk.FACING_MODE_USER:Sk.FACING_MODE_ENVIRONMENT),jD(n.fillMode)||(o.objectFit=n.fillMode),jD(n.mirror)||(o.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(dB(n.qosPreference)),jD(n.small)||(qD(n.small)&&!n.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(uB(n.small,!0)))),this._room.isJoined&&!jD(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),jD(r)||(yield this._localVideoTrack.setMute(r)),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),uN(this._localVideoConfig,e)}))}stopLocalVideo(){return Ib(this,null,(function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),gL(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return Ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:i=null,publish:r=!0,option:n}=t,o=new sV(e._room.videoManager);o.on("4",(t=>{let i;t.error&&(i=cB.convertFrom(t.error)),e.emit(PB.PUBLISH_STATE_CHANGED,fb(_b({},t),{error:i}))})),o.once("first-video-frame",(t=>{e.emit(PB.FIRST_VIDEO_FRAME,fb(_b({},t),{streamType:lB(t.streamType)}))})),e._listenOutputTrackChanged(o),"main"===t.streamType&&(o.mediaType=4);let s=null,a={},c={};n&&(jD(n.profile)||(JD(n.profile)?yk[n.profile]&&o.setProfile(yk[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(a.systemAudio=!0,a.echoCancellation=n.echoCancellation,a.noiseSuppression=n.noiseSuppression,a.autoGainControl=n.autoGainControl),jD(n.fillMode)||(c.objectFit=n.fillMode),n.videoTrack&&(a.videoTrack=n.videoTrack),n.audioTrack&&(a.audioTrack=n.audioTrack),n.captureElement&&(a.captureElement=n.captureElement),n.preferDisplaySurface&&(a.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(a.contentHint=dB(n.qosPreference)));let l=yield o.capture(a);if(o.mediaTrack.addEventListener(Sk.ENDED,(()=>{e._stopScreenShare(),e.emit(PB.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(s=new cV(e._room.audioManager),yield s.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&s.setAudioOutput(e._speakerId)),fL(o,o).add("player-state-changed",(t=>{e.emit(PB.VIDEO_PLAY_STATE_CHANGED,fb(_b({},t),{userId:"",streamType:"sub"}))})),r&&e._room.isJoined){let t=[o];s&&t.push(s),e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=o,e._localScreenAudioTrack=s,e._localScreenConfig=fb(_b({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:o})}()}))}updateScreenShare(e){return Ib(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(jD(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let e=dB(r.qosPreference);this._localScreenTrack.setContentHint(e)}this._room.isJoined&&!jD(i)&&(i&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch((()=>{}))),this._localScreenConfig.publish&&!i&&(this._room.unpublish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch((()=>{})))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),uN(this._localScreenConfig,e)}))}stopScreenShare(){return Ib(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return Ib(this,null,(function*(){let{view:t,userId:i,streamType:r,option:n}=e,o="".concat(i,"_").concat(r);if(this._remoteVideoConfigMap.has(o))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(r));let s=this._room.remotePublishedUserMap.get(i);if(!s)return;let a={},c="main"===r?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._listenOutputTrackChanged(c),n&&(jD(n.fillMode)||(a.objectFit=n.fillMode),jD(n.mirror)||(a.mirror=n.mirror),jD(n.poster)||(a.poster=n.poster),a.canvasRender=n.canvasRender,"main"===r&&!jD(n.small)&&(!s.remoteVideoTrack.isSubscribing&&!s.remoteVideoTrack.isSubscribed&&s.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,c.user))),yield this._room.subscribe(c),yield this._enableVideoDecodeFallback(c,r),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._emitTrackEvent(c),this._remoteVideoConfigMap.set(o,{config:e}),n&&!jD(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return Ib(this,null,(function*(){var t,i;let{view:r,userId:n,streamType:o,option:s}=e,a="".concat(n,"_").concat(o),c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(n))return;let l={};s&&(jD(s.fillMode)||(l.objectFit=s.fillMode),jD(s.mirror)||(l.mirror=s.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);if("main"===o&&null!=u&&u.muteState.hasVideo&&(d=u.remoteVideoTrack),"sub"===o&&null!=u&&u.muteState.hasAuxiliary&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:h}=c;"main"===o&&s&&!jD(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:h}),uN(h,e);let p=jD(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=jD(r)?h.view:r,_=jD(null==s?void 0:s.viewRoot)?null==(i=h.option)?void 0:i.viewRoot:s.viewRoot;this._observeView({remoteTrack:d,view:m,receiveWhenViewVisible:p,viewRoot:_})}))}stopRemoteVideo(e){return Ib(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ib(this,null,(function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:n,remoteAuxiliaryTrack:o}=r;"main"===e.streamType&&(n.stop(),t.hasVideo&&i.push(n)),"sub"===e.streamType&&(o.stop(),t.hasAuxiliary&&i.push(o))}for(let e of i)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.delete(e.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)}))}_removeRemoteVideoConfig(e,t){let i="".concat(e,"_").concat(t),r=this._remoteVideoConfigMap.get(i);r&&r.observer&&r.observer.disconnect(),this._remoteVideoConfigMap.delete(i)}muteRemoteAudio(e,t){return Ib(this,null,(function*(){this._remoteAudioMuteMap.set(e,t);try{if("*"===e)if(t)yield this._stopRemoteAudio({userId:e});else{let e=[...this._room.remotePublishedUserMap.values()];for(let t of e)t.muteState.hasAudio&&!this._remoteAudioConfigMap.has(t.userId)&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(JO){throw this._remoteAudioMuteMap.delete(e),JO}}))}setRemoteAudioVolume(e,t){if("*"===e){let e=[...this._room.remotePublishedUserMap.values()];for(let i of e)this._remoteAudioVolumeMap.set(i.userId,t),i.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),i&&i.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}startPlugin(e,t){return Ib(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return Ib(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return Ib(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){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(PB.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:e}=this.room.audioManager;e.get("")||e.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];try{MB.has(e)&&this._log.debug("emit ".concat(e," ").concat(JSON.stringify(i)))}catch(JO){}return super.emit(e,...i)}off(t,i,r){if(this._log.debug("off",t),"*"===t?(this._eventListened.clear(),this.removeAllListeners()):super.off(t,i,r),(t===e.EVENT.AUDIO_FRAME||"*"===t)&&0===this.listeners(e.EVENT.AUDIO_FRAME).length){let{getPCMAbortCtrlMap:e}=this.room.audioManager;e.forEach((e=>{null==e||e.abort("off")})),e.clear()}return this}getAudioTrack(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},i=null,r="main",n=!1;if(JD(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 Ib(this,null,(function*(){(yield yx()).forEach((t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(PB.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),WH=t)})),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')}))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return Ib(this,null,(function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let i=this._room.remotePublishedUserMap.get(t);if(!i)return;let r={},n=i.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let i=this._remoteAudioVolumeMap.get(t),o=KD(i)?i:100;r.volume=o,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),IV(eU(n,"decode-failed"),SU(eU(n,sL.INIT)),yF((()=>{this.startPlugin(VH.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})}))),yield this._updateAudioPlayOption({playOption:r,track:n}),OO.emit("115",{userId:t,room:this.room})}catch(KO){throw this._remoteAudioConfigMap.delete(t),KO}this._emitTrackEvent(n)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ib(this,null,(function*(){let i=this._room.remotePublishedUserMap.get(e.userId);i&&(i.remoteAudioTrack.stop(),i.muteState.hasAudio&&t&&(yield this._room.unsubscribe(i.remoteAudioTrack)),this._mediaTrackMap.delete(i.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId)),OO.emit("116",{userId:e.userId,room:this.room})}))}_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),IV(eU(e,"decode-failed"),SU(eU(e,sL.INIT)),SF((()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})})),tF(eU(e,"decode-downgrade-state-changed")),yF((r=>{i=r.state,this.emit(PB.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,fb(_b({},r),{streamType:t,userId:e.userId}))}),(t=>{e.log.error("fallback",t)}),(()=>{"STARTED"===i&&e.log.info("fallback complete")}))))}_updateVideoPlayOption(e){return Ib(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),jD(t)&&n&&n.view&&!aN(i)){let e=pN(n.view);e.length>0&&(yield r.play(e,i))}if(!jD(t)){let e=pN(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return Ib(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:r}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t)}catch(Yb){}jD(t.muted)||i.setPlayerMute(t.muted),jD(t.volume)||i.setAudioVolume(t.volume/100)}()}))}_listenOutputTrackChanged(e){0===e.listeners("output-media-track-changed").length&&e.on("output-media-track-changed",(()=>this._emitTrackEvent(e,!1)))}_emitTrackEvent(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===i||(this._mediaTrackMap.set(e.outMediaTrack,i),this.emit(PB.TRACK,{userId:i,streamType:lB(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var e,t,i;let r=[];if(null!=(e=this._localAudioConfig)&&e.publish&&this._localAudioTrack&&r.push(this._localAudioTrack),null!=(t=this._localVideoConfig)&&t.publish&&this._localVideoTrack&&r.push(this._localVideoTrack),null!=(i=this._localScreenConfig)&&i.publish&&(this._localScreenTrack&&r.push(this._localScreenTrack),this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack)),0!==r.length)return this._room.publish(...r).catch((()=>{}))}_observeView(e){let{remoteTrack:t,view:i,receiveWhenViewVisible:r=!1,viewRoot:n}=e;if(jD(i))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(lB(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||zD(i)&&0===i.length||!r)return null==s||s.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch((()=>{})));let a=o.visibleViewMap||new Map,c=-1;(!s||s.root!==n)&&(null==s||s.disconnect(),a.clear(),s=new IntersectionObserver((e=>{e.forEach((e=>{a.set(e.target,e.isIntersecting),t.log.info("view ".concat(e.target.id," is").concat(e.isIntersecting?"":" not"," visible"))})),clearTimeout(c),c=window.setTimeout((()=>{[...a.values()].find((e=>e))?t.isSubscribed||this._room.subscribe(t).catch((()=>{})):t.isSubscribed&&this._room.unsubscribe(t).catch((()=>{}))}),200)}),{root:n}));let l=new Set(pN(i));a.forEach(((e,t)=>{l.has(t)||(s.unobserve(t),a.delete(t))})),l.forEach((e=>{a.set(e,!0),s.observe(e)})),s.takeRecords().forEach((e=>{a.set(e.target,e.isIntersecting)})),o.visibleViewMap=a,o.observer=s}_exitRoom(){return Ib(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach((e=>{this._stopRemoteAudio({userId:e}).catch()})),[...this._remoteVideoConfigMap.keys()].forEach((e=>{let t=e.includes("main")?"main":"sub",i=e.split("_".concat(t))[0];i&&this._stopRemoteVideo({userId:i,streamType:t}).catch()})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),function(e){let t=ZB.get(e);t&&(t.forEach((e=>clearTimeout(e))),ZB.delete(e))}(this),this._room.remotePublishedUserMap.forEach((e=>{gL(e.remoteAudioTrack),gL(e.remoteVideoTrack),gL(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return Ib(this,null,(function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield null==(e=this._room)?void 0:e.unpublish(...t).catch((()=>{}))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),gL(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_onLocalTrackCaptured(e){let{track:t}=e;"audio"===t.kind&&(!WH||fx(WH))&&(this._initActiveSpeaker(),OO.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return Ib(this,null,(function*(){if(WH&&!fx(WH))this.emit(PB.DEVICE_CHANGED,{type:"speaker",action:"active",device:WH});else{let e=yield yx();e[0]&&!fx(e[0])?(WH=e[0],this.emit(PB.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):OO.on("102",this._onLocalTrackCaptured,this)}}))}_onAudioAvailable(e){let{userId:t}=e,i=this._remoteAudioMuteMap.has(t)?this._remoteAudioMuteMap.get(t):this._remoteAudioMuteMap.get("*");(!1===i||this._room.autoReceiveAudio&&!i)&&this._doStartRemoteAudio({userId:t}).catch((()=>{}))}_onVideoAvailable(e){let{userId:t,streamType:i}=e;if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(t);if(r){let e="main"===i?r.remoteVideoTrack:r.remoteAuxiliaryTrack,t=[e];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&t.push(r.remoteAudioTrack),this._room.subscribe(...t).then((()=>{this._emitTrackEvent(e)})).catch((()=>{}))}}_onAudioUnavailable(e){let{userId:t,muteState:i}=e;i.hasAudio&&i.audioMuted||this._stopRemoteAudio({userId:t},!1).catch((()=>{}))}_onVideoUnavailable(e){let{userId:t,streamType:i}=e;this._stopRemoteVideo({userId:t,streamType:i},!1).catch((()=>{}))}sendSEIMessage(e,t){var i;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:fb(_b({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),iM.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),iM.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return Ib(this,null,(function*(){return this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(t),")")),FH.call(e,_b({trtcInstance:this},t))}))}static setLogLevel(e,t){xO.setLogLevel(e),jD(t)||(t?xO.enableUploadLog():xO.disableUploadLog())}static isSupported(){return mM()}static getCameraList(){return Tx(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return Ex(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return yx(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(t){return Ib(this,null,(function*(){if(!XN||t!==iB.SPEAKER&&t!==iB.HEADSET)(yield yx()).forEach((e=>{e.deviceId===t&&(HH.forEach((i=>{i._setCurrentSpeaker(t),i.emit(PB.DEVICE_CHANGED,{type:"speaker",action:"active",device:e})})),WH=e)}));else{let i=yield e.getMicrophoneList(),r="";if(i.forEach((e=>{e.label===t&&(r=e.deviceId)})),!r)return;HH.forEach((e=>Ib(this,null,(function*(){e._localAudioTrack&&(yield e.updateLocalAudio({option:{microphoneId:r}}))}))))}}))}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:o,version:s,max:a}=e;switch(s&&(tM.version=s),t){case"count":tM.addCount({key:i,useUV:o});break;case"enum":tM.addEnum({key:i,value:r,useUV:o});break;case"number":tM.addNumber({key:i,value:r,split:n,max:a})}}};yb(jH,"_loggerManager",xO),yb(jH,"EVENT",PB),yb(jH,"ERROR_CODE",rB),yb(jH,"TYPE",iB),yb(jH,"frameWorkType",30),vb([rH({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"}})})],jH.prototype,"use",1),vb([$B(yB.TRTC.enterRoom),NB("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})),Bx((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),rH()],jH.prototype,"enterRoom",1),vb([rH()],jH.prototype,"exitRoom",1),vb([$B(yB.TRTC.switchRole),wB("room",{merge:(e,t)=>t}),rH()],jH.prototype,"switchRole",1),vb([rH()],jH.prototype,"destroy",1),vb([$B(yB.TRTC.startLocalAudio),NB("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)})),rH()],jH.prototype,"startLocalAudio",1),vb([$B(yB.TRTC.updateLocalAudio),wB("audio",{debounce:{delay:200,getKey:()=>"".concat(BH,"-localAudio"),isNeedToDebounce:e=>{var t;return!jD(null==(t=e.option)?void 0:t.captureVolume)}}}),rH()],jH.prototype,"updateLocalAudio",1),vb([OB("audio"),rH()],jH.prototype,"stopLocalAudio",1),vb([$B(yB.TRTC.startLocalVideo),NB("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)})),rH()],jH.prototype,"startLocalVideo",1),vb([$B(yB.TRTC.updateLocalVideo),wB("video"),rH()],jH.prototype,"updateLocalVideo",1),vb([OB("video"),rH()],jH.prototype,"stopLocalVideo",1),vb([$B(yB.TRTC.startScreenShare),NB("screen",(()=>!0)),rH()],jH.prototype,"startScreenShare",1),vb([$B(yB.TRTC.updateScreenShare),wB("screen"),rH()],jH.prototype,"updateScreenShare",1),vb([rH()],jH.prototype,"stopScreenShare",1),vb([$B(yB.TRTC.startRemoteVideo),NB((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),rH({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],jH.prototype,"startRemoteVideo",1),vb([$B(yB.TRTC.updateRemoteVideo),wB((e=>"v".concat(e.userId).concat(e.streamType))),rH({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],jH.prototype,"updateRemoteVideo",1),vb([$B(yB.TRTC.stopRemoteVideo),Bx((e=>function(t){return Ib(this,null,(function*(){if("*"===t.userId){let e=[];return this._room.remotePublishedUserMap.forEach((t=>{this._remoteVideoConfigMap.has("".concat(t.userId,"_main"))&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch((()=>{}))),this._remoteVideoConfigMap.has("".concat(t.userId,"_sub"))&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch((()=>{})))})),Promise.all(e)}return e.call(this,t)}))})),rH({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],jH.prototype,"stopRemoteVideo",1),vb([OB((e=>"v".concat(e.userId).concat(e.streamType)))],jH.prototype,"_stopRemoteVideo",1),vb([$B(...yB.TRTC.muteRemoteAudio),rH({getRemoteId:e=>e})],jH.prototype,"muteRemoteAudio",1),vb([eH(...yB.TRTC.setRemoteAudioVolume),function(e,t){return Bx(((i,r)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let s=ZB.get(this);s||(s=new Map,ZB.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=ZB.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=ZB.get(this))||e.delete(a)}),e);s.set(a,t)}}))}(200,(e=>e)),rH({getRemoteId:e=>e})],jH.prototype,"setRemoteAudioVolume",1),vb([nH("start"),Ux((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),NB(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),rH({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>QP[e.getName()],ignoreLog:e=>"Debug"===e.getName()})],jH.prototype,"startPlugin",1),vb([nH("update"),wB(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),rH({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>ZP[e.getName()]})],jH.prototype,"updatePlugin",1),vb([nH("stop"),OB(((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i})),rH({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>$P[e.getName()]})],jH.prototype,"stopPlugin",1),vb([eH(...yB.TRTC.enableAudioVolumeEvaluation)],jH.prototype,"enableAudioVolumeEvaluation",1),vb([rH()],jH.prototype,"getVideoSnapshot",1),vb([rH()],jH.prototype,"_setCurrentSpeaker",1),vb([NB((e=>"a".concat(e.userId)),(()=>!0))],jH.prototype,"_startRemoteAudio",1),vb([Bx((e=>function(t){return Ib(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(fb(_b({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),OB((e=>"a".concat(e.userId)))],jH.prototype,"_stopRemoteAudio",1),vb([OB("room")],jH.prototype,"_exitRoom",1),vb([OB("screen")],jH.prototype,"_stopScreenShare",1),vb([$B(...yB.TRTC.sendSEIMessage),$F({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}})],jH.prototype,"sendSEIMessage",1),vb([$B(yB.TRTC.sendCustomMessage),$F({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],jH.prototype,"sendCustomMessage",1),vb([$B(yB.TRTC.create)],jH,"_create",1);var JH=jH,KH=class{constructor(){yb(this,"_set",new Set),OO.on(MO.LEAVE_SUCCESS,this.delete,this)}add(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let r=this.getKey(t.userId,i||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let r=this.getKey(t.userId,t.roomId||i,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(e,t,i,r){return"".concat(i,"_").concat(t,"_").concat(e,"_").concat(r)}isJoined(e){let{userId:t,roomId:i,sdkAppId:r,room:n}=e;return"rtc"!==n.scene&&this._set.has(this.getKey(t,i,r,n.useStringRoomId))}};function qH(){return Ib(this,null,(function*(){let e,t;try{let t=yield Ex();e=t&&t.length}catch(u){}try{let e=yield Tx();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:s}=this.checkSystemResult.detail,a=FO.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:r,h264Decode:o,vp8Encode:n,vp8Decode:s},l={browser:a.browser,os:a.os,trtc:c,devices:i},d={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};EL.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),EL.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var YH=Tb(Rb()),zH="1",XH="2",QH="3",ZH="4",$H="5",eW="6",tW={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},iW=[tW.UPDATE_REMOTE_MUTE_STAT,tW.UPLINK_NETWORK_STATS,tW.USER_LIST_RES,tW.MUTE_RESULT,tW.SERVER_FIRST_PACKAGE_RECEIVED,tW.RECEIVE_CUSTOM_MSG],rW={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"},nW="publish_change",oW="join",sW="leave",aW="quality_report",cW="mute_uplink",lW="publish",dW="publish_state_change",uW="unpublish",hW="subscribe",pW="unsubscribe",mW="subscribe_change",_W="start_publishing",fW="stop_publishing",gW="start_push_user_cdn",EW="stop_push_user_cdn",TW="start_mcu_mix",vW="stop_mcu_mix",yW="start_publish_cdn_stream",SW="update_publish_cdn_stream",IW="stop_publish_cdn_stream",RW="get_user_list",AW="change_role",CW="update_constraint_config",bW="rebuild_pc",kW="join/v2",DW="publish/v2",NW="subscribe/v3",wW="ability_status_report",OW="reconnect",PW="channel_msg",MW=new Set;var LW=class extends YH.default{constructor(e){var t,i,r;super(),yb(this,"room"),yb(this,"sdkAppId"),yb(this,"userId"),yb(this,"userSig"),yb(this,"url"),yb(this,"backupUrl"),yb(this,"destroyed",!1),yb(this,"_socketInUse"),yb(this,"_socket"),yb(this,"_backupSocket"),yb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[]}),yb(this,"_currentState","DISCONNECTED"),yb(this,"_isReconnecting",!1),yb(this,"_seq",0),yb(this,"_log"),yb(this,"_lastMessageTime",-1),yb(this,"_connectStartTime",-1),yb(this,"_stopConnectRetry"),yb(this,"bytesSent",0),yb(this,"bytesReceived",0),yb(this,"keepAlive",!1),yb(this,"signalDomainWhenUnifiedProxy"),yb(this,"stopKeepAliveTimeout"),yb(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-MW.size>0&&this.room.enableSPC&&(this.keepAlive=!0,MW.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=xO.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));this.signalDomainWhenUnifiedProxy&&(e+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy)));let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+="&clientIp=".concat(t)),this.race?"".concat(e,"&race=1"):e}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return"CONNECTED"===this._currentState}get isConnecting(){return"CONNECTING"===this._currentState}get isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return Ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;return function*(){if(e.isConnected)return Promise.resolve();e._log.info("connect to [".concat(e.url,", ").concat(e.backupUrl,"] ").concat(e.race?"race":"").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive))),e.emitConnectionStateChanged("CONNECTING"),e._connectStartTime=rN();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 iN(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?Sk.BACKUP:Sk.MAIN),e.emitConnectionStateChanged("CONNECTED")}()}))}connectWS(e){let{url:t,timeout:i,isMain:r}=e,n=new WebSocket(t);this.bindSocket(n),r?this._socket=n:this._backupSocket=n;let o=-1;return new Promise(((e,t)=>{n.onclose=t,n.onerror=t,n.onopen=()=>e(n),i&&(o=setTimeout((()=>{this.unbindAndCloseSocket(r?Sk.MAIN:Sk.BACKUP),t(new Vb({code:Lb.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),i))})).finally((()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)}))}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===Sk.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(Xk){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(Xk){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn("".concat(e.target===this._socket?"main":"backup"," is closed code:").concat(e.code," ").concat(e.reason)),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||1e3!==e.code)&&this.startReconnection(),this.room.isJoining&&this.emit($H,new Vb({code:Lb.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(Sk.MAIN),this.unbindAndCloseSocket(Sk.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit($H,new Vb({code:Lb.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=EN(e.data);let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values(tW),o=Object.keys(tW)[n.indexOf(i)],s=rW[o]||i;switch(iW.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case tW.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,r.svrTime&&function(e){Ub=e-(new Date).getTime();let t=new Date;t.setTime(e),xO.info("baseTime from server: ".concat(t," offset: ").concat(Ub))}(r.svrTime),this._log.info("ChannelSetup Success ".concat(rN()-this._connectStartTime)),iM.addSuccessEvent({key:521701,cost:rN()-this._connectStartTime}),this._connectStartTime=-1,this.emit(zH,{signalInfo:this._signalInfo});else{let e=new Vb({code:Lb.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:JP({key:HP.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),iM.addFailedEvent({key:521701,error:e}),this.emit($H,e)}break;case tW.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=r.relayOuterIp,this._signalInfo.relayInnerIp=r.relayInnerIp,this._signalInfo.bakRelayIps=r.bakRelayIps,this._signalInfo.relayPort=r.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=r.endReportExtend,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(s,{data:t});break;default:this.emit(String(s),{data:t})}}reGetSignalChannelUrl(){return Ib(this,null,(function*(){try{if(!this.room.joinParams)return;FB(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(qb){}}))}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?Sk.MAIN:Sk.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return Ib(this,null,(function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:i,relayInnerIp:r,relayPort:n}=this._signalInfo,{data:o}=yield this.sendWaitForResponse({command:OW,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:rW.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),iM.addSuccessEvent({key:521702,cost:rN()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(iM.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(qb){this._log.error(qb),this.room.reJoin()}}}))}send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let i={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},r=JSON.stringify(i);return this._socketInUse.send(r),this.bytesSent+=EN(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:o,enableLog:s=!0,addReceiveTime:a=!1}=e;return new Promise(((e,c)=>{let l=setTimeout((()=>{this.off(n,d);let e=new Vb({code:Lb.API_CALL_TIMEOUT,message:JP({key:HP.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),c(e)}),r),d=t=>{t.data.seq===u&&(clearTimeout(l),this.off(n,d),a&&(t.data.receiveTime=Date.now()),e(t))};this.on(n,d);let u=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:r=0,retryTimeout:n=0}=e;return xN({retryFunction:this.sendWaitForResponse,onError:e=>{let{retry:t}=e;this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(QH,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),MW.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(Sk.MAIN),this.unbindAndCloseSocket(Sk.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}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(rW.JOIN_ROOM_RESULT,t)}),1e3*e);let t=e=>{0===e.data.code&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(rW.JOIN_ROOM_RESULT,t))};this.on(rW.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(XH,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(QH):"DISCONNECTED"===e&&this.emit(eW))}};vb([vL({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn("retrying to connect ".concat(e)),e>=3&&e%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],LW.prototype,"connect",1);var xW=Tb(Rb()),VW=0,UW=!1,FW=new Set,BW=!1,HW=class{constructor(e){yb(this,"userId"),yb(this,"tinyId"),yb(this,"_sdpSemantics"),yb(this,"_isUplink"),yb(this,"_room"),yb(this,"_log"),yb(this,"_signalChannel"),yb(this,"_isErrorObserved",!1),yb(this,"_waitForPeerConnectionConnectedPromise"),yb(this,"_waitForPeerConnectionConnectedPromiseReject",null),yb(this,"_peerConnection",null),yb(this,"_emitter",new xW.default),yb(this,"_currentState","DISCONNECTED"),yb(this,"_isReconnecting",!1),yb(this,"_reconnectionCount",0),yb(this,"_reconnectionTimer",-1),yb(this,"_isFirstConnection",!0),yb(this,"_prevTime",-1),yb(this,"_localAddress"),yb(this,"_remoteAddress"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=xO.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=rN())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,iM.addSuccessEvent({key:521705,cost:Math.min(rN()-this._prevTime,3e4)})):this._isReconnecting&&iM.addSuccessEvent({key:521706,cost:rN()-this._prevTime}),this._prevTime=-1}catch(jO){throw this._isFirstConnection?(this._isFirstConnection=!1,iM.addFailedEvent({key:521705,error:jO})):this._isReconnecting&&this._reconnectionCount>=3&&iM.addFailedEvent({key:521706,error:jO}),jO}}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(),FW.delete(this)}closePeerConnection(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,e&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new Vb({code:Lb.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Jk;let e=null;if(this._isUplink){if(!bM()||0===this._peerConnection.getSenders().length)return Jk;e=this._peerConnection.getSenders()[0].transport}else{if(!CM()||0===this._peerConnection.getReceivers().length)return Jk;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:Jk}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(e.target.connectionState,", ICE: ").concat(t,", DTLS: ").concat(i)),e.target.connectionState===Kk.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===Kk.FAILED||e.target.connectionState===Kk.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new Vb({message:r,code:Lb.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===Kk.CONNECTED||e.target.connectionState===Kk.COMPLETED)&&(this.logSelectedCandidate(),EL.logSuccessEvent({userId:this._room.userId,eventType:Zk.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(VW=0,UW=!1,BW=!0,FW.add(this)):FW.delete(this),OO.emit(MO.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return Ib(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(TM(t)){let i=e.get(t.localCandidateId),r=e.get(t.remoteCandidateId);i&&(this._log.info("local candidate: ".concat(i.candidateType," ").concat(i.protocol,":").concat(i.ip||i.address,":").concat(i.port," ").concat(i.networkType||""," ").concat("relay"===i.candidateType?"relayProtocol:".concat(i.relayProtocol):"")),this._localAddress="".concat(i.ip||i.address,":").concat(i.port)),r&&(this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port)),this._remoteAddress="".concat(r.protocol,":").concat(r.ip||r.address));break}}))}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this._currentState)return e();this._waitForPeerConnectionConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new Vb({code:Lb.API_CALL_ABORTED,message:JP({key:HP.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{OO.off(MO.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new Vb({code:Lb.API_CALL_TIMEOUT,message:"connection timeout"});var i;VW+=1,i=this._signalChannel.isConnected,VW>2&&!UW&&0===FW.size&&i&&(this._log.warn("firewall restriction"),UW=!0,this._emitter.emit("firewall-restriction")),t(e)}),dD);OO.on(MO.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(QH,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=zk()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new Vb({code:this._isUplink?Lb.UPLINK_RECONNECTION_FAILED:Lb.DOWNLINK_RECONNECTION_FAILED,message:JP({key:this._isUplink?HP.UPLINK_RECONNECTION_FAILED:HP.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(QH,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)}};vb([zx(521712,!1)],HW.prototype,"setOffer",1),vb([zx(521713,!1)],HW.prototype,"setAnswer",1);var WW=Tb(Ob()),GW=function(e){return WW.default.parse(e)},jW=function(e){return WW.default.write(e)};function JW(e){return Object.keys(e).filter((t=>e[t]))}var KW=class e extends HW{constructor(e){super(fb(_b({},e),{isUplink:!1})),yb(this,"_flag",0),yb(this,"isRobot",!1),yb(this,"role","anchor"),yb(this,"remoteAudioTrack"),yb(this,"remoteVideoTrack"),yb(this,"remoteAuxiliaryTrack"),yb(this,"ssrc",{audio:0,video:0,auxiliary:0}),yb(this,"_isSDPExchanging",!1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new bF(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new JF(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new KF(this._room,this)}get videoCodec(){var e,t;let i=null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)?void 0:t.sdp;return i?i.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return cN(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===Sk.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let t=e.streams[0],{track:i}=e,r=t.id===Mk?Sk.MAIN:Sk.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=Sk.AUDIO;i.kind===Sk.VIDEO&&(n=r===Sk.MAIN?Sk.VIDEO:Sk.AUXILIARY);let o=this.remoteAudioTrack;n===Sk.VIDEO?o=this.remoteVideoTrack:n===Sk.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}addRRTRLine(e){let t=e.split("\r\n"),i=new Map;t.forEach(((e,r)=>{/^a=rtcp-fb:/.test(e)&&t[r+1]&&!/^a=rtcp-fb:/.test(t[r+1])&&i.set(r+1,"".concat(e.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))}));let r=[...i];for(let n=0;n<r.length;n++){let[e,i]=r[n];t.splice(e+n,0,i)}return t.join("\r\n")}addSPSDescription(e){let t=GW(e);return t.media.forEach((e=>{e.type===Sk.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),jW(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=GW(e);return i.media.forEach((e=>{e.ext&&(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),jW(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return Ib(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===Kk.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===Kk.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(t," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else this.initialize(),yield this.connect(e)}catch(Yb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Yb.message," ").concat(JSON.stringify(this.muteState))),new Vb({code:Lb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Yb}}))}unsubscribe(e){return Ib(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:r}=e;return function*(){if("CONNECTED"===t._currentState&&("main"===r&&!t.isMainStreamSubscribed||"auxiliary"===r&&!t.isAuxStreamSubscribed))return void t._log.info("".concat(r," stream already unsubscribed"));let e=_b({},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(JW(e),"]")),yield t.sendSubscription(n,e),"unsubscribe"===n&&(t.closePeerConnection(),t.emitConnectionStateChangedEvent("DISCONNECTED"))}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=pW,n=rW.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=mW,n=rW.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:r,data:i,responseCommand:n,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new Vb({code:i.code,message:JP({key:HP.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return Ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(t),yield e.waitForPeerConnectionConnected()}catch(Xk){throw e.closePeerConnection(!0),Xk}}()}))}exchangeSDP(e){return Ib(this,null,(function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:i}=this._peerConnection.localDescription,r={type:t,sdp:i,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:hW,commandDesc:"exchange sdp",data:r,responseCommand:rW.SUBSCRIBE_RESULT,timeout:tD});if(!this._peerConnection){let e=new Vb({code:Lb.INVALID_OPERATION,message:JP({key:HP.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(Xk){throw this._isSDPExchanging=!1,Xk}}))}createOffer(){return Ib(this,null,(function*(){let e={voiceActivityDetection:!1};DM()&&this._sdpSemantics===iD?(this._peerConnection.addTransceiver(Sk.AUDIO,{direction:Ik.RECVONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Ik.RECVONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Ik.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield pM();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=GW(e);return t.media.forEach((e=>{var t,i;if(e.type===Sk.VIDEO){let r=new Set;e.rtp.forEach((e=>{let{payload:t,codec:i}=e;return"H264"===i&&r.add(t)})),e.fmtp.forEach((e=>{let{payload:t,config:i}=e,n=i.match(/apt=(\d+)/);n&&n[1]&&r.has(Number(n[1]))&&r.add(t)}));let n=e=>{let{payload:t}=e;return!r.has(t)};e.rtp=e.rtp.filter(n),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=null==(i=e.payloads)?void 0:i.split(" ").filter((e=>!r.has(Number(e)))).join(" ")}})),jW(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=GW(e);return t.media.forEach((e=>{e.type===Sk.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),jW(t)}(t.sdp),this._sdpSemantics===iD&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)}))}onSubscribeResult(e){return Ib(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===nD)throw new Vb({code:Lb.NOT_SUPPORTED_H264,message:JP({key:HP.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new Vb({code:t,message:JP({key:HP.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(KO){throw this._log.error(KO),KO}}))}updateSSRC(e){try{GW(e).media.forEach((e=>{if(e.ssrcs)if(e.type===Sk.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Mk)}));t&&(this.ssrc.audio=Number(t.id))}else{let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Mk)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Lk)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(Xk){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return Ib(this,null,(function*(){if(!(Sb(e.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(Xk){let t=HD(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}};vb([Bx((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this._emitter.off("closed",n),r(new Vb({code:Lb.API_CALL_ABORTED,message:JP({key:HP.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],KW.prototype,"subscribe",1),vb([zx(521717,!1)],KW.prototype,"unsubscribe",1),vb([Ux(HW.prototype.afterConnect),Vx(HW.prototype.beforeConnect)],KW.prototype,"connect",1);var qW=KW,YW={voiceActivityDetection:!1},zW=class e extends HW{constructor(e){super(fb(_b({},e),{isUplink:!0})),yb(this,"localMainAudioTrack",null),yb(this,"localMainVideoTrack",null),yb(this,"localAuxAudioTrack",null),yb(this,"localAuxVideoTrack",null),yb(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),yb(this,"_isPublishingAux",!1),yb(this,"_publishingLocalAudioTrack"),yb(this,"_publishingLocalVideoTrack"),yb(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}),yb(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(kM()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(i=o[2])||!i.track),n.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((e=>{e.track&&(e.track.kind===Sk.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return Ib(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){let e;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),r&&(t._publishingLocalVideoTrack=r),t._isPublishingAux=n,r&&!n&&r.small&&(e=t._room.videoManager.smallTrack),t.sendMediaSettings(),DM()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:e,isAuxiliary:n}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:r,smallTrack:e}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,n?(r&&(t.localAuxVideoTrack=r),i&&(t.localAuxAudioTrack=i)):(r&&(t.localMainVideoTrack=r),i&&(t.localMainAudioTrack=i)),t.installTrackMuteEvents(i,r),t.sendMutedFlag()}()}))}publishByTransceiver(e){return Ib(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n,isAuxiliary:o}=e;return function*(){t._log.info("publish by transceiver");let e=new MediaStream,s=null==r?void 0:r.outMediaTrack,a=null==i?void 0:i.outMediaTrack;a&&e.addTrack(a),s&&e.addTrack(s);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||Sk.AUDIO,{direction:Ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?Sk.VIDEO:s||Sk.VIDEO,{direction:Ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||Sk.VIDEO,{direction:Ik.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||Sk.VIDEO,{direction:Ik.SENDONLY,streams:[e]}),yield t.connect();else{let e=[];if(a&&(c[0].sender.track||e.push(0),yield c[0].sender.replaceTrack(a),yield t.setBandwidth({bandwidth:(null==i?void 0:i.profile.bitrate)||40,type:Sk.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:Sk.VIDEO,videoType:o?Sk.AUXILIARY:Sk.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:Sk.VIDEO,videoType:Sk.SMALL}),e.push(2))}yield t.setTransceiverDirection(Ik.SENDONLY,e),yield t.doPublishChange(),null==r||r.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),null==r||r.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()}))}publishByAddTrack(e){return Ib(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n}=e;return function*(){t._log.info("publish by addtrack");let e=null==r?void 0:r.outMediaTrack,o=null==i?void 0:i.outMediaTrack;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return i&&o&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(r)));let s=new MediaStream;if(o&&s.addTrack(o),e&&s.addTrack(e),o&&t._peerConnection.addTrack(o,s),e&&(t._peerConnection.addTrack(e,s),n)){let e=new MediaStream;e.addTrack(n),t._peerConnection.addTrack(n,e)}yield t.connect()}()}))}enableSmall(e){return Ib(this,null,(function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(Ik.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Ik.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return Ib(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!kM())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=fb(_b({},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=fb(_b({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.setTransceiverDirection(Ik.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Ib(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:dW,data:t,responseCommand:rW.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:uW,commandDesc:"unpublish",responseCommand:rW.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===Lb.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),xM){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:CW,data:this._mediaSettings,responseCommand:rW.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return Ib(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Sk.AUXILIARY:Sk.MAIN," stream")),DM()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return Ib(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Sk.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),1===n&&null!=(i=this.localMainVideoTrack)&&i.small&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Ik.INACTIVE&&(yield this.setTransceiverDirection(Ik.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return Ib(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;kM()&&this._peerConnection.getTransceivers().findIndex((e=>"stopped"===e.direction))>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let i=this._peerConnection.getSenders().find((e=>e.track&&e.track.kind===t.kind));if(i&&i.track){this._log.warn("sender already exists, remove sender first");let e=i.track;this.removeSender(i),yield this.updateOffer("remove",e)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===Sk.VIDEO&&e instanceof rV&&e.small){let e=new MediaStream,{smallTrack:t}=this._room.videoManager;e.addTrack(t),this._peerConnection.addTrack(t,e)}yield this.updateOffer("add",t)}))}isNeedToResetOfferOrder(){if(this._sdpSemantics===rD||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=GW(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===Sk.VIDEO)return!0;return!1}removeSender(e){let t=null;kM()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&GD(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return Ib(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?Sk.AUXILIARY:Sk.MAIN," stream")),DM()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return Ib(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Sk.AUDIO)yield i[0].sender.replaceTrack(null);else{let r=t?3:1;yield i[r].sender.replaceTrack(null),1===r&&e.small&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Ik.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return Ib(this,null,(function*(){if(!ew)return;let i=!1,r=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let n=this._peerConnection.getTransceivers();if(t.forEach((t=>{n[t].direction!==e&&(n[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this.setOffer(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(Ik.INACTIVE,"|").concat(Ik.RECVONLY,"|").concat(Ik.SENDONLY,")")))&&o++,t.includes(o)){if(e===Ik.INACTIVE&&i.includes("a=".concat(Ik.RECVONLY)))return r=!0,"a=".concat(e);if(e===Ik.SENDONLY&&i.includes("a=".concat(Ik.INACTIVE)))return r=!0,"a=".concat(Ik.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:s}))}))}removeTrackBySender(e){return Ib(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===Sk.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let t=this._peerConnection.getSenders().find((t=>t.track===e.outMediaTrack));t&&(this.removeSender(t),e.kind===Sk.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===Sk.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return Ib(this,null,(function*(){var t;let i,r=null==(t=this._peerConnection)?void 0:t.getSenders();if(!r||0===r.length||!e.mediaTrack)return!1;if(i=DM()?e.kind===Sk.AUDIO?r[0]:r[1]:r.find((t=>t.track&&t.track.kind===e.kind)),!i)return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(e.kind," track on ").concat(n?Sk.AUXILIARY:Sk.MAIN," stream")),e.kind===Sk.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===Sk.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack)),!0}))}updateOffer(e,t){return Ib(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(YW);ew&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this.setOffer(i);let r=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===Sk.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:r,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(n.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:nW,data:n,responseCommand:rW.UPDATE_OFFER_RESULT,timeout:eD,commandDesc:"update offer"}),{code:s,message:a}=o.data;0!==s&&this.checkPublishResultCode(s,a),yield this.acceptAnswer(o.data.data),i.sdp&&this.updateSSRC(i.sdp)}catch(JO){throw this._log.error(JO),JO}}))}setBandwidth(e){return Ib(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!MM())return o?r===Sk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(DM()){let t=0;r===Sk.VIDEO&&(t=n===Sk.SMALL?2:n===Sk.AUXILIARY?3:1),e=s[t]}else e=s.find((e=>e.track&&e.track.kind===r));if(e){let s=e.getParameters();(!s.encodings||0===s.encodings.length)&&(s.encodings=[{}]),s.encodings[0].maxBitrate=1e3*i;try{return yield e.setParameters(s),t._log.info("".concat(n||"").concat(r," bandwidth ").concat(i," kbps")),o}catch(KP){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(KP)),o)return r===Sk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";ew&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===Sk.SMALL?n=1:i===Sk.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(o+=1,o===n?"".concat(e,"b=").concat(r,":").concat(t,"\r\n"):e)))}updateAudioBandwidthRestriction(e,t){let i="AS";return ew&&(i="TIAS",t*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,"m=audio $1\r\nc=IN $2\r\nb=".concat(i,":").concat(t,"\r\n"))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return Ib(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(qb){throw this.closePeerConnection(!0),this.uninstallEvents(),qb}}))}exchangeSDP(){return Ib(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(qb){throw qb}}))}createOffer(){return Ib(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(YW);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(qb){throw qb}}))}doExchangeSDP(){let e={command:lW,responseCommand:rW.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof sV||this.localAuxVideoTrack instanceof sV,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then((e=>{let{code:t,message:i,data:r}=e.data;return 0===t?this.acceptAnswer(r):this.checkPublishResultCode(t,i)}))}setSDPDirection(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"all",r=GW(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),jW(r)}acceptAnswer(e){return Ib(this,null,(function*(){var t,i,r,n,o;try{let s;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let e=(null==(t=this._publishingLocalVideoTrack)?void 0:t.profile.bitrate)||(null==(i=this.localMainVideoTrack)?void 0:i.profile.bitrate),o=(null==(r=this._publishingLocalAudioTrack)?void 0:r.profile.bitrate)||(null==(n=this.localMainAudioTrack)?void 0:n.profile.bitrate);if(e){let t=this._isPublishingAux?Sk.AUXILIARY:Sk.BIG;s=yield this.setBandwidth({bandwidth:e,type:Sk.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:Sk.AUDIO,sdp:s}))}if(s=this.removeVideoOrientation(e.sdp),null!=(o=this._publishingLocalVideoTrack)&&o.small){let{smallStreamConfig:e}=this._room;s=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:Sk.VIDEO,videoType:Sk.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this.setAnswer(a),this._log.debug("accepted answer: ".concat(s))}catch(s){throw this._log.error("failed to accept remote answer ".concat(s)),s}}))}sendMutedFlag(e){var t,i,r;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let n={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(i=this.localMainVideoTrack)||!i.muted),auxVideo:!(null==(r=this.localAuxVideoTrack)||!r.muted)};this._log.info("send muted state: ".concat(JSON.stringify(n))),this._signalChannel.send(cW,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return Ib(this,null,(function*(){if(!(Sb(e.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:uW,responseCommand:rW.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(Xk){let t=HD(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)&&OO.emit(MO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{GW(e).media.forEach(((e,t)=>{if(e.type===Sk.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===rD&&e.ssrcGroups)return void e.ssrcGroups.forEach(((e,t)=>{let i=Number(e.ssrcs.split(" ")[0]);0===t?this.ssrc.video=i:1===t&&(this.ssrc.small=i)}));let i=e.ssrcs&&e.ssrcs[0];if(!i)return;switch(t){case 1:this.ssrc.video=Number(i.id);break;case 2:this.ssrc.small=Number(i.id);break;case 3:this.ssrc.auxiliary=Number(i.id)}}}))}catch(Xk){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Sk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Sk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Sk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Sk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Sk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===nD?(this._log.error(WP.NOT_SUPPORTED_H264ENCODE),new Vb({code:Lb.NOT_SUPPORTED_H264,message:JP({key:HP.NOT_SUPPORTED_H264ENCODE})})):new Vb({code:Lb.UNKNOWN,message:JP({key:HP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:rW.PUBLISH_RESULT,code:e,message:t}})})}};vb([Bx((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this._emitter.off("closed",n),r(new Vb({code:Lb.API_CALL_ABORTED,message:JP({key:HP.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],zW.prototype,"publish",1),vb([zx(521715,!1)],zW.prototype,"unpublish",1),vb([Ux(HW.prototype.afterConnect),Vx(HW.prototype.beforeConnect)],zW.prototype,"connect",1);var XW=zW,QW=class{constructor(e,t){this.room=e,yb(this,"_log"),yb(this,"_prevReportTime",0),yb(this,"_prevReport",{}),yb(this,"_prevStats",null),yb(this,"_prevEncoderImplementation",""),yb(this,"_prevAuxEncoderImpl",""),yb(this,"_prevQualityLimitationReason",""),yb(this,"_prevAuxQualityLimitationReason",""),yb(this,"_prevDecoderImplementationMap",new Map),yb(this,"totalBytesSent",0),yb(this,"totalBytesReceived",0),yb(this,"_spcStats",null),this._log=t}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return Ib(this,null,(function*(){var t;let i={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},r=e.getPeerConnection(),n=e.getSSRC();if(r)try{if((this._spcStats||(yield r.getStats())).forEach((t=>{var r,o,s;let a,c;if("outbound-rtp"===t.type)if((t.mediaType||t.kind)===Sk.VIDEO){if(t.ssrc===n.video?(a=Sk.VIDEO,c=e.localMainVideoTrack):t.ssrc===n.small?a=Sk.SMALL:t.ssrc===n.auxiliary&&(c=e.localAuxVideoTrack,a=Sk.AUXILIARY),!a)return;if(i[a].bytesSent=t.bytesSent,i[a].packetsSent=t.packetsSent,i[a].framesEncoded=t.framesEncoded,jD(t.keyFramesEncoded)||(i[a].keyFramesEncoded=t.keyFramesEncoded),jD(t.nackCount)||(i[a].nackCount=t.nackCount),jD(t.pliCount)||(i[a].pliCount=t.pliCount),jD(t.retransmittedPacketsSent)||(i[a].retransmittedPacketsSent=t.retransmittedPacketsSent),jD(t.totalEncodeTime)||(i[a].totalEncodeTime=t.totalEncodeTime),jD(t.totalPacketSendDelay)||(i[a].totalPacketSendDelay=t.totalPacketSendDelay),!jD(t.encoderImplementation)&&(a===Sk.VIDEO&&this._prevEncoderImplementation!==t.encoderImplementation||a===Sk.AUXILIARY&&this._prevAuxEncoderImpl!==t.encoderImplementation)){let i=2,r=this._prevEncoderImplementation;a===Sk.AUXILIARY&&(i=7,r=this._prevAuxEncoderImpl),OO.emit("262",{userId:e.userId,streamType:i,prevImplementation:r,implementation:t.encoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientEncoder}),this[a===Sk.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=t.encoderImplementation,this._log.info("".concat(a===Sk.AUXILIARY?"aux ":"","encoderImplementation change to ").concat(t.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(t.powerEfficientEncoder))}t.ssrc===n.video?!jD(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),OO.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:null==(r=e.localMainVideoTrack)?void 0:r.isQosClearFirst}),this._prevQualityLimitationReason=t.qualityLimitationReason):t.ssrc===n.auxiliary&&!jD(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),OO.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(o=e.localAuxVideoTrack)?void 0:o.isQosClearFirst}),this._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else i.audio.bytesSent=t.bytesSent,i.audio.packetsSent=t.packetsSent;else"candidate-pair"===t.type?TM(t)&&(this.totalBytesSent=t.bytesSent,KD(t.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*t.currentRoundTripTime))):"media-source"===t.type&&(t.kind===Sk.AUDIO?(i.audio.audioLevel=t.audioLevel||0,i.audio.totalAudioEnergy=t.totalAudioEnergy||0,t.echoReturnLoss,t.totalSamplesDuration&&(i.audio.totalSamplesDuration=t.totalSamplesDuration)):t.kind===Sk.VIDEO&&(t.trackIdentifier===e.getVideoTrackId(Sk.VIDEO)?i.video.fpsCapture=t.framesPerSecond:t.trackIdentifier===e.getVideoTrackId(Sk.AUXILIARY)?i.auxiliary.fpsCapture=t.framesPerSecond:i.small.fpsCapture=t.framesPerSecond));if(!jD(t.audioLevel)&&null!=(s=e.localMainAudioTrack)&&s.mediaTrack&&t.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(i.audio.audioLevel=t.audioLevel||0),!jD(t.frameWidth)){let r=Sk.SMALL;t.trackIdentifier===e.getVideoTrackId(Sk.VIDEO)||t.ssrc===n.video?r=Sk.VIDEO:(t.trackIdentifier===e.getVideoTrackId(Sk.AUXILIARY)||t.ssrc===n.auxiliary)&&(r=Sk.AUXILIARY),i[r].frameWidth=t.frameWidth,i[r].frameHeight=t.frameHeight,i[r].framesSent=t.framesSent}})),e.localMainAudioTrack){let t=e.localMainAudioTrack.getInternalAudioLevel();i.audio.micAudioLevel=t,0===i.audio.audioLevel&&(i.audio.audioLevel=t)}this.totalBytesSent||(this.totalBytesSent+=i.audio.bytesSent+i.video.bytesSent+i.auxiliary.bytesSent),Object.keys(i).forEach((t=>{t===Sk.AUDIO?(e.localMainAudioTrack&&(e.localMainAudioTrack.stat=i[t]),e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=i[t])):t===Sk.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=i[t]):t===Sk.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=i[t])}))}catch(Yb){this._log.warn("failed to getStats on sender connection ".concat(Yb))}return 0===i.rtt&&(i.rtt=(null==(t=this.room.networkQuality)?void 0:t.uplinkRTT)||0),i}))}getReceiverStats(e){return Ib(this,null,(function*(){var t,i,r;let n={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0}},o=e.getPeerConnection();if(o)try{let{ssrc:r}=e,{muteState:s,subscribeState:a}=e;(this._spcStats||(yield o.getStats())).forEach((t=>{if("inbound-rtp"===t.type){let i=(t.mediaType||t.kind)===Sk.AUDIO;if(i){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);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(ew&&0===t.bytesReceived)return;let i;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,i=e.remoteVideoTrack,s.hasSmall&&a.smallVideo&&(n.isSmallSubscribed=!0),t.decoderImplementation&&(!this._prevDecoderImplementationMap.has(n.userId)||this._prevDecoderImplementationMap.get(n.userId)!==t.decoderImplementation)&&(this._log.info("".concat(n.userId," decoderImplementation change to ").concat(t.decoderImplementation," HWDecoder: ").concat(t.powerEfficientDecoder)),OO.emit("262",{userId:this.room.userId,remoteUserId:n.userId,prevImplementation:this._prevDecoderImplementationMap.get(n.userId),implementation:t.decoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(n.userId,t.decoderImplementation))),t.ssrc===r.auxiliary&&s.hasAuxiliary&&(n.auxiliary.packetsReceived=t.packetsReceived,n.auxiliary.bytesReceived=t.bytesReceived,n.auxiliary.packetsLost=t.packetsLost,n.auxiliary.framesReceived=t.framesReceived,n.auxiliary.framesDecoded=t.framesDecoded,n.auxiliary.fpsDecoded=t.framesPerSecond,i=e.remoteAuxiliaryTrack,n.auxiliary.p2pDelay=i.stat.end2EndDelay,n.hasAuxiliary=!0),i&&(i.stat.packetsReceived=t.packetsReceived,i.stat.bytesReceived=t.bytesReceived,i.stat.packetsLost=t.packetsLost,i.stat.framesReceived=t.framesReceived,i.stat.framesDecoded=t.framesDecoded,t.jitterBufferDelay&&(i.stat.jitterBufferDelay=Math.floor(t.jitterBufferDelay/t.jitterBufferEmittedCount*1e3)),n.video.p2pDelay=i.stat.end2EndDelay)}t.jitterBufferDelay&&(i?(n.audio.totalJitter=t.jitterBufferDelay,n.audio.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.video&&s.hasVideo?(n.video.totalJitter=t.jitterBufferDelay,n.video.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.auxiliary&&s.hasAuxiliary&&(n.auxiliary.totalJitter=t.jitterBufferDelay,n.auxiliary.totalJitterCount=t.jitterBufferEmittedCount))}else"candidate-pair"===t.type&&TM(t)&&(this.totalBytesReceived=t.bytesReceived,KD(t.currentRoundTripTime)&&(n.rtt=Math.floor(1e3*t.currentRoundTripTime)));jD(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)),!jD(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),jD(null==(t=e.remoteVideoTrack.player.stat)?void 0:t.fps)||(n.video.fpsRender=e.remoteVideoTrack.player.stat.fps),jD(null==(i=e.remoteAuxiliaryTrack.player.stat)?void 0:i.fps)||(n.auxiliary.fpsRender=e.remoteAuxiliaryTrack.player.stat.fps)}catch(KO){this._log.warn("failed to getStats on receiver connection ".concat(KO))}return 0===n.rtt&&(n.rtt=(null==(r=this.room.networkQuality)?void 0:r.uplinkRTT)||0),n}))}getStats(e,t){return Ib(this,null,(function*(){let i={},r=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:i,receiverStats:r};let t=rN(),n=yield e.getStats(),o=rN();o-t>2e3&&this._log.warn("getStats cost ".concat(o-t,"ms"));let s=[],a=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);n.forEach((e=>a.has(e.type)&&s.push(e))),this._spcStats=s}e&&(i=yield this.getSenderStats(e));for(let[e,n]of t){let e=yield this.getReceiverStats(n);r.push(e)}return{senderStats:i,receiverStats:r}}))}getDifferenceValue(e,t){if(wx(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r}=e;var n,o,s;if(!wx(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*NP,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*NP),t.senderStats.audio.totalSamplesDuration&&(i.msg_device_info.uint32_audio_capture_cost=t.senderStats.audio.totalSamplesDuration);let r=[];if(t.senderStats.video.bytesSent){let e={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};r.push(e)}if(t.senderStats.small.bytesSent){let e={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};r.push(e)}if(t.senderStats.auxiliary.bytesSent){let e={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};r.push(e)}let n={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:e,msg_video_status:r,msg_network_status:n}}let a=null==(n=$L())?void 0:n.playoutStats;a&&(i.msg_device_info.uint32_audio_play_cost=a.totalFramesDuration);let{statInterval:c}=this;i.msg_down_stream_info=[],t.receiverStats.forEach((e=>{let t={msg_user_info:{str_identifier:e.userId,uint64_tinyid:e.tinyId},msg_network_status:{uint32_rtt:e.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(e.hasAudio){let i={uint32_audio_p2p_delay:e.audio.p2pDelay,uint32_audio_cache_ms:e.audio.totalJitter,uint32_audio_cache_ms_count:e.audio.totalJitterCount,uint32_audio_codec_bitrate:e.audio.bytesReceived,uint32_audio_total_bitrate:e.audio.bytesReceived,uint32_audio_level:1e8*e.audio.audioLevel,uint32_audio_energy:1e6*e.audio.totalAudioEnergy,uint32_audio_receive:e.audio.packetsReceived,uint32_audio_origin_lost:e.audio.packetsLost};t.msg_audio_status=i}if(e.hasVideo){let i=r.get("".concat(e.userId,"_").concat(xk)),n=i?i.duration:0,o={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.video.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.video.totalJitter,uint32_video_cache_ms_count:e.video.totalJitterCount,uint32_video_p2p_delay:e.video.p2pDelay};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=r.get("".concat(e.userId,"_").concat(Vk)),n=i?i.duration:0,o={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.auxiliary.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.auxiliary.totalJitter,uint32_video_cache_ms_count:e.auxiliary.totalJitterCount,uint32_video_p2p_delay:e.auxiliary.p2pDelay};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let l=this._prevReport,d=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(i)),this._prevStats=JSON.parse(JSON.stringify(t)),i.msg_up_stream_info.msg_audio_status&&l.msg_up_stream_info.msg_audio_status){let e=l.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let r=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*r/c),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}null!=(o=l.msg_device_info)&&o.uint32_audio_capture_cost?i.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(l.msg_device_info.uint32_audio_capture_cost,i.msg_device_info.uint32_audio_capture_cost)/c):delete i.msg_device_info.uint32_audio_capture_cost}let u=l.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=u.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type));if(!t||0===t.uint32_video_codec_bitrate)return e.uint32_video_codec_bitrate=0,e.uint32_video_enc_fps=0,void(e.uint32_video_codec_fps=0);let r=0,n=0,o=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(r=t.uint32_video_codec_bitrate,n=t.uint32_video_enc_fps,o=t.uint32_video_codec_fps);let s=this.getDifferenceValue(r,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*s/c),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(n,e.uint32_video_enc_fps)/c),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_codec_fps)/c),0===t.uint32_video_width&&0===t.uint32_video_height&&0===t.uint32_video_codec_fps&&(e.uint32_video_codec_fps=e.uint32_video_enc_fps),jD(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),jD(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),jD(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),jD(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),jD(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/c)),jD(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/c))}));let h=l.msg_down_stream_info;i.msg_down_stream_info=i.msg_down_stream_info.filter((e=>h.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid))));let p=i.msg_down_stream_info;return p.forEach((e=>{let t=h.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(wx(e.msg_audio_status)||wx(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,r=t.msg_audio_status,n=this.getDifferenceValue(r.uint32_audio_cache_ms_count,i.uint32_audio_cache_ms_count);delete i.uint32_audio_cache_ms_count,i.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(r.uint32_audio_cache_ms,i.uint32_audio_cache_ms)/n)||0;let o=this.room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);o&&(o.remoteAudioTrack.stat.jitterBufferDelay=i.uint32_audio_cache_ms),i.uint32_audio_origin_lost=this.getDifferenceValue(r.uint32_audio_origin_lost,i.uint32_audio_origin_lost),i.uint32_audio_receive=this.getDifferenceValue(r.uint32_audio_receive,i.uint32_audio_receive),i.uint32_audio_receive+=i.uint32_audio_origin_lost;let s=this.getDifferenceValue(r.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*s/c),i.uint32_audio_total_bitrate=Math.round(8*s/c)}if(e.msg_video_status&&t.msg_video_status){let i=t.msg_video_status;e.msg_video_status=e.msg_video_status.filter((e=>i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)))),e.msg_video_status.forEach((e=>{let t=i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)),r=t.uint32_video_receive,n=t.uint32_video_origin_lost,o=t.uint32_video_codec_bitrate,s=t.uint32_video_receive_fps,a=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(n,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(r,e.uint32_video_receive)+e.uint32_video_origin_lost;let l=this.getDifferenceValue(o,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/c);let d=this.getDifferenceValue(s,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/c),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(a,e.uint32_video_dec_fps)/c);let u=this.getDifferenceValue(t.uint32_video_cache_ms_count,e.uint32_video_cache_ms_count);delete e.uint32_video_cache_ms_count,e.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(t.uint32_video_cache_ms,e.uint32_video_cache_ms)/u)||0}))}})),null!=(s=l.msg_device_info)&&s.uint32_audio_play_cost?i.msg_device_info.uint32_audio_play_cost=2*Math.floor(this.getDifferenceValue(l.msg_device_info.uint32_audio_play_cost,i.msg_device_info.uint32_audio_play_cost)/c):delete i.msg_device_info.uint32_audio_play_cost,d&&t.receiverStats.forEach((e=>{if(e.audio.concealedSamples&&e.audio.totalSamplesReceived){let t=d.receiverStats.find((t=>t.userId===e.userId));if(t&&t.audio.concealedSamples&&t.audio.totalSamplesReceived){let i=e.audio.concealedSamples-t.audio.concealedSamples,r=e.audio.totalSamplesReceived-t.audio.totalSamplesReceived,n=Math.floor(i/r*1e3*c);if(n>1e3*c/5){let t=p.find((t=>t.msg_user_info.str_identifier===e.userId));t&&(t.msg_audio_status.uint32_audio_block_time=n)}}}})),i}getStatsReport(e){return Ib(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:r,freezeMap:n}=e;return function*(){let e={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield t.getStats(i,r);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:n}),t._prevReportTime=Date.now(),e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},ZW=Tb(Rb());function $W(e){return new Promise((t=>Ib(this,null,(function*(){let i=setTimeout((()=>{t({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})}),1e4),r=Date.now(),n="https://".concat(e,"/?t=").concat(r);try{yield fetch(n)}catch(Yb){}clearTimeout(i);let o=function(e){let t={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let i=performance.getEntriesByType("resource").reverse();for(let r of i)if(r.name===e){let e=Math.round(r.duration),i=Math.max(Math.round(r.domainLookupStart-r.startTime),0),n=r.redirectStart>0?Math.max(Math.round(r.redirectEnd-r.redirectStart),0):0,o=r.fetchStart>0?Math.max(Math.round(r.domainLookupStart-r.fetchStart),0):0,s=Math.round(r.domainLookupEnd-r.domainLookupStart),a=Math.round(r.requestStart-r.secureConnectionStart),c=Math.round(r.secureConnectionStart-r.connectStart),l=Math.round(r.responseStart-r.requestStart),d=Math.round(r.responseEnd-(r.responseStart||r.startTime));t=fb(_b({},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 eG=class e extends ZW.default{constructor(e){let{signalChannel:t,room:i}=e;super(),yb(this,"_room"),yb(this,"_signalChannel"),yb(this,"_log"),yb(this,"uplinkRTT",0),yb(this,"uplinkLoss",0),yb(this,"downlinkRTT",0),yb(this,"downlinkLoss",0),yb(this,"pingResults",{}),yb(this,"_downlinkPrevStatMap",new Map),yb(this,"_downlinkLossAndRTTMap",new Map),yb(this,"_interval",-1),yb(this,"_uplinkNetworkQuality",0),yb(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=xO.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:i}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(t,", loss: ").concat(i," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(rW.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(XH,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 Ib(this,null,(function*(){if(0===this._room.remotePublishedUserMap.size)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],t=e.filter((e=>{var t;return(null==(t=e.getPeerConnection())?void 0:t.connectionState)===Kk.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let n=0;n<t.length;n++){let e=t[n].getPeerConnection();if(!e)return;let{rtt:i,totalPacketsLost:r,totalPacketsReceived:o}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o});continue}let s=0,a=this._downlinkPrevStatMap.get(e),c=r-a.totalPacketsLost,l=o-a.totalPacketsReceived;s=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:s,userId:t[n].getUserId(),audioDelay:t[n].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[n].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach((e=>{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:i,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=i,this.downlinkLoss=r,this.downlinkNetworkQuality=this.getNetworkQuality(r,i)}))}getStat(e){return Ib(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!CM())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&&KD(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===Sk.AUDIO||e.mediaType===Sk.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return 0===t.rtt&&(t.rtt=this.uplinkRTT),t}catch(YO){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){"DISCONNECTED"===e.state?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):"CONNECTED"===e.state&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(e){let{state:t}=e;"DISCONNECTED"===t?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):"CONNECTED"===t&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==Kk.DISCONNECTED&&e.connectionState!==Kk.FAILED&&e.connectionState!==Kk.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){-1===this._interval?(this._log.debug("start network quality calculating"),this._interval=hL.run("ric",(()=>{var t;this.handleDownlinkNetworkQuality();let i=[...this._downlinkLossAndRTTMap.values()];OO.emit(MO.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=fb(_b({},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=>$W(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=>{iM.addSuccessEvent({key:521718,cost:e.cost})})),this._log.warn("All ping results: ".concat(JSON.stringify(e)))})).catch((e=>{this._log.warn("Error during pinging domains: ".concat(e))}))}}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.debug("stopped"),-1!==this._interval&&(hL.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})}}))}};yb(eG,"EVENT_NETWORK_QUALITY","0"),yb(eG,"lastPingTime",0);var tG=eG;var iG=class{constructor(e){yb(this,"_frameWorkType"),yb(this,"_component"),yb(this,"_language"),yb(this,"connectionType"),yb(this,"_room"),yb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0}),yb(this,"_keyPrefix"),yb(this,"_log"),yb(this,"_intervalId"),yb(this,"_firstPublishedUserList"),yb(this,"_networkQuality"),yb(this,"_basicInfo"),yb(this,"_pathJoinRoom"),yb(this,"_pathLeaveRoom"),yb(this,"_pathMainVideoMap"),yb(this,"_pathMainAudioMap"),yb(this,"_pathAuxiliaryMap"),yb(this,"_remoteStreamStatMap"),yb(this,"_localStreamStat"),yb(this,"_eventMap",new Map),yb(this,"_captureCostSum",0),yb(this,"_captureCostCount",0),yb(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=xO.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&GD(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 ZD(o)?o.catch((e=>xO.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(Xk){xO.error("".concat(t.name,"() error observed ").concat(Xk))}}}({fn:this[e],context:this}))})),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Jb,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:"live"===this._room.scene?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,SO().then((e=>{this._basicInfo.string_os_version=kO(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),OO.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(MO.JOIN_START,this.handleJoinStart).addEvent(MO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(MO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(MO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(MO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(MO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(MO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(MO.JOIN_FAILED,this.handleJoinFailed).addEvent(MO.LEAVE_START,this.handleLeaveStart).addEvent(MO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(MO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(MO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(MO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(MO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(MO.PUBLISH_START,this.handlePublishStart).addEvent(MO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(MO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(MO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(MO.PLAY_TRACK_START,this.handlePlayStart).addEvent(MO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(MO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!t.isRemote||!this.hitTest(t.room)||"PLAYING"===i&&(r===Sk.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(MO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(MO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(MO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(MO.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(MO.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)=>OO.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),hL.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&&(jD(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),jD(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),jD(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(e){let{room:t,detailCost:i}=e;if(this.hitTest(t)&&i){let{totalCost:e,local:t,dns:r,tcp:n,tls:o,request:s,response:a}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=r,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=o,this._pathJoinRoom.int32_schedule_request=s,this._pathJoinRoom.int32_schedule_response=a}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(e){let{room:t,error:i}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=i instanceof Vb?Number(i.getExtraCode()||i.getCode()):Lb.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}handleJoinFailed(e){let{room:t,error:i}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=i.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout((()=>{this.report()})))}handleReceivedPublishUserList(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(e,t){var i;let r="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(r)){let n={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:fb(_b({},nG),{msg_user_info:new oG({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 oG({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,iM.addNumber({key:516820,value:e})}}0===(null==r?void 0:r.statsToReport.uint64_render_first_frame_time)&&(r.statsToReport.uint64_render_first_frame_time=i)}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=this._pathMainAudioMap.get(t);i&&0===i.statsToReport.uint64_play_first_frame_time&&(i.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(e){this.hitTest(e.room)&&(this._networkQuality.totalUplinkLoss+=e.uplink.loss,this._networkQuality.totalUplinkRTT+=e.uplink.rtt,this._networkQuality.count++,e.downlinks.forEach((e=>{let{rtt:t,loss:i,userId:r,videoDelay:n,audioDelay:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(s)s.totalRTT+=t,s.totalLoss+=i,n&&(s.totalVideoDelay=(s.totalVideoDelay||0)+n,s.videoDelayCount=(s.videoDelayCount||0)+1),o&&(s.totalAudioDelay=(s.totalAudioDelay||0)+o,s.audioDelayCount=(s.audioDelayCount||0)+1),s.count++;else{let e,s,a,c;n&&(s=n,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_device_info:t,msg_up_stream_info:i,msg_down_stream_info:r}=e.report;if(i.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:t,uint32_video_width:r,uint32_video_height:n}=i.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=t,this._localStreamStat.totalVideoWidth+=r,this._localStreamStat.totalVideoHeight+=n,this._localStreamStat.videoCount++}if(i.msg_audio_status){let{uint32_audio_level:e}=i.msg_audio_status;Math.floor(e/NP*100)>0&&(this._localStreamStat.totalAudioLevel+=e/NP,this._localStreamStat.audioLevelCount++)}r.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:r}=e,n=t.str_identifier,o=this._room.remotePublishedUserMap.get(n);if(r.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,r="".concat(n,"_").concat(t?"main":"auxiliary"),s=this._remoteStreamStatMap.get(r);if(s&&(t&&null!=o&&o.remoteVideoTrack.isSubscribed||i&&null!=o&&o.remoteAuxiliaryTrack)){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*pb(10,6)))}})),!aN(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/NP*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/NP,t.audioLevelCount++))}})),t.uint32_audio_capture_cost&&(this._captureCostSum+=t.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart(e){let{room:t}=e;this.hitTest(t)&&0===this._localStreamStat.publishStartTime&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof Vb?i.getExtraCode()||i.getCode():Lb.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Ck))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Dk))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&kk))>=0}hitTest(e){return e===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach(((e,t)=>{let{userId:i}=e,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(r){let{totalLoss:t,count:i,audioDelayCount:n,videoDelayCount:o,totalAudioDelay:s,totalVideoDelay:a}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),n&&s&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(s/n),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/o))}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:n}=this._room;n&&(e.statsToReport.uint32_audio_play_time=n.getDuration(t,Sk.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,Sk.VIDEO)),e.statsToReport.uint32_video_render_first&&(e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,rG));let{badCaseDetector:o}=this._room,{dataFreeze:s,count:a}=o.getDataFreezeDuration(t),{renderFreeze:c}=o.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=a,e.statsToReport.uint32_video_block_time=Math.min(s,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),o.isBlackStream(t)&&0===e.statsToReport.uint32_video_avg_fps?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>rG&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+rG):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>rG&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+rG):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>rG&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+rG)}getReportData(){this._basicInfo.uint32_networkType=wD();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new oG({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:dN(this._signalInfo.relayIp),uint32_client_ip:dN(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*pb(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:dN(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return SN(e),e}report(){return Ib(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(jO){this._log.warn(jO)}finally{this.isDestroyed&&(this._room=null)}}))}upload(e){return Ib(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=yield DN(e),r=i instanceof ArrayBuffer,n="".concat(CD(t,dk.KEY_POINT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i));let s=[this.uploadKVStat(iM),this.uploadKVStat(tM)];o||s.push(kN({url:n,body:i,priority:"low"})),yield Promise.all(s)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return Ib(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=fb(_b({},t.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(t);let i=yield DN(t),r="".concat(CD(+this._room.sdkAppId,dk.KV_STAT),"&gzip=").concat(+(i instanceof ArrayBuffer)),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(r,i)),n||kN({url:r,body:i})}))}};vb([vL({settings:{timeout:500,retries:3}})],iG.prototype,"upload",1);var rG=5e3,nG={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},oG=class{constructor(e){yb(this,"str_identifier"),yb(this,"str_tinyid"),yb(this,"uint32_role"),this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},sG=iG,aG=class{constructor(){yb(this,"_startTime"),yb(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=rN())}stop(){0===this._endTime&&(this._endTime=rN())}getDuration(){return 0===this._endTime?rN()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},cG=class{constructor(e){yb(this,"_room",null),yb(this,"_durationMap"),yb(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(MO.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(MO.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(MO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;var n;let{userId:o}=r;if(!this.hitTest(t))return;i.hasAudio&&!r.hasAudio&&this.stopDurationItem("".concat(o,"_main"),Sk.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_main"),Sk.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_auxiliary"),Sk.VIDEO);let s=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);s&&(!i.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,Sk.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,Sk.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,Sk.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>OO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>OO.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 aG,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===Sk.AUDIO?[n]:[],video:t===Sk.AUDIO?[]:[n]})}stopDurationItem(e,t){if(this._durationMap.has(e)){let i=this._durationMap.get(e)[t].find((e=>0===e.endTime));i&&i.stop()}}hitTest(e){return this._room===e}getDuration(e,t){return this._durationMap.has(e)?this._durationMap.get(e)[t].reduce(((e,t)=>e+t.getDuration()),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},lG=class{constructor(e){yb(this,"_room"),yb(this,"_renderFreezeMap",new Map),yb(this,"_isVideoPlayingEventFiredMap",new Map),yb(this,"_dataFreezeMap",new Map),yb(this,"_monitorFreezeData",new Map),yb(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(MO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(MO.PLAY_TRACK_START,this.onPlayTrackStart).set(MO.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(MO.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(MO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(t.isRemote&&t.room&&this.hitTest(t.room)&&n===Sk.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===Sk.MUTE?this.onVideoTrackMuted(t):r===Sk.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(MO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>OO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>OO.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 aG;n?n.durationItemList.push(o):this._dataFreezeMap.set(r,{userId:t,type:i,durationItemList:[o],isFreezing(){let e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i);this.stopDataFreeze({key:r,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;this.hitTest(t)&&i.msg_down_stream_info.forEach((e=>{let t=this._room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);if(!t)return;let{userId:i,muteState:r}=t;e.msg_video_status.forEach((e=>{2===e.uint32_video_stream_type&&r.hasVideo&&!r.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"main"}),7===e.uint32_video_stream_type&&r.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"auxiliary"})}))}))}stopDataFreeze(e){let{key:t,userId:i,type:r}=e,n=this._dataFreezeMap.get(t);if(!n||!n.isFreezing())return;let o=n.durationItemList[n.durationItemList.length-1];o.stop();let s=o.getDuration();s>sD?this._monitorFreezeData.set(t,{userId:i,type:r,duration:s}):n.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return Ib(this,arguments,(function(e){var t=this;let{userId:i,fps:r,type:n}=e;return function*(){let e="".concat(i,"_").concat(n),o=t._renderFreezeMap.get(e);if(r<=2){let r=rN();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:r,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(e,{userId:i,type:n,isFreeze:!0,freezeTimeline:[{startTime:r,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let e=o.freezeTimeline.pop();if(e){e.endTime=rN();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room)||t.kind!==Sk.VIDEO||!t.isRemotePublished)return;let i="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(i)||this._isVideoPlayingEventFiredMap.set(i,!1)}getDataFreezeDuration(e){let t={dataFreeze:0,count:0},i=this._dataFreezeMap.get(e);if(i){if(i.isFreezing()){let e=i.durationItemList[i.durationItemList.length-1];e.stop(),e.getDuration()<sD&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){let t=this._renderFreezeMap.get(e),i=0,r=0;if(t)if(t.isFreeze){let e=rN()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;i=t.renderFreezeTotal+Math.min(e,5e3),r=t.freezeTimeline.length}else i=t.renderFreezeTotal;return{renderFreeze:i,count:r}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},dG=Tb(Rb(),1),uG=[1,0,0,0,1,1,0,1],hG=class extends NF{constructor(e,t){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:t}),e instanceof GF)try{this.setTexBuffer(uG)}catch(Xk){e.destroy(new Vb({code:Lb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(Xk.message||Xk)}))}}draw2d(e,t,i,r,n){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let o=super.draw2d(e,t,i,r,n);return this.ctx2d.restore(),o}return!1}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}},pG=class{constructor(e,t){this.node=e,this.layout=t,yb(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}},mG=class extends NF{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),yb(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new pG(e,t);this.inputs[t.zIndex]=i}resize(e,t){let i=this.inputs.reduce(((e,t)=>t?Object.assign(e,{width:Math.max(e.width,t.right),height:Math.max(e.height,t.bottom)}):e),{width:0,height:0});super.resize(i.width,i.height),this.context instanceof GF&&this.inputs.forEach((e=>{if(e){let t=this.layout2texCoords(e);e.positionBuffer?this.changeBufferData(e.positionBuffer,t):e.positionBuffer=this.createBuffer(t)}}))}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return super.connect(e,...i),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex((t=>(null==t?void 0:t.node)===e))]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&(t.node.useTexture(),this.draw(t.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&this.draw2d(t.node.image,t.x,t.y,t.width,t.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:i,width:r,height:n,name:o}=this,s=Date.now(),a=(e-this.lastInfo.totalFrames)/((s-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:i,width:r,height:n,timestamp:s,fps:a,name:o},_b({parent:this.inputs.filter((e=>e)).map((e=>e.node.getInfo()))},this.lastInfo)}close(){super.close(),this.inputs.forEach((e=>{var t,i;if(e&&(null==(t=e.node)||t.disconnect(),e.positionBuffer&&this.context instanceof GF))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(YO){}}))}},_G=class{constructor(e,t,i){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:4/3;this.vbMode=e,this.faceDetector=t,this.logger=i,yb(this,"animationState"),yb(this,"originalAspect"),yb(this,"totalOffsetX",0),yb(this,"totalOffsetY",0),yb(this,"defaultScaleRatio",.1),yb(this,"isRecovering",!1),yb(this,"boundaryY",280),yb(this,"lastActionTime",0),yb(this,"restTime",1e3),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.faceDetector),this.originalAspect=r||4/3}addEvent(e,t,i){let r=[{key:570704,error:null!=i?i:t?void 0:11},{key:570705,error:null!=i?i:t?void 0:22}][e-1];r&&(t?iM.addSuccessEvent({key:r.key}):iM.addFailedEvent({key:r.key,error:r.error}))}actionCentering(e){let t=Date.now();if(this.animation(),!this.faceDetector||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;try{let t=this.faceDetector.detectForVideo(e,Date.now());if(t.detections.length<=0)return void this.recoverOriginal(i,r);let n=t.detections[0].boundingBox,o=n.originX,s=n.originY,a=n.width,c=n.height;1===this.vbMode?this.dualStageCropping(i,r,o,s,a,c):2===this.vbMode&&this.movingPortrait(i,r,o,s,a,c)}catch(YO){this.logger.error(YO)}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){if(!this.animationState.current||!this.animationState.target)return this.animationState.current=_b({},e),void(this.animationState.target=_b({},e));let i=this.positionDistance(this.animationState.target,e),r=this.positionDistance(this.animationState.current,e),n=this.animationState.current.cropWidth/t;i>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&r>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=_b({},e),void(this.animationState.target=_b({},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)),KD(this.animationState.current.scaleOffsetX)&&KD(this.animationState.target.scaleOffsetX)&&KD(this.animationState.current.scaleOffsetY)&&KD(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(pb(e.sx-t.sx,2)+pb(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]:.55;if(this.isRecovering)return;let a=this.calculateTargetPosition(i,r,n,o,e,t,s);this.processFacePositionCrop(a,e),n/a.cropWidth>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}},fG=class extends FF{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}),yb(this,"_bgTexture"),yb(this,"_waterMarkTexture"),yb(this,"_lastMaskTexture"),yb(this,"_lastMaskFbo"),yb(this,"_textureValid",!1),yb(this,"_selfieTextureValid",!1),yb(this,"_selfieSegmentation"),yb(this,"wasm"),yb(this,"_prePrograme"),yb(this,"_segmentationMask"),yb(this,"_weixin",!1),yb(this,"_centerFace"),yb(this,"_textureMatrixLocation"),yb(this,"_offsetMatrixLocation"),yb(this,"_enableFaceCentering",!1),yb(this,"_mat4"),t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(t)}catch(JO){e.log.error(JO),e.destroy(new Vb({code:Lb.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(JO.message||JO)}))}}init(e){var t;let i=e.Wasm,r=this.context.ctx;if(this._mat4=e.mat4,this.wasm=new i.AllIn1(r),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,this._enableFaceCentering=null!=(t=e.enableFaceCentering)&&t,e.waterMark){let{x:t,y:i,width:r,height:n}=e.waterMark;this.wasm.setWaterMark(t,i,r,n)}if(e.beautyParams){let{beauty:t,brightness:i,ruddy:r}=e.beautyParams;this.wasm.setBeauty(t,i,r,null==e?void 0:e.width,null==e?void 0:e.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(r.uniform1i(r.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(r.uniform1i(r.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),this._textureMatrixLocation=r.getUniformLocation(this.program,"u_textureMatrix"),r.uniformMatrix4fv(this._textureMatrixLocation,!1,this._mat4.create()),this._offsetMatrixLocation=r.getUniformLocation(this.program,"u_offsetMatrix"),r.uniformMatrix4fv(this._offsetMatrixLocation,!1,this._mat4.create()),r.uniform1i(r.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(r.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(r.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),r.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this._prePrograme,"mask"),1)}this._enableFaceCentering&&(this._centerFace=new _G(this.wasm.vbMode,e.faceDetector,this.context.log))}onPredict(e){var t;let i=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():null==this||this._selfieSegmentation.bindTexture(),i.activeTexture(i.TEXTURE1),null==(t=this._selfieSegmentation)||t.bindTexture2d(e),i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,this._bgTexture||null),i.activeTexture(i.TEXTURE3),i.bindTexture(i.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),i.drawArrays(i.TRIANGLE_STRIP,0,4)}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){var t,i,r,n;let o=this.context.ctx,{image:s}=this;this.tryVideoFrameCallback();let{videoWidth:a,videoHeight:c}=s;if(0===a||0===c||!this.available)return!1;s.width=a,s.height=c;let l=!1;if(this.totalFrames)this._weixin?this.useTexture():null==(t=this._selfieSegmentation)||t.bindTexture(),l=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),l=this._textureValid,this._textureValid=!0}return this.width===a&&this.height===c&&l?o.texSubImage2D(o.TEXTURE_2D,0,0,0,o.RGBA,o.UNSIGNED_BYTE,s):(this.resize(a,c),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,s)),this._weixin&&(o.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(o.activeTexture(o.TEXTURE1),null==(i=this._selfieSegmentation)||i.bindTexture2d(this._segmentationMask),o.bindFramebuffer(o.FRAMEBUFFER,this._lastMaskFbo||null)),o.drawArrays(o.TRIANGLE_STRIP,0,4),null==(r=this._selfieSegmentation)||r.bindTexture(),this._segmentationMask?o.copyTexSubImage2D(o.TEXTURE_2D,0,0,0,0,0,a,c):o.copyTexImage2D(o.TEXTURE_2D,0,o.RGBA,0,0,a,c,0)),this.wasm.vbMode&&(null==(n=this._selfieSegmentation)||n.send(a,c)),this.totalFrames||(o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this._bgTexture||null),o.activeTexture(o.TEXTURE3),o.bindTexture(o.TEXTURE_2D,this._waterMarkTexture||null),o.drawArrays(o.TRIANGLE_STRIP,0,4)),!1}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(e.canvas.width,e.canvas.height,t.sx,t.sy,t.cropWidth,t.cropHeight),i&&2===this.wasm.vbMode)){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,n,o){let s=this.context.ctx,a=this._mat4.create();this._mat4.fromTranslation(a,[i/e,1-(r+o)/t,0]),this._mat4.scale(a,a,[n/e,o/t,1]),s.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),null==(e=this.wasm)||e.close()}},gG=class extends NF{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 }"}),yb(this,"yTextureRef"),yb(this,"uTextureRef"),yb(this,"vTextureRef"),yb(this,"Y"),yb(this,"U"),yb(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)}},EG=[e=>{e.codec="avc1.42e01f"},e=>{delete e.hardwareAcceleration}],TG=(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 vG=0,yG=class{constructor(e){yb(this,"id",vG++),yb(this,"trackDoneOB"),yb(this,"startOB"),yb(this,"stopOB"),yb(this,"decoder"),yb(this,"videoContext"),yb(this,"gop",0),yb(this,"gop_helper",0),yb(this,"waitFirstKeyFrame",!0),yb(this,"startTimestamp",0),yb(this,"startTime",0),yb(this,"startPerformanceTime",0),yb(this,"inputFrameCount",0),yb(this,"decodedFrameCount",0),yb(this,"decodeFrameCount",0),yb(this,"downgradeLevel",0),yb(this,"lastDowngradeTime",0),yb(this,"lastFrameDiff",0),yb(this,"lastDecodeFrameTimestamp",0),yb(this,"config"),yb(this,"gop_before_configure",[]),yb(this,"videoElement"),yb(this,"type","wasm"),yb(this,"goodType"),yb(this,"renderer","2d"),yb(this,"wasmOption"),yb(this,"createDecoder"),yb(this,"_decodeSink"),yb(this,"isReported",!1),yb(this,"track"),yb(this,"stateChangeOB"),yb(this,"failedReason");let{track:t,createDecoder:i}=e;if(this.stateChangeOB=jV(),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=eU(t.availableState,sL.OFF),this.stopOB=jV(),"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),IV(this.stateChangeOB,jU(((e,i)=>(e!==i&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:e,state:i}),i)),"INITIALIZED"),SU(this.stopOB),yF()),this.start()}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=IV(this.pipe(this.track),SU(this.stopOB),wV());IV(t,yF((()=>{this.track.stat.framesDecoded++}),(t=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(t," retryCount: ").concat(e)),iM.addFailedEvent({key:TG(this.type,this.renderer),error:t}),e>4)this.failedReason=t,this.stateChangeOB.next("FAILED");else{if(this.goodType)return void this.start(e);switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":if("webgl"===this.renderer)this.changeRenderer("videoFrame")}this.start(e+1)}}),(()=>{this.track.log.warn("".concat(this.id," decoderOB completed")),iM.addSuccessEvent({key:TG(this.type,this.renderer)}),iM.addSuccessEvent({key:514704})}))),IV(t,yU(1),yF((()=>{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&&!uM()&&(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=rN()}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=>Ib(this,null,(function*(){this._decodeSink=t;let i,r=e.mediaTrack;t.defer((()=>{var t;r&&(e.player.setCanvas(),e.setInputMediaStreamTrack(r)),null==i||i.close(),null==(t=this.videoContext)||t.destroy(),delete this._decodeSink}));let{renderer:n,type:o}=this;e.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(o){case"wasm":i=this.createDecoder(o,this.wasmOption);break;case"webCodecs":for(let e=0;e<=EG.length;e++){let{supported:i}=yield VideoDecoder.isConfigSupported(this.config);if(i)break;if(e===EG.length)return void t.error(3);EG[e](this.config)}i=this.createDecoder(o);break;default:throw new Error("not supported yet")}let r=0;if(i.on("videoFrame",(i=>{this.decodedFrameCount++,r++,(r<=10||r%500==0)&&e.log.debug("frame ".concat(r," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(i.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&("webCodecs"===this.type?this.checkDowngradeByFrameDiff():"wasm"===this.type&&this.checkDowngradeByTimestampDiff(i.timestamp)),t.next(i)})),i.on("error",(i=>{e.log.error(i),t.error("webCodecs"===o?4:8)})),yield i.initialize(this.videoElement),!this._decodeSink)return;if(i.configure(this.config),"wasm"===o&&"webgl"===n){this.videoContext=new GF({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(GF.UNAVAILABLE,(i=>{e.log.error(i),t.error(7)}));let r=new gG(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 jF({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 PF(this.videoContext,{name:"remotePlayer",logger:e.log});r.connect(n),e.source=r,e.player.setCanvas(this.videoContext._canvas,2)}this.decoder=i}catch(KO){e.log.error(KO),t.error("webCodecs"===o?2:6)}}))}},SG=class extends dG.EventEmitter{constructor(e){super(),this.room=e,yb(this,"videoContext"),yb(this,"_glVideoContext"),yb(this,"_2dVideoContext"),yb(this,"destination"),yb(this,"smallVideoContext"),yb(this,"smallDestination"),yb(this,"smallTrackSource"),yb(this,"smallImageSource"),yb(this,"_isMirror",!1),yb(this,"cameraTrack"),yb(this,"cameraNode"),yb(this,"mirrorNode"),yb(this,"mixNode"),yb(this,"screenTrack"),yb(this,"screenNode"),yb(this,"selfModel",!1),yb(this,"blurRadius",3),yb(this,"arTrack"),yb(this,"_enableFaceCentering",!1),yb(this,"Wasm"),yb(this,"waterMarkNode"),yb(this,"_waterMarkOption"),yb(this,"watermarkImageList",[]),yb(this,"_beautyParams"),yb(this,"isUsingArTrack",!1),yb(this,"_isMixScreen",!1),yb(this,"_virtualBackground"),yb(this,"_virtualBackgroundAbortCallback"),yb(this,"virtualBackgroundInstance"),yb(this,"_bgAssetPath"),yb(this,"log",xO.createLogger({id:"vm"})),yb(this,"_faceDetector"),yb(this,"_mat4"),yb(this,"_checkId",0),yb(this,"_use2d",!1),yb(this,"_autoSwitchRenderMode",!0),yb(this,"_selfieSegmentation"),yb(this,"encodePipeline",[]),yb(this,"decodePipeline",[]),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new jF({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 renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode="auto"===e,this._autoSwitchRenderMode)return;let t="2d"===e;this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new jF({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 GF({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on(GF.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(qb){this.emit("error",qb)}}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=hL.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(),hL.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(nO||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(){let e=arguments.length>1?arguments[1]:void 0,t="videoCtxGl"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"videoCtxGl")?512700:512701;e?iM.addFailedEvent({key:t,error:e}):iM.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 GF({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return null==(e=this.smallDestination)?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return null==(e=this.cameraTrack)?void 0:e.mediaTrack}initVirtualBackground(e,t,i){return this._selfieSegmentation=e,this._faceDetector=t,this._mat4=i,this._selfieSegmentation.changeModel()}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 xF(this.smallVideoContext,e,this.log),this.smallVideoContext.on(GF.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;nO&&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._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info("set main output ".concat(o?o.label:"no output track")),this.setSmallVideo(r,e),i.setOutputMediaStreamTrack(o)}catch(JO){this.log.error("set main output failed",JO)}}update(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Ib(this,null,(function*(){var t,i,r;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:n,profile:o}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),16===lO?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof FF?(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 FF?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(n.width,n.height)):e&&this.cameraNode&&this.destination?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new LF(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new fG(this.videoContext,{input:this.initialTrack,width:n.width,height:n.height,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,faceDetector:this._faceDetector,mat4:this._mat4}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=o.frameRate,this._use2d){let e=this.cameraNode;e.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new hG(this.videoContext,this.log)),e=e.connect(this.mirrorNode),e.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new mG(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):null==(t=this.waterMarkNode)||t.resize(n.width,n.height),null==(i=this.waterMarkNode)||i.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),null==(r=this.screenNode)||r.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)}))}changeInput(e){var t,i,r,n;if(e instanceof sV)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof rV)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof JF){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);let t=e.mediaTrack;return e.setOutputMediaStreamTrack(t)}this.log.warn("change unknown input",null==(n=e.mediaTrack)?void 0:n.label)}removeInput(e){var t;e instanceof sV?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof rV?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof JF&&e.source&&e.source.context.destroy()}setCameraTrack(e){return Ib(this,null,(function*(){this.cameraTrack=e,this.update(!0)}))}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return Ib(this,null,(function*(){let i=document.createElement("canvas");t&&e&&(i.height=t,i.width=e);let r=i.getContext("2d");if(!r)throw new Vb({code:Lb.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort(((e,t)=>e.zIndex-t.zIndex)),this.watermarkImageList.forEach((e=>{let{image:t,x:i,y:n,width:o,height:s}=e;r.drawImage(t,i,n,o,s)})),vN(i.toDataURL())}))}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some((t=>t.imageUrl===e.imageUrl&&t.height===e.height&&t.width===e.width&&t.x===e.x&&t.y===e.y&&t.type===e.type&&t.zIndex===e.zIndex))||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==t))),this.watermarkImageList.push(e))}setBeautyParams(e){return Ib(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return Ib(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return Ib(this,null,(function*(){var t,i;let r;try{r=yield vN((null==e?void 0:e.imageElement)||e.imageUrl)}catch(d){throw new Vb({code:Lb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:n=0,y:o=0,width:s=r.width,height:a=r.height,type:c="watermark",zIndex:l=2}=e;this.watermarkImageList.some((e=>e.type===c))?(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==c)),this.pushWaterMarkImageList({x:n,y:o,width:s,height:a,image:r,zIndex:l,type:c,imageUrl:e.imageUrl}),r=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(i=this.cameraTrack)?void 0:i.settings.height),this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(r.width,r.height),this.waterMarkNode.image=r):this.update()):(this.pushWaterMarkImageList({x:n,y:o,width:s,height:a,image:r,zIndex:l,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,((e,t)=>"imageUrl"===e?void 0:t)))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return Ib(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 Ib(this,null,(function*(){var e,t,i;null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let r=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(i=this.cameraTrack)?void 0:i.settings.height);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()}))}setVirtualBackground(e){return Ib(this,null,(function*(){var t;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 vN(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=null!=(t=e.enableFaceCentering)?t:this._enableFaceCentering}else delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;if(this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat((null==e?void 0:e.type)||"",", ").concat(this.blurRadius||"")),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new Vb({code:Lb.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})}))}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return Ib(this,null,(function*(){var e;null!=(e=this.cameraTrack)&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))}))}disableAr(){var e;this.isUsingArTrack=!1,null==(e=this.arTrack)||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new yG(e)}clear(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(e){let{processor:t,type:i}=e;var r;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:i}=e;var r;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}};vb([Fx((function(e){this.log.error("update failed",e)}))],SG.prototype,"update",1);var IG=0,RG=class extends sL{constructor(e){super("room"),yb(this,"seq",++IG),yb(this,"sdkAppId"),yb(this,"userId"),yb(this,"userSig"),yb(this,"privateMapKey"),yb(this,"latencyLevel"),yb(this,"tinyId"),yb(this,"scene"),yb(this,"roomId"),yb(this,"useStringRoomId"),yb(this,"role","anchor"),yb(this,"joinParams",null),yb(this,"localTracks",new Set),yb(this,"enableAutoPlayDialog",!0),yb(this,"autoReceiveAudio",!0),yb(this,"autoReceiveVideo",!0),yb(this,"proxy_ws"),yb(this,"proxy_wt"),yb(this,"proxy_unified"),yb(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}}),yb(this,"keyPointManager"),yb(this,"audioManager"),yb(this,"videoManager"),yb(this,"callDurationCalculator"),yb(this,"badCaseDetector"),yb(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),yb(this,"videoDecodeFallbackType"),yb(this,"smallMode","canvas"),yb(this,"_isUsingCachedSchedule",!1),yb(this,"_log",xO.createLogger({id:"r".concat(this.seq)})),yb(this,"_joinedTimestamp",0),yb(this,"_sdkType"),yb(this,"heartbeatReport"),yb(this,"quality"),yb(this,"enableSEI"),yb(this,"isDestroyed",!1),this.useStringRoomId=!!e.useStringRoomId,qD(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),qD(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),qD(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new sG({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new cG({room:this}),this.badCaseDetector=new lG({room:this}),this.audioManager=new dV(this),this.videoManager=new SG(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(4&e.mediaType)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(2&e.mediaType)return e;return null}getLogger(){return this._log}get isJoining(){return"joining"===this.state.toString()}get isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return Ib(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return Ib(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return Ib(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(JD(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(FD(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?(WB([o,o]),$b("https://".concat(o))):(r&&$b(r),n&&WB(n))}OO.once(MO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:HB.main,sched_back_domain:HB.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return Ib(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return Ib(this,null,(function*(){var e;let t={rtt:(null==(e=this.quality)?void 0:e.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let i of this.quality.downlinkInfo)t.downlinksRTT[i.userId]=i.rtt;return t}))}getRemoteVideoStats(){return Ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"main";return function*(){let i={};return e.remotePublishedUserMap.forEach((e=>{let r="auxiliary"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;i[e.userId]=r.stat})),i}()}))}checkDestroy(){if(this.isDestroyed)throw new Vb({code:Lb.INVALID_OPERATION,message:JP({key:HP.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(WP.INVALID_DESTROY),new Vb({code:Lb.INVALID_OPERATION,message:JP({key:HP.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,OO.emit(MO.ROOM_DESTROY,{room:this})}schedule(e,t){return Ib(this,null,(function*(){var i,r,n,o;let s=rN();try{let{isCached:a,result:c,detailCost:l}=yield BB({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Jb,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(fN(c,{keysToExclude:["username","credential"]}))),a&&OO.once(MO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=_b(_b({},this.scheduleResult),c),KD(null==(i=c.config)?void 0:i.retryCount)&&Yk(c.config.retryCount),JD(null==(r=c.config)?void 0:r.loggerDomain)&&$b(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,OO.emit(MO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:l}),iM.addSuccessEvent({key:521700,cost:rN()-s})}catch(WO){throw iM.addFailedEvent({key:521700,error:WO}),WO}}))}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}},AG=Tb(Rb()),CG=Tb(Ob());function bG(e){var t;let i=[];for(let r=0;r<e.rtp.length;r++){if(["rtx","red","ulpfec"].includes(e.rtp[r].codec))continue;let n=e.fmtp.filter((t=>t.payload===e.rtp[r].payload))[0];i.push({payload:e.rtp[r].payload,codec:e.rtp[r].codec,fmtp:n?n.config:"",rate:e.rtp[r].rate,rtx:"rtx"===(null==(t=e.rtp[r+1])?void 0:t.codec)?e.rtp[r+1].payload:0,rtcpfb:((null==e?void 0:e.rtcpFb)||[]).filter((t=>t.payload===e.rtp[r].payload)).map((e=>{let{type:t,subtype:i}=e;return{id:t,params:i?[i]:[]}}))})}return i}var kG=(e,t)=>Ib(void 0,null,(function*(){var i;let r=GW(e),n={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};n.ice.ufrag=String(r.media[0].iceUfrag),n.ice.password=r.media[0].icePwd||"",r.fingerprint&&(n.dtls.hash=r.fingerprint.type,n.dtls.fingerprint=r.fingerprint.hash,n.dtls.setup=r.setup||""),r.media[0].fingerprint&&(n.dtls.hash=r.media[0].fingerprint.type,n.dtls.fingerprint=r.media[0].fingerprint.hash),n.dtls.setup=r.media[0].setup||"";let o=r.media[0],s=r.media[1];o.ext&&(n.audio.extensions=o.ext.map((e=>({id:e.value,uri:e.uri})))),s.ext&&(n.video.extensions=s.ext.map((e=>({id:e.value,uri:e.uri}))));let a={codec:o.rtp[0].codec,fmtp:o.fmtp[0].config,payload:o.fmtp[0].payload,rate:o.rtp[0].rate,channels:o.rtp[0].encoding,rtcpfb:[],rtx:0};null==(i=o.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:r}=e;if(t===a.payload){let e={id:i,params:[]};r&&e.params.push(r),a.rtcpfb.push(e)}})),n.audio.codecs.push(a);let c=["h264","vp8"];return t&&c.shift(),n.video.codecs=[...bG(s)].filter((e=>c.includes(e.codec.toLocaleLowerCase()))),n.video.decoders=(yield function(){return Ib(this,null,(function*(){let e=new RTCPeerConnection;e.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY});let t=yield e.createOffer();if(!t.sdp)return[];let i=bG(GW(t.sdp).media[0]);return e.close(),i}))}()).filter((e=>["h264","vp8"].includes(e.codec.toLocaleLowerCase()))),n})),DG=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,o=GW(r),s={extmapAllowMixed:"extmap-allow-mixed",groups:o.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},a={candidates:t.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:o.media[0].port,protocol:o.media[0].protocol,type:Sk.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map((e=>({payload:t.audio.codecs[0].payload,type:e.id,subtype:e.params[0]}))),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};return s.media.push(a),[1,2,3].forEach((e=>{s.media.push(NG({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),n&&s.media.push(o.media.find((e=>"dc"===e.mid))),jW(s)},NG=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,isDownlink:o=!1}=e,s={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(t),payloads:"",port:n.media[0].port,protocol:n.media[0].protocol,type:Sk.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(o){let e=i.video.decoders;(!e||0===e.length)&&(e=i.video.codecs),(!e||0===e.length)&&(e=r.video.decoders),e.forEach((e=>{wG(s,e)}))}else{let e=i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264"))),t=i.video.codecs[e]||r.video.codecs[0];wG(s,t)}return s},wG=(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 OG=(e,t,i)=>{let r=CG.default.parse(e);return r.media.forEach(((e,n)=>{var o;if((e.type===Sk.AUDIO||e.type===Sk.VIDEO)&&(function(e){if(!e.rtcpFb)return;let t=[];e.rtcpFb.forEach(((i,r)=>{var n;t.push(i),e.rtcpFb&&(null==(n=e.rtcpFb[r+1])?void 0:n.payload)!==i.payload&&"rrtr"!==i.type&&t.push({payload:i.payload,type:"rrtr"})})),e.rtcpFb=t}(e),function(e){e.type===Sk.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===Sk.AUDIO&&e.fmtp&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))}(e),function(e){let t=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}(e),e.type===Sk.VIDEO))if(n<4)e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach((t=>wG(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=>wG(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")})),CG.default.write(r)},PG=Tb(Rb()),MG=class extends PG.EventEmitter{constructor(e){super(),this.room=e,yb(this,"mainFpsHealth",1),yb(this,"mainBitrateHealth",1),yb(this,"badMainBitrateHealthCount",0),yb(this,"lastEmitBadHealthTime",0),yb(this,"log"),!XN&&Zw&&OO.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(){OO.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};yb(MG,"EVENT_BAD_HEALTH","bad_health");var LG=MG;function xG(e){let{seiMessageList:t,isAudio:i,isMain:r}=e;return new TransformStream({transform(e,n){let o=e;i?audioEncodePipeline.forEach((e=>{o=e({frame:o})})):videoEncodePipeline.forEach((e=>{o=e({frame:o,seiMessageList:t,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:o.data,userId:"",streamType:r?"main":"auxiliary"})}})})),n.enqueue(o)}})}function VG(e,t,i){return new TransformStream({transform(r,n){let o=r;videoDecodePipeline.forEach((r=>{o=r({frame:o,onSEI:i=>{i.forEach((i=>{self.postMessage({type:"sei",seiPayloadType:i.seiPayloadType,data:i.seiPayload.buffer,userId:e,streamType:t})}))},onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:o.data,userId:e,streamType:t})}})})),n.enqueue(o)}})}var UG=(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))(UG||{}),FG=0,BG=!1,HG=new Set,WG=1,GG=class extends AG.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),yb(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),yb(this,"currentState","DISCONNECTED"),yb(this,"_room"),yb(this,"_signalChannel"),yb(this,"_peerConnection",null),yb(this,"_datachannel",null),yb(this,"_enableCustomMessage"),yb(this,"_log"),yb(this,"_downlinkMIDMap",new Map),yb(this,"_downlinkMIDUserIDMap",new Map),yb(this,"_reconnectionTimer",-1),yb(this,"reconnectionCount",0),yb(this,"clientAbility"),yb(this,"_serverAbility",null),yb(this,"addDownlinkQueue",new Set),yb(this,"removeDownlinkQueue",new Set),yb(this,"_parsedAnswer",null),yb(this,"_updateSDPPromise",null),yb(this,"_waitForPCConnectedPromise"),yb(this,"clearConnectTimeout"),yb(this,"_isSDPLogged",!1),yb(this,"enableInsertableStreams",!1),yb(this,"insertableStreamsAbortMap",new Map),yb(this,"receiverRemoteTrackMap",new WeakMap),yb(this,"scriptTransformWorker"),yb(this,"_isRelayTried",!1),yb(this,"_rttOverCount",0),yb(this,"originOffer",null),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=xO.createLogger({id:"spc".concat(WG++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(UM?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((e=>"h264"===e.codec.toLowerCase()))),e}addAbortController(e,t){var i;null==(i=this.insertableStreamsAbortMap.get(e))||i.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find((e=>"vp8"===e.codec.toLowerCase()))),e}get videoCodec(){var e,t;let i=null==(e=this._parsedAnswer)?void 0:e.media[1].rtp.find((e=>["h264","vp8"].includes(e.codec.toLowerCase())));return i?i.codec.toLowerCase():null!=(t=this._serverAbility)&&t.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return null!=(e=this._serverAbility)&&e.video.decoders.find((e=>"h264"===e.codec.toLowerCase()))?"h264":"vp8"}get isUsingH264(){return"h264"===this.videoCodec}get is42001fSupported(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f")))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=GW(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&&!jD(e.ssrcs[0].id)){let n=Number(e.ssrcs[0].id),o=Number(null==(r=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:r.id);switch(t){case 0:i.audioSsrc=n;break;case 1:i.bigVideoSsrc=n,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=n,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=n,i.auxVideoRtxSsrc=o}}})),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(e){let{isAux:t}=e;this.useHWEncoder(!1,t?7:2)}initScriptTransformWorker(){FM&&(this.scriptTransformWorker=function(e){let t=[eV],i=[vH,EH,TH,gH,xG,VG],r="const videoEncodePipeline=[".concat(e.videoEncodePipeline.toString(),"];\n const videoDecodePipeline=[").concat(e.videoDecodePipeline.toString(),"];\n const audioEncodePipeline = [").concat(e.audioEncodePipeline.toString(),"];\n const audioDecodePipeline = [").concat(e.audioDecodePipeline.toString(),"];"),n="(()=>{".concat(t.map((e=>"const ".concat(e.name,"=(()=>").concat(e.toString(),")()"))).join("\n"),"\n").concat(i.map((e=>e.toString())).join("\n"),";(").concat((()=>{let e=[],t=[],i=[];self.onmessage=r=>{"sei"===r.data.type&&(r.data.isMain?(e.push(r.data.data),r.data.small&&i.push(r.data.data)):t.push(r.data.data))},self.onrtctransform=r=>{let{options:n}=r.transformer,o=n.isReceiver?VG(n.userId,n.streamType,n.isAudio):xG({isAudio:n.isAudio,seiMessageList:n.isMain?n.small?i:e:t,isMain:n.isMain});r.transformer.readable.pipeThrough(o).pipeTo(r.transformer.writable)}}),")();").concat(r,"})()"),o=new Blob([n],{type:"text/javascript"}),s=URL.createObjectURL(o),a=new Worker(s);return URL.revokeObjectURL(s),a}({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{"sei"===e.data.type&&this.emit("sei-message",e.data),"dump"===e.data.type&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e)})}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}getPeerConnectionConfig(e){var t;let i={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=null==(t=this._peerConnection)?void 0:t.getConfiguration().encodedInsertableStreams;return PN(r)&&(i.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(i)),i}initialize(e){return Ib(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(),iM.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):"failed"===e&&iM.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var e;let t=(null==(e=this._peerConnection)?void 0:e.signalingState)||"";this._log["closed"===t?"debug":"info"]("signaling state: ".concat(t))},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=e=>this.emit("track",e),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=e=>{let t=new JG(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(Sk.AUDIO,{direction:Sk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_SENDONLY}),i=yield this._peerConnection.createOffer(),this.clientAbility=yield kG(i.sdp,(null==(t=this._room.scheduleResult.config)?void 0:t.remove264FromSDP)||!1),this.originOffer=i,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;e&&(this._log.debug("dtls state: ".concat(e.state)),"connecting"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():"connected"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()))}),iM.addSuccessEvent({key:521707}),this.clientAbility}catch(YO){throw iM.addFailedEvent({key:521707,error:YO}),this._log.error("initialize failed ".concat(YO," \noffer: ").concat(null==i?void 0:i.sdp)),YO}}))}setIceServers(e){return Ib(this,null,(function*(){var t;if(this._peerConnection&&0!==e.length)try{if(this._log.info("setIceServers",JSON.stringify(e)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),null!=(t=this._peerConnection)&&t.localDescription||!this.originOffer)return void this._log.warn("setIceServers already has localDescription or no origin Offer");yield this.setOffer(this.originOffer)}catch(JO){this._log.warn("setIceServers error ",JO)}}))}setPriority(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"high";if(this._peerConnection)try{this._peerConnection.getSenders().forEach((t=>{let i=t.getParameters();i.encodings[0]&&(i.encodings[0].priority=e,i.encodings[0].networkPriority=e,t.setParameters(i).catch((e=>{this._log.warn("setPriority error ",e)})))}))}catch(Xk){this._log.warn("setPriority error ",Xk)}}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Ib(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=rN(),s={type:"answer",sdp:DG({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(s),yield this.waitForPeerConnectionConnected();let a=(null==(r=this._room.scheduleResult.config)?void 0:r.priority)||(null==(n=this._room.joinParams)?void 0:n.priority)||new URLSearchParams(location.search).get("priority");a&&this.setPriority(a),t||iM.addSuccessEvent({key:521703,cost:rN()-o})}catch(KO){let i=KO instanceof Vb&&KO.code===Lb.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(KO),e),this.reset(),!i&&!this.isReconnecting&&(iM.addFailedEvent({key:521703,error:KO}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),KO}}))}reconnect(){return Ib(this,null,(function*(){if(-1===this._reconnectionTimer){if(!this._signalChannel.isConnected)return this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(QH,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=_b({ability:t},e),r=yield this._signalChannel.sendWaitForResponse({command:bW,responseCommand:rW.REBUILD_PEER_CONNECTION_RES,data:i,enableLog:!1});if(0!==r.data.code)throw new Vb({code:r.data.code,message:r.data.message});yield this.connect(r.data.data.ability,!0),iM.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),OO.emit(MO.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(qb){if(!this.isReconnecting)return;if(null!=qb&&qb.message.includes("timeout")){let e=HD(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield IN(e,(e=>{this._reconnectionTimer=e})),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(null==qb?void 0:qb.code," ").concat(qb)),iM.addFailedEvent({key:521704,error:qb}),this.reconnectionCount>=zk()&&this._log.warn("SDK has tried reconnect for ".concat(zk()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")}))}getPeerConnection(){return this._peerConnection}startReconnection(){return Ib(this,null,(function*(){this.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(QH,this.reconnect,this),"RECONNECTING"===this.currentState&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===Kk.CLOSED&&this.startReconnection()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var t;let i=(null==(t=this._peerConnection)?void 0:t.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info("connectionState: ".concat(e.target.connectionState," ICE: ").concat(i," DTLS: ").concat(r)),e.target.connectionState===Kk.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===Kk.FAILED||e.target.connectionState===Kk.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===Kk.CONNECTED||e.target.connectionState===Kk.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),OO.emit(MO.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return Jk;let e=null;return bM()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,CM()&&0!==this._peerConnection.getReceivers().length&&e?e.state:Jk):Jk}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(UG.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return Ib(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(TM(i)){let t=e.get(i.localCandidateId),r=e.get(i.remoteCandidateId);t&&(this._log.info("local candidate: ".concat(t.candidateType," ").concat(t.protocol,":").concat(t.ip||t.address,":").concat(t.port," ").concat(t.networkType||""," ").concat("relay"===t.candidateType?"relayProtocol:".concat(t.relayProtocol):"")),t.networkType&&ND(t.networkType)),r&&this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port));break}}))}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this.currentState)return e();let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new Vb({code:Lb.API_CALL_ABORTED,message:JP({key:HP.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{OO.off(MO.LEAVE_SUCCESS,r,this),this.off(UG.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{n();let e=new Vb({code:Lb.API_CALL_TIMEOUT,message:"connection timeout"});var i;FG+=1,i=this._signalChannel.isConnected,FG>2&&!BG&&0===HG.size&&i&&(this._log.warn("firewall restriction"),BG=!0,this.emit(UG.FIREWALL_RESTRICTION)),t(e)}),dD);this.clearConnectTimeout=()=>{n(),clearTimeout(o),delete this.clearConnectTimeout},OO.on(MO.LEAVE_SUCCESS,r,this),this.on(UG.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 Ib(this,null,(function*(){if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),0===this.addDownlinkQueue.size)try{yield this.updateSDP(),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(Xk){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(Xk)),yield this.startReconnection()}}))}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,userId:i,tinyId:r}=e;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(i," ").concat(JSON.stringify(t)));let n=this._peerConnection.getTransceivers().slice(4).filter((e=>"inactive"===e.direction)).slice(0,3).map((e=>(e.direction=Sk.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=GW(this._peerConnection.remoteDescription.sdp));let o,s,a,c=this._parsedAnswer.media.filter((e=>{var t;return null==(t=e.ssrcs)?void 0:t.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(r)}))}));if(3===c.length)o=c[0],s=c[1],a=c[2];else if(3===n.length)o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[0]))),s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[1]))),a=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[2])));else if(0===n.length){this._peerConnection.addTransceiver(Sk.AUDIO,{direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:Sk.TRANSCEIVER_DIRECTION_RECVONLY}),o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=NG({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:GW(this._peerConnection.localDescription.sdp),isDownlink:!0});s=JSON.parse(JSON.stringify(e)),a=JSON.parse(JSON.stringify(e)),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a)}o.direction=Sk.TRANSCEIVER_DIRECTION_SENDONLY;let l="".concat(r,"-").concat(t.audio);o.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(l)},{id:t.audio,attribute:"msid",value:"".concat(l,"-").concat(Sk.MAIN," ").concat(l,"-audio")}],s.direction=Sk.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(Sk.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(Sk.MAIN," ").concat(l,"-bigvideo")}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=Sk.TRANSCEIVER_DIRECTION_SENDONLY;let d="".concat(l,"-aux");a.ssrcs=[{id:t.auxiliary,attribute:"cname",value:d},{id:t.auxiliary,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Sk.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(Sk.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Sk.VIDEO)}],a.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map((e=>e.mid)).join(" ")),this._downlinkMIDMap.set(i,[o.mid,s.mid,a.mid]),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(s.mid,i),this._downlinkMIDUserIDMap.set(a.mid,i)}removeDownlink(e){return Ib(this,null,(function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(e,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),i=!1;this._peerConnection.getTransceivers().forEach((e=>{null!=t&&t.includes(Number(e.mid))&&(i=!0,e.direction="inactive")})),this._parsedAnswer||(this._parsedAnswer=GW(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((e=>{null!=t&&t.includes(Number(e.mid))&&(i=!0,e.direction="inactive",e.ssrcs=[],e.ssrcGroups=[])})),0===this.removeDownlinkQueue.size&&i&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),null==t||t.forEach((e=>this._downlinkMIDUserIDMap.delete(e))),this._log.info("removeDownlink(".concat(e,") done"))}))}setBandwidth(e){return Ib(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(MM()){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(KO){this._log.error("failed to set bandwidth: ".concat(KO))}}))}setStartBitrate(e,t){var i,r;return!(null==(i=this._peerConnection)||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=GW(this._peerConnection.remoteDescription.sdp)),null==(r=this._parsedAnswer.media[e])||!r.fmtp[0]))&&(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),!0)}setSenderMaxBitrate(e,t){let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),"unlimited"===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,e.setParameters(i)}setBandwidthBySDP(e){let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=GW(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=GW(this._peerConnection.remoteDescription.sdp));let s=ew?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:ew?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:ew?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:ew?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:ew?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:s,limit:ew?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:ew?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:s,limit:ew?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:ew?1e3*n:n}]);let a={type:"offer",sdp:jW(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(jD(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(Zw&&tO<83||zN&&cO(aO,"12.1")||ew&&iw<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=jW(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,r)=>Ib(this,null,(function*(){var n,o;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,i()}catch(s){this._log.error(s),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection(null==(n=this._peerConnection.localDescription)?void 0:n.sdp)," \nnext offer: ").concat(this.filterSDPDirection(null==e?void 0:e.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection(null==(o=this._peerConnection.remoteDescription)?void 0:o.sdp)," \nnext answer: ").concat(this.filterSDPDirection(t))),this._log.warn("offer: ".concat(null==e?void 0:e.sdp)),this._log.warn("answer: ".concat(t)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map((e=>{let{mid:t,currentDirection:i,direction:r,stopped:n}=e;return{mid:t,currentDirection:i,direction:r,stopped:n}}))))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,r(s)}})))),this._updateSDPPromise}setTransceiverDirection(e,t){return Ib(this,null,(function*(){if(!ew||!this._peerConnection||!this._parsedAnswer)return;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let i=this._peerConnection.getTransceivers();t.forEach((t=>{i[t].direction!==e&&(i[t].direction=e)}));for(let r of t){let t=this._parsedAnswer.media[r].direction;e===Ik.INACTIVE&&t===Ik.RECVONLY&&(this._parsedAnswer.media[r].direction=e),e===Ik.SENDONLY&&t===Ik.INACTIVE&&(this._parsedAnswer.media[r].direction=Ik.RECVONLY)}yield this.updateSDP()}))}filterSDPDirection(){return GW(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((e=>e.direction))}setOffer(e){this._log.info("setting offer");let t=OG(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 Ib(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach((i=>{var r;if(i.type===Sk.VIDEO){let n=this._serverAbility.video.codecs.find((t=>t.codec.toLowerCase()===e));n&&(null==(r=i.payloads)||!r.includes(String(n.payload)))&&(i.fmtp=[],i.payloads="",i.rtp=[],i.rtcpFb=[],wG(i,n),t=!0)}})),t&&(this._log.warn("switch video encoder to ".concat(e)),yield this.updateSDP())}))}useHWEncoder(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;return Ib(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];jD(t)?r=this._parsedAnswer.media.slice(1,4):2===t?r.push(this._parsedAnswer.media[1]):3===t?r.push(this._parsedAnswer.media[2]):7===t&&r.push(this._parsedAnswer.media[3]),r.forEach((t=>{var r;if(t.type===Sk.VIDEO){let n;e&&this.is42001fSupported?n=this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f"))):e||(n=this._serverAbility.video.codecs.find((e=>e.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264")))),n&&(null==(r=t.payloads)||!r.includes(String(n.payload)))&&(t.fmtp=[],t.payloads="",t.rtp=[],t.rtcpFb=[],wG(t,n),i=!0)}})),i&&(this._log.warn("use ".concat(e?"hw":"sw"," encoder")),yield this.updateSDP())}))}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),this._waitForPCConnectedPromise=null,this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach((e=>wN(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 Ib(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")),iM.addSuccessEvent({key:r,cost:Date.now()-t})}catch(Yb){this._log.warn("switchRelay ".concat(i," failed"),Yb),iM.addFailedEvent({key:r,error:Yb}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}}))}doSwitchRelay(e){return new Promise(((t,i)=>{let r=setTimeout((()=>{this.stopReconnection(),i(new Error("switch ".concat(e," timeout")))}),1e4);this.startReconnection().then(t,i).finally((()=>clearTimeout(r)))}))}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};vb([qx("reconnect")],GG.prototype,"startReconnection",1),vb([Yx((e=>e.userId))],GG.prototype,"addDownlink",1),vb([Yx((e=>e))],GG.prototype,"removeDownlink",1),vb([Kx(!0)],GG.prototype,"updateSDP",1),vb([zx(521712,!1)],GG.prototype,"setOffer",1),vb([zx(521713,!1)],GG.prototype,"setAnswer",1);var jG=class{constructor(e){yb(this,"tag"),yb(this,"len"),yb(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}},JG=class{constructor(e){yb(this,"tinyId"),yb(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new jG(new Uint8Array(e).slice(i,i+2+2+n).buffer);r.push(o),i+=4+n}r.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},KG=new Set;function qG(){let e=Math.floor(4294967296*Math.random());return KG.has(e)?qG():(KG.add(e),e)}var YG=Tb(Rb()),zG=class extends YG.default{constructor(e){super(),yb(this,"userId"),yb(this,"tinyId"),yb(this,"_sdpSemantics"),yb(this,"_isUplink"),yb(this,"_room"),yb(this,"_log"),yb(this,"_currentState","DISCONNECTED"),yb(this,"_prevTime",-1),yb(this,"_blackSmallVideoDetectionId"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=xO.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(OO.emit(MO.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"))}},XG=new class{constructor(){yb(this,"worker"),yb(this,"callbacks",new Map),yb(this,"_log"),this._log=xO.createLogger({id:"bvd",isLocal:!1})}getWorker(){if(!this.worker){let e=new Blob(['\n const tracks=new Map,blackFramesCount={};let canvas,ctx;const log=(...a)=>postMessage({type:"log",message:"[worker] "+a.join(" ")});function handleAddTrack(e,a){blackFramesCount[e]=0;var t=setInterval(()=>{checkFrameBlack(e).then(a=>{a?(blackFramesCount[e]+=1,log(e+" black frames count: "+blackFramesCount[e]),3<=blackFramesCount[e]&&(postMessage({type:"black",trackId:e}),blackFramesCount[e]=0)):blackFramesCount[e]=0}).catch(a=>{log("Error checking frame:",a)})},1e3);tracks.set(e,{reader:a.getReader(),interval:t})}function handleRemoveTrack(a){blackFramesCount[a]=0;var e,t=tracks.get(a);t&&({reader:t,interval:e}=t,t.cancel(),clearInterval(e),tracks.delete(a))}async function checkFrameBlack(a){var e=tracks.get(a);if(!e)return log("track not found",a),!1;e=e.reader;try{var{done:t,value:r}=await e.read();if(t)return handleRemoveTrack(a),!1;if(!r)return!1;canvas||(canvas=new OffscreenCanvas(r.codedWidth,r.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===r.codedWidth&&canvas.height===r.codedHeight||(canvas.width=r.codedWidth,canvas.height=r.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(r,0,0,canvas.width,canvas.height);var c=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return r.close(),1===c}catch(a){return!1}}function getFrameBlackRatio(a){var e=a.data;let t=0;var r=e.length/4;for(let a=0;a<100;a++){var c=4*Math.floor(Math.random()*r),n=e[c],d=e[1+c],o=e[2+c];0!==e[3+c]&&0===n&&0===d&&0===o&&(t+=1)}return t/100}self.onmessage=a=>{var{type:a,trackId:e,readable:t}=a.data;"addTrack"===a&&handleAddTrack(e,t),"removeTrack"===a&&handleRemoveTrack(e)};\n '],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t)}return this.worker}start(e,t){if(this._log.debug("start detect black video",e.id),uM())try{let i=this.getWorker();if(!i)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:e});return this.callbacks.set(e.id,t),i.onerror=e=>this._log.error("Worker error:",e),i.onmessage=e=>{var t;let{type:i,trackId:r,message:n}=e.data;"black"===i?null==(t=this.callbacks.get(r))||t():"log"===i&&this._log.warn(n)},i.postMessage({type:"addTrack",trackId:e.id,readable:r.readable},[r.readable]),e.id}catch(Xk){return this._log.warn("Failed to start black video detector:",Xk),null}}stop(e){var t;e&&(null==(t=this.worker)||t.postMessage({type:"removeTrack",trackId:e}),this.callbacks.delete(e))}},QG=class extends zG{constructor(e){super(fb(_b({},e),{isUplink:!0})),yb(this,"localMainAudioTrack",null),yb(this,"localMainVideoTrack",null),yb(this,"localAuxAudioTrack",null),yb(this,"localAuxVideoTrack",null),yb(this,"_isPublishingAux",!1),yb(this,"_publishingLocalAudioTrack"),yb(this,"_publishingLocalVideoTrack"),yb(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}),yb(this,"_flag",0),yb(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc:r,smallVideoRtxSsrc:n,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:o||0,auxiliaryRtx:s||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:i}=this,r=Object.keys(t).find((e=>t[e]!==i[e]));if(r){if(!e)return void(this._checkPublishStateTimeoutId=hL.run("timeout",(()=>this.checkPublishState(!0)),{delay:1e4,count:1}));this._log.warn("publish state not matched, ".concat(r," local:").concat(t[r]," server:").concat(i[r]," ").concat(kO()," ").concat(RO())),iM.addCount({key:521e3})}hL.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(kM()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(i=o[2])||!i.track),n.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((e=>{e.track&&(e.track.kind===Sk.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}get publishingState(){let{publishState:e}=this,t=_b({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}get serverPublishState(){return{audio:!!(this.flag&Dk),bigVideo:!!(this.flag&Ck),smallVideo:!!(this.flag&bk),auxVideo:!!(this.flag&kk)}}get muteState(){var e,t,i;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(i=this.localAuxVideoTrack)||!i.muted)}}initialize(){this.installEvents()}close(e){var t;let i=(null==(t=this._peerConnection)?void 0:t.getSenders())||[];for(let r of i)r.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;null!=(e=this.singlePC)&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(t=this.singlePC)||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}onVideoEncodeFailed(e){var t;e&&e.isMediaTrackActive&&"h264"===this.videoCodec&&(this._log.warn("h264 encoder not working"),null!=(t=this.singlePC)&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),this.singlePC.switchVideoEncoder("vp8")))}publish(e){return Ib(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e,o,s,a,c,l,d;if(!t.singlePC)return;t.installEvents(),yield Promise.all([t.singlePC.waitForPeerConnectionConnected(),t.singlePC.waitForReconnected()]);let u,{publishState:h,muteState:p}=t;if(i&&(t._publishingLocalAudioTrack=i,h.audio=!0,p.audio=i.muted),r){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new Vb({code:Lb.NOT_SUPPORTED_H264,message:JP({key:HP.NOT_SUPPORTED_H264ENCODE})});t.singlePC.isUsingH264&&!t.singlePC.isH264EncodeSupported&&t.singlePC.isVP8EncodeSupported&&(t._log.warn("h264 encoder not supported"),yield t.singlePC.switchVideoEncoder("vp8")),XN&&115===Qw()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(Tk))),r.setProfile(Tk),yield r.applyProfile()),t._publishingLocalVideoTrack=r,n?(h.auxVideo=!0,p.auxVideo=r.muted):(h.bigVideo=!0,p.bigVideo=r.muted)}if(t._isPublishingAux=n,r&&!n&&r.small&&(u=t._room.videoManager.smallTrack,h.smallVideo=!0),yield t._signalChannel.sendWaitForResponseWithRetry({command:DW,responseCommand:rW.SPC_PUBLISH_RESULT,data:fb(_b({},t.singlePC.uplinkSSRC),{state:h,muteState:p}),retries:3}),yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:u,isAuxiliary:n}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r){t[n?"localAuxVideoTrack":"localMainVideoTrack"]=r,yield t.singlePC.setDegradationPreference(t._peerConnection.getSenders()[n?3:1],r.contentHint,r.streamType);let{scaleResolutionDownBy:e}=r;yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[n?3:1],e,r.streamType)}i&&(t[n?"localAuxAudioTrack":"localMainAudioTrack"]=i),yield t.singlePC.setBandwidth({audio:(null==(e=t.localMainAudioTrack)?void 0:e.profile.bitrate)||(null==(o=t.localAuxAudioTrack)?void 0:o.profile.bitrate),bigVideo:null==(s=t.localMainVideoTrack)?void 0:s.profile.bitrate,smallVideo:null==(c=null==(a=t.localMainVideoTrack)?void 0:a.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),t.sendMediaSettings(),t.installTrackMuteEvents(i,r),(t._room.preferHW||null!=(d=t._room.scheduleResult.config)&&d.preferHW)&&r&&r.profile.width*r.profile.height>=921600&&t.singlePC.useHWEncoder(!0,n?7:2)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!DM())return;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[],d=(e,t,i)=>{var r;let n=a[t].sender.replaceTrack(i);l.push(t),null!=(r=this.singlePC)&&r.enableInsertableStreams&&n.then((()=>this.createEncodedStreams(a[t].sender,e))),this.initSenderTransform(a[t].sender,e),c.push(n)};s&&d(t.mediaType,0,s),o&&d(i.mediaType,n?3:1,o),null!=i&&i.small&&c.push(this.publishSmall(this._room.videoManager.smallMode,i));let u=this.singlePC.setTransceiverDirection(Ik.SENDONLY,l);return c.push(u),Promise.all(c)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var i,r;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let n=e.createEncodedStreams(),o=new AbortController;null==(i=this.singlePC)||i.addAbortController(e,o),(null!=(r=this.getTrackByMediaType(t))&&r.enableEncodeFrame?n.readable.pipeThrough(new TransformStream({transform:(e,i)=>{var r;let n=this.getTrackByMediaType(t);i.enqueue(null!=(r=this.singlePC)&&r.isUsingH264&&n?n.encodeFrame(e,8===t):e)}}),o):n.readable).pipeTo(n.writable,o).catch((e=>{this._log.debug("encoded stream error",e),"destory"!==e&&this._log.warn(e)}))}initSenderTransform(e,t){if(!(this._peerConnection&&this.singlePC&&this.singlePC.scriptTransformWorker&&FM))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 Ib(this,null,(function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()}))}publishSmall(e){return Ib(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;let n=t._peerConnection.getTransceivers(),{sender:o}=n[2],s=yield t.doPublishSmall(e,i),a="canvas"===e?524700:524701;iM.addSuccessEvent({key:a}),s?(null!=(r=t.singlePC)&&r.enableInsertableStreams&&t.createEncodedStreams(o,8),t.initSenderTransform(o,8),yield t.singlePC.setTransceiverDirection(Ik.SENDONLY,[2]),t.updateMediaSettings(),yield t.doPublishChange(),t._blackSmallVideoDetectionId=XG.start(o.track,(()=>{t._log.warn("small video is black");let i="canvas"===e?524700:524701;iM.addFailedEvent({key:i,error:10002}),XG.stop(t._blackSmallVideoDetectionId)}))):iM.addFailedEvent({key:a,error:10001})}()}))}doPublishSmall(e){return Ib(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=bN(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 Ib(this,null,(function*(){this.singlePC&&(this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Ik.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),XG.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return Ib(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){var e,n;yield Promise.all([null==(e=t.singlePC)?void 0:e.waitForPeerConnectionConnected(),null==(n=t.singlePC)?void 0:n.waitForReconnected()]);let o=r&&r===t.localAuxVideoTrack,s=null==r?void 0:r.outMediaTrack,a=t._peerConnection.getSenders(),c=[];i&&(o?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localMainAudioTrack&&!t.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),s&&(o?(yield a[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=fb(_b({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=fb(_b({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.singlePC.setTransceiverDirection(Ik.INACTIVE,c),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Ib(this,null,(function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:dW,data:t,responseCommand:rW.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:uW,commandDesc:"unpublish",responseCommand:rW.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===Lb.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){var e;this._mediaSettings.videoCodec=(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264";let t=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:i,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:i=this._publishingLocalVideoTrack),xM){if(t&&t.outMediaTrack){let e=t.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*t.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings(),{scaleResolutionDownBy:t}=i;this._mediaSettings.videoWidth=e.width/t||0,this._mediaSettings.videoHeight=e.height/t||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*i.profile.bitrate,i.small&&(this._mediaSettings.smallVideoWidth=i.small.width,this._mediaSettings.smallVideoHeight=i.small.height,this._mediaSettings.smallVideoFps=i.small.frameRate,this._mediaSettings.smallVideoBps=1e3*i.small.bitrate)}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:t}=r;this._mediaSettings.auxVideoWidth=e.width/t||0,this._mediaSettings.auxVideoHeight=e.height/t||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate}}else t&&t.outMediaTrack&&(this._mediaSettings.audioChannel=t.profile.channelCount,this._mediaSettings.audioBps=1e3*t.profile.bitrate,this._mediaSettings.audioFs=t.profile.sampleRate),i&&i.outMediaTrack&&(this._mediaSettings.videoWidth=i.profile.width,this._mediaSettings.videoHeight=i.profile.height,this._mediaSettings.videoFps=i.profile.frameRate,this._mediaSettings.videoBps=1e3*i.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:CW,data:this._mediaSettings,responseCommand:rW.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return Ib(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Sk.AUXILIARY:Sk.MAIN," stream")),kM()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return Ib(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Sk.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),1===n&&null!=(i=this.localMainVideoTrack)&&i.small&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Ik.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Ik.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return Ib(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?Sk.AUXILIARY:Sk.MAIN," stream")),kM()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return Ib(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Sk.AUDIO)yield i[0].sender.replaceTrack(null);else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._room.videoManager.hasSmall&&(yield i[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(Ik.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}replaceTrack(e){return Ib(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!i||0===i.length||!r||i.find((e=>e.track===r)))return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(r.kind," track ").concat(r.id," ").concat(r.label," on ").concat(n?Sk.AUXILIARY:Sk.MAIN," stream")),r.kind===Sk.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===Sk.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0}))}setBandwidth(e){return Ib(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===Sk.AUDIO?e.audio=i:"big"===n?e.bigVideo=i:"small"===n?e.smallVideo=i:e.auxVideo=i,yield t.singlePC.setBandwidth(e)}}()}))}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:cW,responseCommand:rW.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&OO.emit(MO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Sk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Sk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Sk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Sk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Sk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===nD?(this._log.error(WP.NOT_SUPPORTED_H264ENCODE),new Vb({code:Lb.NOT_SUPPORTED_H264,message:JP({key:HP.NOT_SUPPORTED_H264ENCODE})})):new Vb({code:Lb.UNKNOWN,message:JP({key:HP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:rW.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return Ib(this,null,(function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))}))}};vb([Ux((function(e){let{localVideoTrack:t}=e;null==t||t.once("6",this.onVideoEncodeFailed,this)}))],QG.prototype,"publish",1),vb([Ux((function(e){let{localVideoTrack:t}=e;null==t||t.off("6",this.onVideoEncodeFailed,this)}))],QG.prototype,"unpublish",1);var ZG=QG;function $G(e){return Object.keys(e).filter((t=>e[t]))}var ej=class extends zG{constructor(e){super(fb(_b({},e),{isUplink:!1})),yb(this,"_flag",0),yb(this,"isRobot",!1),yb(this,"role","anchor"),yb(this,"remoteAudioTrack"),yb(this,"remoteVideoTrack"),yb(this,"remoteAuxiliaryTrack"),yb(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),yb(this,"jitterBufferTimeoutId",-1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new bF(this._room,this),this.remoteVideoTrack=new JF(this._room,this),this.remoteAuxiliaryTrack=new KF(this._room,this),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.downlinkVideoCodec)||"h264"}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return cN(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===Sk.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){var t,i;let r=e.streams[0],{track:n,receiver:o}=e;if(!r.id.includes(this.tinyId))return;let s=r.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(s," ").concat(n.kind));let a=Sk.AUDIO;n.kind===Sk.VIDEO&&(a=s===Sk.MAIN?Sk.VIDEO:Sk.AUXILIARY);let c=this.remoteAudioTrack;a===Sk.VIDEO?c=this.remoteVideoTrack:a===Sk.AUXILIARY&&(c=this.remoteAuxiliaryTrack),null==(t=this.singlePC)||t.receiverRemoteTrackMap.set(o,c),null!=(i=this.singlePC)&&i.scriptTransformWorker&&this.initReceiverTransform(o,s,n.kind===Sk.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(o),c.setInputMediaStreamTrack(n)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),i=new AbortController,r={abortController:i,enqueue:t=>{var i,r;let n=null==(i=this.singlePC)?void 0:i.receiverRemoteTrackMap.get(e);return n&&("video"!==n.kind||null!=(r=this.singlePC)&&r.isUsingH264)?n.decodeFrame(t):t}};t.readable.pipeThrough(new TransformStream({transform:(e,t)=>{let i=r.enqueue(e);i&&t.enqueue(i)}})).pipeTo(t.writable,i).catch((e=>{"destory"!==e&&this._log.warn(e)})),this.singlePC.addAbortController(e,i)}}initReceiverTransform(e,t,i){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:i,userId:this.userId,streamType:t}))}subscribe(e,t){return Ib(this,null,(function*(){try{if(this._log.info("subscribe ".concat(t," ").concat($G(e))),this.hasSSRC){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e);if(e.smallVideo){let{user:e,mediaTrack:t}=this.remoteVideoTrack;iM.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=XG.start(t,(()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,e),iM.addFailedEvent({key:524702}),XG.stop(this._blackSmallVideoDetectionId)}))}else XG.stop(this._blackSmallVideoDetectionId)}catch(JO){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(JO.message," ").concat(JSON.stringify(this.muteState))),new Vb({code:Lb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):JO}}))}checkTrackEnded(e){var t,i,r;if((e.audio&&"ended"===(null==(t=this.remoteAudioTrack.mediaTrack)?void 0:t.readyState)||e.video&&"ended"===(null==(i=this.remoteVideoTrack.mediaTrack)?void 0:i.readyState)||e.auxiliary&&"ended"===(null==(r=this.remoteAuxiliaryTrack.mediaTrack)?void 0:r.readState))&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Zw&&tO<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return Ib(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:r}=e;return function*(){var e;if("main"===r&&!t.isMainStreamSubscribed||"auxiliary"===r&&!t.isAuxStreamSubscribed)return void t._log.info("".concat(r," stream already unsubscribed"));let n=_b({},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($G(n),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,n),"main"===r&&(XG.stop(t._blackSmallVideoDetectionId),t._blackSmallVideoDetectionId=void 0),"unsubscribe"===o&&(yield t.removeDownlink())}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=pW,n=rW.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=mW,n=rW.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:r,data:i,responseCommand:n,timeout:1e4,retries:3}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new Vb({code:i.code,message:JP({key:HP.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 Ib(this,null,(function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())}))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return Ib(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected();try{if(i||!e.hasSSRC){let i={audioSsrc:qG(),bigVideoSsrc:qG(),bigVideoRtxSsrc:qG(),auxVideoSsrc:qG(),auxVideoRtxSsrc:qG()},{audioSsrc:r,bigVideoSsrc:n,bigVideoRtxSsrc:o,auxVideoSsrc:s,auxVideoRtxSsrc:a}=i;e.ssrc={audio:r,video:n,videoRtx:o,auxiliary:s,auxiliaryRtx:a},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let r=yield e._signalChannel.sendWaitForResponseWithRetry({command:NW,responseCommand:rW.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!1,ssrc:i},retries:3,retryTimeout:0});if(0!==r.data.code)throw new Vb({code:r.data.code,message:r.data.message})}catch(KP){throw yield e.removeDownlink(),KP}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}finally{if(!XM)return;let{main:t,aux:i}=e._room.jitterBufferDelay||{},{jitterDelay:r=t,jitterDelayAux:n=i}=e._room.scheduleResult.config||{};(KD(r)||KD(n))&&e.setJitterBufferDelay({mainDelay:r,auxDelay:n})}}}()}))}removeDownlink(){return Ib(this,null,(function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(null!=e&&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(!XM||!this.singlePC||!this._peerConnection||ON(t)&&ON(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return KD(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),KD(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,ON(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||ON(t)&&e.track===this.remoteAudioTrack.outMediaTrack;if(n&&ON(i)||!n&&ON(t))return;let o=n?i||0:t,s=(e.jitterBufferTarget||0)+100;s>o||(e.jitterBufferTarget=s,this._log.debug("set ".concat(n?"aux ":"").concat(null==(r=null==e?void 0:e.track)?void 0:r.kind," jitterBuffer delay ").concat(s," -> ").concat(o)))})),!r.find((e=>{let r=e.track===this.remoteAuxiliaryTrack.outMediaTrack?i||0:t;return e.jitterBufferTarget<r})))return this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i," done")),n();this.jitterBufferTimeoutId=setTimeout((()=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:n})}),1e3)}catch(Yb){this._log.warn("set jitterBuffer delay error: ".concat(Yb)),clearTimeout(this.jitterBufferTimeoutId),n()}}get audioReceiver(){var e;return(null==(e=this.singlePC)?void 0:e.getReceiversByUserId(this.userId)[0])||null}};vb([Kx(),Bx((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this.off("closed",n),r(new Vb({code:Lb.API_CALL_ABORTED,message:JP({key:HP.CONNECTION_ABORTED,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],ej.prototype,"subscribe",1),vb([Kx()],ej.prototype,"unsubscribe",1),vb([Yx((()=>"jitter"))],ej.prototype,"setJitterBufferDelay",1);var tj=ej;var ij=Tb(Rb());var rj=class e extends ij.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,yb(this,"log"),yb(this,"cmdIdSeqMap",new Map),yb(this,"messageMap",new Map),this.log=xO.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(rW.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",(e=>{[...this.messageMap.keys()].forEach((t=>{t.split("_").slice(0,-1).join("_")===e&&this.messageMap.delete(t)}))}))}send(e){let{cmdId:t,data:i}=e,r=this.cmdIdSeqMap.get(t)||Math.floor(16383*Math.random()),n={cmdId:t,msg:btoa(String.fromCharCode(...new Uint8Array(i))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(t,r+1),this.signalChannel.send(PW,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),IN(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)}};yb(rj,"SEQ_INTERVAL",300);var nj,oj=rj,{isString:sj,isUndefined:aj,getNetworkType:cj,isEmpty:lj}=Wb,dj=class extends RG{constructor(e){super(e),yb(this,"_businessInfo"),yb(this,"userManager"),yb(this,"_version"),yb(this,"_heartbeat",-1),yb(this,"_lastHeartBeatTime",-1),yb(this,"_stats"),yb(this,"_joinTimeout",-1),yb(this,"_firstPublishedList",null),yb(this,"_joinReject",null),yb(this,"_isRelayChanged",!1),yb(this,"sdpSemantics"),yb(this,"signalChannel",null),yb(this,"uplinkConnection",null),yb(this,"singlePC",null),yb(this,"enableSPC",NM),yb(this,"_changeBigSmallRecords",new Map),yb(this,"networkQuality"),yb(this,"_iceTransportPolicy"),yb(this,"forceRelay",!1),yb(this,"_turnServers",[]),yb(this,"_iceServersFromJoin"),yb(this,"_syncUserListInterval",-1),yb(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),yb(this,"enableSEI",!1),yb(this,"_enableAudioVolumeEvaluation",!1),yb(this,"_audioVolumeIntervalId",0),yb(this,"_enableMultiAuxStream",!1),yb(this,"_pureAudioPushMode",!1),yb(this,"_customMessageManager"),yb(this,"preferHW",!1),yb(this,"healthDetector"),yb(this,"playoutDelay"),yb(this,"jitterBufferDelay"),yb(this,"_updateAudioLevelTaskId",-1),this._stats=new QW(this,this._log),this.userManager=new ZF(this.userId,this._log),this._version=Jb,this.sdpSemantics=rD,aj(e.sdpSemantics)?FO.isUnifiedPlanDefault()&&(this.sdpSemantics=iD):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(cj())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!aj(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&NM,!aj(e.enableSPC)&&NM&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new LG(this)}get isMainStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex((e=>e.muteState.hasAuxiliary))>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,i){return Ib(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",(e=>{this.emit("peer-join",e)})),this.userManager.on("2",(e=>{this.closeDownLinkConnection(e,"remote user exitRoom"),this.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(e=>{var t=((e,t)=>{var i={};for(var r in e)db.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&cb)for(var r of cb(e))t.indexOf(r)<0&&ub.call(e,r)&&(i[r]=e[r]);return i})(e,[]);OO.emit(MO.REMOTE_PUBLISH_STATE_CHANGED,_b({room:this},t)),this.emit("remote-publish-state-changed",_b({},t))})),this.joinParams=e,new Promise(((t,i)=>Ib(this,null,(function*(){var r,n;this._joinReject=i;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(KP){if(!(KP instanceof Vb&&KP.code===Lb.SPC_INITIALIZED_FAILED))return i(KP);null==(r=this.signalChannel)||r.destroy(),yield this.initialize()}let o=rN();yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),iM.addSuccessEvent({key:521708,cost:rN()-o}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(WO){iM.addFailedEvent({key:521708,error:WO}),i(WO)}this._joinReject=null}))))}))}initSinglePC(){return Ib(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new GG({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",(e=>this.emit("sei-message",e))),this.singlePC.on("dump",(e=>this.emit("dump",e))),this.singlePC.once("error",(()=>this.fallbackToMPC()));try{return yield this.singlePC.initialize()}catch(qb){throw this.fallbackToMPC(),new Vb({code:Lb.SPC_INITIALIZED_FAILED,message:null==qb?void 0:qb.message})}}}))}doJoin(e,t){return new Promise(((i,r)=>Ib(this,null,(function*(){var n,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once($H,(e=>{this.clearJoinTimeout(),OO.emit(MO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)})),qD(null==(o=null==(n=this.scheduleResult)?void 0:n.config)?void 0:o.singlePC)&&NM&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let a={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:"live"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:DO(),netType:wD(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;null!=(s=this.scheduleResult.config)&&s.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{r(new Vb({code:Lb.JOIN_ROOM_FAILED,message:JP({key:HP.JOIN_ROOM_TIMEOUT})}))}),c),OO.emit(MO.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?kW:oW,a),this.signalChannel.once(rW.JOIN_ROOM_RESULT,(t=>Ib(this,null,(function*(){this.clearJoinTimeout();let{code:n,message:o,data:s,tinyId:a}=t.data;OO.emit(MO.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(fb(_b({},s.ability),{useVp8:s.ability.useVp8||!!e.useVp8})).catch((()=>{}))})),i()):(this._log.error("Join room failed result: ".concat(n," error: ").concat(o)),r(new Vb({code:Lb.JOIN_ROOM_FAILED,extraCode:n,message:JP({key:HP.JOIN_ROOM_FAILED,data:{error:o,code:n}})})))}))))}))))}reJoin(){return Ib(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(fb(_b({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),EL.logSuccessEvent({userId:this.userId,eventType:Zk.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(UG.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof ZG&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(UG.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof XW&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(qb){this._log.warn("reJoin fail ".concat(qb)),this.reset(),EL.logFailedEvent({userId:this.userId,eventType:Zk.REJOIN,error:qb}),this.emit("error",new Vb({code:Lb.JOIN_ROOM_FAILED,message:JP({key:HP.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return Ib(this,null,(function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this.signalChannel||function(e){let t=[...MW.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);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 LW({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 oj(this,this.signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this.networkQuality||(this.networkQuality=new tG({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(tG.EVENT_NETWORK_QUALITY,(e=>{var t;this.emit("network-quality",e),null==(t=this.singlePC)||t.detectTCPAndUDP(e)}))),fL(this,this.signalChannel).add(XH,(e=>{OO.emit(MO.SIGNAL_CONNECTION_STATE_CHANGED,_b({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(ZH,(e=>{this.reset(),this.emit("error",e)})).add(rW.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})).add(rW.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(rW.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(rW.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(EL.uploadEvent({log:"stat-banned:".concat(i),userId:this.userId}),"user_time_out"===i)return this._log.warn("".concat(i," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log["kick"===i?"error":"info"]("user was banned because of [".concat(i,"]")),this.reset(),this.emit("banned",{reason:i})})),this.signalChannel.once(zH,(e=>{this.tinyId=e.signalInfo.tinyId,OO.emit(MO.JOIN_SIGNAL_CONNECTION_END,{room:this})})),OO.emit(MO.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&OO.emit(MO.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this.signalChannel=e,e||gL(this)}leave(){return Ib(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(Xk){}this._log.info("leave() => leaving room"),OO.emit(MO.LEAVE_SEND_CMD,{room:this}),null==(e=this.signalChannel)||e.send(sW)}))}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=hL.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),hL.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return Ib(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});this.badCaseDetector.resetMonitor();let r=null!=(e=this.signalChannel)&&e.isConnected?function(e){if(qF.has(e)){let t=qF.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 qF.delete(e),t}return[]}(this.userId):[],n=fb(_b({str_sdk_version:jb,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i),{msg_device_info:_b({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:wD()},i.msg_device_info)});if(this.heartbeatReport=n,OO.emit(MO.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(aW,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",fb(_b({},n),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter((e=>e.flag!==Pk)).map((e=>{let{userId:t,srcTinyId:i,flag:r}=e;t===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=r);let n=this.remotePublishedUserMap.get(t);return n&&this.checkSubscribeBigSmallVideo(n),{userId:t,tinyId:i,flag:r}}));e.data.mixRobotList.forEach((e=>{let{userId:i,srcTinyId:r,flag:n,mixUserList:o}=e;t.unshift({userId:i,tinyId:r,flag:n,isRobot:!0,mixUserList:o})})),OO.emit(MO.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof XW&&(this.uplinkConnection=null)),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r,isRobot:n}=e,o=new(this.singlePC?tj:qW)({userId:t,tinyId:i,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:n});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,t),this.emit("remote-published",o)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",(e=>{let i=e.getCode();i!==Lb.ICE_TRANSPORT_ERROR&&(i===Lb.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",fb(_b({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=hL.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){hL.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:RW,responseCommand:rW.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((e=>{let{data:t}=e,{code:i,message:r}=t;if(0===i)return(t.data&&t.data.userList||[]).map((e=>{let{userId:t,srcTinyId:i,role:r}=e;return{userId:t,tinyId:i,role:r}}));throw JP({key:HP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:rW.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||!BW)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?(null==(e=this.singlePC.getPeerConnection())?void 0:e.connectionState)===Kk.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof HW&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===Kk.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return Ib(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),EL.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 XW({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 qW({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(e,t.userId),this.remotePublishedUserMap.set(t.userId,e),t.isMainStreamSubscribed&&(yield e.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield e.subscribe(t.subscribeState,"auxiliary"))}}))}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new Vb({code:Lb.INVALID_OPERATION,message:JP({key:HP.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),hL.clearTask(this._audioVolumeIntervalId))}switchRole(e){return Ib(this,null,(function*(){this.role!==e&&("audience"===e&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))}))}doSwitchRole(e){let t={command:AW,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:rW.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(t.data))),this.signalChannel.sendWaitForResponseWithRetry(t).then((t=>{let{code:i,message:r}=t.data;if(0!==i)throw new Vb({code:Lb.SWITCH_ROLE_FAILED,message:JP({key:HP.SWITCH_ROLE_FAILED,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof Vb&&e.getCode()===Lb.API_CALL_TIMEOUT&&(e=new Vb({code:Lb.SWITCH_ROLE_FAILED,message:JP({key:HP.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e}))}publish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Ib(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof $x&&(t instanceof cV?i.audio=t:e.audio=t),t instanceof rV&&(t instanceof sV&&2===t.mediaType?i.video=t:e.video=t)}));let r=lj(e),n=lj(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new ZG({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new XW({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",fb(_b({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==Lb.ICE_TRANSPORT_ERROR&&(t===Lb.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})));let o=t.map((e=>e.kind)).join(",");r||(this._log.info("publish() => main ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:e.audio,localVideoTrack:e.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info("publish() => aux ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:i.audio,localVideoTrack:i.video,isAuxiliary:!0}),this._log.info("aux is published"))}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Ib(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let e={},i={};t.forEach((t=>{!t.mediaTrack||!t.isPublished||(t instanceof $x&&(t instanceof cV?i.audio=t:e.audio=t),t instanceof rV&&(t instanceof sV&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");lj(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),lj(i)||(this._log.info("unpublish() => aux ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(YO){}0===this.localTracks.size&&this.closeUplink("you unpublished")}))}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return this.uplinkConnection&&e.mediaTrack?this.uplinkConnection.removeTrack(e).then((t=>(e.unpublish(),t))):Promise.resolve()}replaceTrack(e){return this.uplinkConnection&&e.mediaTrack&&PM()?this.uplinkConnection.replaceTrack(e).then((t=>{t&&OO.emit(MO.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return Ib(this,null,(function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return Ib(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:Sk.VIDEO,videoType:Sk.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)}))}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Ib(this,null,(function*(){if(t=t.filter((e=>!e.isSubscribed)),0===t.length)return;let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let r=t.find((e=>2===e.mediaType))?"auxiliary":"main";try{let n=_b({},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),OO.emit(MO.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(JW(n),"] prev: [").concat(JW(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());OO.emit(MO.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(Yb){let i=Yb instanceof Vb?Yb.getCode():Lb.UNKNOWN,n=Yb;throw Yb instanceof Vb?i===Lb.REMOTE_STREAM_NOT_EXIST&&(n=new Vb({code:Lb.API_CALL_ABORTED,message:JP({key:HP.API_CALL_ABORTED,data:{message:Yb.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new Vb({code:i,message:JP({key:HP.SUBSCRIBE_FAILED,data:{message:Yb.message,userId:e,streamType:r}})}),this._log.error(n)),n}}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Ib(this,null,(function*(){let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let r=t.find((e=>2===e.mediaType))?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(e," ").concat(r));try{yield i.unsubscribe({remoteTracks:t,streamType:r})}catch(Yb){this._log.warn("unsubscribe() => failed ".concat(Yb))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),OO.emit(MO.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 hL.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),OO.emit(MO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&hL.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=hL.run("intervalInWorker",(()=>{var i;dx.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];null==(i=this.remotePublishedUserMap)||i.forEach((e=>{if(e.muteState.hasAudio){!dx.isRunning&&e.muteState.audioAvailable&&e.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(e):e.remoteAudioTrack.volume=0;let t=Math.floor(100*e.remoteAudioTrack.getAudioLevel());r.push({userId:e.userId,volume:t})}})),this.emit("audio-volume",r)}),{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return Ib(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=hL.run("intervalInWorker",(()=>Ib(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"),hL.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(!LM||!i)return;let r=null==(t=i.getSynchronizationSources()[0])?void 0:t.audioLevel;KD(r)?e.remoteAudioTrack.volume=Math.min(2*r,1):i.getStats().then((t=>{t.forEach((t=>{"inbound-rtp"===t.type&&KD(t.audioLevel)&&(e.remoteAudioTrack.volume=t.audioLevel)}))}))}getLocalAudioStats(){return Ib(this,null,(function*(){var e;let t={};return t[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},null!=(e=this.uplinkConnection)&&e.localMainAudioTrack&&(t[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),t}))}getLocalVideoStats(){return Ib(this,null,(function*(){var e,t;let i={};return i[this.userId]=(null==(t=null==(e=this.uplinkConnection)?void 0:e.localMainVideoTrack)?void 0:t.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},i}))}getTransportStats(){return Ib(this,null,(function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let i=yield this._stats.getReceiverStats(t);e.downlinksRTT[i.userId]=i.rtt}return e}))}getRemoteVideoStats(e){return Ib(this,null,(function*(){let t={};for(let[i,r]of this.remotePublishedUserMap)"main"===e&&r.muteState.hasVideo&&(t[i]=r.remoteVideoTrack.stat),"auxiliary"===e&&r.muteState.hasAuxiliary&&(t[i]=r.remoteAuxiliaryTrack.stat);return t}))}getRemoteAudioStats(){return Ib(this,null,(function*(){let e={};for(let[t,i]of this.remotePublishedUserMap)i.muteState.hasAudio&&(e[t]=i.remoteAudioTrack.stat);return e}))}setTurnServer(e,t){this._log.info("set turn server: ".concat(JSON.stringify(e)," ").concat(t||""));let i=[];Array.isArray(e)?e.forEach((e=>i.push(Wb.getTurnServer(e)))):Wb.isPlainObject(e)&&i.push(Wb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:TW,data:e,timeout:5e3,responseCommand:rW.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:vW,data:e,timeout:5e3,responseCommand:rW.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?_W:gW,data:e,timeout:5e3,responseCommand:t?rW.START_PUBLISH_TENCENT_CDN_RES:rW.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?fW:EW,data:e,timeout:5e3,responseCommand:t?rW.STOP_PUBLISH_TENCENT_CDN_RES:rW.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:yW,data:e,timeout:5e3,responseCommand:rW.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:SW,data:e,timeout:5e3,responseCommand:rW.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:IW,data:e,timeout:5e3,responseCommand:rW.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:wW,data:e,timeout:5e3,responseCommand:rW.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=Wb.getEnv();return t?(e.mainUrl="wss://".concat(t,".rtc.qq.com"),e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl="wss://".concat(this.proxy_unified),e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}getSignalInfo(){var e;return(null==(e=this.signalChannel)?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return Ib(this,null,(function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:r,hasVideo:n}}=e;if(!r&&!n||!t.video&&!t.smallVideo)return;let o=this._changeBigSmallRecords.get(i);if(!o||o.isSubscribing||o.reSubscribeCount<=0)return;let{options:s,reSubscribeCount:a}=o;if(s.video&&t.video||s.smallVideo&&t.smallVideo&&r)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:s.video,smallVideo:s.smallVideo};try{if(!r&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;o.isSubscribing=!0,o.reSubscribeCount=a-1,yield e.subscribe(c,"main"),e.remoteVideoTrack.setMediaType(c.smallVideo?8:4),this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video successfully. count ").concat(vD-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=vD}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(vD-o.reSubscribeCount,". reason: ").concat(l)),o.isSubscribing=!1,0===o.reSubscribeCount&&this._changeBigSmallRecords.delete(i)}}))}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:vD};this._changeBigSmallRecords.set(t.userId,i),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big")),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let r=this.remotePublishedUserMap.get(t.userId);r&&this.checkSubscribeBigSmallVideo(r)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(sj(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!aj(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new Vb({code:Lb.INVALID_PARAMETER,message:JP({key:HP.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(!aj(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new Vb({code:Lb.INVALID_PARAMETER,message:JP({key:HP.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!aj(e.userDefinePushArgs)){if(!(sj(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new Vb({code:Lb.INVALID_PARAMETER,message:JP({key:HP.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}lj(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){return Ib(this,null,(function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&UM)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()}))}sendSignalMessage(e){var t;return this.signalChannel?null==(t=this.signalChannel)?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new Vb({code:Lb.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return null==(e=this.singlePC)?void 0:e.scriptTransformWorker}};return vb([rL(["left",sL.INIT],"joined"),vL({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"),FB(!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())}}),Bx((e=>{let t=new KH;return function(i,r,n){return Ib(this,null,(function*(){let o=String(i.roomId||i.strRoomId);if(this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.userSig=i.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,i.privateMapKey=i.privateMapKey||"",this.isJoined)throw new Vb({code:Lb.INVALID_OPERATION,message:JP({key:HP.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new Vb({code:Lb.INVALID_OPERATION,message:JP({key:HP.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)),OO.emit(MO.JOIN_START,{room:this,roomId:o,params:i});let s=Wb.getEnv();s||(s=uk.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Rk.OLD_CLOUD_LADDER)?s=uk.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Rk.WEBRTC)&&(s=uk.WEBRTC))),EL.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),FO.checkSystemRequirementsInternal().then((e=>{this.checkSystemResult=e,qH.call(this)}));try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Wb.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=Wb.performanceNow(),OO.emit(MO.JOIN_SUCCESS,{room:this}),30===n&&!i.component&&EL.uploadEvent({log:"stat-conv-".concat(Number(_O),"-").concat(location.hostname),userId:this.userId}),t}catch(KO){throw t.delete({room:this,roomId:o}),OO.emit(MO.JOIN_FAILED,{room:this,error:KO}),KO}}))}}))],dj.prototype,"join",1),vb([rL("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Bx((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Ib(this,null,(function*(){OO.emit(MO.LEAVE_START,{room:this}),yield e.call(this,...i),OO.emit(MO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),qx("leave room"),yL({fnName:"publish",validateArgs:!1}),yL({fnName:"unsubscribe",validateArgs:!1})],dj.prototype,"leave",1),vb([Kx(),Bx((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Ib(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"ready"===e.state)),!i.length))return;OO.emit("61",{room:this});let t=e.apply(this,i);return i.forEach((e=>e.publish(this,t))),t}))})),vL({settings:{retries:zk,timeout:e=>HD(e)},onError(e,t,i){var r;null!=(r=e.message)&&r.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error("publish failed: ".concat(e)),i(e),OO.emit(MO.PUBLISH_FAILED,{room:this}))}})],dj.prototype,"publish",1),vb([yL({fnName:"publish"}),(nj="api-call",function(e,t,i){let r=i.value;return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let n=jx.get(this);if(n){let e=n.queue.filter(((e,i)=>{if(0===i)return!0;let r=!0;return e.args.forEach((e=>{t.find((t=>t===e))||(r=!1)})),!r||(e.reject(new Vb({code:Lb.API_CALL_ABORTED,message:nj})),!1)}));n.queue=e}return r.apply(this,t)},i}),Kx(),Bx((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})),Ux((function(){var e,t;0===this.localTracks.size&&bM()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((e=>e.track&&e.replaceTrack(null))))}))],dj.prototype,"unpublish",1),vb([Fx((e=>{if(e.code!==Lb.API_CALL_ABORTED)throw e})),Yx((e=>e.userId))],dj.prototype,"replaceTrack",1),vb([Yx((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),uV(),Bx((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})),vL({settings:{retries:zk,timeout:e=>HD(e)},onError(e,t,i,r){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),i(e),OO.emit(MO.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],dj.prototype,"subscribe",1),vb([yL({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")}))}}),Yx((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],dj.prototype,"unsubscribe",1),JH.create=JH._create.bind(JH,dj),JH}));
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,f=m&&!p.call({1:2},1);h.f=f?function(e){var t=m(this,e);return!!t&&t.enumerable}:p;var _,g,v=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},E=c,T=Function.prototype,y=T.call,S=E&&T.bind.bind(y,y),I=E?S:function(e){return function(){return y.apply(e,arguments)}},A=I,b=A({}.toString),R=A("".slice),C=function(e){return R(b(e),8,-1)},k=s,w=C,D=Object,N=I("".split),O=k((function(){return!D("z").propertyIsEnumerable(0)}))?function(e){return"String"===w(e)?N(e,""):D(e)}:D,P=function(e){return null==e},M=P,L=TypeError,x=function(e){if(M(e))throw new L("Can't call method on "+e);return e},U=O,V=x,B=function(e){return U(V(e))},F="object"==typeof document&&document.all,H=void 0===F&&void 0!==F?function(e){return"function"==typeof e||e===F}:function(e){return"function"==typeof e},W=H,j=function(e){return"object"==typeof e?null!==e:W(e)},G=n,z=H,K=function(e,t){return arguments.length<2?(i=G[e],z(i)?i:void 0):G[e]&&G[e][t];var i},q=I({}.isPrototypeOf),J=n.navigator,Y=J&&J.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=(_=ie.split("."))[0]>0&&_[0]<4?1:+(_[0]+_[1])),!g&&Z&&(!(_=Z.match(/Edge\/(\d+)/))||_[1]>=74)&&(_=Z.match(/Chrome\/(\d+)/))&&(g=+_[1]);var re=g,ne=re,oe=s,se=n.String,ae=!!Object.getOwnPropertySymbols&&!oe((function(){var e=Symbol("symbol detection");return!se(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),ce=ae&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,le=K,de=H,ue=q,he=Object,pe=ce?function(e){return"symbol"==typeof e}:function(e){var t=le("Symbol");return de(t)&&ue(t.prototype,he(e))},me=String,fe=function(e){try{return me(e)}catch(t){return"Object"}},_e=H,ge=fe,ve=TypeError,Ee=function(e){if(_e(e))return e;throw new ve(ge(e)+" is not a function")},Te=Ee,ye=P,Se=function(e,t){var i=e[t];return ye(i)?void 0:Te(i)},Ie=u,Ae=H,be=j,Re=TypeError,Ce={exports:{}},ke=n,we=Object.defineProperty,De=function(e,t){try{we(ke,e,{value:t,configurable:!0,writable:!0})}catch(i){ke[e]=t}return t},Ne=n,Oe=De,Pe="__core-js_shared__",Me=Ce.exports=Ne[Pe]||Oe(Pe,{});(Me.versions||(Me.versions=[])).push({version:"3.40.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.40.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Le=Ce.exports,xe=Le,Ue=function(e,t){return xe[e]||(xe[e]=t||{})},Ve=x,Be=Object,Fe=function(e){return Be(Ve(e))},He=Fe,We=I({}.hasOwnProperty),je=Object.hasOwn||function(e,t){return We(He(e),t)},Ge=I,ze=0,Ke=Math.random(),qe=Ge(1..toString),Je=function(e){return"Symbol("+(void 0===e?"":e)+")_"+qe(++ze+Ke,36)},Ye=Ue,Xe=je,Qe=Je,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=j,st=pe,at=Se,ct=function(e,t){var i,r;if("string"===t&&Ae(i=e.toString)&&!be(r=Ie(i,e)))return r;if(Ae(i=e.valueOf)&&!be(r=Ie(i,e)))return r;if("string"!==t&&Ae(i=e.toString)&&!be(r=Ie(i,e)))return r;throw new Re("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+""},ft=j,_t=n.document,gt=ft(_t)&&ft(_t.createElement),vt=function(e){return gt?_t.createElement(e):{}},Et=vt,Tt=!a&&!s((function(){return 7!==Object.defineProperty(Et("div"),"a",{get:function(){return 7}}).a})),yt=a,St=u,It=h,At=v,bt=B,Rt=mt,Ct=je,kt=Tt,wt=Object.getOwnPropertyDescriptor;o.f=yt?wt:function(e,t){if(e=bt(e),t=Rt(t),kt)try{return wt(e,t)}catch(i){}if(Ct(e,t))return At(!St(It.f,e,t),e[t])};var Dt={},Nt=a&&s((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Ot=j,Pt=String,Mt=TypeError,Lt=function(e){if(Ot(e))return e;throw new Mt(Pt(e)+" is not an object")},xt=a,Ut=Tt,Vt=Nt,Bt=Lt,Ft=mt,Ht=TypeError,Wt=Object.defineProperty,jt=Object.getOwnPropertyDescriptor,Gt="enumerable",zt="configurable",Kt="writable";Dt.f=xt?Vt?function(e,t,i){if(Bt(e),t=Ft(t),Bt(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Kt in i&&!i[Kt]){var r=jt(e,t);r&&r[Kt]&&(e[t]=i.value,i={configurable:zt in i?i[zt]:r[zt],enumerable:Gt in i?i[Gt]:r[Gt],writable:!1})}return Wt(e,t,i)}:Wt:function(e,t,i){if(Bt(e),t=Ft(t),Bt(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 qt=Dt,Jt=v,Yt=a?function(e,t,i){return qt.f(e,t,Jt(1,i))}:function(e,t,i){return e[t]=i,e},Xt={exports:{}},Qt=a,Zt=je,$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=Je,mi=Ue("keys"),fi=function(e){return mi[e]||(mi[e]=pi(e))},_i={},gi=hi,vi=n,Ei=j,Ti=Yt,yi=je,Si=Le,Ii=fi,Ai=_i,bi="Object already initialized",Ri=vi.TypeError,Ci=vi.WeakMap;if(gi||Si.state){var ki=Si.state||(Si.state=new Ci);ki.get=ki.get,ki.has=ki.has,ki.set=ki.set,si=function(e,t){if(ki.has(e))throw new Ri(bi);return t.facade=e,ki.set(e,t),t},ai=function(e){return ki.get(e)||{}},ci=function(e){return ki.has(e)}}else{var wi=Ii("state");Ai[wi]=!0,si=function(e,t){if(yi(e,wi))throw new Ri(bi);return t.facade=e,Ti(e,wi,t),t},ai=function(e){return yi(e,wi)?e[wi]:{}},ci=function(e){return yi(e,wi)}}var Di={set:si,get:ai,has:ci,enforce:function(e){return ci(e)?ai(e):si(e,{})},getterFor:function(e){return function(t){var i;if(!Ei(t)||(i=ai(t)).type!==e)throw new Ri("Incompatible receiver, "+e+" required");return i}}},Ni=I,Oi=s,Pi=H,Mi=je,Li=a,xi=ii.CONFIGURABLE,Ui=li,Vi=Di.enforce,Bi=Di.get,Fi=String,Hi=Object.defineProperty,Wi=Ni("".slice),ji=Ni("".replace),Gi=Ni([].join),zi=Li&&!Oi((function(){return 8!==Hi((function(){}),"length",{value:8}).length})),Ki=String(String).split("String"),qi=Xt.exports=function(e,t,i){"Symbol("===Wi(Fi(t),0,7)&&(t="["+ji(Fi(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=Gi(Ki,"string"==typeof t?t:"")),e};Function.prototype.toString=qi((function(){return Pi(this)&&Bi(this).source||Ui(this)}),"toString");var Ji=Xt.exports,Yi=H,Xi=Dt,Qi=Ji,Zi=De,$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)},fr=B,_r=lr,gr=mr,vr=function(e){return function(t,i,r){var n=fr(t),o=gr(n);if(0===o)return!e&&-1;var s,a=_r(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}},Er={includes:vr(!0),indexOf:vr(!1)},Tr=je,yr=B,Sr=Er.indexOf,Ir=_i,Ar=I([].push),br=function(e,t){var i,r=yr(e),n=0,o=[];for(i in r)!Tr(Ir,i)&&Tr(r,i)&&Ar(o,i);for(;t.length>n;)Tr(r,i=t[n++])&&(~Sr(o,i)||Ar(o,i));return o},Rr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Cr=br,kr=Rr.concat("length","prototype");er.f=Object.getOwnPropertyNames||function(e){return Cr(e,kr)};var wr={};wr.f=Object.getOwnPropertySymbols;var Dr=K,Nr=er,Or=wr,Pr=Lt,Mr=I([].concat),Lr=Dr("Reflect","ownKeys")||function(e){var t=Nr.f(Pr(e)),i=Or.f;return i?Mr(t,i(e)):t},xr=je,Ur=Lr,Vr=o,Br=Dt,Fr=function(e,t,i){for(var r=Ur(t),n=Br.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,jr=/#|\.prototype\./,Gr=function(e,t){var i=Kr[zr(e)];return i===Jr||i!==qr&&(Wr(t)?Hr(t):!!t)},zr=Gr.normalize=function(e){return String(e).replace(jr,".").toLowerCase()},Kr=Gr.data={},qr=Gr.NATIVE="N",Jr=Gr.POLYFILL="P",Yr=Gr,Xr=n,Qr=o.f,Zr=Yt,$r=$i,en=De,tn=Fr,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=C,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,fn=function(e){if("Symbol"===pn(e))throw new TypeError("Cannot convert a Symbol value to a string");return mn(e)},_n=Ji,gn=Dt,vn=function(e,t,i){return i.get&&_n(i.get,t,{getter:!0}),i.set&&_n(i.set,t,{setter:!0}),gn.f(e,t,i)},En=nn,Tn=a,yn=I,Sn=je,In=H,An=q,bn=fn,Rn=vn,Cn=Fr,kn=n.Symbol,wn=kn&&kn.prototype;if(Tn&&In(kn)&&(!("description"in wn)||void 0!==kn().description)){var Dn={},Nn=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:bn(arguments[0]),t=An(wn,this)?new kn(e):void 0===e?kn():kn(e);return""===e&&(Dn[t]=!0),t};Cn(Nn,kn),Nn.prototype=wn,wn.constructor=Nn;var On="Symbol(description detection)"===String(kn("description detection")),Pn=yn(wn.valueOf),Mn=yn(wn.toString),Ln=/^Symbol\((.*)\)[^)]+$/,xn=yn("".replace),Un=yn("".slice);Rn(wn,"description",{configurable:!0,get:function(){var e=Pn(this);if(Sn(Dn,e))return"";var t=Mn(e),i=On?Un(t,7,-1):xn(t,Ln,"$1");return""===i?void 0:i}}),En({global:!0,constructor:!0,forced:!0},{Symbol:Nn})}var Vn={},Bn=br,Fn=Rr,Hn=Object.keys||function(e){return Bn(e,Fn)},Wn=a,jn=Nt,Gn=Dt,zn=Lt,Kn=B,qn=Hn;Vn.f=Wn&&!jn?Object.defineProperties:function(e,t){zn(e);for(var i,r=Kn(t),n=qn(t),o=n.length,s=0;o>s;)Gn.f(e,i=n[s++],r[i]);return e};var Jn,Yn=K("document","documentElement"),Xn=Lt,Qn=Vn,Zn=Rr,$n=_i,eo=Yn,to=vt,io="prototype",ro="script",no=fi("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{Jn=new ActiveXObject("htmlfile")}catch(t){}co="undefined"!=typeof document?document.domain&&Jn?ao(Jn):function(){var e,t=to("iframe"),i="java"+ro+":";return 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(Jn);for(var e=Zn.length;e--;)delete co[io][Zn[e]];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=Dt.f,mo=uo("unscopables"),fo=Array.prototype;void 0===fo[mo]&&po(fo,mo,{configurable:!0,value:ho(null)});var _o=function(e){fo[mo][e]=!0},go=Er.includes,vo=_o;nn({target:"Array",proto:!0,forced:s((function(){return!Array(1).includes()}))},{includes:function(e){return go(this,e,arguments.length>1?arguments[1]:void 0)}}),vo("includes");var Eo,To,yo,So={},Io=!s((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Ao=je,bo=H,Ro=Fe,Co=Io,ko=fi("IE_PROTO"),wo=Object,Do=wo.prototype,No=Co?wo.getPrototypeOf:function(e){var t=Ro(e);if(Ao(t,ko))return t[ko];var i=t.constructor;return bo(i)&&t instanceof i?i.prototype:t instanceof wo?Do:null},Oo=s,Po=H,Mo=j,Lo=No,xo=$i,Uo=rt("iterator"),Vo=!1;[].keys&&("next"in(yo=[].keys())?(To=Lo(Lo(yo)))!==Object.prototype&&(Eo=To):Vo=!0);var Bo=!Mo(Eo)||Oo((function(){var e={};return Eo[Uo].call(e)!==e}));Bo&&(Eo={}),Po(Eo[Uo])||xo(Eo,Uo,(function(){return this}));var Fo={IteratorPrototype:Eo,BUGGY_SAFARI_ITERATORS:Vo},Ho=Dt.f,Wo=je,jo=rt("toStringTag"),Go=function(e,t,i){e&&!i&&(e=e.prototype),e&&!Wo(e,jo)&&Ho(e,jo,{configurable:!0,value:t})},zo=Fo.IteratorPrototype,Ko=lo,qo=v,Jo=Go,Yo=So,Xo=function(){return this},Qo=function(e,t,i,r){var n=t+" Iterator";return e.prototype=Ko(zo,{next:qo(+!r,i)}),Jo(e,n,!1),Yo[n]=Xo,e},Zo=I,$o=Ee,es=j,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=j,ss=x,as=function(e){if(ts(e))return e;throw new rs("Can't set "+is(e)+" as a prototype")},cs=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=ns(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return ss(i),as(r),os(i)?(t?e(i,r):i.__proto__=r,i):i}}():void 0),ls=nn,ds=u,us=H,hs=Qo,ps=No,ms=cs,fs=Go,_s=Yt,gs=$i,vs=So,Es=ii.PROPER,Ts=ii.CONFIGURABLE,ys=Fo.IteratorPrototype,Ss=Fo.BUGGY_SAFARI_ITERATORS,Is=rt("iterator"),As="keys",bs="values",Rs="entries",Cs=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&&f)return f;if(!Ss&&e&&e in p)return p[e];switch(e){case As:case bs:case Rs: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],f=!Ss&&m||d(n),_="Array"===t&&p.entries||m;if(_&&(a=ps(_.call(new e)))!==Object.prototype&&a.next&&(ps(a)!==ys&&(ms?ms(a,ys):us(a[Is])||gs(a,Is,Cs)),fs(a,u,!0)),Es&&n===bs&&m&&m.name!==bs&&(Ts?_s(p,"name",bs):(h=!0,f=function(){return ds(m,this)})),n)if(c={values:d(bs),keys:o?f:d(As),entries:d(Rs)},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]!==f&&gs(p,Is,f,{name:n}),vs[t]=f,c},ws=function(e,t){return{value:e,done:t}},Ds=B,Ns=_o,Os=So,Ps=Di,Ms=Dt.f,Ls=ks,xs=ws,Us=a,Vs="Array Iterator",Bs=Ps.set,Fs=Ps.getterFor(Vs),Hs=Ls(Array,"Array",(function(e,t){Bs(this,{type:Vs,target:Ds(e),index:0,kind:t})}),(function(){var e=Fs(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,xs(void 0,!0);switch(e.kind){case"keys":return xs(i,!1);case"values":return xs(t[i],!1)}return xs([i,t[i]],!1)}),"values"),Ws=Os.Arguments=Os.Array;if(Ns("keys"),Ns("values"),Ns("entries"),Us&&"values"!==Ws.name)try{Ms(Ws,"name",{value:"values"})}catch(Hz){}var js=Ee,Gs=Fe,zs=O,Ks=mr,qs=TypeError,Js="Reduce of empty array with no initial value",Ys=function(e){return function(t,i,r,n){var o=Gs(t),s=zs(o),a=Ks(o);if(js(i),0===a&&r<2)throw new qs(Js);var c=e?a-1:0,l=e?-1:1;if(r<2)for(;;){if(c in s){n=s[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw new qs(Js)}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=C,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=C,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=fe,ma=TypeError,fa=I([].slice),_a=fa,ga=Math.floor,va=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=va(_a(e,0,s),t),c=va(_a(e,s),t),l=a.length,d=c.length,u=0,h=0;u<l||h<d;)e[u+h]=u<l&&h<d?t(a[u],c[h])<=0?a[u++]:c[h++]:u<l?a[u++]:c[h++];return e},Ea=va,Ta=X.match(/firefox\/(\d+)/i),ya=!!Ta&&+Ta[1],Sa=/MSIE|Trident/.test(X),Ia=X.match(/AppleWebKit\/(\d+)\./),Aa=!!Ia&&+Ia[1],ba=nn,Ra=I,Ca=Ee,ka=Fe,wa=mr,Da=function(e,t){if(!delete e[t])throw new ma("Cannot delete property "+pa(t)+" of "+pa(e))},Na=fn,Oa=s,Pa=Ea,Ma=Zs,La=ya,xa=Sa,Ua=re,Va=Aa,Ba=[],Fa=Ra(Ba.sort),Ha=Ra(Ba.push),Wa=Oa((function(){Ba.sort(void 0)})),ja=Oa((function(){Ba.sort(null)})),Ga=Ma("sort"),za=!Oa((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++)Ba.push({k:t+r,v:i})}for(Ba.sort((function(e,t){return t.v-e.v})),r=0;r<Ba.length;r++)t=Ba[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));ba({target:"Array",proto:!0,forced:Wa||!ja||!Ga||!za},{sort:function(e){void 0!==e&&Ca(e);var t=ka(this);if(za)return void 0===e?Fa(t):Fa(t,e);var i,r,n=[],o=wa(t);for(r=0;r<o;r++)r in t&&Ha(n,t[r]);for(Pa(n,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:Na(t)>Na(i)?1:-1}}(e)),i=wa(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)Da(t,r++);return t}});var Ka="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,qa=$i,Ja=function(e,t,i){for(var r in t)qa(e,r,t[r],i);return e},Ya=q,Xa=TypeError,Qa=function(e,t){if(Ya(t,e))return e;throw new Xa("Incorrect invocation")},Za=or,$a=hr,ec=RangeError,tc=function(e){if(void 0===e)return 0;var t=Za(e),i=$a(t);if(t!==i)throw new ec("Wrong length or index");return i},ic=Math.sign||function(e){var t=+e;return 0===t||t!=t?t:t<0?-1:1},rc=4503599627370496,nc=ic,oc=function(e){return e+rc-rc},sc=Math.abs,ac=function(e,t,i,r){var n=+e,o=sc(n),s=nc(n);if(o<r)return s*oc(o/r/t)*r*t;var a=(1+t/2220446049250313e-31)*o,c=a-(a-o);return c>i||c!=c?Infinity*s:s*c},cc=Math.fround||function(e){return ac(e,1.1920928955078125e-7,34028234663852886e22,11754943508222875e-54)},lc=Array,dc=Math.abs,uc=Math.pow,hc=Math.floor,pc=Math.log,mc=Math.LN2,fc={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)}},_c=Fe,gc=lr,vc=mr,Ec=function(e){for(var t=_c(this),i=vc(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},Tc=H,yc=j,Sc=cs,Ic=function(e,t,i){var r,n;return Sc&&Tc(r=t.constructor)&&r!==i&&yc(n=r.prototype)&&n!==i.prototype&&Sc(e,n),e},Ac=n,bc=I,Rc=a,Cc=Ka,kc=Yt,wc=vn,Dc=Ja,Nc=s,Oc=Qa,Pc=or,Mc=hr,Lc=tc,xc=cc,Uc=fc,Vc=No,Bc=cs,Fc=Ec,Hc=fa,Wc=Ic,jc=Fr,Gc=Go,zc=Di,Kc=ii.PROPER,qc=ii.CONFIGURABLE,Jc="ArrayBuffer",Yc="DataView",Xc="prototype",Qc="Wrong index",Zc=zc.getterFor(Jc),$c=zc.getterFor(Yc),el=zc.set,tl=Ac[Jc],il=tl,rl=il&&il[Xc],nl=Ac[Yc],ol=nl&&nl[Xc],sl=Object.prototype,al=Ac.Array,cl=Ac.RangeError,ll=bc(Fc),dl=bc([].reverse),ul=Uc.pack,hl=Uc.unpack,pl=function(e){return[255&e]},ml=function(e){return[255&e,e>>8&255]},fl=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},_l=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},gl=function(e){return ul(xc(e),23,4)},vl=function(e){return ul(e,52,8)},El=function(e,t,i){wc(e[Xc],t,{configurable:!0,get:function(){return i(this)[t]}})},Tl=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(Cc){var Sl=Kc&&tl.name!==Jc;Nc((function(){tl(1)}))&&Nc((function(){new tl(-1)}))&&!Nc((function(){return new tl,new tl(1.5),new tl(NaN),1!==tl.length||Sl&&!qc}))?Sl&&qc&&kc(tl,"name",Jc):((il=function(e){return Oc(this,rl),Wc(new tl(Lc(e)),this,il)})[Xc]=rl,rl.constructor=il,jc(il,tl)),Bc&&Vc(ol)!==sl&&Bc(ol,sl);var Il=new nl(new il(2)),Al=bc(ol.setInt8);Il.setInt8(0,2147483648),Il.setInt8(1,2147483649),!Il.getInt8(0)&&Il.getInt8(1)||Dc(ol,{setInt8:function(e,t){Al(this,e,t<<24>>24)},setUint8:function(e,t){Al(this,e,t<<24>>24)}},{unsafe:!0})}else rl=(il=function(e){Oc(this,rl);var t=Lc(e);el(this,{type:Jc,bytes:ll(al(t),0),byteLength:t}),Rc||(this.byteLength=t,this.detached=!1)})[Xc],ol=(nl=function(e,t,i){Oc(this,ol),Oc(e,rl);var r=Zc(e),n=r.byteLength,o=Pc(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}),Rc||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[Xc],Rc&&(El(il,"byteLength",Zc),El(nl,"buffer",$c),El(nl,"byteLength",$c),El(nl,"byteOffset",$c)),Dc(ol,{getInt8:function(e){return Tl(this,1,e)[0]<<24>>24},getUint8:function(e){return Tl(this,1,e)[0]},getInt16:function(e){var t=Tl(this,2,e,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=Tl(this,2,e,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return _l(Tl(this,4,e,arguments.length>1&&arguments[1]))},getUint32:function(e){return _l(Tl(this,4,e,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(e){return hl(Tl(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return hl(Tl(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,fl,t,arguments.length>2&&arguments[2])},setUint32:function(e,t){yl(this,4,e,fl,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,vl,t,arguments.length>2&&arguments[2])}});Gc(il,Jc),Gc(nl,Yc);var bl={ArrayBuffer:il,DataView:nl},Rl=K,Cl=vn,kl=a,wl=rt("species"),Dl=function(e){var t=Rl(e);kl&&t&&!t[wl]&&Cl(t,wl,{configurable:!0,get:function(){return this}})},Nl=Dl,Ol="ArrayBuffer",Pl=bl[Ol];nn({global:!0,constructor:!0,forced:n[Ol]!==Pl},{ArrayBuffer:Pl}),Nl(Ol);var Ml=C,Ll=I,xl=function(e){if("Function"===Ml(e))return Ll(e)},Ul=nn,Vl=xl,Bl=s,Fl=Lt,Hl=lr,Wl=hr,jl=bl.ArrayBuffer,Gl=bl.DataView,zl=Gl.prototype,Kl=Vl(jl.prototype.slice),ql=Vl(zl.getUint8),Jl=Vl(zl.setUint8);Ul({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:Bl((function(){return!new jl(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(Kl&&void 0===t)return Kl(Fl(this),e);for(var i=Fl(this).byteLength,r=Hl(e,i),n=Hl(void 0===t?i:t,i),o=new jl(Wl(n-r)),s=new Gl(this),a=new Gl(o),c=0;r<n;)Jl(a,c++,ql(s,r++));return o}});var Yl=I,Xl=s,Ql=H,Zl=hn,$l=li,ed=function(){},td=K("Reflect","construct"),id=/^\s*(?:class|function)\b/,rd=Yl(id.exec),nd=!id.test(ed),od=function(e){if(!Ql(e))return!1;try{return td(ed,[],e),!0}catch(Hz){return!1}},sd=function(e){if(!Ql(e))return!1;switch(Zl(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return nd||!!rd(id,$l(e))}catch(Hz){return!0}};sd.sham=!0;var ad,cd,ld,dd,ud=!td||Xl((function(){var e;return od(od.call)||!od(Object)||!od((function(){e=!0}))||e}))?sd:od,hd=ud,pd=fe,md=TypeError,fd=function(e){if(hd(e))return e;throw new md(pd(e)+" is not a constructor")},_d=Lt,gd=fd,vd=P,Ed=rt("species"),Td=function(e,t){var i,r=_d(e).constructor;return void 0===r||vd(i=_d(r)[Ed])?t:gd(i)},yd=c,Sd=Function.prototype,Id=Sd.apply,Ad=Sd.call,bd="object"==typeof Reflect&&Reflect.apply||(yd?Ad.bind(Id):function(){return Ad.apply(Id,arguments)}),Rd=Ee,Cd=c,kd=xl(xl.bind),wd=function(e,t){return Rd(e),void 0===t?e:Cd?kd(e,t):function(){return e.apply(t,arguments)}},Dd=TypeError,Nd=function(e,t){if(e<t)throw new Dd("Not enough arguments");return e},Od=/(?:ipad|iphone|ipod).*applewebkit/i.test(X),Pd=n,Md=bd,Ld=wd,xd=H,Ud=je,Vd=s,Bd=Yn,Fd=fa,Hd=vt,Wd=Nd,jd=Od,Gd=na,zd=Pd.setImmediate,Kd=Pd.clearImmediate,qd=Pd.process,Jd=Pd.Dispatch,Yd=Pd.Function,Xd=Pd.MessageChannel,Qd=Pd.String,Zd=0,$d={},eu="onreadystatechange";Vd((function(){ad=Pd.location}));var tu=function(e){if(Ud($d,e)){var t=$d[e];delete $d[e],t()}},iu=function(e){return function(){tu(e)}},ru=function(e){tu(e.data)},nu=function(e){Pd.postMessage(Qd(e),ad.protocol+"//"+ad.host)};zd&&Kd||(zd=function(e){Wd(arguments.length,1);var t=xd(e)?e:Yd(e),i=Fd(arguments,1);return $d[++Zd]=function(){Md(t,void 0,i)},cd(Zd),Zd},Kd=function(e){delete $d[e]},Gd?cd=function(e){qd.nextTick(iu(e))}:Jd&&Jd.now?cd=function(e){Jd.now(iu(e))}:Xd&&!jd?(dd=(ld=new Xd).port2,ld.port1.onmessage=ru,cd=Ld(dd.postMessage,dd)):Pd.addEventListener&&xd(Pd.postMessage)&&!Pd.importScripts&&ad&&"file:"!==ad.protocol&&!Vd(nu)?(cd=nu,Pd.addEventListener("message",ru,!1)):cd=eu in Hd("script")?function(e){Bd.appendChild(Hd("script"))[eu]=function(){Bd.removeChild(this),tu(e)}}:function(e){setTimeout(iu(e),0)});var ou={set:zd,clear:Kd},su=n,au=a,cu=Object.getOwnPropertyDescriptor,lu=function(e){if(!au)return su[e];var t=cu(su,e);return t&&t.value},du=function(){this.head=null,this.tail=null};du.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var uu,hu,pu,mu,fu,_u=du,gu=/ipad|iphone|ipod/i.test(X)&&"undefined"!=typeof Pebble,vu=/web0s(?!.*chrome)/i.test(X),Eu=n,Tu=lu,yu=wd,Su=ou.set,Iu=_u,Au=Od,bu=gu,Ru=vu,Cu=na,ku=Eu.MutationObserver||Eu.WebKitMutationObserver,wu=Eu.document,Du=Eu.process,Nu=Eu.Promise,Ou=Tu("queueMicrotask");if(!Ou){var Pu=new Iu,Mu=function(){var e,t;for(Cu&&(e=Du.domain)&&e.exit();t=Pu.get();)try{t()}catch(Hz){throw Pu.head&&uu(),Hz}e&&e.enter()};Au||Cu||Ru||!ku||!wu?!bu&&Nu&&Nu.resolve?((mu=Nu.resolve(void 0)).constructor=Nu,fu=yu(mu.then,mu),uu=function(){fu(Mu)}):Cu?uu=function(){Du.nextTick(Mu)}:(Su=yu(Su,Eu),uu=function(){Su(Mu)}):(hu=!0,pu=wu.createTextNode(""),new ku(Mu).observe(pu,{characterData:!0}),uu=function(){pu.data=hu=!hu}),Ou=function(e){Pu.head||uu(),Pu.add(e)}}var Lu=Ou,xu=function(e){try{return{error:!1,value:e()}}catch(Hz){return{error:!0,value:Hz}}},Uu=n.Promise,Vu=n,Bu=Uu,Fu=H,Hu=Yr,Wu=li,ju=rt,Gu=ra,zu=re;Bu&&Bu.prototype;var Ku=ju("species"),qu=!1,Ju=Fu(Vu.PromiseRejectionEvent),Yu=Hu("Promise",(function(){var e=Wu(Bu),t=e!==String(Bu);if(!t&&66===zu)return!0;if(!zu||zu<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"!==Gu&&"DENO"!==Gu||Ju)})),Xu={CONSTRUCTOR:Yu,REJECTION_EVENT:Ju,SUBCLASSING:qu},Qu={},Zu=Ee,$u=TypeError,eh=function(e){var t,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw new $u("Bad Promise constructor");t=e,i=r})),this.resolve=Zu(t),this.reject=Zu(i)};Qu.f=function(e){return new eh(e)};var th,ih,rh,nh=nn,oh=na,sh=n,ah=u,ch=$i,lh=cs,dh=Go,uh=Dl,hh=Ee,ph=H,mh=j,fh=Qa,_h=Td,gh=ou.set,vh=Lu,Eh=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(Hz){}},Th=xu,yh=_u,Sh=Di,Ih=Uu,Ah=Qu,bh="Promise",Rh=Xu.CONSTRUCTOR,Ch=Xu.REJECTION_EVENT,kh=Xu.SUBCLASSING,wh=Sh.getterFor(bh),Dh=Sh.set,Nh=Ih&&Ih.prototype,Oh=Ih,Ph=Nh,Mh=sh.TypeError,Lh=sh.document,xh=sh.process,Uh=Ah.f,Vh=Uh,Bh=!!(Lh&&Lh.createEvent&&sh.dispatchEvent),Fh="unhandledrejection",Hh=function(e){var t;return!(!mh(e)||!ph(t=e.then))&&t},Wh=function(e,t){var i,r,n,o=t.value,s=1===t.state,a=s?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{a?(s||(2===t.rejection&&qh(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),n=!0)),i===e.promise?l(new Mh("Promise-chain cycle")):(r=Hh(i))?ah(r,i,c,l):c(i)):l(o)}catch(Hz){d&&!n&&d.exit(),l(Hz)}},jh=function(e,t){e.notified||(e.notified=!0,vh((function(){for(var i,r=e.reactions;i=r.get();)Wh(i,e);e.notified=!1,t&&!e.rejection&&zh(e)})))},Gh=function(e,t,i){var r,n;Bh?((r=Lh.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),sh.dispatchEvent(r)):r={promise:t,reason:i},!Ch&&(n=sh["on"+e])?n(r):e===Fh&&Eh("Unhandled promise rejection",i)},zh=function(e){ah(gh,sh,(function(){var t,i=e.facade,r=e.value;if(Kh(e)&&(t=Th((function(){oh?xh.emit("unhandledRejection",r,i):Gh(Fh,i,r)})),e.rejection=oh||Kh(e)?2:1,t.error))throw t.value}))},Kh=function(e){return 1!==e.rejection&&!e.parent},qh=function(e){ah(gh,sh,(function(){var t=e.facade;oh?xh.emit("rejectionHandled",t):Gh("rejectionhandled",t,e.value)}))},Jh=function(e,t,i){return function(r){e(t,r,i)}},Yh=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,jh(e,!0))},Xh=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new Mh("Promise can't be resolved itself");var r=Hh(t);r?vh((function(){var i={done:!1};try{ah(r,t,Jh(Xh,i,e),Jh(Yh,i,e))}catch(Hz){Yh(i,Hz,e)}})):(e.value=t,e.state=1,jh(e,!1))}catch(Hz){Yh({done:!1},Hz,e)}}};if(Rh&&(Ph=(Oh=function(e){fh(this,Ph),hh(e),ah(th,this);var t=wh(this);try{e(Jh(Xh,t),Jh(Yh,t))}catch(Hz){Yh(t,Hz)}}).prototype,(th=function(e){Dh(this,{type:bh,done:!1,notified:!1,parent:!1,reactions:new yh,rejection:!1,state:0,value:null})}).prototype=ch(Ph,"then",(function(e,t){var i=wh(this),r=Uh(_h(this,Oh));return i.parent=!0,r.ok=!ph(e)||e,r.fail=ph(t)&&t,r.domain=oh?xh.domain:void 0,0===i.state?i.reactions.add(r):vh((function(){Wh(r,i)})),r.promise})),ih=function(){var e=new th,t=wh(e);this.promise=e,this.resolve=Jh(Xh,t),this.reject=Jh(Yh,t)},Ah.f=Uh=function(e){return e===Oh||undefined===e?new ih(e):Vh(e)},ph(Ih)&&Nh!==Object.prototype)){rh=Nh.then,kh||ch(Nh,"then",(function(e,t){var i=this;return new Oh((function(e,t){ah(rh,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete Nh.constructor}catch(Hz){}lh&&lh(Nh,Ph)}nh({global:!0,constructor:!0,wrap:!0,forced:Rh},{Promise:Oh}),dh(Oh,bh,!1),uh(bh);var Qh=So,Zh=rt("iterator"),$h=Array.prototype,ep=function(e){return void 0!==e&&(Qh.Array===e||$h[Zh]===e)},tp=hn,ip=Se,rp=P,np=So,op=rt("iterator"),sp=function(e){if(!rp(e))return ip(e,op)||ip(e,"@@iterator")||np[tp(e)]},ap=u,cp=Ee,lp=Lt,dp=fe,up=sp,hp=TypeError,pp=function(e,t){var i=arguments.length<2?up(e):t;if(cp(i))return lp(ap(i,e));throw new hp(dp(e)+" is not iterable")},mp=u,fp=Lt,_p=Se,gp=function(e,t,i){var r,n;fp(e);try{if(!(r=_p(e,"return"))){if("throw"===t)throw i;return i}r=mp(r,e)}catch(Hz){n=!0,r=Hz}if("throw"===t)throw i;if(n)throw r;return fp(r),i},vp=wd,Ep=u,Tp=Lt,yp=fe,Sp=ep,Ip=mr,Ap=q,bp=pp,Rp=sp,Cp=gp,kp=TypeError,wp=function(e,t){this.stopped=e,this.result=t},Dp=wp.prototype,Np=function(e,t,i){var r,n,o,s,a,c,l,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),f=vp(t,d),_=function(e){return r&&Cp(r,"normal",e),new wp(!0,e)},g=function(e){return u?(Tp(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(!(n=Rp(e)))throw new kp(yp(e)+" is not iterable");if(Sp(n)){for(o=0,s=Ip(e);s>o;o++)if((a=g(e[o]))&&Ap(Dp,a))return a;return new wp(!1)}r=bp(e,n)}for(c=h?e.next:r.next;!(l=Ep(c,r)).done;){try{a=g(l.value)}catch(Hz){Cp(r,"throw",Hz)}if("object"==typeof a&&a&&Ap(Dp,a))return a}return new wp(!1)},Op=rt("iterator"),Pp=!1;try{var Mp=0,Lp={next:function(){return{done:!!Mp++}},return:function(){Pp=!0}};Lp[Op]=function(){return this},Array.from(Lp,(function(){throw 2}))}catch(Hz){}var xp=function(e,t){try{if(!t&&!Pp)return!1}catch(Hz){return!1}var i=!1;try{var r={};r[Op]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(Hz){}return i},Up=Uu,Vp=Xu.CONSTRUCTOR||!xp((function(e){Up.all(e).then(void 0,(function(){}))})),Bp=u,Fp=Ee,Hp=Qu,Wp=xu,jp=Np;nn({target:"Promise",stat:!0,forced:Vp},{all:function(e){var t=this,i=Hp.f(t),r=i.resolve,n=i.reject,o=Wp((function(){var i=Fp(t.resolve),o=[],s=0,a=1;jp(e,(function(e){var c=s++,l=!1;a++,Bp(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 Gp=nn,zp=Xu.CONSTRUCTOR,Kp=Uu,qp=K,Jp=H,Yp=$i,Xp=Kp&&Kp.prototype;if(Gp({target:"Promise",proto:!0,forced:zp,real:!0},{catch:function(e){return this.then(void 0,e)}}),Jp(Kp)){var Qp=qp("Promise").prototype.catch;Xp.catch!==Qp&&Yp(Xp,"catch",Qp,{unsafe:!0})}var Zp=u,$p=Ee,em=Qu,tm=xu,im=Np;nn({target:"Promise",stat:!0,forced:Vp},{race:function(e){var t=this,i=em.f(t),r=i.reject,n=tm((function(){var n=$p(t.resolve);im(e,(function(e){Zp(n,t,e).then(i.resolve,r)}))}));return n.error&&r(n.value),i.promise}});var rm=Qu;nn({target:"Promise",stat:!0,forced:Xu.CONSTRUCTOR},{reject:function(e){var t=rm.f(this);return(0,t.reject)(e),t.promise}});var nm=Lt,om=j,sm=Qu,am=function(e,t){if(nm(e),om(t)&&t.constructor===e)return t;var i=sm.f(e);return(0,i.resolve)(t),i.promise},cm=nn,lm=Xu.CONSTRUCTOR,dm=am;K("Promise"),cm({target:"Promise",stat:!0,forced:lm},{resolve:function(e){return dm(this,e)}});var um=nn,hm=Uu,pm=s,mm=K,fm=H,_m=Td,gm=am,vm=$i,Em=hm&&hm.prototype;if(um({target:"Promise",proto:!0,real:!0,forced:!!hm&&pm((function(){Em.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=_m(this,mm("Promise")),i=fm(e);return this.then(i?function(i){return gm(t,e()).then((function(){return i}))}:e,i?function(i){return gm(t,e()).then((function(){throw i}))}:e)}}),fm(hm)){var Tm=mm("Promise").prototype.finally;Em.finally!==Tm&&vm(Em,"finally",Tm,{unsafe:!0})}var ym=j,Sm=C,Im=rt("match"),Am=function(e){var t;return ym(e)&&(void 0!==(t=e[Im])?!!t:"RegExp"===Sm(e))},bm=Lt,Rm=function(){var e=bm(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},Cm=u,km=je,wm=q,Dm=Rm,Nm=RegExp.prototype,Om=function(e){var t=e.flags;return void 0!==t||"flags"in Nm||km(e,"flags")||!wm(Nm,e)?t:Cm(Dm,e)},Pm=s,Mm=n.RegExp,Lm=Pm((function(){var e=Mm("a","y");return e.lastIndex=2,null!==e.exec("abcd")})),xm=Lm||Pm((function(){return!Mm("a","y").sticky})),Um={BROKEN_CARET:Lm||Pm((function(){var e=Mm("^r","gy");return e.lastIndex=2,null!==e.exec("str")})),MISSED_STICKY:xm,UNSUPPORTED_Y:Lm},Vm=Dt.f,Bm=s,Fm=n.RegExp,Hm=Bm((function(){var e=Fm(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)})),Wm=s,jm=n.RegExp,Gm=Wm((function(){var e=jm("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),zm=a,Km=n,qm=I,Jm=Yr,Ym=Ic,Xm=Yt,Qm=lo,Zm=er.f,$m=q,ef=Am,tf=fn,rf=Om,nf=Um,of=function(e,t,i){i in e||Vm(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},sf=$i,af=s,cf=je,lf=Di.enforce,df=Dl,uf=Hm,hf=Gm,pf=rt("match"),mf=Km.RegExp,ff=mf.prototype,_f=Km.SyntaxError,gf=qm(ff.exec),vf=qm("".charAt),Ef=qm("".replace),Tf=qm("".indexOf),yf=qm("".slice),Sf=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,If=/a/g,Af=/a/g,bf=new mf(If)!==If,Rf=nf.MISSED_STICKY,Cf=nf.UNSUPPORTED_Y,kf=zm&&(!bf||Rf||uf||hf||af((function(){return Af[pf]=!1,mf(If)!==If||mf(Af)===Af||"/a/i"!==String(mf(If,"i"))})));if(Jm("RegExp",kf)){for(var wf=function(e,t){var i,r,n,o,s,a,c=$m(ff,this),l=ef(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===wf)return e;if((l||$m(ff,e))&&(e=e.source,d&&(t=rf(h))),e=void 0===e?"":tf(e),t=void 0===t?"":tf(t),h=e,uf&&"dotAll"in If&&(r=!!t&&Tf(t,"s")>-1)&&(t=Ef(t,/s/g,"")),i=t,Rf&&"sticky"in If&&(n=!!t&&Tf(t,"y")>-1)&&Cf&&(t=Ef(t,/y/g,"")),hf&&(o=function(e){for(var t,i=e.length,r=0,n="",o=[],s=Qm(null),a=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=vf(e,r)))t+=vf(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:if(n+=t,"?:"===yf(e,r+1,r+3))continue;gf(Sf,yf(e,r+1))&&(r+=2,c=!0),l++;continue;case">"===t&&c:if(""===d||cf(s,d))throw new _f("Invalid capture group name");s[d]=!0,o[o.length]=[d,l],c=!1,d="";continue}c?d+=t:n+=t}return[n,o]}(e),e=o[0],u=o[1]),s=Ym(mf(e,t),c?this:ff,wf),(r||n||u.length)&&(a=lf(s),r&&(a.dotAll=!0,a.raw=wf(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=vf(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+vf(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Xm(s,"source",""===h?"(?:)":h)}catch(Hz){}return s},Df=Zm(mf),Nf=0;Df.length>Nf;)of(wf,mf,Df[Nf++]);ff.constructor=wf,wf.prototype=ff,sf(Km,"RegExp",wf,{constructor:!0})}df("RegExp");var Of=u,Pf=I,Mf=fn,Lf=Rm,xf=Um,Uf=lo,Vf=Di.get,Bf=Hm,Ff=Gm,Hf=Ue("native-string-replace",String.prototype.replace),Wf=RegExp.prototype.exec,jf=Wf,Gf=Pf("".charAt),zf=Pf("".indexOf),Kf=Pf("".replace),qf=Pf("".slice),Jf=function(){var e=/a/,t=/b*/g;return Of(Wf,e,"a"),Of(Wf,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Yf=xf.BROKEN_CARET,Xf=void 0!==/()??/.exec("")[1];(Jf||Xf||Yf||Bf||Ff)&&(jf=function(e){var t,i,r,n,o,s,a,c=this,l=Vf(c),d=Mf(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=Of(jf,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Yf&&c.sticky,m=Of(Lf,c),f=c.source,_=0,g=d;if(p&&(m=Kf(m,"y",""),-1===zf(m,"g")&&(m+="g"),g=qf(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Gf(d,c.lastIndex-1))&&(f="(?: "+f+")",g=" "+g,_++),i=new RegExp("^(?:"+f+")",m)),Xf&&(i=new RegExp("^"+f+"$(?!\\s)",m)),Jf&&(r=c.lastIndex),n=Of(Wf,p?i:c,g),p?n?(n.input=qf(n.input,_),n[0]=qf(n[0],_),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:Jf&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),Xf&&n&&n.length>1&&Of(Hf,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=Uf(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=n[a[1]];return n});var Qf=jf;nn({target:"RegExp",proto:!0,forced:/./.exec!==Qf},{exec:Qf});var Zf=a,$f=vn,e_=Rm,t_=s,i_=n.RegExp,r_=i_.prototype,n_=Zf&&t_((function(){var e=!0;try{i_(".","d")}catch(Hz){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(r_,"flags").get.call(t)!==r||i!==r}));n_&&$f(r_,"flags",{configurable:!0,get:e_});var o_=or,s_=fn,a_=x,c_=RangeError,l_=I,d_=hr,u_=fn,h_=function(e){var t=s_(a_(this)),i="",r=o_(e);if(r<0||Infinity===r)throw new c_("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},p_=x,m_=l_(h_),f_=l_("".slice),__=Math.ceil,g_=function(e){return function(t,i,r){var n,o,s=u_(p_(t)),a=d_(i),c=s.length,l=void 0===r?" ":u_(r);return a<=c||""===l?s:((o=m_(l,__((n=a-c)/l.length))).length>n&&(o=f_(o,0,n)),e?s+o:o+s)}},v_={start:g_(!1),end:g_(!0)},E_=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(X),T_=v_.start;nn({target:"String",proto:!0,forced:E_},{padStart:function(e){return T_(this,e,arguments.length>1?arguments[1]:void 0)}});var y_=u,S_=$i,I_=Qf,A_=s,b_=rt,R_=Yt,C_=b_("species"),k_=RegExp.prototype,w_=I,D_=or,N_=fn,O_=x,P_=w_("".charAt),M_=w_("".charCodeAt),L_=w_("".slice),x_=function(e){return function(t,i){var r,n,o=N_(O_(t)),s=D_(i),a=o.length;return s<0||s>=a?e?"":void 0:(r=M_(o,s))<55296||r>56319||s+1===a||(n=M_(o,s+1))<56320||n>57343?e?P_(o,s):r:e?L_(o,s,s+2):n-56320+(r-55296<<10)+65536}},U_={codeAt:x_(!1),charAt:x_(!0)},V_=U_.charAt,B_=I,F_=Fe,H_=Math.floor,W_=B_("".charAt),j_=B_("".replace),G_=B_("".slice),z_=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,K_=/\$([$&'`]|\d{1,2})/g,q_=function(e,t,i,r,n,o){var s=i+e.length,a=r.length,c=K_;return void 0!==n&&(n=F_(n),c=z_),j_(o,c,(function(o,c){var l;switch(W_(c,0)){case"$":return"$";case"&":return e;case"`":return G_(t,0,i);case"'":return G_(t,s);case"<":l=n[G_(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=H_(d/10);return 0===u?o:u<=a?void 0===r[u-1]?W_(c,1):r[u-1]+W_(c,1):o}l=r[d-1]}return void 0===l?"":l}))},J_=u,Y_=Lt,X_=H,Q_=C,Z_=Qf,$_=TypeError,eg=bd,tg=u,ig=I,rg=function(e,t,i,r){var n=b_(e),o=!A_((function(){var t={};return t[n]=function(){return 7},7!==""[e](t)})),s=o&&!A_((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[C_]=function(){return i},i.flags="",i[n]=/./[n]),i.exec=function(){return t=!0,null},i[n](""),!t}));if(!o||!s||i){var a=/./[n],c=t(n,""[e],(function(e,t,i,r,n){var s=t.exec;return s===I_||s===k_.exec?o&&!n?{done:!0,value:y_(a,t,i,r)}:{done:!0,value:y_(e,i,t,r)}:{done:!1}}));S_(String.prototype,e,c[0]),S_(k_,n,c[1])}r&&R_(k_[n],"sham",!0)},ng=s,og=Lt,sg=H,ag=P,cg=or,lg=hr,dg=fn,ug=x,hg=function(e,t,i){return t+(i?V_(e,t).length:1)},pg=Se,mg=q_,fg=function(e,t){var i=e.exec;if(X_(i)){var r=J_(i,e,t);return null!==r&&Y_(r),r}if("RegExp"===Q_(e))return J_(Z_,e,t);throw new $_("RegExp#exec called on incompatible receiver")},_g=rt("replace"),gg=Math.max,vg=Math.min,Eg=ig([].concat),Tg=ig([].push),yg=ig("".indexOf),Sg=ig("".slice),Ig=function(e){return void 0===e?e:String(e)},Ag="$0"==="a".replace(/./,"$0"),bg=!!/./[_g]&&""===/./[_g]("a","$0");rg("replace",(function(e,t,i){var r=bg?"$":"$0";return[function(e,i){var r=ug(this),n=ag(e)?void 0:pg(e,_g);return n?tg(n,e,r,i):tg(t,dg(r),e,i)},function(e,n){var o=og(this),s=dg(e);if("string"==typeof n&&-1===yg(n,r)&&-1===yg(n,"$<")){var a=i(t,o,s,n);if(a.done)return a.value}var c=sg(n);c||(n=dg(n));var l,d=o.global;d&&(l=o.unicode,o.lastIndex=0);for(var u,h=[];null!==(u=fg(o,s))&&(Tg(h,u),d);){""===dg(u[0])&&(o.lastIndex=hg(s,lg(o.lastIndex),l))}for(var p="",m=0,f=0;f<h.length;f++){for(var _,g=dg((u=h[f])[0]),v=gg(vg(cg(u.index),s.length),0),E=[],T=1;T<u.length;T++)Tg(E,Ig(u[T]));var y=u.groups;if(c){var S=Eg([g],E,v,s);void 0!==y&&Tg(S,y),_=dg(eg(n,void 0,S))}else _=mg(g,s,v,E,y,n);v>=m&&(p+=Sg(s,m,v)+_,m=v+g.length)}return p+Sg(s,m)}]}),!!ng((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}))||!Ag||bg);var Rg="\t\n\v\f\r                 \u2028\u2029\ufeff",Cg=x,kg=fn,wg=Rg,Dg=I("".replace),Ng=RegExp("^["+wg+"]+"),Og=RegExp("(^|[^"+wg+"])["+wg+"]+$"),Pg=function(e){return function(t){var i=kg(Cg(t));return 1&e&&(i=Dg(i,Ng,"")),2&e&&(i=Dg(i,Og,"$1")),i}},Mg={start:Pg(1),end:Pg(2),trim:Pg(3)},Lg=ii.PROPER,xg=s,Ug=Rg,Vg=Mg.trim;nn({target:"String",proto:!0,forced:function(e){return xg((function(){return!!Ug[e]()||"​…᠎"!=="​…᠎"[e]()||Lg&&Ug[e].name!==e}))}("trim")},{trim:function(){return Vg(this)}});var Bg,Fg,Hg,Wg={exports:{}},jg=Ka,Gg=a,zg=n,Kg=H,qg=j,Jg=je,Yg=hn,Xg=fe,Qg=Yt,Zg=$i,$g=vn,ev=q,tv=No,iv=cs,rv=rt,nv=Je,ov=Di.enforce,sv=Di.get,av=zg.Int8Array,cv=av&&av.prototype,lv=zg.Uint8ClampedArray,dv=lv&&lv.prototype,uv=av&&tv(av),hv=cv&&tv(cv),pv=Object.prototype,mv=zg.TypeError,fv=rv("toStringTag"),_v=nv("TYPED_ARRAY_TAG"),gv="TypedArrayConstructor",vv=jg&&!!iv&&"Opera"!==Yg(zg.opera),Ev=!1,Tv={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},yv={BigInt64Array:8,BigUint64Array:8},Sv=function(e){var t=tv(e);if(qg(t)){var i=sv(t);return i&&Jg(i,gv)?i[gv]:Sv(t)}},Iv=function(e){if(!qg(e))return!1;var t=Yg(e);return Jg(Tv,t)||Jg(yv,t)};for(Bg in Tv)(Hg=(Fg=zg[Bg])&&Fg.prototype)?ov(Hg)[gv]=Fg:vv=!1;for(Bg in yv)(Hg=(Fg=zg[Bg])&&Fg.prototype)&&(ov(Hg)[gv]=Fg);if((!vv||!Kg(uv)||uv===Function.prototype)&&(uv=function(){throw new mv("Incorrect invocation")},vv))for(Bg in Tv)zg[Bg]&&iv(zg[Bg],uv);if((!vv||!hv||hv===pv)&&(hv=uv.prototype,vv))for(Bg in Tv)zg[Bg]&&iv(zg[Bg].prototype,hv);if(vv&&tv(dv)!==hv&&iv(dv,hv),Gg&&!Jg(hv,fv))for(Bg in Ev=!0,$g(hv,fv,{configurable:!0,get:function(){return qg(this)?this[_v]:void 0}}),Tv)zg[Bg]&&Qg(zg[Bg],_v,Bg);var Av={NATIVE_ARRAY_BUFFER_VIEWS:vv,TYPED_ARRAY_TAG:Ev&&_v,aTypedArray:function(e){if(Iv(e))return e;throw new mv("Target is not a typed array")},aTypedArrayConstructor:function(e){if(Kg(e)&&(!iv||ev(uv,e)))return e;throw new mv(Xg(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(Gg){if(i)for(var n in Tv){var o=zg[n];if(o&&Jg(o.prototype,e))try{delete o.prototype[e]}catch(Hz){try{o.prototype[e]=t}catch(s){}}}hv[e]&&!i||Zg(hv,e,i?t:vv&&cv[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(Gg){if(iv){if(i)for(r in Tv)if((n=zg[r])&&Jg(n,e))try{delete n[e]}catch(Hz){}if(uv[e]&&!i)return;try{return Zg(uv,e,i?t:vv&&uv[e]||t)}catch(Hz){}}for(r in Tv)!(n=zg[r])||n[e]&&!i||Zg(n,e,t)}},getTypedArrayConstructor:Sv,isView:function(e){if(!qg(e))return!1;var t=Yg(e);return"DataView"===t||Jg(Tv,t)||Jg(yv,t)},isTypedArray:Iv,TypedArray:uv,TypedArrayPrototype:hv},bv=n,Rv=s,Cv=xp,kv=Av.NATIVE_ARRAY_BUFFER_VIEWS,wv=bv.ArrayBuffer,Dv=bv.Int8Array,Nv=!kv||!Rv((function(){Dv(1)}))||!Rv((function(){new Dv(-1)}))||!Cv((function(e){new Dv,new Dv(null),new Dv(1.5),new Dv(e)}),!0)||Rv((function(){return 1!==new Dv(new wv(2),1,void 0).length})),Ov=j,Pv=Math.floor,Mv=Number.isInteger||function(e){return!Ov(e)&&isFinite(e)&&Pv(e)===e},Lv=or,xv=RangeError,Uv=function(e){var t=Lv(e);if(t<0)throw new xv("The argument can't be less than 0");return t},Vv=RangeError,Bv=function(e,t){var i=Uv(e);if(i%t)throw new Vv("Wrong offset");return i},Fv=Math.round,Hv=hn,Wv=ut,jv=TypeError,Gv=function(e){var t=Wv(e,"number");if("number"==typeof t)throw new jv("Can't convert number to bigint");return BigInt(t)},zv=wd,Kv=u,qv=fd,Jv=Fe,Yv=mr,Xv=pp,Qv=sp,Zv=ep,$v=function(e){var t=Hv(e);return"BigInt64Array"===t||"BigUint64Array"===t},eE=Av.aTypedArrayConstructor,tE=Gv,iE=function(e){var t,i,r,n,o,s,a,c,l=qv(this),d=Jv(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=Qv(d);if(m&&!Zv(m))for(c=(a=Xv(d,m)).next,d=[];!(s=Kv(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=zv(h,arguments[2])),i=Yv(d),r=new(eE(l))(i),n=$v(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?tE(o):+o;return r},rE=ca,nE=ud,oE=j,sE=rt("species"),aE=Array,cE=function(e){var t;return rE(e)&&(t=e.constructor,(nE(t)&&(t===aE||rE(t.prototype))||oE(t)&&null===(t=t[sE]))&&(t=void 0)),void 0===t?aE:t},lE=wd,dE=O,uE=Fe,hE=mr,pE=function(e,t){return new(cE(e))(0===t?0:t)},mE=I([].push),fE=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=uE(c),f=dE(m),_=hE(f),g=lE(l,d),v=0,E=u||pE,T=t?E(c,_):i||s?E(c,0):void 0;_>v;v++)if((a||v in f)&&(p=g(h=f[v],v,m),e))if(t)T[v]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return v;case 2:mE(T,h)}else switch(e){case 4:return!1;case 7:mE(T,h)}return o?-1:r||n?n:T}},_E={forEach:fE(0),map:fE(1),filter:fE(2),some:fE(3),every:fE(4),find:fE(5),findIndex:fE(6),filterReject:fE(7)},gE=mr,vE=nn,EE=n,TE=u,yE=a,SE=Nv,IE=Av,AE=bl,bE=Qa,RE=v,CE=Yt,kE=Mv,wE=hr,DE=tc,NE=Bv,OE=function(e){var t=Fv(e);return t<0?0:t>255?255:255&t},PE=mt,ME=je,LE=hn,xE=j,UE=pe,VE=lo,BE=q,FE=cs,HE=er.f,WE=iE,jE=_E.forEach,GE=Dl,zE=vn,KE=Dt,qE=o,JE=function(e,t,i){for(var r=0,n=arguments.length>2?i:gE(t),o=new e(n);n>r;)o[r]=t[r++];return o},YE=Ic,XE=Di.get,QE=Di.set,ZE=Di.enforce,$E=KE.f,eT=qE.f,tT=EE.RangeError,iT=AE.ArrayBuffer,rT=iT.prototype,nT=AE.DataView,oT=IE.NATIVE_ARRAY_BUFFER_VIEWS,sT=IE.TYPED_ARRAY_TAG,aT=IE.TypedArray,cT=IE.TypedArrayPrototype,lT=IE.isTypedArray,dT="BYTES_PER_ELEMENT",uT="Wrong length",hT=function(e,t){zE(e,t,{configurable:!0,get:function(){return XE(this)[t]}})},pT=function(e){var t;return BE(rT,e)||"ArrayBuffer"===(t=LE(e))||"SharedArrayBuffer"===t},mT=function(e,t){return lT(e)&&!UE(t)&&t in e&&kE(+t)&&t>=0},fT=function(e,t){return t=PE(t),mT(e,t)?RE(2,e[t]):eT(e,t)},_T=function(e,t,i){return t=PE(t),!(mT(e,t)&&xE(i)&&ME(i,"value"))||ME(i,"get")||ME(i,"set")||i.configurable||ME(i,"writable")&&!i.writable||ME(i,"enumerable")&&!i.enumerable?$E(e,t,i):(e[t]=i.value,e)};yE?(oT||(qE.f=fT,KE.f=_T,hT(cT,"buffer"),hT(cT,"byteOffset"),hT(cT,"byteLength"),hT(cT,"length")),vE({target:"Object",stat:!0,forced:!oT},{getOwnPropertyDescriptor:fT,defineProperty:_T}),Wg.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=EE[n],c=a,l=c&&c.prototype,d={},u=function(e,t){$E(e,t,{get:function(){return function(e,t){var i=XE(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=XE(e);o.view[s](t*r+o.byteOffset,i?OE(n):n,!0)}(this,t,e)},enumerable:!0})};oT?SE&&(c=t((function(e,t,i,n){return bE(e,l),YE(xE(t)?pT(t)?void 0!==n?new a(t,NE(i,r),n):void 0!==i?new a(t,NE(i,r)):new a(t):lT(t)?JE(c,t):TE(WE,c,t):new a(DE(t)),e,c)})),FE&&FE(c,aT),jE(HE(a),(function(e){e in c||CE(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,n){bE(e,l);var o,s,a,d=0,h=0;if(xE(t)){if(!pT(t))return lT(t)?JE(c,t):TE(WE,c,t);o=t,h=NE(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw new tT(uT);if((s=p-h)<0)throw new tT(uT)}else if((s=wE(n)*r)+h>p)throw new tT(uT);a=s/r}else a=DE(t),o=new iT(s=a*r);for(QE(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new nT(o)});d<a;)u(e,d++)})),FE&&FE(c,aT),l=c.prototype=VE(cT)),l.constructor!==c&&CE(l,"constructor",c),ZE(l).TypedArrayConstructor=c,sT&&CE(l,sT,n);var h=c!==a;d[n]=c,vE({global:!0,constructor:!0,forced:h,sham:!oT},d),dT in c||CE(c,dT,r),dT in l||CE(l,dT,r),GE(n)}):Wg.exports=function(){};var gT=Wg.exports;gT("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}})),gT("Int32",(function(e){return function(t,i,r){return e(this,t,i,r)}})),gT("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}})),gT("Uint16",(function(e){return function(t,i,r){return e(this,t,i,r)}})),gT("Uint32",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var vT=Ec,ET=Gv,TT=hn,yT=u,ST=s,IT=Av.aTypedArray,AT=Av.exportTypedArrayMethod,bT=I("".slice);AT("fill",(function(e){var t=arguments.length;IT(this);var i="Big"===bT(TT(this),0,3)?ET(e):+e;return yT(vT,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),ST((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e}))),(0,Av.exportTypedArrayStaticMethod)("from",iE,Nv);var RT=n,CT=u,kT=Av,wT=mr,DT=Bv,NT=Fe,OT=s,PT=RT.RangeError,MT=RT.Int8Array,LT=MT&&MT.prototype,xT=LT&&LT.set,UT=kT.aTypedArray,VT=kT.exportTypedArrayMethod,BT=!OT((function(){var e=new Uint8ClampedArray(2);return CT(xT,e,{length:1,0:3},1),3!==e[1]})),FT=BT&&kT.NATIVE_ARRAY_BUFFER_VIEWS&&OT((function(){var e=new MT(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));VT("set",(function(e){UT(this);var t=DT(arguments.length>1?arguments[1]:void 0,1),i=NT(e);if(BT)return CT(xT,this,i,t);var r=this.length,n=wT(i),o=0;if(n+t>r)throw new PT("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!BT||FT);var HT=xl,WT=s,jT=Ee,GT=Ea,zT=ya,KT=Sa,qT=re,JT=Aa,YT=Av.aTypedArray,XT=Av.exportTypedArrayMethod,QT=n.Uint16Array,ZT=QT&&HT(QT.prototype.sort),$T=!(!ZT||WT((function(){ZT(new QT(2),null)}))&&WT((function(){ZT(new QT(2),{})}))),ey=!!ZT&&!WT((function(){if(qT)return qT<74;if(zT)return zT<67;if(KT)return!0;if(JT)return JT<602;var e,t,i=new QT(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(ZT(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));XT("sort",(function(e){return void 0!==e&&jT(e),ey?ZT(this,e):GT(YT(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))}),!ey||$T);var ty=nn,iy=u,ry=I,ny=x,oy=H,sy=P,ay=Am,cy=fn,ly=Se,dy=Om,uy=q_,hy=rt("replace"),py=TypeError,my=ry("".indexOf);ry("".replace);var fy=ry("".slice),_y=Math.max;ty({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,n,o,s,a,c,l,d,u=ny(this),h=0,p="";if(!sy(e)){if(ay(e)&&(i=cy(ny(dy(e))),!~my(i,"g")))throw new py("`.replaceAll` does not allow non-global regexes");if(r=ly(e,hy))return iy(r,e,u,t)}for(n=cy(u),o=cy(e),(s=oy(t))||(t=cy(t)),a=o.length,c=_y(1,a),l=my(n,o);-1!==l;)d=s?cy(t(o,l,n)):uy(o,n,l,[],void 0,t),p+=fy(n,h,l)+d,h=l+a,l=l+c>n.length?-1:my(n,o,l+c);return h<n.length&&(p+=fy(n,h)),p}});var gy={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},vy=vt("span").classList,Ey=vy&&vy.constructor&&vy.constructor.prototype,Ty=Ey===Object.prototype?void 0:Ey,yy=_E.forEach,Sy=Zs("forEach")?[].forEach:function(e){return yy(this,e,arguments.length>1?arguments[1]:void 0)},Iy=n,Ay=gy,by=Ty,Ry=Sy,Cy=Yt,ky=function(e){if(e&&e.forEach!==Ry)try{Cy(e,"forEach",Ry)}catch(Hz){e.forEach=Ry}};for(var wy in Ay)Ay[wy]&&ky(Iy[wy]&&Iy[wy].prototype);ky(by);var Dy=n,Ny=gy,Oy=Ty,Py=Hs,My=Yt,Ly=Go,xy=rt("iterator"),Uy=Py.values,Vy=function(e,t){if(e){if(e[xy]!==Uy)try{My(e,xy,Uy)}catch(Hz){e[xy]=Uy}if(Ly(e,t,!0),Ny[t])for(var i in Py)if(e[i]!==Py[i])try{My(e,i,Py[i])}catch(Hz){e[i]=Py[i]}}};for(var By in Ny)Vy(Dy[By]&&Dy[By].prototype,By);Vy(Oy,"DOMTokenList");var Fy=ou.clear;nn({global:!0,bind:!0,enumerable:!0,forced:n.clearImmediate!==Fy},{clearImmediate:Fy});var Hy=n,Wy=bd,jy=H,Gy=ra,zy=X,Ky=fa,qy=Nd,Jy=Hy.Function,Yy=/MSIE .\./.test(zy)||"BUN"===Gy&&function(){var e=Hy.Bun.version.split(".");return e.length<3||"0"===e[0]&&(e[1]<3||"3"===e[1]&&"0"===e[2])}(),Xy=nn,Qy=n,Zy=ou.set,$y=function(e,t){var i=t?2:1;return Yy?function(r,n){var o=qy(arguments.length,1)>i,s=jy(r)?r:Jy(r),a=o?Ky(arguments,i):[],c=o?function(){Wy(s,this,a)}:s;return t?e(c,n):e(c)}:e},eS=Qy.setImmediate?$y(Zy,!1):Zy;Xy({global:!0,bind:!0,enumerable:!0,forced:Qy.setImmediate!==eS},{setImmediate:eS});var tS=U_.charAt,iS=fn,rS=Di,nS=ks,oS=ws,sS="String Iterator",aS=rS.set,cS=rS.getterFor(sS);nS(String,"String",(function(e){aS(this,{type:sS,string:iS(e),index:0})}),(function(){var e,t=cS(this),i=t.string,r=t.index;return r>=i.length?oS(void 0,!0):(e=tS(i,r),t.index+=e.length,oS(e,!1))}));var lS=s,dS=a,uS=rt("iterator"),hS=!lS((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&&!dS||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[uS]||"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})),pS=a,mS=I,fS=u,_S=s,gS=Hn,vS=wr,ES=h,TS=Fe,yS=O,SS=Object.assign,IS=Object.defineProperty,AS=mS([].concat),bS=!SS||_S((function(){if(pS&&1!==SS({b:1},SS(IS({},"a",{enumerable:!0,get:function(){IS(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol("assign detection"),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach((function(e){t[e]=e})),7!==SS({},e)[i]||gS(SS({},t)).join("")!==r}))?function(e,t){for(var i=TS(e),r=arguments.length,n=1,o=vS.f,s=ES.f;r>n;)for(var a,c=yS(arguments[n++]),l=o?AS(gS(c),o(c)):gS(c),d=l.length,u=0;d>u;)a=l[u++],pS&&!fS(s,c,a)||(i[a]=c[a]);return i}:SS,RS=Lt,CS=gp,kS=a,wS=Dt,DS=v,NS=wd,OS=u,PS=Fe,MS=function(e,t,i,r){try{return r?t(RS(i)[0],i[1]):t(i)}catch(Hz){CS(e,"throw",Hz)}},LS=ep,xS=ud,US=mr,VS=function(e,t,i){kS?wS.f(e,t,DS(0,i)):e[t]=i},BS=pp,FS=sp,HS=Array,WS=I,jS=2147483647,GS=/[^\0-\u007E]/,zS=/[.\u3002\uFF0E\uFF61]/g,KS="Overflow: input needs wider integers to process",qS=RangeError,JS=WS(zS.exec),YS=Math.floor,XS=String.fromCharCode,QS=WS("".charCodeAt),ZS=WS([].join),$S=WS([].push),eI=WS("".replace),tI=WS("".split),iI=WS("".toLowerCase),rI=function(e){return e+22+75*(e<26)},nI=function(e,t,i){var r=0;for(e=i?YS(e/700):e>>1,e+=YS(e/t);e>455;)e=YS(e/35),r+=36;return YS(r+36*e/(e+38))},oI=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=QS(e,i++);if(n>=55296&&n<=56319&&i<r){var o=QS(e,i++);56320==(64512&o)?$S(t,((1023&n)<<10)+(1023&o)+65536):($S(t,n),i--)}else $S(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&&$S(t,XS(r));var c=t.length,l=c;for(c&&$S(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>YS((jS-s)/u))throw new qS(KS);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++s>jS)throw new qS(KS);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 f=h-m,_=36-m;$S(t,XS(rI(m+f%_))),h=YS(f/_),p+=36}$S(t,XS(rI(h))),a=nI(s,u,l===c),s=0,l++}}s++,o++}return ZS(t,"")},sI=nn,aI=I,cI=lr,lI=RangeError,dI=String.fromCharCode,uI=String.fromCodePoint,hI=aI([].join);sI({target:"String",stat:!0,arity:1,forced:!!uI&&1!==uI.length},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,n=0;r>n;){if(t=+arguments[n++],cI(t,1114111)!==t)throw new lI(t+" is not a valid code point");i[n]=t<65536?dI(t):dI(55296+((t-=65536)>>10),t%1024+56320)}return hI(i,"")}});var pI=nn,mI=n,fI=lu,_I=K,gI=u,vI=I,EI=a,TI=hS,yI=$i,SI=vn,II=Ja,AI=Go,bI=Qo,RI=Di,CI=Qa,kI=H,wI=je,DI=wd,NI=hn,OI=Lt,PI=j,MI=fn,LI=lo,xI=v,UI=pp,VI=sp,BI=ws,FI=Nd,HI=Ea,WI=rt("iterator"),jI="URLSearchParams",GI=jI+"Iterator",zI=RI.set,KI=RI.getterFor(jI),qI=RI.getterFor(GI),JI=fI("fetch"),YI=fI("Request"),XI=fI("Headers"),QI=YI&&YI.prototype,ZI=XI&&XI.prototype,$I=mI.TypeError,eA=mI.encodeURIComponent,tA=String.fromCharCode,iA=_I("String","fromCodePoint"),rA=parseInt,nA=vI("".charAt),oA=vI([].join),sA=vI([].push),aA=vI("".replace),cA=vI([].shift),lA=vI([].splice),dA=vI("".split),uA=vI("".slice),hA=vI(/./.exec),pA=/\+/g,mA=/^[0-9a-f]+$/i,fA=function(e,t){var i=uA(e,t,t+2);return hA(mA,i)?rA(i,16):NaN},_A=function(e){for(var t=0,i=128;i>0&&e&i;i>>=1)t++;return t},gA=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},vA=function(e){for(var t=(e=aA(e,pA," ")).length,i="",r=0;r<t;){var n=nA(e,r);if("%"===n){if("%"===nA(e,r+1)||r+3>t){i+="%",r++;continue}var o=fA(e,r+1);if(o!=o){i+=n,r++;continue}r+=2;var s=_A(o);if(0===s)n=tA(o);else{if(1===s||s>4){i+="�",r++;continue}for(var a=[o],c=1;c<s&&!(++r+3>t||"%"!==nA(e,r));){var l=fA(e,r+1);if(l!=l){r+=3;break}if(l>191||l<128)break;sA(a,l),r+=2,c++}if(a.length!==s){i+="�";continue}var d=gA(a);null===d?i+="�":n=iA(d)}}i+=n,r++}return i},EA=/[!'()~]|%20/g,TA={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},yA=function(e){return TA[e]},SA=function(e){return aA(eA(e),EA,yA)},IA=bI((function(e,t){zI(this,{type:GI,target:KI(e).entries,index:0,kind:t})}),jI,(function(){var e=qI(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,BI(void 0,!0);var r=t[i];switch(e.kind){case"keys":return BI(r.key,!1);case"values":return BI(r.value,!1)}return BI([r.key,r.value],!1)}),!0),AA=function(e){this.entries=[],this.url=null,void 0!==e&&(PI(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===nA(e,0)?uA(e,1):e:MI(e)))};AA.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=VI(e);if(l)for(i=(t=UI(e,l)).next;!(r=gI(i,t)).done;){if(o=(n=UI(OI(r.value))).next,(s=gI(o,n)).done||(a=gI(o,n)).done||!gI(o,n).done)throw new $I("Expected sequence with length 2");sA(c,{key:MI(s.value),value:MI(a.value)})}else for(var d in e)wI(e,d)&&sA(c,{key:d,value:MI(e[d])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,n=dA(e,"&"),o=0;o<n.length;)(t=n[o++]).length&&(i=dA(t,"="),sA(r,{key:vA(cA(i)),value:vA(oA(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],sA(i,SA(e.key)+"="+SA(e.value));return oA(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var bA=function(){CI(this,RA);var e=zI(this,new AA(arguments.length>0?arguments[0]:void 0));EI||(this.size=e.entries.length)},RA=bA.prototype;if(II(RA,{append:function(e,t){var i=KI(this);FI(arguments.length,2),sA(i.entries,{key:MI(e),value:MI(t)}),EI||this.length++,i.updateURL()},delete:function(e){for(var t=KI(this),i=FI(arguments.length,1),r=t.entries,n=MI(e),o=i<2?void 0:arguments[1],s=void 0===o?o:MI(o),a=0;a<r.length;){var c=r[a];if(c.key!==n||void 0!==s&&c.value!==s)a++;else if(lA(r,a,1),void 0!==s)break}EI||(this.size=r.length),t.updateURL()},get:function(e){var t=KI(this).entries;FI(arguments.length,1);for(var i=MI(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=KI(this).entries;FI(arguments.length,1);for(var i=MI(e),r=[],n=0;n<t.length;n++)t[n].key===i&&sA(r,t[n].value);return r},has:function(e){for(var t=KI(this).entries,i=FI(arguments.length,1),r=MI(e),n=i<2?void 0:arguments[1],o=void 0===n?n:MI(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=KI(this);FI(arguments.length,1);for(var r,n=i.entries,o=!1,s=MI(e),a=MI(t),c=0;c<n.length;c++)(r=n[c]).key===s&&(o?lA(n,c--,1):(o=!0,r.value=a));o||sA(n,{key:s,value:a}),EI||(this.size=n.length),i.updateURL()},sort:function(){var e=KI(this);HI(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=KI(this).entries,r=DI(e,arguments.length>1?arguments[1]:void 0),n=0;n<i.length;)r((t=i[n++]).value,t.key,this)},keys:function(){return new IA(this,"keys")},values:function(){return new IA(this,"values")},entries:function(){return new IA(this,"entries")}},{enumerable:!0}),yI(RA,WI,RA.entries,{name:"entries"}),yI(RA,"toString",(function(){return KI(this).serialize()}),{enumerable:!0}),EI&&SI(RA,"size",{get:function(){return KI(this).entries.length},configurable:!0,enumerable:!0}),AI(bA,jI),pI({global:!0,constructor:!0,forced:!TI},{URLSearchParams:bA}),!TI&&kI(XI)){var CA=vI(ZI.has),kA=vI(ZI.set),wA=function(e){if(PI(e)){var t,i=e.body;if(NI(i)===jI)return t=e.headers?new XI(e.headers):new XI,CA(t,"content-type")||kA(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),LI(e,{body:xI(0,MI(i)),headers:xI(0,t)})}return e};if(kI(JI)&&pI({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return JI(e,arguments.length>1?wA(arguments[1]):{})}}),kI(YI)){var DA=function(e){return CI(this,QI),new YI(e,arguments.length>1?wA(arguments[1]):{})};QI.constructor=DA,DA.prototype=QI,pI({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:DA})}}var NA,OA=nn,PA=a,MA=hS,LA=n,xA=wd,UA=I,VA=$i,BA=vn,FA=Qa,HA=je,WA=bS,jA=function(e){var t=PS(e),i=xS(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=NS(n,r>2?arguments[2]:void 0));var s,a,c,l,d,u,h=FS(t),p=0;if(!h||this===HS&&LS(h))for(s=US(t),a=i?new this(s):HS(s);s>p;p++)u=o?n(t[p],p):t[p],VS(a,p,u);else for(a=i?new this:[],d=(l=BS(t,h)).next;!(c=OS(d,l)).done;p++)u=o?MS(l,n,[c.value,p],!0):c.value,VS(a,p,u);return a.length=p,a},GA=fa,zA=U_.codeAt,KA=function(e){var t,i,r=[],n=tI(eI(iI(e),zS,"."),".");for(t=0;t<n.length;t++)i=n[t],$S(r,JS(GS,i)?"xn--"+oI(i):i);return ZS(r,".")},qA=fn,JA=Go,YA=Nd,XA={URLSearchParams:bA,getState:KI},QA=Di,ZA=QA.set,$A=QA.getterFor("URL"),eb=XA.URLSearchParams,tb=XA.getState,ib=LA.URL,rb=LA.TypeError,nb=LA.parseInt,ob=Math.floor,sb=Math.pow,ab=UA("".charAt),cb=UA(/./.exec),lb=UA([].join),db=UA(1..toString),ub=UA([].pop),hb=UA([].push),pb=UA("".replace),mb=UA([].shift),fb=UA("".split),_b=UA("".slice),gb=UA("".toLowerCase),vb=UA([].unshift),Eb="Invalid scheme",Tb="Invalid host",yb="Invalid port",Sb=/[a-z]/i,Ib=/[\d+-.a-z]/i,Ab=/\d/,bb=/^0x/i,Rb=/^[0-7]+$/,Cb=/^\d+$/,kb=/^[\da-f]+$/i,wb=/[\0\t\n\r #%/:<>?@[\\\]^|]/,Db=/[\0\t\n\r #/:<>?@[\\\]^|]/,Nb=/^[\u0000-\u0020]+/,Ob=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,Pb=/[\t\n\r]/g,Mb=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)vb(t,e%256),e=ob(e/256);return lb(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+=db(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},Lb={},xb=WA({},Lb,{" ":1,'"':1,"<":1,">":1,"`":1}),Ub=WA({},xb,{"#":1,"?":1,"{":1,"}":1}),Vb=WA({},Ub,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Bb=function(e,t){var i=zA(e,0);return i>32&&i<127&&!HA(t,e)?e:encodeURIComponent(e)},Fb={ftp:21,file:null,http:80,https:443,ws:80,wss:443},Hb=function(e,t){var i;return 2===e.length&&cb(Sb,ab(e,0))&&(":"===(i=ab(e,1))||!t&&"|"===i)},Wb=function(e){var t;return e.length>1&&Hb(_b(e,0,2))&&(2===e.length||"/"===(t=ab(e,2))||"\\"===t||"?"===t||"#"===t)},jb=function(e){return"."===e||"%2e"===gb(e)},Gb={},zb={},Kb={},qb={},Jb={},Yb={},Xb={},Qb={},Zb={},$b={},eR={},tR={},iR={},rR={},nR={},oR={},sR={},aR={},cR={},lR={},dR={},uR=function(e,t,i){var r,n,o,s=qA(e);if(t){if(n=this.parse(s))throw new rb(n);this.searchParams=null}else{if(void 0!==i&&(r=new uR(i,!0)),n=this.parse(s,null,r))throw new rb(n);(o=tb(new eb)).bindURL(this),this.searchParams=o}};uR.prototype={type:"URL",parse:function(e,t,i){var r,n,o,s,a,c=this,l=t||Gb,d=0,u="",h=!1,p=!1,m=!1;for(e=qA(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=pb(e,Nb,""),e=pb(e,Ob,"$1")),e=pb(e,Pb,""),r=jA(e);d<=r.length;){switch(n=r[d],l){case Gb:if(!n||!cb(Sb,n)){if(t)return Eb;l=Kb;continue}u+=gb(n),l=zb;break;case zb:if(n&&(cb(Ib,n)||"+"===n||"-"===n||"."===n))u+=gb(n);else{if(":"!==n){if(t)return Eb;u="",l=Kb,d=0;continue}if(t&&(c.isSpecial()!==HA(Fb,u)||"file"===u&&(c.includesCredentials()||null!==c.port)||"file"===c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&Fb[c.scheme]===c.port&&(c.port=null));u="","file"===c.scheme?l=rR:c.isSpecial()&&i&&i.scheme===c.scheme?l=qb:c.isSpecial()?l=Qb:"/"===r[d+1]?(l=Jb,d++):(c.cannotBeABaseURL=!0,hb(c.path,""),l=cR)}break;case Kb:if(!i||i.cannotBeABaseURL&&"#"!==n)return Eb;if(i.cannotBeABaseURL&&"#"===n){c.scheme=i.scheme,c.path=GA(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=dR;break}l="file"===i.scheme?rR:Yb;continue;case qb:if("/"!==n||"/"!==r[d+1]){l=Yb;continue}l=Zb,d++;break;case Jb:if("/"===n){l=$b;break}l=aR;continue;case Yb:if(c.scheme=i.scheme,n===NA)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=GA(i.path),c.query=i.query;else if("/"===n||"\\"===n&&c.isSpecial())l=Xb;else if("?"===n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=GA(i.path),c.query="",l=lR;else{if("#"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=GA(i.path),c.path.length--,l=aR;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=GA(i.path),c.query=i.query,c.fragment="",l=dR}break;case Xb:if(!c.isSpecial()||"/"!==n&&"\\"!==n){if("/"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=aR;continue}l=$b}else l=Zb;break;case Qb:if(l=Zb,"/"!==n||"/"!==ab(u,d+1))continue;d++;break;case Zb:if("/"!==n&&"\\"!==n){l=$b;continue}break;case $b:if("@"===n){h&&(u="%40"+u),h=!0,o=jA(u);for(var f=0;f<o.length;f++){var _=o[f];if(":"!==_||m){var g=Bb(_,Vb);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n===NA||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(h&&""===u)return"Invalid authority";d-=jA(u).length+1,u="",l=eR}else u+=n;break;case eR:case tR:if(t&&"file"===c.scheme){l=oR;continue}if(":"!==n||p){if(n===NA||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(c.isSpecial()&&""===u)return Tb;if(t&&""===u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=sR,t)return;continue}"["===n?p=!0:"]"===n&&(p=!1),u+=n}else{if(""===u)return Tb;if(s=c.parseHost(u))return s;if(u="",l=iR,t===tR)return}break;case iR:if(!cb(Ab,n)){if(n===NA||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()||t){if(""!==u){var v=nb(u,10);if(v>65535)return yb;c.port=c.isSpecial()&&v===Fb[c.scheme]?null:v,u=""}if(t)return;l=sR;continue}return yb}u+=n;break;case rR:if(c.scheme="file","/"===n||"\\"===n)l=nR;else{if(!i||"file"!==i.scheme){l=aR;continue}switch(n){case NA:c.host=i.host,c.path=GA(i.path),c.query=i.query;break;case"?":c.host=i.host,c.path=GA(i.path),c.query="",l=lR;break;case"#":c.host=i.host,c.path=GA(i.path),c.query=i.query,c.fragment="",l=dR;break;default:Wb(lb(GA(r,d),""))||(c.host=i.host,c.path=GA(i.path),c.shortenPath()),l=aR;continue}}break;case nR:if("/"===n||"\\"===n){l=oR;break}i&&"file"===i.scheme&&!Wb(lb(GA(r,d),""))&&(Hb(i.path[0],!0)?hb(c.path,i.path[0]):c.host=i.host),l=aR;continue;case oR:if(n===NA||"/"===n||"\\"===n||"?"===n||"#"===n){if(!t&&Hb(u))l=aR;else if(""===u){if(c.host="",t)return;l=sR}else{if(s=c.parseHost(u))return s;if("localhost"===c.host&&(c.host=""),t)return;u="",l=sR}continue}u+=n;break;case sR:if(c.isSpecial()){if(l=aR,"/"!==n&&"\\"!==n)continue}else if(t||"?"!==n)if(t||"#"!==n){if(n!==NA&&(l=aR,"/"!==n))continue}else c.fragment="",l=dR;else c.query="",l=lR;break;case aR:if(n===NA||"/"===n||"\\"===n&&c.isSpecial()||!t&&("?"===n||"#"===n)){if(".."===(a=gb(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"===n||"\\"===n&&c.isSpecial()||hb(c.path,"")):jb(u)?"/"===n||"\\"===n&&c.isSpecial()||hb(c.path,""):("file"===c.scheme&&!c.path.length&&Hb(u)&&(c.host&&(c.host=""),u=ab(u,0)+":"),hb(c.path,u)),u="","file"===c.scheme&&(n===NA||"?"===n||"#"===n))for(;c.path.length>1&&""===c.path[0];)mb(c.path);"?"===n?(c.query="",l=lR):"#"===n&&(c.fragment="",l=dR)}else u+=Bb(n,Ub);break;case cR:"?"===n?(c.query="",l=lR):"#"===n?(c.fragment="",l=dR):n!==NA&&(c.path[0]+=Bb(n,Lb));break;case lR:t||"#"!==n?n!==NA&&("'"===n&&c.isSpecial()?c.query+="%27":c.query+="#"===n?"%23":Bb(n,Lb)):(c.fragment="",l=dR);break;case dR:n!==NA&&(c.fragment+=Bb(n,xb))}d++}},parseHost:function(e){var t,i,r;if("["===ab(e,0)){if("]"!==ab(e,e.length-1))return Tb;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 ab(e,u)};if(":"===h()){if(":"!==ab(e,1))return;u+=2,d=++l}for(;h();){if(8===l)return;if(":"!==h()){for(t=i=0;i<4&&cb(kb,h());)t=16*t+nb(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(!cb(Ab,h()))return;for(;cb(Ab,h());){if(o=nb(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}(_b(e,1,-1)),!t)return Tb;this.host=t}else if(this.isSpecial()){if(e=KA(e),cb(wb,e))return Tb;if(t=function(e){var t,i,r,n,o,s,a,c=fb(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"===ab(n,0)&&(o=cb(bb,n)?16:8,n=_b(n,8===o?1:2)),""===n)s=0;else{if(!cb(10===o?Cb:8===o?Rb:kb,n))return e;s=nb(n,o)}hb(i,s)}for(r=0;r<t;r++)if(s=i[r],r===t-1){if(s>=sb(256,5-t))return null}else if(s>255)return null;for(a=ub(i),r=0;r<i.length;r++)a+=i[r]*sb(256,3-r);return a}(e),null===t)return Tb;this.host=t}else{if(cb(Db,e))return Tb;for(t="",i=jA(e),r=0;r<i.length;r++)t+=Bb(i[r],Lb);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return HA(Fb,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&Hb(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+=Mb(n),null!==o&&(l+=":"+o)):"file"===t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+lb(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw new rb(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new hR(e.path[0]).origin}catch(Hz){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+Mb(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(qA(e)+":",Gb)},getUsername:function(){return this.username},setUsername:function(e){var t=jA(qA(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=Bb(t[i],Vb)}},getPassword:function(){return this.password},setPassword:function(e){var t=jA(qA(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=Bb(t[i],Vb)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?Mb(e):Mb(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,eR)},getHostname:function(){var e=this.host;return null===e?"":Mb(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,tR)},getPort:function(){var e=this.port;return null===e?"":qA(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=qA(e))?this.port=null:this.parse(e,iR))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+lb(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,sR))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=qA(e))?this.query=null:("?"===ab(e,0)&&(e=_b(e,1)),this.query="",this.parse(e,lR)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=qA(e))?("#"===ab(e,0)&&(e=_b(e,1)),this.fragment="",this.parse(e,dR)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var hR=function(e){var t=FA(this,pR),i=YA(arguments.length,1)>1?arguments[1]:void 0,r=ZA(t,new uR(e,!1,i));PA||(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())},pR=hR.prototype,mR=function(e,t){return{get:function(){return $A(this)[e]()},set:t&&function(e){return $A(this)[t](e)},configurable:!0,enumerable:!0}};if(PA&&(BA(pR,"href",mR("serialize","setHref")),BA(pR,"origin",mR("getOrigin")),BA(pR,"protocol",mR("getProtocol","setProtocol")),BA(pR,"username",mR("getUsername","setUsername")),BA(pR,"password",mR("getPassword","setPassword")),BA(pR,"host",mR("getHost","setHost")),BA(pR,"hostname",mR("getHostname","setHostname")),BA(pR,"port",mR("getPort","setPort")),BA(pR,"pathname",mR("getPathname","setPathname")),BA(pR,"search",mR("getSearch","setSearch")),BA(pR,"searchParams",mR("getSearchParams")),BA(pR,"hash",mR("getHash","setHash"))),VA(pR,"toJSON",(function(){return $A(this).serialize()}),{enumerable:!0}),VA(pR,"toString",(function(){return $A(this).serialize()}),{enumerable:!0}),ib){var fR=ib.createObjectURL,_R=ib.revokeObjectURL;fR&&VA(hR,"createObjectURL",xA(fR,ib)),_R&&VA(hR,"revokeObjectURL",xA(_R,ib))}JA(hR,"URL"),OA({global:!0,constructor:!0,forced:!MA,sham:!PA},{URL:hR});var gR=u;nn({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return gR(URL.prototype.toString,this)}});let vR=!0,ER=!0;function TR(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function yR(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 SR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(vR=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function IR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ER=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function AR(){if("object"==typeof window){if(vR)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function bR(e,t){ER&&console.warn(e+" is deprecated, please use "+t+" instead.")}function RR(e){return"[object Object]"===Object.prototype.toString.call(e)}function CR(e){return RR(e)?Object.keys(e).reduce((function(t,i){const r=RR(e[i]),n=r?CR(e[i]):e[i],o=r&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[i]:n})}),{}):e}function kR(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?kR(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{kR(e,e.get(t),i)}))})))}function wR(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&&kR(e,i,n)}))})),n}const DR=AR;function NR(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const r=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const r="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==r.ideal){t.optional=t.optional||[];let e={};"number"==typeof r.ideal?(e[n("min",i)]=r.ideal,t.optional.push(e),e={},e[n("max",i)]=r.ideal,t.optional.push(e)):(e[n("",i)]=r.ideal,t.optional.push(e))}void 0!==r.exact&&"number"!=typeof r.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",i)]=r.exact):["min","max"].forEach((e=>{void 0!==r[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,i)]=r[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=r(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let s=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=r(e.video),DR("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return DR("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 OR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function PR(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 yR(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function MR(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 LR(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 xR(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=>wR(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}),yR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>wR(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 UR(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const r=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(r)&&this._shimmedLocalStreams[i.id].push(r):this._shimmedLocalStreams[i.id]=[i,r],r};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const r=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(r)};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function VR(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return UR(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 BR(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}))}function FR(e,t){yR(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var HR=Object.freeze({__proto__:null,shimMediaStream:OR,shimOnTrack:PR,shimGetSendersWithDtmf:MR,shimGetStats:LR,shimSenderReceiverGetStats:xR,shimAddTrackRemoveTrackWithNative:UR,shimAddTrackRemoveTrack:VR,shimPeerConnection:BR,fixNegotiationNeeded:FR,shimGetUserMedia:NR,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const r=i.video&&i.video.width,n=i.video&&i.video.height,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 WR(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){bR("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 jR(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 GR(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(vk){if("TypeError"!==vk.name)throw vk;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,o)}}function zR(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function KR(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),yR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function qR(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){bR("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function JR(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function YR(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 XR(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function QR(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function ZR(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 $R=Object.freeze({__proto__:null,shimOnTrack:jR,shimPeerConnection:GR,shimSenderGetStats:zR,shimReceiverGetStats:KR,shimRemoveStream:qR,shimRTCDataChannel:JR,shimAddTransceiver:YR,shimGetParameters:XR,shimCreateOffer:QR,shimCreateAnswer:ZR,shimGetUserMedia:WR,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 eC(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 tC(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 iC(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 rC(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(nC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function nC(e){return e&&void 0!==e.video?Object.assign({},e,{video:CR(e.video)}):e}function oC(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?(bR("RTCIceServer.url","RTCIceServer.urls"),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function sC(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function aC(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 cC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var lC=Object.freeze({__proto__:null,shimLocalStreamsAPI:eC,shimRemoteStreamsAPI:tC,shimCallbacksAPI:iC,shimGetUserMedia:rC,shimConstraints:nC,shimRTCIceServerUrls:oC,shimTrackEventTransceiver:sC,shimCreateOfferLegacy:aC,shimAudioContext:cC}),dC={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}(dC);var uC=dC.exports,hC=i(uC),pC=e({__proto__:null,default:hC},[uC]);function mC(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=hC.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,yR(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function fC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||yR(e,"icecandidate",(e=>{if(e.candidate){const t=hC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function _C(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=hC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=hC.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=hC.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 gC(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},yR(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function vC(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 EC(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function TC(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 yC(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 SC=Object.freeze({__proto__:null,shimRTCIceCandidate:mC,shimRTCIceCandidateRelayProtocol:fC,shimMaxMessageSize:_C,shimSendThrowTypeError:gC,shimConnectionState:vC,removeExtmapAllowMixed:EC,shimAddIceCandidateNullOrEmpty:TC,shimParameterlessSetLocalDescription:yC});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=AR,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=TR(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=TR(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=TR(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:SC,extractVersion:TR,disableLog:SR,disableWarnings:IR,sdp:pC};switch(r.browser){case"chrome":if(!HR||!BR||!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=HR,TC(e,r),yC(e),NR(e,r),OR(e),BR(e,r),PR(e),VR(e,r),MR(e),LR(e),xR(e),FR(e,r),mC(e),fC(e),vC(e),_C(e,r),gC(e),EC(e,r);break;case"firefox":if(!$R||!GR||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=$R,TC(e,r),yC(e),WR(e,r),GR(e,r),jR(e),qR(e),zR(e),KR(e),JR(e),YR(e),XR(e),QR(e),ZR(e),mC(e),vC(e),_C(e,r),gC(e);break;case"safari":if(!lC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=lC,TC(e,r),yC(e),oC(e),aC(e),iC(e),eC(e),tC(e),sC(e),rC(e),cC(e),mC(e),fC(e),_C(e,r),gC(e),EC(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var IC,AC,bC=Object.create,RC=Object.defineProperty,CC=Object.defineProperties,kC=Object.getOwnPropertyDescriptor,wC=Object.getOwnPropertyDescriptors,DC=Object.getOwnPropertyNames,NC=Object.getOwnPropertySymbols,OC=Object.getPrototypeOf,PC=Object.prototype.hasOwnProperty,MC=Object.prototype.propertyIsEnumerable,LC=Reflect.get,xC=Math.pow,UC=(e,t,i)=>t in e?RC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,VC=(e,t)=>{for(var i in t||(t={}))PC.call(t,i)&&UC(e,i,t[i]);if(NC)for(var i of NC(t))MC.call(t,i)&&UC(e,i,t[i]);return e},BC=(e,t)=>CC(e,wC(t)),FC=(IC=function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')},"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(IC,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):IC),HC=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),WC=(e,t)=>{for(var i in t)RC(e,i,{get:t[i],enumerable:!0})},jC=(e,t,i)=>(i=null!=e?bC(OC(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of DC(t))!PC.call(e,n)&&n!==i&&RC(e,n,{get:()=>t[n],enumerable:!(r=kC(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:RC(i,"default",{value:e,enumerable:!0}),e)),GC=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?kC(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&&RC(t,i,o),o},zC=(e,t,i)=>UC(e,"symbol"!=typeof t?t+"":t,i),KC=(e,t,i)=>LC(OC(e),i,t),qC=(e,t,i)=>new Promise(((r,n)=>{var o=e=>{try{a(i.next(e))}catch(dP){n(dP)}},s=e=>{try{a(i.throw(e))}catch(dP){n(dP)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),JC=HC(((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)})),YC=HC(((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")}))}))})),XC=HC((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=YC(),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}}))}))}})),QC=HC(((e,t)=>{var i=YC(),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"}})),ZC=HC((e=>{var t=XC(),i=QC(),r=YC();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})),$C=HC(((e,t)=>{!function(i){"object"==typeof e&&void 0!==t?t.exports=i():"function"==typeof define&&define.amd?define([],i):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).JSZip=i()}((function(){return function e(t,i,r){function n(s,a){if(!i[s]){if(!t[s]){var c="function"==typeof FC&&FC;if(!a&&c)return c(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var d=i[s]={exports:{}};t[s][0].call(d.exports,(function(e){return n(t[s][1][e]||e)}),d,d.exports,e,t,i,r)}return i[s].exports}for(var o="function"==typeof FC&&FC,s=0;s<r.length;s++)n(r[s]);return n}({1:[function(e,t,i){var r=e("./utils"),n=e("./support"),o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(e){for(var t,i,n,s,a,c,l,d=[],u=0,h=e.length,p=h,m="string"!==r.getTypeOf(e);u<e.length;)p=h-u,n=m?(t=e[u++],i=u<h?e[u++]:0,u<h?e[u++]:0):(t=e.charCodeAt(u++),i=u<h?e.charCodeAt(u++):0,u<h?e.charCodeAt(u++):0),s=t>>2,a=(3&t)<<4|i>>4,c=1<p?(15&i)<<2|n>>6:64,l=2<p?63&n:64,d.push(o.charAt(s)+o.charAt(a)+o.charAt(c)+o.charAt(l));return d.join("")},i.decode=function(e){var t,i,r,s,a,c,l=0,d=0,u="data:";if(e.substr(0,5)===u)throw new Error("Invalid base64 input, it looks like a data url.");var h,p=3*(e=e.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(e.charAt(e.length-1)===o.charAt(64)&&p--,e.charAt(e.length-2)===o.charAt(64)&&p--,p%1!=0)throw new Error("Invalid base64 input, bad content length.");for(h=n.uint8array?new Uint8Array(0|p):new Array(0|p);l<e.length;)t=o.indexOf(e.charAt(l++))<<2|(s=o.indexOf(e.charAt(l++)))>>4,i=(15&s)<<4|(a=o.indexOf(e.charAt(l++)))>>2,r=(3&a)<<6|(c=o.indexOf(e.charAt(l++))),h[d++]=t,64!==a&&(h[d++]=i),64!==c&&(h[d++]=r);return h}},{"./support":30,"./utils":32}],2:[function(e,t,i){var r=e("./external"),n=e("./stream/DataWorker"),o=e("./stream/Crc32Probe"),s=e("./stream/DataLengthProbe");function a(e,t,i,r,n){this.compressedSize=e,this.uncompressedSize=t,this.crc32=i,this.compression=r,this.compressedContent=n}a.prototype={getContentWorker:function(){var e=new n(r.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new s("data_length")),t=this;return e.on("end",(function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")})),e},getCompressedWorker:function(){return new n(r.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(e,t,i){return e.pipe(new o).pipe(new s("uncompressedSize")).pipe(t.compressWorker(i)).pipe(new s("compressedSize")).withStreamInfo("compression",t)},t.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,i){var r=e("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new r("STORE compression")},uncompressWorker:function(){return new r("STORE decompression")}},i.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,i){var r=e("./utils"),n=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==r.getTypeOf(e)?function(e,t,i){var r=n,o=0+i;e^=-1;for(var s=0;s<o;s++)e=e>>>8^r[255&(e^t[s])];return~e}(0|t,e,e.length):function(e,t,i){var r=n,o=0+i;e^=-1;for(var s=0;s<o;s++)e=e>>>8^r[255&(e^t.charCodeAt(s))];return~e}(0|t,e,e.length):0}},{"./utils":32}],5:[function(e,t,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(e,t,i){var r;r="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:r}},{lie:37}],7:[function(e,t,i){var r="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,n=e("pako"),o=e("./utils"),s=e("./stream/GenericWorker"),a=r?"uint8array":"array";function c(e,t){s.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}i.magic="\b\0",o.inherits(c,s),c.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(o.transformTo(a,e.data),!1)},c.prototype.flush=function(){s.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},c.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this._pako=null},c.prototype._createPako=function(){this._pako=new n[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},i.compressWorker=function(e){return new c("Deflate",e)},i.uncompressWorker=function(){return new c("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,i){function r(e,t){var i,r="";for(i=0;i<t;i++)r+=String.fromCharCode(255&e),e>>>=8;return r}function n(e,t,i,n,s,d){var u,h,p=e.file,m=e.compression,f=d!==a.utf8encode,_=o.transformTo("string",d(p.name)),g=o.transformTo("string",a.utf8encode(p.name)),v=p.comment,E=o.transformTo("string",d(v)),T=o.transformTo("string",a.utf8encode(v)),y=g.length!==p.name.length,S=T.length!==v.length,I="",A="",b="",R=p.dir,C=p.date,k={crc32:0,compressedSize:0,uncompressedSize:0};t&&!i||(k.crc32=e.crc32,k.compressedSize=e.compressedSize,k.uncompressedSize=e.uncompressedSize);var w=0;t&&(w|=8),f||!y&&!S||(w|=2048);var D,N,O,P=0,M=0;R&&(P|=16),"UNIX"===s?(M=798,P|=(D=p.unixPermissions,N=R,O=D,D||(O=N?16893:33204),(65535&O)<<16)):(M=20,P|=function(e){return 63&(e||0)}(p.dosPermissions)),u=C.getUTCHours(),u<<=6,u|=C.getUTCMinutes(),u<<=5,u|=C.getUTCSeconds()/2,h=C.getUTCFullYear()-1980,h<<=4,h|=C.getUTCMonth()+1,h<<=5,h|=C.getUTCDate(),y&&(A=r(1,1)+r(c(_),4)+g,I+="up"+r(A.length,2)+A),S&&(b=r(1,1)+r(c(E),4)+T,I+="uc"+r(b.length,2)+b);var L="";return L+="\n\0",L+=r(w,2),L+=m.magic,L+=r(u,2),L+=r(h,2),L+=r(k.crc32,4),L+=r(k.compressedSize,4),L+=r(k.uncompressedSize,4),L+=r(_.length,2),L+=r(I.length,2),{fileRecord:l.LOCAL_FILE_HEADER+L+_+I,dirRecord:l.CENTRAL_FILE_HEADER+r(M,2)+L+r(E.length,2)+"\0\0\0\0"+r(P,4)+r(n,4)+_+I+E}}var o=e("../utils"),s=e("../stream/GenericWorker"),a=e("../utf8"),c=e("../crc32"),l=e("../signature");function d(e,t,i,r){s.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=i,this.encodeFileName=r,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(d,s),d.prototype.push=function(e){var t=e.meta.percent||0,i=this.entriesCount,r=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,s.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:i?(t+100*(i-r-1))/i:100}}))},d.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var i=n(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:i.fileRecord,meta:{percent:0}})}else this.accumulate=!0},d.prototype.closedSource=function(e){this.accumulate=!1;var t,i=this.streamFiles&&!e.file.dir,o=n(e,i,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(o.dirRecord),i)this.push({data:(t=e,l.DATA_DESCRIPTOR+r(t.crc32,4)+r(t.compressedSize,4)+r(t.uncompressedSize,4)),meta:{percent:100}});else for(this.push({data:o.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},d.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var i,n,s,a,c,d,u=this.bytesWritten-e,h=(i=this.dirRecords.length,n=u,s=e,a=this.zipComment,c=this.encodeFileName,d=o.transformTo("string",c(a)),l.CENTRAL_DIRECTORY_END+"\0\0\0\0"+r(i,2)+r(i,2)+r(n,4)+r(s,4)+r(d.length,2)+d);this.push({data:h,meta:{percent:100}})},d.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},d.prototype.registerPrevious=function(e){this._sources.push(e);var t=this;return e.on("data",(function(e){t.processChunk(e)})),e.on("end",(function(){t.closedSource(t.previous.streamInfo),t._sources.length?t.prepareNextSource():t.end()})),e.on("error",(function(e){t.error(e)})),this},d.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},d.prototype.error=function(e){var t=this._sources;if(!s.prototype.error.call(this,e))return!1;for(var i=0;i<t.length;i++)try{t[i].error(e)}catch(r){}return!0},d.prototype.lock=function(){s.prototype.lock.call(this);for(var e=this._sources,t=0;t<e.length;t++)e[t].lock()},t.exports=d},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(e,t,i){var r=e("../compressions"),n=e("./ZipFileWorker");i.generateWorker=function(e,t,i){var o=new n(t.streamFiles,i,t.platform,t.encodeFileName),s=0;try{e.forEach((function(e,i){s++;var n=function(e,t){var i=e||t,n=r[i];if(!n)throw new Error(i+" is not a valid compression method !");return n}(i.options.compression,t.compression),a=i.options.compressionOptions||t.compressionOptions||{},c=i.dir,l=i.date;i._compressWorker(n,a).withStreamInfo("file",{name:e,dir:c,date:l,comment:i.comment||"",unixPermissions:i.unixPermissions,dosPermissions:i.dosPermissions}).pipe(o)})),o.entriesCount=s}catch(pM){o.error(pM)}return o}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(e,t,i){function r(){if(!(this instanceof r))return new r;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var e=new r;for(var t in this)"function"!=typeof this[t]&&(e[t]=this[t]);return e}}(r.prototype=e("./object")).loadAsync=e("./load"),r.support=e("./support"),r.defaults=e("./defaults"),r.version="3.10.1",r.loadAsync=function(e,t){return(new r).loadAsync(e,t)},r.external=e("./external"),t.exports=r},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(e,t,i){var r=e("./utils"),n=e("./external"),o=e("./utf8"),s=e("./zipEntries"),a=e("./stream/Crc32Probe"),c=e("./nodejsUtils");function l(e){return new n.Promise((function(t,i){var r=e.decompressed.getContentWorker().pipe(new a);r.on("error",(function(e){i(e)})).on("end",(function(){r.streamInfo.crc32!==e.decompressed.crc32?i(new Error("Corrupted zip : CRC32 mismatch")):t()})).resume()}))}t.exports=function(e,t){var i=this;return t=r.extend(t||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:o.utf8decode}),c.isNode&&c.isStream(e)?n.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):r.prepareContent("the loaded zip file",e,!0,t.optimizedBinaryString,t.base64).then((function(e){var i=new s(t);return i.load(e),i})).then((function(e){var i=[n.Promise.resolve(e)],r=e.files;if(t.checkCRC32)for(var o=0;o<r.length;o++)i.push(l(r[o]));return n.Promise.all(i)})).then((function(e){for(var n=e.shift(),o=n.files,s=0;s<o.length;s++){var a=o[s],c=a.fileNameStr,l=r.resolve(a.fileNameStr);i.file(l,a.decompressed,{binary:!0,optimizedBinaryString:!0,date:a.date,dir:a.dir,comment:a.fileCommentStr.length?a.fileCommentStr:null,unixPermissions:a.unixPermissions,dosPermissions:a.dosPermissions,createFolders:t.createFolders}),a.dir||(i.file(l).unsafeOriginalName=c)}return n.zipComment.length&&(i.comment=n.zipComment),i}))}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(e,t,i){var r=e("../utils"),n=e("../stream/GenericWorker");function o(e,t){n.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=!1,this._bindStream(t)}r.inherits(o,n),o.prototype._bindStream=function(e){var t=this;(this._stream=e).pause(),e.on("data",(function(e){t.push({data:e,meta:{percent:0}})})).on("error",(function(e){t.isPaused?this.generatedError=e:t.error(e)})).on("end",(function(){t.isPaused?t._upstreamEnded=!0:t.end()}))},o.prototype.pause=function(){return!!n.prototype.pause.call(this)&&(this._stream.pause(),!0)},o.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},t.exports=o},{"../stream/GenericWorker":28,"../utils":32}],13:[function(e,t,i){var r=e("readable-stream").Readable;function n(e,t,i){r.call(this,t),this._helper=e;var n=this;e.on("data",(function(e,t){n.push(e)||n._helper.pause(),i&&i(t)})).on("error",(function(e){n.emit("error",e)})).on("end",(function(){n.push(null)}))}e("../utils").inherits(n,r),n.prototype._read=function(){this._helper.resume()},t.exports=n},{"../utils":32,"readable-stream":16}],14:[function(e,t,i){t.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(e,t){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,t);if("number"==typeof e)throw new Error('The "data" argument must not be a number');return new Buffer(e,t)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&"function"==typeof e.on&&"function"==typeof e.pause&&"function"==typeof e.resume}}},{}],15:[function(e,t,i){function r(e,t,i){var r,n=o.getTypeOf(t),a=o.extend(i||{},c);a.date=a.date||new Date,null!==a.compression&&(a.compression=a.compression.toUpperCase()),"string"==typeof a.unixPermissions&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&16384&a.unixPermissions&&(a.dir=!0),a.dosPermissions&&16&a.dosPermissions&&(a.dir=!0),a.dir&&(e=f(e)),a.createFolders&&(r=m(e))&&_.call(this,r,!0);var u="string"===n&&!1===a.binary&&!1===a.base64;i&&void 0!==i.binary||(a.binary=!u),(t instanceof l&&0===t.uncompressedSize||a.dir||!t||0===t.length)&&(a.base64=!1,a.binary=!0,t="",a.compression="STORE",n="string");var g;g=t instanceof l||t instanceof s?t:h.isNode&&h.isStream(t)?new p(e,t):o.prepareContent(e,t,a.binary,a.optimizedBinaryString,a.base64);var v=new d(e,g,a);this.files[e]=v}var n=e("./utf8"),o=e("./utils"),s=e("./stream/GenericWorker"),a=e("./stream/StreamHelper"),c=e("./defaults"),l=e("./compressedObject"),d=e("./zipObject"),u=e("./generate"),h=e("./nodejsUtils"),p=e("./nodejs/NodejsStreamInputAdapter"),m=function(e){"/"===e.slice(-1)&&(e=e.substring(0,e.length-1));var t=e.lastIndexOf("/");return 0<t?e.substring(0,t):""},f=function(e){return"/"!==e.slice(-1)&&(e+="/"),e},_=function(e,t){return t=void 0!==t?t:c.createFolders,e=f(e),this.files[e]||r.call(this,e,null,{dir:!0,createFolders:t}),this.files[e]};function g(e){return"[object RegExp]"===Object.prototype.toString.call(e)}var v={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(e){var t,i,r;for(t in this.files)r=this.files[t],(i=t.slice(this.root.length,t.length))&&t.slice(0,this.root.length)===this.root&&e(i,r)},filter:function(e){var t=[];return this.forEach((function(i,r){e(i,r)&&t.push(r)})),t},file:function(e,t,i){if(1!==arguments.length)return e=this.root+e,r.call(this,e,t,i),this;if(g(e)){var n=e;return this.filter((function(e,t){return!t.dir&&n.test(e)}))}var o=this.files[this.root+e];return o&&!o.dir?o:null},folder:function(e){if(!e)return this;if(g(e))return this.filter((function(t,i){return i.dir&&e.test(t)}));var t=this.root+e,i=_.call(this,t),r=this.clone();return r.root=i.name,r},remove:function(e){e=this.root+e;var t=this.files[e];if(t||("/"!==e.slice(-1)&&(e+="/"),t=this.files[e]),t&&!t.dir)delete this.files[e];else for(var i=this.filter((function(t,i){return i.name.slice(0,e.length)===e})),r=0;r<i.length;r++)delete this.files[i[r].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(e){var t,i={};try{if((i=o.extend(e||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:n.utf8encode})).type=i.type.toLowerCase(),i.compression=i.compression.toUpperCase(),"binarystring"===i.type&&(i.type="string"),!i.type)throw new Error("No output type specified.");o.checkSupport(i.type),"darwin"!==i.platform&&"freebsd"!==i.platform&&"linux"!==i.platform&&"sunos"!==i.platform||(i.platform="UNIX"),"win32"===i.platform&&(i.platform="DOS");var r=i.comment||this.comment||"";t=u.generateWorker(this,i,r)}catch(c){(t=new s("error")).error(c)}return new a(t,i.type||"string",i.mimeType)},generateAsync:function(e,t){return this.generateInternalStream(e).accumulate(t)},generateNodeStream:function(e,t){return(e=e||{}).type||(e.type="nodebuffer"),this.generateInternalStream(e).toNodejsStream(t)}};t.exports=v},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(e,t,i){t.exports=e("stream")},{stream:void 0}],17:[function(e,t,i){var r=e("./DataReader");function n(e){r.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=255&e[t]}e("../utils").inherits(n,r),n.prototype.byteAt=function(e){return this.data[this.zero+e]},n.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),i=e.charCodeAt(1),r=e.charCodeAt(2),n=e.charCodeAt(3),o=this.length-4;0<=o;--o)if(this.data[o]===t&&this.data[o+1]===i&&this.data[o+2]===r&&this.data[o+3]===n)return o-this.zero;return-1},n.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),i=e.charCodeAt(1),r=e.charCodeAt(2),n=e.charCodeAt(3),o=this.readData(4);return t===o[0]&&i===o[1]&&r===o[2]&&n===o[3]},n.prototype.readData=function(e){if(this.checkOffset(e),0===e)return[];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=n},{"../utils":32,"./DataReader":18}],18:[function(e,t,i){var r=e("../utils");function n(e){this.data=e,this.length=e.length,this.index=0,this.zero=0}n.prototype={checkOffset:function(e){this.checkIndex(this.index+e)},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e},skip:function(e){this.setIndex(this.index+e)},byteAt:function(){},readInt:function(e){var t,i=0;for(this.checkOffset(e),t=this.index+e-1;t>=this.index;t--)i=(i<<8)+this.byteAt(t);return this.index+=e,i},readString:function(e){return r.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=n},{"../utils":32}],19:[function(e,t,i){var r=e("./Uint8ArrayReader");function n(e){r.call(this,e)}e("../utils").inherits(n,r),n.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=n},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,i){var r=e("./DataReader");function n(e){r.call(this,e)}e("../utils").inherits(n,r),n.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},n.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},n.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},n.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=n},{"../utils":32,"./DataReader":18}],21:[function(e,t,i){var r=e("./ArrayReader");function n(e){r.call(this,e)}e("../utils").inherits(n,r),n.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=n},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,i){var r=e("../utils"),n=e("../support"),o=e("./ArrayReader"),s=e("./StringReader"),a=e("./NodeBufferReader"),c=e("./Uint8ArrayReader");t.exports=function(e){var t=r.getTypeOf(e);return r.checkSupport(t),"string"!==t||n.uint8array?"nodebuffer"===t?new a(e):n.uint8array?new c(r.transformTo("uint8array",e)):new o(r.transformTo("array",e)):new s(e)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\b"},{}],24:[function(e,t,i){var r=e("./GenericWorker"),n=e("../utils");function o(e){r.call(this,"ConvertWorker to "+e),this.destType=e}n.inherits(o,r),o.prototype.processChunk=function(e){this.push({data:n.transformTo(this.destType,e.data),meta:e.meta})},t.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,i){var r=e("./GenericWorker"),n=e("../crc32");function o(){r.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(o,r),o.prototype.processChunk=function(e){this.streamInfo.crc32=n(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,i){var r=e("../utils"),n=e("./GenericWorker");function o(e){n.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}r.inherits(o,n),o.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}n.prototype.processChunk.call(this,e)},t.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,i){var r=e("../utils"),n=e("./GenericWorker");function o(e){n.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then((function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=r.getTypeOf(e),t.isPaused||t._tickAndRepeat()}),(function(e){t.error(e)}))}r.inherits(o,n),o.prototype.cleanUp=function(){n.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,r.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(r.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,i){function r(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}r.prototype={push:function(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(pP){this.emit("error",pP)}return!0},error:function(e){return!this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var i=0;i<this._listeners[e].length;i++)this._listeners[e][i].call(this,t)},pipe:function(e){return e.registerPrevious(this)},registerPrevious:function(e){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=e.streamInfo,this.mergeStreamInfo(),this.previous=e;var t=this;return e.on("data",(function(e){t.processChunk(e)})),e.on("end",(function(){t.end()})),e.on("error",(function(e){t.error(e)})),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var e=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),e=!0),this.previous&&this.previous.resume(),!e},flush:function(){},processChunk:function(e){this.push(e)},withStreamInfo:function(e,t){return this.extraStreamInfo[e]=t,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var e in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,e)&&(this.streamInfo[e]=this.extraStreamInfo[e])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var e="Worker "+this.name;return this.previous?this.previous+" -> "+e:e}},t.exports=r},{}],29:[function(e,t,i){var r=e("../utils"),n=e("./ConvertWorker"),o=e("./GenericWorker"),s=e("../base64"),a=e("../support"),c=e("../external"),l=null;if(a.nodestream)try{l=e("../nodejs/NodejsStreamOutputAdapter")}catch(lP){}function d(e,t,i){var s=t;switch(t){case"blob":case"arraybuffer":s="uint8array";break;case"base64":s="string"}try{this._internalType=s,this._outputType=t,this._mimeType=i,r.checkSupport(s),this._worker=e.pipe(new n(s)),e.lock()}catch(gP){this._worker=new o("error"),this._worker.error(gP)}}d.prototype={accumulate:function(e){return function(e,t){return new c.Promise((function(i,n){var o=[],a=e._internalType,c=e._outputType,l=e._mimeType;e.on("data",(function(e,i){o.push(e),t&&t(i)})).on("error",(function(e){o=[],n(e)})).on("end",(function(){try{var e=function(e,t,i){switch(e){case"blob":return r.newBlob(r.transformTo("arraybuffer",t),i);case"base64":return s.encode(t);default:return r.transformTo(e,t)}}(c,function(e,t){var i,r=0,n=null,o=0;for(i=0;i<t.length;i++)o+=t[i].length;switch(e){case"string":return t.join("");case"array":return Array.prototype.concat.apply([],t);case"uint8array":for(n=new Uint8Array(o),i=0;i<t.length;i++)n.set(t[i],r),r+=t[i].length;return n;case"nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}(a,o),l);i(e)}catch(mM){n(mM)}o=[]})).resume()}))}(this,e)},on:function(e,t){var i=this;return"data"===e?this._worker.on(e,(function(e){t.call(i,e.data,e.meta)})):this._worker.on(e,(function(){r.delay(t,arguments,i)})),this},resume:function(){return r.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(e){if(r.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new l(this,{objectMode:"nodebuffer"!==this._outputType},e)}},t.exports=d},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(e,t,i){if(i.base64=!0,i.array=!0,i.string=!0,i.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,i.nodebuffer="undefined"!=typeof Buffer,i.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)i.blob=!1;else{var r=new ArrayBuffer(0);try{i.blob=0===new Blob([r],{type:"application/zip"}).size}catch(_P){try{var n=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);n.append(r),i.blob=0===n.getBlob("application/zip").size}catch(Ek){i.blob=!1}}}try{i.nodestream=!!e("readable-stream").Readable}catch(_P){i.nodestream=!1}},{"readable-stream":16}],31:[function(e,t,i){for(var r=e("./utils"),n=e("./support"),o=e("./nodejsUtils"),s=e("./stream/GenericWorker"),a=new Array(256),c=0;c<256;c++)a[c]=252<=c?6:248<=c?5:240<=c?4:224<=c?3:192<=c?2:1;function l(){s.call(this,"utf-8 decode"),this.leftOver=null}function d(){s.call(this,"utf-8 encode")}a[254]=a[254]=1,i.utf8encode=function(e){return n.nodebuffer?o.newBufferFrom(e,"utf-8"):function(e){var t,i,r,o,s,a=e.length,c=0;for(o=0;o<a;o++)55296==(64512&(i=e.charCodeAt(o)))&&o+1<a&&56320==(64512&(r=e.charCodeAt(o+1)))&&(i=65536+(i-55296<<10)+(r-56320),o++),c+=i<128?1:i<2048?2:i<65536?3:4;for(t=n.uint8array?new Uint8Array(c):new Array(c),o=s=0;s<c;o++)55296==(64512&(i=e.charCodeAt(o)))&&o+1<a&&56320==(64512&(r=e.charCodeAt(o+1)))&&(i=65536+(i-55296<<10)+(r-56320),o++),i<128?t[s++]=i:(i<2048?t[s++]=192|i>>>6:(i<65536?t[s++]=224|i>>>12:(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63),t[s++]=128|i>>>6&63),t[s++]=128|63&i);return t}(e)},i.utf8decode=function(e){return n.nodebuffer?r.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,i,n,o,s=e.length,c=new Array(2*s);for(t=i=0;t<s;)if((n=e[t++])<128)c[i++]=n;else if(4<(o=a[n]))c[i++]=65533,t+=o-1;else{for(n&=2===o?31:3===o?15:7;1<o&&t<s;)n=n<<6|63&e[t++],o--;1<o?c[i++]=65533:n<65536?c[i++]=n:(n-=65536,c[i++]=55296|n>>10&1023,c[i++]=56320|1023&n)}return c.length!==i&&(c.subarray?c=c.subarray(0,i):c.length=i),r.applyFromCharCode(c)}(e=r.transformTo(n.uint8array?"uint8array":"array",e))},r.inherits(l,s),l.prototype.processChunk=function(e){var t=r.transformTo(n.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(n.uint8array){var o=t;(t=new Uint8Array(o.length+this.leftOver.length)).set(this.leftOver,0),t.set(o,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var s=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;0<=i&&128==(192&e[i]);)i--;return i<0||0===i?t:i+a[e[i]]>t?i:t}(t),c=t;s!==t.length&&(n.uint8array?(c=t.subarray(0,s),this.leftOver=t.subarray(s,t.length)):(c=t.slice(0,s),this.leftOver=t.slice(s,t.length))),this.push({data:i.utf8decode(c),meta:e.meta})},l.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=l,r.inherits(d,s),d.prototype.processChunk=function(e){this.push({data:i.utf8encode(e.data),meta:e.meta})},i.Utf8EncodeWorker=d},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,i){var r=e("./support"),n=e("./base64"),o=e("./nodejsUtils"),s=e("./external");function a(e){return e}function c(e,t){for(var i=0;i<e.length;++i)t[i]=255&e.charCodeAt(i);return t}e("setimmediate"),i.newBlob=function(e,t){i.checkSupport("blob");try{return new Blob([e],{type:t})}catch(gP){try{var r=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return r.append(e),r.getBlob(t)}catch(n){throw new Error("Bug : can't construct the Blob.")}}};var l={stringifyByChunk:function(e,t,i){var r=[],n=0,o=e.length;if(o<=i)return String.fromCharCode.apply(null,e);for(;n<o;)"array"===t||"nodebuffer"===t?r.push(String.fromCharCode.apply(null,e.slice(n,Math.min(n+i,o)))):r.push(String.fromCharCode.apply(null,e.subarray(n,Math.min(n+i,o)))),n+=i;return r.join("")},stringifyByChar:function(e){for(var t="",i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t},applyCanBeUsed:{uint8array:function(){try{return r.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(e){return!1}}(),nodebuffer:function(){try{return r.nodebuffer&&1===String.fromCharCode.apply(null,o.allocBuffer(1)).length}catch(e){return!1}}()}};function d(e){var t=65536,r=i.getTypeOf(e),n=!0;if("uint8array"===r?n=l.applyCanBeUsed.uint8array:"nodebuffer"===r&&(n=l.applyCanBeUsed.nodebuffer),n)for(;1<t;)try{return l.stringifyByChunk(e,r,t)}catch(o){t=Math.floor(t/2)}return l.stringifyByChar(e)}function u(e,t){for(var i=0;i<e.length;i++)t[i]=e[i];return t}i.applyFromCharCode=d;var h={};h.string={string:a,array:function(e){return c(e,new Array(e.length))},arraybuffer:function(e){return h.string.uint8array(e).buffer},uint8array:function(e){return c(e,new Uint8Array(e.length))},nodebuffer:function(e){return c(e,o.allocBuffer(e.length))}},h.array={string:d,array:a,arraybuffer:function(e){return new Uint8Array(e).buffer},uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return o.newBufferFrom(e)}},h.arraybuffer={string:function(e){return d(new Uint8Array(e))},array:function(e){return u(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:a,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return o.newBufferFrom(new Uint8Array(e))}},h.uint8array={string:d,array:function(e){return u(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:a,nodebuffer:function(e){return o.newBufferFrom(e)}},h.nodebuffer={string:d,array:function(e){return u(e,new Array(e.length))},arraybuffer:function(e){return h.nodebuffer.uint8array(e).buffer},uint8array:function(e){return u(e,new Uint8Array(e.length))},nodebuffer:a},i.transformTo=function(e,t){if(t=t||"",!e)return t;i.checkSupport(e);var r=i.getTypeOf(t);return h[r][e](t)},i.resolve=function(e){for(var t=e.split("/"),i=[],r=0;r<t.length;r++){var n=t[r];"."===n||""===n&&0!==r&&r!==t.length-1||(".."===n?i.pop():i.push(n))}return i.join("/")},i.getTypeOf=function(e){return"string"==typeof e?"string":"[object Array]"===Object.prototype.toString.call(e)?"array":r.nodebuffer&&o.isBuffer(e)?"nodebuffer":r.uint8array&&e instanceof Uint8Array?"uint8array":r.arraybuffer&&e instanceof ArrayBuffer?"arraybuffer":void 0},i.checkSupport=function(e){if(!r[e.toLowerCase()])throw new Error(e+" is not supported by this platform")},i.MAX_VALUE_16BITS=65535,i.MAX_VALUE_32BITS=-1,i.pretty=function(e){var t,i,r="";for(i=0;i<(e||"").length;i++)r+="\\x"+((t=e.charCodeAt(i))<16?"0":"")+t.toString(16).toUpperCase();return r},i.delay=function(e,t,i){setImmediate((function(){e.apply(i||null,t||[])}))},i.inherits=function(e,t){function i(){}i.prototype=t.prototype,e.prototype=new i},i.extend=function(){var e,t,i={};for(e=0;e<arguments.length;e++)for(t in arguments[e])Object.prototype.hasOwnProperty.call(arguments[e],t)&&void 0===i[t]&&(i[t]=arguments[e][t]);return i},i.prepareContent=function(e,t,o,a,l){return s.Promise.resolve(t).then((function(e){return r.blob&&(e instanceof Blob||-1!==["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(e)))&&"undefined"!=typeof FileReader?new s.Promise((function(t,i){var r=new FileReader;r.onload=function(e){t(e.target.result)},r.onerror=function(e){i(e.target.error)},r.readAsArrayBuffer(e)})):e})).then((function(t){var d,u=i.getTypeOf(t);return u?("arraybuffer"===u?t=i.transformTo("uint8array",t):"string"===u&&(l?t=n.decode(t):o&&!0!==a&&(t=c(d=t,r.uint8array?new Uint8Array(d.length):new Array(d.length)))),t):s.Promise.reject(new Error("Can't read the data of '"+e+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))}))}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(e,t,i){var r=e("./reader/readerFor"),n=e("./utils"),o=e("./signature"),s=e("./zipEntry"),a=e("./support");function c(e){this.files=[],this.loadOptions=e}c.prototype={checkSignature:function(e){if(!this.reader.readAndCheckSignature(e)){this.reader.index-=4;var t=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+n.pretty(t)+", expected "+n.pretty(e)+")")}},isSignature:function(e,t){var i=this.reader.index;this.reader.setIndex(e);var r=this.reader.readString(4)===t;return this.reader.setIndex(i),r},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var e=this.reader.readData(this.zipCommentLength),t=a.uint8array?"uint8array":"array",i=n.transformTo(t,e);this.zipComment=this.loadOptions.decodeFileName(i)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var e,t,i,r=this.zip64EndOfCentralSize-44;0<r;)e=this.reader.readInt(2),t=this.reader.readInt(4),i=this.reader.readData(t),this.zip64ExtensibleData[e]={id:e,length:t,value:i}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var e,t;for(e=0;e<this.files.length;e++)t=this.files[e],this.reader.setIndex(t.localHeaderOffset),this.checkSignature(o.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes()},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(o.CENTRAL_FILE_HEADER);)(e=new s({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(e);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var e=this.reader.lastIndexOfSignature(o.CENTRAL_DIRECTORY_END);if(e<0)throw this.isSignature(0,o.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(e);var t=e;if(this.checkSignature(o.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===n.MAX_VALUE_16BITS||this.diskWithCentralDirStart===n.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===n.MAX_VALUE_16BITS||this.centralDirRecords===n.MAX_VALUE_16BITS||this.centralDirSize===n.MAX_VALUE_32BITS||this.centralDirOffset===n.MAX_VALUE_32BITS){if(this.zip64=!0,(e=this.reader.lastIndexOfSignature(o.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(e),this.checkSignature(o.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,o.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(o.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(o.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var i=this.centralDirOffset+this.centralDirSize;this.zip64&&(i+=20,i+=12+this.zip64EndOfCentralSize);var r=t-i;if(0<r)this.isSignature(t,o.CENTRAL_FILE_HEADER)||(this.reader.zero=r);else if(r<0)throw new Error("Corrupted zip: missing "+Math.abs(r)+" bytes.")},prepareReader:function(e){this.reader=r(e)},load:function(e){this.prepareReader(e),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},t.exports=c},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(e,t,i){var r=e("./reader/readerFor"),n=e("./utils"),o=e("./compressedObject"),s=e("./crc32"),a=e("./utf8"),c=e("./compressions"),l=e("./support");function d(e,t){this.options=e,this.loadOptions=t}d.prototype={isEncrypted:function(){return!(1&~this.bitFlag)},useUTF8:function(){return!(2048&~this.bitFlag)},readLocalPart:function(e){var t,i;if(e.skip(22),this.fileNameLength=e.readInt(2),i=e.readInt(2),this.fileName=e.readData(this.fileNameLength),e.skip(i),-1===this.compressedSize||-1===this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(null===(t=function(e){for(var t in c)if(Object.prototype.hasOwnProperty.call(c,t)&&c[t].magic===e)return c[t];return null}(this.compressionMethod)))throw new Error("Corrupted zip : compression "+n.pretty(this.compressionMethod)+" unknown (inner file : "+n.transformTo("string",this.fileName)+")");this.decompressed=new o(this.compressedSize,this.uncompressedSize,this.crc32,t,e.readData(this.compressedSize))},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=r(this.extraFields[1].value);this.uncompressedSize===n.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===n.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===n.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===n.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t,i,r,n=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4<n;)t=e.readInt(2),i=e.readInt(2),r=e.readData(i),this.extraFields[t]={id:t,length:i,value:r};e.setIndex(n)},handleUTF8:function(){var e=l.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=a.utf8decode(this.fileName),this.fileCommentStr=a.utf8decode(this.fileComment);else{var t=this.findExtraFieldUnicodePath();if(null!==t)this.fileNameStr=t;else{var i=n.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(i)}var r=this.findExtraFieldUnicodeComment();if(null!==r)this.fileCommentStr=r;else{var o=n.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(o)}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=r(e.value);return 1!==t.readInt(1)||s(this.fileName)!==t.readInt(4)?null:a.utf8decode(t.readData(e.length-5))}return null},findExtraFieldUnicodeComment:function(){var e=this.extraFields[25461];if(e){var t=r(e.value);return 1!==t.readInt(1)||s(this.fileComment)!==t.readInt(4)?null:a.utf8decode(t.readData(e.length-5))}return null}},t.exports=d},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(e,t,i){function r(e,t,i){this.name=e,this.dir=i.dir,this.date=i.date,this.comment=i.comment,this.unixPermissions=i.unixPermissions,this.dosPermissions=i.dosPermissions,this._data=t,this._dataBinary=i.binary,this.options={compression:i.compression,compressionOptions:i.compressionOptions}}var n=e("./stream/StreamHelper"),o=e("./stream/DataWorker"),s=e("./utf8"),a=e("./compressedObject"),c=e("./stream/GenericWorker");r.prototype={internalStream:function(e){var t=null,i="string";try{if(!e)throw new Error("No output type specified.");var r="string"===(i=e.toLowerCase())||"text"===i;"binarystring"!==i&&"text"!==i||(i="string"),t=this._decompressWorker();var o=!this._dataBinary;o&&!r&&(t=t.pipe(new s.Utf8EncodeWorker)),!o&&r&&(t=t.pipe(new s.Utf8DecodeWorker))}catch(a){(t=new c("error")).error(a)}return new n(t,i,"")},async:function(e,t){return this.internalStream(e).accumulate(t)},nodeStream:function(e,t){return this.internalStream(e||"nodebuffer").toNodejsStream(t)},_compressWorker:function(e,t){if(this._data instanceof a&&this._data.compression.magic===e.magic)return this._data.getCompressedWorker();var i=this._decompressWorker();return this._dataBinary||(i=i.pipe(new s.Utf8EncodeWorker)),a.createWorkerFrom(i,e,t)},_decompressWorker:function(){return this._data instanceof a?this._data.getContentWorker():this._data instanceof c?this._data:new o(this._data)}};for(var l=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],d=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},u=0;u<l.length;u++)r.prototype[l[u]]=d;t.exports=r},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(e,t,i){(function(e){var i,r,n=e.MutationObserver||e.WebKitMutationObserver;if(n){var o=0,s=new n(d),a=e.document.createTextNode("");s.observe(a,{characterData:!0}),i=function(){a.data=o=++o%2}}else if(e.setImmediate||void 0===e.MessageChannel)i="document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var t=e.document.createElement("script");t.onreadystatechange=function(){d(),t.onreadystatechange=null,t.parentNode.removeChild(t),t=null},e.document.documentElement.appendChild(t)}:function(){setTimeout(d,0)};else{var c=new e.MessageChannel;c.port1.onmessage=d,i=function(){c.port2.postMessage(0)}}var l=[];function d(){var e,t;r=!0;for(var i=l.length;i;){for(t=l,l=[],e=-1;++e<i;)t[e]();i=l.length}r=!1}t.exports=function(e){1!==l.push(e)||r||i()}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(e,t,i){var r=e("immediate");function n(){}var o={},s=["REJECTED"],a=["FULFILLED"],c=["PENDING"];function l(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=c,this.queue=[],this.outcome=void 0,e!==n&&p(this,e)}function d(e,t,i){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof i&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}function u(e,t,i){r((function(){var r;try{r=t(i)}catch(n){return o.reject(e,n)}r===e?o.reject(e,new TypeError("Cannot resolve promise with itself")):o.resolve(e,r)}))}function h(e){var t=e&&e.then;if(e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof t)return function(){t.apply(e,arguments)}}function p(e,t){var i=!1;function r(t){i||(i=!0,o.reject(e,t))}function n(t){i||(i=!0,o.resolve(e,t))}var s=m((function(){t(n,r)}));"error"===s.status&&r(s.value)}function m(e,t){var i={};try{i.value=e(t),i.status="success"}catch(r){i.status="error",i.value=r}return i}(t.exports=l).prototype.finally=function(e){if("function"!=typeof e)return this;var t=this.constructor;return this.then((function(i){return t.resolve(e()).then((function(){return i}))}),(function(i){return t.resolve(e()).then((function(){throw i}))}))},l.prototype.catch=function(e){return this.then(null,e)},l.prototype.then=function(e,t){if("function"!=typeof e&&this.state===a||"function"!=typeof t&&this.state===s)return this;var i=new this.constructor(n);return this.state!==c?u(i,this.state===a?e:t,this.outcome):this.queue.push(new d(i,e,t)),i},d.prototype.callFulfilled=function(e){o.resolve(this.promise,e)},d.prototype.otherCallFulfilled=function(e){u(this.promise,this.onFulfilled,e)},d.prototype.callRejected=function(e){o.reject(this.promise,e)},d.prototype.otherCallRejected=function(e){u(this.promise,this.onRejected,e)},o.resolve=function(e,t){var i=m(h,t);if("error"===i.status)return o.reject(e,i.value);var r=i.value;if(r)p(e,r);else{e.state=a,e.outcome=t;for(var n=-1,s=e.queue.length;++n<s;)e.queue[n].callFulfilled(t)}return e},o.reject=function(e,t){e.state=s,e.outcome=t;for(var i=-1,r=e.queue.length;++i<r;)e.queue[i].callRejected(t);return e},l.resolve=function(e){return e instanceof this?e:o.resolve(new this(n),e)},l.reject=function(e){var t=new this(n);return o.reject(t,e)},l.all=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var i=e.length,r=!1;if(!i)return this.resolve([]);for(var s=new Array(i),a=0,c=-1,l=new this(n);++c<i;)d(e[c],c);return l;function d(e,n){t.resolve(e).then((function(e){s[n]=e,++a!==i||r||(r=!0,o.resolve(l,s))}),(function(e){r||(r=!0,o.reject(l,e))}))}},l.race=function(e){if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var t,i=e.length,r=!1;if(!i)return this.resolve([]);for(var s=-1,a=new this(n);++s<i;)t=e[s],this.resolve(t).then((function(e){r||(r=!0,o.resolve(a,e))}),(function(e){r||(r=!0,o.reject(a,e))}));return a}},{immediate:36}],38:[function(e,t,i){var r={};(0,e("./lib/utils/common").assign)(r,e("./lib/deflate"),e("./lib/inflate"),e("./lib/zlib/constants")),t.exports=r},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(e,t,i){var r=e("./zlib/deflate"),n=e("./utils/common"),o=e("./utils/strings"),s=e("./zlib/messages"),a=e("./zlib/zstream"),c=Object.prototype.toString;function l(e){if(!(this instanceof l))return new l(e);this.options=n.assign({level:-1,method:8,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,to:""},e||{});var t=this.options;t.raw&&0<t.windowBits?t.windowBits=-t.windowBits:t.gzip&&0<t.windowBits&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var i=r.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(0!==i)throw new Error(s[i]);if(t.header&&r.deflateSetHeader(this.strm,t.header),t.dictionary){var d;if(d="string"==typeof t.dictionary?o.string2buf(t.dictionary):"[object ArrayBuffer]"===c.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,0!==(i=r.deflateSetDictionary(this.strm,d)))throw new Error(s[i]);this._dict_set=!0}}function d(e,t){var i=new l(t);if(i.push(e,!0),i.err)throw i.msg||s[i.err];return i.result}l.prototype.push=function(e,t){var i,s,a=this.strm,l=this.options.chunkSize;if(this.ended)return!1;s=t===~~t?t:!0===t?4:0,"string"==typeof e?a.input=o.string2buf(e):"[object ArrayBuffer]"===c.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new n.Buf8(l),a.next_out=0,a.avail_out=l),1!==(i=r.deflate(a,s))&&0!==i)return this.onEnd(i),!(this.ended=!0);0!==a.avail_out&&(0!==a.avail_in||4!==s&&2!==s)||("string"===this.options.to?this.onData(o.buf2binstring(n.shrinkBuf(a.output,a.next_out))):this.onData(n.shrinkBuf(a.output,a.next_out)))}while((0<a.avail_in||0===a.avail_out)&&1!==i);return 4===s?(i=r.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,0===i):2!==s||(this.onEnd(0),!(a.avail_out=0))},l.prototype.onData=function(e){this.chunks.push(e)},l.prototype.onEnd=function(e){0===e&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=n.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Deflate=l,i.deflate=d,i.deflateRaw=function(e,t){return(t=t||{}).raw=!0,d(e,t)},i.gzip=function(e,t){return(t=t||{}).gzip=!0,d(e,t)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(e,t,i){var r=e("./zlib/inflate"),n=e("./utils/common"),o=e("./utils/strings"),s=e("./zlib/constants"),a=e("./zlib/messages"),c=e("./zlib/zstream"),l=e("./zlib/gzheader"),d=Object.prototype.toString;function u(e){if(!(this instanceof u))return new u(e);this.options=n.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var i=r.inflateInit2(this.strm,t.windowBits);if(i!==s.Z_OK)throw new Error(a[i]);this.header=new l,r.inflateGetHeader(this.strm,this.header)}function h(e,t){var i=new u(t);if(i.push(e,!0),i.err)throw i.msg||a[i.err];return i.result}u.prototype.push=function(e,t){var i,a,c,l,u,h,p=this.strm,m=this.options.chunkSize,f=this.options.dictionary,_=!1;if(this.ended)return!1;a=t===~~t?t:!0===t?s.Z_FINISH:s.Z_NO_FLUSH,"string"==typeof e?p.input=o.binstring2buf(e):"[object ArrayBuffer]"===d.call(e)?p.input=new Uint8Array(e):p.input=e,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new n.Buf8(m),p.next_out=0,p.avail_out=m),(i=r.inflate(p,s.Z_NO_FLUSH))===s.Z_NEED_DICT&&f&&(h="string"==typeof f?o.string2buf(f):"[object ArrayBuffer]"===d.call(f)?new Uint8Array(f):f,i=r.inflateSetDictionary(this.strm,h)),i===s.Z_BUF_ERROR&&!0===_&&(i=s.Z_OK,_=!1),i!==s.Z_STREAM_END&&i!==s.Z_OK)return this.onEnd(i),!(this.ended=!0);p.next_out&&(0!==p.avail_out&&i!==s.Z_STREAM_END&&(0!==p.avail_in||a!==s.Z_FINISH&&a!==s.Z_SYNC_FLUSH)||("string"===this.options.to?(c=o.utf8border(p.output,p.next_out),l=p.next_out-c,u=o.buf2string(p.output,c),p.next_out=l,p.avail_out=m-l,l&&n.arraySet(p.output,p.output,c,l,0),this.onData(u)):this.onData(n.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(_=!0)}while((0<p.avail_in||0===p.avail_out)&&i!==s.Z_STREAM_END);return i===s.Z_STREAM_END&&(a=s.Z_FINISH),a===s.Z_FINISH?(i=r.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===s.Z_OK):a!==s.Z_SYNC_FLUSH||(this.onEnd(s.Z_OK),!(p.avail_out=0))},u.prototype.onData=function(e){this.chunks.push(e)},u.prototype.onEnd=function(e){e===s.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=n.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Inflate=u,i.inflate=h,i.inflateRaw=function(e,t){return(t=t||{}).raw=!0,h(e,t)},i.ungzip=h},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(e,t,i){var r="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;i.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var r in i)i.hasOwnProperty(r)&&(e[r]=i[r])}}return e},i.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var n={arraySet:function(e,t,i,r,n){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+r),n);else for(var o=0;o<r;o++)e[n+o]=t[i+o]},flattenChunks:function(e){var t,i,r,n,o,s;for(t=r=0,i=e.length;t<i;t++)r+=e[t].length;for(s=new Uint8Array(r),t=n=0,i=e.length;t<i;t++)o=e[t],s.set(o,n),n+=o.length;return s}},o={arraySet:function(e,t,i,r,n){for(var o=0;o<r;o++)e[n+o]=t[i+o]},flattenChunks:function(e){return[].concat.apply([],e)}};i.setTyped=function(e){e?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,n)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,o))},i.setTyped(r)},{}],42:[function(e,t,i){var r=e("./common"),n=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(dP){n=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(dP){o=!1}for(var s=new r.Buf8(256),a=0;a<256;a++)s[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function c(e,t){if(t<65537&&(e.subarray&&o||!e.subarray&&n))return String.fromCharCode.apply(null,r.shrinkBuf(e,t));for(var i="",s=0;s<t;s++)i+=String.fromCharCode(e[s]);return i}s[254]=s[254]=1,i.string2buf=function(e){var t,i,n,o,s,a=e.length,c=0;for(o=0;o<a;o++)55296==(64512&(i=e.charCodeAt(o)))&&o+1<a&&56320==(64512&(n=e.charCodeAt(o+1)))&&(i=65536+(i-55296<<10)+(n-56320),o++),c+=i<128?1:i<2048?2:i<65536?3:4;for(t=new r.Buf8(c),o=s=0;s<c;o++)55296==(64512&(i=e.charCodeAt(o)))&&o+1<a&&56320==(64512&(n=e.charCodeAt(o+1)))&&(i=65536+(i-55296<<10)+(n-56320),o++),i<128?t[s++]=i:(i<2048?t[s++]=192|i>>>6:(i<65536?t[s++]=224|i>>>12:(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63),t[s++]=128|i>>>6&63),t[s++]=128|63&i);return t},i.buf2binstring=function(e){return c(e,e.length)},i.binstring2buf=function(e){for(var t=new r.Buf8(e.length),i=0,n=t.length;i<n;i++)t[i]=e.charCodeAt(i);return t},i.buf2string=function(e,t){var i,r,n,o,a=t||e.length,l=new Array(2*a);for(i=r=0;i<a;)if((n=e[i++])<128)l[r++]=n;else if(4<(o=s[n]))l[r++]=65533,i+=o-1;else{for(n&=2===o?31:3===o?15:7;1<o&&i<a;)n=n<<6|63&e[i++],o--;1<o?l[r++]=65533:n<65536?l[r++]=n:(n-=65536,l[r++]=55296|n>>10&1023,l[r++]=56320|1023&n)}return c(l,r)},i.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;0<=i&&128==(192&e[i]);)i--;return i<0||0===i?t:i+s[e[i]]>t?i:t}},{"./common":41}],43:[function(e,t,i){t.exports=function(e,t,i,r){for(var n=65535&e,o=e>>>16&65535,s=0;0!==i;){for(i-=s=2e3<i?2e3:i;o=o+(n=n+t[r++]|0)|0,--s;);n%=65521,o%=65521}return n|o<<16}},{}],44:[function(e,t,i){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(e,t,i){var r=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t,i,n){var o=r,s=n+i;e^=-1;for(var a=n;a<s;a++)e=e>>>8^o[255&(e^t[a])];return~e}},{}],46:[function(e,t,i){var r,n=e("../utils/common"),o=e("./trees"),s=e("./adler32"),a=e("./crc32"),c=e("./messages"),l=-2,d=258,u=262,h=113;function p(e,t){return e.msg=c[t],t}function m(e){return(e<<1)-(4<e?9:0)}function f(e){for(var t=e.length;0<=--t;)e[t]=0}function _(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(n.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function g(e,t){o._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,_(e.strm)}function v(e,t){e.pending_buf[e.pending++]=t}function E(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function T(e,t){var i,r,n=e.max_chain_length,o=e.strstart,s=e.prev_length,a=e.nice_match,c=e.strstart>e.w_size-u?e.strstart-(e.w_size-u):0,l=e.window,h=e.w_mask,p=e.prev,m=e.strstart+d,f=l[o+s-1],_=l[o+s];e.prev_length>=e.good_match&&(n>>=2),a>e.lookahead&&(a=e.lookahead);do{if(l[(i=t)+s]===_&&l[i+s-1]===f&&l[i]===l[o]&&l[++i]===l[o+1]){o+=2,i++;do{}while(l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&o<m);if(r=d-(m-o),o=m-d,s<r){if(e.match_start=t,a<=(s=r))break;f=l[o+s-1],_=l[o+s]}}}while((t=p[t&h])>c&&0!=--n);return s<=e.lookahead?s:e.lookahead}function y(e){var t,i,r,o,c,l,d,h,p,m,f=e.w_size;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=f+(f-u)){for(n.arraySet(e.window,e.window,f,f,0),e.match_start-=f,e.strstart-=f,e.block_start-=f,t=i=e.hash_size;r=e.head[--t],e.head[t]=f<=r?r-f:0,--i;);for(t=i=f;r=e.prev[--t],e.prev[t]=f<=r?r-f:0,--i;);o+=f}if(0===e.strm.avail_in)break;if(l=e.strm,d=e.window,h=e.strstart+e.lookahead,m=void 0,(p=o)<(m=l.avail_in)&&(m=p),i=0===m?0:(l.avail_in-=m,n.arraySet(d,l.input,l.next_in,m,h),1===l.state.wrap?l.adler=s(l.adler,d,m,h):2===l.state.wrap&&(l.adler=a(l.adler,d,m,h)),l.next_in+=m,l.total_in+=m,m),e.lookahead+=i,e.lookahead+e.insert>=3)for(c=e.strstart-e.insert,e.ins_h=e.window[c],e.ins_h=(e.ins_h<<e.hash_shift^e.window[c+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[c+3-1])&e.hash_mask,e.prev[c&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=c,c++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<u&&0!==e.strm.avail_in)}function S(e,t){for(var i,r;;){if(e.lookahead<u){if(y(e),e.lookahead<u&&0===t)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-u&&(e.match_length=T(e,i)),e.match_length>=3)if(r=o._tr_tally(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart,0!=--e.match_length;);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else r=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(g(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,4===t?(g(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(g(e,!1),0===e.strm.avail_out)?1:2}function I(e,t){for(var i,r,n;;){if(e.lookahead<u){if(y(e),e.lookahead<u&&0===t)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-u&&(e.match_length=T(e,i),e.match_length<=5&&(1===e.strategy||3===e.match_length&&4096<e.strstart-e.match_start)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){for(n=e.strstart+e.lookahead-3,r=o._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=n&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!=--e.prev_length;);if(e.match_available=0,e.match_length=2,e.strstart++,r&&(g(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((r=o._tr_tally(e,0,e.window[e.strstart-1]))&&g(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=o._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,4===t?(g(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(g(e,!1),0===e.strm.avail_out)?1:2}function A(e,t,i,r,n){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=r,this.func=n}function b(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=8,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new n.Buf16(1146),this.dyn_dtree=new n.Buf16(122),this.bl_tree=new n.Buf16(78),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new n.Buf16(16),this.heap=new n.Buf16(573),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new n.Buf16(573),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function R(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=2,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?42:h,e.adler=2===t.wrap?0:1,t.last_flush=0,o._tr_init(t),0):p(e,l)}function C(e){var t,i=R(e);return 0===i&&((t=e.state).window_size=2*t.w_size,f(t.head),t.max_lazy_match=r[t.level].max_lazy,t.good_match=r[t.level].good_length,t.nice_match=r[t.level].nice_length,t.max_chain_length=r[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),i}function k(e,t,i,r,o,s){if(!e)return l;var a=1;if(-1===t&&(t=6),r<0?(a=0,r=-r):15<r&&(a=2,r-=16),o<1||9<o||8!==i||r<8||15<r||t<0||9<t||s<0||4<s)return p(e,l);8===r&&(r=9);var c=new b;return(e.state=c).strm=e,c.wrap=a,c.gzhead=null,c.w_bits=r,c.w_size=1<<c.w_bits,c.w_mask=c.w_size-1,c.hash_bits=o+7,c.hash_size=1<<c.hash_bits,c.hash_mask=c.hash_size-1,c.hash_shift=~~((c.hash_bits+3-1)/3),c.window=new n.Buf8(2*c.w_size),c.head=new n.Buf16(c.hash_size),c.prev=new n.Buf16(c.w_size),c.lit_bufsize=1<<o+6,c.pending_buf_size=4*c.lit_bufsize,c.pending_buf=new n.Buf8(c.pending_buf_size),c.d_buf=1*c.lit_bufsize,c.l_buf=3*c.lit_bufsize,c.level=t,c.strategy=s,c.method=i,C(e)}r=[new A(0,0,0,0,(function(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(y(e),0===e.lookahead&&0===t)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var r=e.block_start+i;if((0===e.strstart||e.strstart>=r)&&(e.lookahead=e.strstart-r,e.strstart=r,g(e,!1),0===e.strm.avail_out)||e.strstart-e.block_start>=e.w_size-u&&(g(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(g(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(g(e,!1),e.strm.avail_out),1)})),new A(4,4,8,4,S),new A(4,5,16,8,S),new A(4,6,32,32,S),new A(4,4,16,16,I),new A(8,16,32,32,I),new A(8,16,128,128,I),new A(8,32,128,256,I),new A(32,128,258,1024,I),new A(32,258,258,4096,I)],i.deflateInit=function(e,t){return k(e,t,8,15,8,0)},i.deflateInit2=k,i.deflateReset=C,i.deflateResetKeep=R,i.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?l:(e.state.gzhead=t,0):l},i.deflate=function(e,t){var i,n,s,c;if(!e||!e.state||5<t||t<0)return e?p(e,l):l;if(n=e.state,!e.output||!e.input&&0!==e.avail_in||666===n.status&&4!==t)return p(e,0===e.avail_out?-5:l);if(n.strm=e,i=n.last_flush,n.last_flush=t,42===n.status)if(2===n.wrap)e.adler=0,v(n,31),v(n,139),v(n,8),n.gzhead?(v(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),v(n,255&n.gzhead.time),v(n,n.gzhead.time>>8&255),v(n,n.gzhead.time>>16&255),v(n,n.gzhead.time>>24&255),v(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),v(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(v(n,255&n.gzhead.extra.length),v(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=a(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(v(n,0),v(n,0),v(n,0),v(n,0),v(n,0),v(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),v(n,3),n.status=h);else{var u=8+(n.w_bits-8<<4)<<8;u|=(2<=n.strategy||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(u|=32),u+=31-u%31,n.status=h,E(n,u),0!==n.strstart&&(E(n,e.adler>>>16),E(n,65535&e.adler)),e.adler=1}if(69===n.status)if(n.gzhead.extra){for(s=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>s&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),_(e),s=n.pending,n.pending!==n.pending_buf_size));)v(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>s&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){s=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>s&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),_(e),s=n.pending,n.pending===n.pending_buf_size)){c=1;break}c=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,v(n,c)}while(0!==c);n.gzhead.hcrc&&n.pending>s&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),0===c&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){s=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>s&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),_(e),s=n.pending,n.pending===n.pending_buf_size)){c=1;break}c=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,v(n,c)}while(0!==c);n.gzhead.hcrc&&n.pending>s&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),0===c&&(n.status=103)}else n.status=103;if(103===n.status&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&_(e),n.pending+2<=n.pending_buf_size&&(v(n,255&e.adler),v(n,e.adler>>8&255),e.adler=0,n.status=h)):n.status=h),0!==n.pending){if(_(e),0===e.avail_out)return n.last_flush=-1,0}else if(0===e.avail_in&&m(t)<=m(i)&&4!==t)return p(e,-5);if(666===n.status&&0!==e.avail_in)return p(e,-5);if(0!==e.avail_in||0!==n.lookahead||0!==t&&666!==n.status){var T=2===n.strategy?function(e,t){for(var i;;){if(0===e.lookahead&&(y(e),0===e.lookahead)){if(0===t)return 1;break}if(e.match_length=0,i=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(g(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(g(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(g(e,!1),0===e.strm.avail_out)?1:2}(n,t):3===n.strategy?function(e,t){for(var i,r,n,s,a=e.window;;){if(e.lookahead<=d){if(y(e),e.lookahead<=d&&0===t)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&0<e.strstart&&(r=a[n=e.strstart-1])===a[++n]&&r===a[++n]&&r===a[++n]){s=e.strstart+d;do{}while(r===a[++n]&&r===a[++n]&&r===a[++n]&&r===a[++n]&&r===a[++n]&&r===a[++n]&&r===a[++n]&&r===a[++n]&&n<s);e.match_length=d-(s-n),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=o._tr_tally(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(g(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(g(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(g(e,!1),0===e.strm.avail_out)?1:2}(n,t):r[n.level].func(n,t);if(3!==T&&4!==T||(n.status=666),1===T||3===T)return 0===e.avail_out&&(n.last_flush=-1),0;if(2===T&&(1===t?o._tr_align(n):5!==t&&(o._tr_stored_block(n,0,0,!1),3===t&&(f(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),_(e),0===e.avail_out))return n.last_flush=-1,0}return 4!==t?0:n.wrap<=0?1:(2===n.wrap?(v(n,255&e.adler),v(n,e.adler>>8&255),v(n,e.adler>>16&255),v(n,e.adler>>24&255),v(n,255&e.total_in),v(n,e.total_in>>8&255),v(n,e.total_in>>16&255),v(n,e.total_in>>24&255)):(E(n,e.adler>>>16),E(n,65535&e.adler)),_(e),0<n.wrap&&(n.wrap=-n.wrap),0!==n.pending?0:1)},i.deflateEnd=function(e){var t;return e&&e.state?42!==(t=e.state.status)&&69!==t&&73!==t&&91!==t&&103!==t&&t!==h&&666!==t?p(e,l):(e.state=null,t===h?p(e,-3):0):l},i.deflateSetDictionary=function(e,t){var i,r,o,a,c,d,u,h,p=t.length;if(!e||!e.state||2===(a=(i=e.state).wrap)||1===a&&42!==i.status||i.lookahead)return l;for(1===a&&(e.adler=s(e.adler,t,p,0)),i.wrap=0,p>=i.w_size&&(0===a&&(f(i.head),i.strstart=0,i.block_start=0,i.insert=0),h=new n.Buf8(i.w_size),n.arraySet(h,t,p-i.w_size,i.w_size,0),t=h,p=i.w_size),c=e.avail_in,d=e.next_in,u=e.input,e.avail_in=p,e.next_in=0,e.input=t,y(i);i.lookahead>=3;){for(r=i.strstart,o=i.lookahead-2;i.ins_h=(i.ins_h<<i.hash_shift^i.window[r+3-1])&i.hash_mask,i.prev[r&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=r,r++,--o;);i.strstart=r,i.lookahead=2,y(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,e.next_in=d,e.input=u,e.avail_in=c,i.wrap=a,0},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(e,t,i){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(e,t,i){t.exports=function(e,t){var i,r,n,o,s,a,c,l,d,u,h,p,m,f,_,g,v,E,T,y,S,I,A,b,R;i=e.state,r=e.next_in,b=e.input,n=r+(e.avail_in-5),o=e.next_out,R=e.output,s=o-(t-e.avail_out),a=o+(e.avail_out-257),c=i.dmax,l=i.wsize,d=i.whave,u=i.wnext,h=i.window,p=i.hold,m=i.bits,f=i.lencode,_=i.distcode,g=(1<<i.lenbits)-1,v=(1<<i.distbits)-1;e:do{m<15&&(p+=b[r++]<<m,m+=8,p+=b[r++]<<m,m+=8),E=f[p&g];t:for(;;){if(p>>>=T=E>>>24,m-=T,0==(T=E>>>16&255))R[o++]=65535&E;else{if(!(16&T)){if(!(64&T)){E=f[(65535&E)+(p&(1<<T)-1)];continue t}if(32&T){i.mode=12;break e}e.msg="invalid literal/length code",i.mode=30;break e}y=65535&E,(T&=15)&&(m<T&&(p+=b[r++]<<m,m+=8),y+=p&(1<<T)-1,p>>>=T,m-=T),m<15&&(p+=b[r++]<<m,m+=8,p+=b[r++]<<m,m+=8),E=_[p&v];i:for(;;){if(p>>>=T=E>>>24,m-=T,!(16&(T=E>>>16&255))){if(!(64&T)){E=_[(65535&E)+(p&(1<<T)-1)];continue i}e.msg="invalid distance code",i.mode=30;break e}if(S=65535&E,m<(T&=15)&&(p+=b[r++]<<m,(m+=8)<T&&(p+=b[r++]<<m,m+=8)),c<(S+=p&(1<<T)-1)){e.msg="invalid distance too far back",i.mode=30;break e}if(p>>>=T,m-=T,(T=o-s)<S){if(d<(T=S-T)&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(A=h,(I=0)===u){if(I+=l-T,T<y){for(y-=T;R[o++]=h[I++],--T;);I=o-S,A=R}}else if(u<T){if(I+=l+u-T,(T-=u)<y){for(y-=T;R[o++]=h[I++],--T;);if(I=0,u<y){for(y-=T=u;R[o++]=h[I++],--T;);I=o-S,A=R}}}else if(I+=u-T,T<y){for(y-=T;R[o++]=h[I++],--T;);I=o-S,A=R}for(;2<y;)R[o++]=A[I++],R[o++]=A[I++],R[o++]=A[I++],y-=3;y&&(R[o++]=A[I++],1<y&&(R[o++]=A[I++]))}else{for(I=o-S;R[o++]=R[I++],R[o++]=R[I++],R[o++]=R[I++],2<(y-=3););y&&(R[o++]=R[I++],1<y&&(R[o++]=R[I++]))}break}}break}}while(r<n&&o<a);r-=y=m>>3,p&=(1<<(m-=y<<3))-1,e.next_in=r,e.next_out=o,e.avail_in=r<n?n-r+5:5-(r-n),e.avail_out=o<a?a-o+257:257-(o-a),i.hold=p,i.bits=m}},{}],49:[function(e,t,i){var r=e("../utils/common"),n=e("./adler32"),o=e("./crc32"),s=e("./inffast"),a=e("./inftrees"),c=-2;function l(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function d(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function u(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new r.Buf32(852),t.distcode=t.distdyn=new r.Buf32(592),t.sane=1,t.back=-1,0):c}function h(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,u(e)):c}function p(e,t){var i,r;return e&&e.state?(r=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?c:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=i,r.wbits=t,h(e))):c}function m(e,t){var i,r;return e?(r=new d,(e.state=r).window=null,0!==(i=p(e,t))&&(e.state=null),i):c}var f,_,g=!0;function v(e){if(g){var t;for(f=new r.Buf32(512),_=new r.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(1,e.lens,0,288,f,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(2,e.lens,0,32,_,0,e.work,{bits:5}),g=!1}e.lencode=f,e.lenbits=9,e.distcode=_,e.distbits=5}function E(e,t,i,n){var o,s=e.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new r.Buf8(s.wsize)),n>=s.wsize?(r.arraySet(s.window,t,i-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):(n<(o=s.wsize-s.wnext)&&(o=n),r.arraySet(s.window,t,i-n,o,s.wnext),(n-=o)?(r.arraySet(s.window,t,i-n,n,0),s.wnext=n,s.whave=s.wsize):(s.wnext+=o,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=o))),0}i.inflateReset=h,i.inflateReset2=p,i.inflateResetKeep=u,i.inflateInit=function(e){return m(e,15)},i.inflateInit2=m,i.inflate=function(e,t){var i,d,u,h,p,m,f,_,g,T,y,S,I,A,b,R,C,k,w,D,N,O,P,M,L=0,x=new r.Buf8(4),U=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return c;12===(i=e.state).mode&&(i.mode=13),p=e.next_out,u=e.output,f=e.avail_out,h=e.next_in,d=e.input,m=e.avail_in,_=i.hold,g=i.bits,T=m,y=f,O=0;e:for(;;)switch(i.mode){case 1:if(0===i.wrap){i.mode=13;break}for(;g<16;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}if(2&i.wrap&&35615===_){x[i.check=0]=255&_,x[1]=_>>>8&255,i.check=o(i.check,x,2,0),g=_=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&_)<<8)+(_>>8))%31){e.msg="incorrect header check",i.mode=30;break}if(8!=(15&_)){e.msg="unknown compression method",i.mode=30;break}if(g-=4,N=8+(15&(_>>>=4)),0===i.wbits)i.wbits=N;else if(N>i.wbits){e.msg="invalid window size",i.mode=30;break}i.dmax=1<<N,e.adler=i.check=1,i.mode=512&_?10:12,g=_=0;break;case 2:for(;g<16;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}if(i.flags=_,8!=(255&i.flags)){e.msg="unknown compression method",i.mode=30;break}if(57344&i.flags){e.msg="unknown header flags set",i.mode=30;break}i.head&&(i.head.text=_>>8&1),512&i.flags&&(x[0]=255&_,x[1]=_>>>8&255,i.check=o(i.check,x,2,0)),g=_=0,i.mode=3;case 3:for(;g<32;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}i.head&&(i.head.time=_),512&i.flags&&(x[0]=255&_,x[1]=_>>>8&255,x[2]=_>>>16&255,x[3]=_>>>24&255,i.check=o(i.check,x,4,0)),g=_=0,i.mode=4;case 4:for(;g<16;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}i.head&&(i.head.xflags=255&_,i.head.os=_>>8),512&i.flags&&(x[0]=255&_,x[1]=_>>>8&255,i.check=o(i.check,x,2,0)),g=_=0,i.mode=5;case 5:if(1024&i.flags){for(;g<16;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}i.length=_,i.head&&(i.head.extra_len=_),512&i.flags&&(x[0]=255&_,x[1]=_>>>8&255,i.check=o(i.check,x,2,0)),g=_=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(m<(S=i.length)&&(S=m),S&&(i.head&&(N=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),r.arraySet(i.head.extra,d,h,S,N)),512&i.flags&&(i.check=o(i.check,d,S,h)),m-=S,h+=S,i.length-=S),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===m)break e;for(S=0;N=d[h+S++],i.head&&N&&i.length<65536&&(i.head.name+=String.fromCharCode(N)),N&&S<m;);if(512&i.flags&&(i.check=o(i.check,d,S,h)),m-=S,h+=S,N)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===m)break e;for(S=0;N=d[h+S++],i.head&&N&&i.length<65536&&(i.head.comment+=String.fromCharCode(N)),N&&S<m;);if(512&i.flags&&(i.check=o(i.check,d,S,h)),m-=S,h+=S,N)break e}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;g<16;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}if(_!==(65535&i.check)){e.msg="header crc mismatch",i.mode=30;break}g=_=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=12;break;case 10:for(;g<32;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}e.adler=i.check=l(_),g=_=0,i.mode=11;case 11:if(0===i.havedict)return e.next_out=p,e.avail_out=f,e.next_in=h,e.avail_in=m,i.hold=_,i.bits=g,2;e.adler=i.check=1,i.mode=12;case 12:if(5===t||6===t)break e;case 13:if(i.last){_>>>=7&g,g-=7&g,i.mode=27;break}for(;g<3;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}switch(i.last=1&_,g-=1,3&(_>>>=1)){case 0:i.mode=14;break;case 1:if(v(i),i.mode=20,6!==t)break;_>>>=2,g-=2;break e;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=30}_>>>=2,g-=2;break;case 14:for(_>>>=7&g,g-=7&g;g<32;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}if((65535&_)!=(_>>>16^65535)){e.msg="invalid stored block lengths",i.mode=30;break}if(i.length=65535&_,g=_=0,i.mode=15,6===t)break e;case 15:i.mode=16;case 16:if(S=i.length){if(m<S&&(S=m),f<S&&(S=f),0===S)break e;r.arraySet(u,d,h,S,p),m-=S,h+=S,f-=S,p+=S,i.length-=S;break}i.mode=12;break;case 17:for(;g<14;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}if(i.nlen=257+(31&_),_>>>=5,g-=5,i.ndist=1+(31&_),_>>>=5,g-=5,i.ncode=4+(15&_),_>>>=4,g-=4,286<i.nlen||30<i.ndist){e.msg="too many length or distance symbols",i.mode=30;break}i.have=0,i.mode=18;case 18:for(;i.have<i.ncode;){for(;g<3;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}i.lens[U[i.have++]]=7&_,_>>>=3,g-=3}for(;i.have<19;)i.lens[U[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,P={bits:i.lenbits},O=a(0,i.lens,0,19,i.lencode,0,i.work,P),i.lenbits=P.bits,O){e.msg="invalid code lengths set",i.mode=30;break}i.have=0,i.mode=19;case 19:for(;i.have<i.nlen+i.ndist;){for(;R=(L=i.lencode[_&(1<<i.lenbits)-1])>>>16&255,C=65535&L,!((b=L>>>24)<=g);){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}if(C<16)_>>>=b,g-=b,i.lens[i.have++]=C;else{if(16===C){for(M=b+2;g<M;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}if(_>>>=b,g-=b,0===i.have){e.msg="invalid bit length repeat",i.mode=30;break}N=i.lens[i.have-1],S=3+(3&_),_>>>=2,g-=2}else if(17===C){for(M=b+3;g<M;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}g-=b,N=0,S=3+(7&(_>>>=b)),_>>>=3,g-=3}else{for(M=b+7;g<M;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}g-=b,N=0,S=11+(127&(_>>>=b)),_>>>=7,g-=7}if(i.have+S>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=30;break}for(;S--;)i.lens[i.have++]=N}}if(30===i.mode)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=30;break}if(i.lenbits=9,P={bits:i.lenbits},O=a(1,i.lens,0,i.nlen,i.lencode,0,i.work,P),i.lenbits=P.bits,O){e.msg="invalid literal/lengths set",i.mode=30;break}if(i.distbits=6,i.distcode=i.distdyn,P={bits:i.distbits},O=a(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,P),i.distbits=P.bits,O){e.msg="invalid distances set",i.mode=30;break}if(i.mode=20,6===t)break e;case 20:i.mode=21;case 21:if(6<=m&&258<=f){e.next_out=p,e.avail_out=f,e.next_in=h,e.avail_in=m,i.hold=_,i.bits=g,s(e,y),p=e.next_out,u=e.output,f=e.avail_out,h=e.next_in,d=e.input,m=e.avail_in,_=i.hold,g=i.bits,12===i.mode&&(i.back=-1);break}for(i.back=0;R=(L=i.lencode[_&(1<<i.lenbits)-1])>>>16&255,C=65535&L,!((b=L>>>24)<=g);){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}if(R&&!(240&R)){for(k=b,w=R,D=C;R=(L=i.lencode[D+((_&(1<<k+w)-1)>>k)])>>>16&255,C=65535&L,!(k+(b=L>>>24)<=g);){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}_>>>=k,g-=k,i.back+=k}if(_>>>=b,g-=b,i.back+=b,i.length=C,0===R){i.mode=26;break}if(32&R){i.back=-1,i.mode=12;break}if(64&R){e.msg="invalid literal/length code",i.mode=30;break}i.extra=15&R,i.mode=22;case 22:if(i.extra){for(M=i.extra;g<M;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}i.length+=_&(1<<i.extra)-1,_>>>=i.extra,g-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;R=(L=i.distcode[_&(1<<i.distbits)-1])>>>16&255,C=65535&L,!((b=L>>>24)<=g);){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}if(!(240&R)){for(k=b,w=R,D=C;R=(L=i.distcode[D+((_&(1<<k+w)-1)>>k)])>>>16&255,C=65535&L,!(k+(b=L>>>24)<=g);){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}_>>>=k,g-=k,i.back+=k}if(_>>>=b,g-=b,i.back+=b,64&R){e.msg="invalid distance code",i.mode=30;break}i.offset=C,i.extra=15&R,i.mode=24;case 24:if(i.extra){for(M=i.extra;g<M;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}i.offset+=_&(1<<i.extra)-1,_>>>=i.extra,g-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=30;break}i.mode=25;case 25:if(0===f)break e;if(S=y-f,i.offset>S){if((S=i.offset-S)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=30;break}I=S>i.wnext?(S-=i.wnext,i.wsize-S):i.wnext-S,S>i.length&&(S=i.length),A=i.window}else A=u,I=p-i.offset,S=i.length;for(f<S&&(S=f),f-=S,i.length-=S;u[p++]=A[I++],--S;);0===i.length&&(i.mode=21);break;case 26:if(0===f)break e;u[p++]=i.length,f--,i.mode=21;break;case 27:if(i.wrap){for(;g<32;){if(0===m)break e;m--,_|=d[h++]<<g,g+=8}if(y-=f,e.total_out+=y,i.total+=y,y&&(e.adler=i.check=i.flags?o(i.check,u,y,p-y):n(i.check,u,y,p-y)),y=f,(i.flags?_:l(_))!==i.check){e.msg="incorrect data check",i.mode=30;break}g=_=0}i.mode=28;case 28:if(i.wrap&&i.flags){for(;g<32;){if(0===m)break e;m--,_+=d[h++]<<g,g+=8}if(_!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=30;break}g=_=0}i.mode=29;case 29:O=1;break e;case 30:O=-3;break e;case 31:return-4;default:return c}return e.next_out=p,e.avail_out=f,e.next_in=h,e.avail_in=m,i.hold=_,i.bits=g,(i.wsize||y!==e.avail_out&&i.mode<30&&(i.mode<27||4!==t))&&E(e,e.output,e.next_out,y-e.avail_out)?(i.mode=31,-4):(T-=e.avail_in,y-=e.avail_out,e.total_in+=T,e.total_out+=y,i.total+=y,i.wrap&&y&&(e.adler=i.check=i.flags?o(i.check,u,y,e.next_out-y):n(i.check,u,y,e.next_out-y)),e.data_type=i.bits+(i.last?64:0)+(12===i.mode?128:0)+(20===i.mode||15===i.mode?256:0),(0==T&&0===y||4===t)&&0===O&&(O=-5),O)},i.inflateEnd=function(e){if(!e||!e.state)return c;var t=e.state;return t.window&&(t.window=null),e.state=null,0},i.inflateGetHeader=function(e,t){var i;return e&&e.state&&2&(i=e.state).wrap?((i.head=t).done=!1,0):c},i.inflateSetDictionary=function(e,t){var i,r=t.length;return e&&e.state?0!==(i=e.state).wrap&&11!==i.mode?c:11===i.mode&&n(1,t,r,0)!==i.check?-3:E(e,t,r,r)?(i.mode=31,-4):(i.havedict=1,0):c},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(e,t,i){var r=e("../utils/common"),n=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],o=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],s=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,i,c,l,d,u,h){var p,m,f,_,g,v,E,T,y,S=h.bits,I=0,A=0,b=0,R=0,C=0,k=0,w=0,D=0,N=0,O=0,P=null,M=0,L=new r.Buf16(16),x=new r.Buf16(16),U=null,V=0;for(I=0;I<=15;I++)L[I]=0;for(A=0;A<c;A++)L[t[i+A]]++;for(C=S,R=15;1<=R&&0===L[R];R--);if(R<C&&(C=R),0===R)return l[d++]=20971520,l[d++]=20971520,h.bits=1,0;for(b=1;b<R&&0===L[b];b++);for(C<b&&(C=b),I=D=1;I<=15;I++)if(D<<=1,(D-=L[I])<0)return-1;if(0<D&&(0===e||1!==R))return-1;for(x[1]=0,I=1;I<15;I++)x[I+1]=x[I]+L[I];for(A=0;A<c;A++)0!==t[i+A]&&(u[x[t[i+A]]++]=A);if(v=0===e?(P=U=u,19):1===e?(P=n,M-=257,U=o,V-=257,256):(P=s,U=a,-1),I=b,g=d,w=A=O=0,f=-1,_=(N=1<<(k=C))-1,1===e&&852<N||2===e&&592<N)return 1;for(;;){for(E=I-w,y=u[A]<v?(T=0,u[A]):u[A]>v?(T=U[V+u[A]],P[M+u[A]]):(T=96,0),p=1<<I-w,b=m=1<<k;l[g+(O>>w)+(m-=p)]=E<<24|T<<16|y,0!==m;);for(p=1<<I-1;O&p;)p>>=1;if(0!==p?(O&=p-1,O+=p):O=0,A++,0==--L[I]){if(I===R)break;I=t[i+u[A]]}if(C<I&&(O&_)!==f){for(0===w&&(w=C),g+=b,D=1<<(k=I-w);k+w<R&&!((D-=L[k+w])<=0);)k++,D<<=1;if(N+=1<<k,1===e&&852<N||2===e&&592<N)return 1;l[f=O&_]=C<<24|k<<16|g-d}}return 0!==O&&(l[g+O]=I-w<<24|64<<16),h.bits=C,0}},{"../utils/common":41}],51:[function(e,t,i){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(e,t,i){var r=e("../utils/common");function n(e){for(var t=e.length;0<=--t;)e[t]=0}var o=256,s=286,a=30,c=15,l=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],d=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],u=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],h=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],p=new Array(576);n(p);var m=new Array(60);n(m);var f=new Array(512);n(f);var _=new Array(256);n(_);var g=new Array(29);n(g);var v,E,T,y=new Array(a);function S(e,t,i,r,n){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=r,this.max_length=n,this.has_stree=e&&e.length}function I(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function A(e){return e<256?f[e]:f[256+(e>>>7)]}function b(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function R(e,t,i){e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,b(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function C(e,t,i){R(e,i[2*t],i[2*t+1])}function k(e,t){for(var i=0;i|=1&e,e>>>=1,i<<=1,0<--t;);return i>>>1}function w(e,t,i){var r,n,o=new Array(16),s=0;for(r=1;r<=c;r++)o[r]=s=s+i[r-1]<<1;for(n=0;n<=t;n++){var a=e[2*n+1];0!==a&&(e[2*n]=k(o[a]++,a))}}function D(e){var t;for(t=0;t<s;t++)e.dyn_ltree[2*t]=0;for(t=0;t<a;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function N(e){8<e.bi_valid?b(e,e.bi_buf):0<e.bi_valid&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function O(e,t,i,r){var n=2*t,o=2*i;return e[n]<e[o]||e[n]===e[o]&&r[t]<=r[i]}function P(e,t,i){for(var r=e.heap[i],n=i<<1;n<=e.heap_len&&(n<e.heap_len&&O(t,e.heap[n+1],e.heap[n],e.depth)&&n++,!O(t,r,e.heap[n],e.depth));)e.heap[i]=e.heap[n],i=n,n<<=1;e.heap[i]=r}function M(e,t,i){var r,n,s,a,c=0;if(0!==e.last_lit)for(;r=e.pending_buf[e.d_buf+2*c]<<8|e.pending_buf[e.d_buf+2*c+1],n=e.pending_buf[e.l_buf+c],c++,0===r?C(e,n,t):(C(e,(s=_[n])+o+1,t),0!==(a=l[s])&&R(e,n-=g[s],a),C(e,s=A(--r),i),0!==(a=d[s])&&R(e,r-=y[s],a)),c<e.last_lit;);C(e,256,t)}function L(e,t){var i,r,n,o=t.dyn_tree,s=t.stat_desc.static_tree,a=t.stat_desc.has_stree,l=t.stat_desc.elems,d=-1;for(e.heap_len=0,e.heap_max=573,i=0;i<l;i++)0!==o[2*i]?(e.heap[++e.heap_len]=d=i,e.depth[i]=0):o[2*i+1]=0;for(;e.heap_len<2;)o[2*(n=e.heap[++e.heap_len]=d<2?++d:0)]=1,e.depth[n]=0,e.opt_len--,a&&(e.static_len-=s[2*n+1]);for(t.max_code=d,i=e.heap_len>>1;1<=i;i--)P(e,o,i);for(n=l;i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],P(e,o,1),r=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=r,o[2*n]=o[2*i]+o[2*r],e.depth[n]=(e.depth[i]>=e.depth[r]?e.depth[i]:e.depth[r])+1,o[2*i+1]=o[2*r+1]=n,e.heap[1]=n++,P(e,o,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,r,n,o,s,a,l=t.dyn_tree,d=t.max_code,u=t.stat_desc.static_tree,h=t.stat_desc.has_stree,p=t.stat_desc.extra_bits,m=t.stat_desc.extra_base,f=t.stat_desc.max_length,_=0;for(o=0;o<=c;o++)e.bl_count[o]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<573;i++)f<(o=l[2*l[2*(r=e.heap[i])+1]+1]+1)&&(o=f,_++),l[2*r+1]=o,d<r||(e.bl_count[o]++,s=0,m<=r&&(s=p[r-m]),a=l[2*r],e.opt_len+=a*(o+s),h&&(e.static_len+=a*(u[2*r+1]+s)));if(0!==_){do{for(o=f-1;0===e.bl_count[o];)o--;e.bl_count[o]--,e.bl_count[o+1]+=2,e.bl_count[f]--,_-=2}while(0<_);for(o=f;0!==o;o--)for(r=e.bl_count[o];0!==r;)d<(n=e.heap[--i])||(l[2*n+1]!==o&&(e.opt_len+=(o-l[2*n+1])*l[2*n],l[2*n+1]=o),r--)}}(e,t),w(o,d,e.bl_count)}function x(e,t,i){var r,n,o=-1,s=t[1],a=0,c=7,l=4;for(0===s&&(c=138,l=3),t[2*(i+1)+1]=65535,r=0;r<=i;r++)n=s,s=t[2*(r+1)+1],++a<c&&n===s||(a<l?e.bl_tree[2*n]+=a:0!==n?(n!==o&&e.bl_tree[2*n]++,e.bl_tree[32]++):a<=10?e.bl_tree[34]++:e.bl_tree[36]++,o=n,l=(a=0)===s?(c=138,3):n===s?(c=6,3):(c=7,4))}function U(e,t,i){var r,n,o=-1,s=t[1],a=0,c=7,l=4;for(0===s&&(c=138,l=3),r=0;r<=i;r++)if(n=s,s=t[2*(r+1)+1],!(++a<c&&n===s)){if(a<l)for(;C(e,n,e.bl_tree),0!=--a;);else 0!==n?(n!==o&&(C(e,n,e.bl_tree),a--),C(e,16,e.bl_tree),R(e,a-3,2)):a<=10?(C(e,17,e.bl_tree),R(e,a-3,3)):(C(e,18,e.bl_tree),R(e,a-11,7));o=n,l=(a=0)===s?(c=138,3):n===s?(c=6,3):(c=7,4)}}n(y);var V=!1;function B(e,t,i,n){var o,s,a;R(e,0+(n?1:0),3),s=t,a=i,N(o=e),b(o,a),b(o,~a),r.arraySet(o.pending_buf,o.window,s,a,o.pending),o.pending+=a}i._tr_init=function(e){V||(function(){var e,t,i,r,n,o=new Array(16);for(r=i=0;r<28;r++)for(g[r]=i,e=0;e<1<<l[r];e++)_[i++]=r;for(_[i-1]=r,r=n=0;r<16;r++)for(y[r]=n,e=0;e<1<<d[r];e++)f[n++]=r;for(n>>=7;r<a;r++)for(y[r]=n<<7,e=0;e<1<<d[r]-7;e++)f[256+n++]=r;for(t=0;t<=c;t++)o[t]=0;for(e=0;e<=143;)p[2*e+1]=8,e++,o[8]++;for(;e<=255;)p[2*e+1]=9,e++,o[9]++;for(;e<=279;)p[2*e+1]=7,e++,o[7]++;for(;e<=287;)p[2*e+1]=8,e++,o[8]++;for(w(p,287,o),e=0;e<a;e++)m[2*e+1]=5,m[2*e]=k(e,5);v=new S(p,l,257,s,c),E=new S(m,d,0,a,c),T=new S(new Array(0),u,0,19,7)}(),V=!0),e.l_desc=new I(e.dyn_ltree,v),e.d_desc=new I(e.dyn_dtree,E),e.bl_desc=new I(e.bl_tree,T),e.bi_buf=0,e.bi_valid=0,D(e)},i._tr_stored_block=B,i._tr_flush_block=function(e,t,i,r){var n,s,a=0;0<e.level?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<o;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),L(e,e.l_desc),L(e,e.d_desc),a=function(e){var t;for(x(e,e.dyn_ltree,e.l_desc.max_code),x(e,e.dyn_dtree,e.d_desc.max_code),L(e,e.bl_desc),t=18;3<=t&&0===e.bl_tree[2*h[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),n=e.opt_len+3+7>>>3,(s=e.static_len+3+7>>>3)<=n&&(n=s)):n=s=i+5,i+4<=n&&-1!==t?B(e,t,i,r):4===e.strategy||s===n?(R(e,2+(r?1:0),3),M(e,p,m)):(R(e,4+(r?1:0),3),function(e,t,i,r){var n;for(R(e,t-257,5),R(e,i-1,5),R(e,r-4,4),n=0;n<r;n++)R(e,e.bl_tree[2*h[n]+1],3);U(e,e.dyn_ltree,t-1),U(e,e.dyn_dtree,i-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),M(e,e.dyn_ltree,e.dyn_dtree)),D(e),r&&N(e)},i._tr_tally=function(e,t,i){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(_[i]+o+1)]++,e.dyn_dtree[2*A(t)]++),e.last_lit===e.lit_bufsize-1},i._tr_align=function(e){var t;R(e,2,3),C(e,256,p),16===(t=e).bi_valid?(b(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):8<=t.bi_valid&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}},{"../utils/common":41}],53:[function(e,t,i){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,t,i){(function(e){!function(e){if(!e.setImmediate){var t,i,r,n,o=1,s={},a=!1,c=e.document,l=Object.getPrototypeOf&&Object.getPrototypeOf(e);l=l&&l.setTimeout?l:e,t="[object process]"==={}.toString.call(e.process)?function(e){process.nextTick((function(){u(e)}))}:function(){if(e.postMessage&&!e.importScripts){var t=!0,i=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=i,t}}()?(n="setImmediate$"+Math.random()+"$",e.addEventListener?e.addEventListener("message",h,!1):e.attachEvent("onmessage",h),function(t){e.postMessage(n+t,"*")}):e.MessageChannel?((r=new MessageChannel).port1.onmessage=function(e){u(e.data)},function(e){r.port2.postMessage(e)}):c&&"onreadystatechange"in c.createElement("script")?(i=c.documentElement,function(e){var t=c.createElement("script");t.onreadystatechange=function(){u(e),t.onreadystatechange=null,i.removeChild(t),t=null},i.appendChild(t)}):function(e){setTimeout(u,0,e)},l.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var i=new Array(arguments.length-1),r=0;r<i.length;r++)i[r]=arguments[r+1];var n={callback:e,args:i};return s[o]=n,t(o),o++},l.clearImmediate=d}function d(e){delete s[e]}function u(e){if(a)setTimeout(u,0,e);else{var t=s[e];if(t){a=!0;try{!function(e){var t=e.callback,i=e.args;switch(i.length){case 0:t();break;case 1:t(i[0]);break;case 2:t(i[0],i[1]);break;case 3:t(i[0],i[1],i[2]);break;default:t.apply(undefined,i)}}(t)}finally{d(e),a=!1}}}}function h(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(n)&&u(+t.data.slice(n.length))}}("undefined"==typeof self?void 0===e?this:e:self)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10)}))})),ek=HC(((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")}))}))})),tk=HC((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=ek(),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}}))}))}})),ik=HC(((e,t)=>{var i=ek(),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"}})),rk=HC((e=>{var t=tk(),i=ik();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})),nk=jC(JC()),ok=((AC=ok||{})[AC.INVALID_PARAMETER=4096]="INVALID_PARAMETER",AC[AC.INVALID_OPERATION=4097]="INVALID_OPERATION",AC[AC.NOT_SUPPORTED=4098]="NOT_SUPPORTED",AC[AC.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",AC[AC.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",AC[AC.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",AC[AC.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",AC[AC.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",AC[AC.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",AC[AC.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",AC[AC.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",AC[AC.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",AC[AC.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",AC[AC.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",AC[AC.CLIENT_BANNED=16448]="CLIENT_BANNED",AC[AC.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",AC[AC.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",AC[AC.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",AC[AC.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",AC[AC.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",AC[AC.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",AC[AC.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",AC[AC.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",AC[AC.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",AC[AC.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",AC[AC.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",AC[AC.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",AC[AC.API_CALL_ABORTED=16461]="API_CALL_ABORTED",AC[AC.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",AC[AC.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",AC[AC.UNKNOWN=65535]="UNKNOWN",AC),sk=ok,ak=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=sk.UNKNOWN,extraCode:n=0,constraint:o}=e,s="<".concat(function(e){for(let t in sk)if(sk[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),zC(this,"code"),zC(this,"extraCode"),zC(this,"message"),zC(this,"originMessage"),zC(this,"name"),zC(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}},ck=ak,lk=((new Date).getTime(),0),dk=function(){return(new Date).getTime()+lk},uk=function(){let e=new Date;return e.setTime(dk()),e.toLocaleString()},hk=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)},pk={};WC(pk,{bytes2ms:()=>iD,convertObjectNumberToInt:()=>zD,copyProperties:()=>tD,deepClone:()=>LD,deepMerge:()=>MD,delay:()=>KD,fibonacci:()=>lD,formatedTime:()=>VD,getConstructorName:()=>ID,getContainerFromElement:()=>UD,getEnv:()=>qw,getInternalVersion:()=>kD,getLoggerUrl:()=>Yw,getMediaStreamTrackInfo:()=>YD,getMuteStateFromFlag:()=>ND,getNetworkType:()=>Qw,getNumNetworkType:()=>eD,getReconnectionTimeout:()=>dD,getStringByteLength:()=>HD,getTurnServer:()=>OD,getUint32Version:()=>GD,getValueType:()=>uD,getViewListFromView:()=>xD,glog:()=>sD,ipv4ToUint32:()=>PD,isArray:()=>vD,isAudioWorkletSupported:()=>AD,isBoolean:()=>_D,isConstructor:()=>SD,isEmpty:()=>DD,isFunction:()=>hD,isLangChinese:()=>aD,isMediaStreamTrack:()=>ED,isNumber:()=>fD,isObject:()=>gD,isOverseaSdkAppId:()=>Jw,isPlainObject:()=>cD,isPortrait:()=>WD,isPromise:()=>yD,isRemoteTrack:()=>TD,isString:()=>mD,isUndefined:()=>pD,loadImage:()=>jD,ms2bytes:()=>nD,ms2samples:()=>oD,normalizeUrl:()=>JD,performanceNow:()=>RD,promiseAny:()=>bD,samples2ms:()=>rD,setNetworkType:()=>$w,stringify:()=>BD,stringifyIncludeValue:()=>FD,throttlePromise:()=>qD});var mk={};WC(mk,{AUDIO_MUTE_BIT:()=>$k,AUDIO_STAT_BIT:()=>Zk,AUX_STAT_BIT:()=>Qk,AUX_STREAM_MSID:()=>nw,BACKEND_ENV:()=>qk,BASE_DOC_URL:()=>wk,BASE_HOST:()=>bk,CAPABILITIES_KEYS:()=>zw,CLASS_NAME:()=>xw,CLOUD_CONSOLE_URL:()=>kk,CROSS_ROOM_BIT:()=>iw,DATA_FREEZE_TIMING:()=>ww,DEFAULT_ASSETS_URL:()=>Dk,DOC_URL:()=>Nk,DTLS_STATE_UNKNOWN:()=>mw,ENV_NAME:()=>xk,EXCHANGE_SDP_TIMEOUT:()=>Aw,IS_WORKER:()=>Tk,IS_WORKLET:()=>yk,KIBANA_EVENT:()=>yw,LOCAL_STREAM_PUBLISH_STATE:()=>kw,LOGGER_CMD_TYPE:()=>Lk,LOGGER_DOMAIN:()=>Ok,LOGGER_DOMAIN_OVERSEA:()=>Pk,LOG_LEVEL:()=>Uk,LOG_LEVEL_NAME:()=>Hw,MAIN_STREAM_MSID:()=>rw,MAX_RTT:()=>Kw,MICROPHONE_COMMUNICATIONS:()=>Fw,MICROPHONE_DEFAULT:()=>Vw,MUTE_ALL_BIT:()=>tw,NAME:()=>zk,NETWORK_TYPE:()=>Fk,NOT_SUPPORTED_H264:()=>Cw,PAUSED_RETRY_COUNT:()=>Uw,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Pw,PEER_CONNECTION_STATE:()=>fw,PEER_LEAVE_REASON:()=>Ww,RECOVER_CAPTURE_INTERVAL:()=>Gw,REMOTE_STREAM_TYPE_AUX:()=>sw,REMOTE_STREAM_TYPE_MAIN:()=>ow,RENDER_FREEZE_TIMING:()=>Dw,SCHEDULE_DOMAIN:()=>Mw,SCHEDULE_TIMEOUT:()=>Lw,SDP_SEMANTICS_PLAN_B:()=>Rw,SDP_SEMANTICS_UNIFIED_PLAN:()=>bw,SECOND_HOST:()=>Rk,SIGNAL_PING_PONG_INTERVAL:()=>Bk,SIGNAL_PING_TIMEOUT:()=>Vk,SIGNAL_RECONNECTION_COUNT:()=>Tw,SMALL_STAT_BIT:()=>Xk,SPEAKER_DEFAULT:()=>Bw,STORAGE_EXPIRES_TIME:()=>Hk,STREAM_TYPE_BIG:()=>Nw,STREAM_TYPE_SMALL:()=>Ow,SUBSCRIBE_SMALL_RETRY_COUNT:()=>jw,SYNC_USER_LIST_INTERVAL:()=>Sw,Scene:()=>Jk,THIRD_HOST:()=>Ck,TRANSPORT_DIRECTION:()=>Kk,TRTC_ERROR_ASSISTANCE:()=>Mk,TRTC_QUALITY_BAD:()=>uw,TRTC_QUALITY_DISCONNECTED:()=>pw,TRTC_QUALITY_EXCELLENT:()=>cw,TRTC_QUALITY_GOOD:()=>lw,TRTC_QUALITY_POOR:()=>dw,TRTC_QUALITY_UNKNOWN:()=>aw,TRTC_QUALITY_VERY_BAD:()=>hw,UPDATE_OFFER_TIMEOUT:()=>Iw,VIDEO_MUTE_BIT:()=>ew,VIDEO_STAT_BIT:()=>Yk,audioProfileMap:()=>Wk,getRetryCount:()=>vw,getScriptDir:()=>Sk,innerVersion:()=>fk,loggerProxy:()=>Ik,screenProfileMap:()=>Gk,setLoggerProxy:()=>Ak,setRetryCount:()=>gw,setVersion:()=>gk,version:()=>_k,videoProfileMap:()=>jk});var fk="4.15.00.1600",_k="5.0.0";function gk(e){_k=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));fk="".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 vk,Ek,Tk="undefined"!=typeof importScripts,yk="undefined"!=typeof registerProcessor,Sk=()=>{let e=Tk?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Ik="",Ak=e=>Ik=e,bk="web.sdk.qcloud.com",Rk="web.sdk.tencent.cn",Ck="web.sdk.cloud.tencent.cn",kk="https://console.cloud.tencent.com/trtc",wk="https://".concat(bk,"/trtc/webrtc/v5/doc"),Dk="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",Nk="".concat(wk,"/zh-cn/"),Ok="https://yun.tim.qq.com",Pk="https://apisgp.my-imcloud.com",Mk="trtc_error_assistance",Lk={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},xk={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Uk=((Ek=Uk||{})[Ek.TRACE=0]="TRACE",Ek[Ek.DEBUG=1]="DEBUG",Ek[Ek.INFO=2]="INFO",Ek[Ek.WARN=3]="WARN",Ek[Ek.ERROR=4]="ERROR",Ek[Ek.NONE=5]="NONE",Ek),Vk=18e3,Bk=2e3,Fk={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Hk=6048e5,Wk={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}},jk={"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}},Gk={"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}},zk={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},Kk={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},qk={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Jk=((vk=Jk||{}).LIVE="live",vk.RTC="rtc",vk),Yk=1,Xk=2,Qk=4,Zk=8,$k=64,ew=16,tw=112,iw=128,rw="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",nw="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",ow=zk.MAIN,sw=zk.AUXILIARY,aw=0,cw=1,lw=2,dw=3,uw=4,hw=5,pw=6,mw="unknown",fw={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},_w=1/0;function gw(e){_w=e}function vw(){return _w}var Ew,Tw=30,yw={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"},Sw=1e4,Iw=1e4,Aw=1e4,bw="unified-plan",Rw="plan-b",Cw=1028,kw=((Ew=kw||{})[Ew.UNPUBLISH=-1]="UNPUBLISH",Ew[Ew.PUBLISHING=0]="PUBLISHING",Ew[Ew.PUBLISHED=1]="PUBLISHED",Ew),ww=500,Dw=1e3,Nw=zk.BIG,Ow=zk.SMALL,Pw=1e4,Mw={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"},Lw=2e3,xw={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Uw=5,Vw="default",Bw=Vw,Fw="communications",Hw=Object.keys(Uk),Ww=["normal leave","timeout leave","kick","role change"],jw=10,Gw=2e3,zw=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Kw=1e4,qw=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Jw=e=>Number(e)<14e8,Yw=function(e,t){let i;i=Ik||(Jw(e)?Pk:Ok);let r=Math.floor(Math.random()*xC(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},Xw="unknown";function Qw(){if("unknown"!==Xw)return Xw;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&&(Xw=Zw(r,n)),Xw}function Zw(e,t){if(Fk[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function $w(e){Xw=Zw(e)}function eD(){return Fk[Qw()]}function tD(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 iD(e){return rD(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function rD(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function nD(e){return 4*oD(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function oD(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var sD="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},aD=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},cD=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 lD(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:lD(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function dD(e){return e>8?3e4:1e3*lD(e)}function uD(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var hD=e=>"function"==typeof e,pD=e=>void 0===e,mD=e=>"string"==typeof e,fD=e=>"number"==typeof e,_D=e=>"boolean"==typeof e,gD=e=>"object"===uD(e),vD=e=>"array"===uD(e),ED=e=>uD(e)==="MediaStreamTrack".toLowerCase(),TD=e=>e.isRemote,yD=e=>"promise"===uD(e),SD=e=>hD(e)&&e.prototype.constructor===e,ID=e=>SD(e)?e.prototype.constructor.name:"",AD="undefined"!=typeof AudioWorkletNode;function bD(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 RD(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var CD=e=>+e<10?"0".concat(e):e,kD=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=CD(i[1])+CD(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},wD=Object.prototype.hasOwnProperty;function DD(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(cD(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(wD.call(e,t))return!1;return!0}return!1}function ND(e,t){return{userId:t,hasAudio:!!(e&Zk),hasVideo:!!(e&Yk),hasAuxiliary:!!(e&Qk),hasSmall:!!(e&Xk),audioMuted:!!(e&$k),videoMuted:!!(e&ew),audioAvailable:!(!(e&Zk)||e&$k),videoAvailable:!(!(e&Yk)||e&ew)}}function OD(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!pD(e.username)&&!pD(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",pD(e.credentialType)||(t.credentialType=e.credentialType)),t}function PD(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!mD(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 MD=function(e,t,i,r){if(!gD(e)||!gD(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],!(pD(t[n])||i&&i.includes(n)))if(gD(e[n])&&gD(t[n]))o+=MD(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=LD(t[n]),o+=1)}return o};function LD(e){if(vD(e)){let t=[];return e.forEach(((e,i)=>{t[i]=LD(e)})),t}if(gD(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=LD(e[i])})),t}return e}var xD=e=>{let t=[];if(vD(e))t=[...e];else if(mD(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},UD=e=>mD(e)?document.getElementById(e):e,VD=()=>(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 BD(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(vD(e))return"[".concat(e.map((e=>BD(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!cD(e)||!vD(i)&&!vD(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]=cD(e[s])||vD(e[s])?JSON.parse(BD(e[s],{keysToExclude:r,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(Ew){return"{}"}}function FD(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)})),BD(e,{keysToInclude:i})}function HD(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var WD=()=>{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},jD=e=>qC(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(mD(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 ck({code:sk.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}}))})),GD=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},zD=e=>(Object.keys(e).forEach((t=>{fD(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(cD(e[t])||vD(e[t]))&&zD(e[t])})),e);function KD(e,t){return new Promise((i=>{let r=setTimeout(i,e);t&&t(r)}))}function qD(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 JD(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function YD(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===zk.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(vk){return""}}function XD(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.text())).then((t=>{try{e({data:JSON.parse(t)})}catch(dP){e({data:t})}}),s);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(4===a.readyState)if(a.status>=200&&a.status<300)try{let t=JSON.parse(a.response);e({data:t})}catch(t){e({data:a.response})}else s({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=n||5e3,a.open(r,t,!0),a.send(i)}))}function QD(e){return qC(this,null,(function*(){let t=RD(),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 nP.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(RD()-t,"ms")),r}catch(Ew){return i}}))}var ZD=Object.prototype.hasOwnProperty,$D=e=>"function"==typeof e,eN=e=>void 0===e,tN=e=>"boolean"==typeof e,iN=e=>e.isRemote;function rN(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(ZD.call(e,t))return!1;return!0}return!1}var nN=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,f=(e,i)=>qC(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(_){let t=()=>{clearTimeout(p),h=0,m=2,i(_)},s=()=>{2!==m&&h<($D(d)?d():d)?(h++,m=1,$D(n)&&n.call(this,h,t),p=window.setTimeout((()=>{p=-1,f(e,i)}),$D(u)?u(h):u)):(t(),$D(o)&&o.call(this,_))};$D(r)?r.call(this,{error:_,retry:s,reject:i,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(f)}},oN=class{constructor(e){zC(this,"userId"),zC(this,"remoteUserId"),zC(this,"id"),zC(this,"sdkAppId"),zC(this,"type"),zC(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!tN(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}createChild(e){return Object.setPrototypeOf(e,this)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId;t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(this.id).concat(i?"|".concat(i):"","]")),nP.log(e,t,eN(this.userId)||rN(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)}},sN={};WC(sN,{ANDROID_VERSION:()=>EN,CHROME_MAJOR_VERSION:()=>IO,CHROME_VERSION:()=>AO,EDGE_VERSION:()=>RN,EDG_MAJOR_VERSION:()=>wN,EDG_VERSION:()=>kN,FIREFOX_MAJOR_VERSION:()=>AN,FIREFOX_VERSION:()=>IN,HUAWEI_VERSION:()=>dO,IE_VERSION:()=>FN,IOS_MAIN_VERSION:()=>NO,IOS_VERSION:()=>wO,IPADQQB_VERSION:()=>QN,IS_ANDROID:()=>vN,IS_ANDROID_WEBVIEW:()=>kO,IS_ANY_SAFARI:()=>RO,IS_CHROME:()=>yO,IS_CHROME_OS:()=>tO,IS_CHROMIUM_BASE:()=>TO,IS_DESKTOP_IOS_CHROME:()=>xO,IS_EDG:()=>CN,IS_EDGE:()=>bN,IS_ELECTRON:()=>nO,IS_FIREFOX:()=>SN,IS_HEADLESS_CHROME:()=>SO,IS_HONOR:()=>lO,IS_HUAWEI:()=>cO,IS_HUAWEIBROWSER:()=>aO,IS_IE:()=>BN,IS_IE8:()=>VN,IS_IOS:()=>gN,IS_IOS_13_OR_14:()=>MO,IS_IOS_15_1:()=>PO,IS_IOS_CHROME:()=>LO,IS_IPAD:()=>pN,IS_IPADQQB:()=>XN,IS_IPAD_PRO:()=>mN,IS_IPHONE:()=>fN,IS_IPOD:()=>_N,IS_LINUX:()=>eO,IS_LOCAL:()=>UO,IS_MAC:()=>$N,IS_MACQQB:()=>JN,IS_MIBROWSER:()=>oO,IS_MQQB:()=>GN,IS_NATIVE_ANDROID:()=>yN,IS_OLD_ANDROID:()=>TN,IS_OPENHARMONY:()=>gO,IS_OPPOBROWSER:()=>pO,IS_SAFARI:()=>bO,IS_SAFARI_15_1:()=>OO,IS_SAMSUNGBROWSER:()=>uO,IS_SOGOU:()=>ON,IS_SOGOUM:()=>DN,IS_TBS:()=>MN,IS_UCBROWSER:()=>rO,IS_VIVOBROWSER:()=>fO,IS_WECHAT:()=>HN,IS_WIN:()=>ZN,IS_WQQB:()=>KN,IS_WX:()=>iO,IS_X5MQQB:()=>jN,IS_XWEB:()=>xN,MACQQB_VERSION:()=>YN,MI_VERSION:()=>sO,MQQB_VERSION:()=>zN,OPENHARMONY_VERSION:()=>vO,OPPO_VERSION:()=>mO,SAFARI_VERSION:()=>CO,SAMSUNG_VERSION:()=>hO,SOGOUM_VERSION:()=>NN,SOGOU_VERSION:()=>PN,TBS_VERSION:()=>LN,UA_DATA_STRING:()=>jO,USER_AGENT:()=>aN,VIVO_VERSION:()=>_O,WECHAT_VERSION:()=>WN,WQQB_VERSION:()=>qN,XWEB_VERSION:()=>UN,browserInfo:()=>BO,getBrowserInfo:()=>FO,getChromeMajorVersion:()=>EO,getDeviceModel:()=>KO,getGPUInfo:()=>zO,getOSName:()=>JO,getOSNumber:()=>YO,getOSString:()=>XO,getOSType:()=>ZO,getTerminalType:()=>QO,getUserAgentData:()=>GO,isLocalStorageEnabled:()=>VO,isMobile:()=>WO,isVersionSmallerThan:()=>DO});var aN="undefined"==typeof navigator?"":navigator.userAgent,cN=e=>new RegExp(e,"i").test(aN),lN=e=>{if(cN(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=aN.match(t);if(i&&i[1])return i[1]}return""},dN=e=>{if(cN(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=aN.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},uN=/AppleWebKit\/([\d.]+)/i.exec(aN),hN=uN?parseFloat(uN[1]):NaN,pN=cN("iPad"),mN="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&cN("Macintosh"),fN=cN("iPhone")&&!pN,_N=cN("iPod"),gN=fN||pN||_N||mN,vN=cN("Android"),EN=function(){if(vN){let e=aN.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}(),TN=vN&&cN("webkit")&&EN<2.3,yN=vN&&EN<5&&hN<537,SN=cN("Firefox"),IN=lN("Firefox"),AN=dN("Firefox"),bN=cN("Edge"),RN=lN("Edge"),CN=cN("Edg"),kN=lN("Edg"),wN=dN("Edg"),DN=cN("SogouMobileBrowser"),NN=lN("SogouMobileBrowser"),ON=cN("MetaSr\\s"),PN=lN("MetaSr\\s"),MN=cN("TBS"),LN=lN("TBS"),xN=cN("XWEB"),UN=lN("XWEB"),VN=cN("MSIE\\s8\\.0"),BN=cN("MSIE\\/\\d+"),FN=function(){if(BN){let e=/MSIE\s(\d+)\.\d/.exec(aN),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(aN)&&/rv:11.0/.test(aN)&&(t=11),t}return NaN}(),HN=cN("(micromessenger|webbrowser)"),WN=lN("MicroMessenger"),jN=!MN&&cN("MQQBrowser")&&cN("COVC"),GN=!MN&&cN("MQQBrowser")&&!cN("COVC"),zN=GN||jN?lN("MQQBrowser"):"",KN=!MN&&cN(" QQBrowser"),qN=lN(" QQBrowser"),JN=!MN&&cN("QQBrowserLite"),YN=lN("QQBrowserLite"),XN=!MN&&cN("MQBHD"),QN=lN("MQBHD"),ZN=cN("Windows"),$N=!gN&&cN("MAC OS X"),eO=!vN&&cN("Linux"),tO=cN("CrOS"),iO=cN("MicroMessenger"),rO=cN("UCBrowser"),nO=cN("Electron"),oO=cN("MiuiBrowser"),sO=lN("MiuiBrowser"),aO=cN("HuaweiBrowser"),cO=cN("Huawei")||cN("HUAWEI"),lO=cN("Honor")||cN("HONOR"),dO=lN("HuaweiBrowser"),uO=cN("SamsungBrowser"),hO=lN("SamsungBrowser"),pO=cN("HeyTapBrowser"),mO=lN("HeyTapBrowser"),fO=cN("VivoBrowser"),_O=lN("VivoBrowser"),gO=cN("OpenHarmony"),vO=lN("OpenHarmony"),EO=()=>dN("Chrome"),TO=cN("Chrome"),yO=!bN&&!ON&&!DN&&!MN&&!xN&&!CN&&!KN&&!oO&&!aO&&!uO&&!pO&&!fO&&TO,SO=cN("HeadlessChrome"),IO=EO(),AO=lN("Chrome"),bO=!TO&&!GN&&!jN&&!JN&&!XN&&cN("Safari"),RO=bO||gN,CO=lN("Version"),kO=/Android.*(wv|.0.0.0)/.test(aN),wO=(()=>{if(mN)return CO;if(gN){let e=aN.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}var NO=Number(wO.split(".")[0]),OO="15.1"===CO,PO="15.1"===wO,MO=(()=>{let e=Number(wO.split(".")[0]);return 14===e||13===e})(),LO=cN("CriOS"),xO=LO&&"11.1.1"===CO,UO="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),VO=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(hP){e=!1}return e}})(),BO=FO();function FO(){let e=new Map([[SN,["Firefox",IN]],[CN,["Edg",kN]],[yO,["Chrome",AO]],[bO,["Safari",CO]],[MN,["TBS",LN]],[xN,["XWEB",UN]],[HN&&fN,["WeChat",WN]],[KN,["QQ(Win)",qN]],[GN,["QQ(Mobile)",zN]],[jN,["QQ(Mobile X5)",zN]],[JN,["QQ(Mac)",YN]],[XN,["QQ(iPad)",QN]],[oO,["MI",sO]],[aO,["HW",dO]],[uO,["Samsung",hO]],[pO,["OPPO",mO]],[fO,["VIVO",_O]],[bN,["EDGE",RN]],[DN,["SogouMobile",NN]],[ON,["Sogou",PN]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var HO=null;function WO(){return HO&&"boolean"==typeof HO.mobile?HO.mobile:vN||gN||fN||pN||gO}var jO="";function GO(){return qC(this,null,(function*(){if(HO)return HO;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(HO=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!jO&&(jO="UAData: ".concat(HO.platform,"/").concat(HO.platformVersion),HO.architecture&&HO.bitness&&(jO+=" ".concat(HO.architecture,"/").concat(HO.bitness)),HO.mobile&&(jO+=" mobile"),HO.model&&(jO+=" model: ".concat(HO.model.replace(/\s+/g,"/"))),HO.fullVersionList&&(jO+=" ".concat(HO.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),HO}catch(IC){return null}}))}function zO(){try{let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"";let i=t.getExtension("WEBGL_debug_renderer_info");if(i){let e=t.getParameter(i.UNMASKED_VENDOR_WEBGL),r=t.getParameter(i.UNMASKED_RENDERER_WEBGL);return"".concat(e," ").concat(r)}return""}catch(IC){return""}}function KO(){return(null==HO?void 0:HO.model)||""}var qO=new Map([[vN,"Android"],[gN,"iOS"],[ZN,"Windows"],[$N,"MacOS"],[eO,"Linux"],[tO,"ChromeOS"]]),JO=function(){return qO.get(!0)?qO.get(!0):HO?HO.platform:"unknown"};function YO(){return ZN?1:vN?2:$N?3:gN?4:eO?5:tO?6:0}var XO=()=>{let e=JO();return e+="/".concat(BO.name,"/").concat(bO?BO.version:BO.version.split(".")[0]),null!=HO&&HO.platformVersion&&(e+="/".concat(HO.platformVersion)),null!=HO&&HO.architecture&&(e+="/".concat(HO.architecture)),e};function QO(){return vN?4:fN?2:pN?3:$N?12:ZN?5:eO?13:gO?22:1}function ZO(){return vN?"Android":fN?"iPhone":pN?"iPad":$N?"Mac":ZN?"Windows":eO?"Linux":"unknown"}var $O,eP=new(jC(JC(),1).default),tP=(($O=tP||{}).ROOM_DESTROY="1",$O.JOIN_START="21",$O.JOIN_SCHEDULE_SUCCESS="22",$O.JOIN_SIGNAL_CONNECTION_START="23",$O.JOIN_SIGNAL_CONNECTION_END="24",$O.JOIN_SEND_CMD="25",$O.JOIN_RECEIVED_CMD_RES="26",$O.JOIN_SUCCESS="27",$O.JOIN_FAILED="28",$O.LEAVE_START="51",$O.LEAVE_SEND_CMD="52",$O.LEAVE_SUCCESS="53",$O.PUBLISH_START="61",$O.SEND_FIRST_VIDEO_FRAME="62",$O.PUBLISH_FAILED="63",$O.SUBSCRIBE_START="81",$O.SUBSCRIBE_SUCCESS="82",$O.SUBSCRIBE_FAILED="84",$O.UNSUBSCRIBE_SUCCESS="83",$O.LOCAL_TRACK_CAPTURE_START="101",$O.LOCAL_TRACK_CAPTURE_SUCCESS="102",$O.LOCAL_TRACK_CAPTURE_FAILED="103",$O.LOCAL_TRACK_PUBLISHED="104",$O.LOCAL_TRACK_UNPUBLISHED="105",$O.LOCAL_TRACK_REPLACED="106",$O.SWITCH_DEVICE_SUCCESS="107",$O.TRACK_MUTED="108",$O.TRACK_UNMUTED="109",$O.REMOTE_TRACK_SUBSCRIBED="110",$O.REMOTE_TRACK_UNSUBSCRIBED="111",$O.LOCAL_TRACK_RECAPTURE="112",$O.PLAY_TRACK_START="151",$O.PLAYER_STATE_CHANGED="152",$O.VIDEO_LOADED_DATA="153",$O.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",$O.SIGNAL_CONNECTION_STATE_CHANGED="201",$O.PEER_CONNECTION_STATE_CHANGED="202",$O.SINGLE_CONNECTION_STAT="203",$O.SPC_RECONNECTED="204",$O.HEARTBEAT_REPORT="251",$O.RECEIVED_PUBLISHED_USER_LIST="252",$O.REMOTE_PUBLISH_STATE_CHANGED="253",$O.AUDIO_LEVEL_INTERVAL="260",$O.NETWORK_QUALITY="261",$O.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",$O.QUALITY_LIMITATION_CHANGED="263",$O.LOG="264",$O.AUDIO_PROCESSOR_DEBUG="265",$O.AUDIO_PROCESSOR_REFERENCE_CHANGED="266",$O),iP=tP,rP=class e{constructor(){zC(this,"_isEnableUploadLog",!0),zC(this,"_localJoinedUser",new Map),zC(this,"_queue",[]),zC(this,"_timeoutId",-1),zC(this,"_logLevel",1),zC(this,"_logLevelToUpload",2),!Tk&&!yk&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){eP.on(iP.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.logLevelToUpload&&Uk[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),eP.on(iP.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),eP.once(iP.JOIN_FAILED,(()=>{this.startUpload()})),eP.on(iP.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(mD(i.userId)&&fD(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 qC(this,null,(function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;e<t.length;e++){let{userId:i,sdkAppId:r,logs:n}=t[e];yield this.uploadLogWithRetry(JSON.stringify({timestamp:uk(),sdkAppId:String(r),userId:i,version:_k,log:n.map((e=>e.log)).join("\n")}),r),n.forEach((e=>e.uploaded=!0))}}catch(pP){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return nN({retryFunction:()=>XD({url:Yw(t,Lk.LOG),body:e,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;return t.setTime(dk()),"[".concat(hk(t),"] <").concat(Uk[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){pD(Uk[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(mD(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(vk){return""}}log(t,i){let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0;var s;i.unshift(this.getPrefix(t));let a={log:i.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:t,userId:n,sdkAppId:o,forAllJoinedClients:r};if(eP.emit(iP.LOG,{log:a}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(a),t<this._logLevel)return;let c=(null==(s=Uk[t])?void 0:s.toLowerCase())||"info";e.PRINT_LOG_TAG?console[c]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...i):console[c](...i)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}createLogger(e){return new oN(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Uk[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};zC(rP,"PRINT_LOG_TAG",!(gN||vN||SO));var nP=new rP,oP=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)}))},sP=new class{constructor(){zC(this,"_prefix","TRTC"),zC(this,"_queue",new Map)}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){VO()&&(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(pP){return!1}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(VO())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(hP){nP.warn(hP)}}getItem(e){if(!VO())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(vk){nP.warn(vk)}}setItem(e,t){if(VO())try{let i={expiresIn:Date.now()+Hk,value:t};this._queue.set(this.getRealKey(e),i)}catch(Ew){nP.warn(Ew)}}deleteItem(e){if(!VO())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(vk){return nP.warn(vk),!1}}clear(){if(VO())try{localStorage.clear()}catch(hP){nP.warn(hP)}}},aP={};WC(aP,{HTTPS_API:()=>BM,IS_GET_CAPABILITIES_SUPPORTED:()=>nL,IS_GET_SETTINGS_SUPPORTED:()=>rL,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>iL,IS_INSERTABLE_STREAM_SUPPORTED:()=>oL,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>gL,IS_RTC_RTP_SENDER_SUPPORTED:()=>$M,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>sL,IS_SEI_SUPPORTED:()=>aL,IS_SPC_SUPPORTED:()=>QM,basis:()=>pL,capabilityCheck:()=>fL,checkSystemRequirementsInternal:()=>LM,decodeSupportStatus:()=>MM,encodeSupportStatus:()=>PM,getBrowserInfo:()=>RM,getDisplayResolution:()=>HM,isAddTransceiverSupported:()=>XM,isBrowserSupported:()=>CM,isGetReceiversSupported:()=>qM,isGetSendersSupported:()=>JM,isGetTransceiversSupported:()=>YM,isGetUserMediaSupported:()=>WM,isMediaDevicesSupported:()=>wM,isMediaSessionSupported:()=>dL,isMediaStreamTrackProcessorSupported:()=>OM,isReplaceTrackSupported:()=>eL,isRequestVideoFrameCallbackSupported:()=>_L,isSIMDSupported:()=>hL,isScreenCaptureApiAvailable:()=>UM,isSelectedCandidatePair:()=>FM,isSetParametersSupported:()=>tL,isSmallStreamAPISupported:()=>GM,isSmallStreamSupported:()=>zM,isStopTransceiverSupported:()=>ZM,isTRTCSupported:()=>xM,isUnifiedPlanDefault:()=>KM,isUsedInHttpProtocol:()=>NM,isWebAudioSupported:()=>jM,isWebCodecSupported:()=>lL,isWebCodecsSupported:()=>kM,isWebRTCSupported:()=>cL,isWebTransportSupported:()=>uL});var cP={};WC(cP,{AUDIO_LEVEL_SCALE:()=>ZP,AudioCodecPipelineType:()=>rM,AudioDecoderDowngradeState:()=>PP,AudioPlayerMode:()=>YP,AudioType:()=>BP,BASIC_TYPE:()=>eM,BannedReason:()=>XP,CONNECTION_CLOSED_REASON:()=>TP,ClientEvent:()=>yP,CodecType:()=>nM,ConnectionEvent:()=>EP,ConnectionState:()=>OP,DECODE_FAILED_ERROR_CODE:()=>oM,FacingMode:()=>qP,LeaveReason:()=>QP,LocalTrackEvent:()=>IP,MULTI_VIDEO_DATA_TYPE:()=>jP,MediaType:()=>UP,MediaTypeLabel:()=>VP,MonitorEventId:()=>GP,MutedFlag:()=>kP,NetworkQualityValue:()=>zP,PlayerState:()=>AP,ReceiveMode:()=>KP,RemoteStreamType:()=>WP,RemoteTrackEvent:()=>CP,RoomEvent:()=>bP,SceneNumber:()=>wP,StreamEvent:()=>SP,StreamType:()=>HP,SubscribeMediaType:()=>$P,TIMER_TYPE:()=>aM,TRACK_ACTION:()=>xP,TRACK_KIND:()=>LP,TrackEvent:()=>RP,UserRole:()=>NP,UserRoleNumber:()=>DP,VideoCodec:()=>tM,VideoCodecPipelineType:()=>iM,VideoContentHint:()=>sM,VideoDecoderDowngradeState:()=>MP,VideoPlayerMode:()=>JP,VideoType:()=>FP});var lP,dP,uP,hP,pP,mP,fP,_P,gP,vP,EP=((vP=EP||{}).TRACK_ADDED="track-added",vP.TRACK_UPDATED="track-updated",vP.TRACK_SUBSCRIBED="track-subscribed",vP.STREAM_ADDED="stream-added",vP.STREAM_REMOVED="stream-removed",vP.STREAM_UPDATED="stream-updated",vP.STREAM_PUBLISHED="stream-published",vP.STREAM_SUBSCRIBED="stream-subscribed",vP.STREAM_UNSUBSCRIBED="stream-unsubscribed",vP.STATE_CHANGED="state-changed",vP.ERROR="error",vP.CONNECTION_STATE_CHANGED="connection-state-changed",vP.FIREWALL_RESTRICTION="firewall-restriction",vP.SEI_MESSAGE="sei-message",vP.CLOSED="closed",vP),TP=(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))(TP||{}),yP=((gP=yP||{}).STREAM_ADDED="stream-added",gP.STREAM_REMOVED="stream-removed",gP.STREAM_UPDATED="stream-updated",gP.STREAM_SUBSCRIBED="stream-subscribed",gP.CONNECTION_STATE_CHANGED="connection-state-changed",gP.PEER_JOIN="peer-join",gP.PEER_LEAVE="peer-leave",gP.MUTE_AUDIO="mute-audio",gP.MUTE_VIDEO="mute-video",gP.UNMUTE_AUDIO="unmute-audio",gP.UNMUTE_VIDEO="unmute-video",gP.CLIENT_BANNED="client-banned",gP.NETWORK_QUALITY="network-quality",gP.AUDIO_VOLUME="audio-volume",gP.SEI_MESSAGE="sei-message",gP.ERROR="error",gP),SP=((_P=SP||{}).PLAYER_STATE_CHANGED="player-state-changed",_P.SCREEN_SHARING_STOPPED="screen-sharing-stopped",_P.CONNECTION_STATE_CHANGED="connection-state-changed",_P.DEVICE_AUTO_RECOVERED="device-auto-recovered",_P.ERROR="error",_P),IP=(e=>(e.DEVICE_AUTO_RECOVERED="1",e.DEVICE_RECOVER_FAILED="5",e.DEVICE_CHANGED="2",e.ERROR="3",e.PUBLISH_STATE_CHANGED="4",e.ENCODE_FAILED="6",e))(IP||{}),AP=(e=>(e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e))(AP||{}),bP=((fP=bP||{}).PEER_JOIN="peer-join",fP.PEER_LEAVE="peer-leave",fP.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",fP.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",fP.BANNED="banned",fP.NETWORK_QUALITY="network-quality",fP.AUDIO_VOLUME="audio-volume",fP.SEI_MESSAGE="sei-message",fP.ERROR="error",fP.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",fP.REMOTE_PUBLISHED="remote-published",fP.REMOTE_UNPUBLISHED="remote-unpublished",fP.FIREWALL_RESTRICTION="firewall-restriction",fP.HEARTBEAT_REPORT="heartbeat-report",fP.CUSTOM_MESSAGE="custom-message",fP.LAYER_DATA="layerData",fP.FIRST_VIDEO_FRAME="first-video-frame",fP.DUMP="dump",fP.AUDIO_FRAME="audio-frame",fP.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",fP),RP=((mP=RP||{}).PLAYER_STATE_CHANGED="player-state-changed",mP.MUTE="mute",mP.UNMUTE="unmute",mP.ERROR="error",mP.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",mP.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",mP.FIRST_VIDEO_FRAME="first-video-frame",mP),CP=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(CP||{}),kP=(e=>(e[e.VIDEO=1]="VIDEO",e[e.SMALL=2]="SMALL",e[e.AUX=4]="AUX",e[e.AUDIO=8]="AUDIO",e[e.VIDEO_MUTE=16]="VIDEO_MUTE",e[e.AUX_MUTE=32]="AUX_MUTE",e[e.AUDIO_MUTE=64]="AUDIO_MUTE",e))(kP||{}),wP=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(wP||{}),DP=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(DP||{}),NP=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(NP||{}),OP=(e=>(e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e))(OP||{}),PP=((pP=PP||{}).INITIALIZED="INITIALIZED",pP.STARTING="STARTING",pP.STARTED="STARTED",pP.FAILED="FAILED",pP),MP=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(MP||{}),LP=(e=>(e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e))(LP||{}),xP=(e=>(e.ADD="add",e.REMOVE="remove",e))(xP||{}),UP=(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))(UP||{}),VP={1:"audio",2:"auxVideo",4:"video"},BP=((hP=BP||{})[hP.opus=111]="opus",hP),FP=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(FP||{}),HP=(e=>(e.Big="big",e.Small="small",e))(HP||{}),WP=(e=>(e.Main="main",e.Aux="auxiliary",e))(WP||{}),jP=(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))(jP||{}),GP=((uP=GP||{})[uP.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",uP[uP.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",uP[uP.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",uP[uP.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",uP[uP.MUTE_AUDIO=32772]="MUTE_AUDIO",uP[uP.MUTE_VIDEO=32773]="MUTE_VIDEO",uP[uP.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",uP[uP.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",uP[uP.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",uP[uP.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",uP[uP.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",uP[uP.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",uP[uP.SWITCH_CAMERA=32780]="SWITCH_CAMERA",uP[uP.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",uP[uP.REPLACE_VIDEO=32782]="REPLACE_VIDEO",uP[uP.REPLACE_AUDIO=32783]="REPLACE_AUDIO",uP[uP.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",uP[uP.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",uP[uP.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",uP[uP.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",uP[uP.JOIN=32788]="JOIN",uP[uP.LEAVE=32789]="LEAVE",uP[uP.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",uP[uP.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",uP[uP.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",uP[uP.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",uP[uP.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",uP[uP.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",uP[uP.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",uP[uP.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",uP[uP.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",uP[uP.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",uP[uP.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",uP[uP.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",uP[uP.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",uP[uP.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",uP[uP.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",uP[uP.PUBLISH_AUX=32805]="PUBLISH_AUX",uP[uP.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",uP[uP.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",uP[uP.VIDEO_ENCODER=4004]="VIDEO_ENCODER",uP[uP.VIDEO_DECODER=4005]="VIDEO_DECODER",uP),zP=(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))(zP||{}),KP=(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))(KP||{}),qP=(e=>(e.user="user",e.environment="environment",e))(qP||{}),JP=(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))(JP||{}),YP=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(YP||{}),XP=(e=>(e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e))(XP||{}),QP=((dP=QP||{})[dP.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",dP[dP.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",dP[dP.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",dP[dP.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",dP[dP.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",dP[dP.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",dP[dP.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",dP[dP.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",dP[dP.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",dP),ZP=1e8,$P=class{constructor(){zC(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)}},eM=(e=>(e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e))(eM||{}),tM=(e=>(e.H264="h264",e.H265="h265",e.VP8="vp8",e))(tM||{}),iM=(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))(iM||{}),rM=(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))(rM||{}),nM=(e=>(e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e))(nM||{}),oM=((lP=oM||{})[lP.SUCCESS=0]="SUCCESS",lP[lP.FAILED=1]="FAILED",lP[lP.WEBCODEC_INIT=2]="WEBCODEC_INIT",lP[lP.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",lP[lP.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",lP[lP.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",lP[lP.WASM_INIT=6]="WASM_INIT",lP[lP.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",lP[lP.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",lP[lP.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",lP[lP.TEST=10]="TEST",lP[lP.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",lP),sM=(e=>(e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e))(sM||{}),aM=(e=>(e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e))(aM||{}),cM={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"},lM={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(uD(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(uD(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,"()")},dM=(e,t)=>t?"".concat(wk,"/").concat(e,"/").concat(t):"".concat(wk,"/").concat(e,"/index.html"),uM=()=>{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(Mk);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 hM(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",s="",a="";hD(lM[t])?o=lM[t](i):mD(lM[t])&&(o=lM[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=uM();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(hD(l[t])?a=l[t](i):mD(l[t])&&(a=l[t]));let d=o;return aD()&&(c&&c[t]&&(hD(c[t])?s=c[t](i):mD(c[t])&&(s=c[t])),s&&(d=n?"".concat(s,"\n请查看文档: ").concat(dM("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(dM("en",a),"\n")),d}var pM,mM,fM=jC(ZC(),1),_M=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];zC(this,"countMap",new Map),zC(this,"distributionMap",new Map),zC(this,"version"),zC(this,"log",nP.createLogger({id:"kv"})),e&&(eP.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===zk.AUDIO?501700:511700,cost:i})})),eP.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===zk.AUDIO?501700:511700,error:i})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:GD(this.version||_k),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,uint32_count:i}})),stats_distribution:[...this.distributionMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,distribution_items:[...i.entries()].map((e=>{let[t,i]=e;return{uint32_item_key:t,uint32_item_value:i}}))}}))};return this.countMap.clear(),this.distributionMap.clear(),e}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){let t=+String(e).slice(-3);return t>=700&&t<799}isErrorCodeKey(e){let t=+String(e).slice(-3);return t>=600&&t<699}isCountKey(e){let t=+String(e).slice(-3);return t>=0&&t<599}isNumberKey(e){let t=+String(e).slice(-3);return t>=800&&t<899}addCount(e){let{key:t,useUV:i=!1}=e;this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}addEnum(e){let{key:t,value:i,useUV:r=!0}=e;var n;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=(null==(n=this.distributionMap)?void 0:n.get(t))||new Map;o.set(i,(o.get(i)||0)+1),this.distributionMap.set(t,o)}addNumber(e){let{key:t,value:i,split:r=100,useUV:n=!1}=e;var o;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(n&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=(null==(o=this.distributionMap)?void 0:o.get(t))||new Map,a=0;if(fD(r))a=Math.floor(i/r);else for(let c=r.length-1;c>0;c--)if(i>r[c]){a=c;break}s.set(a,(s.get(a)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent(e){let{key:t,cost:i,timeKey:r,split:n}=e;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),i)){let e=+String(t).slice(-3);e<800&&e>=700?this.addNumber({key:r||t+100,value:i,split:n}):r||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:i}=e;if(!t)return;let r=sk.UNKNOWN;i&&(fD(i)?r=i:(!pD(i.extraCode)||!pD(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})}},gM=((mM=gM||{})[mM.enterRoom=500700]="enterRoom",mM[mM.exitRoom=500701]="exitRoom",mM[mM.switchRole=500702]="switchRole",mM[mM.destroy=500703]="destroy",mM[mM.startLocalAudio=500704]="startLocalAudio",mM[mM.updateLocalAudio=500705]="updateLocalAudio",mM[mM.stopLocalAudio=500706]="stopLocalAudio",mM[mM.startLocalVideo=500707]="startLocalVideo",mM[mM.updateLocalVideo=500708]="updateLocalVideo",mM[mM.stopLocalVideo=500709]="stopLocalVideo",mM[mM.startScreenShare=500710]="startScreenShare",mM[mM.updateScreenShare=500711]="updateScreenShare",mM[mM.stopScreenShare=500712]="stopScreenShare",mM[mM.startRemoteVideo=500713]="startRemoteVideo",mM[mM.updateRemoteVideo=500714]="updateRemoteVideo",mM[mM.stopRemoteVideo=500715]="stopRemoteVideo",mM[mM.muteRemoteAudio=500716]="muteRemoteAudio",mM[mM.setRemoteAudioVolume=500717]="setRemoteAudioVolume",mM[mM.use=500718]="use",mM[mM.sendSEIMessage=5e5]="sendSEIMessage",mM[mM.sendCustomMessage=500001]="sendCustomMessage",mM),vM=((pM=vM||{})[pM.AudioMixer=550700]="AudioMixer",pM[pM.AIDenoiser=551700]="AIDenoiser",pM[pM.VirtualBackground=570700]="VirtualBackground",pM[pM.Beauty=571700]="Beauty",pM[pM.Watermark=572700]="Watermark",pM[pM.BasicBeauty=574700]="BasicBeauty",pM[pM.CDNStreaming=590700]="CDNStreaming",pM[pM.DeviceDetector=591700]="DeviceDetector",pM[pM.Debug=592700]="Debug",pM[pM.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",pM),EM=(e=>(e[e.AudioMixer=550701]="AudioMixer",e[e.AIDenoiser=551701]="AIDenoiser",e[e.VirtualBackground=570701]="VirtualBackground",e[e.Beauty=571701]="Beauty",e[e.Watermark=572701]="Watermark",e[e.BasicBeauty=574701]="BasicBeauty",e[e.CDNStreaming=590701]="CDNStreaming",e[e.DeviceDetector=591701]="DeviceDetector",e[e.Debug=592701]="Debug",e[e.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",e))(EM||{}),TM=(e=>(e[e.AudioMixer=550702]="AudioMixer",e[e.AIDenoiser=551702]="AIDenoiser",e[e.VirtualBackground=570702]="VirtualBackground",e[e.Beauty=571702]="Beauty",e[e.Watermark=572702]="Watermark",e[e.BasicBeauty=574702]="BasicBeauty",e[e.CDNStreaming=590702]="CDNStreaming",e[e.DeviceDetector=591702]="DeviceDetector",e[e.Debug=592702]="Debug",e[e.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",e))(TM||{}),yM=new _M(!0),SM=new _M(!1),IM=yM,AM={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},bM=new Map([[SN,["Firefox",IN]],[CN,["Edg",kN]],[yO,["Chrome",AO]],[bO,["Safari",CO]],[MN,["TBS",LN]],[xN,["XWEB",UN]],[HN&&fN,["WeChat",WN]],[KN,["QQ(Win)",qN]],[GN,["QQ(Mobile)",zN]],[jN,["QQ(Mobile X5)",zN]],[JN,["QQ(Mac)",YN]],[XN,["QQ(iPad)",QN]],[oO,["MI",sO]],[aO,["HW",dO]],[uO,["Samsung",hO]],[pO,["OPPO",mO]],[fO,["VIVO",_O]],[bN,["EDGE",RN]],[DN,["SogouMobile",NN]],[ON,["Sogou",PN]]]);function RM(){let e=bM.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var CM=function(){return!(rO||bN||CN&&wN<80||SN&&AN<56)},kM=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},wM=function(){if(!navigator.mediaDevices)return NM()||nP.error(lM.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},DM=!1;function NM(){return"http:"===location.protocol&&!UO&&(DM||nP.error(hM({key:cM.NOT_SUPPORTED_HTTP})),DM=!0,!0)}var OM=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},PM=function(){return qC(this,null,(function*(){if(AM.detail.isH264EncodeSupported&&AM.detail.isVp8EncodeSupported)return{isH264EncodeSupported:AM.detail.isH264EncodeSupported,isVp8EncodeSupported:AM.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection,n=document.createElement(zk.CANVAS);n.getContext("2d");let o=n.captureStream(0);return r.addTrack(o.getVideoTracks()[0],o),e=yield r.createOffer(),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),AM.detail.isH264EncodeSupported=t,AM.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:AM.detail.isH264EncodeSupported,isVp8EncodeSupported:AM.detail.isVp8EncodeSupported}}catch(Ew){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},MM=function(){return qC(this,null,(function*(){if(AM.detail.isH264DecodeSupported&&AM.detail.isVp8DecodeSupported)return{isH264DecodeSupported:AM.detail.isH264DecodeSupported,isVp8DecodeSupported:AM.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection;return e=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch(Ew){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},LM=qD((()=>qC(void 0,null,(function*(){if(AM.result&&AM.detail.isH264EncodeSupported&&AM.detail.isVp8EncodeSupported&&AM.detail.isH264DecodeSupported&&AM.detail.isVp8DecodeSupported)return AM;let e=Date.now(),t=CM(),i=cL(),r=kM(),n=wM(),{isH264EncodeSupported:o,isVp8EncodeSupported:s}=yield PM(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield MM();if(!o||!s){let e=yield PM();nP.warn("detect encode again h264:".concat(o," vp8:").concat(s," result: ").concat(JSON.stringify(e))),o=e.isH264EncodeSupported,s=e.isVp8EncodeSupported}if(o&&a&&vN&&TO&&!xN&&!MN){let{encode:e,decode:t}=yield function(){return qC(this,null,(function*(){return VM||(VM=new Promise((e=>qC(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{let r=document.createElement("canvas"),n=r.getContext("2d");r.width=320,r.height=240;let o=setInterval((()=>{n.fillText("test",Math.floor(320*Math.random()),Math.floor(240*Math.random()))}),66),s=-1,a=-1;i=()=>{clearInterval(s),clearInterval(o),clearTimeout(a),l.close(),d.close(),c.getTracks().forEach((e=>e.stop()))},a=setTimeout((()=>{i(),e(t)}),2e3);let c=r.captureStream(),l=new RTCPeerConnection({}),d=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",(e=>d.addIceCandidate(e.candidate))),d.addEventListener("icecandidate",(e=>l.addIceCandidate(e.candidate))),l.addTrack(c.getVideoTracks()[0],c);let u=yield l.createOffer();yield l.setLocalDescription(u),yield d.setRemoteDescription(u);let h=yield d.createAnswer(),p=fM.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=fM.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval((()=>qC(this,null,(function*(){t.encode&&t.decode&&(i(),e(t));let[r,n]=yield Promise.all([l.getSenders()[0].getStats(),d.getReceivers()[0].getStats()]);t.encode||r.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===zk.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===zk.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(r){i(),nP.warn("detectH264Supported failed",r),e({encode:!0,decode:!0})}})))).then((e=>(e.encode||(e.decode=!0),(!e.encode||!e.decode)&&nP.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(jO)),e))),VM)}))}();o=e,a=t}return AM.result=t&&i&&n&&(o||s)&&(a||c),AM.detail.isBrowserSupported=t,AM.detail.isWebRTCSupported=i,AM.detail.isWebCodecsSupported=r,AM.detail.isMediaDevicesSupported=n,AM.detail.isScreenShareSupported=UM(),AM.detail.isSmallStreamSupported=zM(),AM.detail.isH264EncodeSupported=o,AM.detail.isVp8EncodeSupported=s,AM.detail.isH264DecodeSupported=a,AM.detail.isVp8DecodeSupported=c,AM.result||nP.error("".concat(navigator.userAgent," ").concat(FD(AM.detail,!1))),sP.setItem(mL,{ua:navigator.userAgent,checkResult:AM}),IM.addNumber({key:523800,value:Date.now()-e}),AM})))),xM=function(){return AM.result},UM=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},VM=null;var BM=(e,t,i)=>{"http:"===location.protocol&&!UO&&(e[t]=()=>{throw new ck({code:sk.INVALID_OPERATION,message:lM.NOT_SUPPORTED_HTTP})})},FM=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(_D(e.selected)&&!e.selected)};function HM(){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 WM(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function jM(){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 GM(){return"captureStream"in HTMLCanvasElement.prototype}function zM(){return!(HN||gN||IO&&IO<63)&&!(!CM()||!GM())}var KM=function(){if(pD(window.RTCRtpTransceiver)||!XM()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:bw}),e.addTransceiver(zk.AUDIO),t=!0}catch(vk){}return null==e||e.close(),t};function qM(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function JM(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function YM(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function XM(){return!(11===NO&&!xO)&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var QM=!(!XM()||TO&&IO<86);function ZM(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var $M="RTCRtpSender"in window;function eL(){return $M&&"replaceTrack"in window.RTCRtpSender.prototype}function tL(){return $M&&"setParameters"in window.RTCRtpSender.prototype&&JM()}var iL="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,rL=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,nL=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,oL=$M&&"createEncodedStreams"in window.RTCRtpSender.prototype&&EO()>=86,sL="RTCRtpScriptTransform"in window,aL=$M&&(oL||sL),cL=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function lL(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return pD(window.AudioDecoder)||(e.AudioDecoder=!0),pD(window.AudioEncoder)||(e.AudioEncoder=!0),pD(window.VideoDecoder)||(e.VideoDecoder=!0),pD(window.VideoEncoder)||(e.VideoEncoder=!0),pD(window.ImageDecoder)||(e.ImageDecoder=!0),e}function dL(){return"mediaSession"in navigator&&!pD(navigator.mediaSession.setActionHandler)}function uL(){return!pD(window.WebTransport)}function hL(){return"undefined"!=typeof WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function pL(){let e={browser:"".concat(BO.name,"/").concat(BO.version),os:JO(),displayResolution:HM(),isScreenShareSupported:UM(),isWebRTCSupported:cL(),isGetUserMediaSupported:WM(),isWebAudioSupported:jM(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:lL(),isMediaSessionSupported:dL(),isWebTransportSupported:uL()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var mL="checkResult";function fL(){NM();let e=sP.getItem(mL);e&&e.ua===navigator.userAgent&&(AM=e.checkResult),LM()}function _L(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var gL="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype,vL=jC(JC(),1),EL=Symbol("instance"),TL=Symbol("cacheResult"),yL=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,RL.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},SL=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var IL=new Map;function AL(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=IL.get(r)||[];IL.has(r)||IL.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=CL.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return i.sync?r[TL]:Promise.resolve(r[TL]);r.state instanceof yL&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof yL&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new SL(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 SL(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e)));let d=e=>{if(i.fail&&i.fail.call(this,e),i.sync){if(i.ignoreError)return e;throw e}return i.ignoreError?Promise.resolve(e):Promise.reject(e)};if(l)return d(l);let u=r.state,h=new yL(u,t,s);RL.call(r,h);let p=e=>{var n;return r[TL]=e,h.aborted||(RL.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[TL])),e},m=e=>(RL.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(gP){return m(new SL(r._state,"".concat(r.name," ").concat(s," from ").concat(e," to ").concat(t," failed: ").concat(gP),gP instanceof Error?gP:new Error(String(gP))))}}}}var bL="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 RL(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(CL.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var CL=class e extends vL.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[EL];n?this.name=n.name+"-"+n.count++:r[EL]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=IL.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);IL.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]:{};bL(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){RL.call(this,e)}};CL.STATECHANGED="stateChanged",CL.UPDATEAFSM="updateAFSM",CL.INIT="[*]",CL.ON="on",CL.OFF="off",CL.instances=new Map,CL.instances2=new WeakMap;var kL="undefined"!=typeof window,wL=kL&&window.requestIdleCallback||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},DL=kL&&window.cancelIdleCallback||function(e){clearTimeout(e)},NL=kL&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),OL=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=VC("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=BC(VC({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=RD(),n=()=>{if(i=RD()-r,i>=t.delay&&(r=RD()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!e.isBreakLoop(t))return t.ricID=wL(n,{timeout:t.delay})};return t.ricID=wL(n,{timeout:t.delay})}static raf(t){let i,r=RD(),n=()=>document.hidden&&t.backgroundTask?(i=RD()-r,r=RD(),t.callback(),t.loopCount+=1,e.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(n,t.delay-Math.floor(i%t.delay))):(i=RD()-r,i>=t.delay&&(r=RD()-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=RD()-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&&NL&&NL(r),n&&DL(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)}};zC(OL,"taskMap",new Map),zC(OL,"currentTaskID",1),zC(OL,"sharedWorker",null),zC(OL,"workerTasks",new Map);var PL=OL;zk.SEI_MESSAGE;var ML={LOADED_DATA:zk.LOADEDDATA,LOADED_META_DATA:zk.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},LL={};WC(LL,{create:()=>UL,remove:()=>VL});var xL=new WeakMap;function UL(e,t){xL.has(e)||xL.set(e,[]);let i=xL.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 VL(e){let t=xL.get(e);t&&(t.forEach((e=>e())),xL.delete(e))}var BL=new class{constructor(){zC(this,"_roomIdMap",new Map),zC(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:_k,env:xk.QCLOUD,browserVersion:BO.name+BO.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){UO||!nP.isAbleToUpload||this._configs.env===xk.QCLOUD&&this.uploadEventToKibana(BC(VC({},e),{result:"success"}))}logFailedEvent(e){if(UO||!nP.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)||sk.UNKNOWN};this._configs.env===xk.QCLOUD&&this.uploadEventToKibana(BC(VC({},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:uk(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:_k,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+="\n".concat(r.stack))),this.sendRequest(Yw(this._configs.sdkAppId,Lk.LOG),n)}sendRequest(e,t){setTimeout((()=>XD({url:e,body:JSON.stringify(t),priority:"low"}).catch((()=>{}))),2e3)}},FL=new WeakMap;function HL(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,s){let a=nN({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=FL.get(e))&&t.has(o)?n():s(r)}),s,a):null!=(c=FL.get(e))&&c.has(o)?n():s(r)},onRetrying(t,i){var n;$D(r)&&r.call(this,t,i),null!=(n=FL.get(e))&&n.has(o)&&(FL.get(e).get(o).stopRetry=i)},onRetryFailed:n});return s.value=function(){let t=FL.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}):FL.set(e,new Map([[o,{args:r}]])),a.apply(this,r).finally((()=>{var t;return null==(t=FL.get(e))?void 0:t.delete(o)}))},s}}function WL(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=FL.get(e))&&n.has(t)){let{stopRetry:n,args:s}=FL.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=FL.get(e))||o.delete(t))}return s.apply(this,c)},o}}var jL=class extends CL{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,zC(this,"id"),zC(this,"element",null),zC(this,"track"),zC(this,"url"),zC(this,"attr"),zC(this,"mode"),zC(this,"muted"),zC(this,"_log"),zC(this,"_pausedRetryCount"),zC(this,"_isElementPlayingFired",!1),zC(this,"_interval"),zC(this,"_delayDestroyTimeoutId",0),zC(this,"_playSuccessResolve"),zC(this,"_isReplayByRecreateMediaStreamCalled",!1),zC(this,"isInAutoPlayFailedState",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Uw,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){var e;return"PLAYING"===this._state&&!1===(null==(e=this.element)?void 0:e.paused)}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,null!==e&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return qC(this,null,(function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise(((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)}))}catch(vk){let t=hM({key:cM.PLAY_FAILED,data:{media:this.kind,error:vk}});if(this.track&&!this.track.muted&&this._log.warn(vk),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new ck({code:sk.PLAY_NOT_ALLOWED,message:t})}}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!RO?this._delayDestroyTimeoutId||(this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout((()=>this.destroyElement()),3*e)):this.destroyElement(),this.handleStopped(zk.ENDED),this._interval>0&&PL.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():PO?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 UL(this.element,this.element).add(zk.PLAYING,e).add(zk.ENDED,e).add(zk.PAUSE,e).add(zk.ERROR,e).add(zk.LOADEDDATA,e).add(zk.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==LL||LL.create(e,e).add(zk.ENDED,t).add(zk.MUTE,t).add(zk.UNMUTE,t),e.readyState===zk.ENDED&&this.handleTrackEvent({type:zk.ENDED}),e.muted&&this.handleTrackEvent({type:zk.MUTE})}}bindAutoPlayEvent(){eP.on(iP.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;e&&VL(e)}unbindEvents(){this.element&&VL(this.element),this.unbindTrackEvents(),eP.off(iP.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case zk.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(zk.PLAYING),this._interval&&(PL.clearTask(this._interval),this._interval=-1);break;case zk.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(zk.ENDED);break;case zk.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(zk.PAUSE),gN&&(this._interval=PL.run("timeout",(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case zk.ERROR:if(this.element&&this.element.error){this.handlePaused(zk.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)),BL.uploadEvent({log:"stat-".concat(this.kind,"-").concat(yw.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),lO||cO?this.emit(ML.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case zk.LOADEDDATA:this.kind===zk.VIDEO&&this.emit(ML.LOADED_DATA);break;case zk.LOADEDMETADATA:this.kind===zk.VIDEO&&this.emit(ML.LOADED_META_DATA)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),BL.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),IM.addSuccessEvent({key:this.kind===zk.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),BL.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),IM.addFailedEvent({key:this.kind===zk.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(ML.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,i)=>{KD(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)}),KD(5e3).then((()=>{var e,r;(!this.isPlaying||null!=(e=this.element)&&e.error)&&i(null==(r=this.element)?void 0:r.error),t()}))}))})).finally((()=>{this.element&&(this.element.onerror=null)}))}handleTrackEvent(e){switch(e.type){case zk.ENDED:this.handleStopped(zk.ENDED);break;case zk.MUTE:this.handlePaused(zk.MUTE);break;case zk.UNMUTE:this._isElementPlayingFired?this.handlePlaying(zk.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString())}}handlePlaying(e){var t;null==(t=this._playSuccessResolve)||t.call(this,e),this.emit(ML.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(ML.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(ML.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};GC([HL({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],jL.prototype,"doReplayByRecreateMediaStream",1),GC([AL([],"PLAYING",{sync:!0})],jL.prototype,"handlePlaying",1),GC([AL("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],jL.prototype,"handlePaused",1),GC([AL([],"STOPPED",{sync:!0})],jL.prototype,"handleStopped",1);var GL,zL="trtc_autoplay",KL="".concat(zL,"_mask"),qL="".concat(zL,"_wrapper"),JL="".concat(zL,"_header"),YL="".concat(zL,"_content"),XL="".concat(zL,"_action_wrapper"),QL="".concat(zL,"_question"),ZL="".concat(zL,"_collapse"),$L="".concat(zL,"_action_confirm"),ex="".concat(zL,"_detail"),tx="#2473E8",ix="dialog",rx="".concat(ix,"-show"),nx="".concat(ix,"-1"),ox="".concat(ix,"-2"),sx=!1,ax=()=>!!document.querySelector(".".concat(qL)),cx="".concat(wk,"/").concat(aD()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),lx="<br><a href='".concat(cx,"' target='_blank'>").concat(aD()?"其他方案?":"Any other solution?","</a>"),dx="".concat(aD()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(lx):"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(lx)),ux=class{constructor(){if(zC(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),zC(this,"_dialogNode",null),zC(this,"_bodyPosition",""),zC(this,"_showDetail",!1),zC(this,"_isCollapseClicked",!1),zC(this,"_isQuestionClicked",!1),aD()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!sx){let e=document.createElement("style");e.innerHTML=".".concat(KL,"{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(KL," div:not(.").concat(XL,"){display:block !important;}.").concat(qL,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(qL," a{color:").concat(tx,";}.").concat(JL,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(YL,"{margin:8px 0;}.").concat(XL,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(ZL,"{margin-right:auto;cursor:pointer}.").concat(QL,"{height:100%;line-height:16px;cursor:pointer;}.").concat($L,"{margin-left:8px;color:#fff;background:").concat(tx,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat($L,":hover{opacity:0.9;}.").concat(ZL,",.").concat($L,",.").concat(YL,",.").concat(QL,"{font-size:14px;}@media screen and (max-width:750px){.").concat(qL,"{width:80vw;}}"),document.head.appendChild(e),sx=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(KL,"\"><div class='").concat(qL,"'><div class='").concat(JL,"'>").concat(location.host,"</div><div class='").concat(YL,"'>").concat(this.content,"</div><div class='").concat(ex,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(dx,"</div><div class='").concat(XL,"'></div></div></div>").trim();let t=document.createElement("button");t.className=$L,t.innerText=aD()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=QL,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=ZL,r.innerText="".concat(aD()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(XL));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){ax()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(qL)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",nP.info("show autoplay dialog"),BL.uploadEvent({log:rx}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){nP.warn("confirm clicked, try resume stream"),eP.emit(iP.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(ex));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||BL.uploadEvent({log:nx}),this._isCollapseClicked=!0}onQuestionClick(){window.open(cx,"_blank"),this._isQuestionClicked||BL.uploadEvent({log:ox}),this._isQuestionClicked=!0}},hx=class extends jL{constructor(e){super(e,zk.VIDEO),zC(this,"stat",{}),zC(this,"_calculateTimeout",-1),zC(this,"viewMirror",!1),zC(this,"objectFit"),zC(this,"container"),zC(this,"canvas"),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,pD(e.viewMirror)||(this.viewMirror=e.viewMirror),pD(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(zk.VIDEO);this.track&&2!==this.mode&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(zk.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(zk.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;super.handleTrackEvent(e),e.type===zk.MUTE&&null!=(t=this.stat)&&t.fps&&(this.stat.fps=0)}handleElementEvent(e){var t,i;if(2===this.mode)return;super.handleElementEvent(e);let r=e.type;if(r===zk.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id)),this.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=Uw,this._log.info("view container ".concat(null==(i=this.container)?void 0:i.id," is recreated"))),this._pausedRetryCount>0&&!ax()&&(this._log.info("[".concat(Uw-this._pausedRetryCount+1,"/").concat(Uw,"] ").concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let e=this.element.style.transform;r===zk.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):r===zk.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}}setCanvas(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;var i,r,n,o;this.canvas!==e&&(null==(i=this.canvas)||i.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,2===this.mode&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?(null==(r=this.element)||r.remove(),null==(n=this.container)||n.appendChild(e)):this.element&&(null==(o=this.container)||o.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(t,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}setPoster(e){this.element&&(this.element.poster=e)}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;super.stop(e),null==(t=this.canvas)||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),2===this.mode?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(ML.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(_L()&&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(vk){this._log.warn("init stat failed",vk)}}};function px(e,t){return qC(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),nP.info("worklet addModule success")}catch(vk){throw nP.info("worklet addModule catch error. ".concat(vk.message)),vk}}))}"undefined"!=typeof AudioContext?GL=AudioContext:"undefined"!=typeof webkitAudioContext?GL=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(GL=mozAudioContext);var mx,fx=-1;!function e(){try{if(mx)return;(mx=new GL({sampleRate:48e3})).onstatechange=()=>{nP.info("context state: ".concat(mx.state).concat("running"!==mx.state?" visibilityState: ".concat(document.visibilityState):"")),_x()},clearTimeout(fx)}catch(IC){nP.error("initAudioContext failed: ".concat(IC," typeof AudioContextClass: ").concat(typeof GL)),fx=setTimeout(e,1e3)}}();var _x=()=>{"suspended"===mx.state?(Ex(),document.addEventListener("click",_x)):"interrupted"===mx.state?Ex():(document.removeEventListener("visibilitychange",_x),document.removeEventListener("click",_x))},gx=0,vx=-1;function Ex(){return new Promise(((e,t)=>{if("running"===mx.state)return e();Date.now()-gx<1e3?(clearTimeout(vx),vx=setTimeout((()=>{gx=Date.now(),mx.resume().then(e,t)}),1e3)):(clearTimeout(vx),gx=Date.now(),mx.resume().then(e,t))})).catch((e=>{nP.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",_x)}))}document.addEventListener("click",_x);var Tx=e=>mx,yx=class{constructor(e){zC(this,"name"),zC(this,"node"),zC(this,"node2"),zC(this,"pre",new Set),zC(this,"next",new Set),zC(this,"context"),zC(this,"connectedNodes",new Set),zC(this,"nextInputChannelMap",new Map),zC(this,"_channelCount",1),this.name=e}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(Ew){nP.error(Ew)}}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(),IM.addSuccessEvent({key:502701})}catch(pP){nP.error(pP),IM.addFailedEvent({key:502701,error:pP})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),IM.addSuccessEvent({key:502702})}catch(vk){nP.error(vk),IM.addFailedEvent({key:502702,error:vk})}}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}},Sx=class extends yx{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,zC(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}},Ix=class{constructor(){zC(this,"source",new yx),zC(this,"gain",new yx),zC(this,"destination",new yx)}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(Tx().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.replaceNode(Cx(e))}get track(){var e;return null==(e=this.stream)?void 0:e.getAudioTracks()[0]}get stream(){var e;return null==(e=this.destination.node)?void 0:e.stream}},Ax=class extends Ix{constructor(e){super(),this.context=e,zC(this,"audioProcessor",new yx("aec")),zC(this,"mixNode",new yx("mixNode")),zC(this,"muteNode",new yx("muteNode")),zC(this,"denoiser",new yx),zC(this,"voiceChanger",new yx),this.source.pipeTo(this.audioProcessor).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.muteNode.pipeTo(this.mixNode).pipeTo(this.audioProcessor,1)}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.audioProcessor.setContext(this.context),this.muteNode.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.audioProcessor.removeContext(),this.muteNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.audioProcessor.deleteNode(),this.muteNode.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()}},bx=class{constructor(){zC(this,"audioContext",Tx()),zC(this,"destination",this.audioContext.createMediaStreamDestination()),zC(this,"inputs",new Set),zC(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]}},Rx=new WeakMap;function Cx(e){let t=Rx.get(e);if(t)return t;let i=Tx();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return Rx.set(e,t),t}var kx=class e{constructor(e){zC(this,"_volume",0),zC(this,"_volumeDb",0),zC(this,"_log"),zC(this,"_scriptProcessorNode",null),zC(this,"_audioWorkletNode",null),zC(this,"_interval",200),zC(this,"ready",this.preload());let{log:t}=e;this._log=t,eP.on(iP.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=px(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(hP){this._log.error("volumeMeter init audio worklet error: ".concat(hP)),BL.logFailedEvent({userId:this._log.userId,eventType:yw.LOAD_WORKLET,error:hP}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Tx().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(hP){this._log.error("volumeMeter init script processor error: ".concat(hP))}}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,eP.off(iP.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})}};zC(kx,"lastMessageTime",0),zC(kx,"audioContext",Tx()),zC(kx,"workletReady");var wx=kx,Dx=class extends yx{constructor(e){super(),zC(this,"_volumeMeter"),this._volumeMeter=new wx(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return qC(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()}}},Nx=wx,Ox=jC(JC(),1),Px=e=>t=>t.deviceId===e,Mx=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";zC(this,"kind"),zC(this,"type"),zC(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&&Ux(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(Px(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");nP.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(Px(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");nP.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},Lx=class extends Ox.EventEmitter{constructor(){super(),zC(this,"audioInputs",new Mx(zk.AUDIO)),zC(this,"videoInputs",new Mx(zk.VIDEO)),zC(this,"audioOutputs",new Mx(zk.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||PL.run("interval",(()=>{this.update()}),{delay:1e4}))}init(){Vx().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return qC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield Vx(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},xx=yk||Tk?null:new Lx;function Ux(e){return e.deviceId===e.groupId&&""===e.groupId}function Vx(){return qC(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(NM()||!wM())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{Ux(e)&&(e.kind===zk.AUDIO_INPUT?i.audio=!0:e.kind===zk.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&&Ex()}catch(pP){nP.debug("capture before getDevices failed: ",pP)}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&&jx.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function Bx(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return xx.update(e?1:0).then((e=>e.audioInputs.devices))}function Fx(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return xx.update(e?2:0).then((e=>e.videoInputs.devices))}var Hx=!1;function Wx(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return qC(this,null,(function*(){return(gN||bO)&&(e=!1),xx.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var jx=new Set;function Gx(e,t){return qC(this,null,(function*(){let i=(yield Bx()).find((e=>e.deviceId===Vw));return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t}))}var zx,Kx=class extends Ix{constructor(e){super(),this.log=e,zC(this,"volumeMeter"),zC(this,"volumeDestination"),zC(this,"analyser",new Sx),this.volumeMeter=new Dx({log:this.log}),this.volumeDestination=new yx,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},qx=class e extends jL{constructor(e){super(e,zk.AUDIO),zC(this,"_outputDeviceId"),zC(this,"_volume",1),zC(this,"_destination",Tx().createMediaStreamDestination()),zC(this,"pipeline"),zC(this,"volumeMeterMode","worklet"),this.mode=0,this.pipeline=new Kx(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(("15.2"===wO||"15.3"===wO||"15.4"===wO)&&this.muted)return void this._log.info("audioElement is muted.");let t=zx||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,fD(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),t===zx&&(zx=void 0),this.bindElementEvents()}play(t){return qC(this,null,(function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(null==t?void 0:t.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(Tx().createAnalyser()),function(){qC(this,null,(function*(){try{Hx||(Hx=!0,nP.info("speakers:".concat((yield Wx()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(e){}}))}(),KC(e.prototype,this,"play").call(this)}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy(),super.stop(e)}setSinkId(e){return qC(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()}},Jx=class extends qx{setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ML.MEDIA_TRACK_CHANGED,e),e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]))))}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}},Yx=class extends qx{constructor(e){super(e),zC(this,"_sourceElement"),zC(this,"_output",new yx),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(Tx().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(ML.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=(null==(r=e.getSettings())?void 0:r.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?this.element?(this._log.info("set element volume: ".concat(e)),this.element.volume=e):this._log.info("set element volume: no element"):gN||(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),VL(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&RO&&(zx=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},Xx=class extends CL{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:o=(1===r?Yx:hx)}=e;var s;super(),zC(this,"id",oP()),zC(this,"userId",""),zC(this,"isRemote"),zC(this,"mediaType"),zC(this,"room"),zC(this,"user"),zC(this,"_log"),zC(this,"_inputTrack"),zC(this,"_outputTrack"),zC(this,"isPlayCalled"),zC(this,"container",null),zC(this,"player"),zC(this,"subVideoPlayerMap"),zC(this,"muted",!1),zC(this,"abortCtrl"),zC(this,"objectFit","cover"),zC(this,"mirror"),zC(this,"isScreen",!1),zC(this,"manager"),zC(this,"trackSettings"),zC(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=nP.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=n||this.room)?void 0:s.userId,remoteUserId:this instanceof vU?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof vU}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(ML.PLAYER_STATE_CHANGED,(e=>{eP.emit(iP.PLAYER_STATE_CHANGED,VC({track:this},e)),this.emit("player-state-changed",e)})),this.kind===zk.VIDEO&&(this.player.on(ML.LOADED_DATA,(()=>{this.emitFirstVideoFrameEvent(ML.LOADED_DATA),eP.emit(iP.VIDEO_LOADED_DATA,{track:this})})),this.player.on(ML.LOADED_META_DATA,(()=>{this.emitFirstVideoFrameEvent(ML.LOADED_META_DATA)})),this.player.on(ML.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))}))),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(ML.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||nP}get kind(){return 1===this.mediaType?zk.AUDIO:zk.VIDEO}get strMediaType(){return 4===this.mediaType?zk.VIDEO:2===this.mediaType?zk.SCREEN:zk.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 qC(this,null,(function*(){let i=vD(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!pD(t.muted)&&this.setPlayerMute(t.muted),t&&!pD(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof hx&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),vD(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!pD(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===zk.VIDEO)&&this.setPlayerMute(!0),t&&!pD(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof hx&&(this.player.setObjectFit(this.objectFit),t&&!pD(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof hx&&this.player.setContainer(i)),eP.emit(iP.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),vD(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(_P){throw this.handleAutoPlayFailed(_P),_P}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==zk.VIDEO||pD(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(_D(this.mirror))return i.setViewMirror(this.mirror),void(r&&(r.mirror=!1));switch(this.mirror){case"view":r&&(r.mirror=!1),i.setViewMirror(!0);break;case"publish":r&&(r.mirror=!0),i.setViewMirror(!0);break;case"both":r&&(r.mirror=!0),i.setViewMirror(!1)}}playSubContainer(e,t){return qC(this,null,(function*(){if(!this._outputTrack||this.kind===zk.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&&(pD(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new hx({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(r+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let e of i)e.setViewMirror(this.player.mirror),yield e.play()}))}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return(null==(e=this.player)?void 0:e.getInternalAudioLevel())||0}stop(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(iN(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return qC(this,null,(function*(){var e;this.isPlayCalled&&(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),eP.emit(e?iP.TRACK_MUTED:iP.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){UL(e,e).add(zk.MUTE,this.onTrackMuted).add(zk.UNMUTE,this.onTrackUnmuted).add(zk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===zk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){VL(e)}setInputMediaStreamTrack(e){var t;let i=this._inputTrack;if(e!==i)return this._inputTrack=e,this.trackSettings=null==(t=e.getSettings)?void 0:t.call(e),e.enabled=!this.muted,i&&this.uninstallTrackEvent(i),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,i||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(t=e.getSettings)?void 0:t.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled)if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch((e=>this.handleAutoPlayFailed(e))),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(iN(this)?this.jitterBufferDelay:0),void this.log.info("playing state updated, stop ".concat(this.kind));this.log.debug("updatePlayingState abort ".concat(this.isPlayCalled," ").concat(e," ").concat(this.player.isStopped))}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new ux;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof hx?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===ML.LOADED_META_DATA&&!o&&!s||(e===ML.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,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"))}};GC([AL([],CL.INIT,{sync:!0})],Xx.prototype,"close",1);var Qx=Object.prototype.hasOwnProperty;var Zx=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(cD(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(Qx.call(e,t))return!1;return!0}return!1},$x=nN({retryFunction:function(e){return qC(this,null,(function*(){let t=function(e){return{audio:tU(e),video:iU(e)}}(e);nP.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId","groupId"];t.audio&&(i=yield Bx(),nP.info("microphones: ".concat(BD(i.map((e=>BC(VC({},e),{groupId:e.groupId.substring(0,8)}))),{keysToInclude:n})))),t.video&&(r=yield Fx(),nP.info("cameras: ".concat(BD(r,{keysToInclude:n}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return nL&&e.getTracks().forEach((e=>{nP.info("".concat(e.kind," capabilities: ").concat(BD(e.getCapabilities(),{keysToInclude:zw})))})),t.audio&&Ex(),e}catch(_P){let{message:n}=_P;throw"NotFoundError"===_P.name&&(e.video&&r&&0===r.length&&(n=hM({key:cM.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(n=hM({key:cM.MICROPHONE_NOT_FOUND}))),new ck({code:sk.INITIALIZE_FAILED,name:_P.name,message:n,constraint:_P.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,retryFuncArgs:n,retriedCount:o}=e,s=o+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===s?(n[0].video&&(n[0].maxResolution=!1,(!bO||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&&eU(n[0].microphoneId,!1),n[0].cameraId&&eU(n[0].cameraId,!0)},onRetrying:e=>{nP.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{BL.logFailedEvent({eventType:yw.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{BL.logSuccessEvent({eventType:yw.GET_USER_MEDIA_RETRY}),BL.uploadEvent({log:"stat-".concat(yw.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function eU(e,t){return qC(this,null,(function*(){let i=(t?yield Fx():yield Bx()).find((t=>t.deviceId===e));i&&hD(i.getCapabilities)&&nP.warn(BD(i.getCapabilities(),{keysToInclude:zw}))}))}function tU(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!Zx(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(fD(e.channelCount)&&(t.channelCount=e.channelCount),_D(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),_D(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),_D(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!Zx(t)||t)}function iU(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&&!Zx(i)?i:(e.width&&(i.width={ideal:e.width},t&&!SN&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!SN&&(i.height.max=e.height)),SN&&$N&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!Zx(i)||i)}var rU=$x;function nU(e){return aU(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return qC(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function oU(e){return aU(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return qC(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function sU(e){return aU(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return qC(this,null,(function*(){try{return yield t.apply(this,r)}catch(pP){e.call(this,pP)}}))}))}function aU(e){return function(t,i,r){return r.value=e(r.value,i),r}}var cU=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&nP.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{nP.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),lU=0,dU=class{constructor(){zC(this,"log",nP.createLogger({id:"fq".concat(++lU)})),zC(this,"isRunning",!1),zC(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return 0===this.length?null:this.queue[this.length-1]}push(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i,r;let n=VC({},e),o=new Promise(((e,t)=>{n.resolve=e,n.reject=t}));return n.promise=o,t?this.length<=1?this.queue.push(n):null==(r=null==(i=this.lastQueueItem)?void 0:i.promise)||r.then(n.resolve,n.reject):this.queue.push(n),this.log.debug("push ".concat(this.length)),this.isRunning||this.callNext(),o}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length)),e}callNext(){if(this.isRunning||0===this.length)return;this.log.debug("callNext ",this.length);let{fn:e,args:t,context:i,resolve:r,reject:n}=this.queue[0];this.isRunning=!0,e.apply(i,t).then(r,n).finally((()=>{this.isRunning=!1,this.shift(),this.callNext()}))}},uU=new WeakMap,hU=new WeakMap;function pU(){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=uU.get(this)||new dU;for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return uU.set(this,t),t.push({fn:n,args:r,context:this},e)},r}}function mU(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=uU.get(this))?void 0:t.queue)||i.forEach((e=>o.push(e))),null==(r=hU.get(this))||r.forEach((e=>null==e?void 0:e.queue.forEach((e=>o.push(e))))),o.forEach((t=>{t.reject(new ck({code:sk.API_CALL_ABORTED,message:e}))})),uU.delete(this),hU.delete(this),n.apply(this,a)},r}}function fU(e){return function(t,i,r){let n=r.value,o=t=>e(...t);return r.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=hU.get(this)||new Map,s=r.get(o(t))||new dU;return r.set(o(t),s),hU.set(this,r),s.push({fn:n,args:t,context:this})},r}}function _U(e,t){return aU(((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=RD();return yD(e)?e.then((e=>(t?IM.addSuccessEvent({key:r,cost:RD()-a}):IM.addSuccessEvent({key:r}),e))).catch((e=>{throw IM.addFailedEvent({key:r,error:e}),e})):(IM.addSuccessEvent({key:r}),e)}catch(Ek){throw IM.addFailedEvent({key:r,error:Ek}),Ek}}))}var gU=class e extends Xx{constructor(e,t){super({mediaType:e,PlayerClass:t}),zC(this,"isRemote",!1),zC(this,"deviceId"),zC(this,"groupId",""),zC(this,"label",""),zC(this,"sourceTrack"),zC(this,"_isRecapturing",!1),zC(this,"_lastRecaptureTime",0),zC(this,"_onMuteTimeoutId",-1),zC(this,"_encodeCheckTimeoutId",-1),zC(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return"publishing"===this.state.toString()}get isPublished(){return"publish"===this.state}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){UL(e,e).add(zk.MUTE,this.onTrackMuted).add(zk.UNMUTE,this.onTrackUnmuted).add(zk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===zk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){VL(e)}setStateToCapture(){}capture(e){return qC(this,null,(function*(){var t;try{let i,r=RD();eP.emit(iP.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield rU(e));let n=i.getTracks()[0];return this.sourceTrack=n,yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),eP.emit(iP.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:RD()-r}),i}catch(pP){throw eP.emit(iP.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:pP}),this.log.error("getUserMedia error observed ".concat(pP)),pP}}))}setInputMediaStreamTrack(e){return this.state===CL.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return null==(t=this.room)?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),eP.emit(iP.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return qC(this,null,(function*(){if(this.mediaTrack&&rL){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return qC(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==zk.AUDIO||t!==Vw||(yield Gx(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),Vx().then((t=>{let i=t.find((t=>t.deviceId===e));i&&this.emit("2",i)})))}}))}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return!(!this.deviceId||!this.mediaTrack||this.kind===zk.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(zk.AUDIO_INPUT);return!!jx.has(i)}(this.mediaTrack)||this.kind===zk.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(zk.VIDEO_INPUT);return!!jx.has(i)}(this.mediaTrack)||this._isRecapturing||e&&$N&&bO)}onTrackMuted(){if(super.onTrackMuted(),cU(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Gw)return void setTimeout((()=>this.onTrackMuted()),Gw);this._onMuteTimeoutId=setTimeout((()=>qC(this,null,(function*(){var e;if(null!=(e=this.mediaTrack)&&e.muted){if((gN||vN)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return qC(this,null,(function*(){if(KC(e.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Gw)return void setTimeout((()=>this.onTrackEnded()),Gw);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return qC(this,null,(function*(){var t;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),null==(t=this._inputTrack)||t.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let i={useExactDeviceId:!0};if("user"===e||"environment"===e)i.facingMode=e;else{let t;("audio"===this.kind?yield Bx():yield Fx()).find((t=>t.deviceId===e))&&(t=e),i.deviceId=t}return this.capture(i).then((()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),eP.emit(iP.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),eP.emit(iP.LOCAL_TRACK_RECAPTURE,{track:this,error:e})}))}))}getRecoverCaptureDeviceId(){return qC(this,null,(function*(){let e=this instanceof AU;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(EU.get(t)||0)+1;if(EU.set(t,i),i>=3){let r=e?(yield Fx()).find((e=>!EU.has(e.deviceId))):(yield Bx()).find((e=>!EU.has(e.deviceId)));r&&(this.log.warn("".concat(t," capture fail ").concat(i," times, change new ").concat(r.deviceId)),t=r.deviceId)}}return t}))}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),null==(e=this.manager)||e.removeInput(this)}};GC([AL(CL.INIT,"capture",{ignoreError:!0,sync:!0})],gU.prototype,"setStateToCapture",1),GC([pU()],gU.prototype,"capture",1),GC([AL("capture","publish",{ignoreError:!0,success(){var e,t;this.room.localTracks.add(this),eP.emit(iP.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout((()=>{var e,t;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let e=this.kind===zk.AUDIO,t=this.stat.bytesSent>0;IM[t?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),t||(IM.addEnum({key:e?503701:513703,value:YO()}),BL.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(KO()||XO()),userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}}),5e3))},fail(e){let t="error";if(e.cause instanceof RTCError){let i=e.cause;i.message.includes("timeout")?t="timeout":i.code===sk.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),_U(521714,!1)],gU.prototype,"publish",1),GC([aU((e=>function(){return qC(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)}))})),AL([],"capture",{sync:!0})],gU.prototype,"unpublish",1);var vU=gU,EU=new Map;eP.on(iP.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&EU.delete(e.track.deviceId)}));var TU=class e extends vU{constructor(e){super(1,Jx),zC(this,"mediaType",1),zC(this,"volume",0),zC(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),zC(this,"playerMuted",!0),zC(this,"pipeline"),zC(this,"earMonitorGainNode",new yx),zC(this,"_output",new yx),zC(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),zC(this,"mixedAudioReferenceMap",new Map),this.manager=e,this.pipeline=new Ax(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return Nx.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}setInputMediaStreamTrack(t){return qC(this,null,(function*(){let i=this.trackSettings||{};IM.addEnum({key:501701,value:i.channelCount||0,useUV:!1}),IM.addEnum({key:501702,value:i.sampleRate||0,useUV:!1}),IM.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 KC(e.prototype,this,"setInputMediaStreamTrack").call(this,t),this.updatePlayingState(!!t)}))}capture(e){let{deviceId:t,customSource:i,useExactDeviceId:r=!0,retryWhenExactFailed:n=!0}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:n,customSource:i})}switchDevice(e){return qC(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==Vw)return;if(yield Gx(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),eP.emit(iP.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(Ew){throw this.log.error("switch microphone failed ".concat(Ew)),this.deviceId&&this.recapture(this.deviceId),Ew}}}))}listenDeviceChange(){xx&&!xx.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&xx.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return qC(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e))),fF(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield Bx();t[0]?this.recapture(t[0].deviceId):xx.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return qC(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;!pD(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,o.echoCancellation=i,s=!0),!pD(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,o.noiseSuppression=r,s=!0),!pD(n)&&n!==t.profile.autoGainControl&&(t.profile.autoGainControl=n,o.autoGainControl=n,s=!0),s&&(SN||bO?yield e.applyConstraints(o).catch((e=>t._log.warn("update3A failed: ",e))):t.deviceId&&(yield t.recapture(t.deviceId)))}()}))}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&IM.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),gN&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Tx().createGain()),this._output.setNode(Tx().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this._inputTrack&&!bO&&!gN)return this.update3A({echoCancellation:e})}addDenoiser(e){var t;IO<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(IM.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=Cx(e),r=new yx,n=Tx().createGain();n.gain.value=1;let o=new yx;r.pipeTo(o).pipeTo(this.pipeline.mixNode),r.setNode(i),o.setNode(n),this.mixedAudioReferenceMap.set(t,[r,o])}unMixAudioReference(e){let[t,i]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info("unMixAudioReference() => ".concat(e)),t.deleteNode(),null==i||i.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[i,r]=this.mixedAudioReferenceMap.get(e)||[];null!=r&&r.node&&(r.node.gain.value=t/100,this.log.info("setAudioReferenceVolume() => ".concat(e," ").concat(r.node.gain.value)))}addAudioProcessor(e,t,i,r){this.pipeline.muteNode.setNode(i),this.pipeline.mixNode.setNode(t),this.pipeline.audioProcessor.setNode(e),this.enableTrackAEC(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}removeAudioProcessor(e,t,i,r){this.pipeline.audioProcessor.node===e&&(this.pipeline.audioProcessor.deleteNode(),this.pipeline.muteNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}close(){this.mixedAudioReferenceMap.forEach((e=>{let[t,i]=e;t.deleteNode(),i.deleteNode()})),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),xx.off("audioInputAdded",this.handleMicrophoneAdded,this),xx.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(t){return qC(this,null,(function*(){try{yield KC(e.prototype,this,"recapture").call(this,t)}catch(Ew){let r=(yield Bx()).find((e=>e.deviceId!==t));if(!r)throw Ew;yield KC(e.prototype,this,"recapture").call(this,r.deviceId)}}))}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight(((e,t)=>t?t({frame:e}):e),e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}},yU=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,i=[],r=0;for(let o=e;o<=t;o++){let e=this.dataView.getInt8(o);switch(e){case 0:case 1:case 2:case 3:2===r&&(i.push(3),r=0),0==e?r++:r=0,i.push(e);break;default:r=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],r=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:r++,i.push(this.dataView.getInt8(o));break;case 3:2!==r&&i.push(this.dataView.getInt8(o)),r=0;break;default:i.push(this.dataView.getInt8(o)),r=0}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}get isSEI(){return 6===this.dataView.getUint8(4)}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let n=6;n<this.dataView.buffer.byteLength;n++){let i=this.dataView.getUint8(n);if(t++,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),r=new DataView(i);for(let n=0;n<i.byteLength;n++,t++)r.setInt8(n,this.dataView.getInt8(t));return r}},SU=class{constructor(){zC(this,"_seiMessageList",[]),zC(this,"_smallSeiMessageList",[]),zC(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 yU(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}},IU=class e extends vU{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,hx),zC(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),zC(this,"avoidCropping",!1),zC(this,"_scaleResolutionDownBy"),zC(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0}),zC(this,"small"),zC(this,"isNeedToSetBandwidth"),zC(this,"muteImage"),zC(this,"manager"),zC(this,"_seiCodec",new SU),this.manager=e;let t=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(BC(VC({},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(rL&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return(null==(e=this._inputTrack)?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}setMute(t){return qC(this,null,(function*(){var i,r,n;if(mD(t)){if(this.muteImage===t)return;yield null==(i=this.manager)?void 0:i.deleteWatermark("mute"),yield null==(r=this.manager)?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:t}),this.muteImage=t,KC(e.prototype,this,"setMute").call(this,!1)}else yield null==(n=this.manager)?void 0:n.deleteWatermark("mute"),this.muteImage=void 0,KC(e.prototype,this,"setMute").call(this,t)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:r=!0,customSource:n,retryWhenExactFailed:o=!0}=e;return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:o,customSource:n})}setProfile(e){let t=VC({},e),i=t.width>t.height;t.width*t.height<=19200&&vN&&TO&&(this.log.warn("resolution is ".concat(t.width,"*").concat(t.height,", fallback to 240*180")),t.width=i?240:180,t.height=i?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&MO&&(t.width=i?1280:720,t.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),this.avoidCropping&&(TO||SN)&&!WO()&&t.width*t.height<=230400&&t.width/t.height==16/9&&(this._scaleResolutionDownBy=1280/t.width,t.width=1280,t.height=720,this.log.warn("capture 720p, scale: ".concat(this._scaleResolutionDownBy))),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(BC(VC({},this.profile),{width:1920,height:1080})))}applyProfile(){return qC(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;if((n.height!==this.profile.height||n.width!==this.profile.width||n.frameRate!==this.profile.frameRate)&&this.deviceId&&(16===NO?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 i&&r&&i===r?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:zk.VIDEO,videoType:zk.BIG})}}))}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return rL&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){if(this._scaleResolutionDownBy)return this._scaleResolutionDownBy;let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:WD()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||1===(null==(t=this.room.scheduleResult.trtcAutoConf)?void 0:t["2k4k"])}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return qC(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),eP.emit(iP.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(Ew){throw this.log.error("switch camera failed ".concat(Ew)),this.deviceId&&this.recapture(this.deviceId),Ew}}))}listenDeviceChange(){xx&&!xx.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&xx.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return qC(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e))),fF(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield Fx();t[0]?this.recapture(t[0].deviceId):xx.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return qC(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}encodeFrame(e,t){if(!this.manager)return e;let i=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight(((e,t)=>t?t({frame:e,mediaType:i}):e),e)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}play(e,t){return pD(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){xx.off("videoInputAdded",this.handleCameraAdded,this),xx.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return qC(this,null,(function*(){try{yield KC(e.prototype,this,"recapture").call(this,t)}catch(Ew){let r=(yield Fx()).find((e=>e.deviceId!==t));if(!r)throw Ew;yield KC(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))}};GC([oU((function(e){this.setContentHint(e.contentHint||"motion")}))],IU.prototype,"capture",1);var AU=IU,bU=oP();if("undefined"!=typeof navigator&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:bU,exposeOrigin:!0,permittedOrigins:["*"]})}catch(IC){}var RU=function(e){return qC(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:bO?{max:e.width}:{ideal:e.width,max:e.width},height:bO?{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);nP.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(yO&&IO<74||bO||SN)&&nP.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(_P){nP.warn("screen applyConstraints failed: ".concat(_P))}e.captureElement&&(yield function(e,t){return qC(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&hD(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==bU)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){nP.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 pD(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);nP.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},CU=class extends AU{constructor(e){super(e,2),zC(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),zC(this,"objectFit","contain"),zC(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return qC(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:r,echoCancellation:n,noiseSuppression:o,audioTrack:s,videoTrack:a,captureElement:c,preferDisplaySurface:l}=e;return function*(){try{let e;return a||s?(e=new MediaStream,a&&e.addTrack(a),s&&e.addTrack(s)):e=yield RU({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:r,echoCancellation:n,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof ck?e:new ck({code:sk.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return qC(this,null,(function*(){throw new Error("Method not implemented.")}))}};GC([oU((function(e){this.setContentHint(e.contentHint||"detail")}))],CU.prototype,"capture",1);var kU,wU=class extends TU{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}addAudioProcessor(e,t,i,r){this.pipeline.muteNode.setNode(i),this.pipeline.mixNode.setNode(t),this.pipeline.audioProcessor.setNode(r),this.enableTrackAEC(!1)}removeAudioProcessor(e,t,i,r){this.pipeline.audioProcessor.node===r&&(this.pipeline.audioProcessor.deleteNode(),this.pipeline.muteNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};function DU(e){return qC(this,null,(function*(){let t=Tx();kU||(kU=px(t,URL.createObjectURL(new Blob(["registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});"],{type:"application/javascript"})))),yield kU;let i=new AudioWorkletNode(t,"dumper",{numberOfInputs:e.length,numberOfOutputs:0});return e.forEach(((e,t)=>e.connect(i,0,t))),new ReadableStream({start(e){i.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach((e=>e.disconnect(i))),i.port.close()}})}))}var NU=class extends bx{constructor(e){super(),this.room=e,zC(this,"_localAudioTrack"),zC(this,"_localScreenAudioTrack"),zC(this,"log",nP.createLogger({id:"am"})),zC(this,"denoiser"),zC(this,"voiceChanger"),zC(this,"mixChangedDebounce"),zC(this,"audioProcessor"),zC(this,"encodePipeline",[]),zC(this,"decodePipeline",[]),zC(this,"audioReferenceMap",new Map),zC(this,"isLocalAudioNeedAudioProcess",!1),zC(this,"isScreenAudioNeedAudioProcess",!1),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.handleAudioReferenceChanged=this.handleAudioReferenceChanged.bind(this),eP.on(iP.AUDIO_PROCESSOR_REFERENCE_CHANGED,this.handleAudioReferenceChanged)}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=DU(r).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>s[t]=s[t]?s[t].concat(e[0]):[e[0]]))}}),o).catch((e=>c))));return{then:l.then.bind(l),download:c}}getPCM(e){var t;if(pD(WritableStream))return void this.log.warn("getPCM failed: browser not support WritableStream");if(null==(t=this._localAudioPipline)||!t.source.node)return void this.log.warn("getPCM failed: no local audio track");this.log.warn("getPCM");let i=new Float32Array(1920),r=0,n=new AbortController;return DU([this._localAudioPipline.source.node]).then((t=>t.pipeTo(new WritableStream({write(t){t[0][0]&&(i.set(t[0][0],r),r+=t[0][0].length,r>=1920&&(r=0,e(i),i=new Float32Array(1920)))}}),n).catch((e=>this.log.warn("stop getPCM reason:".concat(e)))))),n}get hasScreenAudioTrack(){return!pD(this._localScreenAudioTrack)}get hasAudioTrack(){return!pD(this._localAudioTrack)}changeInput(e){return e instanceof wU?(this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach(((t,i)=>{e.mixAudioReference(t,i)}))),e.pipeline.connect(),this.mixOnChange()):e instanceof TU?(this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach(((t,i)=>{e.mixAudioReference(t,i)}))),e.pipeline.connect(),this.mixOnChange()):e instanceof JB?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 wU?delete this._localScreenAudioTrack:e instanceof TU&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}addAudioProcessor(e,t,i,r){var n;this.audioProcessor=[e,t,i,r],this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&(this._localAudioTrack.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach(((e,t)=>{var i;null==(i=this._localAudioTrack)||i.mixAudioReference(e,t)}))),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&(null==(n=this._localScreenAudioTrack)||n.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach(((e,t)=>{var i;null==(i=this._localScreenAudioTrack)||i.mixAudioReference(e,t)})))}removeDenoiser(e){var t;delete this.denoiser,null==(t=this._localAudioTrack)||t.removeDenoiser(e)}addVoiceChanger(e,t){var i;this.voiceChanger=[e,t],null==(i=this._localAudioTrack)||i.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,null==(e=this._localAudioTrack)||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t,i,r){var n;delete this.audioProcessor,null==(n=this._localAudioTrack)||n.removeAudioProcessor(e,t,i,r)}destroy(){eP.off(iP.AUDIO_PROCESSOR_REFERENCE_CHANGED,this.handleAudioReferenceChanged),this.close()}addEncodeProcessor(e){let{processor:t,type:i}=e;var r;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:i}=e;var r;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}handleAudioReferenceChanged(e){let{room:t,type:i,audioReference:r,refId:n,volume:o}=e;if(t===this.room)if("add"===i){if(this.audioReferenceMap.get(n)||!r||(this.audioReferenceMap.set(n,r),!this.audioProcessor))return;this.mixAudioReference(r,n)}else if("remove"===i)this.audioReferenceMap.get(n)&&(this.audioReferenceMap.delete(n),this.unMixAudioReference(n));else if("update_volume"===i){if(!this.audioProcessor||pD(o))return;this.setAudioReferenceVolume(n,o)}}checkScreenAudioEchoCancellation(){}};function OU(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return aU(((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 ck({code:sk.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});nP.warn(i),2===t?s(i):1===t&&n()}),1e3*e);i.apply(this,o).then(n,s).finally((()=>{clearTimeout(a)}))}))}))}var PU={};function MU(){}WC(PU,{Events:()=>YU,Inspect:()=>FU,LastSink:()=>HU,Sink:()=>WU,Subscribe:()=>jU,TimeoutError:()=>XU,audit:()=>eB,bindCallback:()=>wV,bindNodeCallback:()=>DV,buffer:()=>lV,bufferCount:()=>cV,bufferTime:()=>UB,call:()=>LU,catchError:()=>BB,combineLatest:()=>nV,concat:()=>tV,concatMap:()=>bB,concatMapTo:()=>RB,count:()=>xV,create:()=>zU,debounce:()=>rB,debounceTime:()=>nB,defer:()=>hV,delay:()=>VB,deliver:()=>KU,dispose:()=>UU,elementAt:()=>oB,empty:()=>PV,every:()=>dB,exhaustMap:()=>PB,exhaustMapTo:()=>MB,filter:()=>FV,find:()=>sB,findIndex:()=>aB,first:()=>cB,fromAnimationFrame:()=>CV,fromArray:()=>_V,fromEvent:()=>yV,fromEventPattern:()=>TV,fromFetch:()=>IV,fromIterable:()=>AV,fromPromise:()=>SV,fromReadableStream:()=>RV,fromReader:()=>bV,groupBy:()=>LB,identity:()=>xU,ignoreElements:()=>HV,iif:()=>rV,inspect:()=>VU,interval:()=>gV,last:()=>lB,map:()=>mB,mapTo:()=>fB,max:()=>UV,merge:()=>$U,mergeMap:()=>wB,mergeMapTo:()=>DB,min:()=>VV,never:()=>NV,nothing:()=>MU,of:()=>fV,pairwise:()=>hB,pipe:()=>GU,race:()=>eV,range:()=>kV,reduce:()=>LV,retry:()=>zB,scan:()=>uB,share:()=>ZU,shareReplay:()=>iV,skip:()=>KV,skipUntil:()=>qV,skipWhile:()=>JV,startWith:()=>sV,subject:()=>uV,subscribe:()=>WB,sum:()=>BV,switchMap:()=>TB,switchMapTo:()=>SB,take:()=>WV,takeLast:()=>zV,takeUntil:()=>jV,takeWhile:()=>GV,tap:()=>jB,throttle:()=>ZV,throwError:()=>OV,timeInterval:()=>xB,timeout:()=>GB,timer:()=>vV,toPromise:()=>FB,toReadableStream:()=>HB,withLatestFrom:()=>aV,zip:()=>oV});var LU=e=>e(),xU=e=>e;function UU(){this.dispose()}var VU=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,BU=1,FU=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new JU(e,this,this.streamId++);return YU.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},HU=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=MU,this.error=MU,this.next=MU,this.dispose=MU,this.subscribe=MU,this.doDefer()}subscribe(e){return e instanceof FU?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(LU),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}},WU=class extends HU{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)}},jU=class extends HU{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:MU,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:MU,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:MU;if(super(),this._next=t,this._error=i,this._complete=r,this.then=MU,e instanceof FU){let n={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{YU.defer(n,0)})),YU.create(n),YU.pipe(n),this.sourceId=n.id,this.subscribe(e),YU.subscribe({id:n.id,end:!0}),t==MU?this._next=e=>YU.next(n,0,e):this.next=e=>{YU.next(n,0,e),t(e)},r==MU?this._complete=()=>YU.complete(n,0):this.complete=()=>{this.dispose(),YU.complete(n,0),r()},i==MU?this._error=e=>YU.complete(n,0,e):this.error=e=>{this.dispose(),YU.complete(n,0,e),i()}}else this.subscribe(e)}next(e){this._next(e)}complete(){this.dispose(),this._complete()}error(e){this.dispose(),this._error(e)}};function GU(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 zU(e,t,i){if(VU()){let r=Object.defineProperties(Object.setPrototypeOf(e,FU.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}});YU.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof FU&&YU.addSource(r,t)}return r}return e}function KU(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 FU){let n=zU((t=>{let o=new e(t,...r);o.sourceId=n.id,o.subscribe(i)}),t,arguments);return n.source=i,YU.pipe(n),n}return t=>i(new e(t,...r))}}}function qU(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var JU=class extends WU{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{YU.defer(this.source,this.id)}))}next(e){YU.next(this.source,this.id,e),this.sink.next(e)}complete(){YU.complete(this.source,this.id),this.sink.complete()}error(e){YU.complete(this.source,this.id,e),this.sink.error(e)}},YU={addSource(e,t){qU("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){qU("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;qU("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){qU("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){qU("defer",{id:e.id,streamId:t})},pipe(e){qU("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){qU("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=BU++),qU("create",{name:e.toString(),id:e.id})}},XU=class extends Error{constructor(e){super("timeout after ".concat(e,"ms")),this.timeout=e}},QU=class extends HU{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 ZU(){return e=>{let t=new QU(e);if(e instanceof FU){let i=zU((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,YU.pipe(i),i}return zU(t.add.bind(t),"share",arguments)}}function $U(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return zU((e=>{let i=new WU(e),r=t.length;i.complete=()=>{0==--r&&e.complete()},t.forEach(i.bindSubscribe)}),"merge",arguments)}function eV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return zU((e=>{let i=new Map;t.forEach((t=>{let r=new WU(e);i.set(t,r),r.complete=()=>{i.delete(t),0===i.size?e.complete():r.dispose()},r.next=e=>{i.delete(t),i.forEach((e=>e.dispose())),r.resetNext(),r.resetComplete(),r.next(e)}})),t.forEach((e=>i.get(e).subscribe(e)))}),"race",arguments)}function tV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return zU((e=>{let i=0,r=t.length,n=new WU(e);n.complete=()=>{i<r&&!n.disposed?(n.doDefer(),n.subscribe(t[i++])):e.complete()},n.complete()}),"concat",arguments)}function iV(e){return t=>{let i=new QU(t),r=[];return i.next=function(t){r.push(t),r.length>e&&r.shift(),this.sinks.forEach((e=>e.next(t)))},zU((e=>{e.defer((()=>i.remove(e))),r.forEach((t=>e.next(t))),i.add(e)}),"shareReplay",arguments)}}function rV(e,t,i){return zU((r=>e()?t(r):i(r)),"iif",arguments)}function nV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return zU((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 WU(e);n.next=t=>{0==--r?(n.next=t=>{o[i]=t,e.next(o)},n.next(t)):o[i]=t},n.complete=s,n.subscribe(t)}))}),"combineLatest",arguments)}function oV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return zU((e=>{let i=t.length,r=i,n=new Array(i),o=()=>{0==--r&&e.complete()};t.forEach(((t,i)=>{let r=new WU(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 sV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>zU((function(i){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.length;for(;r<n&&!i.disposed;)i.next(t[r++]);i.disposed||i.subscribe(e)}),"startWith",arguments)}var aV=KU(class extends WU{constructor(e){super(e);let t=new WU(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=MU,t.subscribe(nV(...r))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},"withLatestFrom"),cV=KU(class extends WU{constructor(e,t,i){super(e),this.bufferSize=t,this.startBufferEvery=i,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(e){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach((t=>{t.push(e)})),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(e),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach((e=>this.sink.next(e))),super.complete()}},"bufferCount"),lV=KU(class extends WU{constructor(e,t){super(e),this.buffer=[];let i=new WU(e);i.next=t=>{e.next(this.buffer),this.buffer=[]},i.complete=MU,i.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),dV=function(e,t,i,r){return new(i||(i=Promise))((function(n,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 uV(e){let t=arguments,i=ZU()(zU((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=MU,i.complete=MU,i.error=MU,i}function hV(e){return zU((t=>t.subscribe(e())),"defer",arguments)}var pV=e=>t=>{setTimeout((()=>e(t)))},mV=e=>pV((t=>{for(let i=0;!t.disposed&&i<e.length;i++)t.next(e[i]);t.complete()}));function fV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return zU(mV(t),"of",arguments)}function _V(e){return zU(mV(e),"fromArray",arguments)}function gV(e){return zU((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}function vV(e,t){return zU((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 EV(e,t){return i=>{let r=e=>i.next(e);i.defer((()=>t(r))),e(r)}}function TV(e,t){return zU(EV(e,t),"fromEventPattern",arguments)}function yV(e,t){if("on"in e&&"off"in e)return zU(EV((i=>e.on(t,i)),(i=>e.off(t,i))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return zU(EV((i=>e.addListener(t,i)),(i=>e.removeListener(t,i))),"fromEvent",arguments);if("addEventListener"in e)return zU(EV((i=>e.addEventListener(t,i)),(i=>e.removeEventListener(t,i))),"fromEvent",arguments);throw"target is not a EventDispachter"}function SV(e){return zU((t=>{e.then(t.next.bind(t),t.error.bind(t))}),"fromPromise",arguments)}function IV(e,t){return zU(hV((()=>SV(fetch(e,t)))),"fromFetch",arguments)}function AV(e){return zU(pV((t=>{try{for(let i of e){if(t.disposed)return;t.next(i)}t.complete()}catch(vk){t.error(vk)}})),"fromIterable",arguments)}function bV(e){let t=i=>dV(this,void 0,void 0,(function*(){if(i.disposed)return;let{done:r,value:n}=yield e.read();r?i.complete():(i.next(n),t(i))}));return zU((e=>{t(e)}),"fromReader",arguments)}function RV(e){return zU((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 CV(){return zU((e=>{let t=requestAnimationFrame((function i(r){e.disposed||(e.next(r),t=requestAnimationFrame(i))}));e.defer((()=>cancelAnimationFrame(t)))}),"fromAnimationFrame",arguments)}function kV(e,t){return zU((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 wV(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 zU((i=>{let n=r.concat((e=>(i.next(e),i.complete())));e.apply(t,n)}),"bindCallback",arguments)}function DV(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return zU((i=>{let n=r.concat(((e,t)=>e?i.error(e):(i.next(t),i.complete())));e.apply(t,n)}),"bindNodeCallback",arguments)}function NV(){return zU((()=>{}),"never",arguments)}function OV(e){return zU((t=>t.error(e)),"throwError",arguments)}function PV(){return zU((e=>e.complete()),"empty",arguments)}var MV=class extends WU{constructor(e,t,i){super(e),this.f=t;let r=()=>{this.sink.next(this.acc),this.sink.complete()};void 0===i?this.next=e=>{this.acc=e,this.complete=r,this.resetNext()}:(this.acc=i,this.complete=r)}next(e){this.acc=this.f(this.acc,e)}},LV=KU(MV,"reduce"),xV=e=>KU(MV,"count")(((t,i)=>e(i)?t+1:t),0),UV=()=>KU(MV,"max")(Math.max),VV=()=>KU(MV,"min")(Math.min),BV=()=>KU(MV,"sum")(((e,t)=>e+t),0),FV=KU(class extends WU{constructor(e,t,i){super(e),this.filter=t,this.thisArg=i}next(e){this.filter.call(this.thisArg,e)&&this.sink.next(e)}},"filter"),HV=KU(class extends WU{next(e){}},"ignoreElements"),WV=KU(class extends WU{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&this.complete()}},"take"),jV=KU(class extends WU{constructor(e,t){super(e);let i=new WU(e);i.next=()=>e.complete(),i.complete=UU,i.subscribe(t)}},"takeUntil"),GV=KU(class extends WU{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):this.complete()}},"takeWhile"),zV=e=>LV(((t,i)=>(t.push(i),t.length>e&&t.shift(),t)),[]),KV=KU(class extends WU{constructor(e,t){super(e),this.count=t}next(e){0==--this.count&&(this.next=super.next)}},"skip"),qV=KU(class extends WU{constructor(e,t){super(e),e.next=MU;let i=new WU(e);i.next=()=>{i.dispose(),e.resetNext()},i.complete=UU,i.subscribe(t)}},"skipUntil"),JV=KU(class extends WU{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),YV={leading:!0,trailing:!1},XV=class extends WU{constructor(e,t,i){super(e),this.durationSelector=t,this.trailing=i}cacheValue(e){this.last=e,this.disposed&&this.throttle(e)}send(e){this.sink.next(e),this.throttle(e)}throttle(e){this.reset(),this.subscribe(this.durationSelector(e))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},QV=class extends WU{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:YV;super(e),this.durationSelector=t,this.config=i,this._throttle=new XV(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(e){this._throttle.disposed&&this.config.leading?this._throttle.send(e):this._throttle.cacheValue(e)}complete(){this._throttle.throttle=MU,this._throttle.complete(),super.complete()}},ZV=KU(QV,"throttle"),$V={leading:!1,trailing:!0},eB=e=>KU(QV,"audit")(e,$V),tB=class extends WU{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},iB=class extends WU{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new tB(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()}},rB=KU(iB,"debounce"),nB=e=>KU(iB,"debounceTime")((t=>vV(e))),oB=KU(class extends WU{constructor(e,t,i){super(e),this.count=t,this.defaultValue=i}next(e){0==this.count--&&(this.defaultValue=e,this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("not enough elements in sequence"))}},"elementAt"),sB=e=>t=>WV(1)(JV((t=>!e(t)))(t)),aB=KU(class extends WU{constructor(e,t){super(e),this.f=t,this.i=0}next(e){this.f(e)?(this.sink.next(this.i++),this.complete()):++this.i}},"findIndex"),cB=KU(class extends WU{constructor(e,t,i){super(e),this.f=t,this.defaultValue=i,this.index=0}next(e){(!this.f||this.f(e,this.index++))&&(this.defaultValue=e,this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"first"),lB=KU(class extends WU{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"),dB=KU(class extends WU{constructor(e,t){super(e),this.predicate=t,this.index=0}next(e){this.predicate(e,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){void 0!==this.result?(this.sink.next(this.result),super.complete()):this.error(new Error("no elements in sequence"))}},"every"),uB=KU(class extends WU{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"),hB=KU(class extends WU{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},"pairwise"),pB=class extends WU{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},mB=KU(pB,"map"),fB=e=>KU(pB,"mapTo")((t=>e)),_B=class extends WU{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()}},gB=class extends WU{constructor(e,t,i){super(e),this.makeSource=t,this.combineResults=i,this.index=0}subInner(e,t){let i=this.currentSink=new t(this.sink,e,this);this.complete=this.tryComplete,i.complete=i.tryComplete,i.subscribe(this.makeSource(e,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},vB=class extends _B{},EB=class extends gB{next(e){this.subInner(e,vB),this.next=e=>{this.currentSink.dispose(),this.subInner(e,vB)}}},TB=KU(EB,"switchMap");function yB(e){return(t,i)=>e((()=>t),i)}var SB=yB(KU(EB,"switchMapTo")),IB=class extends _B{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},AB=class extends gB{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(),IB),this.disposed&&0===this.sources.length&&this.currentSink.resetComplete()}tryComplete(){0===this.sources.length&&this.currentSink.resetComplete(),this.dispose()}},bB=KU(AB,"concatMap"),RB=yB(KU(AB,"concatMapTo")),CB=class extends _B{tryComplete(){this.context.inners.delete(this),super.dispose(),0===this.context.inners.size&&this.context.resetComplete()}},kB=class extends gB{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,CB),this.inners.add(this.currentSink)}tryComplete(){1===this.inners.size?this.inners.forEach((e=>e.resetComplete())):this.dispose()}},wB=KU(kB,"mergeMap"),DB=yB(KU(kB,"mergeMapTo")),NB=class extends _B{dispose(){this.context.resetNext(),super.dispose()}},OB=class extends gB{next(e){this.next=MU,this.subInner(e,NB)}},PB=KU(OB,"exhaustMap"),MB=yB(KU(OB,"exhaustMapTo")),LB=KU(class extends WU{constructor(e,t){super(e),this.f=t,this.groups=new Map}next(e){let t=this.f(e),i=this.groups.get(t);void 0===i&&(i=uV(),i.key=t,this.groups.set(t,i),super.next(i)),i.next(e)}complete(){this.groups.forEach((e=>e.complete())),super.complete()}error(e){this.groups.forEach((t=>t.error(e))),super.error(e)}},"groupBy"),xB=KU(class extends WU{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"),UB=KU(class extends WU{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"),VB=KU(class extends WU{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"),BB=KU(class extends WU{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),FB=()=>e=>new Promise(((t,i)=>{let r;new jU(e,(e=>r=e),i,(()=>t(r)))})),HB=()=>e=>{let t;return new ReadableStream({start(i){t=new jU(e,i.enqueue.bind(i),i.error.bind(i),i.close.bind(i))},cancel(){t.dispose()}})},WB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:MU,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:MU,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:MU;return r=>new jU(r,e,t,i)},jB=KU(class extends WU{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=KU(class extends WU{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout((()=>this.error(new XU(this.timeout))),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),zB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0;return t=>{if(t instanceof FU){let i=zU((r=>{let n=e,o=new WU(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,YU.pipe(i),i}return i=>{let r=e,n=new WU(i);n.error=e=>{r-- >0?t(n):i.error(e)},t(n)}}},KB=class e extends Xx{constructor(t,i,r){super({userId:i.userId,sdkAppId:t.sdkAppId,mediaType:r,room:t}),this.room=t,this.user=i,zC(this,"tinyId"),zC(this,"isRemote",!0),zC(this,"jitterBufferDelay",0),zC(this,"availableState"),zC(this,"remotePublishState"),zC(this,"_triggerCheckDecodeSubject",uV(yV(this,e.STATE_SUBSCRIBE))),this.tinyId=i.tinyId,this.availableState=new CL("".concat(i.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new CL("".concat(i.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),GU($U(yV(this,CL.STATECHANGED),yV(this.remotePublishState,CL.STATECHANGED)),mB((()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing))),WB((e=>{this.availableState.state!==(e?CL.ON:CL.OFF)&&(this.availableState.state=e?CL.ON:CL.OFF),this.updatePlayingState(e)})));let n=GU(yV(this.player,ML.ERROR),FV((e=>e.code===MediaError.MEDIA_ERR_DECODE))),o=GU(vV(5e3),FV((()=>!(this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived)&&(!this.player.isPlaying&&!(this.kind===zk.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1))))),s=GU(eV(n,o),jV(yV(this,CL.INIT)));GU(this._triggerCheckDecodeSubject,FV((()=>!this.ignoreDecodeError)),SB(s),WB((e=>{this.reportDecodeResult(!1,e)})))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)}))}get ignoreDecodeError(){var e,t;return((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===e.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===CL.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){let i=this.kind===zk.AUDIO;IM[e?"addSuccessEvent":"addFailedEvent"]({key:i?504700:514702}),e||(IM.addEnum({key:i?504701:514703,value:YO()}),BL.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(KO()||XO()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===zk.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," isAvailable: ").concat(this.isRemotePublished," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?CL.ON:CL.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};zC(KB,"STATE_SUBSCRIBE","subscribe"),GC([OU(5,1)],KB.prototype,"waitHasMediaTrack",1),GC([AL(CL.INIT,KB.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),eP.emit(iP.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),_U(521716,!1)],KB.prototype,"subscribe",1),GC([AL(KB.STATE_SUBSCRIBE,CL.INIT,{sync:!0,success(){this.log.info("unsubscribed"),eP.emit(iP.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],KB.prototype,"unsubscribe",1);var qB=KB,JB=class extends qB{constructor(e,t){super(e,t,1),zC(this,"volume",0),zC(this,"mediaType",1),zC(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}get dbVolume(){return Nx.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let t=e;for(let i of this.manager.decodePipeline)if(i&&(t=i({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}},YB=[-1,-1,1,-1,-1,1,1,1],XB=[0,0,1,0,0,1,1,1],QB=class extends CL{constructor(e,t){if(super(),this.context=e,zC(this,"name"),zC(this,"input"),zC(this,"output"),zC(this,"texture"),zC(this,"ctx2d",null),zC(this,"fbo"),zC(this,"width",0),zC(this,"height",0),zC(this,"x",0),zC(this,"y",0),zC(this,"program"),zC(this,"vertexShader"),zC(this,"fragmentShader"),zC(this,"totalFrames",0),zC(this,"dropFrames",0),zC(this,"matchInputSize",!0),zC(this,"texCoordBuffer"),zC(this,"positionBuffer"),zC(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),zC(this,"cost",0),zC(this,"_canvas",null),zC(this,"_image"),zC(this,"log"),this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof uF)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==NO?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(XB),this.positionBuffer=this.createBuffer(YB),!1!==t.createTexture&&(this.texture=i.createTexture(),this.useTexture(),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.pixelStorei(i.PACK_ALIGNMENT,1),i.pixelStorei(i.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=i.createFramebuffer(),this.useBufferFrame(),this.useTexture(),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(i.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(i.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(pP){this.context.destroy(new ck({code:sk.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(pP.message||pP)}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,i=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,i),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),i}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return e.addInput(this,...i),this.output=e,e}addInput(e){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();return!!(this.context instanceof dF&&this.render(e)||this.context instanceof uF&&this.render2d(e))&&(this.totalFrames++,this.cost=Date.now()-t,!0)}render2d(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&this.draw2d(this.input.image,0,0,this.width,this.height)}update(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;null==(t=this.output)||t.update(e)}disconnect(){for(var e,t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];null==(e=this.output)||e.removeInput(this,...i),delete this.output}removeInput(e){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),null==(e=this.output)||e.removeInput(this),delete this.output,null==(t=this.input)||t.disconnect(),this.context instanceof dF){let e=this.context.ctx;e.deleteBuffer(this.texCoordBuffer),e.deleteBuffer(this.positionBuffer),this.fbo&&e.deleteFramebuffer(this.fbo),this.texture&&e.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&e.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&e.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&e.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures(null==(e=this.input)?void 0:e.texture)}useTextures(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];i.forEach(((t,i)=>{t&&(e.activeTexture(e.TEXTURE0+i),e.bindTexture(e.TEXTURE_2D,t))}))}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),i}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let i=this.context.ctx;i.bindBuffer(i.ARRAY_BUFFER,e),i.bufferData(i.ARRAY_BUFFER,new Float32Array(t),i.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];i.forEach(((t,i)=>{e.enableVertexAttribArray(i),e.bindBuffer(e.ARRAY_BUFFER,t),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0)}))}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(this.width!==e||this.height!==t){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let i=this.context.ctx;i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let i=this.context.ctx;i.drawArrays(i.TRIANGLE_STRIP,0,4)}draw2d(e,t,i,r,n){return!(!this.ctx2d||!e)&&(e instanceof ImageData?this.ctx2d.putImageData(e,t,i):(this.ctx2d.drawImage(e,t,i,r,n),"undefined"!=typeof VideoFrame&&e instanceof VideoFrame&&e.close()),!0)}getInfo(){var e;let{totalFrames:t,x:i,y:r,width:n,height: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},VC({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,i=t.createTexture();return this.useTextures(i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};GC([AL(CL.INIT,"connected",{sync:!0})],QB.prototype,"connect",1),GC([AL("connected",CL.INIT,{ignoreError:!0,sync:!0})],QB.prototype,"disconnect",1),GC([AL([],"closed",{sync:!0})],QB.prototype,"close",1);var ZB=GU(gV(250),mB((()=>performance.now())),ZU()),$B=[0,1,1,1,0,0,1,0],eF=class extends QB{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),zC(this,"_intervalId",0),zC(this,"_sequence",0),zC(this,"checkGLError",!1),zC(this,"checkVisibilityChange"),e instanceof uF?this.ctx2d=e.ctx||null:e.available&&null!=t&&t.mirrorUpAndDown&&this.setTexBuffer($B)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),PL.clearTask(this._intervalId),this._intervalId=PL.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(PL.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof dF){let e=this.context.ctx.getError();e&&this.context.destroy(new ck({code:sk.VIDEO_MANAGER_ERROR,extraCode:5,message:"".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)}))}}),{fps:this.context.frameRate})}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];super.addInput(e,...i),this.start(this.context.frameRate)}update(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(this._intervalId&&(PL.clearTask(this._intervalId),this._intervalId=0,1===e)){this.log.info("".concat(this.name," use requestVideoFrameCallback"));let e=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",e))};document.addEventListener("visibilitychange",e)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),PL.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),PL.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},tF=class extends eF{constructor(e,t){super(e,t),zC(this,"_videoTrack"),zC(this,"_muteOb"),zC(this,"_closedOb",yV(this,"closed")),zC(this,"_subscription"),zC(this,"_canvasContainer"),Number(CO)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=yV(this._videoTrack,"mute"),GU(yV(this._videoTrack,"ended"),jV(this._closedOb),WB((()=>{this.context.destroy(new ck({code:sk.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){this._subscription=GU(this._muteOb,jV(this._closedOb),SB((e=>t=>{let i=performance.now();GU(ZB,JV((t=>t-i<e)),WV(1))(t)})(5e3)),FV((()=>{var e;return!(null==(e=this._videoTrack)||!e.muted||document.hidden)})),WB((()=>{this.context.destroy(new ck({code:sk.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))})))}disableCheckMute(){var e;null==(e=this._subscription)||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info("".concat(this.name," put canvas to body")),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack,null==(t=this._canvasContainer)||t.remove()}},iF=class extends tF{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},rF=class extends tF{constructor(e,t,i){super(e,{name:"smallDestination",logger:i}),this.resolution=t}resize(e,t){let i,r=e*t,n=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),r>n?i=r/n:(this.log.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(e," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),i=r/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},nF=class extends QB{constructor(e,t){super(e,VC({name:"imageSource"},t)),zC(this,"_lastImage"),zC(this,"_totalFrames",0),zC(this,"_autoResize",!1),zC(this,"_canvasRendered"),zC(this,"_videoCallbackId",0),zC(this,"waitingFirstFrame",!0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===NO&&(this._canvasRendered=uV(),GU(this._canvasRendered,sV(this._image),TB((e=>e instanceof HTMLCanvasElement?yV(e,"rendered"):PV())),jV(yV(this,"closed")),WB((()=>{this.update()}))))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){let e=this.image;this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),_L()&&!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!1}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)}},oF=class extends nF{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",GU(yV(this._player,ML.PLAYER_STATE_CHANGED),jV(yV(this,"closed")),FV((e=>{let{state:t}=e;return"PLAYING"===t})),WB((()=>{this.tryVideoFrameCallback()})))}get image(){return this._player.element}},sF=class extends oF{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,t,i){super(e,new hx({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()}},aF=class extends CL{constructor(e){super(),zC(this,"frameRate"),zC(this,"_canvas"),zC(this,"log"),zC(this,"hasAlpha",!1),zC(this,"name"),zC(this,"error"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new sF(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new tF(this,e)}createVideoImageSource(e,t){return new nF(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new oF(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};zC(aF,"_ids",0);var cF={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},lF=class extends aF{constructor(){super(...arguments),zC(this,"defaultProgam"),zC(this,"defaultVShader"),zC(this,"defaultFShader"),zC(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(aF._ids++)),this.ctx=this._canvas.getContext("webgl2",cF),!this.ctx)throw new ck({code:sk.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 ck({code:sk.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}))}destroy(e){let t="";return e&&(t=e.message,this.error=e,IM.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info("video context destroy".concat(t)?": ".concat(t):""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;null==(t=this.ctx)||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let i=this.ctx,r=i.createShader(e);return i.shaderSource(r,t),i.compileShader(r),r}createProgram(e,t){let i=this.ctx,r=i.createProgram();return i.attachShader(r,e),i.attachShader(r,t),i.linkProgram(r),i.getProgramParameter(r,i.LINK_STATUS)||this.log.error(i.getProgramInfoLog(r)),r}};zC(lF,"UNAVAILABLE","unavailable"),GC([AL(CL.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),IM.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),IM.addSuccessEvent({key:512700})}})],lF.prototype,"create",1),GC([AL("created",CL.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(lF.UNAVAILABLE,e),this.removeAllListeners()}})],lF.prototype,"destroy",1);var dF=lF,uF=class extends aF{constructor(){super(...arguments),zC(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(aF._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new ck({code:sk.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,IM.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(),IM.addSuccessEvent({key:512703})}};GC([AL(CL.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),IM.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),IM.addSuccessEvent({key:512701})}})],uF.prototype,"create",1),GC([AL("created",CL.INIT,{ignoreError:!0,sync:!0})],uF.prototype,"destroy",1);var hF=class extends qB{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),zC(this,"mediaType",4),zC(this,"source"),zC(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager,this.once("first-video-frame",(e=>{this.room.emit("first-video-frame",e)}))}play(e,t){return(_D(null==t?void 0:t.canvasRender)?t.canvasRender:17===NO)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then((()=>{this.player.calculateStat()}))}useCanvasPlayer(){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let e=new uF({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new eF(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),_L()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,i=function(e){return[15,30,45,60].reduce(((t,i)=>Math.abs(i-e)<Math.abs(t-e)?i:t))}(t);!fD(t)||t<=0?this.log.debug("updateCanvasPlayerFPS() ignore decoder: ".concat(t," ")):i!==e.frameRate?(this.log.info("updateCanvasPlayerFPS() decoder: ".concat(t,", closest: ").concat(i,", current: ").concat(e.frameRate)),e.frameRate=i):this.log.debug("updateCanvasPlayerFPS() ignore ClosestFPS ".concat(i," == ").concat(e.frameRate))}get decodeFPS(){var e;let{msg_video_status:t}=(null==(e=this.room.heartbeatReport)?void 0:e.msg_down_stream_info.find((e=>e.msg_user_info.str_identifier===this.userId)))||{},i=2===this.mediaType?7:this.isSmall?3:2;if(!t||0===t.length)return 0;let r=t.find((e=>e.uint32_video_stream_type===i));return(null==r?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&!(e=t({frame:e,track:this})))return;return e}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},pF=class extends hF{constructor(e,t){super(e,t,2),zC(this,"mediaType",2),zC(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},mF=new Map;function fF(e,t){let i=BC(VC({},t),{timestamp:dk()});mF.has(e)?mF.get(e).push(i):mF.set(e,[i])}eP.on(iP.JOIN_SUCCESS,(e=>{let{room:t}=e;fF(t.userId,{eventId:32788})})),eP.on(iP.LEAVE_START,(e=>{let{room:t}=e;fF(t.userId,{eventId:32789})})),eP.on(iP.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),fF(t.room.userId,{eventId:e})}})),eP.on(iP.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),fF(t.room.userId,{eventId:e})}})),eP.on(iP.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===zk.AUDIO?fF(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):fF(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),eP.on(iP.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===zk.AUDIO?fF(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):fF(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),eP.on(iP.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&fF(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&fF(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&fF(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),eP.on(iP.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&fF(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&fF(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&fF(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),eP.on(iP.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&fF(t.room.userId,{eventId:t.kind===zk.VIDEO?32780:32781})})),eP.on(iP.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&fF(t.room.userId,{eventId:t.kind===zk.VIDEO?32782:32783})})),eP.on(iP.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&&fF(i.userId,{eventId:t})})),eP.on(iP.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&&fF(i.userId,{eventId:t,remoteUserId:o})})),eP.on(iP.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"===n?0:2,d={eventId:4004,param1:c,param2:l,streamType:a||2};r&&(d.remoteUserId=r,d.eventId=4005),fF(i,d),IM.addEnum({key:r?514701:513701,value:c}),IM.addEnum({key:r?514700:513700,value:l})})),eP.on(iP.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===zk.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),fF(t.userId,e)}}));var _F=jC(JC(),1),gF=class extends _F.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,zC(this,"userMap",new Map),zC(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find((e=>e.isRobot))}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:r,role:n}=e;if(this.userMap.has(t))return;let o={userId:i,tinyId:r,role:20===n?"anchor":"audience"};this.userMap.set(t,o),this.emit("1",o)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let r="peer leave [".concat(e,"]");pD(t)||(r+=":".concat(Ww[t])),this._log.info(r);let n=this.remotePublishedUserMap.get(e);if(n){let t=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:t,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",i.userId)}setUserList(e){this.userMap.forEach((t=>{e.findIndex((e=>e[this.key]===t[this.key]))<0&&this.deleteUser(t[this.key],0)})),e.forEach((e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)}))}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach((t=>{let i=t[this.key];if(e.findIndex((e=>e[this.key]===t[this.key]))<0){this._log.info("remote [".concat(i,"] unpublish"));let e=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(i),this.emit("6",{prevMuteState:e,muteState:t.muteState,flag:0})}})),e.forEach((e=>{var t;let i=e[this.key];if(i===this.mySelfId)return;let{flag:r,userId:n,tinyId:o}=e,s=ND(r,n),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==r&&(e.flag=r,this._log.info("remote publish updated: ".concat(JSON.stringify(e.muteState))),this.emit("6",{prevMuteState:a,muteState:s,flag:r}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(s))),this.addUser({userId:n,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:ND(0,n),muteState:s,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function vF(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return aU(((e,n)=>{let o=new WeakMap;return eP.on(iP.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 ck({code:sk.INVALID_OPERATION,message:hM({key:cM.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 EF,TF=!0,yF={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"},SF={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},IF=((EF=IF||{})[EF.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",EF[EF.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",EF[EF.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",EF[EF.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",EF[EF.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",EF[EF.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",EF[EF.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",EF[EF.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",EF[EF.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",EF[EF.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",EF[EF.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",EF[EF.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",EF[EF.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",EF[EF.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",EF[EF.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",EF[EF.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",EF[EF.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",EF[EF.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",EF[EF.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",EF[EF.INVALID_OPERATION=5100]="INVALID_OPERATION",EF[EF.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",EF[EF.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",EF[EF.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",EF[EF.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",EF[EF.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",EF[EF.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",EF[EF.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",EF[EF.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",EF[EF.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",EF[EF.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",EF[EF.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",EF[EF.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",EF[EF.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",EF[EF.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",EF[EF.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",EF[EF.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",EF[EF.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",EF[EF.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",EF[EF.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",EF[EF.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",EF[EF.DEVICE_ERROR=5300]="DEVICE_ERROR",EF[EF.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",EF[EF.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",EF[EF.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",EF[EF.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",EF[EF.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",EF[EF.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",EF[EF.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",EF[EF.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",EF[EF.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",EF[EF.SERVER_ERROR=5400]="SERVER_ERROR",EF[EF.NEED_TO_BUY=5401]="NEED_TO_BUY",EF[EF.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",EF[EF.OPERATION_FAILED=5500]="OPERATION_FAILED",EF[EF.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",EF[EF.REJOIN_FAILED=5502]="REJOIN_FAILED",EF[EF.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",EF[EF.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",EF[EF.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",EF[EF.OPERATION_ABORT=5998]="OPERATION_ABORT",EF[EF.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",EF);var AF=BC(VC({},lM),{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(uD(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(uD(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,value:r}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(r,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,value:r}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(r,".")},INVALID_ELEMENT_ID(e){let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE(e){let{key:t,fnName:i,type:r}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(r,".")},INVALID_STREAM_ID(e){let{key:t}=e;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(e){let{key:t}=e;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(e){let{key:t}=e;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(e){let{fnName:t}=e;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(e){let{fnName:t}=e;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing ").concat(i.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(e){let{fnName:t}=e;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the microphone is not turned on.")},INVALID_BUFFER_EMPTY:e=>{let{key:t}=e;return"the buffer size of paramerter '".concat(t,"' cannot be empty")},INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:e=>{let{fnName:t}=e;return"you need to call ".concat(t,"() after publish stream.")},ENV_NOT_SUPPORTED(e){let{fnName:t}=e;return"the current browser does not support the capability of the function '".concat(t,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(e){let{fnName:t}=e;return"cannot call ".concat(t," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got device exception").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:i=bF(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=bF(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=bF(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=bF(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=bF(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=bF(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=bF(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 bF(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var RF=class e extends Error{constructor(e){let{code:t,extraCode:i,message:r="",messageParams:n,fnName:o="",originError:s}=e;var a;let c;c=r||function(e){let t,{code:i,params:r,enableDocLink:n=!1}=e,s="",a=IF[i];try{t=AF[a]}catch(o){t=AF.UNKNOWN_ERROR}return hD(t)?s=t(r):mD(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===SF.SERVER_ERROR?t:i||t,params:VC({fnName:o,error:s},n)}),super(c),zC(this,"name","RtcError"),zC(this,"code"),zC(this,"extraCode"),zC(this,"functionName"),zC(this,"message"),zC(this,"handler"),zC(this,"originError"),this.name=IF[t],this.code=t,this.extraCode=i,this.functionName=o,this.originError=s,this.message=c,5302===this.extraCode&&null!=(a=this.originError)&&a.message.includes("system")&&(this.handler=()=>{let e=document.createElement("a");ZN?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):$N&&(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 ck){let{stack:o}=t,s={code:SF.UNKNOWN_ERROR,fnName:i,originError:t};switch(t.getCode()){case sk.INVALID_PARAMETER:s.code=SF.INVALID_PARAMETER,s.message=t.message;break;case sk.INVALID_OPERATION:s.code=SF.INVALID_OPERATION;break;case sk.NOT_SUPPORTED:case sk.NOT_SUPPORTED_H264:s.code=SF.ENV_NOT_SUPPORTED,t.getCode()===sk.NOT_SUPPORTED_H264&&(s.extraCode=t.message.includes(lM.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case sk.JOIN_ROOM_FAILED:s.messageParams={fnParams:r};case sk.SERVER_TIMEOUT:case sk.SWITCH_ROLE_FAILED:s.code=SF.SERVER_ERROR,s.extraCode=t.getExtraCode();break;case sk.API_CALL_ABORTED:s.code=SF.OPERATION_ABORT;break;case sk.DEVICE_NOT_FOUND:case sk.DEVICE_AUTO_RECOVER_FAILED:case sk.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 sk.UNKNOWN:break;default:s.code=SF.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:SF.UNKNOWN_ERROR,fnName:i,originError:t})}return n}};var CF=RF,kF={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},wF={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}}},DF={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(mD(e)&&!document.getElementById(e))throw new CF({code:SF.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},NF={name:"userId",required:!0,type:"string"},OF={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[yF.AUDIO_PROFILE_STANDARD,yF.AUDIO_PROFILE_STANDARD_STEREO,yF.AUDIO_PROFILE_HIGH,yF.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function PF(e,t){if(!e)throw new CF({code:SF.INVALID_OPERATION,extraCode:5101,fnName:t})}function MF(e,t,i){if(!e)throw new CF({code:SF.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var LF={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(e,t,i){if(this._room.isJoined)throw new CF({code:SF.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(mD(e.roomId))throw new CF({code:SF.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new CF({code:SF.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new CF({code:SF.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new CF({code:SF.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}})}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},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:DF,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:kF},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&NM())throw new CF({code:SF.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:BC(VC({},DF),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:kF}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:OF},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&NM())throw new CF({code:SF.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:OF}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:DF,publish:{type:"boolean"},option:wF},validate(e,t,i,r,n){var o;if(null==(o=null==e?void 0:e.option)||!o.videoTrack){if(NM())throw new CF({code:SF.ENV_NOT_SUPPORTED,extraCode:5201});if(!UM())throw new CF({code:SF.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:DF,publish:{type:"boolean"},option:wF}},muteRemoteAudio:[NF,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[NF,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:DF,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(e,t,i){PF(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(MF(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new CF({code:SF.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:BC(VC({},DF),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(e,t,i){PF(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(MF(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new CF({code:SF.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(e,t,i){if("*"!==e.userId&&pD(e.streamType))throw new CF({code:SF.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){PF(this._room.isJoining||this._room.isJoined,i)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(e,t,i,r){if(!aL)throw new CF({code:SF.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new CF({code:SF.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new CF({code:SF.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new CF({code:SF.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});PF(this._room.isJoined,i)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(e,t,i){if(!e&&!this._room.isMainStreamPublished||e&&!this._room.isAuxStreamPublished)throw new CF({code:SF.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:i})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(e,t,i,r){if(e.byteLength>1e3)throw new CF({code:SF.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new CF({code:SF.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(PF(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new CF({code:SF.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}}},xF={TRTC:LF},UF=class extends Error{};function VF(e,t){let i=LD(e);for(let r=0;r<t.length;r++)MD(i[r],t[r]);return i}function BF(e){this._resolve=Promise.resolve(e)}function FF(e){this._reject=Promise.reject(e)}var HF=class e{constructor(t,i){this.instance=t,this.group=i,zC(this,"started",!1),zC(this,"ops",[]),zC(this,"startSame",(()=>!0)),zC(this,"mergeUpdate",VF);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 UF("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:BF,reject:FF};try{switch(this.state){case 1:if(0===e)throw new UF("already started");break;case 4:if(2===e)throw new UF("not started");break;default:return this.cacheOp(o)}}catch(mP){return Promise.reject(mP)}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 UF("already start");break;case 3:switch(e.type){case 2:throw new UF("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new UF("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new UF("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 UF("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new UF("start not allowed after update");case 0:throw new UF("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new UF("keep start")),new UF("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}};zC(HF,"instances",new WeakMap);var WF=HF,jF=new WeakMap,GF=(e,t)=>{if(t instanceof UF){let{stack:i}=t;t=new CF({code:SF.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function zF(e,t){return aU(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let a=WF.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(GF.bind(null,r))):i.apply(this,o)}))}function KF(e,t){let{merge:i,debounce:r}=t||{};return aU(((t,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=WF.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=jF.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(GF.bind(null,n)).then(r,o)}),e);jF.has(this)?null==(l=jF.get(this))||l.set(i(...s),{timeoutId:u,resolve:r}):jF.set(this,new Map([[i(...s),{timeoutId:u,resolve:r}]]))}))}return c.action(2,t.bind(this),s).catch(GF.bind(null,n))}))}function qF(e){return aU(((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(WF.gets(this,s).map((e=>e.action(3,(()=>Promise.resolve()),n)))).then((()=>t.call(this,...n)));let a=WF.get(this,s);return a?a.action(3,t.bind(this),n).catch(GF.bind(null,i)):t.apply(this,n)}))}var JF={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame"},YF=new Set([JF.ERROR,JF.AUTOPLAY_FAILED,JF.KICKED_OUT,JF.REMOTE_USER_ENTER,JF.REMOTE_USER_EXIT,JF.REMOTE_AUDIO_AVAILABLE,JF.REMOTE_AUDIO_UNAVAILABLE,JF.REMOTE_VIDEO_AVAILABLE,JF.REMOTE_VIDEO_UNAVAILABLE,JF.CONNECTION_STATE_CHANGED,JF.PUBLISH_STATE_CHANGED,JF.SCREEN_SHARE_STOPPED,JF.DEVICE_CHANGED,JF.FIRST_VIDEO_FRAME]);function XF(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function QF(e){return e===yF.QOS_PREFERENCE_CLEAR?"detail":e===yF.QOS_PREFERENCE_SMOOTH?"motion":""}var ZF={};WC(ZF,{bytes2ms:()=>iD,convertObjectNumberToInt:()=>zD,copyProperties:()=>tD,deepClone:()=>LD,deepMerge:()=>MD,delay:()=>KD,fibonacci:()=>lD,formatedTime:()=>VD,getConstructorName:()=>ID,getContainerFromElement:()=>UD,getEnv:()=>qw,getInternalVersion:()=>kD,getLoggerUrl:()=>Yw,getMediaStreamTrackInfo:()=>YD,getMuteStateFromFlag:()=>ND,getNetworkType:()=>Qw,getNumNetworkType:()=>eD,getReconnectionTimeout:()=>dD,getStringByteLength:()=>HD,getTurnServer:()=>OD,getUint32Version:()=>GD,getValueType:()=>uD,getViewListFromView:()=>xD,glog:()=>sD,ipv4ToUint32:()=>PD,isArray:()=>vD,isAudioWorkletSupported:()=>AD,isBoolean:()=>_D,isConstructor:()=>SD,isEmpty:()=>DD,isFunction:()=>hD,isLangChinese:()=>aD,isMediaStreamTrack:()=>ED,isNumber:()=>fD,isObject:()=>gD,isOverseaSdkAppId:()=>Jw,isPlainObject:()=>cD,isPortrait:()=>WD,isPromise:()=>yD,isRemoteTrack:()=>TD,isString:()=>mD,isUndefined:()=>pD,loadImage:()=>jD,ms2bytes:()=>nD,ms2samples:()=>oD,normalizeUrl:()=>JD,performanceNow:()=>RD,promiseAny:()=>bD,samples2ms:()=>rD,setNetworkType:()=>$w,stringify:()=>BD,stringifyIncludeValue:()=>FD,throttlePromise:()=>qD});var $F={};WC($F,{ScheduleRequestType:()=>sH,getAbilityConfig:()=>cH,getScheduleDomain:()=>lH,isNeedToSchedule:()=>tH,scheduleProxy:()=>nH,sendScheduleRequest:()=>rH,setIsNeedToSchedule:()=>iH,setScheduleProxy:()=>oH});var eH=null,tH=!0;function iH(e){_D(e)&&e!==tH&&(tH=e,nP.info("setIsNeedToSchedule ".concat(e)))}function rH(e){return qC(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:n,userSig:o,version:s,frameWorkType:a,role:c,latencyLevel:l}=e;return function*(){if(!tH&&eH)return{isCached:!0,result:eH};let e={delta:0,count:[1,1],msg:[],detail:[]};try{let d=new FormData;d.append("userId",String(t)),d.append("sdkAppId",String(i)),d.append("isStrGroupId",String(r)),d.append("groupId",String(n)),d.append("sdkVersion",s),d.append("userSig",String(o));let u=yield GO();null!=u&&u.model&&d.append("model",String(null==u?void 0:u.model)),c&&d.append("role",String(c)),l&&d.append("latencyLevel",String(l)),a&&d.append("frameWorkType",String(a));let h=RD(),p=yield function(e,t,i){return new Promise(((r,n)=>{let o=null;bD([uH((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]=aH(i,"config",zk.MAIN,!0)),n())}))(aH(i,"config",zk.MAIN),e,{get timeout(){return 1e3*lD(2+t.count[0])}}),uH((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]=aH(i,"config",zk.BACKUP,!0)),n())}))(aH(i,"config",zk.BACKUP),e,{get timeout(){return 1e3*lD(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}(d,e,i);p.config&&(p.config.loggerDomain&&Ak(p.config.loggerDomain),_D(p.config.scheduleCache)&&iH(!p.config.scheduleCache)),e.delta=RD()-h;let m=function(e,t,i){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let n=performance.getEntriesByType("resource"),o=aH(e,"config",zk.MAIN),s=aH(e,"config",zk.BACKUP);for(let e of n)if(e.startTime>=i&&(e.name===o||e.name===s)&&e.transferSize>0){let i=e.name===o?zk.MAIN:zk.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];BL.uploadEvent({log:"stat-schedule-net:".concat(n,"(").concat(s,"(").concat(a,"->").concat(c,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=BC(VC({},r),{totalCost:n,local:s,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(o){nP.error("getScheduleDetailCost error",o)}return r}(Number(i),t,h);return eH=p,{isCached:!1,result:p,detailCost:m}}catch(d){let e=vD(d)?d[0]:d,t=fD(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),r=new ck({code:sk.SCHEDULE_FAILED,extraCode:t,message:hM({key:cM.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw nP.error(i,t),r}}()}))}"undefined"!=typeof document&&document.head.insertAdjacentHTML("beforeend",Object.values(Mw).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),eP.on("28",(()=>iH(!0))),eP.on("63",(()=>iH(!0))),eP.on("84",(()=>iH(!0))),eP.on("201",(e=>{"RECONNECTING"===e.state&&iH(!0)})),eP.on("202",(e=>{"RECONNECTING"===e.state&&iH(!0)}));var nH={main:"",backup:""};function oH(e){vD(e)?(nH.main=e[0],nH.backup=e[1]):nH.main=e}var sH=(e=>(e.CONFIG="config",e.TRTC_AUTO_CONF="trtcAutoConf",e.AUDIO_AI_AUTH="audioAiAuth",e))(sH||{});function aH(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:zk.MAIN,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return"https://".concat(nH[i]||lH(e,i,r),"/api/v1/").concat(t)}function cH(e,t,i){let r=aH(e,t),n=aH(e,t,zk.BACKUP),o=new URLSearchParams(i).toString();return bD([fetch("".concat(r,"?").concat(o)).then((e=>e.json())),fetch("".concat(n,"?").concat(o)).then((e=>e.json()))])}function lH(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:zk.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=Jw(e)?r?i===zk.MAIN?Mw.MAIN_OVERSEA_BACKUP:Mw.BACKUP_OVERSEA:i===zk.MAIN?Mw.MAIN_OVERSEA:Mw.BACKUP_OVERSEA:i===zk.MAIN?Mw.MAIN:Mw.BACKUP,t}function dH(e,t,i){return new Promise(((r,n)=>{XD({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 uH=(e,t)=>nN({retryFunction:dH,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var hH=class{constructor(){zC(this,"_log"),this._log=nP.createLogger({id:"fd"})}download(e,t){return qC(this,null,(function*(){let{type:i="blob"}=t||{};e=JD(e);try{let t,r=RD();if(t=hD(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let n=RD()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(n,"ms")),IM.addSuccessEvent({key:522700,cost:RD()-r}),t.data}catch(pP){throw this._log.error("failed to download: ".concat(e,", error: ").concat(pP)),IM.addFailedEvent({key:522700,error:pP}),pP}}))}downloadWithFetch(e,t){return qC(this,null,(function*(){this._log.info("download with fetch: ".concat(e,", return type: ").concat(t));try{let i,r=yield fetch(e);if(!r.ok)throw new Error("network response was not ok");return i="arraybuffer"===t?yield r.arrayBuffer():yield r.blob(),{data:i}}catch(Ew){throw Ew}}))}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType=t,n.onload=()=>{200===n.status||0===n.status&&n.response?i({data:n.response}):r(new Error("XHR failed"))},n.onerror=r,n.send(null)}))}loadWasm(e,t){return qC(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=RD(),r=null,n=null;if(hD(WebAssembly.instantiateStreaming)&&!(e=>e.startsWith("data:application/octet-stream;base64,"))(e)&&!(e=>e.startsWith("file://"))(e)&&hD(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(Ek){n=Ek}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(Ek){n=Ek}if(r){let t=RD()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),IM.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),IM.addFailedEvent({key:522701,error:n}),n}))}};GC([HL({settings:{timeout:0,retries:3},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],hH.prototype,"download",1);var pH=new hH;function mH(e){let{TRTC:t,room:i,errorModule:r,assetsPath:n}=e;return{TRTC:t,room:i,assetsPath:n,fileDownloader:pH,innerEmitter:eP,constants:mk,environment:sN,utils:ZF,eventLogger:BL,log:this.room.getLogger(),loggerManager:nP,errorModule:r,kvStatManager:IM,rtcDectection:aP,trtc:this,rx:PU,enums:cP,schedule:$F,clearStarted:(e,t)=>{let i=e.getAlias(),r=WF.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:DU,createAudioNode:Cx}}var fH=new WeakMap;function _H(e,t){return aU(((i,r)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let s=fH.get(this);s||(s=new Map,fH.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=fH.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=fH.get(this))||e.delete(a)}),e);s.set(a,t)}}))}function gH(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return aU(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{EH.call(this,t,n,i,this._name)}catch(pP){return Promise.reject(pP)}return e.apply(this,n)}))}function vH(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return aU(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{EH.call(this,t,n,i,this._name)}catch(pP){throw pP}return e.apply(this,n)}))}function EH(e,t,i,r){if(vD(e))for(let n=0;n<e.length;n++)TH.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else TH.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function TH(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function s(e){return{code:SF.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(pD(i)){if(t.required)throw new CF(s(5001));if(pD(t.defaultValue))return void(hD(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),hD(t.type[r])&&i instanceof t.type[r]&&(e=!0),mD(t.type[r])&&uD(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new CF({code:SF.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>SD(e)?ID(e):mD(e)?e:uD(e)))},value:i}})}else if(!pD(t.type)&&uD(i)!==t.type)throw new CF(s(5002));if(!1===t.allowEmpty){let e=fD(i)&&(0===i||Number.isNaN(i)),t=mD(i)&&""===i.trim();if(e||t)throw new CF(s(5003))}if(t.notLessThanZero&&fD(i)&&i<0)throw new CF(s(5006));if(!pD(t.min)&&fD(i)&&i<t.min)throw new CF(s(5007));if(!pD(t.max)&&fD(i)&&i>t.max)throw new CF(s(5008));if(mD(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new CF(s(5004))}else if(hD(t.instanceOf)&&!(i instanceof t.instanceOf))throw new CF(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new CF(s(5005));let{properties:a}=t;cD(a)&&gD(i)&&Object.keys(a).forEach((e=>{TH.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;cD(c)&&vD(i)&&i.forEach(((e,t)=>{TH.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),hD(t.validate)&&t.validate.call(this,i,r,n,o,this)}function yH(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r,ignoreLog:n}=e;return aU(((e,o)=>function(){for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];var l;function d(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...a);if(a[e.argIndex]===t)return e.value}if(t===a||e in a)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(uD(t)):t instanceof MediaStreamTrack?YD(t):(JSON.stringify(t),t)}catch(vP){return"type:".concat(uD(t))}}let u=this._log||nP;if(null!=n&&n(...a))return e.apply(this,a);a.length>0?u.info("".concat(o,"() ").concat(JSON.stringify(a,((e,t)=>d(e,t,["userSig","privateMapKey"]))))):u.info("".concat(o,"()"));let h=r?r(...a):gM[o];try{let i=e.apply(this,a),r=RD();return yD(i)?i.then((e=>(u.info("".concat(o,"() success ").concat(t.call(this,...a))),IM.addSuccessEvent({key:h,cost:RD()-r}),e))).catch((e=>{var i;let r=(e=CF.convertFrom.call(this,e,o,1===a.length?a[0]:a)).extraCode||e.code,n=null!=(i=e.message)&&i.includes(r)?"":" code:".concat(r);throw u.error("".concat(o,"() failed ").concat(t.call(this,...a)," ").concat(e).concat(n," params: ").concat(JSON.stringify(a,d))),IM.addFailedEvent({key:h,error:e}),e})):(IM.addSuccessEvent({key:h}),i)}catch(lP){let t=(lP=CF.convertFrom.call(this,lP,o)).extraCode||lP.code,i=null!=(l=lP.message)&&l.includes(t)?"":" code:".concat(t);throw u.error("".concat(o,"() failed ").concat(lP).concat(i," params: ").concat(JSON.stringify(a,d))),IM.addFailedEvent({key:h,error:lP}),lP}}))}var SH,IH=e=>aU(((t,i)=>function(r,n){return qC(this,null,(function*(){let o=this._plugins.get(r);if(!o)throw this._log.error("plugin ".concat(String(r)," is not found")),new CF({code:SF.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(hD(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new CF({code:SF.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return EH.call(this,o.getValidateRule(e),[n],i,"TRTC"),t.call(this,o,n)}))})),AH=0,bH=class e{constructor(e){this.core=e,zC(this,"log"),zC(this,"customAudioReferenceMap",new Map),zC(this,"audioRefId",0),zC(this,"audioContext",Tx()),zC(this,"localAudioWorkletNode"),zC(this,"screenAudioWorkletNode"),zC(this,"mixNode"),zC(this,"mixNodeConnector"),zC(this,"muteNode"),zC(this,"muteNodeConnector"),AH+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(AH)}),this.log.info("created id=".concat(this.getAlias()).concat(AH)),e.assetsPath&&this.preload("".concat(e.assetsPath,"/audioProcessor-wasm.js"))}static startValidateRule(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,i,r){}}}preload(e){return SH||(SH=this.doPreload(e)),SH}doPreload(e){return qC(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield px(this.audioContext,i)}catch(pP){this.log.error("preload audioProcessor failed. ".concat(pP))}finally{URL.revokeObjectURL(i)}}))}getName(){return e.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return e.startValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return qC(this,null,(function*(){let{room:t}=this.core,{sdkAppId:i,userId:r,assetsPath:n,audioReference:o,processLevel:s,enableDump:a,isLocalAudioNeedAudioProcess:c=!0,isScreenAudioNeedAudioProcess:l=!0}=e;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=c,this.core.room.audioManager.isScreenAudioNeedAudioProcess=l,yield this.preload("".concat(n,"/audioProcessor-wasm.js")),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let n=String(Date.now()).slice(0,-3),{auth:o,sign:s,status:a,message:c}=yield function(e){return qC(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]:zk.MAIN;return"https://".concat(nH[t]||lH(e,t),"/api/v1/audioAiAuth")}(t),"?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(r,"&timestamp=").concat(n),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d=Jw(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)}}()}))}(BC(VC({},e),{timestamp:n}));if(!o)throw this.log.info("audioProcessor: ".concat(r," auth result: ").concat(o,". Message: ").concat(c)),new CF({code:SF.INVALID_PARAMETER,message:c});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.localAudioWorkletNode.port.postMessage({type:"init",data:{sdkAppId:String(i),userId:r,timestamp:n,sign:s,status:a}}),this.localAudioWorkletNode.port.onmessage=e=>{var i;let{data:r}=e;switch(r.type){case"cost":let e=(null==r?void 0:r.value)>20?"warn":(null==r?void 0:r.value)>10?"info":"debug";return void this.log[e]("avg cost: ".concat(r.value," max: ").concat(null==r?void 0:r.max,"(").concat(hk(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(r.value));case"dump":return void eP.emit("265",{room:t,data:r.value,type:"dump"})}},this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.screenAudioWorkletNode.port.postMessage({type:"init",data:{sdkAppId:String(i),userId:r,timestamp:n,sign:s,status:a}}),this.screenAudioWorkletNode.port.onmessage=e=>{var i;let{data:r}=e;switch(r.type){case"cost":let e=(null==r?void 0:r.value)>20?"warn":(null==r?void 0:r.value)>10?"info":"debug";return void this.log[e]("[dump-screen-audio] avg cost: ".concat(r.value," max: ").concat(null==r?void 0:r.max,"(").concat(hk(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]("[dump-screen-audio] ".concat(r.value));case"dump":return void eP.emit("265",{room:t,data:r.value,type:"dump-screen-audio"})}}}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.muteNode||(this.muteNode=this.audioContext.createConstantSource(),this.muteNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.muteNode.start()),this.localAudioWorkletNode.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),t.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.muteNode,this.screenAudioWorkletNode),pD(o)||o.forEach((e=>{this.customAudioReferenceMap.set(e,"o-".concat(this.audioRefId++)),eP.emit("266",{room:this.core.room,type:"add",audioReference:e,refId:"o-".concat(this.audioRefId++)})})),pD(s)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:s}}),pD(a)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:a}})}))}update(e){return qC(this,null,(function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:t,enableDump:i,processLevel:r}=e;pD(t)||(this.customAudioReferenceMap.forEach(((e,t)=>{this.customAudioReferenceMap.delete(t),eP.emit("266",{room:this.core.room,type:"remove",refId:e})})),t.forEach((e=>{this.customAudioReferenceMap.set(e,"o-".concat(this.audioRefId++)),eP.emit("266",{room:this.core.room,type:"add",audioReference:e,refId:"o-".concat(this.audioRefId++)})}))),pD(r)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),pD(i)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:i}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:i}}))}))}stop(){return qC(this,null,(function*(){if(!(this.localAudioWorkletNode&&this.mixNode&&this.muteNode&&this.screenAudioWorkletNode))return;let{room:e}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.muteNode,this.screenAudioWorkletNode)}))}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}};zC(bH,"updateValidateRule",{type:"object"}),zC(bH,"stopValidateRule",{type:"object"}),zC(bH,"Name","AudioProcessor");var RH=bH;var CH=0,kH=class{constructor(e,t){zC(this,"player"),zC(this,"publisher"),zC(this,"mixInput"),this.mixInput=new Ax(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&&(pD(e.volume)||(this.volume=e.volume),pD(e.loop)||(this.loop=e.loop),pD(e.playbackRate)||(this.playbackRate=e.playbackRate))}updateListener(e){if(this.player){if(e.onDurationChange){let{onDurationChange:t}=e;this.player.ondurationchange=e=>{t(e.target.duration)}}if(e.onTimeUpdate){let t=e.onTimeUpdate,{player:i}=this;i.ontimeupdate=()=>{t(i.currentTime,i.duration)}}e.onEnded&&(this.player.onended=e.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(e){this.player&&(e<0&&e>this.player.duration||(this.player.currentTime=e,this.publisher.currentTime=e))}play(){var e,t;return null==(e=this.publisher)||e.play(),null==(t=this.player)?void 0:t.play()}pause(){var e,t;null==(e=this.player)||e.pause(),null==(t=this.publisher)||t.pause()}stop(){var e;null==(e=this.player)||e.pause(),this.mixInput.disconnect()}setOperation(e){"pause"===e&&this.pause(),"resume"===e&&(this.pause(),this.play()),"stop"===e&&(this.pause(),this.seek(0))}set volume(e){!this.player||!this.publisher||(this.player.volume=e,this.publisher.volume=e)}set loop(e){!this.player||!this.publisher||(this.player.loop=e,this.publisher.loop=e)}set playbackRate(e){!this.player||!this.publisher||(this.player.playbackRate=e,this.publisher.playbackRate=e)}};function wH(e,t){if(t&&"function"!=typeof t)throw new CF({code:SF.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var DH=class e{constructor(e){this.core=e,zC(this,"log"),zC(this,"mixedMusicMap",new Map),zC(this,"cacheMusicMap",new Map),CH+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(CH)}),this.log.info("created id=".concat(this.getAlias()).concat(CH))}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 qC(this,null,(function*(){let{room:t}=this.core;this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:i,url:r}=e;if(this.mixedMusicMap.has(i))return;let n=this.cacheMusicMap.get(i);n?e.url?n.reset():(n.mixInput.replaceSource(e.track),n.mixInput.connect()):(n=new kH(e,t.audioManager),this.cacheMusicMap.set(i,n)),n.updateListener(e),n.updateSettings(e),yield n.play(),this.mixedMusicMap.set(i,n),n.mixInput.source.node&&eP.emit("266",{room:this.core.room,type:"add",audioReference:n.mixInput.source.node,refId:"ax-".concat(i)}),this.log.info("start mix audio track ".concat(i," success.")),IM.addEnum({key:502700,value:3}),this.kvUpload(e)}))}update(e){return qC(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),pD(i)||o.setOperation(i),pD(r)||o.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return qC(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&&eP.emit("266",{room:t.core.room,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&&IM.addCount({key:502711}),i&&IM.addCount({key:502703}),r&&IM.addCount({key:502704}),n&&IM.addCount({key:502705}),o&&IM.addCount({key:502706}),s&&IM.addCount({key:502707}),"function"!=typeof a&&IM.addCount({key:502709}),"function"!=typeof l&&IM.addCount({key:502710}),"function"!=typeof c&&IM.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>{null!=e&&e.mixInput.track&&eP.emit("266",{room:this.core.room,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()}};zC(DH,"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 CF({code:SF.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new CF({code:SF.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});wH("onTimeUpdate",e.onTimeUpdate),wH("onEnded",e.onEnded),wH("onDurationChange",e.onDurationChange)}}),zC(DH,"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){wH("onTimeUpdate",e.onTimeUpdate),wH("onEnded",e.onEnded),wH("onDurationChange",e.onDurationChange)}}),zC(DH,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),zC(DH,"Name","AudioMixer");var NH,OH=DH,PH=0,MH=class e{constructor(e){this.core=e,zC(this,"log"),zC(this,"audioContext",Tx()),zC(this,"workletNode"),PH+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(PH)}),this.log.info("created id=".concat(this.getAlias()).concat(PH)),e.assetsPath&&this.preload("".concat(e.assetsPath,"/denoiser-wasm.js")).catch((e=>{}))}static startValidateRule(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(t,i,r,n){if(!e.room.audioManager.hasAudioTrack)throw new CF({code:SF.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return NH||(NH=this.doPreload(e)),NH}doPreload(e){return qC(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield px(this.audioContext,i)}catch(pP){throw this.log.error("load worklet failed",pP),pP}finally{URL.revokeObjectURL(i)}}))}getName(){return e.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(t){switch(t){case"start":return e.startValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return qC(this,null,(function*(){let{room:t,schedule:i}=this.core;if(yield this.preload("".concat(e.assetsPath,"/denoiser-wasm.js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:n,status:o,message:s}=yield function(e,t){return qC(this,arguments,(function(e,t){let{sdkAppId:i,userId:r,userSig:n,timestamp:s}=t;return function*(){try{let{data:{errCode:t,errMsg:o,sign:a,status:c}}=yield e.getAbilityConfig(i,e.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:r,userSig:n,timestamp:s});if("1"===c)return{auth:!0,sign:a,status:c,message:o};let l="Init RTCAIDenoiser failed.",d="";switch(t){case 1:d="Please check your params.";break;case 2:d="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:d="Server is invalid. Please contact our engineer. ";break;case 4:d="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:d="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:d="Your version is not supported."}return{auth:!1,status:c,message:o?"".concat(l," Reason: ").concat(o,". ").concat(d):"".concat(l,", ").concat(d)}}catch(o){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(o)}}}()}))}(i,BC(VC({},e),{timestamp:t}));if(!r)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(r,". Message: ").concat(s)),new CF({code:SF.INVALID_PARAMETER,message:s});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(e.sdkAppId),userId:e.userId,timestamp:t,sign: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(hk(new Date(null==i?void 0:i.maxCostTimestamp)),") hist: ").concat(null==(t=null==i?void 0:i.hist)?void 0:t.join(" ")))}else"log"===i.type&&this.log[i.logLevel]("".concat(i.value))}}this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})}))}update(){return qC(this,null,(function*(){}))}stop(){return qC(this,null,(function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)}))}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};zC(MH,"updateValidateRule",{type:"object"}),zC(MH,"stopValidateRule",{type:"object"}),zC(MH,"Name","AIDenoiser");var LH=MH;var xH=jC(JC(),1),UH=class extends xH.EventEmitter{constructor(){super(),zC(this,"observer"),zC(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 qC(this,null,(function*(){if(!this.observer)try{"PressureObserver"in window&&!vN&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(vk){BL.uploadEvent({log:"stat-pressure-detector-start-failed",error:vk})}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&nP.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(Ew){BL.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:Ew})}}},VH=new UH;function BH(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 yU(new DataView(new Uint8Array(s).buffer),!0)}function FH(e){return"empty"===e.type||0===e.data.byteLength}function HH(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}function WH(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 jH(e){let{frame:t,seiMessageList:i}=e;if(!i||0===i.length||0===t.data.byteLength)return t;let r=9-WH(t.data);if(r<=0)return t;let n=i.splice(0,r).reverse().map(BH),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 GH(e){let{frame:t,onSEI:i}=e;try{let e=new DataView(t.data);if(FH(t)||!HH(e))return t;let r=[],n=0,o=-1,s=-1;for(let i=0;i<t.data.byteLength;i++){let a=e.getUint8(i);if(0===a)n++;else if(1===a){if(2===n||3===n){let a=i-n;if(-1===o?o=a:-1===s&&(s=a,r.push(new yU(new DataView(e.buffer.slice(o,s)))),o=a,s=-1),6!==e.getUint8(i+1)){t.data=e.buffer.slice(a);break}}n=0}else n=0}null==i||i(r.reverse())}catch(vk){}return t}var zH=0,KH=class e{constructor(e){this.core=e,zC(this,"log"),zC(this,"_seiMessageList",[]),zC(this,"_smallSeiMessageList",[]),zC(this,"_subStreamSeiMessageList",[]),zH++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(zH)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(zH)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:t,mediaType:i}=e;try{return jH({frame:t,seiMessageList:8===i?this._smallSeiMessageList:2===i?this._subStreamSeiMessageList:this._seiMessageList})}catch(Ew){this.log.warn(Ew)}return t}decode(e){let{frame:t,track:i}=e;return GH({frame:t,onSEI:e=>{e.forEach((e=>{this.core.trtc.emit(JF.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:i.userId,streamType:2===i.mediaType?"sub":"main"})}))}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:oL?this.encode:jH,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:oL?this.decode:GH,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"}};zC(KH,"autoStart",!0),zC(KH,"Name","SEI");var qH=KH;function JH(e){let{frame:t,onDump:i}=e;return null==i||i(),t}function YH(e){let{frame:t,onDump:i}=e;return null==i||i(),t}var XH="Log",QH="Network",ZH="Dump",$H="Dumping",eW="End",tW="Upload Log",iW="Export Log",rW="Hide",nW="goBottom",oW="backTop",sW="Clear Log",aW="Uplink",cW="Downlink",lW="No Data",dW="Basic",uW="Duration",hW="Video",pW="Audio",mW="Screen",fW={"play() error: NotAllowedError:":{tips:e=>e.includes("main <video>")||e.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:e=>e.includes("↓")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:e=>e.includes("↓")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:"The remote stream audio playback is paused, which usually has two possibilities:\n 1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.\n 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.",color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:"The remote stream video playback is paused, which usually has two possibilities:\n 1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.\n 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.",color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach((e=>{fW["".concat(e,"()")]={tips:"Call trtc.".concat(e),color:"blue",class:"blue",textColor:"#fff"}}));var _W=Object.keys(fW),gW=jC($C()),vW="trtc_debug_dialog",EW="".concat(vW,"_activated"),TW="".concat(vW,"_switch"),yW="".concat(vW,"_mask"),SW="".concat(vW,"_panel"),IW="".concat(vW,"_tabber"),AW="".concat(vW,"_tab"),bW="".concat(vW,"_topbar"),RW="".concat(vW,"_toptab"),CW="".concat(vW,"_content"),kW="".concat(vW,"_has_topbar"),wW="".concat(CW,"_log"),DW="".concat(CW,"_network"),NW="".concat(vW,"_dump"),OW="".concat(DW,"_title"),PW="".concat(DW,"_basic"),MW="".concat(DW,"_local"),LW="".concat(DW,"_remote"),xW="".concat(NW,"_title"),UW="".concat(NW,"_local"),VW="".concat(NW,"_remote"),BW="".concat(VW,"_hook"),FW="".concat(vW,"_banner"),HW="".concat(FW,"_item"),WW="".concat(vW,"_toolbar"),jW="".concat(vW,"_tool"),GW="".concat(vW,"_item"),zW="".concat(GW,"_debug"),KW="".concat(GW,"_info"),qW="".concat(GW,"_warn"),JW="".concat(GW,"_error"),YW="".concat(vW,"_back_top"),XW="".concat(vW,"_go_bottom"),QW="".concat(NW,"_local_audio"),ZW="".concat(NW,"_local_video_main"),$W="".concat(NW,"_local_video_aux"),ej="".concat(vW,"_tooltip"),tj="".concat(PW,"_network_info"),ij="".concat(PW,"_room_info"),rj="".concat(wW,"_controller"),nj="success",oj="warning",sj="failed",aj=0,cj=class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}),this.addStyle(),this.addDialog()}addDialog(){var e;let t=document.createElement("template");t.innerHTML='<div id="'.concat(vW,'" class="').concat(vW,'"><div class="').concat(TW,'">Debug#').concat(++aj,'</div><div class="').concat(yW,'"></div><div class="').concat(SW,'"><div class="').concat(IW,'"><a class="').concat(AW," ").concat(EW,'" data-tab="log">').concat(XH,'</a><a class="').concat(AW,'" data-tab="network">').concat(QH,'</a><a class="').concat(AW,'" data-tab="dump">').concat(ZH,'</a></div><div class="').concat(rj,'"><div data-type="back_top">').concat(oW,'</div><div data-type="go_bottom">').concat(nW,'</div><div data-type="clear_log">').concat(sW,'</div></div><div class="').concat(bW,'"><a class="').concat(RW," ").concat(EW,'" data-type="all">All</a><a class="').concat(RW,'" data-type="debug">Debug</a><a class="').concat(RW,'" data-type="info">Info</a><a class="').concat(RW,'" data-type="warn">Warn</a><a class="').concat(RW,'" data-type="error">Error</a></div><div class="').concat(CW," ").concat(kW,'"><div class="').concat(wW,'"></div><div class="').concat(DW,'"><div class="').concat(OW,'">').concat(dW,'</div><div class="').concat(PW,'"><div class="').concat(ij,'"></div><div class="').concat(tj,'">').concat(lW,'</div></div><div class="').concat(OW,'">').concat(aW,'</div><div class="').concat(MW,'">').concat(lW,'</div><div class="').concat(OW,'">').concat(cW,'</div><div class="').concat(LW,'">').concat(lW,'</div></div><div class="').concat(NW,'"><div class="').concat(xW,'">').concat(aW,'</div><div class="').concat(UW,'"><div id="').concat(QW,'"><span>').concat(pW," - ").concat(uW,'(s):</span><input type="number" min=0 value=0></input><button class="dump">').concat(ZH,'</button><button class="end-dump" disabled>').concat(eW,'</button></div><div id="').concat(ZW,'"><span>').concat(hW," - ").concat(uW,'(s):</span><input type="number" min=0 value=10></input><button class="dump">').concat(ZH,'</button><button class="end-dump" disabled>').concat(eW,'</button></div><div id="').concat($W,'"><span>').concat(mW," - ").concat(uW,'(s):</span><input type="number" min=0 value=10></input><button class="dump">').concat(ZH,'</button><button class="end-dump" disabled>').concat(eW,'</button></div></div><div class="').concat(xW,'">').concat(cW,'</div><div class="').concat(VW,'"><div class="').concat(BW,"\">userId:<input id=\"dump-remote-video-hook-userid\" value='*' />duration:<input id=\"dump-remote-video-hook-duration\" min='1' value='10' type='number' />mediaType:<select id=\"dump-remote-video-hook-mediaType\" value='main' ><option value='main' checked>Video</option><option value='sub'>Screen</option></select><button id=\"dump-remote-video-hook-button\">dump if video is available</button></div></div></div></div><div class=\"").concat(FW,'"></div><div class="').concat(WW,'"><a id="trtc_upload" class="').concat(jW,'">').concat(tW,'</a><a id="trtc_export" class="').concat(jW,'">').concat(iW,'</a><a id="trtc_hide" class="').concat(jW,'">').concat(rW,"</a></div></div></div>"),null==(e=this.shadowRoot)||e.appendChild(t.content.firstChild)}addStyle(){var e;let t=document.createElement("style");t.textContent="#".concat(vW,"{font-size:14px;--DD-BG-0:#ededed;--DD-BG-1:#f7f7f7;--DD-BG-2:#fff;--DD-BORDER:rgba(0,0,0,0.1);--DD-ERROR:red;--DD-WARN:#fa9d3b;--DD-INFO:#000;--DD-DEBUG:#10aeff;--DD-WARN-BG:#fff3cc;--DD-ERROR-BG:#ffe6e6;}#").concat(vW," a,.").concat(TW,"{cursor:pointer;}.").concat(vW,"{color:black;}.").concat(TW,"{display:block;position:fixed;right:50px;bottom:").concat(150+50*aj,"px;border-radius:5px;background-color:#07c160;color:#fff;padding:5px 10px;z-index:10000;}.").concat(yW,"{display:none;position:fixed;left:0;top:0;right:0;bottom:0;z-index:10001;background-color:rgb(0,0,0,0.6);}.").concat(SW,"{background-color:#ededed;display:none;position:fixed;min-height:85%;left:60%;right:0;bottom:0;z-index:10002;border:1px solid var(--DD-BG-0);}@media (max-width:768px) {.").concat(SW,"{left:0;}}.").concat(IW,"{display:flex;height:2em;border-bottom:1px solid var(--DD-BORDER);}.").concat(AW,"{padding:0 20px;border-right:1px solid rgba(0,0,0,0.1);line-height:2em;color:black;}.").concat(AW,".").concat(EW,"{background-color:var(--DD-BG-2);}.").concat(AW,".disabled{cursor:not-allowed;background-color:#ededed;color:#999;}.").concat(bW,"{height:2em;display:flex;flex-direction:row;}.").concat(RW,"{width:20%;text-align:center;line-height:2em;border-right:1px solid var(--DD-BORDER);border-bottom:1px solid var(--DD-BORDER);color:black;}.").concat(RW,".").concat(EW,"{border-bottom:1px solid #1485ee;background-color:var(--DD-BG-2);}.").concat(CW,"{background-color:#fff;position:absolute;left:0;right:0;top:2em;bottom:8em;overflow-y:scroll;overflow-x:hidden;}.").concat(CW,".").concat(kW,"{top:4em;bottom:10em}.").concat(DW,"{display:none;}.").concat(NW,"{display:none;}.").concat(OW,",.").concat(xW,"{line-height:2em;text-align:center;background-color:var(--DD-BG-0);border-bottom:1px solid var(--DD-BORDER);}.").concat(PW,",.").concat(MW,",.").concat(LW,"{text-align:center;border-bottom:1px solid var(--DD-BORDER);}.").concat(UW,",.").concat(VW,"{display:flex;flex-direction:column;padding:0.5em 0;justify-content:center;align-items:center;}.").concat(UW," div input{margin:0 10px;height:1.5em;width:4em;}.").concat(UW," div {padding:10px 0;border-radius:5px;}.").concat(UW," div button,.").concat(VW," div button {cursor:pointer;height:1.8em;border-radius:5px;margin-right:5px;}.").concat(UW," div button[disabled],.").concat(VW," div button[disabled]{cursor:not-allowed;}.").concat(VW," select {height:1.8em;margin:0 10px;}.").concat(VW," div input{margin:0 10px;height:1.5em;width:4em;}.").concat(BW," {line-height:3em;padding:0.5em;}.").concat(OW,"{text-align:center;background-color:var(--DD-BG-0);border-bottom:1px solid var(--DD-BORDER);}.").concat(PW,",.").concat(MW,",.").concat(LW,"{text-align:center;border-bottom:1px solid var(--DD-BORDER);}.").concat(GW,"{border-bottom:1px solid var(--DD-BG-0);padding:5px 10px;overflow-wrap: break-word;}.").concat(JW,"{color:var(--DD-ERROR);background-color:var(--DD-ERROR-BG);}.").concat(qW,"{color:var(--DD-WARN);background-color:var(--DD-WARN-BG);}div .").concat(KW,"{color:var(--DD-INFO);}.").concat(zW,"{color:var(--DD-DEBUG);}.").concat(FW,"{position:absolute;left:0;right:0;bottom:2em;height:6em;border-bottom:1px solid var(--DD-BORDER);display:flex;flex-direction:column;overflow-y:scroll;background-color:var(--DD-BG-1);}.").concat(HW,"{border-bottom:1px solid var(--DD-BORDER);padding:5px 10px;overflow-wrap: break-word;}.").concat(WW,"{position:absolute;line-height:2em;display:flex;flex-direction:row;left:0;right:0;bottom:0;}.").concat(jW,"{flex:1;color:black;text-align:center;background-color:#ededed;border-right:1px solid var(--DD-BORDER);}#").concat(vW," .").concat(YW,",#").concat(vW," .").concat(XW,"{position:absolute;height:2em;width:6em;right:2em;border-radius:5px;background-color:rgba(30,136,229,0.8);z-index:10003;cursor:pointer;padding:0 5px;line-height:2em;color:white;text-align:center;}.").concat(XW,"{bottom:9em;}.").concat(YW,"{bottom:11.5em;}#").concat(vW," .").concat(jW,".disable{cursor:not-allowed;background-color:#ededed;color:#999;}.").concat(ej," {position:relative;display:inline-block;}.").concat(ej," .tooltiptext{visibility:hidden;width:180px;background-color:black;color:#fff;text-align:center;padding:5px 0;border-radius:6px;position:absolute;}.").concat(ej," .tooltip-top {bottom:125%;left:50%;margin-left:-90px;}.").concat(ej,":hover .tooltiptext{visibility:visible;}.").concat(rj,"{position:absolute;left:0;right:0;bottom:8em;height:2em;display:flex;align-items:center;}.").concat(rj," div{flex:1;cursor:pointer;border-right:1px solid var(--DD-BORDER);text-align: center;}"),null==(e=this.shadowRoot)||e.appendChild(t)}};customElements.define("trtc-basic-debug-dialog",cj);var lj=class{constructor(e,t,i,r){zC(this,"_dialogNode",null),zC(this,"_switchNode",null),zC(this,"_maskNode",null),zC(this,"_panelNode",null),zC(this,"_logContentNode",null),zC(this,"_networkContentNode",null),zC(this,"_dumpContentNode",null),zC(this,"_tabNodes",[]),zC(this,"_toptabNodes",[]),zC(this,"_hasMove",!1),zC(this,"_showDialog",!1),zC(this,"_isMobile",!1),zC(this,"_showLogType","all"),zC(this,"prevBytesSent",0),zC(this,"prevBytesReceived",0),zC(this,"_core"),zC(this,"_log"),zC(this,"_logList",[]),zC(this,"isUploading",!1),zC(this,"publishMap",new Map),zC(this,"dumpLocalVideoMap"),zC(this,"dumpRemoteVideoMap"),zC(this,"eventMap",new Map),zC(this,"switchPos",{x:0,y:0,startX:0,startY:0,endX:0,endY:0,isTouchEnd:!1}),zC(this,"handleLeaveSuccess",(e=>{let{room:t}=e;var i,r;if(!this.hitTest(t))return;let n=null==(r=null==(i=this._dialogNode)?void 0:i.shadowRoot)?void 0:r.querySelector(".".concat(VW));for(let o of this.publishMap.values())null==n||n.removeChild(o);this.publishMap.clear()})),zC(this,"handleJoinSuccess",(e=>{let{room:t}=e;var i,r;if(!this.hitTest(t))return;(null==(r=null==(i=this._dialogNode)?void 0:i.shadowRoot)?void 0:r.querySelector(".".concat(ij))).innerHTML="sdkAppId: ".concat(t.sdkAppId,"<br/>roomId: ").concat(t.roomId,"<br/>userId: ").concat(t.userId,"<br/>")})),zC(this,"handleRemoteVideoAvailable",(e=>{let t="sub"===e.streamType?"auxiliary":"main";this.renderDumpTab(e.userId,"remote",t,"publish")})),zC(this,"handleRemoteVideoUnavailable",(e=>{let t="sub"===e.streamType?"auxiliary":"main";this.renderDumpTab(e.userId,"remote",t,"unpublish")})),zC(this,"handleRemoteAudioAvailable",(e=>{this.renderDumpTab(e.userId,"remote","audio","publish")})),zC(this,"handleRemoteAudioUnavailable",(e=>{this.renderDumpTab(e.userId,"remote","audio","unpublish")})),zC(this,"renderDumpTab",((e,t,i,r)=>{var n,o,s;let a={main:"video",auxiliary:"screen",audio:"audio"},c=(e,t)=>{var i,r,n;let o=document.createElement("div");o.innerText="".concat(e," - ").concat(a[t]," - ").concat(uW,"(s):");let s=document.createElement("input");s.type="number",s.min="0",s.value="10",s.id="dump_remote_".concat(t,"_").concat(e);let c=document.createElement("button");c.innerText=eW,c.disabled=!0;let l=document.createElement("button");l.innerText=ZH,l.onclick=()=>{let i,r,n=Number(s.value);if("audio"===t)({download:i,onDumpEnd:r}=this.dumpAudio("remote",n,e));else{if(!this.isSupportDumpVideo())return;({download:i,onDumpEnd:r}=this.dumpVideo(t,"remote",n,e))}i&&(this.inactiveButton(l,$H),n>0?setTimeout((()=>{null==i||i(),this.activeButton(l,ZH)}),1e3*n):(this.activeButton(c),c.onclick=()=>{c.onclick=null,null==i||i(),null==r||r(),this.activeButton(l,ZH),this.inactiveButton(c)}))},o.appendChild(s),o.appendChild(l),o.appendChild(c),o.style.cssText="padding:10px;";let d=document.createElement("div");return d.style.cssText="width:100%;display:flex;justify-content:center;border-top: 1px solid var(--DD-BORDER);",d.appendChild(o),null==(n=null==(r=null==(i=this._dialogNode)?void 0:i.shadowRoot)?void 0:r.querySelector(".".concat(VW)))||n.appendChild(d),d};if("remote"===t)if("publish"===r){let r=c(e,i);this.publishMap.set("".concat(e,"-").concat(t,"-").concat(i),r)}else{let r=this.publishMap.get("".concat(e,"-").concat(t,"-").concat(i));if(!r)return;null==(s=null==(o=null==(n=this._dialogNode)?void 0:n.shadowRoot)?void 0:o.querySelector(".".concat(VW)))||s.removeChild(r),this.publishMap.delete("".concat(e,"-").concat(t,"-").concat(i))}})),zC(this,"handleStatistics",(e=>{var t,i,r,n,o,s;let a=(e.bytesSent-this.prevBytesSent)/2,c=(e.bytesReceived-this.prevBytesReceived)/2;this.prevBytesSent=e.bytesSent,this.prevBytesReceived=e.bytesReceived,(null==(i=null==(t=this._dialogNode)?void 0:t.shadowRoot)?void 0:i.querySelector(".".concat(tj))).innerHTML="rtt: ".concat(e.rtt," ms upLoss: ").concat(e.upLoss,"% downLoss: ").concat(e.downLoss,"% <br>\n ↑ ").concat(a/1e3," KB/s (").concat(8*a/1e3," Kb/s) <br>\n ↓ ").concat(c/1e3," KB/s (").concat(8*c/1e3," Kb/s) <br>\n ");let l=null==(n=null==(r=this._dialogNode)?void 0:r.shadowRoot)?void 0:n.querySelector(".".concat(MW)),d="";e.localStatistics.audio.bitrate&&(d="<li>local audio: ".concat(e.localStatistics.audio.bitrate," Kb/s audioLevel: ").concat(e.localStatistics.audio.audioLevel.toFixed(5),"</li>")),e.localStatistics.video.length>0&&(d+="".concat(e.localStatistics.video.map((e=>"<li>local ".concat(e.videoType," video: ").concat(e.bitrate," Kb/s ").concat(e.width,"*").concat(e.height," ").concat(e.frameRate,"fps</li>"))).join(""))),l.innerHTML=""===d?"".concat(lW):d;let u=null==(s=null==(o=this._dialogNode)?void 0:o.shadowRoot)?void 0:s.querySelector(".".concat(LW)),h="";e.remoteStatistics.length>0&&e.remoteStatistics.forEach((e=>{let t="remote ".concat(e.userId,":");e.audio.bitrate>0&&(t+="<li>audio: ".concat(e.audio.bitrate," Kb/s audioLevel: ").concat(e.audio.audioLevel.toFixed(5),"</li>")),e.video.length>0&&e.video.forEach((e=>{t+="<li>".concat(e.videoType," video: ").concat(e.bitrate," Kb/s ").concat(e.width,"*").concat(e.height," ").concat(e.frameRate,"fps</li>")})),h+=t})),u.innerHTML=""===h?"".concat(lW):h})),zC(this,"pad",(e=>e<10?"0".concat(e):"".concat(e))),this._core=e,this._log=t,this.dumpLocalVideoMap=i,this.dumpRemoteVideoMap=r,this.initCustomElements(),this.synchronizeLog(),this.installEvents()}initCustomElements(){this._isMobile=(()=>{let e=window.navigator&&window.navigator.userAgent||"",t=/iPad/i.test(e)||/iPhone/i.test(e),i=/Android/i.test(e);return t||i})();let e=document.createElement("trtc-basic-debug-dialog");document.body.appendChild(e);let t=e.shadowRoot;if(this._dialogNode=e,!t)return;this._switchNode=t.querySelector(".".concat(TW)),this._addEventListener(this._switchNode,"click",this.onSwitchClick.bind(this));let i=getComputedStyle(this._switchNode);this.switchPos.x=parseInt(i.right,10)||50,this.switchPos.y=parseInt(i.bottom,10)||100+50*aj,this._isMobile?(this._switchNode.ontouchstart=this.onTouchStart.bind(this),this._switchNode.ontouchend=this.onTouchEnd.bind(this),this._switchNode.ontouchmove=this.onTouchMove.bind(this)):this._switchNode.onmousedown=this.onMouseDown.bind(this),this._maskNode=t.querySelector(".".concat(yW)),this._addEventListener(this._maskNode,"click",this.onMaskClick.bind(this)),this._panelNode=t.querySelector(".".concat(SW)),t.querySelector(".".concat(rj)).childNodes.forEach((e=>{switch(e.getAttribute("data-type")){case"go_bottom":this._addEventListener(e,"click",this.onGoBottomClick.bind(this));break;case"back_top":this._addEventListener(e,"click",this.onBackTopClick.bind(this));break;case"clear_log":this._addEventListener(e,"click",this.onClearLogClick.bind(this))}})),this._logContentNode=t.querySelector(".".concat(wW)),this._networkContentNode=t.querySelector(".".concat(DW)),this._dumpContentNode=t.querySelector(".".concat(NW)),this._tabNodes=Array.from(t.querySelector(".".concat(IW)).children),this._tabNodes.forEach((e=>{this._addEventListener(e,"click",this.onTabClick.bind(this))})),this._toptabNodes=Array.from(t.querySelector(".".concat(bW)).children),this._toptabNodes.forEach((e=>{this._addEventListener(e,"click",this.onToptabClick.bind(this))}));let r=t.querySelector("#trtc_upload");this._addEventListener(r,"click",this.onUploadClick.bind(this));let n=t.querySelector("#trtc_export");this._addEventListener(n,"click",this.onExportClick.bind(this));let o=t.querySelector("#trtc_hide");this._addEventListener(o,"click",this.onHideClick.bind(this));let s=t.querySelector("#".concat(ZW," .dump")),a=t.querySelector("#".concat(ZW," .end-dump")),c=Number(t.querySelector("#".concat(ZW," input")).value);this._addEventListener(s,"click",this.getDumpButtonClickHandler.bind(this,s,a,c,"main","local"));let l=t.querySelector("#".concat($W," .dump")),d=t.querySelector("#".concat($W," .end-dump")),u=Number(t.querySelector("#".concat($W," input")).value);this._addEventListener(l,"click",this.getDumpButtonClickHandler.bind(this,l,d,u,"auxiliary","local"));let h=t.querySelector("#".concat(QW," button"));this._addEventListener(h,"click",(()=>{let e=Number(t.querySelector("#".concat(QW," input")).value),{download:i,onDumpEnd:r}=this.dumpAudio("local",e);if(i)if(this.inactiveButton(h,$H),e>0)setTimeout((()=>{i(),this.activeButton(h,ZH)}),1e3*e);else{let e=t.querySelector("#".concat(QW," .end-dump"));this.activeButton(e),e.onclick=()=>{e.onclick=null,i(),null==r||r(),this.activeButton(h,ZH),this.inactiveButton(e)}}else this.addInfoToBanner(sj,"Failed to dump, please check if the current user has started the audio")}));let p=t.querySelector("#dump-remote-video-hook-userid"),m=t.querySelector("#dump-remote-video-hook-duration"),f=t.querySelector("#dump-remote-video-hook-mediaType"),_=t.querySelector("#dump-remote-video-hook-button");_.onclick=()=>{let e=Number(m.value);if(e<1)return void this.addInfoToBanner(sj,"duration at least 1s");let t=p.value;if(!t)return void this.addInfoToBanner(sj,"please input user id");"*"===t&&this.inactiveButton(_);let i,r,n=f.value,o="remote_".concat(t,"_").concat("sub"===n?"auxiliary":n),s=o=>{if((o.userId===t||"*"===t)&&o.streamType===n){if(this.addInfoToBanner(nj,"[".concat(o.userId,"_").concat(n,"] starting to dump video, duration: ").concat(e,"s")),({download:i,onDumpEnd:r}=this.dumpVideo("sub"===o.streamType?"auxiliary":o.streamType,"remote",e,o.userId)),!i)return;setTimeout((()=>{null==i||i(),null==r||r(),"*"!==t&&this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_VIDEO_AVAILABLE,s)}),1e3*e)}};this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_VIDEO_AVAILABLE,s),this.addInfoToBanner(nj,"[".concat(o,"] waiting to dump video from ").concat("*"===t?"all remote users":"user ".concat(t),", duration: ").concat(e,"s"))}}synchronizeLog(){this._core.loggerManager.getQueue().forEach((e=>{this.updateLog(e)}))}isSupportDumpVideo(){return!(!this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED&&!this._core.rtcDectection.IS_SCRIPT_TRANSFORM_SUPPORTED)||(this.addInfoToBanner(sj,"Current browser does not support dumping video"),!1)}_addEventListener(e,t,i,r){e&&(e.addEventListener(t,i,r),this.eventMap.set(e,{type:t,listener:i}))}_removeEventListener(){this.eventMap.forEach(((e,t)=>{let{type:i,listener:r}=e;t&&t.removeEventListener(i,r)})),this.eventMap.clear(),this._switchNode&&(this._switchNode.onmousedown=null,this._switchNode.ontouchmove=null,this._switchNode.ontouchstart=null,this._switchNode.ontouchend=null)}closeDialog(){this.uninstallEvents(),this._removeEventListener(),this._dialogNode&&(document.body.removeChild(this._dialogNode),this._dialogNode=null)}updateLog(e){var t;this._logList.push(e);let i=document.createElement("div");switch(i.classList.add(GW),e.level){case 4:i.classList.add(JW);break;case 2:i.classList.add(KW);break;case 3:i.classList.add(qW);break;case 1:i.classList.add(zW)}i.textContent=e.log,"all"!==this._showLogType&&!i.classList.contains("".concat(GW,"_").concat(this._showLogType))&&(i.style.display="none"),null==(t=this._logContentNode)||t.appendChild(i),this.addHelper(i)}getDumpButtonClickHandler(e,t,i,r,n){if(!this.isSupportDumpVideo())return;let{download:o,onDumpEnd:s}=this.dumpVideo(r,n,i);if(o)return this.addInfoToBanner(nj,"[".concat(n,"_").concat(r,"] starting to dump...")),this.inactiveButton(e,$H),void(i>0?setTimeout((()=>{o(),this.activeButton(e,ZH)}),1e3*i):(this.activeButton(t),t.onclick=()=>{t.onclick=null,null==s||s(),o(),this.activeButton(e,ZH),this.inactiveButton(t)}));this.addInfoToBanner(nj,"[".concat(n,"_").concat(r,"] waiting to dump..."));let a=o=>{let{track:s}=o;if(s.room===this._core.room&&s.streamType===r){this.addInfoToBanner(nj,"[".concat(n,"_").concat(r,"] starting to dump")),"local"===n&&this._core.innerEmitter.off("104",a);let{download:o,onDumpEnd:s}=this.dumpVideo(r,n,i);if(!o)return;i>0?setTimeout((()=>{o(),this.activeButton(e,ZH)}),1e3*i):(this.activeButton(t),t.onclick=()=>{t.onclick=null,null==s||s(),o(),this.activeButton(e,ZH),this.inactiveButton(t)})}};a.bind(this),"local"===n&&this._core.innerEmitter.on("104",a),this.inactiveButton(e,$H)}onSwitchClick(){this._hasMove?this._hasMove=!1:this._showDialog?this.hideDialog():(this._isMobile&&(this._maskNode.style.display="block"),this._panelNode.style.display="block",this._switchNode.style.display="none",this._showDialog=!0,this.logContentGoBottom())}onTabClick(e){var t,i,r,n,o,s,a;let c=e.target;null==(t=this._tabNodes)||t.forEach((e=>{e.classList.remove(EW)})),c.classList.add(EW);let l=c.getAttribute("data-tab");"log"===l?(null==(n=null==(r=null==(i=this._dialogNode)?void 0:i.shadowRoot)?void 0:r.querySelector(".".concat(CW)))||n.classList.add(kW),this._logContentNode.style.display="block",this._networkContentNode.style.display="none",this._dumpContentNode.style.display="none",this.logContentGoBottom()):(null==(a=null==(s=null==(o=this._dialogNode)?void 0:o.shadowRoot)?void 0:s.querySelector(".".concat(CW)))||a.classList.remove(kW),"network"===l?(this._networkContentNode.style.display="block",this._logContentNode.style.display="none",this._dumpContentNode.style.display="none"):"dump"===l&&(this._dumpContentNode.style.display="block",this._networkContentNode.style.display="none",this._logContentNode.style.display="none"))}onToptabClick(e){var t,i;let r=e.target;null==(t=this._toptabNodes)||t.forEach((e=>{e.classList.remove(EW)})),r.classList.add(EW),this._showLogType=r.getAttribute("data-type");let n=null==(i=this._logContentNode)?void 0:i.querySelectorAll(".".concat(GW)),o="".concat(GW,"_").concat(this._showLogType);n.forEach((e=>{e.classList.contains(o)||"all"===this._showLogType?e.style.display="block":e.style.display="none"})),this.logContentGoBottom()}onExportClick(){let e=this._logList.reduce(((e,t)=>"".concat(e+t.log,"\n")),""),t=new Blob([e],{type:"text/plain"}),i=document.createElement("a"),r=URL.createObjectURL(t);i.href=r;let n="trtc_".concat(void 0===this._core.room.sdkAppId?"EmptySdkAppId":this._core.room.sdkAppId,"_").concat(void 0===this._core.room.userId?"EmptyUserId":this._core.room.userId,"_").concat(this.formatStartDumpTime(+new Date),".log");i.download=n,i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(r),document.body.removeChild(i),this.addInfoToBanner(nj,"Export success: The log file name is ".concat(n)),this._core.kvStatManager.addSuccessEvent({key:592703})}addInfoToBanner(e,t){var i,r;let n=null==(r=null==(i=this._dialogNode)?void 0:i.shadowRoot)?void 0:r.querySelector(".".concat(FW)),o=document.createElement("div");o.classList.add(HW);let s=e===nj?"🟩":e===oj?"🟧":"🟥";o.innerText="".concat(s," [").concat(this.getCurrentTime(),"] ").concat(t),n.appendChild(o),n.scrollTop=n.scrollHeight}onUploadClick(){return qC(this,null,(function*(){var e,t;if(this.isUploading)return;this.isUploading=!0;let i=null==(t=null==(e=this._dialogNode)?void 0:e.shadowRoot)?void 0:t.querySelector("#trtc_upload");i.innerText="Uploading...",null==i||i.classList.add(".disable");let r=this._logList.reduce(((e,t)=>"".concat(e+t.log,"\n")),""),n=new Blob([r],{type:"text/plain"}),o=new FormData;o.append("file",n,"trtc.log"),o.append("sdkAppId","".concat(this._core.room.sdkAppId||"EmptySdkAppId")),o.append("userId","".concat(this._core.room.userId||"EmptyUserId")),fetch("https://service.trtc.qcloud.com/api/uploadLogFile",{method:"POST",body:o}).then((e=>e.json())).then((e=>{this.addInfoToBanner(e.type,e.message_en||"Upload Failed: Please use local export"),this.isUploading=!1,this._log.info(e.message_en),this._core.kvStatManager.addSuccessEvent({key:592704})})).catch((()=>{this.addInfoToBanner(sj,"Upload Failed: Please use local export"),this._log.info("Upload Failed: Please use local export"),this._core.kvStatManager.addFailedEvent({key:592704})})).finally((()=>{i.innerText=tW,null==i||i.classList.remove(".disable"),this.isUploading=!1}))}))}onHideClick(){this.hideDialog()}onMaskClick(){this.hideDialog()}hideDialog(){this._isMobile&&(this._maskNode.style.display="none"),this._panelNode.style.display="none",this._switchNode.style.display="block",this._showDialog=!1}onBackTopClick(){var e,t,i;null==(i=null==(t=null==(e=this._dialogNode)?void 0:e.shadowRoot)?void 0:t.querySelector(".".concat(CW)))||i.scrollTo(0,0)}onGoBottomClick(){this.logContentGoBottom()}onClearLogClick(){this._logList=[],this._logContentNode&&(this._logContentNode.innerHTML="")}logContentGoBottom(){var e,t;let i=null==(t=null==(e=this._dialogNode)?void 0:e.shadowRoot)?void 0:t.querySelector(".".concat(CW));null==i||i.scrollTo(0,null==i?void 0:i.scrollHeight)}onMouseDown(e){e.preventDefault(),this.switchPos.startX=e.pageX,this.switchPos.startY=e.pageY,document.onmousemove=this.onMouseMove.bind(this),document.onmouseup=this.onMouseUp.bind(this)}onMouseMove(e){e.cancelable&&e.preventDefault(),this._hasMove=!0;let t=this.switchPos.x-(e.pageX-this.switchPos.startX),i=this.switchPos.y-(e.pageY-this.switchPos.startY);[t,i]=this.getSafeAreaXY(t,i),this._switchNode.style.right="".concat(t,"px"),this._switchNode.style.bottom="".concat(i,"px"),this.switchPos.endX=t,this.switchPos.endY=i}onMouseUp(){this.switchPos.startX=0,this.switchPos.startY=0,this.switchPos.x=this.switchPos.endX,this.switchPos.y=this.switchPos.endY,document.onmousemove=null,document.onmouseup=null}onTouchStart(e){this.switchPos.startX=e.touches[0].pageX,this.switchPos.startY=e.touches[0].pageY,this.switchPos.isTouchEnd=!1}onTouchEnd(){this.switchPos.isTouchEnd&&(this.switchPos.startX=0,this.switchPos.startY=0,this.switchPos.isTouchEnd=!1,this.switchPos.x=this.switchPos.endX,this.switchPos.y=this.switchPos.endY)}onTouchMove(e){if(e.touches.length<=0)return;let t=e.touches[0].pageX-this.switchPos.startX,i=e.touches[0].pageY-this.switchPos.startY,r=Math.floor(this.switchPos.x-t),n=Math.floor(this.switchPos.y-i);[r,n]=this.getSafeAreaXY(r,n),this._switchNode.style.right="".concat(r,"px"),this._switchNode.style.bottom="".concat(n,"px"),this.switchPos.endX=r,this.switchPos.endY=n,this.switchPos.isTouchEnd=!0,e.cancelable&&e.preventDefault()}getSafeAreaXY(e,t){let i=Math.max(document.documentElement.offsetWidth,window.innerWidth),r=Math.max(document.documentElement.offsetHeight,window.innerHeight);return e+this._switchNode.offsetWidth>i&&(e=i-this._switchNode.offsetWidth),t+this._switchNode.offsetHeight>r&&(t=r-this._switchNode.offsetHeight),e<0&&(e=0),t<20&&(t=20),[e,t]}hitTest(e){return e===this._core.room}installEvents(){this._core.innerEmitter.on("264",this.handleLog,this),this._core.innerEmitter.on("53",this.handleLeaveSuccess,this),this._core.innerEmitter.on("27",this.handleJoinSuccess,this),this._core.trtc.on(this._core.TRTC.EVENT.STATISTICS,this.handleStatistics,this),this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_AUDIO_AVAILABLE,this.handleRemoteAudioAvailable),this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_AUDIO_UNAVAILABLE,this.handleRemoteAudioUnavailable),this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_VIDEO_AVAILABLE,this.handleRemoteVideoAvailable),this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_VIDEO_UNAVAILABLE,this.handleRemoteVideoUnavailable),this._core.room.on("dump",this.handleDumpFromScriptTransform,this)}uninstallEvents(){this._core.innerEmitter.off("264",this.handleLog,this),this._core.innerEmitter.off("53",this.handleLeaveSuccess,this),this._core.innerEmitter.off("27",this.handleJoinSuccess,this),this._core.trtc.off(this._core.TRTC.EVENT.STATISTICS,this.handleStatistics,this),this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_AUDIO_AVAILABLE,this.handleRemoteAudioAvailable),this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_AUDIO_UNAVAILABLE,this.handleRemoteAudioUnavailable),this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_VIDEO_AVAILABLE,this.handleRemoteVideoAvailable),this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_VIDEO_UNAVAILABLE,this.handleRemoteVideoUnavailable),this._core.room.off("dump",this.handleDumpFromScriptTransform,this)}handleDumpFromScriptTransform(e){if(!e.isAudio)if(e.userId){let t=this.dumpRemoteVideoMap["".concat(e.userId,"-").concat(e.streamType)];t&&(t.data.push(e.data),t.duration>0&&Date.now()-t.startTimestamp>1e3*t.duration&&t.onDumpEnd())}else{let t="main"===e.streamType?"main":"sub",i=this.dumpLocalVideoMap[t];i&&(i.data.push(e.data),i.duration>0&&Date.now()-i.startTimestamp>1e3*i.duration&&i.onDumpEnd())}}inactiveButton(e,t){e.disabled=!0,t&&(e.innerText=t)}activeButton(e,t){e.disabled=!1,t&&(e.innerText=t)}handleLog(e){this.updateLog(e.log)}addHelper(e){let t=/((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/g,i=_W,r=e.innerText;r=r.split("\n").map((e=>{if((e=e.replace(/</g,"&lt;").replace(/>/g,"&gt;")).includes("failed"))return e.includes("on autoplay-failed")?e:"<span class='red' style=\"background:red; color:#fff;\">".concat(e,"</span>");if(e.includes("clientIp:")){let i=e.match(t);return null==i||i.forEach((t=>{e=e.replace(t,'<a href="javascript:void(0);" target=""><span class=\'ip\' style="background:#e1dfdf">'.concat(t,"</span></a>"))})),e}return e.includes("URL of current page")&&(e=e.replace(/URL of current page: (.+)/,'URL of current page: <a href="$1">$1</a>')),e})).join("\n"),i.forEach((t=>{if(e.innerText.includes(t)){let i="";i="function"==typeof fW[t].tips?fW[t].tips(e.innerText):fW[t].tips,r=r.replace(new RegExp("".concat((e=>e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d").replace(">","&gt;").replace(">","&lt;"))(t)),"gi"),'<span class="'.concat(ej,'" style="background:').concat(fW[t].color||"#e1dfdf","; color: ").concat(fW[t].textColor||"#000",'">').concat(t,'\n <span class="tooltiptext tooltip-top">').concat(i,"</span>\n </span>"))}})),e.innerHTML=r}getCurrentTime(){let e=new Date,t=this.pad(e.getHours()),i=this.pad(e.getMinutes()),r=this.pad(e.getSeconds());return"".concat(t,":").concat(i,":").concat(r)}dumpVideo(e,t,i,r){let n,o=Date.now(),s=this.formatStartDumpTime(o),a=[],c="".concat(t,"_").concat(r,"_").concat(e);if("local"===t){if(!this.hasLocalTrack(e,"video"))return{};n=()=>{delete this.dumpLocalVideoMap["auxiliary"===e?"sub":"main"]},this.dumpLocalVideoMap["auxiliary"===e?"sub":"main"]={startTimestamp:o,data:a,duration:i,onDumpEnd:n}}if("remote"===t&&r){if(n=()=>{delete this.dumpRemoteVideoMap["".concat(r,"-").concat(e)]},this.dumpRemoteVideoMap["".concat(r,"-").concat(e)])return this.addInfoToBanner(oj,"[".concat(c,"] dump already exists.")),{};this.dumpRemoteVideoMap["".concat(r,"-").concat(e)]={startTimestamp:o,data:a,duration:i,onDumpEnd:n}}return{download:()=>{if(0===a.length)return void this.addInfoToBanner(sj,"[".concat(c,"] dump failed. Reason: data is empty"));let i;"main"===e?i="video":"auxiliary"===e&&(i="screen");let n=URL.createObjectURL(new Blob(a)),o=document.createElement("a"),l="local"===t?"local_".concat(i,"_").concat(s,".h264"):"remote-".concat(r,"_").concat(i,"_").concat(s,".h264");o.href=n,o.download=l,o.style.display="none",document.body.appendChild(o),o.click(),URL.revokeObjectURL(n),o.remove(),this.addInfoToBanner(nj,"[".concat(c,"] dump success. File name is: ").concat(l))},onDumpEnd:n}}hasLocalTrack(e,t){for(let i of this._core.room.localTracks)if(i.streamType===e&&i.kind===t)return!0;return!1}dumpAudio(e,t,i){var r,n,o;let s,a,c=null,l=[],d=[],u=[],h=[],p=[],m=[],f=[],_=new AbortController,g=Date.now(),v=this.formatStartDumpTime(g),E=this._core.room.audioManager._localAudioPipline,T=this._core.room.audioManager._localScreenAudioPipeline,y=e=>{let{data:t}=e;u[0]=u[0]?u[0].concat(t):[t]},S=e=>{let{room:t,data:i,type:r}=e;if(this.hitTest(t)){if("dump"===r){if(h[0]=h[0]?h[0].concat(i.captureInput):i.captureInput,h[1]=h[1]?h[1].concat(i.playInput):i.playInput,s){let e=i.startTime-s,t=i.endTime-i.startTime;if(e>30||t>30){let r=function(e){if("number"!=typeof e||e<0)return"0毫秒";let t=[],i=Math.floor(e/6e4),r=e%6e4;i>0&&t.push("".concat(i,"分"));let n=Math.floor(r/1e3);return r%=1e3,(n>0||t.length)&&t.push("".concat(n,"秒")),(r>0||!t.length)&&t.push("".concat(r,"毫秒")),t.join("")},n=i.startTime-a,o=s-a;f.push("".concat(i.startTime,"\t").concat(r(n),"~").concat(r(o),"\t").concat(e,"\t").concat(t))}s=i.startTime}else s=i.startTime,a=i.startTime;m.push(i.startTime)}"dump-screen-audio"===r&&(p[0]=p[0]?p[0].concat(i.captureInput):i.captureInput,p[1]=p[1]?p[1].concat(i.playInput):i.playInput)}};if("local"===e){let{sampleRate:e}=this._core.room.audioManager.audioContext;if(!this._core.room.audioManager.hasAudioTrack&&!this._core.room.audioManager.hasScreenAudioTrack)return{};if(null!=E&&E.source.node&&(l.push(E.source.node),d.push("local_audio_raw_capture-".concat(e,"-").concat(E.source.node.channelCount))),(null!=(r=null==E?void 0:E.audioProcessor)&&r.node||null!=T&&T.audioProcessor.node)&&(this._core.trtc.updatePlugin("AudioProcessor",{enableDump:!0}),this._core.innerEmitter.on("265",S),null!=(n=null==E?void 0:E.audioProcessor)&&n.node&&(l.push(E.audioProcessor.node),d.push("local_audio_audioProcessor_processed-".concat(e,"-").concat(E.audioProcessor.node.channelCount))),null!=T&&T.audioProcessor.node&&(l.push(T.audioProcessor.node),d.push("screen_audio_audioProcessor_processed-".concat(e,"-").concat(T.audioProcessor.node.channelCount)))),null!=E&&E.denoiser.node&&(l.push(E.denoiser.node),d.push("local_audio_denoiser_processed-".concat(e,"-").concat(E.denoiser.node.channelCount))),this._core.room.audioManager.mixWeight>1&&null!=E&&E.stream){let t=this._core.room.audioManager.audioContext.createMediaStreamSource(E.stream);t.channelCount=1,l.push(t),d.push("local_audio_destination-".concat(e,"-").concat(t.channelCount))}}else if("remote"===e&&void 0!==i){let e=null==(o=this._core.room.remotePublishedUserMap.get(i))?void 0:o.remoteAudioTrack;if(null==e||!e.mediaTrack)return{};let t=this._core.createAudioNode(e.mediaTrack);l.push(t),d.push("remote_".concat(i))}let I=()=>qC(this,null,(function*(){var t,i,r,n,o;let s=new gW.default;for(let e=0;e<d.length;e++)s.file("".concat(d[e],".pcm"),new Blob(u[e]));if(null!=(t=null==h?void 0:h[0])&&t.length&&s.file("audioProcessor_input_capture.pcm",new Blob(h[0])),null!=(i=null==h?void 0:h[1])&&i.length&&s.file("audioProcessor_input_playback.pcm",new Blob(h[1])),null!=(r=null==p?void 0:p[0])&&r.length&&s.file("audioProcessor_screen_audio_input_capture.pcm",new Blob(p[0])),null!=(n=null==p?void 0:p[1])&&n.length&&s.file("audioProcessor_screen_audio_input_playback.pcm",new Blob(p[1])),null!=m&&m.length){let e=m.reduce(((e,t)=>"".concat(e,"\n").concat(t)));s.file("audioProcessor_handle_timestamp.txt",new Blob([e]))}if(null!=f&&f.length){let e=f.reduce(((e,t)=>"".concat(e,"\n").concat(t)));s.file("audioProcessor_big_gap_data.txt",new Blob([e]))}let a=yield s.generateAsync({type:"blob"}),l=URL.createObjectURL(a),g=document.createElement("a");g.href=l,g.download="".concat(e,"-audio-").concat(v,".zip"),g.style.display="none",document.body.appendChild(g),g.click(),URL.revokeObjectURL(l),g.remove(),this.addInfoToBanner(nj,"Dump success, file name is: ".concat(e,"-").concat(v,".zip")),this._core.trtc.off(JF.AUDIO_FRAME,y),this._core.innerEmitter.off("265",S),(null!=(o=null==E?void 0:E.audioProcessor)&&o.node||null!=T&&T.audioProcessor.node)&&this._core.trtc.updatePlugin("AudioProcessor",{enableDump:!1}),c&&clearTimeout(c),_.abort("download")}));return t>0&&(c=Number(setTimeout((()=>{_.abort("timeout")}),1e3*t))),l.length>0&&this._core.startGetPCM(l).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>{u[t]=u[t]?u[t].concat(e[0]):[e[0]]}))}}),_).catch((()=>I)))),{download:I,onDumpEnd:()=>{_.abort("timeout")}}}formatStartDumpTime(e){let t=new Date(e),i=t.getFullYear(),r=this.pad(t.getMonth()+1),n=this.pad(t.getDate()),o=this.pad(t.getHours()),s=this.pad(t.getMinutes()),a=this.pad(t.getSeconds()),c=-t.getTimezoneOffset(),l=Math.floor(Math.abs(c)/60),d=Math.abs(c)%60,u=c>=0?"+":"-";return"".concat(i,"-").concat(r,"-").concat(n,"T").concat(o,"-").concat(s,"-").concat(a).concat(u).concat(this.pad(l),"-").concat(this.pad(d))}};GC([_H(300,(()=>"export"))],lj.prototype,"onExportClick",1),GC([_H(300,(()=>"upload"))],lj.prototype,"onUploadClick",1);var dj=lj,uj=0,hj=class e{constructor(e){this.core=e,zC(this,"_core"),zC(this,"log"),zC(this,"dumpLocalVideoMap",{}),zC(this,"dumpRemoteVideoMap",{}),zC(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++uj)}),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 qC(this,null,(function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&"true"!==(null==(e=window.sessionStorage)?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))||(yield this.openDebugDiaLog(),this.addVideoProcessor())}))}update(e){return qC(this,arguments,(function(e){var t=this;let{forceOpen:i}=e;return function*(){pD(i)&&(i?(yield t.openDebugDiaLog(),t.addVideoProcessor()):(t.closeDebugDiaLog(),t.removeVideoProcessor()))}()}))}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return qC(this,null,(function*(){if(!this.dialog)try{this.dialog=new dj(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(hP){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(hP))}}))}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):JH,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):YH,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo(e){let{frame:t,mediaType:i}=e;return JH({frame:t,onDump:()=>{if(!i)return;let e=2===i?"sub":"main",r=this.dumpLocalVideoMap[e];r&&(r.data.push(t.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>1e3*r.duration&&r.onDumpEnd())}})}decodeVideo(e){let{frame:t,track:i}=e;return YH({frame:t,onDump:()=>{if(!i)return;let e=this.dumpRemoteVideoMap["".concat(i.userId,"-").concat(i.streamType)];e&&(e.data.push(t.data.slice(0)),e.duration>0&&Date.now()-e.startTimestamp>1e3*e.duration&&e.onDumpEnd())}})}loadScript(e){return new Promise(((t,i)=>{this.log.info("loading debug dialog from ".concat(e));let r=document.createElement("script");r.type="text/javascript",r.onload=t,r.onerror=i,r.crossOrigin="anonymous",r.src=e,document.head.append?document.head.append(r):document.getElementsByTagName("head")[0].appendChild(r)}))}};zC(hj,"Name","Debug"),zC(hj,"autoStart",!0),GC([HL({settings:{timeout:3e3,retries:3},onError(e,t,i){var r;null!=(r=null==e?void 0:e.message)&&r.includes("timeout")?t():i(e)}})],hj.prototype,"loadScript",1);var pj=hj,mj=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},fj=class{constructor(e,t,i){zC(this,"trackDoneOB"),zC(this,"startOB"),zC(this,"stopOB"),zC(this,"inputFrameCount",0),zC(this,"decodedFrameCount",0),zC(this,"type","auto"),zC(this,"config"),zC(this,"decoder"),zC(this,"_decodeSink");let{kvStatManager:r,trtc:n}=e;this.config=i.config,this.trackDoneOB=yV(t,CL.INIT),this.stopOB=uV(),this.startOB=uV(),"auto"===i.type?this.type="webCodecs":this.type=i.type;let o=uV();GU(this.startOB,sV(0),TB((e=>{let i=this.pipe(t);return o.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),GU(i,jV(this.stopOB),WB((()=>{}),(i=>{t.log.error(i),r.addFailedEvent({key:mj(this.type),error:i}),e>4?this.startOB.error(i):this.startOB.next(e+1)}))),GU(i,WV(1),BB(PV))})),jV(this.stopOB),WB((()=>{t.player.setOutput(),o.next("STARTED")}),(e=>{o.next("FAILED")}),(()=>{r.addSuccessEvent({key:mj(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 ZU()((t=>qC(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(pP){e.log.error(pP),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"}))}},_j={type:"object"},gj=class e{constructor(e){this.core=e,zC(this,"log"),zC(this,"contextMap",new Map),zC(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 _j}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 GU(n.trackDoneOB,WV(1),WB((()=>{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))}}};zC(gj,"Name","TRTCAudioDecoder");var vj=gj,Ej=0,Tj=new Set,yj=null;gk("5.10.2-beta.16"),sP.checkStorage(),fL();var Sj={RtcError:CF,ErrorCode:SF,ErrorCodeDictionary:IF},Ij=class e extends nk.EventEmitter{constructor(t,i){super(),zC(this,"_room"),zC(this,"_eventListened",new Set),zC(this,"_localVideoTrack",null),zC(this,"_localAudioTrack",null),zC(this,"_localScreenTrack",null),zC(this,"_localScreenAudioTrack",null),zC(this,"_localVideoConfig",null),zC(this,"_localScreenConfig",null),zC(this,"_localAudioConfig",null),zC(this,"_remoteVideoConfigMap",new Map),zC(this,"_remoteAudioConfigMap",new Map),zC(this,"_remoteAudioVolumeMap",new Map),zC(this,"_remoteAudioMuteMap",new Map),zC(this,"_mediaTrackMap",new WeakMap),zC(this,"_log",nP.createLogger({id:"t".concat(++Ej)})),zC(this,"_plugins",new Map),zC(this,"_networkQuality",null),zC(this,"_speakerId"),zC(this,"_getPCMAbortCtrl"),this._room=new t(VC({logger:this._log,frameWorkType:e.frameWorkType},i)),this._room.videoDecodeFallbackType=i.videoDecodeFallback,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(OH,i.assetsPath),this._use(RH,i.assetsPath),this._use(LH,i.assetsPath),this._use(vj,i.assetsPath||Dk),this._use(pj),i.enableSEI&&aL&&this._use(qH),this._room.on("audio-volume",(e=>{!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*this._localAudioTrack.getAudioLevel())}),1===i.volumeType&&e.forEach((e=>{var t;let i=""===e.userId?this._localAudioTrack:null==(t=this.room.remotePublishedUserMap.get(e.userId))?void 0:t.remoteAudioTrack;i&&(e.volume=i.dbVolume)})),this.emit(JF.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{this._log.error(new CF({code:SF.OPERATION_FAILED,extraCode:5504,message:e.message,originError:e}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:i}=e;e.emit=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{return i.apply(e,n)}catch(pP){let i=hM({key:cM.CATCH_HANDLER_ERROR,data:{name:t,event:n[0]},addDocLink:!1});return nP.warn("".concat(i,"\n\n").concat(pP.stack)),!1}}})(this,"trtc")}static create(e){}static _create(t,i){!function(){var e;if(TF){TF=!1,5!==nP.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(wk,"/en/index.html")),console.info("* Changelog: ".concat(wk,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),nP.info("TRTC Web SDK Version:",_k),UO||nP.debug("Build Time:","2025-06-06 15:06:22");let t="UA: ".concat(navigator.userAgent," \nCPU core: ").concat(navigator.hardwareConcurrency,", GPU: ").concat(zO()),i=navigator.deviceMemory;i&&(t+=", minRAM: ".concat(i,"GB")),nP.info(t),nP.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),GO().then((e=>{e&&nP.info(jO)}))}}();let r=new e(t,i||{});return Tj.add(r),r}get room(){return this._room}_listenEvents(){UL(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(JF.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(JF.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)})).add("banned",(e=>{this._exitRoom().finally((()=>{this.emit(JF.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().finally((()=>{this.emit(JF.ERROR,CF.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(JF.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e;let t=BC(VC({},e),{uplinkRTT:Math.min(e.uplinkRTT,Kw),downlinkRTT:Math.min(e.downlinkRTT,Kw)});this.emit(JF.NETWORK_QUALITY,t)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{UL(t,t).add("player-state-changed",(i=>{let r=BC(VC({},i),{userId:e.userId});t.kind===zk.VIDEO&&(r.streamType=XF(t.streamType)),this.emit(t.kind===zk.AUDIO?JF.AUDIO_PLAY_STATE_CHANGED:JF.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===sk.PLAY_NOT_ALLOWED&&this.emit(JF.AUTOPLAY_FAILED,{userId:t.userId,resume:()=>t.player.resume()})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{VL(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?JF.REMOTE_VIDEO_AVAILABLE:JF.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),n!==s&&(s?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i}),this.emit(s?JF.REMOTE_AUDIO_AVAILABLE:JF.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?JF.REMOTE_VIDEO_AVAILABLE:JF.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))})).add("sei-message",(e=>{this.emit(JF.SEI_MESSAGE,BC(VC({},e),{streamType:XF(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(JF.ERROR,new CF({code:SF.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,Kw),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)/ZP},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)/ZP},video:e.msg_video_status.map((e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_dec_fps,videoType:c[e.uint32_video_stream_type]})))})))};this.emit(JF.STATISTICS,l)})).add("custom-message",(e=>{this.emit(JF.CUSTOM_MESSAGE,e)})).add("layerData",(e=>this.emit(JF.LAYER_DATA,e))).add("first-video-frame",(e=>{this.emit(JF.FIRST_VIDEO_FRAME,BC(VC({},e),{streamType:XF(e.streamType)}))})),UL(this,xx).add("audioInputAdded",(e=>{this.emit(JF.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(JF.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(JF.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(JF.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>qC(this,null,(function*(){if(this.emit(JF.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),yj&&yj.deviceId===Bw){let e=(yield Wx()).find((e=>e.deviceId===Bw));e&&yj.groupId!==e.groupId&&(yj=e,this.emit(JF.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>qC(this,null,(function*(){this.emit(JF.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Wx())[0];if(!t||!yj||yj.groupId===t.groupId)return;let i=yj.deviceId===e.deviceId,r=yj.deviceId===Bw&&yj.deviceId===t.deviceId;(i||r)&&(yj=t,this.emit(JF.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))))}use(e){let t,i;"plugin"in e?(t=e.plugin,i=e.assetsPath):t=e,this._use(t,i||Dk)}_use(t,i){if(this._plugins.get(t.Name))return void this._log.warn("duplicate install plugin",t.Name);let r=new t(mH.call(this,{TRTC:e,room:this._room,errorModule:Sj,assetsPath:i}));this._plugins.set(t.Name,r),t.autoStart&&this.startPlugin(t.Name)}enterRoom(t){return qC(this,null,(function*(){var i,r;let{scene:n="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:a=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!mD(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,_D(t.preferHW)&&(this._room.preferHW=t.preferHW),t.playoutDelay&&(this._room.playoutDelay=t.playoutDelay),t.jitterBufferDelay&&(this._room.jitterBufferDelay=t.jitterBufferDelay);let c={sdkAppId:t.sdkAppId,userId:t.userId,userSig:t.userSig,privateMapKey:t.privateMapKey||null,latencyLevel:t.latencyLevel,role:"audience"===t.role?21:20,roomId:t.roomId||0,strRoomId:t.strRoomId||"",businessInfo:t.businessInfo||null,streamId:null,userDefineRecordId:t.userDefineRecordId||null,frameWorkType:t.frameWorkType,component:t.component,language:t.language,priority:t.priority,useVp8:t.useVp8,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(),VH.start()}))}exitRoom(){return qC(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return qC(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(){VL(this),this.removeAllListeners(),this._room.destroy(),Tj.delete(this),0===Tj.size&&VH.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach((e=>{var t;return null==(t=e.destroy)?void 0:t.call(e)})),this._plugins.clear(),eP.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return qC(this,arguments,(function(){var t=this;let i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(t._localAudioTrack)return void t._log.warn("local audio is already started");let{publish:r=!0,mute:n,option:o}=i,s=new TU(t._room.audioManager),a={},c={muted:!0};o&&(pD(o.microphoneId)?pD(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&fD(o.captureVolume)&&s.setCaptureVolume(o.captureVolume),pD(o.profile)||(mD(o.profile)?Wk[o.profile]&&s.setProfile(Wk[o.profile]):s.setProfile(o.profile)),fD(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),pD(o.echoCancellation)||(s.profile.echoCancellation=o.echoCancellation),pD(o.noiseSuppression)||(s.profile.noiseSuppression=o.noiseSuppression),pD(o.autoGainControl)||(s.profile.autoGainControl=o.autoGainControl)),s.on("5",(e=>{t.emit(JF.ERROR,new CF({code:SF.DEVICE_ERROR,extraCode:5309,messageParams:{error:e}}))})),s.on("2",(e=>{t.emit(JF.DEVICE_CHANGED,{type:"microphone",action:"active",device:e})})),s.on("4",(e=>{let i;e.error&&(i=CF.convertFrom(e.error)),t.emit(JF.PUBLISH_STATE_CHANGED,BC(VC({},e),{error:i}))})),t._listenOutputTrackChanged(s),t._speakerId&&s.setAudioOutput(t._speakerId),yield s.capture(a),pD(n)||s.setMute(n),UL(s,s).add("player-state-changed",(e=>{t.emit(JF.AUDIO_PLAY_STATE_CHANGED,BC(VC({},e),{userId:""}))})),t.listeners(JF.AUDIO_FRAME).length>0&&(t._getPCMAbortCtrl=t._room.audioManager.getPCM((i=>{t.emit(e.EVENT.AUDIO_FRAME,{data:i})}))),t._getPCMAbortCtrl&&s.on("input-media-track-changed",(()=>{t._getPCMAbortCtrl&&(t._getPCMAbortCtrl.abort("inputMediaTrackChanged"),t._getPCMAbortCtrl=t._room.audioManager.getPCM((i=>{t.emit(e.EVENT.AUDIO_FRAME,{data:i})})))})),r&&t._room.isJoined&&t._room.publish(s).catch((()=>{})),t._localAudioTrack=s,t._localAudioConfig=BC(VC({},i),{publish:r}),yield t._updateAudioPlayOption({playOption:c,track:s})}()}))}updateLocalAudio(e){return qC(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:r}=e,n={};r&&(r.microphoneId?yield this._localAudioTrack.switchDevice(r.microphoneId):pD(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),pD(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),pD(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!pD(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),pD(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),MD(this._localAudioConfig,e)}))}stopLocalAudio(){return qC(this,null,(function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),VL(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))}))}startLocalVideo(){return qC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:i,publish:r=!0,mute:n,option:o}=t,s=new AU(e._room.videoManager),a={},c={};_D(null==o?void 0:o.avoidCropping)&&(s.avoidCropping=o.avoidCropping),o&&(o.cameraId?a.deviceId=o.cameraId:pD(o.useFrontCamera)?pD(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?zk.FACING_MODE_USER:zk.FACING_MODE_ENVIRONMENT,o.qosPreference&&(a.contentHint=QF(o.qosPreference)),pD(o.profile)||(mD(o.profile)?jk[o.profile]&&s.setProfile(jk[o.profile]):s.setProfile(o.profile)),pD(o.fillMode)||(c.objectFit=o.fillMode),pD(o.mirror)||(c.mirror=o.mirror),pD(o.small)||(zM()?mD(o.small)?s.small=jk[o.small]:!0===o.small?s.small=jk["120p"]:s.small=o.small:e._log.warn("small stream is not supported"))),s.once("first-video-frame",(t=>{e.emit(JF.FIRST_VIDEO_FRAME,BC(VC({},t),{streamType:XF(t.streamType)}))})),s.on("5",(t=>{e.emit(JF.ERROR,new CF({code:SF.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),s.on("2",(t=>{e.emit(JF.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),s.on("4",(t=>{let i;t.error&&(i=CF.convertFrom(t.error)),e.emit(JF.PUBLISH_STATE_CHANGED,BC(VC({},t),{error:i}))})),e._listenOutputTrackChanged(s),yield s.capture(a),pD(n)||(yield s.setMute(n)),UL(s,s).add("player-state-changed",(t=>{e.emit(JF.VIDEO_PLAY_STATE_CHANGED,BC(VC({},t),{userId:"",streamType:"main"}))})),r&&e._room.isJoined&&e._room.publish(s).catch((()=>{})),e._localVideoTrack=s,e._localVideoConfig=BC(VC({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:s})}()}))}updateLocalVideo(e){return qC(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:r,option:n}=e,o={};if(n)if(pD(n.profile)||(mD(n.profile)?jk[n.profile]&&this._localVideoTrack.setProfile(jk[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&pD(n.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):pD(n.useFrontCamera)?pD(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?zk.FACING_MODE_USER:zk.FACING_MODE_ENVIRONMENT),pD(n.fillMode)||(o.objectFit=n.fillMode),pD(n.mirror)||(o.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(QF(n.qosPreference)),n.small){let e=!this._localVideoTrack.small;zM()?(!0===n.small?this._localVideoTrack.small=jk["120p"]:mD(n.small)?this._localVideoTrack.small=jk[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),e&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else!1===n.small&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1));this._room.isJoined&&!pD(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),pD(r)||(yield this._localVideoTrack.setMute(r)),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),MD(this._localVideoConfig,e)}))}stopLocalVideo(){return qC(this,null,(function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),VL(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return qC(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;if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:r=null,publish:n=!0,option:o}=t,s=new CU(e._room.videoManager);s.on("4",(t=>{let i;t.error&&(i=CF.convertFrom(t.error)),e.emit(JF.PUBLISH_STATE_CHANGED,BC(VC({},t),{error:i}))})),s.once("first-video-frame",(t=>{e.emit(JF.FIRST_VIDEO_FRAME,BC(VC({},t),{streamType:XF(t.streamType)}))})),e._listenOutputTrackChanged(s),"main"===t.streamType&&(s.mediaType=4);let a=null,c={},l={};o&&(pD(o.profile)||(mD(o.profile)?Gk[o.profile]&&s.setProfile(Gk[o.profile]):s.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),pD(o.fillMode)||(l.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface),o.qosPreference&&(c.contentHint=QF(o.qosPreference)));let d=yield s.capture(c);if(s.mediaTrack.addEventListener(zk.ENDED,(()=>{e._stopScreenShare(),e.emit(JF.SCREEN_SHARE_STOPPED)})),d.getAudioTracks()[0]&&(a=new wU(e._room.audioManager),yield a.setInputMediaStreamTrack(d.getAudioTracks()[0]),e._speakerId&&a.setAudioOutput(e._speakerId)),UL(s,s).add("player-state-changed",(t=>{e.emit(JF.VIDEO_PLAY_STATE_CHANGED,BC(VC({},t),{userId:"",streamType:"sub"}))})),n&&e._room.isJoined){let t=[s];if(a){t.push(a);let{echoCancellation:r}=(null==(i=a.mediaTrack)?void 0:i.getSettings())||{};if(!1===r){e._log.warn("echoCancellation of screen audio track is disable, try to open audioProcessor plugin");try{e.startPlugin("AudioProcessor",{sdkAppId:Number(e.room.sdkAppId),userId:e._room.userId,userSig:e.room.userSig,screenAudio:!0,localAudio:!1})}catch(u){e._log.warn("start audioProcessor plugin failed: ",u)}}}e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=s,e._localScreenAudioTrack=a,e._localScreenConfig=BC(VC({},t),{view:r,publish:n}),yield e._updateVideoPlayOption({view:r,playOption:l,track:s})}()}))}updateScreenShare(e){return qC(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(pD(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let e=QF(r.qosPreference);this._localScreenTrack.setContentHint(e)}this._room.isJoined&&!pD(i)&&(i&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch((()=>{}))),this._localScreenConfig.publish&&!i&&(this._room.unpublish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch((()=>{})))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),MD(this._localScreenConfig,e)}))}stopScreenShare(){return qC(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return qC(this,null,(function*(){let{view:t,userId:i,streamType:r,option:n}=e,o="".concat(i,"_").concat(r);if(this._remoteVideoConfigMap.has(o))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(r));let s=this._room.remotePublishedUserMap.get(i);if(!s)return;let a={},c="main"===r?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._listenOutputTrackChanged(c),n&&(pD(n.fillMode)||(a.objectFit=n.fillMode),pD(n.mirror)||(a.mirror=n.mirror),pD(n.poster)||(a.poster=n.poster),a.canvasRender=n.canvasRender,"main"===r&&!pD(n.small)&&(!s.remoteVideoTrack.isSubscribing&&!s.remoteVideoTrack.isSubscribed&&s.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,c.user))),yield this._room.subscribe(c),yield this._enableVideoDecodeFallback(c,r),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._emitTrackEvent(c),this._remoteVideoConfigMap.set(o,{config:e}),n&&!pD(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return qC(this,null,(function*(){var t,i;let{view:r,userId:n,streamType:o,option:s}=e,a="".concat(n,"_").concat(o),c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(n))return;let l={};s&&(pD(s.fillMode)||(l.objectFit=s.fillMode),pD(s.mirror)||(l.mirror=s.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);if("main"===o&&null!=u&&u.muteState.hasVideo&&(d=u.remoteVideoTrack),"sub"===o&&null!=u&&u.muteState.hasAuxiliary&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:h}=c;"main"===o&&s&&!pD(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:h}),MD(h,e);let p=pD(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=pD(r)?h.view:r,f=pD(null==s?void 0:s.viewRoot)?null==(i=h.option)?void 0:i.viewRoot:s.viewRoot;this._observeView({remoteTrack:d,view:m,receiveWhenViewVisible:p,viewRoot:f})}))}stopRemoteVideo(e){return qC(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return qC(this,null,(function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:n,remoteAuxiliaryTrack:o}=r;"main"===e.streamType&&(n.stop(),t.hasVideo&&i.push(n)),"sub"===e.streamType&&(o.stop(),t.hasAuxiliary&&i.push(o))}for(let e of i)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.delete(e.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)}))}_removeRemoteVideoConfig(e,t){let i="".concat(e,"_").concat(t),r=this._remoteVideoConfigMap.get(i);r&&r.observer&&r.observer.disconnect(),this._remoteVideoConfigMap.delete(i)}muteRemoteAudio(e,t){return qC(this,null,(function*(){this._remoteAudioMuteMap.set(e,t);try{if("*"===e)if(t)yield this._stopRemoteAudio({userId:e});else{let e=[...this._room.remotePublishedUserMap.values()];for(let t of e)t.muteState.hasAudio&&!this._remoteAudioConfigMap.has(t.userId)&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(pP){throw this._remoteAudioMuteMap.delete(e),pP}}))}setRemoteAudioVolume(e,t){if("*"===e){let e=[...this._room.remotePublishedUserMap.values()];for(let i of e)this._remoteAudioVolumeMap.set(i.userId,t),i.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),i&&i.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}startPlugin(e,t){return qC(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return qC(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return qC(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(t,i,r){return this.listeners(t).includes(i)||(this._log.debug("on",t),super.on(t,i,r),this._eventListened.add(t),t===e.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM((t=>{this.emit(e.EVENT.AUDIO_FRAME,{data:t})})),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",(()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM((t=>{this.emit(e.EVENT.AUDIO_FRAME,{data:t})})))})))),this}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];try{YF.has(e)&&this._log.debug("emit ".concat(e," ").concat(JSON.stringify(i)))}catch(pP){}return super.emit(e,...i)}off(t,i,r){var n,o;return this._log.debug("off",t),"*"===t?(this._eventListened.clear(),this.removeAllListeners(),null==(n=this._getPCMAbortCtrl)||n.abort("off"),delete this._getPCMAbortCtrl):(super.off(t,i,r),t===e.EVENT.AUDIO_FRAME&&(null==(o=this._getPCMAbortCtrl)||o.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},i=null,r="main",n=!1;if(mD(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 qC(this,null,(function*(){(yield Wx()).forEach((t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(JF.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),yj=t)})),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')}))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return qC(this,null,(function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let i=this._room.remotePublishedUserMap.get(t);if(!i)return;let r={},n=i.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let i=this._remoteAudioVolumeMap.get(t),o=fD(i)?i:100;r.volume=o,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),GU(yV(n,"decode-failed"),jV(yV(n,CL.INIT)),WB((()=>{this.startPlugin(vj.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})}))),yield this._updateAudioPlayOption({playOption:r,track:n}),n.outMediaTrack&&eP.emit("266",{room:this.room,type:"add",audioReference:n.outMediaTrack,refId:"ra-".concat(t)})}catch(mP){throw this._remoteAudioConfigMap.delete(t),mP}this._emitTrackEvent(n)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return qC(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)),eP.emit("266",{room:this.room,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),GU(yV(e,"decode-failed"),jV(yV(e,CL.INIT)),jB((()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})})),SB(yV(e,"decode-downgrade-state-changed")),WB((r=>{i=r.state,this.emit(JF.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,BC(VC({},r),{streamType:t,userId:e.userId}))}),(t=>{e.log.error("fallback",t)}),(()=>{"STARTED"===i&&e.log.info("fallback complete")}))))}_updateVideoPlayOption(e){return qC(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),pD(t)&&n&&n.view&&!DD(i)){let e=xD(n.view);e.length>0&&(yield r.play(e,i))}if(!pD(t)){let e=xD(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return qC(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(Ek){}if(pD(i.muted)||r.setPlayerMute(i.muted),pD(i.volume)||r.setAudioVolume(i.volume/100),r instanceof TU&&r.mediaTrack){let e=!1===i.muted&&!pD(i.volume)&&i.volume>0?"add":"remove";eP.emit("266",{room:t.room,type:e,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof JB){let e=i.muted?0:i.volume;if(pD(e))return;eP.emit("266",{room:t.room,type:"update_volume",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(JF.TRACK,{userId:i,streamType:XF(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var e,t,i,r;let n=[];if(null!=(e=this._localAudioConfig)&&e.publish&&this._localAudioTrack&&n.push(this._localAudioTrack),null!=(t=this._localVideoConfig)&&t.publish&&this._localVideoTrack&&n.push(this._localVideoTrack),null!=(i=this._localScreenConfig)&&i.publish&&(this._localScreenTrack&&n.push(this._localScreenTrack),this._localScreenAudioTrack)){n.push(this._localScreenAudioTrack);let{echoCancellation:e}=(null==(r=this._localScreenAudioTrack.mediaTrack)?void 0:r.getSettings())||{};if(!1===e){this._log.warn("echoCancellation of screen audio track is disable, try to open audioProcessor plugin");try{this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,screenAudio:!0,localAudio:!1})}catch(o){this._log.warn("start audioProcessor plugin failed: ",o)}}}if(0!==n.length)return this._room.publish(...n).catch((()=>{}))}_observeView(e){let{remoteTrack:t,view:i,receiveWhenViewVisible:r=!1,viewRoot:n}=e;if(pD(i))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(XF(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||vD(i)&&0===i.length||!r)return null==s||s.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch((()=>{})));let a=o.visibleViewMap||new Map,c=-1;(!s||s.root!==n)&&(null==s||s.disconnect(),a.clear(),s=new IntersectionObserver((e=>{e.forEach((e=>{a.set(e.target,e.isIntersecting),t.log.info("view ".concat(e.target.id," is").concat(e.isIntersecting?"":" not"," visible"))})),clearTimeout(c),c=window.setTimeout((()=>{[...a.values()].find((e=>e))?t.isSubscribed||this._room.subscribe(t).catch((()=>{})):t.isSubscribed&&this._room.unsubscribe(t).catch((()=>{}))}),200)}),{root:n}));let l=new Set(xD(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 qC(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach((e=>{this._stopRemoteAudio({userId:e}).catch()})),[...this._remoteVideoConfigMap.keys()].forEach((e=>{let t=e.includes("main")?"main":"sub",i=e.split("_".concat(t))[0];i&&this._stopRemoteVideo({userId:i,streamType:t}).catch()})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),function(e){let t=fH.get(e);t&&(t.forEach((e=>clearTimeout(e))),fH.delete(e))}(this),this._room.remotePublishedUserMap.forEach((e=>{VL(e.remoteAudioTrack),VL(e.remoteVideoTrack),VL(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return qC(this,null,(function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield null==(e=this._room)?void 0:e.unpublish(...t).catch((()=>{}))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),VL(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_onLocalTrackCaptured(e){let{track:t}=e;"audio"===t.kind&&(!yj||Ux(yj))&&(this._initActiveSpeaker(),eP.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return qC(this,null,(function*(){if(yj&&!Ux(yj))this.emit(JF.DEVICE_CHANGED,{type:"speaker",action:"active",device:yj});else{let e=yield Wx();e[0]&&!Ux(e[0])?(yj=e[0],this.emit(JF.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):eP.on("102",this._onLocalTrackCaptured,this)}}))}_onAudioAvailable(e){let{userId:t}=e,i=this._remoteAudioMuteMap.has(t)?this._remoteAudioMuteMap.get(t):this._remoteAudioMuteMap.get("*");(!1===i||this._room.autoReceiveAudio&&!i)&&this._doStartRemoteAudio({userId:t}).catch((()=>{}))}_onVideoAvailable(e){let{userId:t,streamType:i}=e;if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(t);if(r){let e="main"===i?r.remoteVideoTrack:r.remoteAuxiliaryTrack,t=[e];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&t.push(r.remoteAudioTrack),this._room.subscribe(...t).then((()=>{this._emitTrackEvent(e)})).catch((()=>{}))}}_onAudioUnavailable(e){let{userId:t,muteState:i}=e;i.hasAudio&&i.audioMuted||this._stopRemoteAudio({userId:t},!1).catch((()=>{}))}_onVideoUnavailable(e){let{userId:t,streamType:i}=e;this._stopRemoteVideo({userId:t,streamType:i},!1).catch((()=>{}))}sendSEIMessage(e,t){var i;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:BC(VC({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),IM.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),IM.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){nP.setLogLevel(e),pD(t)||(t?nP.enableUploadLog():nP.disableUploadLog())}static isSupported(){return LM()}static getCameraList(){return Fx(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return Bx(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return Wx(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(t){return qC(this,null,(function*(){if(!vN||t!==yF.SPEAKER&&t!==yF.HEADSET)(yield Wx()).forEach((e=>{e.deviceId===t&&(Tj.forEach((i=>{i._setCurrentSpeaker(t),i.emit(JF.DEVICE_CHANGED,{type:"speaker",action:"active",device:e})})),yj=e)}));else{let i=yield e.getMicrophoneList(),r="";if(i.forEach((e=>{e.label===t&&(r=e.deviceId)})),!r)return;Tj.forEach((e=>qC(this,null,(function*(){e._localAudioTrack&&(yield e.updateLocalAudio({option:{microphoneId:r}}))}))))}}))}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:o,version:s}=e;switch(s&&(SM.version=s),t){case"count":SM.addCount({key:i,useUV:o});break;case"enum":SM.addEnum({key:i,value:r,useUV:o});break;case"number":SM.addNumber({key:i,value:r,split:n})}}};zC(Ij,"_loggerManager",nP),zC(Ij,"EVENT",JF),zC(Ij,"ERROR_CODE",SF),zC(Ij,"TYPE",yF),zC(Ij,"frameWorkType",30),GC([yH({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"}})})],Ij.prototype,"use",1),GC([gH(xF.TRTC.enterRoom),zF("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})),aU((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),yH()],Ij.prototype,"enterRoom",1),GC([yH()],Ij.prototype,"exitRoom",1),GC([gH(xF.TRTC.switchRole),KF("room",{merge:(e,t)=>t}),yH()],Ij.prototype,"switchRole",1),GC([yH()],Ij.prototype,"destroy",1),GC([gH(xF.TRTC.startLocalAudio),zF("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)})),yH()],Ij.prototype,"startLocalAudio",1),GC([gH(xF.TRTC.updateLocalAudio),KF("audio",{debounce:{delay:200,getKey:()=>"".concat(Ej,"-localAudio"),isNeedToDebounce:e=>{var t;return!pD(null==(t=e.option)?void 0:t.captureVolume)}}}),yH()],Ij.prototype,"updateLocalAudio",1),GC([qF("audio"),yH()],Ij.prototype,"stopLocalAudio",1),GC([gH(xF.TRTC.startLocalVideo),zF("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)})),yH()],Ij.prototype,"startLocalVideo",1),GC([gH(xF.TRTC.updateLocalVideo),KF("video"),yH()],Ij.prototype,"updateLocalVideo",1),GC([qF("video"),yH()],Ij.prototype,"stopLocalVideo",1),GC([gH(xF.TRTC.startScreenShare),zF("screen",(()=>!0)),yH()],Ij.prototype,"startScreenShare",1),GC([gH(xF.TRTC.updateScreenShare),KF("screen"),yH()],Ij.prototype,"updateScreenShare",1),GC([yH()],Ij.prototype,"stopScreenShare",1),GC([gH(xF.TRTC.startRemoteVideo),zF((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),yH({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Ij.prototype,"startRemoteVideo",1),GC([gH(xF.TRTC.updateRemoteVideo),KF((e=>"v".concat(e.userId).concat(e.streamType))),yH({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Ij.prototype,"updateRemoteVideo",1),GC([gH(xF.TRTC.stopRemoteVideo),aU((e=>function(t){return qC(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)}))})),yH({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Ij.prototype,"stopRemoteVideo",1),GC([qF((e=>"v".concat(e.userId).concat(e.streamType)))],Ij.prototype,"_stopRemoteVideo",1),GC([gH(...xF.TRTC.muteRemoteAudio),yH({getRemoteId:e=>e})],Ij.prototype,"muteRemoteAudio",1),GC([vH(...xF.TRTC.setRemoteAudioVolume),_H(200,(e=>e)),yH({getRemoteId:e=>e})],Ij.prototype,"setRemoteAudioVolume",1),GC([IH("start"),oU((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),zF(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),yH({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>vM[e.getName()],ignoreLog:e=>"Debug"===e.getName()})],Ij.prototype,"startPlugin",1),GC([IH("update"),KF(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),yH({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>EM[e.getName()]})],Ij.prototype,"updatePlugin",1),GC([IH("stop"),qF(((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i})),yH({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>TM[e.getName()]})],Ij.prototype,"stopPlugin",1),GC([vH(...xF.TRTC.enableAudioVolumeEvaluation)],Ij.prototype,"enableAudioVolumeEvaluation",1),GC([yH()],Ij.prototype,"getVideoSnapshot",1),GC([yH()],Ij.prototype,"_setCurrentSpeaker",1),GC([zF((e=>"a".concat(e.userId)),(()=>!0))],Ij.prototype,"_startRemoteAudio",1),GC([aU((e=>function(t){return qC(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(BC(VC({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),qF((e=>"a".concat(e.userId)))],Ij.prototype,"_stopRemoteAudio",1),GC([qF("room")],Ij.prototype,"_exitRoom",1),GC([qF("screen")],Ij.prototype,"_stopScreenShare",1),GC([gH(...xF.TRTC.sendSEIMessage),vF({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}})],Ij.prototype,"sendSEIMessage",1),GC([gH(xF.TRTC.sendCustomMessage),vF({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Ij.prototype,"sendCustomMessage",1),GC([gH(xF.TRTC.create)],Ij,"_create",1);var Aj=Ij,bj=class{constructor(){zC(this,"_set",new Set),eP.on(iP.LEAVE_SUCCESS,this.delete,this)}add(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let r=this.getKey(t.userId,i||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let r=this.getKey(t.userId,t.roomId||i,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(e,t,i,r){return"".concat(i,"_").concat(t,"_").concat(e,"_").concat(r)}isJoined(e){let{userId:t,roomId:i,sdkAppId:r,room:n}=e;return"rtc"!==n.scene&&this._set.has(this.getKey(t,i,r,n.useStringRoomId))}};function Rj(){return qC(this,null,(function*(){let e,t;try{let t=yield Bx();e=t&&t.length}catch(u){}try{let e=yield Fx();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:s}=this.checkSystemResult.detail,a=aP.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:r,h264Decode:o,vp8Encode:n,vp8Decode:s},l={browser:a.browser,os:a.os,trtc:c,devices:i},d={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};BL.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),BL.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var Cj=jC(JC()),kj="1",wj="2",Dj="3",Nj="4",Oj="5",Pj="6",Mj={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},Lj=[Mj.UPDATE_REMOTE_MUTE_STAT,Mj.UPLINK_NETWORK_STATS,Mj.USER_LIST_RES,Mj.MUTE_RESULT,Mj.SERVER_FIRST_PACKAGE_RECEIVED,Mj.RECEIVE_CUSTOM_MSG],xj={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"},Uj="publish_change",Vj="join",Bj="leave",Fj="quality_report",Hj="mute_uplink",Wj="publish",jj="publish_state_change",Gj="unpublish",zj="subscribe",Kj="unsubscribe",qj="subscribe_change",Jj="start_publishing",Yj="stop_publishing",Xj="start_push_user_cdn",Qj="stop_push_user_cdn",Zj="start_mcu_mix",$j="stop_mcu_mix",eG="start_publish_cdn_stream",tG="update_publish_cdn_stream",iG="stop_publish_cdn_stream",rG="get_user_list",nG="change_role",oG="update_constraint_config",sG="rebuild_pc",aG="join/v2",cG="publish/v2",lG="subscribe/v3",dG="ability_status_report",uG="reconnect",hG="channel_msg",pG=new Set;var mG=class extends Cj.default{constructor(e){var t,i,r;super(),zC(this,"room"),zC(this,"sdkAppId"),zC(this,"userId"),zC(this,"userSig"),zC(this,"url"),zC(this,"backupUrl"),zC(this,"destroyed",!1),zC(this,"_socketInUse"),zC(this,"_socket"),zC(this,"_backupSocket"),zC(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[]}),zC(this,"_currentState","DISCONNECTED"),zC(this,"_isReconnecting",!1),zC(this,"_seq",0),zC(this,"_log"),zC(this,"_lastMessageTime",-1),zC(this,"_connectStartTime",-1),zC(this,"_stopConnectRetry"),zC(this,"bytesSent",0),zC(this,"bytesReceived",0),zC(this,"keepAlive",!1),zC(this,"signalDomainWhenUnifiedProxy"),zC(this,"stopKeepAliveTimeout"),zC(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-pG.size>0&&this.room.enableSPC&&(this.keepAlive=!0,pG.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=nP.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));this.signalDomainWhenUnifiedProxy&&(e+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy)));let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+="&clientIp=".concat(t)),this.race?"".concat(e,"&race=1"):e}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return"CONNECTED"===this._currentState}get isConnecting(){return"CONNECTING"===this._currentState}get isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return qC(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=RD();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 bD(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?zk.BACKUP:zk.MAIN),e.emitConnectionStateChanged("CONNECTED")}()}))}connectWS(e){let{url:t,timeout:i,isMain:r}=e,n=new WebSocket(t);this.bindSocket(n),r?this._socket=n:this._backupSocket=n;let o=-1;return new Promise(((e,t)=>{n.onclose=t,n.onerror=t,n.onopen=()=>e(n),i&&(o=setTimeout((()=>{this.unbindAndCloseSocket(r?zk.MAIN:zk.BACKUP),t(new ck({code:sk.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===zk.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(Ew){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(Ew){}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(Oj,new ck({code:sk.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(zk.MAIN),this.unbindAndCloseSocket(zk.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Oj,new ck({code:sk.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=HD(e.data);let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values(Mj),o=Object.keys(Mj)[n.indexOf(i)],s=xj[o]||i;switch(Lj.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case Mj.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,r.svrTime&&function(e){lk=e-(new Date).getTime();let t=new Date;t.setTime(e),nP.info("baseTime from server: ".concat(t," offset: ").concat(lk))}(r.svrTime),this._log.info("ChannelSetup Success ".concat(RD()-this._connectStartTime)),IM.addSuccessEvent({key:521701,cost:RD()-this._connectStartTime}),this._connectStartTime=-1,this.emit(kj,{signalInfo:this._signalInfo});else{let e=new ck({code:sk.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:hM({key:cM.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),IM.addFailedEvent({key:521701,error:e}),this.emit(Oj,e)}break;case Mj.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=r.relayOuterIp,this._signalInfo.relayInnerIp=r.relayInnerIp,this._signalInfo.bakRelayIps=r.bakRelayIps,this._signalInfo.relayPort=r.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=r.endReportExtend,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(s,{data:t});break;default:this.emit(String(s),{data:t})}}reGetSignalChannelUrl(){return qC(this,null,(function*(){try{if(!this.room.joinParams)return;iH(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(vk){}}))}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?zk.MAIN:zk.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return qC(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:uG,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:xj.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),IM.addSuccessEvent({key:521702,cost:RD()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(IM.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(vk){this._log.error(vk),this.room.reJoin()}}}))}send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let i={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},r=JSON.stringify(i);return this._socketInUse.send(r),this.bytesSent+=HD(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:o,enableLog:s=!0,addReceiveTime:a=!1}=e;return new Promise(((e,c)=>{let l=setTimeout((()=>{this.off(n,d);let e=new ck({code:sk.API_CALL_TIMEOUT,message:hM({key:cM.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),c(e)}),r),d=t=>{t.data.seq===u&&(clearTimeout(l),this.off(n,d),a&&(t.data.receiveTime=Date.now()),e(t))};this.on(n,d);let u=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:r=0,retryTimeout:n=0}=e;return nN({retryFunction:this.sendWaitForResponse,onError:e=>{let{retry:t}=e;this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(Dj,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),pG.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(zk.MAIN),this.unbindAndCloseSocket(zk.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var e;let t=null==(e=this._signalInfo.bakRelayIps)?void 0:e.shift();return t&&(t.relayPort=t.relayPort||this._signalInfo.relayPort),t}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(e,"s")),this.stopKeepAliveTimeout=setTimeout((()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close(),this.off(xj.JOIN_ROOM_RESULT,t)}),1e3*e);let t=e=>{0===e.data.code&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(xj.JOIN_ROOM_RESULT,t))};this.on(xj.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(wj,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(Dj):"DISCONNECTED"===e&&this.emit(Pj))}};GC([HL({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn("retrying to connect ".concat(e)),e>=3&&e%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],mG.prototype,"connect",1);var fG=jC(JC()),_G=0,gG=!1,vG=new Set,EG=!1,TG=class{constructor(e){zC(this,"userId"),zC(this,"tinyId"),zC(this,"_sdpSemantics"),zC(this,"_isUplink"),zC(this,"_room"),zC(this,"_log"),zC(this,"_signalChannel"),zC(this,"_isErrorObserved",!1),zC(this,"_waitForPeerConnectionConnectedPromise"),zC(this,"_waitForPeerConnectionConnectedPromiseReject",null),zC(this,"_peerConnection",null),zC(this,"_emitter",new fG.default),zC(this,"_currentState","DISCONNECTED"),zC(this,"_isReconnecting",!1),zC(this,"_reconnectionCount",0),zC(this,"_reconnectionTimer",-1),zC(this,"_isFirstConnection",!0),zC(this,"_prevTime",-1),zC(this,"_localAddress"),zC(this,"_remoteAddress"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=nP.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=RD())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,IM.addSuccessEvent({key:521705,cost:Math.min(RD()-this._prevTime,3e4)})):this._isReconnecting&&IM.addSuccessEvent({key:521706,cost:RD()-this._prevTime}),this._prevTime=-1}catch(hP){throw this._isFirstConnection?(this._isFirstConnection=!1,IM.addFailedEvent({key:521705,error:hP})):this._isReconnecting&&this._reconnectionCount>=3&&IM.addFailedEvent({key:521706,error:hP}),hP}}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(),vG.delete(this)}closePeerConnection(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,e&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new ck({code:sk.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return mw;let e=null;if(this._isUplink){if(!JM()||0===this._peerConnection.getSenders().length)return mw;e=this._peerConnection.getSenders()[0].transport}else{if(!qM()||0===this._peerConnection.getReceivers().length)return mw;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:mw}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===fw.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===fw.FAILED||e.target.connectionState===fw.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new ck({message:r,code:sk.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===fw.CONNECTED||e.target.connectionState===fw.COMPLETED)&&(this.logSelectedCandidate(),BL.logSuccessEvent({userId:this._room.userId,eventType:yw.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(_G=0,gG=!1,EG=!0,vG.add(this)):vG.delete(this),eP.emit(iP.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 qC(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(FM(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 ck({code:sk.API_CALL_ABORTED,message:hM({key:cM.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{eP.off(iP.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new ck({code:sk.API_CALL_TIMEOUT,message:"connection timeout"});_G+=1,(e=>_G>2&&!gG&&0===vG.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),gG=!0,this._emitter.emit("firewall-restriction")),t(e)}),Pw);eP.on(iP.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(Dj,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=vw()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new ck({code:this._isUplink?sk.UPLINK_RECONNECTION_FAILED:sk.DOWNLINK_RECONNECTION_FAILED,message:hM({key:this._isUplink?cM.UPLINK_RECONNECTION_FAILED:cM.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(Dj,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)}};GC([_U(521712,!1)],TG.prototype,"setOffer",1),GC([_U(521713,!1)],TG.prototype,"setAnswer",1);var yG=jC(rk()),SG=function(e){return yG.default.parse(e)},IG=function(e){return yG.default.write(e)};function AG(e){return Object.keys(e).filter((t=>e[t]))}var bG=class e extends TG{constructor(e){super(BC(VC({},e),{isUplink:!1})),zC(this,"_flag",0),zC(this,"isRobot",!1),zC(this,"role","anchor"),zC(this,"remoteAudioTrack"),zC(this,"remoteVideoTrack"),zC(this,"remoteAuxiliaryTrack"),zC(this,"ssrc",{audio:0,video:0,auxiliary:0}),zC(this,"_isSDPExchanging",!1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new JB(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new hF(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new pF(this._room,this)}get videoCodec(){var e,t;let i=null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)?void 0:t.sdp;return i?i.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return ND(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===zk.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let t=e.streams[0],{track:i}=e,r=t.id===rw?zk.MAIN:zk.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=zk.AUDIO;i.kind===zk.VIDEO&&(n=r===zk.MAIN?zk.VIDEO:zk.AUXILIARY);let o=this.remoteAudioTrack;n===zk.VIDEO?o=this.remoteVideoTrack:n===zk.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=SG(e);return t.media.forEach((e=>{e.type===zk.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),IG(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=SG(e);return i.media.forEach((e=>{e.ext&&(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),IG(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return qC(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===fw.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===fw.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(Ek){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Ek.message," ").concat(JSON.stringify(this.muteState))),new ck({code:sk.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Ek}}))}unsubscribe(e){return qC(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=VC({},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(AG(e),"]")),yield t.sendSubscription(n,e),"unsubscribe"===n&&(t.closePeerConnection(),t.emitConnectionStateChangedEvent("DISCONNECTED"))}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=Kj,n=xj.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=qj,n=xj.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 ck({code:i.code,message:hM({key:cM.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return qC(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(Ew){throw e.closePeerConnection(!0),Ew}}()}))}exchangeSDP(e){return qC(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:xj.SUBSCRIBE_RESULT,timeout:Aw});if(!this._peerConnection){let e=new ck({code:sk.INVALID_OPERATION,message:hM({key:cM.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(Ew){throw this._isSDPExchanging=!1,Ew}}))}createOffer(){return qC(this,null,(function*(){let e={voiceActivityDetection:!1};XM()&&this._sdpSemantics===bw?(this._peerConnection.addTransceiver(zk.AUDIO,{direction:Kk.RECVONLY}),this._peerConnection.addTransceiver(zk.VIDEO,{direction:Kk.RECVONLY}),this._peerConnection.addTransceiver(zk.VIDEO,{direction:Kk.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield MM();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=SG(e);return t.media.forEach((e=>{var t,i;if(e.type===zk.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(" ")}})),IG(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=SG(e);return t.media.forEach((e=>{e.type===zk.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),IG(t)}(t.sdp),this._sdpSemantics===bw&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)}))}onSubscribeResult(e){return qC(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===Cw)throw new ck({code:sk.NOT_SUPPORTED_H264,message:hM({key:cM.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new ck({code:t,message:hM({key:cM.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(mP){throw this._log.error(mP),mP}}))}updateSSRC(e){try{SG(e).media.forEach((e=>{if(e.ssrcs)if(e.type===zk.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(rw)}));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(rw)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(nw)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(Ew){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return qC(this,null,(function*(){if(!(KC(e.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(Ew){let t=dD(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}};GC([aU((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 ck({code:sk.API_CALL_ABORTED,message:hM({key:cM.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],bG.prototype,"subscribe",1),GC([_U(521717,!1)],bG.prototype,"unsubscribe",1),GC([oU(TG.prototype.afterConnect),nU(TG.prototype.beforeConnect)],bG.prototype,"connect",1);var RG=bG,CG={voiceActivityDetection:!1},kG=class e extends TG{constructor(e){super(BC(VC({},e),{isUplink:!0})),zC(this,"localMainAudioTrack",null),zC(this,"localMainVideoTrack",null),zC(this,"localAuxAudioTrack",null),zC(this,"localAuxVideoTrack",null),zC(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),zC(this,"_isPublishingAux",!1),zC(this,"_publishingLocalAudioTrack"),zC(this,"_publishingLocalVideoTrack"),zC(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}),zC(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(YM()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(i=o[2])||!i.track),n.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((e=>{e.track&&(e.track.kind===zk.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return qC(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(),XM()?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 qC(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||zk.AUDIO,{direction:Kk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?zk.VIDEO:s||zk.VIDEO,{direction:Kk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||zk.VIDEO,{direction:Kk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||zk.VIDEO,{direction:Kk.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:zk.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:zk.VIDEO,videoType:o?zk.AUXILIARY:zk.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:zk.VIDEO,videoType:zk.SMALL}),e.push(2))}yield t.setTransceiverDirection(Kk.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 qC(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 qC(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(Kk.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Kk.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 qC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!YM())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=BC(VC({},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=BC(VC({},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(Kk.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 qC(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:jj,data:t,responseCommand:xj.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:Gj,commandDesc:"unpublish",responseCommand:xj.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===sk.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),rL){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:oG,data:this._mediaSettings,responseCommand:xj.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return qC(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?zk.AUXILIARY:zk.MAIN," stream")),XM()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return qC(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===zk.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===Kk.INACTIVE&&(yield this.setTransceiverDirection(Kk.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return qC(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;YM()&&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===zk.VIDEO&&e instanceof AU&&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===Rw||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=SG(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===zk.VIDEO)return!0;return!1}removeSender(e){let t=null;YM()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&hD(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return qC(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?zk.AUXILIARY:zk.MAIN," stream")),XM()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return qC(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===zk.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(Kk.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return qC(this,null,(function*(){if(!SN)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(Kk.INACTIVE,"|").concat(Kk.RECVONLY,"|").concat(Kk.SENDONLY,")")))&&o++,t.includes(o)){if(e===Kk.INACTIVE&&i.includes("a=".concat(Kk.RECVONLY)))return r=!0,"a=".concat(e);if(e===Kk.SENDONLY&&i.includes("a=".concat(Kk.INACTIVE)))return r=!0,"a=".concat(Kk.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:s}))}))}removeTrackBySender(e){return qC(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===zk.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===zk.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===zk.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return qC(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=XM()?e.kind===zk.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?zk.AUXILIARY:zk.MAIN," stream")),e.kind===zk.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===zk.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack)),!0}))}updateOffer(e,t){return qC(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(CG);SN&&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===zk.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:r,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(n.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:Uj,data:n,responseCommand:xj.UPDATE_OFFER_RESULT,timeout:Iw,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(pP){throw this._log.error(pP),pP}}))}setBandwidth(e){return qC(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!tL())return o?r===zk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(XM()){let t=0;r===zk.VIDEO&&(t=n===zk.SMALL?2:n===zk.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(pM){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(pM)),o)return r===zk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";SN&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===zk.SMALL?n=1:i===zk.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(o+=1,o===n?"".concat(e,"b=").concat(r,":").concat(t,"\r\n"):e)))}updateAudioBandwidthRestriction(e,t){let i="AS";return SN&&(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 qC(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(vk){throw this.closePeerConnection(!0),this.uninstallEvents(),vk}}))}exchangeSDP(){return qC(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(vk){throw vk}}))}createOffer(){return qC(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(CG);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(vk){throw vk}}))}doExchangeSDP(){let e={command:Wj,responseCommand:xj.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof CU||this.localAuxVideoTrack instanceof CU,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then((e=>{let{code:t,message:i,data:r}=e.data;return 0===t?this.acceptAnswer(r):this.checkPublishResultCode(t,i)}))}setSDPDirection(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"all",r=SG(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),IG(r)}acceptAnswer(e){return qC(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?zk.AUXILIARY:zk.BIG;s=yield this.setBandwidth({bandwidth:e,type:zk.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:zk.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:zk.VIDEO,videoType:zk.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this.setAnswer(a),this._log.debug("accepted answer: ".concat(s))}catch(s){throw this._log.error("failed to accept remote answer ".concat(s)),s}}))}sendMutedFlag(e){var t,i,r;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let n={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(i=this.localMainVideoTrack)||!i.muted),auxVideo:!(null==(r=this.localAuxVideoTrack)||!r.muted)};this._log.info("send muted state: ".concat(JSON.stringify(n))),this._signalChannel.send(Hj,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return qC(this,null,(function*(){if(!(KC(e.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Gj,responseCommand:xj.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(Ew){let t=dD(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)&&eP.emit(iP.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{SG(e).media.forEach(((e,t)=>{if(e.type===zk.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===Rw&&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(Ew){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:zk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===zk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===zk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===zk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===zk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Cw?(this._log.error(lM.NOT_SUPPORTED_H264ENCODE),new ck({code:sk.NOT_SUPPORTED_H264,message:hM({key:cM.NOT_SUPPORTED_H264ENCODE})})):new ck({code:sk.UNKNOWN,message:hM({key:cM.SIGNAL_RESPONSE_FAILED,data:{signalResponse:xj.PUBLISH_RESULT,code:e,message:t}})})}};GC([aU((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 ck({code:sk.API_CALL_ABORTED,message:hM({key:cM.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],kG.prototype,"publish",1),GC([_U(521715,!1)],kG.prototype,"unpublish",1),GC([oU(TG.prototype.afterConnect),nU(TG.prototype.beforeConnect)],kG.prototype,"connect",1);var wG=kG,DG=class{constructor(e,t){this.room=e,zC(this,"_log"),zC(this,"_prevReportTime",0),zC(this,"_prevReport",{}),zC(this,"_prevStats",null),zC(this,"_prevEncoderImplementation",""),zC(this,"_prevAuxEncoderImpl",""),zC(this,"_prevQualityLimitationReason",""),zC(this,"_prevAuxQualityLimitationReason",""),zC(this,"_prevDecoderImplementationMap",new Map),zC(this,"totalBytesSent",0),zC(this,"totalBytesReceived",0),zC(this,"_spcStats",null),this._log=t}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return qC(this,null,(function*(){var t;let i={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},r=e.getPeerConnection(),n=e.getSSRC();if(r)try{if((this._spcStats||(yield r.getStats())).forEach((t=>{var r,o,s;let a,c;if("outbound-rtp"===t.type)if((t.mediaType||t.kind)===zk.VIDEO){if(t.ssrc===n.video?(a=zk.VIDEO,c=e.localMainVideoTrack):t.ssrc===n.small?a=zk.SMALL:t.ssrc===n.auxiliary&&(c=e.localAuxVideoTrack,a=zk.AUXILIARY),!a)return;if(i[a].bytesSent=t.bytesSent,i[a].packetsSent=t.packetsSent,i[a].framesEncoded=t.framesEncoded,pD(t.keyFramesEncoded)||(i[a].keyFramesEncoded=t.keyFramesEncoded),pD(t.nackCount)||(i[a].nackCount=t.nackCount),pD(t.pliCount)||(i[a].pliCount=t.pliCount),pD(t.retransmittedPacketsSent)||(i[a].retransmittedPacketsSent=t.retransmittedPacketsSent),pD(t.totalEncodeTime)||(i[a].totalEncodeTime=t.totalEncodeTime),pD(t.totalPacketSendDelay)||(i[a].totalPacketSendDelay=t.totalPacketSendDelay),!pD(t.encoderImplementation)&&(a===zk.VIDEO&&this._prevEncoderImplementation!==t.encoderImplementation||a===zk.AUXILIARY&&this._prevAuxEncoderImpl!==t.encoderImplementation)){let i=2,r=this._prevEncoderImplementation;a===zk.AUXILIARY&&(i=7,r=this._prevAuxEncoderImpl),eP.emit("262",{userId:e.userId,streamType:i,prevImplementation:r,implementation:t.encoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientEncoder}),this[a===zk.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=t.encoderImplementation,this._log.info("".concat(a===zk.AUXILIARY?"aux ":"","encoderImplementation change to ").concat(t.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(t.powerEfficientEncoder))}t.ssrc===n.video?!pD(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),eP.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:null==(r=e.localMainVideoTrack)?void 0:r.isQosClearFirst}),this._prevQualityLimitationReason=t.qualityLimitationReason):t.ssrc===n.auxiliary&&!pD(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),eP.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(o=e.localAuxVideoTrack)?void 0:o.isQosClearFirst}),this._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else i.audio.bytesSent=t.bytesSent,i.audio.packetsSent=t.packetsSent;else"candidate-pair"===t.type?FM(t)&&(this.totalBytesSent=t.bytesSent,fD(t.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*t.currentRoundTripTime))):"media-source"===t.type&&(t.kind===zk.AUDIO?(i.audio.audioLevel=t.audioLevel||0,i.audio.totalAudioEnergy=t.totalAudioEnergy||0,t.echoReturnLoss,t.totalSamplesDuration&&(i.audio.totalSamplesDuration=t.totalSamplesDuration)):t.kind===zk.VIDEO&&(t.trackIdentifier===e.getVideoTrackId(zk.VIDEO)?i.video.fpsCapture=t.framesPerSecond:t.trackIdentifier===e.getVideoTrackId(zk.AUXILIARY)?i.auxiliary.fpsCapture=t.framesPerSecond:i.small.fpsCapture=t.framesPerSecond));if(!pD(t.audioLevel)&&null!=(s=e.localMainAudioTrack)&&s.mediaTrack&&t.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(i.audio.audioLevel=t.audioLevel||0),!pD(t.frameWidth)){let r=zk.SMALL;t.trackIdentifier===e.getVideoTrackId(zk.VIDEO)||t.ssrc===n.video?r=zk.VIDEO:(t.trackIdentifier===e.getVideoTrackId(zk.AUXILIARY)||t.ssrc===n.auxiliary)&&(r=zk.AUXILIARY),i[r].frameWidth=t.frameWidth,i[r].frameHeight=t.frameHeight,i[r].framesSent=t.framesSent}})),e.localMainAudioTrack){let t=e.localMainAudioTrack.getInternalAudioLevel();i.audio.micAudioLevel=t,0===i.audio.audioLevel&&(i.audio.audioLevel=t)}this.totalBytesSent||(this.totalBytesSent+=i.audio.bytesSent+i.video.bytesSent+i.auxiliary.bytesSent),Object.keys(i).forEach((t=>{t===zk.AUDIO?(e.localMainAudioTrack&&(e.localMainAudioTrack.stat=i[t]),e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=i[t])):t===zk.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=i[t]):t===zk.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=i[t])}))}catch(Ek){this._log.warn("failed to getStats on sender connection ".concat(Ek))}return 0===i.rtt&&(i.rtt=(null==(t=this.room.networkQuality)?void 0:t.uplinkRTT)||0),i}))}getReceiverStats(e){return qC(this,null,(function*(){var t,i,r;let n={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},o=e.getPeerConnection();if(o)try{let{ssrc:r}=e,{muteState:s,subscribeState:a}=e;(this._spcStats||(yield o.getStats())).forEach((t=>{if("inbound-rtp"===t.type){let i=(t.mediaType||t.kind)===zk.AUDIO;if(i){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);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(SN&&0===t.bytesReceived)return;let i;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,i=e.remoteVideoTrack,s.hasSmall&&a.smallVideo&&(n.isSmallSubscribed=!0),t.decoderImplementation&&(!this._prevDecoderImplementationMap.has(n.userId)||this._prevDecoderImplementationMap.get(n.userId)!==t.decoderImplementation)&&(this._log.info("".concat(n.userId," decoderImplementation change to ").concat(t.decoderImplementation," HWDecoder: ").concat(t.powerEfficientDecoder)),eP.emit("262",{userId:this.room.userId,remoteUserId:n.userId,prevImplementation:this._prevDecoderImplementationMap.get(n.userId),implementation:t.decoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(n.userId,t.decoderImplementation))),t.ssrc===r.auxiliary&&s.hasAuxiliary&&(n.auxiliary.packetsReceived=t.packetsReceived,n.auxiliary.bytesReceived=t.bytesReceived,n.auxiliary.packetsLost=t.packetsLost,n.auxiliary.framesReceived=t.framesReceived,n.auxiliary.framesDecoded=t.framesDecoded,n.auxiliary.fpsDecoded=t.framesPerSecond,i=e.remoteAuxiliaryTrack,n.hasAuxiliary=!0),i&&(i.stat.packetsReceived=t.packetsReceived,i.stat.bytesReceived=t.bytesReceived,i.stat.packetsLost=t.packetsLost,i.stat.framesReceived=t.framesReceived,i.stat.framesDecoded=t.framesDecoded,t.jitterBufferDelay&&(i.stat.jitterBufferDelay=Math.floor(t.jitterBufferDelay/t.jitterBufferEmittedCount*1e3)))}t.jitterBufferDelay&&(i?(n.audio.totalJitter=t.jitterBufferDelay,n.audio.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.video&&s.hasVideo?(n.video.totalJitter=t.jitterBufferDelay,n.video.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.auxiliary&&s.hasAuxiliary&&(n.auxiliary.totalJitter=t.jitterBufferDelay,n.auxiliary.totalJitterCount=t.jitterBufferEmittedCount))}else"candidate-pair"===t.type&&FM(t)&&(this.totalBytesReceived=t.bytesReceived,fD(t.currentRoundTripTime)&&(n.rtt=Math.floor(1e3*t.currentRoundTripTime)));pD(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)),!pD(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),pD(null==(t=e.remoteVideoTrack.player.stat)?void 0:t.fps)||(n.video.fpsRender=e.remoteVideoTrack.player.stat.fps),pD(null==(i=e.remoteAuxiliaryTrack.player.stat)?void 0:i.fps)||(n.auxiliary.fpsRender=e.remoteAuxiliaryTrack.player.stat.fps)}catch(mP){this._log.warn("failed to getStats on receiver connection ".concat(mP))}return 0===n.rtt&&(n.rtt=(null==(r=this.room.networkQuality)?void 0:r.uplinkRTT)||0),n}))}getStats(e,t){return qC(this,null,(function*(){let i={},r=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:i,receiverStats:r};let t=RD(),n=yield e.getStats(),o=RD();o-t>2e3&&this._log.warn("getStats cost ".concat(o-t,"ms"));let s=[],a=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);n.forEach((e=>a.has(e.type)&&s.push(e))),this._spcStats=s}e&&(i=yield this.getSenderStats(e));for(let[e,n]of t){let e=yield this.getReceiverStats(n);r.push(e)}return{senderStats:i,receiverStats:r}}))}getDifferenceValue(e,t){if(Zx(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r}=e;var n;if(!Zx(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*ZP,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*ZP),t.senderStats.audio.totalSamplesDuration&&(i.msg_device_info.uint32_audio_capture_cost=t.senderStats.audio.totalSamplesDuration);let r=[];if(t.senderStats.video.bytesSent){let e={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};r.push(e)}if(t.senderStats.small.bytesSent){let e={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};r.push(e)}if(t.senderStats.auxiliary.bytesSent){let e={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};r.push(e)}let n={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:e,msg_video_status:r,msg_network_status:n}}let{statInterval:o}=this;i.msg_down_stream_info=[],t.receiverStats.forEach((e=>{let t={msg_user_info:{str_identifier:e.userId,uint64_tinyid:e.tinyId},msg_network_status:{uint32_rtt:e.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(e.hasAudio){let i={uint32_audio_p2p_delay:e.audio.p2pDelay,uint32_audio_cache_ms:e.audio.totalJitter,uint32_audio_cache_ms_count:e.audio.totalJitterCount,uint32_audio_codec_bitrate:e.audio.bytesReceived,uint32_audio_total_bitrate:e.audio.bytesReceived,uint32_audio_level:1e8*e.audio.audioLevel,uint32_audio_energy:1e6*e.audio.totalAudioEnergy,uint32_audio_receive:e.audio.packetsReceived,uint32_audio_origin_lost:e.audio.packetsLost};t.msg_audio_status=i}if(e.hasVideo){let i=r.get("".concat(e.userId,"_").concat(ow)),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};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=r.get("".concat(e.userId,"_").concat(sw)),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};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let s=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(i)),this._prevStats=JSON.parse(JSON.stringify(t)),i.msg_up_stream_info.msg_audio_status&&s.msg_up_stream_info.msg_audio_status){let e=s.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let r=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*r/o),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}null!=(n=s.msg_device_info)&&n.uint32_audio_capture_cost?i.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(s.msg_device_info.uint32_audio_capture_cost,i.msg_device_info.uint32_audio_capture_cost)/o):delete i.msg_device_info.uint32_audio_capture_cost}let c=s.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=c.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type));if(!t||0===t.uint32_video_codec_bitrate)return e.uint32_video_codec_bitrate=0,e.uint32_video_enc_fps=0,void(e.uint32_video_codec_fps=0);let r=0,n=0,s=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(r=t.uint32_video_codec_bitrate,n=t.uint32_video_enc_fps,s=t.uint32_video_codec_fps);let a=this.getDifferenceValue(r,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*a/o),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(n,e.uint32_video_enc_fps)/o),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(s,e.uint32_video_codec_fps)/o),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),pD(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),pD(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),pD(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),pD(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),pD(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/o)),pD(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/o))}));let l=s.msg_down_stream_info;i.msg_down_stream_info=i.msg_down_stream_info.filter((e=>l.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid))));let d=i.msg_down_stream_info;return d.forEach((e=>{let t=l.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(Zx(e.msg_audio_status)||Zx(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,r=t.msg_audio_status,n=this.getDifferenceValue(r.uint32_audio_cache_ms_count,i.uint32_audio_cache_ms_count);delete i.uint32_audio_cache_ms_count,i.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(r.uint32_audio_cache_ms,i.uint32_audio_cache_ms)/n)||0;let s=this.room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);s&&(s.remoteAudioTrack.stat.jitterBufferDelay=i.uint32_audio_cache_ms),i.uint32_audio_origin_lost=this.getDifferenceValue(r.uint32_audio_origin_lost,i.uint32_audio_origin_lost),i.uint32_audio_receive=this.getDifferenceValue(r.uint32_audio_receive,i.uint32_audio_receive),i.uint32_audio_receive+=i.uint32_audio_origin_lost;let a=this.getDifferenceValue(r.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*a/o),i.uint32_audio_total_bitrate=Math.round(8*a/o)}if(e.msg_video_status&&t.msg_video_status){let i=t.msg_video_status;e.msg_video_status=e.msg_video_status.filter((e=>i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)))),e.msg_video_status.forEach((e=>{let t=i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)),r=t.uint32_video_receive,n=t.uint32_video_origin_lost,s=t.uint32_video_codec_bitrate,a=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(n,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(r,e.uint32_video_receive)+e.uint32_video_origin_lost;let l=this.getDifferenceValue(s,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/o);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/o),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/o);let u=this.getDifferenceValue(t.uint32_video_cache_ms_count,e.uint32_video_cache_ms_count);delete e.uint32_video_cache_ms_count,e.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(t.uint32_video_cache_ms,e.uint32_video_cache_ms)/u)||0}))}})),a&&t.receiverStats.forEach((e=>{if(e.audio.concealedSamples&&e.audio.totalSamplesReceived){let t=a.receiverStats.find((t=>t.userId===e.userId));if(t&&t.audio.concealedSamples&&t.audio.totalSamplesReceived){let i=e.audio.concealedSamples-t.audio.concealedSamples,r=e.audio.totalSamplesReceived-t.audio.totalSamplesReceived,n=Math.floor(i/r*1e3*o);if(n>1e3*o/5){let t=d.find((t=>t.msg_user_info.str_identifier===e.userId));t&&(t.msg_audio_status.uint32_audio_block_time=n)}}}})),i}getStatsReport(e){return qC(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:r,freezeMap:n}=e;return function*(){let e={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield t.getStats(i,r);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:n}),t._prevReportTime=Date.now(),e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},NG=jC(JC());function OG(e){return new Promise((t=>qC(this,null,(function*(){let i=setTimeout((()=>{t({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})}),1e4),r=Date.now(),n="https://".concat(e,"/?t=").concat(r);try{yield fetch(n)}catch(Ek){}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=BC(VC({},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 PG=class e extends NG.default{constructor(e){let{signalChannel:t,room:i}=e;super(),zC(this,"_room"),zC(this,"_signalChannel"),zC(this,"_log"),zC(this,"uplinkRTT",0),zC(this,"uplinkLoss",0),zC(this,"downlinkRTT",0),zC(this,"downlinkLoss",0),zC(this,"pingResults",{}),zC(this,"_downlinkPrevStatMap",new Map),zC(this,"_downlinkLossAndRTTMap",new Map),zC(this,"_interval",-1),zC(this,"_uplinkNetworkQuality",0),zC(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=nP.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:i}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(t,", loss: ").concat(i," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(xj.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(wj,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 qC(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)===fw.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 qC(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!qM())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&&fD(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===zk.AUDIO||e.mediaType===zk.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return 0===t.rtt&&(t.rtt=this.uplinkRTT),t}catch(_P){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!==fw.DISCONNECTED&&e.connectionState!==fw.FAILED&&e.connectionState!==fw.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=PL.run("ric",(()=>{var t;this.handleDownlinkNetworkQuality();let i=[...this._downlinkLossAndRTTMap.values()];eP.emit(iP.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=BC(VC({},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=>OG(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=>{IM.addSuccessEvent({key:521718,cost:e.cost})})),this._log.warn("All ping results: ".concat(JSON.stringify(e)))})).catch((e=>{this._log.warn("Error during pinging domains: ".concat(e))}))}}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.debug("stopped"),-1!==this._interval&&(PL.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})}}))}};zC(PG,"EVENT_NETWORK_QUALITY","0"),zC(PG,"lastPingTime",0);var MG=PG;var LG=class{constructor(e){zC(this,"_frameWorkType"),zC(this,"_component"),zC(this,"_language"),zC(this,"connectionType"),zC(this,"_room"),zC(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0}),zC(this,"_keyPrefix"),zC(this,"_log"),zC(this,"_intervalId"),zC(this,"_firstPublishedUserList"),zC(this,"_networkQuality"),zC(this,"_basicInfo"),zC(this,"_pathJoinRoom"),zC(this,"_pathLeaveRoom"),zC(this,"_pathMainVideoMap"),zC(this,"_pathMainAudioMap"),zC(this,"_pathAuxiliaryMap"),zC(this,"_remoteStreamStatMap"),zC(this,"_localStreamStat"),zC(this,"_eventMap",new Map),zC(this,"_captureCostSum",0),zC(this,"_captureCostCount",0),zC(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=nP.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&hD(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 yD(o)?o.catch((e=>nP.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(Ew){nP.error("".concat(t.name,"() error observed ").concat(Ew))}}}({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:_k,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:"live"===this._room.scene?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,GO().then((e=>{this._basicInfo.string_os_version=XO(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),eP.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(iP.JOIN_START,this.handleJoinStart).addEvent(iP.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(iP.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(iP.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(iP.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(iP.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(iP.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(iP.JOIN_FAILED,this.handleJoinFailed).addEvent(iP.LEAVE_START,this.handleLeaveStart).addEvent(iP.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(iP.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(iP.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(iP.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(iP.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(iP.PUBLISH_START,this.handlePublishStart).addEvent(iP.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(iP.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(iP.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(iP.PLAY_TRACK_START,this.handlePlayStart).addEvent(iP.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(iP.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!t.isRemote||!this.hitTest(t.room)||"PLAYING"===i&&(r===zk.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(iP.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(iP.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(iP.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(iP.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(iP.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)=>eP.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),PL.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&&(pD(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),pD(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),pD(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 ck?Number(i.getExtraCode()||i.getCode()):sk.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}handleJoinFailed(e){let{room:t,error:i}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=i.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout((()=>{this.report()})))}handleReceivedPublishUserList(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(e,t){var i;let r="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(r)){let n={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:BC(VC({},UG),{msg_user_info:new VG({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 VG({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,IM.addNumber({key:516820,value:e})}}0===(null==r?void 0:r.statsToReport.uint64_render_first_frame_time)&&(r.statsToReport.uint64_render_first_frame_time=i)}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=this._pathMainAudioMap.get(t);i&&0===i.statsToReport.uint64_play_first_frame_time&&(i.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(e){this.hitTest(e.room)&&(this._networkQuality.totalUplinkLoss+=e.uplink.loss,this._networkQuality.totalUplinkRTT+=e.uplink.rtt,this._networkQuality.count++,e.downlinks.forEach((e=>{let{rtt:t,loss:i,userId:r,videoDelay:n,audioDelay:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(s)s.totalRTT+=t,s.totalLoss+=i,n&&(s.totalVideoDelay=(s.totalVideoDelay||0)+n,s.videoDelayCount=(s.videoDelayCount||0)+1),o&&(s.totalAudioDelay=(s.totalAudioDelay||0)+o,s.audioDelayCount=(s.audioDelayCount||0)+1),s.count++;else{let e,s,a,c;n&&(s=n,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_device_info:t,msg_up_stream_info:i,msg_down_stream_info:r}=e.report;if(i.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:t,uint32_video_width:r,uint32_video_height:n}=i.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=t,this._localStreamStat.totalVideoWidth+=r,this._localStreamStat.totalVideoHeight+=n,this._localStreamStat.videoCount++}if(i.msg_audio_status){let{uint32_audio_level:e}=i.msg_audio_status;Math.floor(e/ZP*100)>0&&(this._localStreamStat.totalAudioLevel+=e/ZP,this._localStreamStat.audioLevelCount++)}r.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:r}=e,n=t.str_identifier,o=this._room.remotePublishedUserMap.get(n);if(r.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,r="".concat(n,"_").concat(t?"main":"auxiliary"),s=this._remoteStreamStatMap.get(r);if(s&&(t&&null!=o&&o.remoteVideoTrack.isSubscribed||i&&null!=o&&o.remoteAuxiliaryTrack)){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*xC(10,6)))}})),!DD(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/ZP*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/ZP,t.audioLevelCount++))}})),t.uint32_audio_capture_cost&&(this._captureCostSum+=t.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart(e){let{room:t}=e;this.hitTest(t)&&0===this._localStreamStat.publishStartTime&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof ck?i.getExtraCode()||i.getCode():sk.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&Yk))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Zk))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Qk))>=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,zk.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,zk.VIDEO)),e.statsToReport.uint32_video_render_first&&(e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,xG));let{badCaseDetector:o}=this._room,{dataFreeze:s,count:a}=o.getDataFreezeDuration(t),{renderFreeze:c}=o.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=a,e.statsToReport.uint32_video_block_time=Math.min(s,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),o.isBlackStream(t)&&0===e.statsToReport.uint32_video_avg_fps?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>xG&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+xG):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>xG&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+xG):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>xG&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+xG)}getReportData(){this._basicInfo.uint32_networkType=eD();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new VG({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:PD(this._signalInfo.relayIp),uint32_client_ip:PD(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*xC(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map((e=>e.statsToReport)),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map((e=>e.statsToReport)),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map((e=>e.statsToReport)),uint32_info_client_ip:PD(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return zD(e),e}report(){return qC(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(hP){this._log.warn(hP)}finally{this.isDestroyed&&(this._room=null)}}))}upload(e){return qC(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=yield QD(e),r=i instanceof ArrayBuffer,n="".concat(Yw(t,Lk.KEY_POINT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i));let s=[this.uploadKVStat(IM),this.uploadKVStat(SM)];o||s.push(XD({url:n,body:i,priority:"low"})),yield Promise.all(s)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return qC(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=BC(VC({},t.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(t);let i=yield QD(t),r="".concat(Yw(+this._room.sdkAppId,Lk.KV_STAT),"&gzip=").concat(+(i instanceof ArrayBuffer)),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(r,i)),n||XD({url:r,body:i})}))}};GC([HL({settings:{timeout:500,retries:3}})],LG.prototype,"upload",1);var xG=5e3,UG={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},VG=class{constructor(e){zC(this,"str_identifier"),zC(this,"str_tinyid"),zC(this,"uint32_role"),this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},BG=LG,FG=class{constructor(){zC(this,"_startTime"),zC(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=RD())}stop(){0===this._endTime&&(this._endTime=RD())}getDuration(){return 0===this._endTime?RD()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},HG=class{constructor(e){zC(this,"_room",null),zC(this,"_durationMap"),zC(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(iP.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(iP.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(iP.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"),zk.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_main"),zk.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_auxiliary"),zk.VIDEO);let s=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);s&&(!i.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,zk.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,zk.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,zk.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>eP.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>eP.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 FG,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===zk.AUDIO?[n]:[],video:t===zk.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()}},WG=class{constructor(e){zC(this,"_room"),zC(this,"_renderFreezeMap",new Map),zC(this,"_isVideoPlayingEventFiredMap",new Map),zC(this,"_dataFreezeMap",new Map),zC(this,"_monitorFreezeData",new Map),zC(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(iP.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(iP.PLAY_TRACK_START,this.onPlayTrackStart).set(iP.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(iP.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(iP.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(t.isRemote&&t.room&&this.hitTest(t.room)&&n===zk.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===zk.MUTE?this.onVideoTrackMuted(t):r===zk.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(iP.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>eP.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>eP.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 FG;n?n.durationItemList.push(o):this._dataFreezeMap.set(r,{userId:t,type:i,durationItemList:[o],isFreezing(){let e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i);this.stopDataFreeze({key:r,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;this.hitTest(t)&&i.msg_down_stream_info.forEach((e=>{let t=this._room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);if(!t)return;let{userId:i,muteState:r}=t;e.msg_video_status.forEach((e=>{2===e.uint32_video_stream_type&&r.hasVideo&&!r.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"main"}),7===e.uint32_video_stream_type&&r.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"auxiliary"})}))}))}stopDataFreeze(e){let{key:t,userId:i,type:r}=e,n=this._dataFreezeMap.get(t);if(!n||!n.isFreezing())return;let o=n.durationItemList[n.durationItemList.length-1];o.stop();let s=o.getDuration();s>ww?this._monitorFreezeData.set(t,{userId:i,type:r,duration:s}):n.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return qC(this,arguments,(function(e){var t=this;let{userId:i,fps:r,type:n}=e;return function*(){let e="".concat(i,"_").concat(n),o=t._renderFreezeMap.get(e);if(r<=2){let r=RD();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:r,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(e,{userId:i,type:n,isFreeze:!0,freezeTimeline:[{startTime:r,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let e=o.freezeTimeline.pop();if(e){e.endTime=RD();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room)||t.kind!==zk.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()<ww&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){let t=this._renderFreezeMap.get(e),i=0,r=0;if(t)if(t.isFreeze){let e=RD()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;i=t.renderFreezeTotal+Math.min(e,5e3),r=t.freezeTimeline.length}else i=t.renderFreezeTotal;return{renderFreeze:i,count:r}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},jG=jC(JC(),1),GG=[1,0,0,0,1,1,0,1],zG=class extends QB{constructor(e,t){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:t}),e instanceof dF)try{this.setTexBuffer(GG)}catch(Ew){e.destroy(new ck({code:sk.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(Ew.message||Ew)}))}}draw2d(e,t,i,r,n){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let o=super.draw2d(e,t,i,r,n);return this.ctx2d.restore(),o}return!1}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}},KG=class{constructor(e,t){this.node=e,this.layout=t,zC(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}},qG=class extends QB{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),zC(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new KG(e,t);this.inputs[t.zIndex]=i}resize(e,t){let i=this.inputs.reduce(((e,t)=>t?Object.assign(e,{width:Math.max(e.width,t.right),height:Math.max(e.height,t.bottom)}):e),{width:0,height:0});super.resize(i.width,i.height),this.context instanceof dF&&this.inputs.forEach((e=>{if(e){let t=this.layout2texCoords(e);e.positionBuffer?this.changeBufferData(e.positionBuffer,t):e.positionBuffer=this.createBuffer(t)}}))}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return super.connect(e,...i),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex((t=>(null==t?void 0:t.node)===e))]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&(t.node.useTexture(),this.draw(t.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&this.draw2d(t.node.image,t.x,t.y,t.width,t.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:i,width:r,height:n,name: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},VC({parent:this.inputs.filter((e=>e)).map((e=>e.node.getInfo()))},this.lastInfo)}close(){super.close(),this.inputs.forEach((e=>{var t,i;if(e&&(null==(t=e.node)||t.disconnect(),e.positionBuffer&&this.context instanceof dF))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(_P){}}))}},JG=class extends sF{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}),zC(this,"_bgTexture"),zC(this,"_waterMarkTexture"),zC(this,"_lastMaskTexture"),zC(this,"_lastMaskFbo"),zC(this,"_textureValid",!1),zC(this,"_selfieTextureValid",!1),zC(this,"_selfieSegmentation"),zC(this,"wasm"),zC(this,"_prePrograme"),zC(this,"_segmentationMask"),zC(this,"_weixin",!1),t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(t)}catch(pP){e.log.error(pP),e.destroy(new ck({code:sk.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(pP.message||pP)}))}}init(e){let t=e.Wasm,i=this.context.ctx;if(this.wasm=new t.AllIn1(i),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:i,width:r,height:n}=e.waterMark;this.wasm.setWaterMark(t,i,r,n)}if(e.beautyParams){let{beauty:t,brightness:i,ruddy:r}=e.beautyParams;this.wasm.setBeauty(t,i,r,null==e?void 0:e.width,null==e?void 0:e.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),i.uniform1i(i.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(i.uniform1i(i.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(i.uniform1i(i.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),i.uniform1i(i.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(i.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\nuniform sampler2D u_texture;\nuniform sampler2D mask;\n\nin vec2 v_texCoord;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);\n}"),t=this.context.createShader(i.VERTEX_SHADER,"#version 300 es\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_texCoord;\nvoid main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n v_texCoord = a_texCoord;\n}");this._prePrograme=this.context.createProgram(t,e),i.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),i.uniform1i(i.getUniformLocation(this._prePrograme,"mask"),1)}}onPredict(e){var t;let i=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():null==this||this._selfieSegmentation.bindTexture(),i.activeTexture(i.TEXTURE1),null==(t=this._selfieSegmentation)||t.bindTexture2d(e),i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,this._bgTexture||null),i.activeTexture(i.TEXTURE3),i.bindTexture(i.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),i.drawArrays(i.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}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){var t,i,r,n;let o=this.context.ctx,{image:s}=this;this.tryVideoFrameCallback();let{videoWidth:a,videoHeight:c}=s;if(0===a||0===c||!this.available)return!1;s.width=a,s.height=c;let l=!1;if(this.totalFrames)this._weixin?this.useTexture():null==(t=this._selfieSegmentation)||t.bindTexture(),l=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),l=this._textureValid,this._textureValid=!0}return this.width===a&&this.height===c&&l?o.texSubImage2D(o.TEXTURE_2D,0,0,0,o.RGBA,o.UNSIGNED_BYTE,s):(this.resize(a,c),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,s)),this._weixin&&(o.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(o.activeTexture(o.TEXTURE1),null==(i=this._selfieSegmentation)||i.bindTexture2d(this._segmentationMask),o.bindFramebuffer(o.FRAMEBUFFER,this._lastMaskFbo||null)),o.drawArrays(o.TRIANGLE_STRIP,0,4),null==(r=this._selfieSegmentation)||r.bindTexture(),this._segmentationMask?o.copyTexSubImage2D(o.TEXTURE_2D,0,0,0,0,0,a,c):o.copyTexImage2D(o.TEXTURE_2D,0,o.RGBA,0,0,a,c,0)),this.wasm.vbMode&&(null==(n=this._selfieSegmentation)||n.send(a,c)),this.totalFrames||(o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this._bgTexture||null),o.activeTexture(o.TEXTURE3),o.bindTexture(o.TEXTURE_2D,this._waterMarkTexture||null),o.drawArrays(o.TRIANGLE_STRIP,0,4)),!1}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&t.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&t.deleteProgram(this._prePrograme),null==(e=this.wasm)||e.close()}},YG=class extends QB{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 }"}),zC(this,"yTextureRef"),zC(this,"uTextureRef"),zC(this,"vTextureRef"),zC(this,"Y"),zC(this,"U"),zC(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)}},XG=[e=>{e.codec="avc1.420028"},e=>{delete e.hardwareAcceleration}],QG=(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 ZG=0,$G=class{constructor(e){zC(this,"id",ZG++),zC(this,"trackDoneOB"),zC(this,"startOB"),zC(this,"stopOB"),zC(this,"decoder"),zC(this,"videoContext"),zC(this,"gop",0),zC(this,"gop_helper",0),zC(this,"waitFirstKeyFrame",!0),zC(this,"startTimestamp",0),zC(this,"startTime",0),zC(this,"startPerformanceTime",0),zC(this,"inputFrameCount",0),zC(this,"decodedFrameCount",0),zC(this,"decodeFrameCount",0),zC(this,"downgradeLevel",0),zC(this,"lastDowngradeTime",0),zC(this,"lastFrameDiff",0),zC(this,"lastDecodeFrameTimestamp",0),zC(this,"config"),zC(this,"gop_before_configure",[]),zC(this,"videoElement"),zC(this,"type","wasm"),zC(this,"goodType"),zC(this,"renderer","2d"),zC(this,"wasmOption"),zC(this,"createDecoder"),zC(this,"_decodeSink"),zC(this,"isReported",!1),zC(this,"track"),zC(this,"stateChangeOB"),zC(this,"failedReason");let{track:t,createDecoder:i}=e;if(this.stateChangeOB=uV(),this.track=t,this.createDecoder=i,this.wasmOption={yuvMode:"webgl"===e.renderer,wasmPath:e.wasmPath,workerMode:e.workerMode,canvas:e.canvas},this.config=e.config,this.videoElement=e.videoElement,this.renderer=e.renderer,this.trackDoneOB=yV(t.availableState,CL.OFF),this.stopOB=uV(),"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),GU(this.stateChangeOB,uB(((e,i)=>(e!==i&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:e,state:i}),i)),"INITIALIZED"),jV(this.stopOB),WB()),this.start()}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=GU(this.pipe(this.track),jV(this.stopOB),ZU());GU(t,WB((()=>{this.track.stat.framesDecoded++}),(t=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(t," retryCount: ").concat(e)),IM.addFailedEvent({key:QG(this.type,this.renderer),error:t}),e>4)this.failedReason=t,this.stateChangeOB.next("FAILED");else{if(this.goodType)return void this.start(e);switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":if("webgl"===this.renderer)this.changeRenderer("videoFrame")}this.start(e+1)}}),(()=>{this.track.log.warn("".concat(this.id," decoderOB completed")),IM.addSuccessEvent({key:QG(this.type,this.renderer)}),IM.addSuccessEvent({key:514704})}))),GU(t,WV(1),WB((()=>{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&&!OM()&&(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(!function(e){return 0===e[0]&&0===e[1]&&0===e[2]&&1===e[3]}(n)||n.length<5)return this.stateChangeOB.next("FAILED"),this.close("not h26x frame ".concat(n.subarray(0,5))),e;let o=!1;switch(31&n[4]){case 5:case 7:o=!0}if("configured"!==(null==(i=this.decoder)?void 0:i.state))return this.track.log.debug("not configured ".concat(this.inputFrameCount)),o&&(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:s}=e;if(o?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!o)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(n.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=s,this.startTime=Date.now(),this.startPerformanceTime=RD()}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(s," ").concat(null==(r=e.getMetadata)?void 0:r.call(e).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=s,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=>qC(this,null,(function*(){this._decodeSink=t;let i,r=e.mediaTrack;t.defer((()=>{var t;r&&(e.player.setCanvas(),e.setInputMediaStreamTrack(r)),null==i||i.close(),null==(t=this.videoContext)||t.destroy(),delete this._decodeSink}));let{renderer:n,type:o}=this;e.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(o){case"wasm":i=this.createDecoder(o,this.wasmOption);break;case"webCodecs":for(let e=0;e<=XG.length;e++){let{supported:i}=yield VideoDecoder.isConfigSupported(this.config);if(i)break;if(e===XG.length)return void t.error(3);XG[e](this.config)}i=this.createDecoder(o);break;default:throw new Error("not supported yet")}let r=0;if(i.on("videoFrame",(i=>{this.decodedFrameCount++,r++,(r<=10||r%500==0)&&e.log.debug("frame ".concat(r," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(i.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&("webCodecs"===this.type?this.checkDowngradeByFrameDiff():"wasm"===this.type&&this.checkDowngradeByTimestampDiff(i.timestamp)),t.next(i)})),i.on("error",(i=>{e.log.error(i),t.error("webCodecs"===o?4:8)})),yield i.initialize(this.videoElement),!this._decodeSink)return;if(i.configure(this.config),"wasm"===o&&"webgl"===n){this.videoContext=new dF({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(dF.UNAVAILABLE,(i=>{e.log.error(i),t.error(7)}));let r=new YG(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 uF({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 eF(this.videoContext,{name:"remotePlayer",logger:e.log});r.connect(n),e.source=r,e.player.setCanvas(this.videoContext._canvas,2)}this.decoder=i}catch(mP){e.log.error(mP),t.error("webCodecs"===o?2:6)}}))}},ez=class extends jG.EventEmitter{constructor(e){super(),this.room=e,zC(this,"videoContext"),zC(this,"_glVideoContext"),zC(this,"_2dVideoContext"),zC(this,"destination"),zC(this,"smallVideoContext"),zC(this,"smallDestination"),zC(this,"smallTrackSource"),zC(this,"smallImageSource"),zC(this,"_isMirror",!1),zC(this,"cameraTrack"),zC(this,"cameraNode"),zC(this,"mirrorNode"),zC(this,"mixNode"),zC(this,"screenTrack"),zC(this,"screenNode"),zC(this,"selfModel",!1),zC(this,"blurRadius",3),zC(this,"arTrack"),zC(this,"Wasm"),zC(this,"waterMarkNode"),zC(this,"_waterMarkOption"),zC(this,"watermarkImageList",[]),zC(this,"_beautyParams"),zC(this,"isUsingArTrack",!1),zC(this,"_isMixScreen",!1),zC(this,"_virtualBackground"),zC(this,"_virtualBackgroundAbortCallback"),zC(this,"virtualBackgroundInstance"),zC(this,"_bgAssetPath"),zC(this,"log",nP.createLogger({id:"vm"})),zC(this,"_checkId",0),zC(this,"_use2d",!1),zC(this,"_autoSwitchRenderMode",!0),zC(this,"_selfieSegmentation"),zC(this,"encodePipeline",[]),zC(this,"decodePipeline",[]),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new uF({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode="auto"===e,this._autoSwitchRenderMode)return;let t="2d"===e;this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new uF({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new dF({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on(dF.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(vk){this.emit("error",vk)}}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=PL.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(),PL.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(RO||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(){let e=arguments.length>1?arguments[1]:void 0,t="videoCtxGl"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"videoCtxGl")?512700:512701;e?IM.addFailedEvent({key:t,error:e}):IM.addSuccessEvent({key:t})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else{if(!t)return!0;if(!this._use2d)return!0;this.clear()}}else{if(this._glVideoContext=new dF({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return null==(e=this.smallDestination)?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return null==(e=this.cameraTrack)?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}setSmallVideo(e,t){if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new rF(this.smallVideoContext,e,this.log),this.smallVideoContext.on(dF.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;this.setSmallVideo(r,e),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._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info("set main output ".concat(o?o.label:"no output track")),i.setOutputMediaStreamTrack(o)}catch(pP){this.log.error("set main output failed",pP)}}update(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return qC(this,null,(function*(){var t,i,r;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:n,profile:o}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),16===NO?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof sF?(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 sF?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(n.width,n.height)):e&&this.cameraNode&&this.destination?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new iF(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new JG(this.videoContext,{input:this.initialTrack,width:n.width,height:n.height,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=o.frameRate,this._use2d){let e=this.cameraNode;e.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new zG(this.videoContext,this.log)),e=e.connect(this.mirrorNode),e.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new qG(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):null==(t=this.waterMarkNode)||t.resize(n.width,n.height),null==(i=this.waterMarkNode)||i.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),null==(r=this.screenNode)||r.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)}))}changeInput(e){var t,i,r,n;if(e instanceof CU)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof AU)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof hF){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);let t=e.mediaTrack;return e.setOutputMediaStreamTrack(t)}this.log.warn("change unknown input",null==(n=e.mediaTrack)?void 0:n.label)}removeInput(e){var t;e instanceof CU?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof AU?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof hF&&e.source&&e.source.context.destroy()}setCameraTrack(e){return qC(this,null,(function*(){this.cameraTrack=e,this.update(!0)}))}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return qC(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 ck({code:sk.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort(((e,t)=>e.zIndex-t.zIndex)),this.watermarkImageList.forEach((e=>{let{image:t,x:i,y:n,width:o,height:s}=e;r.drawImage(t,i,n,o,s)})),jD(i.toDataURL())}))}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some((t=>t.imageUrl===e.imageUrl&&t.height===e.height&&t.width===e.width&&t.x===e.x&&t.y===e.y&&t.type===e.type&&t.zIndex===e.zIndex))||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==t))),this.watermarkImageList.push(e))}setBeautyParams(e){return qC(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return qC(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return qC(this,null,(function*(){var t,i;let r;try{r=yield jD((null==e?void 0:e.imageElement)||e.imageUrl)}catch(d){throw new ck({code:sk.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:n=0,y:o=0,width:s=r.width,height:a=r.height,type:c="watermark",zIndex:l=2}=e;this.watermarkImageList.some((e=>e.type===c))?(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==c)),this.pushWaterMarkImageList({x:n,y:o,width:s,height:a,image:r,zIndex:l,type:c,imageUrl:e.imageUrl}),r=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(i=this.cameraTrack)?void 0:i.settings.height),this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(r.width,r.height),this.waterMarkNode.image=r):this.update()):(this.pushWaterMarkImageList({x:n,y:o,width:s,height:a,image:r,zIndex:l,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,((e,t)=>"imageUrl"===e?void 0:t)))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return qC(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 qC(this,null,(function*(){var e,t,i;null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let r=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(i=this.cameraTrack)?void 0:i.settings.height);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()}))}setVirtualBackground(e){return qC(this,null,(function*(){if(e){if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,"image"===e.type?this._virtualBackground=yield jD(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}else delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;if(this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat((null==e?void 0:e.type)||"",", ").concat(this.blurRadius||"")),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new ck({code:sk.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})}))}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return qC(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 $G(e)}clear(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(e){let{processor:t,type:i}=e;var r;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:i}=e;var r;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}};GC([sU((function(e){this.log.error("update failed",e)}))],ez.prototype,"update",1);var tz=0,iz=class extends CL{constructor(e){super("room"),zC(this,"seq",++tz),zC(this,"sdkAppId"),zC(this,"userId"),zC(this,"userSig"),zC(this,"privateMapKey"),zC(this,"latencyLevel"),zC(this,"tinyId"),zC(this,"scene"),zC(this,"roomId"),zC(this,"useStringRoomId"),zC(this,"role","anchor"),zC(this,"joinParams",null),zC(this,"localTracks",new Set),zC(this,"enableAutoPlayDialog",!0),zC(this,"autoReceiveAudio",!0),zC(this,"autoReceiveVideo",!0),zC(this,"proxy_ws"),zC(this,"proxy_wt"),zC(this,"proxy_unified"),zC(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}}),zC(this,"keyPointManager"),zC(this,"audioManager"),zC(this,"videoManager"),zC(this,"callDurationCalculator"),zC(this,"badCaseDetector"),zC(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),zC(this,"videoDecodeFallbackType"),zC(this,"_isUsingCachedSchedule",!1),zC(this,"_log",nP.createLogger({id:"r".concat(this.seq)})),zC(this,"_joinedTimestamp",0),zC(this,"_sdkType"),zC(this,"heartbeatReport"),zC(this,"quality"),zC(this,"enableSEI"),zC(this,"isDestroyed",!1),this.useStringRoomId=!!e.useStringRoomId,_D(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),_D(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),_D(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new BG({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new HG({room:this}),this.badCaseDetector=new WG({room:this}),this.audioManager=new NU(this),this.videoManager=new ez(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(4&e.mediaType)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(2&e.mediaType)return e;return null}getLogger(){return this._log}get isJoining(){return"joining"===this.state.toString()}get isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return qC(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return qC(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return qC(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(mD(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(cD(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?(oH([o,o]),Ak("https://".concat(o))):(r&&Ak(r),n&&oH(n))}eP.once(iP.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:nH.main,sched_back_domain:nH.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return qC(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return qC(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 qC(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 ck({code:sk.INVALID_OPERATION,message:hM({key:cM.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(lM.INVALID_DESTROY),new ck({code:sk.INVALID_OPERATION,message:hM({key:cM.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,eP.emit(iP.ROOM_DESTROY,{room:this})}schedule(e,t){return qC(this,null,(function*(){var i,r,n;let o=RD();try{let{isCached:s,result:a,detailCost:c}=yield rH({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:_k,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(BD(a,{keysToExclude:["username","credential"]}))),s&&eP.once(iP.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=VC(VC({},this.scheduleResult),a),fD(null==(i=a.config)?void 0:i.retryCount)&&gw(a.config.retryCount),mD(null==(r=a.config)?void 0:r.loggerDomain)&&Ak(a.config.loggerDomain),this.videoDecodeFallbackType=(null==(n=a.config)?void 0:n.videoDecodeFallback)||this.videoDecodeFallbackType,eP.emit(iP.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:c}),IM.addSuccessEvent({key:521700,cost:RD()-o,split:50})}catch(s){throw IM.addFailedEvent({key:521700,error:s}),s}}))}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}},rz=jC(JC()),nz=jC(rk());function oz(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 sz=(e,t)=>qC(void 0,null,(function*(){var i;let r=SG(e),n={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};n.ice.ufrag=String(r.media[0].iceUfrag),n.ice.password=r.media[0].icePwd||"",r.fingerprint&&(n.dtls.hash=r.fingerprint.type,n.dtls.fingerprint=r.fingerprint.hash,n.dtls.setup=r.setup||""),r.media[0].fingerprint&&(n.dtls.hash=r.media[0].fingerprint.type,n.dtls.fingerprint=r.media[0].fingerprint.hash),n.dtls.setup=r.media[0].setup||"";let o=r.media[0],s=r.media[1];o.ext&&(n.audio.extensions=o.ext.map((e=>({id:e.value,uri:e.uri})))),s.ext&&(n.video.extensions=s.ext.map((e=>({id:e.value,uri:e.uri}))));let a={codec:o.rtp[0].codec,fmtp:o.fmtp[0].config,payload:o.fmtp[0].payload,rate:o.rtp[0].rate,channels:o.rtp[0].encoding,rtcpfb:[],rtx:0};null==(i=o.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:r}=e;if(t===a.payload){let e={id:i,params:[]};r&&e.params.push(r),a.rtcpfb.push(e)}})),n.audio.codecs.push(a);let c=["h264","vp8"];return t&&c.shift(),n.video.codecs=[...oz(s)].filter((e=>c.includes(e.codec.toLocaleLowerCase()))),n.video.decoders=(yield function(){return qC(this,null,(function*(){let e=new RTCPeerConnection;e.addTransceiver(zk.VIDEO,{direction:zk.TRANSCEIVER_DIRECTION_RECVONLY});let t=yield e.createOffer();if(!t.sdp)return[];let i=oz(SG(t.sdp).media[0]);return e.close(),i}))}()).filter((e=>["h264","vp8"].includes(e.codec.toLocaleLowerCase()))),n})),az=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,o=SG(r),s={extmapAllowMixed:"extmap-allow-mixed",groups:o.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},a={candidates:t.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:zk.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:o.media[0].port,protocol:o.media[0].protocol,type:zk.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map((e=>({payload:t.audio.codecs[0].payload,type:e.id,subtype:e.params[0]}))),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};return s.media.push(a),[1,2,3].forEach((e=>{s.media.push(cz({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),n&&s.media.push(o.media.find((e=>"dc"===e.mid))),IG(s)},cz=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,isDownlink:o=!1}=e,s={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:zk.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:zk.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=>{lz(s,e)}))}else{let e=i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264"))),t=i.video.codecs[e]||r.video.codecs[0];lz(s,t)}return s},lz=(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 dz=(e,t,i)=>{let r=nz.default.parse(e);return r.media.forEach(((e,n)=>{var o;if((e.type===zk.AUDIO||e.type===zk.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===zk.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===zk.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===zk.VIDEO))if(n<4)e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach((t=>lz(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=>lz(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")})),nz.default.write(r)},uz=jC(JC()),hz=class extends uz.EventEmitter{constructor(e){super(),this.room=e,zC(this,"mainFpsHealth",1),zC(this,"mainBitrateHealth",1),zC(this,"badMainBitrateHealthCount",0),zC(this,"lastEmitBadHealthTime",0),zC(this,"log"),!vN&&TO&&eP.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(){eP.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};zC(hz,"EVENT_BAD_HEALTH","bad_health");var pz=hz;function mz(e){let{seiMessageList:t,isAudio:i,isMain:r}=e;return new TransformStream({transform(e,n){let o=e;i?audioEncodePipeline.forEach((e=>{o=e({frame:o})})):videoEncodePipeline.forEach((e=>{o=e({frame:o,seiMessageList:t,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:o.data,userId:"",streamType:r?"main":"auxiliary"})}})})),n.enqueue(o)}})}function fz(e,t,i){return new TransformStream({transform(r,n){let o=r;videoDecodePipeline.forEach((r=>{o=r({frame:o,onSEI:i=>{i.forEach((i=>{self.postMessage({type:"sei",seiPayloadType:i.seiPayloadType,data:i.seiPayload.buffer,userId:e,streamType:t})}))},onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:o.data,userId:e,streamType:t})}})})),n.enqueue(o)}})}var _z=(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))(_z||{}),gz=0,vz=!1,Ez=new Set,Tz=1,yz=class extends rz.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),zC(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),zC(this,"currentState","DISCONNECTED"),zC(this,"_room"),zC(this,"_signalChannel"),zC(this,"_peerConnection",null),zC(this,"_datachannel",null),zC(this,"_enableCustomMessage"),zC(this,"_log"),zC(this,"_downlinkMIDMap",new Map),zC(this,"_downlinkMIDUserIDMap",new Map),zC(this,"_reconnectionTimer",-1),zC(this,"reconnectionCount",0),zC(this,"clientAbility"),zC(this,"_serverAbility",null),zC(this,"addDownlinkQueue",new Set),zC(this,"removeDownlinkQueue",new Set),zC(this,"_parsedAnswer",null),zC(this,"_updateSDPPromise",null),zC(this,"_waitForPCConnectedPromise"),zC(this,"clearWaitForConnectedPromise"),zC(this,"clearConnectTimeout"),zC(this,"_isSDPLogged",!1),zC(this,"enableInsertableStreams",!1),zC(this,"insertableStreamsAbortMap",new Map),zC(this,"receiverRemoteTrackMap",new WeakMap),zC(this,"scriptTransformWorker"),zC(this,"_isRelayTried",!1),zC(this,"_rttOverCount",0),zC(this,"originOffer",null),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=nP.createLogger({id:"spc".concat(Tz++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(oL?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((e=>"h264"===e.codec.toLowerCase()))),e}addAbortController(e,t){var i;null==(i=this.insertableStreamsAbortMap.get(e))||i.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find((e=>"vp8"===e.codec.toLowerCase()))),e}get videoCodec(){var e,t;let i=null==(e=this._parsedAnswer)?void 0:e.media[1].rtp.find((e=>["h264","vp8"].includes(e.codec.toLowerCase())));return i?i.codec.toLowerCase():null!=(t=this._serverAbility)&&t.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return null!=(e=this._serverAbility)&&e.video.decoders.find((e=>"h264"===e.codec.toLowerCase()))?"h264":"vp8"}get isUsingH264(){return"h264"===this.videoCodec}get is42001fSupported(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f")))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=SG(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&&!pD(e.ssrcs[0].id)){let n=Number(e.ssrcs[0].id),o=Number(null==(r=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:r.id);switch(t){case 0:i.audioSsrc=n;break;case 1:i.bigVideoSsrc=n,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=n,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=n,i.auxVideoRtxSsrc=o}}})),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(e){let{isAux:t}=e;this.useHWEncoder(!1,t?7:2)}initScriptTransformWorker(){sL&&(this.scriptTransformWorker=function(e){let t=[yU],i=[WH,FH,HH,BH,mz,fz],r="const videoEncodePipeline=[".concat(e.videoEncodePipeline.toString(),"];\n const videoDecodePipeline=[").concat(e.videoDecodePipeline.toString(),"];\n const audioEncodePipeline = [").concat(e.audioEncodePipeline.toString(),"];\n const audioDecodePipeline = [").concat(e.audioDecodePipeline.toString(),"];"),n="(()=>{".concat(t.map((e=>"const ".concat(e.name,"=(()=>").concat(e.toString(),")()"))).join("\n"),"\n").concat(i.map((e=>e.toString())).join("\n"),";(").concat((()=>{let e=[],t=[],i=[];self.onmessage=r=>{"sei"===r.data.type&&(r.data.isMain?(e.push(r.data.data),r.data.small&&i.push(r.data.data)):t.push(r.data.data))},self.onrtctransform=r=>{let{options:n}=r.transformer,o=n.isReceiver?fz(n.userId,n.streamType,n.isAudio):mz({isAudio:n.isAudio,seiMessageList:n.isMain?n.small?i:e:t,isMain:n.isMain});r.transformer.readable.pipeThrough(o).pipeTo(r.transformer.writable)}}),")();").concat(r,"})()"),o=new Blob([n],{type:"text/javascript"}),s=URL.createObjectURL(o),a=new Worker(s);return URL.revokeObjectURL(s),a}({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{"sei"===e.data.type&&this.emit("sei-message",e.data),"dump"===e.data.type&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e)})}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}getPeerConnectionConfig(e){var t;let i={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=null==(t=this._peerConnection)?void 0:t.getConfiguration().encodedInsertableStreams;return tN(r)&&(i.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(i)),i}initialize(e){return qC(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(),IM.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):"failed"===e&&IM.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var e;let t=(null==(e=this._peerConnection)?void 0:e.signalingState)||"";this._log["closed"===t?"debug":"info"]("signaling state: ".concat(t))},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=e=>this.emit("track",e),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=e=>{let t=new Iz(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(zk.AUDIO,{direction:zk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(zk.VIDEO,{direction:zk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(zk.VIDEO,{direction:zk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(zk.VIDEO,{direction:zk.TRANSCEIVER_DIRECTION_SENDONLY}),i=yield this._peerConnection.createOffer(),this.clientAbility=yield sz(i.sdp,(null==(t=this._room.scheduleResult.config)?void 0:t.remove264FromSDP)||!1),this.originOffer=i,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;e&&(this._log.debug("dtls state: ".concat(e.state)),"connecting"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():"connected"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()))}),IM.addSuccessEvent({key:521707}),this.clientAbility}catch(_P){throw IM.addFailedEvent({key:521707,error:_P}),this._log.error("initialize failed ".concat(_P," \noffer: ").concat(null==i?void 0:i.sdp)),_P}}))}setIceServers(e){return qC(this,null,(function*(){var t;if(this._peerConnection&&0!==e.length)try{if(this._log.info("setIceServers",JSON.stringify(e)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),null!=(t=this._peerConnection)&&t.localDescription||!this.originOffer)return void this._log.warn("setIceServers already has localDescription or no origin Offer");yield this.setOffer(this.originOffer)}catch(pP){this._log.warn("setIceServers error ",pP)}}))}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(Ew){this._log.warn("setPriority error ",Ew)}}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return qC(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=RD(),s={type:"answer",sdp:az({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(s),yield this.waitForPeerConnectionConnected();let a=(null==(r=this._room.scheduleResult.config)?void 0:r.priority)||(null==(n=this._room.joinParams)?void 0:n.priority)||new URLSearchParams(location.search).get("priority");a&&this.setPriority(a),t||IM.addSuccessEvent({key:521703,cost:RD()-o})}catch(mP){let i=mP instanceof ck&&mP.code===sk.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(mP),e),this.reset(),!i&&!this.isReconnecting&&(IM.addFailedEvent({key:521703,error:mP}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),mP}}))}reconnect(){return qC(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(Dj,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=VC({ability:t},e),r=yield this._signalChannel.sendWaitForResponse({command:sG,responseCommand:xj.REBUILD_PEER_CONNECTION_RES,data:i,enableLog:!1});if(0!==r.data.code)throw new ck({code:r.data.code,message:r.data.message});yield this.connect(r.data.data.ability,!0),IM.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),eP.emit(iP.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(vk){if(!this.isReconnecting)return;if(null!=vk&&vk.message.includes("timeout")){let e=dD(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield KD(e,(e=>{this._reconnectionTimer=e})),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(null==vk?void 0:vk.code," ").concat(vk)),IM.addFailedEvent({key:521704,error:vk}),this.reconnectionCount>=vw()&&this._log.warn("SDK has tried reconnect for ".concat(vw()," 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 qC(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(Dj,this.reconnect,this),"RECONNECTING"===this.currentState&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===fw.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===fw.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===fw.FAILED||e.target.connectionState===fw.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===fw.CONNECTED||e.target.connectionState===fw.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),eP.emit(iP.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 mw;let e=null;return JM()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,qM()&&0!==this._peerConnection.getReceivers().length&&e?e.state:mw):mw}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(_z.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return qC(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(FM(i)){let t=e.get(i.localCandidateId),r=e.get(i.remoteCandidateId);t&&(this._log.info("local candidate: ".concat(t.candidateType," ").concat(t.protocol,":").concat(t.ip||t.address,":").concat(t.port," ").concat(t.networkType||""," ").concat("relay"===t.candidateType?"relayProtocol:".concat(t.relayProtocol):"")),t.networkType&&$w(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 ck({code:sk.API_CALL_ABORTED,message:hM({key:cM.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{eP.off(iP.LEAVE_SUCCESS,r,this),this.off(_z.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{n();let e=new ck({code:sk.API_CALL_TIMEOUT,message:"connection timeout"});gz+=1,(e=>gz>2&&!vz&&0===Ez.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),vz=!0,this.emit(_z.FIREWALL_RESTRICTION)),t(e)}),Pw);this.clearConnectTimeout=()=>{n(),clearTimeout(o),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new ck({code:sk.API_CALL_TIMEOUT,message:"connection timeout"}))},eP.on(iP.LEAVE_SUCCESS,r,this),this.on(_z.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 qC(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(Ew){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(Ew)),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=zk.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=SG(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(zk.AUDIO,{direction:zk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(zk.VIDEO,{direction:zk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(zk.VIDEO,{direction:zk.TRANSCEIVER_DIRECTION_RECVONLY}),o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=cz({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:SG(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=zk.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(zk.MAIN," ").concat(l,"-audio")}],s.direction=zk.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(zk.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(zk.MAIN," ").concat(l,"-bigvideo")}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=zk.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(zk.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(zk.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(zk.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 qC(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=SG(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 qC(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(tL()){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(mP){this._log.error("failed to set bandwidth: ".concat(mP))}}))}setStartBitrate(e,t){var i,r;return!(null==(i=this._peerConnection)||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=SG(this._peerConnection.remoteDescription.sdp)),null==(r=this._parsedAnswer.media[e])||!r.fmtp[0]))&&(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),!0)}setSenderMaxBitrate(e,t){let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),"unlimited"===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,e.setParameters(i)}setBandwidthBySDP(e){let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=SG(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=SG(this._peerConnection.remoteDescription.sdp));let s=SN?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:SN?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:SN?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:SN?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:SN?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:s,limit:SN?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:SN?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:s,limit:SN?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:SN?1e3*n:n}]);let a={type:"offer",sdp:IG(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(pD(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(TO&&IO<83||gN&&DO(wO,"12.1")||SN&&AN<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=IG(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,r)=>qC(this,null,(function*(){var n,o;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,i()}catch(s){this._log.error(s),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection(null==(n=this._peerConnection.localDescription)?void 0:n.sdp)," \nnext offer: ").concat(this.filterSDPDirection(null==e?void 0:e.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection(null==(o=this._peerConnection.remoteDescription)?void 0:o.sdp)," \nnext answer: ").concat(this.filterSDPDirection(t))),this._log.warn("offer: ".concat(null==e?void 0:e.sdp)),this._log.warn("answer: ".concat(t)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map((e=>{let{mid:t,currentDirection:i,direction:r,stopped:n}=e;return{mid:t,currentDirection:i,direction:r,stopped:n}}))))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,r(s)}})))),this._updateSDPPromise}setTransceiverDirection(e,t){return qC(this,null,(function*(){if(!SN||!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===Kk.INACTIVE&&t===Kk.RECVONLY&&(this._parsedAnswer.media[r].direction=e),e===Kk.SENDONLY&&t===Kk.INACTIVE&&(this._parsedAnswer.media[r].direction=Kk.RECVONLY)}yield this.updateSDP()}))}filterSDPDirection(){return SG(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((e=>e.direction))}setOffer(e){this._log.info("setting offer");let t=dz(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 qC(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach((i=>{var r;if(i.type===zk.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=[],lz(i,n),t=!0)}})),t&&(this._log.warn("switch video encoder to ".concat(e)),yield this.updateSDP())}))}useHWEncoder(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;return qC(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];pD(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===zk.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=[],lz(t,n),i=!0)}})),i&&(this._log.warn("use ".concat(e?"hw":"sw"," encoder")),yield this.updateSDP())}))}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),null==(e=this.clearWaitForConnectedPromise)||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach((e=>$D(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 qC(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")),IM.addSuccessEvent({key:r,cost:Date.now()-t})}catch(Ek){this._log.warn("switchRelay ".concat(i," failed"),Ek),IM.addFailedEvent({key:r,error:Ek}),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)}};GC([mU("reconnect")],yz.prototype,"startReconnection",1),GC([fU((e=>e.userId))],yz.prototype,"addDownlink",1),GC([fU((e=>e))],yz.prototype,"removeDownlink",1),GC([pU(!0)],yz.prototype,"updateSDP",1),GC([_U(521712,!1)],yz.prototype,"setOffer",1),GC([_U(521713,!1)],yz.prototype,"setAnswer",1);var Sz=class{constructor(e){zC(this,"tag"),zC(this,"len"),zC(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}},Iz=class{constructor(e){zC(this,"tinyId"),zC(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new Sz(new Uint8Array(e).slice(i,i+2+2+n).buffer);r.push(o),i+=4+n}r.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},Az=new Set;function bz(){let e=Math.floor(4294967296*Math.random());return Az.has(e)?bz():(Az.add(e),e)}var Rz=jC(JC()),Cz=class extends Rz.default{constructor(e){super(),zC(this,"userId"),zC(this,"tinyId"),zC(this,"_sdpSemantics"),zC(this,"_isUplink"),zC(this,"_room"),zC(this,"_log"),zC(this,"_currentState","DISCONNECTED"),zC(this,"_prevTime",-1),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=nP.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(eP.emit(iP.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"))}},kz=class extends Cz{constructor(e){super(BC(VC({},e),{isUplink:!0})),zC(this,"localMainAudioTrack",null),zC(this,"localMainVideoTrack",null),zC(this,"localAuxAudioTrack",null),zC(this,"localAuxVideoTrack",null),zC(this,"_isPublishingAux",!1),zC(this,"_publishingLocalAudioTrack"),zC(this,"_publishingLocalVideoTrack"),zC(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}),zC(this,"_flag",0),zC(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc:r,smallVideoRtxSsrc:n,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:o||0,auxiliaryRtx:s||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:i}=this,r=Object.keys(t).find((e=>t[e]!==i[e]));if(r){if(!e)return void(this._checkPublishStateTimeoutId=PL.run("timeout",(()=>this.checkPublishState(!0)),{delay:1e4,count:1}));this._log.warn("publish state not matched, ".concat(r," local:").concat(t[r]," server:").concat(i[r]," ").concat(XO()," ").concat(KO())),IM.addCount({key:521e3})}PL.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(YM()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(i=o[2])||!i.track),n.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((e=>{e.track&&(e.track.kind===zk.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}get publishingState(){let{publishState:e}=this,t=VC({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}get serverPublishState(){return{audio:!!(this.flag&Zk),bigVideo:!!(this.flag&Yk),smallVideo:!!(this.flag&Xk),auxVideo:!!(this.flag&Qk)}}get muteState(){var e,t,i;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(i=this.localAuxVideoTrack)||!i.muted)}}initialize(){this.installEvents()}close(e){var t;let i=(null==(t=this._peerConnection)?void 0:t.getSenders())||[];for(let r of i)r.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;null!=(e=this.singlePC)&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(t=this.singlePC)||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}onVideoEncodeFailed(e){var t;e&&e.isMediaTrackActive&&"h264"===this.videoCodec&&(this._log.warn("h264 encoder not working"),null!=(t=this.singlePC)&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),this.singlePC.switchVideoEncoder("vp8")))}publish(e){return qC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e,o,s,a,c,l,d;if(!t.singlePC)return;t.installEvents(),yield t.singlePC.waitForPeerConnectionConnected();let u,{publishState:h,muteState:p}=t;if(i&&(t._publishingLocalAudioTrack=i,h.audio=!0,p.audio=i.muted),r){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new ck({code:sk.NOT_SUPPORTED_H264,message:hM({key:cM.NOT_SUPPORTED_H264ENCODE})});t.singlePC.isUsingH264&&!t.singlePC.isH264EncodeSupported&&t.singlePC.isVP8EncodeSupported&&(t._log.warn("h264 encoder not supported"),yield t.singlePC.switchVideoEncoder("vp8")),vN&&115===EO()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to 480p"),r.setProfile(jk["480p_2"]),yield r.applyProfile()),t._publishingLocalVideoTrack=r,n?(h.auxVideo=!0,p.auxVideo=r.muted):(h.bigVideo=!0,p.bigVideo=r.muted)}if(t._isPublishingAux=n,r&&!n&&r.small&&(u=t._room.videoManager.smallTrack,h.smallVideo=!0),yield t._signalChannel.sendWaitForResponseWithRetry({command:cG,responseCommand:xj.SPC_PUBLISH_RESULT,data:BC(VC({},t.singlePC.uplinkSSRC),{state:h,muteState:p}),retries:3}),yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:u,isAuxiliary:n}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r){t[n?"localAuxVideoTrack":"localMainVideoTrack"]=r,yield t.singlePC.setDegradationPreference(t._peerConnection.getSenders()[n?3:1],r.contentHint,r.streamType);let{scaleResolutionDownBy:e}=r;yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[n?3:1],e,r.streamType)}i&&(t[n?"localAuxAudioTrack":"localMainAudioTrack"]=i),yield t.singlePC.setBandwidth({audio:(null==(e=t.localMainAudioTrack)?void 0:e.profile.bitrate)||(null==(o=t.localAuxAudioTrack)?void 0:o.profile.bitrate),bigVideo:null==(s=t.localMainVideoTrack)?void 0:s.profile.bitrate,smallVideo:null==(c=null==(a=t.localMainVideoTrack)?void 0:a.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),t.sendMediaSettings(),t.installTrackMuteEvents(i,r),(t._room.preferHW||null!=(d=t._room.scheduleResult.config)&&d.preferHW)&&r&&r.profile.width*r.profile.height>=921600&&t.singlePC.useHWEncoder(!0,n?7:2)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!XM())return;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[],d=(e,t,i)=>{var r,n;let o=a[t].sender.replaceTrack(i);l.push(t),null!=(r=this.singlePC)&&r.enableInsertableStreams&&o.then((()=>this.createEncodedStreams(a[t].sender,e))),null!=(n=this.singlePC)&&n.scriptTransformWorker&&this.initSenderTransfrom(a[t].sender,e),c.push(o)};s&&d(t.mediaType,0,s),o&&d(i.mediaType,n?3:1,o),r&&d(8,2,r);let u=this.singlePC.setTransceiverDirection(Kk.SENDONLY,l);return c.push(u),Promise.all(c)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var i,r;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let n=e.createEncodedStreams(),o=new AbortController;null==(i=this.singlePC)||i.addAbortController(e,o),(null!=(r=this.getTrackByMediaType(t))&&r.enableEncodeFrame?n.readable.pipeThrough(new TransformStream({transform:(e,i)=>{var r;let n=this.getTrackByMediaType(t);i.enqueue(null!=(r=this.singlePC)&&r.isUsingH264&&n?n.encodeFrame(e,8===t):e)}}),o):n.readable).pipeTo(n.writable,o).catch((e=>{this._log.debug("encoded stream error",e),"destory"!==e&&this._log.warn(e)}))}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)return;let i=2!==t,r=8===t;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:1===t,isMain:i,isSmall:r}))}enableSmall(e){return qC(this,null,(function*(){var t;if(!this.singlePC)return;let i=this._peerConnection.getTransceivers();if(e){if(this._room.videoManager.smallTrack){let{sender:e}=i[2];null!=(t=this.singlePC)&&t.enableInsertableStreams&&this.createEncodedStreams(e,8),yield e.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(Kk.SENDONLY,[2])}}else yield i[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Kk.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 qC(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,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=BC(VC({},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=BC(VC({},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(Kk.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 qC(this,null,(function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:jj,data:t,responseCommand:xj.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:Gj,commandDesc:"unpublish",responseCommand:xj.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===sk.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){var e;this._mediaSettings.videoCodec=(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264";let t=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:i,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:i=this._publishingLocalVideoTrack),rL){if(t&&t.outMediaTrack){let e=t.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*t.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings(),{scaleResolutionDownBy:t}=i;this._mediaSettings.videoWidth=e.width/t||0,this._mediaSettings.videoHeight=e.height/t||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*i.profile.bitrate,i.small&&(this._mediaSettings.smallVideoWidth=i.small.width,this._mediaSettings.smallVideoHeight=i.small.height,this._mediaSettings.smallVideoFps=i.small.frameRate,this._mediaSettings.smallVideoBps=1e3*i.small.bitrate)}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:t}=r;this._mediaSettings.auxVideoWidth=e.width/t||0,this._mediaSettings.auxVideoHeight=e.height/t||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate}}else t&&t.outMediaTrack&&(this._mediaSettings.audioChannel=t.profile.channelCount,this._mediaSettings.audioBps=1e3*t.profile.bitrate,this._mediaSettings.audioFs=t.profile.sampleRate),i&&i.outMediaTrack&&(this._mediaSettings.videoWidth=i.profile.width,this._mediaSettings.videoHeight=i.profile.height,this._mediaSettings.videoFps=i.profile.frameRate,this._mediaSettings.videoBps=1e3*i.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:oG,data:this._mediaSettings,responseCommand:xj.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return qC(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?zk.AUXILIARY:zk.MAIN," stream")),YM()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return qC(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===zk.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===Kk.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Kk.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return qC(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?zk.AUXILIARY:zk.MAIN," stream")),YM()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return qC(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===zk.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(Kk.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}replaceTrack(e){return qC(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!i||0===i.length||!r||i.find((e=>e.track===r)))return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(r.kind," track ").concat(r.id," ").concat(r.label," on ").concat(n?zk.AUXILIARY:zk.MAIN," stream")),r.kind===zk.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===zk.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0}))}setBandwidth(e){return qC(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===zk.AUDIO?e.audio=i:"big"===n?e.bigVideo=i:"small"===n?e.smallVideo=i:e.auxVideo=i,yield t.singlePC.setBandwidth(e)}}()}))}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:Hj,responseCommand:xj.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&eP.emit(iP.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:zk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===zk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===zk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===zk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===zk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Cw?(this._log.error(lM.NOT_SUPPORTED_H264ENCODE),new ck({code:sk.NOT_SUPPORTED_H264,message:hM({key:cM.NOT_SUPPORTED_H264ENCODE})})):new ck({code:sk.UNKNOWN,message:hM({key:cM.SIGNAL_RESPONSE_FAILED,data:{signalResponse:xj.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return qC(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}))}))}};GC([oU((function(e){let{localVideoTrack:t}=e;null==t||t.once("6",this.onVideoEncodeFailed,this)}))],kz.prototype,"publish",1),GC([oU((function(e){let{localVideoTrack:t}=e;null==t||t.off("6",this.onVideoEncodeFailed,this)}))],kz.prototype,"unpublish",1);var wz=kz;function Dz(e){return Object.keys(e).filter((t=>e[t]))}var Nz=class extends Cz{constructor(e){super(BC(VC({},e),{isUplink:!1})),zC(this,"_flag",0),zC(this,"isRobot",!1),zC(this,"role","anchor"),zC(this,"remoteAudioTrack"),zC(this,"remoteVideoTrack"),zC(this,"remoteAuxiliaryTrack"),zC(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),zC(this,"jitterBufferTimeoutId",-1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new JB(this._room,this),this.remoteVideoTrack=new hF(this._room,this),this.remoteAuxiliaryTrack=new pF(this._room,this),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.downlinkVideoCodec)||"h264"}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return ND(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===zk.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){var t,i;let r=e.streams[0],{track:n,receiver: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=zk.AUDIO;n.kind===zk.VIDEO&&(a=s===zk.MAIN?zk.VIDEO:zk.AUXILIARY);let c=this.remoteAudioTrack;a===zk.VIDEO?c=this.remoteVideoTrack:a===zk.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===zk.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;let n=null==(i=this.singlePC)?void 0:i.receiverRemoteTrackMap.get(e);return n&&("video"!==n.kind||null!=(r=this.singlePC)&&r.isUsingH264)?n.decodeFrame(t):t}};t.readable.pipeThrough(new TransformStream({transform:(e,t)=>{let i=r.enqueue(e);i&&t.enqueue(i)}})).pipeTo(t.writable,i).catch((e=>{"destory"!==e&&this._log.warn(e)})),this.singlePC.addAbortController(e,i)}}initReceiverTransform(e,t,i){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:i,userId:this.userId,streamType:t}))}subscribe(e,t){return qC(this,null,(function*(){try{if(this._log.info("subscribe ".concat(t," ").concat(Dz(e))),this.hasSSRC){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(pP){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(pP.message," ").concat(JSON.stringify(this.muteState))),new ck({code:sk.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):pP}}))}checkTrackEnded(e){var t,i,r;if((e.audio&&"ended"===(null==(t=this.remoteAudioTrack.mediaTrack)?void 0:t.readyState)||e.video&&"ended"===(null==(i=this.remoteVideoTrack.mediaTrack)?void 0:i.readyState)||e.auxiliary&&"ended"===(null==(r=this.remoteAuxiliaryTrack.mediaTrack)?void 0:r.readState))&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),TO&&IO<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return qC(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=VC({},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(Dz(n),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,n),"unsubscribe"===o&&(yield t.removeDownlink())}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=Kj,n=xj.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=qj,n=xj.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 ck({code:i.code,message:hM({key:cM.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 qC(this,null,(function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())}))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return qC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected();try{if(i||!e.hasSSRC){let i={audioSsrc:bz(),bigVideoSsrc:bz(),bigVideoRtxSsrc:bz(),auxVideoSsrc:bz(),auxVideoRtxSsrc:bz()},{audioSsrc:r,bigVideoSsrc:n,bigVideoRtxSsrc:o,auxVideoSsrc:s,auxVideoRtxSsrc:a}=i;e.ssrc={audio:r,video:n,videoRtx:o,auxiliary:s,auxiliaryRtx:a},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let r=yield e._signalChannel.sendWaitForResponseWithRetry({command:lG,responseCommand:xj.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!1,ssrc:i},retries:3,retryTimeout:0});if(0!==r.data.code)throw new ck({code:r.data.code,message:r.data.message})}catch(pM){throw yield e.removeDownlink(),pM}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}finally{if(!gL)return;let{main:t,aux:i}=e._room.jitterBufferDelay||{},{jitterDelay:r=t,jitterDelayAux:n=i}=e._room.scheduleResult.config||{};(fD(r)||fD(n))&&e.setJitterBufferDelay({mainDelay:r,auxDelay:n})}}}()}))}removeDownlink(){return qC(this,null,(function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(null!=e&&e.jitterDelay||null!=e&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)}))}setJitterBufferDelay(e){let{mainDelay:t,auxDelay:i}=e;if(!gL||!this.singlePC||!this._peerConnection||eN(t)&&eN(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return fD(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),fD(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,eN(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||eN(t)&&e.track===this.remoteAudioTrack.outMediaTrack;if(n&&eN(i)||!n&&eN(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(Ek){this._log.warn("set jitterBuffer delay error: ".concat(Ek)),clearTimeout(this.jitterBufferTimeoutId),n()}}get audioReceiver(){var e;return(null==(e=this.singlePC)?void 0:e.getReceiversByUserId(this.userId)[0])||null}};GC([pU(),aU((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 ck({code:sk.API_CALL_ABORTED,message:hM({key:cM.CONNECTION_ABORTED,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],Nz.prototype,"subscribe",1),GC([pU()],Nz.prototype,"unsubscribe",1),GC([fU((()=>"jitter"))],Nz.prototype,"setJitterBufferDelay",1);var Oz=Nz;var Pz=jC(JC());var Mz=class e extends Pz.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,zC(this,"log"),zC(this,"cmdIdSeqMap",new Map),zC(this,"messageMap",new Map),this.log=nP.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(xj.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",(e=>{[...this.messageMap.keys()].forEach((t=>{t.split("_").slice(0,-1).join("_")===e&&this.messageMap.delete(t)}))}))}send(e){let{cmdId:t,data:i}=e,r=this.cmdIdSeqMap.get(t)||Math.floor(16383*Math.random()),n={cmdId:t,msg:btoa(String.fromCharCode(...new Uint8Array(i))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(t,r+1),this.signalChannel.send(hG,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),KD(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)}};zC(Mz,"SEQ_INTERVAL",300);var Lz=Mz,{isString:xz,isUndefined:Uz,getNetworkType:Vz,isEmpty:Bz}=pk,Fz=class extends iz{constructor(e){super(e),zC(this,"_businessInfo"),zC(this,"userManager"),zC(this,"_version"),zC(this,"_heartbeat",-1),zC(this,"_lastHeartBeatTime",-1),zC(this,"_stats"),zC(this,"_joinTimeout",-1),zC(this,"_firstPublishedList",null),zC(this,"_joinReject",null),zC(this,"_isRelayChanged",!1),zC(this,"sdpSemantics"),zC(this,"signalChannel",null),zC(this,"uplinkConnection",null),zC(this,"singlePC",null),zC(this,"enableSPC",QM),zC(this,"_changeBigSmallRecords",new Map),zC(this,"networkQuality"),zC(this,"_iceTransportPolicy"),zC(this,"forceRelay",!1),zC(this,"_turnServers",[]),zC(this,"_iceServersFromJoin"),zC(this,"_syncUserListInterval",-1),zC(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),zC(this,"enableSEI",!1),zC(this,"_enableAudioVolumeEvaluation",!1),zC(this,"_audioVolumeIntervalId",0),zC(this,"_enableMultiAuxStream",!1),zC(this,"_pureAudioPushMode",!1),zC(this,"_customMessageManager"),zC(this,"preferHW",!1),zC(this,"healthDetector"),zC(this,"playoutDelay"),zC(this,"jitterBufferDelay"),zC(this,"_updateAudioLevelTaskId",-1),this._stats=new DG(this,this._log),this.userManager=new gF(this.userId,this._log),this._version=_k,this.sdpSemantics=Rw,Uz(e.sdpSemantics)?aP.isUnifiedPlanDefault()&&(this.sdpSemantics=bw):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(Vz())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!Uz(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&QM,!Uz(e.enableSPC)&&QM&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new pz(this)}get isMainStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex((e=>e.muteState.hasAuxiliary))>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,i){return qC(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",(e=>{this.emit("peer-join",e)})),this.userManager.on("2",(e=>{this.closeDownLinkConnection(e,"remote user exitRoom"),this.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(e=>{var t=((e,t)=>{var i={};for(var r in e)PC.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&NC)for(var r of NC(e))t.indexOf(r)<0&&MC.call(e,r)&&(i[r]=e[r]);return i})(e,[]);eP.emit(iP.REMOTE_PUBLISH_STATE_CHANGED,VC({room:this},t)),this.emit("remote-publish-state-changed",VC({},t))})),this.joinParams=e,new Promise(((t,i)=>qC(this,null,(function*(){var r,n;this._joinReject=i;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(pM){if(!(pM instanceof ck&&pM.code===sk.SPC_INITIALIZED_FAILED))return i(pM);null==(r=this.signalChannel)||r.destroy(),yield this.initialize()}let o=RD();yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),IM.addSuccessEvent({key:521708,cost:RD()-o}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(dP){IM.addFailedEvent({key:521708,error:dP}),i(dP)}this._joinReject=null}))))}))}initSinglePC(){return qC(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new yz({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",(e=>this.emit("sei-message",e))),this.singlePC.on("dump",(e=>this.emit("dump",e))),this.singlePC.once("error",(()=>this.fallbackToMPC()));try{return yield this.singlePC.initialize()}catch(vk){throw this.fallbackToMPC(),new ck({code:sk.SPC_INITIALIZED_FAILED,message:null==vk?void 0:vk.message})}}}))}doJoin(e,t){return new Promise(((i,r)=>qC(this,null,(function*(){var n,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Oj,(e=>{this.clearJoinTimeout(),eP.emit(iP.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)})),_D(null==(o=null==(n=this.scheduleResult)?void 0:n.config)?void 0:o.singlePC)&&QM&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let a={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:"live"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:QO(),netType:eD(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;null!=(s=this.scheduleResult.config)&&s.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{r(new ck({code:sk.JOIN_ROOM_FAILED,message:hM({key:cM.JOIN_ROOM_TIMEOUT})}))}),c),eP.emit(iP.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?aG:Vj,a),this.signalChannel.once(xj.JOIN_ROOM_RESULT,(t=>qC(this,null,(function*(){this.clearJoinTimeout();let{code:n,message:o,data:s,tinyId:a}=t.data;eP.emit(iP.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(BC(VC({},s.ability),{useVp8:s.ability.useVp8||!!e.useVp8})).catch((()=>{}))})),i()):(this._log.error("Join room failed result: ".concat(n," error: ").concat(o)),r(new ck({code:sk.JOIN_ROOM_FAILED,extraCode:n,message:hM({key:cM.JOIN_ROOM_FAILED,data:{error:o,code:n}})})))}))))}))))}reJoin(){return qC(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(BC(VC({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),BL.logSuccessEvent({userId:this.userId,eventType:yw.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(_z.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof wz&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(_z.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof wG&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(vk){this._log.warn("reJoin fail ".concat(vk)),this.reset(),BL.logFailedEvent({userId:this.userId,eventType:yw.REJOIN,error:vk}),this.emit("error",new ck({code:sk.JOIN_ROOM_FAILED,message:hM({key:cM.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return qC(this,null,(function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this.signalChannel||function(e){let t=[...pG.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);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 mG({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 Lz(this,this.signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this.networkQuality||(this.networkQuality=new MG({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(MG.EVENT_NETWORK_QUALITY,(e=>{var t;this.emit("network-quality",e),null==(t=this.singlePC)||t.detectTCPAndUDP(e)}))),UL(this,this.signalChannel).add(wj,(e=>{eP.emit(iP.SIGNAL_CONNECTION_STATE_CHANGED,VC({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(Nj,(e=>{this.reset(),this.emit("error",e)})).add(xj.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})).add(xj.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(xj.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(xj.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(BL.uploadEvent({log:"stat-banned:".concat(i),userId:this.userId}),"user_time_out"===i)return this._log.warn("".concat(i," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log["kick"===i?"error":"info"]("user was banned because of [".concat(i,"]")),this.reset(),this.emit("banned",{reason:i})})),this.signalChannel.once(kj,(e=>{this.tinyId=e.signalInfo.tinyId,eP.emit(iP.JOIN_SIGNAL_CONNECTION_END,{room:this})})),eP.emit(iP.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&eP.emit(iP.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this.signalChannel=e,e||VL(this)}leave(){return qC(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(Ew){}this._log.info("leave() => leaving room"),eP.emit(iP.LEAVE_SEND_CMD,{room:this}),null==(e=this.signalChannel)||e.send(Bj)}))}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=PL.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),PL.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return qC(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});this.badCaseDetector.resetMonitor();let r=null!=(e=this.signalChannel)&&e.isConnected?function(e){if(mF.has(e)){let t=mF.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType})));return mF.delete(e),t}return[]}(this.userId):[],n=BC(VC({str_sdk_version:fk,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:VC({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:eD()},i.msg_device_info)});if(this.heartbeatReport=n,eP.emit(iP.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Fj,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",BC(VC({},n),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter((e=>e.flag!==iw)).map((e=>{let{userId:t,srcTinyId:i,flag:r}=e;t===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=r);let n=this.remotePublishedUserMap.get(t);return n&&this.checkSubscribeBigSmallVideo(n),{userId:t,tinyId:i,flag:r}}));e.data.mixRobotList.forEach((e=>{let{userId:i,srcTinyId:r,flag:n,mixUserList:o}=e;t.unshift({userId:i,tinyId:r,flag:n,isRobot:!0,mixUserList:o})})),eP.emit(iP.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof wG&&(this.uplinkConnection=null)),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r,isRobot:n}=e,o=new(this.singlePC?Oz:RG)({userId:t,tinyId:i,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:n});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,t),this.emit("remote-published",o)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",(e=>{let i=e.getCode();i!==sk.ICE_TRANSPORT_ERROR&&(i===sk.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",BC(VC({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=PL.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){PL.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:rG,responseCommand:xj.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((e=>{let{data:t}=e,{code:i,message:r}=t;if(0===i)return(t.data&&t.data.userList||[]).map((e=>{let{userId:t,srcTinyId:i,role:r}=e;return{userId:t,tinyId:i,role:r}}));throw hM({key:cM.SIGNAL_RESPONSE_FAILED,data:{signalResponse:xj.USER_LIST_RES,code:i,message:r}})})):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!EG)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?(null==(e=this.singlePC.getPeerConnection())?void 0:e.connectionState)===fw.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof TG&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===fw.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return qC(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),BL.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 wG({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 RG({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 ck({code:sk.INVALID_OPERATION,message:hM({key:cM.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),PL.clearTask(this._audioVolumeIntervalId))}switchRole(e){return qC(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:nG,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:xj.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 ck({code:sk.SWITCH_ROLE_FAILED,message:hM({key:cM.SWITCH_ROLE_FAILED,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof ck&&e.getCode()===sk.API_CALL_TIMEOUT&&(e=new ck({code:sk.SWITCH_ROLE_FAILED,message:hM({key:cM.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e}))}publish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return qC(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof TU&&(t instanceof wU?i.audio=t:e.audio=t),t instanceof AU&&(t instanceof CU&&2===t.mediaType?i.video=t:e.video=t)}));let r=Bz(e),n=Bz(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new wz({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new wG({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",BC(VC({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==sk.ICE_TRANSPORT_ERROR&&(t===sk.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})));let o=t.map((e=>e.kind)).join(",");r||(this._log.info("publish() => main ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:e.audio,localVideoTrack:e.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info("publish() => aux ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:i.audio,localVideoTrack:i.video,isAuxiliary:!0}),this._log.info("aux is published"))}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return qC(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let e={},i={};t.forEach((t=>{!t.mediaTrack||!t.isPublished||(t instanceof TU&&(t instanceof wU?i.audio=t:e.audio=t),t instanceof AU&&(t instanceof CU&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");Bz(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),Bz(i)||(this._log.info("unpublish() => aux ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(_P){}0===this.localTracks.size&&this.closeUplink("you unpublished")}))}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return this.uplinkConnection&&e.mediaTrack?this.uplinkConnection.removeTrack(e).then((t=>(e.unpublish(),t))):Promise.resolve()}replaceTrack(e){return this.uplinkConnection&&e.mediaTrack&&eL()?this.uplinkConnection.replaceTrack(e).then((t=>{t&&eP.emit(iP.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return qC(this,null,(function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return qC(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:zk.VIDEO,videoType:zk.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 qC(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=VC({},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),eP.emit(iP.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(AG(n),"] prev: [").concat(AG(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());eP.emit(iP.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(Ek){let i=Ek instanceof ck?Ek.getCode():sk.UNKNOWN,n=Ek;throw Ek instanceof ck?i===sk.REMOTE_STREAM_NOT_EXIST&&(n=new ck({code:sk.API_CALL_ABORTED,message:hM({key:cM.API_CALL_ABORTED,data:{message:Ek.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new ck({code:i,message:hM({key:cM.SUBSCRIBE_FAILED,data:{message:Ek.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 qC(this,null,(function*(){let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let r=t.find((e=>2===e.mediaType))?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(e," ").concat(r));try{yield i.unsubscribe({remoteTracks:t,streamType:r})}catch(Ek){this._log.warn("unsubscribe() => failed ".concat(Ek))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),eP.emit(iP.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 PL.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),eP.emit(iP.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&PL.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=PL.run("intervalInWorker",(()=>{var i;Nx.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];null==(i=this.remotePublishedUserMap)||i.forEach((e=>{if(e.muteState.hasAudio){!Nx.isRunning&&e.muteState.audioAvailable&&e.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(e):e.remoteAudioTrack.volume=0;let t=Math.floor(100*e.remoteAudioTrack.getAudioLevel());r.push({userId:e.userId,volume:t})}})),this.emit("audio-volume",r)}),{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return qC(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=PL.run("intervalInWorker",(()=>qC(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"),PL.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,null!=(e=this.uplinkConnection)&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var t;let{audioReceiver:i}=e;if(!iL||!i)return;let r=null==(t=i.getSynchronizationSources()[0])?void 0:t.audioLevel;fD(r)?e.remoteAudioTrack.volume=Math.min(2*r,1):i.getStats().then((t=>{t.forEach((t=>{"inbound-rtp"===t.type&&fD(t.audioLevel)&&(e.remoteAudioTrack.volume=t.audioLevel)}))}))}getLocalAudioStats(){return qC(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 qC(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 qC(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 qC(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 qC(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(pk.getTurnServer(e)))):pk.isPlainObject(e)&&i.push(pk.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Zj,data:e,timeout:5e3,responseCommand:xj.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:$j,data:e,timeout:5e3,responseCommand:xj.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?Jj:Xj,data:e,timeout:5e3,responseCommand:t?xj.START_PUBLISH_TENCENT_CDN_RES:xj.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?Yj:Qj,data:e,timeout:5e3,responseCommand:t?xj.STOP_PUBLISH_TENCENT_CDN_RES:xj.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:eG,data:e,timeout:5e3,responseCommand:xj.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:tG,data:e,timeout:5e3,responseCommand:xj.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:iG,data:e,timeout:5e3,responseCommand:xj.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:dG,data:e,timeout:5e3,responseCommand:xj.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=pk.getEnv();return t?(e.mainUrl="wss://".concat(t,".rtc.qq.com"),e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl="wss://".concat(this.proxy_unified),e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}getSignalInfo(){var e;return(null==(e=this.signalChannel)?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return qC(this,null,(function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:r,hasVideo:n}}=e;if(!r&&!n||!t.video&&!t.smallVideo)return;let o=this._changeBigSmallRecords.get(i);if(!o||o.isSubscribing||o.reSubscribeCount<=0)return;let{options:s,reSubscribeCount:a}=o;if(s.video&&t.video||s.smallVideo&&t.smallVideo&&r)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:s.video,smallVideo:s.smallVideo};try{if(!r&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;o.isSubscribing=!0,o.reSubscribeCount=a-1,yield e.subscribe(c,"main"),e.remoteVideoTrack.setMediaType(c.smallVideo?8:4),this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video successfully. count ").concat(jw-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=jw}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(jw-o.reSubscribeCount,".")),o.isSubscribing=!1,0===o.reSubscribeCount&&this._changeBigSmallRecords.delete(i)}}))}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:jw};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(xz(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!Uz(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new ck({code:sk.INVALID_PARAMETER,message:hM({key:cM.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(!Uz(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new ck({code:sk.INVALID_PARAMETER,message:hM({key:cM.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Uz(e.userDefinePushArgs)){if(!(xz(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new ck({code:sk.INVALID_PARAMETER,message:hM({key:cM.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}Bz(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){return qC(this,null,(function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&oL)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 ck({code:sk.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}};
2
+ /*! Bundled license information:
3
+
4
+ jszip/dist/jszip.min.js:
5
+ (*!
6
+
7
+ JSZip v3.10.1 - A JavaScript class for generating and reading zip files
8
+ <http://stuartk.com/jszip>
9
+
10
+ (c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
11
+ Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
12
+
13
+ JSZip uses the library pako released under the MIT license :
14
+ https://github.com/nodeca/pako/blob/main/LICENSE
15
+ *)
16
+ */
17
+ return GC([AL(["left",CL.INIT],"joined"),HL({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"),iH(!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())}}),aU((e=>{let t=new bj;return function(i,r,n){return qC(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 ck({code:sk.INVALID_OPERATION,message:hM({key:cM.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new ck({code:sk.INVALID_OPERATION,message:hM({key:cM.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)),eP.emit(iP.JOIN_START,{room:this,roomId:o,params:i});let s=pk.getEnv();s||(s=xk.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(qk.OLD_CLOUD_LADDER)?s=xk.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(qk.WEBRTC)&&(s=xk.WEBRTC))),BL.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),aP.checkSystemRequirementsInternal().then((e=>{this.checkSystemResult=e,Rj.call(this)}));try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!pk.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=pk.performanceNow(),eP.emit(iP.JOIN_SUCCESS,{room:this}),30===n&&!i.component&&BL.uploadEvent({log:"stat-conv-".concat(Number(UO),"-").concat(location.hostname),userId:this.userId}),t}catch(mP){throw t.delete({room:this,roomId:o}),eP.emit(iP.JOIN_FAILED,{room:this,error:mP}),mP}}))}}))],Fz.prototype,"join",1),GC([AL("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),aU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return qC(this,null,(function*(){eP.emit(iP.LEAVE_START,{room:this}),yield e.call(this,...i),eP.emit(iP.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),mU("leave room"),WL({fnName:"publish",validateArgs:!1}),WL({fnName:"unsubscribe",validateArgs:!1})],Fz.prototype,"leave",1),GC([pU(),aU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return qC(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"capture"===e.state)),!i.length))return;eP.emit("61",{room:this});let t=e.apply(this,i);return i.forEach((e=>e.publish(this,t))),t}))})),HL({settings:{retries:vw,timeout:e=>dD(e)},onError(e,t,i){var r;null!=(r=e.message)&&r.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error("publish failed: ".concat(e)),i(e),eP.emit(iP.PUBLISH_FAILED,{room:this}))}})],Fz.prototype,"publish",1),GC([WL({fnName:"publish"}),function(e){return function(t,i,r){let n=r.value;return r.value=function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let o=uU.get(this);if(o){let t=o.queue.filter(((t,r)=>{if(0===r)return!0;let n=!0;return t.args.forEach((e=>{i.find((t=>t===e))||(n=!1)})),!n||(t.reject(new ck({code:sk.API_CALL_ABORTED,message:e})),!1)}));o.queue=t}return n.apply(this,i)},r}}("api-call"),pU(),aU((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})),oU((function(){var e,t;0===this.localTracks.size&&JM()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((e=>e.track&&e.replaceTrack(null))))}))],Fz.prototype,"unpublish",1),GC([sU((e=>{if(e.code!==sk.API_CALL_ABORTED)throw e})),fU((e=>e.userId))],Fz.prototype,"replaceTrack",1),GC([fU((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),OU(),aU((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})),HL({settings:{retries:vw,timeout:e=>dD(e)},onError(e,t,i,r){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),i(e),eP.emit(iP.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],Fz.prototype,"subscribe",1),GC([WL({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")}))}}),fU((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],Fz.prototype,"unsubscribe",1),Aj.create=Aj._create.bind(Aj,Fz),Aj}));