trtc-sdk-v5 5.0.2 → 5.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.d.ts +16 -3
- package/package.json +1 -1
- package/trtc.esm.js +31 -32
- package/trtc.js +1 -1
package/trtc.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TRTC=t()}(this,(function(){var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},t=function(e){try{return!!e()}catch(t){return!0}},i=!t((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),r=i,n=Function.prototype,o=n.call,a=r&&n.bind.bind(o,o),s=r?a:function(e){return function(){return o.apply(e,arguments)}},c=s,l=c({}.toString),d=c("".slice),u=function(e){return d(l(e),8,-1)},h=t,p=u,m=Object,_=s("".split),f=h((function(){return!m("z").propertyIsEnumerable(0)}))?function(e){return"String"==p(e)?_(e,""):m(e)}:m,g=function(e){return null==e},v=g,T=TypeError,S=function(e){if(v(e))throw T("Can't call method on "+e);return e},y=f,E=S,I=function(e){return y(E(e))},C=function(e){return e&&e.Math==Math&&e},R=C("object"==typeof globalThis&&globalThis)||C("object"==typeof window&&window)||C("object"==typeof self&&self)||C("object"==typeof e&&e)||function(){return this}()||Function("return this")(),A={},b={get exports(){return A},set exports(e){A=e}},k=R,w=Object.defineProperty,P=function(e,t){try{w(k,e,{value:t,configurable:!0,writable:!0})}catch(i){k[e]=t}return t},D=P,N="__core-js_shared__",O=R[N]||D(N,{}),M=O;(b.exports=function(e,t){return M[e]||(M[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.30.0",mode:"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.30.0/LICENSE",source:"https://github.com/zloirock/core-js"});var L,x,V=S,U=Object,F=function(e){return U(V(e))},B=F,j=s({}.hasOwnProperty),H=Object.hasOwn||function(e,t){return j(B(e),t)},G=s,W=0,J=Math.random(),z=G(1..toString),K=function(e){return"Symbol("+(void 0===e?"":e)+")_"+z(++W+J,36)},q="undefined"!=typeof navigator&&String(navigator.userAgent)||"",Q=R,Y=q,X=Q.process,$=Q.Deno,Z=X&&X.versions||$&&$.version,ee=Z&&Z.v8;ee&&(x=(L=ee.split("."))[0]>0&&L[0]<4?1:+(L[0]+L[1])),!x&&Y&&(!(L=Y.match(/Edge\/(\d+)/))||L[1]>=74)&&(L=Y.match(/Chrome\/(\d+)/))&&(x=+L[1]);var te=x,ie=te,re=t,ne=!!Object.getOwnPropertySymbols&&!re((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ie&&ie<41})),oe=ne&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ae=A,se=H,ce=K,le=ne,de=oe,ue=R.Symbol,he=ae("wks"),pe=de?ue.for||ue:ue&&ue.withoutSetter||ce,me=function(e){return se(he,e)||(he[e]=le&&se(ue,e)?ue[e]:pe("Symbol."+e)),he[e]},_e="object"==typeof document&&document.all,fe={all:_e,IS_HTMLDDA:void 0===_e&&void 0!==_e},ge=fe.all,ve=fe.IS_HTMLDDA?function(e){return"function"==typeof e||e===ge}:function(e){return"function"==typeof e},Te=ve,Se=fe.all,ye=fe.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:Te(e)||e===Se}:function(e){return"object"==typeof e?null!==e:Te(e)},Ee=ye,Ie=String,Ce=TypeError,Re=function(e){if(Ee(e))return e;throw Ce(Ie(e)+" is not an object")},Ae={},be=!t((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),ke=be&&t((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),we={},Pe=ye,De=R.document,Ne=Pe(De)&&Pe(De.createElement),Oe=function(e){return Ne?De.createElement(e):{}},Me=Oe,Le=!be&&!t((function(){return 7!=Object.defineProperty(Me("div"),"a",{get:function(){return 7}}).a})),xe=i,Ve=Function.prototype.call,Ue=xe?Ve.bind(Ve):function(){return Ve.apply(Ve,arguments)},Fe=R,Be=ve,je=function(e){return Be(e)?e:void 0},He=function(e,t){return arguments.length<2?je(Fe[e]):Fe[e]&&Fe[e][t]},Ge=s({}.isPrototypeOf),We=He,Je=ve,ze=Ge,Ke=Object,qe=oe?function(e){return"symbol"==typeof e}:function(e){var t=We("Symbol");return Je(t)&&ze(t.prototype,Ke(e))},Qe=String,Ye=function(e){try{return Qe(e)}catch(t){return"Object"}},Xe=ve,$e=Ye,Ze=TypeError,et=function(e){if(Xe(e))return e;throw Ze($e(e)+" is not a function")},tt=et,it=g,rt=function(e,t){var i=e[t];return it(i)?void 0:tt(i)},nt=Ue,ot=ve,at=ye,st=TypeError,ct=Ue,lt=ye,dt=qe,ut=rt,ht=function(e,t){var i,r;if("string"===t&&ot(i=e.toString)&&!at(r=nt(i,e)))return r;if(ot(i=e.valueOf)&&!at(r=nt(i,e)))return r;if("string"!==t&&ot(i=e.toString)&&!at(r=nt(i,e)))return r;throw st("Can't convert object to primitive value")},pt=TypeError,mt=me("toPrimitive"),_t=function(e,t){if(!lt(e)||dt(e))return e;var i,r=ut(e,mt);if(r){if(void 0===t&&(t="default"),i=ct(r,e,t),!lt(i)||dt(i))return i;throw pt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ht(e,t)},ft=_t,gt=qe,vt=function(e){var t=ft(e,"string");return gt(t)?t:t+""},Tt=be,St=Le,yt=ke,Et=Re,It=vt,Ct=TypeError,Rt=Object.defineProperty,At=Object.getOwnPropertyDescriptor,bt="enumerable",kt="configurable",wt="writable";we.f=Tt?yt?function(e,t,i){if(Et(e),t=It(t),Et(i),"function"==typeof e&&"prototype"===t&&"value"in i&&wt in i&&!i.writable){var r=At(e,t);r&&r.writable&&(e[t]=i.value,i={configurable:kt in i?i.configurable:r.configurable,enumerable:bt in i?i.enumerable:r.enumerable,writable:!1})}return Rt(e,t,i)}:Rt:function(e,t,i){if(Et(e),t=It(t),Et(i),St)try{return Rt(e,t,i)}catch(r){}if("get"in i||"set"in i)throw Ct("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Pt=Math.ceil,Dt=Math.floor,Nt=Math.trunc||function(e){var t=+e;return(t>0?Dt:Pt)(t)},Ot=function(e){var t=+e;return t!=t||0===t?0:Nt(t)},Mt=Ot,Lt=Math.max,xt=Math.min,Vt=function(e,t){var i=Mt(e);return i<0?Lt(i+t,0):xt(i,t)},Ut=Ot,Ft=Math.min,Bt=function(e){return e>0?Ft(Ut(e),9007199254740991):0},jt=Bt,Ht=function(e){return jt(e.length)},Gt=I,Wt=Vt,Jt=Ht,zt=function(e){return function(t,i,r){var n,o=Gt(t),a=Jt(o),s=Wt(r,a);if(e&&i!=i){for(;a>s;)if((n=o[s++])!=n)return!0}else for(;a>s;s++)if((e||s in o)&&o[s]===i)return e||s||0;return!e&&-1}},Kt={includes:zt(!0),indexOf:zt(!1)},qt={},Qt=H,Yt=I,Xt=Kt.indexOf,$t=qt,Zt=s([].push),ei=function(e,t){var i,r=Yt(e),n=0,o=[];for(i in r)!Qt($t,i)&&Qt(r,i)&&Zt(o,i);for(;t.length>n;)Qt(r,i=t[n++])&&(~Xt(o,i)||Zt(o,i));return o},ti=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ii=ei,ri=ti,ni=Object.keys||function(e){return ii(e,ri)},oi=be,ai=ke,si=we,ci=Re,li=I,di=ni;Ae.f=oi&&!ai?Object.defineProperties:function(e,t){ci(e);for(var i,r=li(t),n=di(t),o=n.length,a=0;o>a;)si.f(e,i=n[a++],r[i]);return e};var ui,hi=He("document","documentElement"),pi=K,mi=A("keys"),_i=function(e){return mi[e]||(mi[e]=pi(e))},fi=Re,gi=Ae,vi=ti,Ti=qt,Si=hi,yi=Oe,Ei=_i("IE_PROTO"),Ii=function(){},Ci=function(e){return"<script>"+e+"</"+"script>"},Ri=function(e){e.write(Ci("")),e.close();var t=e.parentWindow.Object;return e=null,t},Ai=function(){try{ui=new ActiveXObject("htmlfile")}catch(r){}var e,t;Ai="undefined"!=typeof document?document.domain&&ui?Ri(ui):((t=yi("iframe")).style.display="none",Si.appendChild(t),t.src=String("javascript:"),(e=t.contentWindow.document).open(),e.write(Ci("document.F=Object")),e.close(),e.F):Ri(ui);for(var i=vi.length;i--;)delete Ai.prototype[vi[i]];return Ai()};Ti[Ei]=!0;var bi=Object.create||function(e,t){var i;return null!==e?(Ii.prototype=fi(e),i=new Ii,Ii.prototype=null,i[Ei]=e):i=Ai(),void 0===t?i:gi.f(i,t)},ki=me,wi=bi,Pi=we.f,Di=ki("unscopables"),Ni=Array.prototype;null==Ni[Di]&&Pi(Ni,Di,{configurable:!0,value:wi(null)});var Oi,Mi,Li,xi=function(e){Ni[Di][e]=!0},Vi={},Ui=ve,Fi=R.WeakMap,Bi=Ui(Fi)&&/native code/.test(String(Fi)),ji=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},Hi=we,Gi=ji,Wi=be?function(e,t,i){return Hi.f(e,t,Gi(1,i))}:function(e,t,i){return e[t]=i,e},Ji=Bi,zi=R,Ki=ye,qi=Wi,Qi=H,Yi=O,Xi=_i,$i=qt,Zi="Object already initialized",er=zi.TypeError,tr=zi.WeakMap;if(Ji||Yi.state){var ir=Yi.state||(Yi.state=new tr);ir.get=ir.get,ir.has=ir.has,ir.set=ir.set,Oi=function(e,t){if(ir.has(e))throw er(Zi);return t.facade=e,ir.set(e,t),t},Mi=function(e){return ir.get(e)||{}},Li=function(e){return ir.has(e)}}else{var rr=Xi("state");$i[rr]=!0,Oi=function(e,t){if(Qi(e,rr))throw er(Zi);return t.facade=e,qi(e,rr,t),t},Mi=function(e){return Qi(e,rr)?e[rr]:{}},Li=function(e){return Qi(e,rr)}}var nr={set:Oi,get:Mi,has:Li,enforce:function(e){return Li(e)?Mi(e):Oi(e,{})},getterFor:function(e){return function(t){var i;if(!Ki(t)||(i=Mi(t)).type!==e)throw er("Incompatible receiver, "+e+" required");return i}}},or={},ar={},sr={}.propertyIsEnumerable,cr=Object.getOwnPropertyDescriptor,lr=cr&&!sr.call({1:2},1);ar.f=lr?function(e){var t=cr(this,e);return!!t&&t.enumerable}:sr;var dr=be,ur=Ue,hr=ar,pr=ji,mr=I,_r=vt,fr=H,gr=Le,vr=Object.getOwnPropertyDescriptor;or.f=dr?vr:function(e,t){if(e=mr(e),t=_r(t),gr)try{return vr(e,t)}catch(i){}if(fr(e,t))return pr(!ur(hr.f,e,t),e[t])};var Tr={},Sr={get exports(){return Tr},set exports(e){Tr=e}},yr=be,Er=H,Ir=Function.prototype,Cr=yr&&Object.getOwnPropertyDescriptor,Rr=Er(Ir,"name"),Ar={EXISTS:Rr,PROPER:Rr&&"something"===function(){}.name,CONFIGURABLE:Rr&&(!yr||yr&&Cr(Ir,"name").configurable)},br=ve,kr=O,wr=s(Function.toString);br(kr.inspectSource)||(kr.inspectSource=function(e){return wr(e)});var Pr=kr.inspectSource,Dr=s,Nr=t,Or=ve,Mr=H,Lr=be,xr=Ar.CONFIGURABLE,Vr=Pr,Ur=nr.enforce,Fr=nr.get,Br=String,jr=Object.defineProperty,Hr=Dr("".slice),Gr=Dr("".replace),Wr=Dr([].join),Jr=Lr&&!Nr((function(){return 8!==jr((function(){}),"length",{value:8}).length})),zr=String(String).split("String"),Kr=Sr.exports=function(e,t,i){"Symbol("===Hr(Br(t),0,7)&&(t="["+Gr(Br(t),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Mr(e,"name")||xr&&e.name!==t)&&(Lr?jr(e,"name",{value:t,configurable:!0}):e.name=t),Jr&&i&&Mr(i,"arity")&&e.length!==i.arity&&jr(e,"length",{value:i.arity});try{i&&Mr(i,"constructor")&&i.constructor?Lr&&jr(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var r=Ur(e);return Mr(r,"source")||(r.source=Wr(zr,"string"==typeof t?t:"")),e};Function.prototype.toString=Kr((function(){return Or(this)&&Fr(this).source||Vr(this)}),"toString");var qr=ve,Qr=we,Yr=Tr,Xr=P,$r=function(e,t,i,r){r||(r={});var n=r.enumerable,o=void 0!==r.name?r.name:t;if(qr(i)&&Yr(i,o,r),r.global)n?e[t]=i:Xr(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch(a){}n?e[t]=i:Qr.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},Zr={},en=ei,tn=ti.concat("length","prototype");Zr.f=Object.getOwnPropertyNames||function(e){return en(e,tn)};var rn={};rn.f=Object.getOwnPropertySymbols;var nn,on,an,sn=He,cn=Zr,ln=rn,dn=Re,un=s([].concat),hn=sn("Reflect","ownKeys")||function(e){var t=cn.f(dn(e)),i=ln.f;return i?un(t,i(e)):t},pn=H,mn=hn,_n=or,fn=we,gn=function(e,t,i){for(var r=mn(t),n=fn.f,o=_n.f,a=0;a<r.length;a++){var s=r[a];pn(e,s)||i&&pn(i,s)||n(e,s,o(t,s))}},vn=t,Tn=ve,Sn=/#|\.prototype\./,yn=function(e,t){var i=In[En(e)];return i==Rn||i!=Cn&&(Tn(t)?vn(t):!!t)},En=yn.normalize=function(e){return String(e).replace(Sn,".").toLowerCase()},In=yn.data={},Cn=yn.NATIVE="N",Rn=yn.POLYFILL="P",An=yn,bn=R,kn=or.f,wn=Wi,Pn=$r,Dn=P,Nn=gn,On=An,Mn=function(e,t){var i,r,n,o,a,s=e.target,c=e.global,l=e.stat;if(i=c?bn:l?bn[s]||Dn(s,{}):(bn[s]||{}).prototype)for(r in t){if(o=t[r],n=e.dontCallGetSet?(a=kn(i,r))&&a.value:i[r],!On(c?r:s+(l?".":"#")+r,e.forced)&&void 0!==n){if(typeof o==typeof n)continue;Nn(o,n)}(e.sham||n&&n.sham)&&wn(o,"sham",!0),Pn(i,r,o,e)}},Ln=!t((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),xn=H,Vn=ve,Un=F,Fn=Ln,Bn=_i("IE_PROTO"),jn=Object,Hn=jn.prototype,Gn=Fn?jn.getPrototypeOf:function(e){var t=Un(e);if(xn(t,Bn))return t[Bn];var i=t.constructor;return Vn(i)&&t instanceof i?i.prototype:t instanceof jn?Hn:null},Wn=t,Jn=ve,zn=ye,Kn=Gn,qn=$r,Qn=me("iterator"),Yn=!1;[].keys&&("next"in(an=[].keys())?(on=Kn(Kn(an)))!==Object.prototype&&(nn=on):Yn=!0);var Xn=!zn(nn)||Wn((function(){var e={};return nn[Qn].call(e)!==e}));Xn&&(nn={}),Jn(nn[Qn])||qn(nn,Qn,(function(){return this}));var $n={IteratorPrototype:nn,BUGGY_SAFARI_ITERATORS:Yn},Zn=we.f,eo=H,to=me("toStringTag"),io=function(e,t,i){e&&!i&&(e=e.prototype),e&&!eo(e,to)&&Zn(e,to,{configurable:!0,value:t})},ro=$n.IteratorPrototype,no=bi,oo=ji,ao=io,so=Vi,co=function(){return this},lo=function(e,t,i,r){var n=t+" Iterator";return e.prototype=no(ro,{next:oo(+!r,i)}),ao(e,n,!1),so[n]=co,e},uo=s,ho=et,po=ve,mo=String,_o=TypeError,fo=function(e,t,i){try{return uo(ho(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},go=Re,vo=function(e){if("object"==typeof e||po(e))return e;throw _o("Can't set "+mo(e)+" as a prototype")},To=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=fo(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return go(i),vo(r),t?e(i,r):i.__proto__=r,i}}():void 0),So=Mn,yo=Ue,Eo=ve,Io=lo,Co=Gn,Ro=To,Ao=io,bo=Wi,ko=$r,wo=Vi,Po=Ar.PROPER,Do=Ar.CONFIGURABLE,No=$n.IteratorPrototype,Oo=$n.BUGGY_SAFARI_ITERATORS,Mo=me("iterator"),Lo="keys",xo="values",Vo="entries",Uo=function(){return this},Fo=function(e,t,i,r,n,o,a){Io(i,t,r);var s,c,l,d=function(e){if(e===n&&_)return _;if(!Oo&&e in p)return p[e];switch(e){case Lo:case xo:case Vo:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[Mo]||p["@@iterator"]||n&&p[n],_=!Oo&&m||d(n),f="Array"==t&&p.entries||m;if(f&&(s=Co(f.call(new e)))!==Object.prototype&&s.next&&(Co(s)!==No&&(Ro?Ro(s,No):Eo(s[Mo])||ko(s,Mo,Uo)),Ao(s,u,!0)),Po&&n==xo&&m&&m.name!==xo&&(Do?bo(p,"name",xo):(h=!0,_=function(){return yo(m,this)})),n)if(c={values:d(xo),keys:o?_:d(Lo),entries:d(Vo)},a)for(l in c)(Oo||h||!(l in p))&&ko(p,l,c[l]);else So({target:t,proto:!0,forced:Oo||h},c);return p[Mo]!==_&&ko(p,Mo,_,{name:n}),wo[t]=_,c},Bo=function(e,t){return{value:e,done:t}},jo=I,Ho=xi,Go=Vi,Wo=nr,Jo=we.f,zo=Fo,Ko=Bo,qo=be,Qo="Array Iterator",Yo=Wo.set,Xo=Wo.getterFor(Qo),$o=zo(Array,"Array",(function(e,t){Yo(this,{type:Qo,target:jo(e),index:0,kind:t})}),(function(){var e=Xo(this),t=e.target,i=e.kind,r=e.index++;return!t||r>=t.length?(e.target=void 0,Ko(void 0,!0)):Ko("keys"==i?r:"values"==i?t[r]:[r,t[r]],!1)}),"values"),Zo=Go.Arguments=Go.Array;if(Ho("keys"),Ho("values"),Ho("entries"),qo&&"values"!==Zo.name)try{Jo(Zo,"name",{value:"values"})}catch(pV){}var ea={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},ta=Oe("span").classList,ia=ta&&ta.constructor&&ta.constructor.prototype,ra=ia===Object.prototype?void 0:ia,na=R,oa=ea,aa=ra,sa=$o,ca=Wi,la=me,da=la("iterator"),ua=la("toStringTag"),ha=sa.values,pa=function(e,t){if(e){if(e[da]!==ha)try{ca(e,da,ha)}catch(pV){e[da]=ha}if(e[ua]||ca(e,ua,t),oa[t])for(var i in sa)if(e[i]!==sa[i])try{ca(e,i,sa[i])}catch(pV){e[i]=sa[i]}}};for(var ma in oa)pa(na[ma]&&na[ma].prototype,ma);pa(aa,"DOMTokenList");var _a="undefined"!=typeof process&&"process"==u(process),fa=Tr,ga=we,va=function(e,t,i){return i.get&&fa(i.get,t,{getter:!0}),i.set&&fa(i.set,t,{setter:!0}),ga.f(e,t,i)},Ta=He,Sa=va,ya=be,Ea=me("species"),Ia=function(e){var t=Ta(e);ya&&t&&!t[Ea]&&Sa(t,Ea,{configurable:!0,get:function(){return this}})},Ca=Ge,Ra=TypeError,Aa=function(e,t){if(Ca(t,e))return e;throw Ra("Incorrect invocation")},ba={};ba[me("toStringTag")]="z";var ka="[object z]"===String(ba),wa=ve,Pa=u,Da=me("toStringTag"),Na=Object,Oa="Arguments"==Pa(function(){return arguments}()),Ma=ka?Pa: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(pV){}}(t=Na(e),Da))?i:Oa?Pa(t):"Object"==(r=Pa(t))&&wa(t.callee)?"Arguments":r},La=s,xa=t,Va=ve,Ua=Ma,Fa=Pr,Ba=function(){},ja=[],Ha=He("Reflect","construct"),Ga=/^\s*(?:class|function)\b/,Wa=La(Ga.exec),Ja=!Ga.exec(Ba),za=function(e){if(!Va(e))return!1;try{return Ha(Ba,ja,e),!0}catch(pV){return!1}},Ka=function(e){if(!Va(e))return!1;switch(Ua(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ja||!!Wa(Ga,Fa(e))}catch(pV){return!0}};Ka.sham=!0;var qa,Qa,Ya,Xa,$a=!Ha||xa((function(){var e;return za(za.call)||!za(Object)||!za((function(){e=!0}))||e}))?Ka:za,Za=$a,es=Ye,ts=TypeError,is=function(e){if(Za(e))return e;throw ts(es(e)+" is not a constructor")},rs=Re,ns=is,os=g,as=me("species"),ss=function(e,t){var i,r=rs(e).constructor;return void 0===r||os(i=rs(r)[as])?t:ns(i)},cs=i,ls=Function.prototype,ds=ls.apply,us=ls.call,hs="object"==typeof Reflect&&Reflect.apply||(cs?us.bind(ds):function(){return us.apply(ds,arguments)}),ps=u,ms=s,_s=function(e){if("Function"===ps(e))return ms(e)},fs=et,gs=i,vs=_s(_s.bind),Ts=function(e,t){return fs(e),void 0===t?e:gs?vs(e,t):function(){return e.apply(t,arguments)}},Ss=s([].slice),ys=TypeError,Es=function(e,t){if(e<t)throw ys("Not enough arguments");return e},Is=/(?:ipad|iphone|ipod).*applewebkit/i.test(q),Cs=R,Rs=hs,As=Ts,bs=ve,ks=H,ws=t,Ps=hi,Ds=Ss,Ns=Oe,Os=Es,Ms=Is,Ls=_a,xs=Cs.setImmediate,Vs=Cs.clearImmediate,Us=Cs.process,Fs=Cs.Dispatch,Bs=Cs.Function,js=Cs.MessageChannel,Hs=Cs.String,Gs=0,Ws={},Js="onreadystatechange";ws((function(){qa=Cs.location}));var zs=function(e){if(ks(Ws,e)){var t=Ws[e];delete Ws[e],t()}},Ks=function(e){return function(){zs(e)}},qs=function(e){zs(e.data)},Qs=function(e){Cs.postMessage(Hs(e),qa.protocol+"//"+qa.host)};xs&&Vs||(xs=function(e){Os(arguments.length,1);var t=bs(e)?e:Bs(e),i=Ds(arguments,1);return Ws[++Gs]=function(){Rs(t,void 0,i)},Qa(Gs),Gs},Vs=function(e){delete Ws[e]},Ls?Qa=function(e){Us.nextTick(Ks(e))}:Fs&&Fs.now?Qa=function(e){Fs.now(Ks(e))}:js&&!Ms?(Xa=(Ya=new js).port2,Ya.port1.onmessage=qs,Qa=As(Xa.postMessage,Xa)):Cs.addEventListener&&bs(Cs.postMessage)&&!Cs.importScripts&&qa&&"file:"!==qa.protocol&&!ws(Qs)?(Qa=Qs,Cs.addEventListener("message",qs,!1)):Qa=Js in Ns("script")?function(e){Ps.appendChild(Ns("script")).onreadystatechange=function(){Ps.removeChild(this),zs(e)}}:function(e){setTimeout(Ks(e),0)});var Ys={set:xs,clear:Vs},Xs=function(){this.head=null,this.tail=null};Xs.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 $s,Zs,ec,tc,ic,rc=Xs,nc=/ipad|iphone|ipod/i.test(q)&&"undefined"!=typeof Pebble,oc=/web0s(?!.*chrome)/i.test(q),ac=R,sc=Ts,cc=or.f,lc=Ys.set,dc=rc,uc=Is,hc=nc,pc=oc,mc=_a,_c=ac.MutationObserver||ac.WebKitMutationObserver,fc=ac.document,gc=ac.process,vc=ac.Promise,Tc=cc(ac,"queueMicrotask"),Sc=Tc&&Tc.value;if(!Sc){var yc=new dc,Ec=function(){var e,t;for(mc&&(e=gc.domain)&&e.exit();t=yc.get();)try{t()}catch(pV){throw yc.head&&$s(),pV}e&&e.enter()};uc||mc||pc||!_c||!fc?!hc&&vc&&vc.resolve?((tc=vc.resolve(void 0)).constructor=vc,ic=sc(tc.then,tc),$s=function(){ic(Ec)}):mc?$s=function(){gc.nextTick(Ec)}:(lc=sc(lc,ac),$s=function(){lc(Ec)}):(Zs=!0,ec=fc.createTextNode(""),new _c(Ec).observe(ec,{characterData:!0}),$s=function(){ec.data=Zs=!Zs}),Sc=function(e){yc.head||$s(),yc.add(e)}}var Ic=Sc,Cc=function(e){try{return{error:!1,value:e()}}catch(pV){return{error:!0,value:pV}}},Rc=R.Promise,Ac="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,bc=!Ac&&!_a&&"object"==typeof window&&"object"==typeof document,kc=R,wc=Rc,Pc=ve,Dc=An,Nc=Pr,Oc=me,Mc=bc,Lc=Ac,xc=te;wc&&wc.prototype;var Vc=Oc("species"),Uc=!1,Fc=Pc(kc.PromiseRejectionEvent),Bc=Dc("Promise",(function(){var e=Nc(wc),t=e!==String(wc);if(!t&&66===xc)return!0;if(!xc||xc<51||!/native code/.test(e)){var i=new wc((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((i.constructor={})[Vc]=r,!(Uc=i.then((function(){}))instanceof r))return!0}return!t&&(Mc||Lc)&&!Fc})),jc={CONSTRUCTOR:Bc,REJECTION_EVENT:Fc,SUBCLASSING:Uc},Hc={},Gc=et,Wc=TypeError,Jc=function(e){var t,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw Wc("Bad Promise constructor");t=e,i=r})),this.resolve=Gc(t),this.reject=Gc(i)};Hc.f=function(e){return new Jc(e)};var zc,Kc,qc,Qc=Mn,Yc=_a,Xc=R,$c=Ue,Zc=$r,el=To,tl=io,il=Ia,rl=et,nl=ve,ol=ye,al=Aa,sl=ss,cl=Ys.set,ll=Ic,dl=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(pV){}},ul=Cc,hl=rc,pl=nr,ml=Rc,_l=Hc,fl="Promise",gl=jc.CONSTRUCTOR,vl=jc.REJECTION_EVENT,Tl=jc.SUBCLASSING,Sl=pl.getterFor(fl),yl=pl.set,El=ml&&ml.prototype,Il=ml,Cl=El,Rl=Xc.TypeError,Al=Xc.document,bl=Xc.process,kl=_l.f,wl=kl,Pl=!!(Al&&Al.createEvent&&Xc.dispatchEvent),Dl="unhandledrejection",Nl=function(e){var t;return!(!ol(e)||!nl(t=e.then))&&t},Ol=function(e,t){var i,r,n,o=t.value,a=1==t.state,s=a?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{s?(a||(2===t.rejection&&Ul(t),t.rejection=1),!0===s?i=o:(d&&d.enter(),i=s(o),d&&(d.exit(),n=!0)),i===e.promise?l(Rl("Promise-chain cycle")):(r=Nl(i))?$c(r,i,c,l):c(i)):l(o)}catch(pV){d&&!n&&d.exit(),l(pV)}},Ml=function(e,t){e.notified||(e.notified=!0,ll((function(){for(var i,r=e.reactions;i=r.get();)Ol(i,e);e.notified=!1,t&&!e.rejection&&xl(e)})))},Ll=function(e,t,i){var r,n;Pl?((r=Al.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),Xc.dispatchEvent(r)):r={promise:t,reason:i},!vl&&(n=Xc["on"+e])?n(r):e===Dl&&dl("Unhandled promise rejection",i)},xl=function(e){$c(cl,Xc,(function(){var t,i=e.facade,r=e.value;if(Vl(e)&&(t=ul((function(){Yc?bl.emit("unhandledRejection",r,i):Ll(Dl,i,r)})),e.rejection=Yc||Vl(e)?2:1,t.error))throw t.value}))},Vl=function(e){return 1!==e.rejection&&!e.parent},Ul=function(e){$c(cl,Xc,(function(){var t=e.facade;Yc?bl.emit("rejectionHandled",t):Ll("rejectionhandled",t,e.value)}))},Fl=function(e,t,i){return function(r){e(t,r,i)}},Bl=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Ml(e,!0))},jl=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw Rl("Promise can't be resolved itself");var r=Nl(t);r?ll((function(){var i={done:!1};try{$c(r,t,Fl(jl,i,e),Fl(Bl,i,e))}catch(pV){Bl(i,pV,e)}})):(e.value=t,e.state=1,Ml(e,!1))}catch(pV){Bl({done:!1},pV,e)}}};if(gl&&(Cl=(Il=function(e){al(this,Cl),rl(e),$c(zc,this);var t=Sl(this);try{e(Fl(jl,t),Fl(Bl,t))}catch(pV){Bl(t,pV)}}).prototype,(zc=function(e){yl(this,{type:fl,done:!1,notified:!1,parent:!1,reactions:new hl,rejection:!1,state:0,value:void 0})}).prototype=Zc(Cl,"then",(function(e,t){var i=Sl(this),r=kl(sl(this,Il));return i.parent=!0,r.ok=!nl(e)||e,r.fail=nl(t)&&t,r.domain=Yc?bl.domain:void 0,0==i.state?i.reactions.add(r):ll((function(){Ol(r,i)})),r.promise})),Kc=function(){var e=new zc,t=Sl(e);this.promise=e,this.resolve=Fl(jl,t),this.reject=Fl(Bl,t)},_l.f=kl=function(e){return e===Il||undefined===e?new Kc(e):wl(e)},nl(ml)&&El!==Object.prototype)){qc=El.then,Tl||Zc(El,"then",(function(e,t){var i=this;return new Il((function(e,t){$c(qc,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete El.constructor}catch(pV){}el&&el(El,Cl)}Qc({global:!0,constructor:!0,wrap:!0,forced:gl},{Promise:Il}),tl(Il,fl,!1),il(fl);var Hl=Vi,Gl=me("iterator"),Wl=Array.prototype,Jl=function(e){return void 0!==e&&(Hl.Array===e||Wl[Gl]===e)},zl=Ma,Kl=rt,ql=g,Ql=Vi,Yl=me("iterator"),Xl=function(e){if(!ql(e))return Kl(e,Yl)||Kl(e,"@@iterator")||Ql[zl(e)]},$l=Ue,Zl=et,ed=Re,td=Ye,id=Xl,rd=TypeError,nd=function(e,t){var i=arguments.length<2?id(e):t;if(Zl(i))return ed($l(i,e));throw rd(td(e)+" is not iterable")},od=Ue,ad=Re,sd=rt,cd=function(e,t,i){var r,n;ad(e);try{if(!(r=sd(e,"return"))){if("throw"===t)throw i;return i}r=od(r,e)}catch(pV){n=!0,r=pV}if("throw"===t)throw i;if(n)throw r;return ad(r),i},ld=Ts,dd=Ue,ud=Re,hd=Ye,pd=Jl,md=Ht,_d=Ge,fd=nd,gd=Xl,vd=cd,Td=TypeError,Sd=function(e,t){this.stopped=e,this.result=t},yd=Sd.prototype,Ed=function(e,t,i){var r,n,o,a,s,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),_=ld(t,d),f=function(e){return r&&vd(r,"normal",e),new Sd(!0,e)},g=function(e){return u?(ud(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=gd(e)))throw Td(hd(e)+" is not iterable");if(pd(n)){for(o=0,a=md(e);a>o;o++)if((s=g(e[o]))&&_d(yd,s))return s;return new Sd(!1)}r=fd(e,n)}for(c=h?e.next:r.next;!(l=dd(c,r)).done;){try{s=g(l.value)}catch(pV){vd(r,"throw",pV)}if("object"==typeof s&&s&&_d(yd,s))return s}return new Sd(!1)},Id=me("iterator"),Cd=!1;try{var Rd=0,Ad={next:function(){return{done:!!Rd++}},return:function(){Cd=!0}};Ad[Id]=function(){return this},Array.from(Ad,(function(){throw 2}))}catch(pV){}var bd=function(e,t){if(!t&&!Cd)return!1;var i=!1;try{var r={};r[Id]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(pV){}return i},kd=Rc,wd=jc.CONSTRUCTOR||!bd((function(e){kd.all(e).then(void 0,(function(){}))})),Pd=Ue,Dd=et,Nd=Hc,Od=Cc,Md=Ed;Mn({target:"Promise",stat:!0,forced:wd},{all:function(e){var t=this,i=Nd.f(t),r=i.resolve,n=i.reject,o=Od((function(){var i=Dd(t.resolve),o=[],a=0,s=1;Md(e,(function(e){var c=a++,l=!1;s++,Pd(i,t,e).then((function(e){l||(l=!0,o[c]=e,--s||r(o))}),n)})),--s||r(o)}));return o.error&&n(o.value),i.promise}});var Ld=Mn,xd=jc.CONSTRUCTOR,Vd=Rc,Ud=He,Fd=ve,Bd=$r,jd=Vd&&Vd.prototype;if(Ld({target:"Promise",proto:!0,forced:xd,real:!0},{catch:function(e){return this.then(void 0,e)}}),Fd(Vd)){var Hd=Ud("Promise").prototype.catch;jd.catch!==Hd&&Bd(jd,"catch",Hd,{unsafe:!0})}var Gd=Ue,Wd=et,Jd=Hc,zd=Cc,Kd=Ed;Mn({target:"Promise",stat:!0,forced:wd},{race:function(e){var t=this,i=Jd.f(t),r=i.reject,n=zd((function(){var n=Wd(t.resolve);Kd(e,(function(e){Gd(n,t,e).then(i.resolve,r)}))}));return n.error&&r(n.value),i.promise}});var qd=Ue,Qd=Hc;Mn({target:"Promise",stat:!0,forced:jc.CONSTRUCTOR},{reject:function(e){var t=Qd.f(this);return qd(t.reject,void 0,e),t.promise}});var Yd=Re,Xd=ye,$d=Hc,Zd=function(e,t){if(Yd(e),Xd(t)&&t.constructor===e)return t;var i=$d.f(e);return(0,i.resolve)(t),i.promise},eu=Mn,tu=jc.CONSTRUCTOR,iu=Zd;He("Promise"),eu({target:"Promise",stat:!0,forced:tu},{resolve:function(e){return iu(this,e)}});var ru=Ma,nu=String,ou=function(e){if("Symbol"===ru(e))throw TypeError("Cannot convert a Symbol value to a string");return nu(e)},au=Mn,su=be,cu=s,lu=H,du=ve,uu=Ge,hu=ou,pu=va,mu=gn,_u=R.Symbol,fu=_u&&_u.prototype;if(su&&du(_u)&&(!("description"in fu)||void 0!==_u().description)){var gu={},vu=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:hu(arguments[0]),t=uu(fu,this)?new _u(e):void 0===e?_u():_u(e);return""===e&&(gu[t]=!0),t};mu(vu,_u),vu.prototype=fu,fu.constructor=vu;var Tu="Symbol(test)"==String(_u("test")),Su=cu(fu.valueOf),yu=cu(fu.toString),Eu=/^Symbol\((.*)\)[^)]+$/,Iu=cu("".replace),Cu=cu("".slice);pu(fu,"description",{configurable:!0,get:function(){var e=Su(this);if(lu(gu,e))return"";var t=yu(e),i=Tu?Cu(t,7,-1):Iu(t,Eu,"$1");return""===i?void 0:i}}),au({global:!0,constructor:!0,forced:!0},{Symbol:vu})}var Ru=Re,Au=function(){var e=Ru(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},bu=t,ku=R.RegExp,wu=bu((function(){var e=ku("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),Pu=wu||bu((function(){return!ku("a","y").sticky})),Du={BROKEN_CARET:wu||bu((function(){var e=ku("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),MISSED_STICKY:Pu,UNSUPPORTED_Y:wu},Nu=t,Ou=R.RegExp,Mu=Nu((function(){var e=Ou(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),Lu=t,xu=R.RegExp,Vu=Lu((function(){var e=xu("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Uu=Ue,Fu=s,Bu=ou,ju=Au,Hu=Du,Gu=bi,Wu=nr.get,Ju=Mu,zu=Vu,Ku=A("native-string-replace",String.prototype.replace),qu=RegExp.prototype.exec,Qu=qu,Yu=Fu("".charAt),Xu=Fu("".indexOf),$u=Fu("".replace),Zu=Fu("".slice),eh=function(){var e=/a/,t=/b*/g;return Uu(qu,e,"a"),Uu(qu,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),th=Hu.BROKEN_CARET,ih=void 0!==/()??/.exec("")[1];(eh||ih||th||Ju||zu)&&(Qu=function(e){var t,i,r,n,o,a,s,c=this,l=Wu(c),d=Bu(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=Uu(Qu,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=th&&c.sticky,m=Uu(ju,c),_=c.source,f=0,g=d;if(p&&(m=$u(m,"y",""),-1===Xu(m,"g")&&(m+="g"),g=Zu(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Yu(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),ih&&(i=new RegExp("^"+_+"$(?!\\s)",m)),eh&&(r=c.lastIndex),n=Uu(qu,p?i:c,g),p?n?(n.input=Zu(n.input,f),n[0]=Zu(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:eh&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),ih&&n&&n.length>1&&Uu(Ku,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=a=Gu(null),o=0;o<h.length;o++)a[(s=h[o])[0]]=n[s[1]];return n});var rh=Qu;Mn({target:"RegExp",proto:!0,forced:/./.exec!==rh},{exec:rh});var nh=et,oh=F,ah=f,sh=Ht,ch=TypeError,lh=function(e){return function(t,i,r,n){nh(i);var o=oh(t),a=ah(o),s=sh(o),c=e?s-1:0,l=e?-1:1;if(r<2)for(;;){if(c in a){n=a[c],c+=l;break}if(c+=l,e?c<0:s<=c)throw ch("Reduce of empty array with no initial value")}for(;e?c>=0:s>c;c+=l)c in a&&(n=i(n,a[c],c,o));return n}},dh={left:lh(!1),right:lh(!0)},uh=t,hh=function(e,t){var i=[][e];return!!i&&uh((function(){i.call(null,t||function(){return 1},1)}))},ph=dh.left;Mn({target:"Array",proto:!0,forced:!_a&&te>79&&te<83||!hh("reduce")},{reduce:function(e){var t=arguments.length;return ph(this,e,t,t>1?arguments[1]:void 0)}});var mh=u,_h=Array.isArray||function(e){return"Array"==mh(e)},fh=_h,gh=$a,vh=ye,Th=me("species"),Sh=Array,yh=function(e){var t;return fh(e)&&(t=e.constructor,(gh(t)&&(t===Sh||fh(t.prototype))||vh(t)&&null===(t=t[Th]))&&(t=void 0)),void 0===t?Sh:t},Eh=Ts,Ih=f,Ch=F,Rh=Ht,Ah=function(e,t){return new(yh(e))(0===t?0:t)},bh=s([].push),kh=function(e){var t=1==e,i=2==e,r=3==e,n=4==e,o=6==e,a=7==e,s=5==e||o;return function(c,l,d,u){for(var h,p,m=Ch(c),_=Ih(m),f=Eh(l,d),g=Rh(_),v=0,T=u||Ah,S=t?T(c,g):i||a?T(c,0):void 0;g>v;v++)if((s||v in _)&&(p=f(h=_[v],v,m),e))if(t)S[v]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return v;case 2:bh(S,h)}else switch(e){case 4:return!1;case 7:bh(S,h)}return o?-1:r||n?n:S}},wh={forEach:kh(0),map:kh(1),filter:kh(2),some:kh(3),every:kh(4),find:kh(5),findIndex:kh(6),filterReject:kh(7)},Ph=wh.forEach,Dh=hh("forEach")?[].forEach:function(e){return Ph(this,e,arguments.length>1?arguments[1]:void 0)},Nh=R,Oh=ea,Mh=ra,Lh=Dh,xh=Wi,Vh=function(e){if(e&&e.forEach!==Lh)try{xh(e,"forEach",Lh)}catch(pV){e.forEach=Lh}};for(var Uh in Oh)Oh[Uh]&&Vh(Nh[Uh]&&Nh[Uh].prototype);Vh(Mh);var Fh=Kt.includes,Bh=xi;Mn({target:"Array",proto:!0,forced:t((function(){return!Array(1).includes()}))},{includes:function(e){return Fh(this,e,arguments.length>1?arguments[1]:void 0)}}),Bh("includes");var jh=_s,Hh=$r,Gh=rh,Wh=t,Jh=me,zh=Wi,Kh=Jh("species"),qh=RegExp.prototype,Qh=s,Yh=Ot,Xh=ou,$h=S,Zh=Qh("".charAt),ep=Qh("".charCodeAt),tp=Qh("".slice),ip=function(e){return function(t,i){var r,n,o=Xh($h(t)),a=Yh(i),s=o.length;return a<0||a>=s?e?"":void 0:(r=ep(o,a))<55296||r>56319||a+1===s||(n=ep(o,a+1))<56320||n>57343?e?Zh(o,a):r:e?tp(o,a,a+2):n-56320+(r-55296<<10)+65536}},rp={codeAt:ip(!1),charAt:ip(!0)},np=rp.charAt,op=s,ap=F,sp=Math.floor,cp=op("".charAt),lp=op("".replace),dp=op("".slice),up=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,hp=/\$([$&'`]|\d{1,2})/g,pp=Ue,mp=Re,_p=ve,fp=u,gp=rh,vp=TypeError,Tp=hs,Sp=Ue,yp=s,Ep=function(e,t,i,r){var n=Jh(e),o=!Wh((function(){var t={};return t[n]=function(){return 7},7!=""[e](t)})),a=o&&!Wh((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[Kh]=function(){return i},i.flags="",i[n]=/./[n]),i.exec=function(){return t=!0,null},i[n](""),!t}));if(!o||!a||i){var s=jh(/./[n]),c=t(n,""[e],(function(e,t,i,r,n){var a=jh(e),c=t.exec;return c===Gh||c===qh.exec?o&&!n?{done:!0,value:s(t,i,r)}:{done:!0,value:a(i,t,r)}:{done:!1}}));Hh(String.prototype,e,c[0]),Hh(qh,n,c[1])}r&&zh(qh[n],"sham",!0)},Ip=t,Cp=Re,Rp=ve,Ap=g,bp=Ot,kp=Bt,wp=ou,Pp=S,Dp=function(e,t,i){return t+(i?np(e,t).length:1)},Np=rt,Op=function(e,t,i,r,n,o){var a=i+e.length,s=r.length,c=hp;return void 0!==n&&(n=ap(n),c=up),lp(o,c,(function(o,c){var l;switch(cp(c,0)){case"$":return"$";case"&":return e;case"`":return dp(t,0,i);case"'":return dp(t,a);case"<":l=n[dp(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>s){var u=sp(d/10);return 0===u?o:u<=s?void 0===r[u-1]?cp(c,1):r[u-1]+cp(c,1):o}l=r[d-1]}return void 0===l?"":l}))},Mp=function(e,t){var i=e.exec;if(_p(i)){var r=pp(i,e,t);return null!==r&&mp(r),r}if("RegExp"===fp(e))return pp(gp,e,t);throw vp("RegExp#exec called on incompatible receiver")},Lp=me("replace"),xp=Math.max,Vp=Math.min,Up=yp([].concat),Fp=yp([].push),Bp=yp("".indexOf),jp=yp("".slice),Hp="$0"==="a".replace(/./,"$0"),Gp=!!/./[Lp]&&""===/./[Lp]("a","$0");Ep("replace",(function(e,t,i){var r=Gp?"$":"$0";return[function(e,i){var r=Pp(this),n=Ap(e)?void 0:Np(e,Lp);return n?Sp(n,e,r,i):Sp(t,wp(r),e,i)},function(e,n){var o=Cp(this),a=wp(e);if("string"==typeof n&&-1===Bp(n,r)&&-1===Bp(n,"$<")){var s=i(t,o,a,n);if(s.done)return s.value}var c=Rp(n);c||(n=wp(n));var l=o.global;if(l){var d=o.unicode;o.lastIndex=0}for(var u=[];;){var h=Mp(o,a);if(null===h)break;if(Fp(u,h),!l)break;""===wp(h[0])&&(o.lastIndex=Dp(a,kp(o.lastIndex),d))}for(var p,m="",_=0,f=0;f<u.length;f++){for(var g=wp((h=u[f])[0]),v=xp(Vp(bp(h.index),a.length),0),T=[],S=1;S<h.length;S++)Fp(T,void 0===(p=h[S])?p:String(p));var y=h.groups;if(c){var E=Up([g],T,v,a);void 0!==y&&Fp(E,y);var I=wp(Tp(n,void 0,E))}else I=Op(g,a,v,T,y,n);v>=_&&(m+=jp(a,_,v)+I,_=v+g.length)}return m+jp(a,_)}]}),!!Ip((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}))||!Hp||Gp);var Wp=ve,Jp=ye,zp=To,Kp=function(e,t,i){var r,n;return zp&&Wp(r=t.constructor)&&r!==i&&Jp(n=r.prototype)&&n!==i.prototype&&zp(e,n),e},qp=ye,Qp=u,Yp=me("match"),Xp=Ue,$p=H,Zp=Ge,em=Au,tm=RegExp.prototype,im=we.f,rm=be,nm=R,om=s,am=An,sm=Kp,cm=Wi,lm=Zr.f,dm=Ge,um=function(e){var t;return qp(e)&&(void 0!==(t=e[Yp])?!!t:"RegExp"==Qp(e))},hm=ou,pm=function(e){var t=e.flags;return void 0!==t||"flags"in tm||$p(e,"flags")||!Zp(tm,e)?t:Xp(em,e)},mm=Du,_m=function(e,t,i){i in e||im(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},fm=$r,gm=t,vm=H,Tm=nr.enforce,Sm=Ia,ym=Mu,Em=Vu,Im=me("match"),Cm=nm.RegExp,Rm=Cm.prototype,Am=nm.SyntaxError,bm=om(Rm.exec),km=om("".charAt),wm=om("".replace),Pm=om("".indexOf),Dm=om("".slice),Nm=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,Om=/a/g,Mm=/a/g,Lm=new Cm(Om)!==Om,xm=mm.MISSED_STICKY,Vm=mm.UNSUPPORTED_Y,Um=rm&&(!Lm||xm||ym||Em||gm((function(){return Mm[Im]=!1,Cm(Om)!=Om||Cm(Mm)==Mm||"/a/i"!=Cm(Om,"i")})));if(am("RegExp",Um)){for(var Fm=function(e,t){var i,r,n,o,a,s,c=dm(Rm,this),l=um(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Fm)return e;if((l||dm(Rm,e))&&(e=e.source,d&&(t=pm(h))),e=void 0===e?"":hm(e),t=void 0===t?"":hm(t),h=e,ym&&"dotAll"in Om&&(r=!!t&&Pm(t,"s")>-1)&&(t=wm(t,/s/g,"")),i=t,xm&&"sticky"in Om&&(n=!!t&&Pm(t,"y")>-1)&&Vm&&(t=wm(t,/y/g,"")),Em&&(o=function(e){for(var t,i=e.length,r=0,n="",o=[],a={},s=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=km(e,r)))t+=km(e,++r);else if("]"===t)s=!1;else if(!s)switch(!0){case"["===t:s=!0;break;case"("===t:bm(Nm,Dm(e,r+1))&&(r+=2,c=!0),n+=t,l++;continue;case">"===t&&c:if(""===d||vm(a,d))throw new Am("Invalid capture group name");a[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]),a=sm(Cm(e,t),c?this:Rm,Fm),(r||n||u.length)&&(s=Tm(a),r&&(s.dotAll=!0,s.raw=Fm(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=km(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+km(e,++r);return n}(e),i)),n&&(s.sticky=!0),u.length&&(s.groups=u)),e!==h)try{cm(a,"source",""===h?"(?:)":h)}catch(pV){}return a},Bm=lm(Cm),jm=0;Bm.length>jm;)_m(Fm,Cm,Bm[jm++]);Rm.constructor=Fm,Fm.prototype=Rm,fm(nm,"RegExp",Fm,{constructor:!0})}Sm("RegExp");var Hm="\t\n\v\f\r \u2028\u2029\ufeff",Gm=S,Wm=ou,Jm=Hm,zm=s("".replace),Km=RegExp("^["+Jm+"]+"),qm=RegExp("(^|[^"+Jm+"])["+Jm+"]+$"),Qm=function(e){return function(t){var i=Wm(Gm(t));return 1&e&&(i=zm(i,Km,"")),2&e&&(i=zm(i,qm,"$1")),i}},Ym={start:Qm(1),end:Qm(2),trim:Qm(3)},Xm=Ar.PROPER,$m=t,Zm=Hm,e_=Ym.trim;Mn({target:"String",proto:!0,forced:function(e){return $m((function(){return!!Zm[e]()||"
"!=="
"[e]()||Xm&&Zm[e].name!==e}))}("trim")},{trim:function(){return e_(this)}});var t_=Ue;Mn({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return t_(URL.prototype.toString,this)}});var i_=Mn,r_=Rc,n_=t,o_=He,a_=ve,s_=ss,c_=Zd,l_=$r,d_=r_&&r_.prototype;if(i_({target:"Promise",proto:!0,real:!0,forced:!!r_&&n_((function(){d_.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=s_(this,o_("Promise")),i=a_(e);return this.then(i?function(i){return c_(t,e()).then((function(){return i}))}:e,i?function(i){return c_(t,e()).then((function(){throw i}))}:e)}}),a_(r_)){var u_=o_("Promise").prototype.finally;d_.finally!==u_&&l_(d_,"finally",u_,{unsafe:!0})}var h_=Ot,p_=ou,m_=S,__=RangeError,f_=s,g_=Bt,v_=ou,T_=S,S_=f_((function(e){var t=p_(m_(this)),i="",r=h_(e);if(r<0||Infinity==r)throw __("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i})),y_=f_("".slice),E_=Math.ceil,I_=function(e){return function(t,i,r){var n,o,a=v_(T_(t)),s=g_(i),c=a.length,l=void 0===r?" ":v_(r);return s<=c||""==l?a:((o=S_(l,E_((n=s-c)/l.length))).length>n&&(o=y_(o,0,n)),e?a+o:o+a)}},C_={start:I_(!1),end:I_(!0)},R_=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(q),A_=C_.start;Mn({target:"String",proto:!0,forced:R_},{padStart:function(e){return A_(this,e,arguments.length>1?arguments[1]:void 0)}});var b_=t,k_=be,w_=me("iterator"),P_=!b_((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i="";return e.pathname="c%20d",t.forEach((function(e,r){t.delete("b"),i+=r+e})),!t.size&&!k_||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[w_]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==i||"x"!==new URL("http://x",void 0).host})),D_=$r,N_=function(e,t,i){for(var r in t)D_(e,r,t[r],i);return e},O_=vt,M_=we,L_=ji,x_=function(e,t,i){var r=O_(t);r in e?M_.f(e,r,L_(0,i)):e[r]=i},V_=Vt,U_=Ht,F_=x_,B_=Array,j_=Math.max,H_=function(e,t,i){for(var r=U_(e),n=V_(t,r),o=V_(void 0===i?r:i,r),a=B_(j_(o-n,0)),s=0;n<o;n++,s++)F_(a,s,e[n]);return a.length=s,a},G_=H_,W_=Math.floor,J_=function(e,t){var i=e.length,r=W_(i/2);return i<8?z_(e,t):K_(e,J_(G_(e,0,r),t),J_(G_(e,r),t),t)},z_=function(e,t){for(var i,r,n=e.length,o=1;o<n;){for(r=o,i=e[o];r&&t(e[r-1],i)>0;)e[r]=e[--r];r!==o++&&(e[r]=i)}return e},K_=function(e,t,i,r){for(var n=t.length,o=i.length,a=0,s=0;a<n||s<o;)e[a+s]=a<n&&s<o?r(t[a],i[s])<=0?t[a++]:i[s++]:a<n?t[a++]:i[s++];return e},q_=J_,Q_=Mn,Y_=R,X_=Ue,$_=s,Z_=be,ef=P_,tf=$r,rf=va,nf=N_,of=io,af=lo,sf=nr,cf=Aa,lf=ve,df=H,uf=Ts,hf=Ma,pf=Re,mf=ye,_f=ou,ff=bi,gf=ji,vf=nd,Tf=Xl,Sf=Es,yf=q_,Ef=me("iterator"),If="URLSearchParams",Cf="URLSearchParamsIterator",Rf=sf.set,Af=sf.getterFor(If),bf=sf.getterFor(Cf),kf=Object.getOwnPropertyDescriptor,wf=function(e){if(!Z_)return Y_[e];var t=kf(Y_,e);return t&&t.value},Pf=wf("fetch"),Df=wf("Request"),Nf=wf("Headers"),Of=Df&&Df.prototype,Mf=Nf&&Nf.prototype,Lf=Y_.RegExp,xf=Y_.TypeError,Vf=Y_.decodeURIComponent,Uf=Y_.encodeURIComponent,Ff=$_("".charAt),Bf=$_([].join),jf=$_([].push),Hf=$_("".replace),Gf=$_([].shift),Wf=$_([].splice),Jf=$_("".split),zf=$_("".slice),Kf=/\+/g,qf=Array(4),Qf=function(e){return qf[e-1]||(qf[e-1]=Lf("((?:%[\\da-f]{2}){"+e+"})","gi"))},Yf=function(e){try{return Vf(e)}catch(pV){return e}},Xf=function(e){var t=Hf(e,Kf," "),i=4;try{return Vf(t)}catch(pV){for(;i;)t=Hf(t,Qf(i--),Yf);return t}},$f=/[!'()~]|%20/g,Zf={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},eg=function(e){return Zf[e]},tg=function(e){return Hf(Uf(e),$f,eg)},ig=af((function(e,t){Rf(this,{type:Cf,iterator:vf(Af(e).entries),kind:t})}),"Iterator",(function(){var e=bf(this),t=e.kind,i=e.iterator.next(),r=i.value;return i.done||(i.value="keys"===t?r.key:"values"===t?r.value:[r.key,r.value]),i}),!0),rg=function(e){this.entries=[],this.url=null,void 0!==e&&(mf(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===Ff(e,0)?zf(e,1):e:_f(e)))};rg.prototype={type:If,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,a,s,c=Tf(e);if(c)for(i=(t=vf(e,c)).next;!(r=X_(i,t)).done;){if(o=(n=vf(pf(r.value))).next,(a=X_(o,n)).done||(s=X_(o,n)).done||!X_(o,n).done)throw xf("Expected sequence with length 2");jf(this.entries,{key:_f(a.value),value:_f(s.value)})}else for(var l in e)df(e,l)&&jf(this.entries,{key:l,value:_f(e[l])})},parseQuery:function(e){if(e)for(var t,i,r=Jf(e,"&"),n=0;n<r.length;)(t=r[n++]).length&&(i=Jf(t,"="),jf(this.entries,{key:Xf(Gf(i)),value:Xf(Bf(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],jf(i,tg(e.key)+"="+tg(e.value));return Bf(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var ng=function(){cf(this,og);var e=arguments.length>0?arguments[0]:void 0,t=Rf(this,new rg(e));Z_||(this.length=t.entries.length)},og=ng.prototype;if(nf(og,{append:function(e,t){Sf(arguments.length,2);var i=Af(this);jf(i.entries,{key:_f(e),value:_f(t)}),Z_||this.length++,i.updateURL()},delete:function(e){Sf(arguments.length,1);for(var t=Af(this),i=t.entries,r=_f(e),n=0;n<i.length;)i[n].key===r?Wf(i,n,1):n++;Z_||(this.length=i.length),t.updateURL()},get:function(e){Sf(arguments.length,1);for(var t=Af(this).entries,i=_f(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){Sf(arguments.length,1);for(var t=Af(this).entries,i=_f(e),r=[],n=0;n<t.length;n++)t[n].key===i&&jf(r,t[n].value);return r},has:function(e){Sf(arguments.length,1);for(var t=Af(this).entries,i=_f(e),r=0;r<t.length;)if(t[r++].key===i)return!0;return!1},set:function(e,t){Sf(arguments.length,1);for(var i,r=Af(this),n=r.entries,o=!1,a=_f(e),s=_f(t),c=0;c<n.length;c++)(i=n[c]).key===a&&(o?Wf(n,c--,1):(o=!0,i.value=s));o||jf(n,{key:a,value:s}),Z_||(this.length=n.length),r.updateURL()},sort:function(){var e=Af(this);yf(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=Af(this).entries,r=uf(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 ig(this,"keys")},values:function(){return new ig(this,"values")},entries:function(){return new ig(this,"entries")}},{enumerable:!0}),tf(og,Ef,og.entries,{name:"entries"}),tf(og,"toString",(function(){return Af(this).serialize()}),{enumerable:!0}),Z_&&rf(og,"size",{get:function(){return Af(this).entries.length},configurable:!0,enumerable:!0}),of(ng,If),Q_({global:!0,constructor:!0,forced:!ef},{URLSearchParams:ng}),!ef&&lf(Nf)){var ag=$_(Mf.has),sg=$_(Mf.set),cg=function(e){if(mf(e)){var t,i=e.body;if(hf(i)===If)return t=e.headers?new Nf(e.headers):new Nf,ag(t,"content-type")||sg(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),ff(e,{body:gf(0,_f(i)),headers:gf(0,t)})}return e};if(lf(Pf)&&Q_({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return Pf(e,arguments.length>1?cg(arguments[1]):{})}}),lf(Df)){var lg=function(e){return cf(this,Of),new Df(e,arguments.length>1?cg(arguments[1]):{})};Of.constructor=lg,lg.prototype=Of,Q_({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:lg})}}var dg={URLSearchParams:ng,getState:Af},ug=rp.charAt,hg=ou,pg=nr,mg=Fo,_g=Bo,fg="String Iterator",gg=pg.set,vg=pg.getterFor(fg);mg(String,"String",(function(e){gg(this,{type:fg,string:hg(e),index:0})}),(function(){var e,t=vg(this),i=t.string,r=t.index;return r>=i.length?_g(void 0,!0):(e=ug(i,r),t.index+=e.length,_g(e,!1))}));var Tg,Sg=be,yg=s,Eg=Ue,Ig=t,Cg=ni,Rg=rn,Ag=ar,bg=F,kg=f,wg=Object.assign,Pg=Object.defineProperty,Dg=yg([].concat),Ng=!wg||Ig((function(){if(Sg&&1!==wg({b:1},wg(Pg({},"a",{enumerable:!0,get:function(){Pg(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol(),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach((function(e){t[e]=e})),7!=wg({},e)[i]||Cg(wg({},t)).join("")!=r}))?function(e,t){for(var i=bg(e),r=arguments.length,n=1,o=Rg.f,a=Ag.f;r>n;)for(var s,c=kg(arguments[n++]),l=o?Dg(Cg(c),o(c)):Cg(c),d=l.length,u=0;d>u;)s=l[u++],Sg&&!Eg(a,c,s)||(i[s]=c[s]);return i}:wg,Og=Re,Mg=cd,Lg=Ts,xg=Ue,Vg=F,Ug=function(e,t,i,r){try{return r?t(Og(i)[0],i[1]):t(i)}catch(pV){Mg(e,"throw",pV)}},Fg=Jl,Bg=$a,jg=Ht,Hg=x_,Gg=nd,Wg=Xl,Jg=Array,zg=s,Kg=2147483647,qg=/[^\0-\u007E]/,Qg=/[.\u3002\uFF0E\uFF61]/g,Yg="Overflow: input needs wider integers to process",Xg=RangeError,$g=zg(Qg.exec),Zg=Math.floor,ev=String.fromCharCode,tv=zg("".charCodeAt),iv=zg([].join),rv=zg([].push),nv=zg("".replace),ov=zg("".split),av=zg("".toLowerCase),sv=function(e){return e+22+75*(e<26)},cv=function(e,t,i){var r=0;for(e=i?Zg(e/700):e>>1,e+=Zg(e/t);e>455;)e=Zg(e/35),r+=36;return Zg(r+36*e/(e+38))},lv=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=tv(e,i++);if(n>=55296&&n<=56319&&i<r){var o=tv(e,i++);56320==(64512&o)?rv(t,((1023&n)<<10)+(1023&o)+65536):(rv(t,n),i--)}else rv(t,n)}return t}(e);var i,r,n=e.length,o=128,a=0,s=72;for(i=0;i<e.length;i++)(r=e[i])<128&&rv(t,ev(r));var c=t.length,l=c;for(c&&rv(t,"-");l<n;){var d=Kg;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>Zg((Kg-a)/u))throw Xg(Yg);for(a+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++a>Kg)throw Xg(Yg);if(r==o){for(var h=a,p=36;;){var m=p<=s?1:p>=s+26?26:p-s;if(h<m)break;var _=h-m,f=36-m;rv(t,ev(sv(m+_%f))),h=Zg(_/f),p+=36}rv(t,ev(sv(h))),s=cv(a,u,l==c),a=0,l++}}a++,o++}return iv(t,"")},dv=Mn,uv=be,hv=P_,pv=R,mv=Ts,_v=s,fv=$r,gv=va,vv=Aa,Tv=H,Sv=Ng,yv=function(e){var t=Vg(e),i=Bg(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=Lg(n,r>2?arguments[2]:void 0));var a,s,c,l,d,u,h=Wg(t),p=0;if(!h||this===Jg&&Fg(h))for(a=jg(t),s=i?new this(a):Jg(a);a>p;p++)u=o?n(t[p],p):t[p],Hg(s,p,u);else for(d=(l=Gg(t,h)).next,s=i?new this:[];!(c=xg(d,l)).done;p++)u=o?Ug(l,n,[c.value,p],!0):c.value,Hg(s,p,u);return s.length=p,s},Ev=H_,Iv=rp.codeAt,Cv=function(e){var t,i,r=[],n=ov(nv(av(e),Qg,"."),".");for(t=0;t<n.length;t++)i=n[t],rv(r,$g(qg,i)?"xn--"+lv(i):i);return iv(r,".")},Rv=ou,Av=io,bv=Es,kv=dg,wv=nr,Pv=wv.set,Dv=wv.getterFor("URL"),Nv=kv.URLSearchParams,Ov=kv.getState,Mv=pv.URL,Lv=pv.TypeError,xv=pv.parseInt,Vv=Math.floor,Uv=Math.pow,Fv=_v("".charAt),Bv=_v(/./.exec),jv=_v([].join),Hv=_v(1..toString),Gv=_v([].pop),Wv=_v([].push),Jv=_v("".replace),zv=_v([].shift),Kv=_v("".split),qv=_v("".slice),Qv=_v("".toLowerCase),Yv=_v([].unshift),Xv="Invalid scheme",$v="Invalid host",Zv="Invalid port",eT=/[a-z]/i,tT=/[\d+-.a-z]/i,iT=/\d/,rT=/^0x/i,nT=/^[0-7]+$/,oT=/^\d+$/,aT=/^[\da-f]+$/i,sT=/[\0\t\n\r #%/:<>?@[\\\]^|]/,cT=/[\0\t\n\r #/:<>?@[\\\]^|]/,lT=/^[\u0000-\u0020]+/,dT=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,uT=/[\t\n\r]/g,hT=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)Yv(t,e%256),e=Vv(e/256);return jv(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&&(t=r,i=n),t}(e),i=0;i<8;i++)n&&0===e[i]||(n&&(n=!1),r===i?(t+=i?":":"::",n=!0):(t+=Hv(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},pT={},mT=Sv({},pT,{" ":1,'"':1,"<":1,">":1,"`":1}),_T=Sv({},mT,{"#":1,"?":1,"{":1,"}":1}),fT=Sv({},_T,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),gT=function(e,t){var i=Iv(e,0);return i>32&&i<127&&!Tv(t,e)?e:encodeURIComponent(e)},vT={ftp:21,file:null,http:80,https:443,ws:80,wss:443},TT=function(e,t){var i;return 2==e.length&&Bv(eT,Fv(e,0))&&(":"==(i=Fv(e,1))||!t&&"|"==i)},ST=function(e){var t;return e.length>1&&TT(qv(e,0,2))&&(2==e.length||"/"===(t=Fv(e,2))||"\\"===t||"?"===t||"#"===t)},yT=function(e){return"."===e||"%2e"===Qv(e)},ET={},IT={},CT={},RT={},AT={},bT={},kT={},wT={},PT={},DT={},NT={},OT={},MT={},LT={},xT={},VT={},UT={},FT={},BT={},jT={},HT={},GT=function(e,t,i){var r,n,o,a=Rv(e);if(t){if(n=this.parse(a))throw Lv(n);this.searchParams=null}else{if(void 0!==i&&(r=new GT(i,!0)),n=this.parse(a,null,r))throw Lv(n);(o=Ov(new Nv)).bindURL(this),this.searchParams=o}};GT.prototype={type:"URL",parse:function(e,t,i){var r,n,o,a,s,c=this,l=t||ET,d=0,u="",h=!1,p=!1,m=!1;for(e=Rv(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=Jv(e,lT,""),e=Jv(e,dT,"$1")),e=Jv(e,uT,""),r=yv(e);d<=r.length;){switch(n=r[d],l){case ET:if(!n||!Bv(eT,n)){if(t)return Xv;l=CT;continue}u+=Qv(n),l=IT;break;case IT:if(n&&(Bv(tT,n)||"+"==n||"-"==n||"."==n))u+=Qv(n);else{if(":"!=n){if(t)return Xv;u="",l=CT,d=0;continue}if(t&&(c.isSpecial()!=Tv(vT,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&vT[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?l=LT:c.isSpecial()&&i&&i.scheme==c.scheme?l=RT:c.isSpecial()?l=wT:"/"==r[d+1]?(l=AT,d++):(c.cannotBeABaseURL=!0,Wv(c.path,""),l=BT)}break;case CT:if(!i||i.cannotBeABaseURL&&"#"!=n)return Xv;if(i.cannotBeABaseURL&&"#"==n){c.scheme=i.scheme,c.path=Ev(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=HT;break}l="file"==i.scheme?LT:bT;continue;case RT:if("/"!=n||"/"!=r[d+1]){l=bT;continue}l=PT,d++;break;case AT:if("/"==n){l=DT;break}l=FT;continue;case bT:if(c.scheme=i.scheme,n==Tg)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Ev(i.path),c.query=i.query;else if("/"==n||"\\"==n&&c.isSpecial())l=kT;else if("?"==n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Ev(i.path),c.query="",l=jT;else{if("#"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Ev(i.path),c.path.length--,l=FT;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Ev(i.path),c.query=i.query,c.fragment="",l=HT}break;case kT:if(!c.isSpecial()||"/"!=n&&"\\"!=n){if("/"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=FT;continue}l=DT}else l=PT;break;case wT:if(l=PT,"/"!=n||"/"!=Fv(u,d+1))continue;d++;break;case PT:if("/"!=n&&"\\"!=n){l=DT;continue}break;case DT:if("@"==n){h&&(u="%40"+u),h=!0,o=yv(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!=f||m){var g=gT(f,fT);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n==Tg||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(h&&""==u)return"Invalid authority";d-=yv(u).length+1,u="",l=NT}else u+=n;break;case NT:case OT:if(t&&"file"==c.scheme){l=VT;continue}if(":"!=n||p){if(n==Tg||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(c.isSpecial()&&""==u)return $v;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(a=c.parseHost(u))return a;if(u="",l=UT,t)return;continue}"["==n?p=!0:"]"==n&&(p=!1),u+=n}else{if(""==u)return $v;if(a=c.parseHost(u))return a;if(u="",l=MT,t==OT)return}break;case MT:if(!Bv(iT,n)){if(n==Tg||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()||t){if(""!=u){var v=xv(u,10);if(v>65535)return Zv;c.port=c.isSpecial()&&v===vT[c.scheme]?null:v,u=""}if(t)return;l=UT;continue}return Zv}u+=n;break;case LT:if(c.scheme="file","/"==n||"\\"==n)l=xT;else{if(!i||"file"!=i.scheme){l=FT;continue}if(n==Tg)c.host=i.host,c.path=Ev(i.path),c.query=i.query;else if("?"==n)c.host=i.host,c.path=Ev(i.path),c.query="",l=jT;else{if("#"!=n){ST(jv(Ev(r,d),""))||(c.host=i.host,c.path=Ev(i.path),c.shortenPath()),l=FT;continue}c.host=i.host,c.path=Ev(i.path),c.query=i.query,c.fragment="",l=HT}}break;case xT:if("/"==n||"\\"==n){l=VT;break}i&&"file"==i.scheme&&!ST(jv(Ev(r,d),""))&&(TT(i.path[0],!0)?Wv(c.path,i.path[0]):c.host=i.host),l=FT;continue;case VT:if(n==Tg||"/"==n||"\\"==n||"?"==n||"#"==n){if(!t&&TT(u))l=FT;else if(""==u){if(c.host="",t)return;l=UT}else{if(a=c.parseHost(u))return a;if("localhost"==c.host&&(c.host=""),t)return;u="",l=UT}continue}u+=n;break;case UT:if(c.isSpecial()){if(l=FT,"/"!=n&&"\\"!=n)continue}else if(t||"?"!=n)if(t||"#"!=n){if(n!=Tg&&(l=FT,"/"!=n))continue}else c.fragment="",l=HT;else c.query="",l=jT;break;case FT:if(n==Tg||"/"==n||"\\"==n&&c.isSpecial()||!t&&("?"==n||"#"==n)){if(".."===(s=Qv(s=u))||"%2e."===s||".%2e"===s||"%2e%2e"===s?(c.shortenPath(),"/"==n||"\\"==n&&c.isSpecial()||Wv(c.path,"")):yT(u)?"/"==n||"\\"==n&&c.isSpecial()||Wv(c.path,""):("file"==c.scheme&&!c.path.length&&TT(u)&&(c.host&&(c.host=""),u=Fv(u,0)+":"),Wv(c.path,u)),u="","file"==c.scheme&&(n==Tg||"?"==n||"#"==n))for(;c.path.length>1&&""===c.path[0];)zv(c.path);"?"==n?(c.query="",l=jT):"#"==n&&(c.fragment="",l=HT)}else u+=gT(n,_T);break;case BT:"?"==n?(c.query="",l=jT):"#"==n?(c.fragment="",l=HT):n!=Tg&&(c.path[0]+=gT(n,pT));break;case jT:t||"#"!=n?n!=Tg&&("'"==n&&c.isSpecial()?c.query+="%27":c.query+="#"==n?"%23":gT(n,pT)):(c.fragment="",l=HT);break;case HT:n!=Tg&&(c.fragment+=gT(n,mT))}d++}},parseHost:function(e){var t,i,r;if("["==Fv(e,0)){if("]"!=Fv(e,e.length-1))return $v;if(t=function(e){var t,i,r,n,o,a,s,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return Fv(e,u)};if(":"==h()){if(":"!=Fv(e,1))return;u+=2,d=++l}for(;h();){if(8==l)return;if(":"!=h()){for(t=i=0;i<4&&Bv(aT,h());)t=16*t+xv(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(!Bv(iT,h()))return;for(;Bv(iT,h());){if(o=xv(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(a=l-d,l=7;0!=l&&a>0;)s=c[l],c[l--]=c[d+a-1],c[d+--a]=s;else if(8!=l)return;return c}(qv(e,1,-1)),!t)return $v;this.host=t}else if(this.isSpecial()){if(e=Cv(e),Bv(sT,e))return $v;if(t=function(e){var t,i,r,n,o,a,s,c=Kv(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"==Fv(n,0)&&(o=Bv(rT,n)?16:8,n=qv(n,8==o?1:2)),""===n)a=0;else{if(!Bv(10==o?oT:8==o?nT:aT,n))return e;a=xv(n,o)}Wv(i,a)}for(r=0;r<t;r++)if(a=i[r],r==t-1){if(a>=Uv(256,5-t))return null}else if(a>255)return null;for(s=Gv(i),r=0;r<i.length;r++)s+=i[r]*Uv(256,3-r);return s}(e),null===t)return $v;this.host=t}else{if(Bv(cT,e))return $v;for(t="",i=yv(e),r=0;r<i.length;r++)t+=gT(i[r],pT);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return Tv(vT,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&TT(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,a=e.path,s=e.query,c=e.fragment,l=t+":";return null!==n?(l+="//",e.includesCredentials()&&(l+=i+(r?":"+r:"")+"@"),l+=hT(n),null!==o&&(l+=":"+o)):"file"==t&&(l+="//"),l+=e.cannotBeABaseURL?a[0]:a.length?"/"+jv(a,"/"):"",null!==s&&(l+="?"+s),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw Lv(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new WT(e.path[0]).origin}catch(pV){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+hT(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(Rv(e)+":",ET)},getUsername:function(){return this.username},setUsername:function(e){var t=yv(Rv(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=gT(t[i],fT)}},getPassword:function(){return this.password},setPassword:function(e){var t=yv(Rv(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=gT(t[i],fT)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?hT(e):hT(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,NT)},getHostname:function(){var e=this.host;return null===e?"":hT(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,OT)},getPort:function(){var e=this.port;return null===e?"":Rv(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=Rv(e))?this.port=null:this.parse(e,MT))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+jv(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,UT))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=Rv(e))?this.query=null:("?"==Fv(e,0)&&(e=qv(e,1)),this.query="",this.parse(e,jT)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=Rv(e))?("#"==Fv(e,0)&&(e=qv(e,1)),this.fragment="",this.parse(e,HT)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var WT=function(e){var t=vv(this,JT),i=bv(arguments.length,1)>1?arguments[1]:void 0,r=Pv(t,new GT(e,!1,i));uv||(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())},JT=WT.prototype,zT=function(e,t){return{get:function(){return Dv(this)[e]()},set:t&&function(e){return Dv(this)[t](e)},configurable:!0,enumerable:!0}};if(uv&&(gv(JT,"href",zT("serialize","setHref")),gv(JT,"origin",zT("getOrigin")),gv(JT,"protocol",zT("getProtocol","setProtocol")),gv(JT,"username",zT("getUsername","setUsername")),gv(JT,"password",zT("getPassword","setPassword")),gv(JT,"host",zT("getHost","setHost")),gv(JT,"hostname",zT("getHostname","setHostname")),gv(JT,"port",zT("getPort","setPort")),gv(JT,"pathname",zT("getPathname","setPathname")),gv(JT,"search",zT("getSearch","setSearch")),gv(JT,"searchParams",zT("getSearchParams")),gv(JT,"hash",zT("getHash","setHash"))),fv(JT,"toJSON",(function(){return Dv(this).serialize()}),{enumerable:!0}),fv(JT,"toString",(function(){return Dv(this).serialize()}),{enumerable:!0}),Mv){var KT=Mv.createObjectURL,qT=Mv.revokeObjectURL;KT&&fv(WT,"createObjectURL",mv(KT,Mv)),qT&&fv(WT,"revokeObjectURL",mv(qT,Mv))}Av(WT,"URL"),dv({global:!0,constructor:!0,forced:!hv,sham:!uv},{URL:WT});var QT="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,YT=Ot,XT=Bt,$T=RangeError,ZT=function(e){if(void 0===e)return 0;var t=YT(e),i=XT(t);if(t!==i)throw $T("Wrong length or index");return i},eS=Array,tS=Math.abs,iS=Math.pow,rS=Math.floor,nS=Math.log,oS=Math.LN2,aS={pack:function(e,t,i){var r,n,o,a=eS(i),s=8*i-t-1,c=(1<<s)-1,l=c>>1,d=23===t?iS(2,-24)-iS(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=tS(e))!=e||Infinity===e?(n=e!=e?1:0,r=c):(r=rS(nS(e)/oS),e*(o=iS(2,-r))<1&&(r--,o*=2),(e+=r+l>=1?d/o:d*iS(2,1-l))*o>=2&&(r++,o/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*o-1)*iS(2,t),r+=l):(n=e*iS(2,l-1)*iS(2,t),r=0));t>=8;)a[h++]=255&n,n/=256,t-=8;for(r=r<<t|n,s+=t;s>0;)a[h++]=255&r,r/=256,s-=8;return a[--h]|=128*u,a},unpack:function(e,t){var i,r=e.length,n=8*r-t-1,o=(1<<n)-1,a=o>>1,s=n-7,c=r-1,l=e[c--],d=127&l;for(l>>=7;s>0;)d=256*d+e[c--],s-=8;for(i=d&(1<<-s)-1,d>>=-s,s+=t;s>0;)i=256*i+e[c--],s-=8;if(0===d)d=1-a;else{if(d===o)return i?NaN:l?-Infinity:Infinity;i+=iS(2,t),d-=a}return(l?-1:1)*i*iS(2,d-t)}},sS=F,cS=Vt,lS=Ht,dS=function(e){for(var t=sS(this),i=lS(t),r=arguments.length,n=cS(r>1?arguments[1]:void 0,i),o=r>2?arguments[2]:void 0,a=void 0===o?i:cS(o,i);a>n;)t[n++]=e;return t},uS=R,hS=s,pS=be,mS=QT,_S=Ar,fS=Wi,gS=va,vS=N_,TS=t,SS=Aa,yS=Ot,ES=Bt,IS=ZT,CS=aS,RS=Gn,AS=To,bS=Zr.f,kS=dS,wS=H_,PS=io,DS=nr,NS=_S.PROPER,OS=_S.CONFIGURABLE,MS="ArrayBuffer",LS="DataView",xS="Wrong index",VS=DS.getterFor(MS),US=DS.getterFor(LS),FS=DS.set,BS=uS.ArrayBuffer,jS=BS,HS=jS&&jS.prototype,GS=uS.DataView,WS=GS&&GS.prototype,JS=Object.prototype,zS=uS.Array,KS=uS.RangeError,qS=hS(kS),QS=hS([].reverse),YS=CS.pack,XS=CS.unpack,$S=function(e){return[255&e]},ZS=function(e){return[255&e,e>>8&255]},ey=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},ty=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},iy=function(e){return YS(e,23,4)},ry=function(e){return YS(e,52,8)},ny=function(e,t,i){gS(e.prototype,t,{configurable:!0,get:function(){return i(this)[t]}})},oy=function(e,t,i,r){var n=IS(i),o=US(e);if(n+t>o.byteLength)throw KS(xS);var a=o.bytes,s=n+o.byteOffset,c=wS(a,s,s+t);return r?c:QS(c)},ay=function(e,t,i,r,n,o){var a=IS(i),s=US(e);if(a+t>s.byteLength)throw KS(xS);for(var c=s.bytes,l=a+s.byteOffset,d=r(+n),u=0;u<t;u++)c[l+u]=d[o?u:t-u-1]};if(mS){var sy=NS&&BS.name!==MS;if(TS((function(){BS(1)}))&&TS((function(){new BS(-1)}))&&!TS((function(){return new BS,new BS(1.5),new BS(NaN),1!=BS.length||sy&&!OS})))sy&&OS&&fS(BS,"name",MS);else{(jS=function(e){return SS(this,HS),new BS(IS(e))}).prototype=HS;for(var cy,ly=bS(BS),dy=0;ly.length>dy;)(cy=ly[dy++])in jS||fS(jS,cy,BS[cy]);HS.constructor=jS}AS&&RS(WS)!==JS&&AS(WS,JS);var uy=new GS(new jS(2)),hy=hS(WS.setInt8);uy.setInt8(0,2147483648),uy.setInt8(1,2147483649),!uy.getInt8(0)&&uy.getInt8(1)||vS(WS,{setInt8:function(e,t){hy(this,e,t<<24>>24)},setUint8:function(e,t){hy(this,e,t<<24>>24)}},{unsafe:!0})}else HS=(jS=function(e){SS(this,HS);var t=IS(e);FS(this,{type:MS,bytes:qS(zS(t),0),byteLength:t}),pS||(this.byteLength=t,this.detached=!1)}).prototype,WS=(GS=function(e,t,i){SS(this,WS),SS(e,HS);var r=VS(e),n=r.byteLength,o=yS(t);if(o<0||o>n)throw KS("Wrong offset");if(o+(i=void 0===i?n-o:ES(i))>n)throw KS("Wrong length");FS(this,{type:LS,buffer:e,byteLength:i,byteOffset:o,bytes:r.bytes}),pS||(this.buffer=e,this.byteLength=i,this.byteOffset=o)}).prototype,pS&&(ny(jS,"byteLength",VS),ny(GS,"buffer",US),ny(GS,"byteLength",US),ny(GS,"byteOffset",US)),vS(WS,{getInt8:function(e){return oy(this,1,e)[0]<<24>>24},getUint8:function(e){return oy(this,1,e)[0]},getInt16:function(e){var t=oy(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=oy(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return ty(oy(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return ty(oy(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return XS(oy(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return XS(oy(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){ay(this,1,e,$S,t)},setUint8:function(e,t){ay(this,1,e,$S,t)},setInt16:function(e,t){ay(this,2,e,ZS,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){ay(this,2,e,ZS,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){ay(this,4,e,ey,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){ay(this,4,e,ey,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){ay(this,4,e,iy,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){ay(this,8,e,ry,t,arguments.length>2?arguments[2]:void 0)}});PS(jS,MS),PS(GS,LS);var py={ArrayBuffer:jS,DataView:GS},my=Ia,_y="ArrayBuffer",fy=py.ArrayBuffer;Mn({global:!0,constructor:!0,forced:R.ArrayBuffer!==fy},{ArrayBuffer:fy}),my(_y);var gy=Mn,vy=_s,Ty=t,Sy=Re,yy=Vt,Ey=Bt,Iy=ss,Cy=py.ArrayBuffer,Ry=py.DataView,Ay=Ry.prototype,by=vy(Cy.prototype.slice),ky=vy(Ay.getUint8),wy=vy(Ay.setUint8);gy({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:Ty((function(){return!new Cy(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(by&&void 0===t)return by(Sy(this),e);for(var i=Sy(this).byteLength,r=yy(e,i),n=yy(void 0===t?i:t,i),o=new(Iy(this,Cy))(Ey(n-r)),a=new Ry(this),s=new Ry(o),c=0;r<n;)wy(s,c++,ky(a,r++));return o}});var Py=Ye,Dy=TypeError,Ny=q.match(/firefox\/(\d+)/i),Oy=!!Ny&&+Ny[1],My=/MSIE|Trident/.test(q),Ly=q.match(/AppleWebKit\/(\d+)\./),xy=!!Ly&&+Ly[1],Vy=Mn,Uy=s,Fy=et,By=F,jy=Ht,Hy=function(e,t){if(!delete e[t])throw Dy("Cannot delete property "+Py(t)+" of "+Py(e))},Gy=ou,Wy=t,Jy=q_,zy=hh,Ky=Oy,qy=My,Qy=te,Yy=xy,Xy=[],$y=Uy(Xy.sort),Zy=Uy(Xy.push),eE=Wy((function(){Xy.sort(void 0)})),tE=Wy((function(){Xy.sort(null)})),iE=zy("sort"),rE=!Wy((function(){if(Qy)return Qy<70;if(!(Ky&&Ky>3)){if(qy)return!0;if(Yy)return Yy<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++)Xy.push({k:t+r,v:i})}for(Xy.sort((function(e,t){return t.v-e.v})),r=0;r<Xy.length;r++)t=Xy[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));Vy({target:"Array",proto:!0,forced:eE||!tE||!iE||!rE},{sort:function(e){void 0!==e&&Fy(e);var t=By(this);if(rE)return void 0===e?$y(t):$y(t,e);var i,r,n=[],o=jy(t);for(r=0;r<o;r++)r in t&&Zy(n,t[r]);for(Jy(n,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:Gy(t)>Gy(i)?1:-1}}(e)),i=jy(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)Hy(t,r++);return t}});var nE,oE,aE,sE={},cE={get exports(){return sE},set exports(e){sE=e}},lE=QT,dE=be,uE=R,hE=ve,pE=ye,mE=H,_E=Ma,fE=Ye,gE=Wi,vE=$r,TE=va,SE=Ge,yE=Gn,EE=To,IE=me,CE=K,RE=nr.enforce,AE=nr.get,bE=uE.Int8Array,kE=bE&&bE.prototype,wE=uE.Uint8ClampedArray,PE=wE&&wE.prototype,DE=bE&&yE(bE),NE=kE&&yE(kE),OE=Object.prototype,ME=uE.TypeError,LE=IE("toStringTag"),xE=CE("TYPED_ARRAY_TAG"),VE="TypedArrayConstructor",UE=lE&&!!EE&&"Opera"!==_E(uE.opera),FE=!1,BE={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},jE={BigInt64Array:8,BigUint64Array:8},HE=function(e){var t=yE(e);if(pE(t)){var i=AE(t);return i&&mE(i,VE)?i.TypedArrayConstructor:HE(t)}},GE=function(e){if(!pE(e))return!1;var t=_E(e);return mE(BE,t)||mE(jE,t)};for(nE in BE)(aE=(oE=uE[nE])&&oE.prototype)?RE(aE).TypedArrayConstructor=oE:UE=!1;for(nE in jE)(aE=(oE=uE[nE])&&oE.prototype)&&(RE(aE).TypedArrayConstructor=oE);if((!UE||!hE(DE)||DE===Function.prototype)&&(DE=function(){throw ME("Incorrect invocation")},UE))for(nE in BE)uE[nE]&&EE(uE[nE],DE);if((!UE||!NE||NE===OE)&&(NE=DE.prototype,UE))for(nE in BE)uE[nE]&&EE(uE[nE].prototype,NE);if(UE&&yE(PE)!==NE&&EE(PE,NE),dE&&!mE(NE,LE))for(nE in FE=!0,TE(NE,LE,{configurable:!0,get:function(){return pE(this)?this[xE]:void 0}}),BE)uE[nE]&&gE(uE[nE],xE,nE);var WE={NATIVE_ARRAY_BUFFER_VIEWS:UE,TYPED_ARRAY_TAG:FE&&xE,aTypedArray:function(e){if(GE(e))return e;throw ME("Target is not a typed array")},aTypedArrayConstructor:function(e){if(hE(e)&&(!EE||SE(DE,e)))return e;throw ME(fE(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(dE){if(i)for(var n in BE){var o=uE[n];if(o&&mE(o.prototype,e))try{delete o.prototype[e]}catch(pV){try{o.prototype[e]=t}catch(a){}}}NE[e]&&!i||vE(NE,e,i?t:UE&&kE[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(dE){if(EE){if(i)for(r in BE)if((n=uE[r])&&mE(n,e))try{delete n[e]}catch(pV){}if(DE[e]&&!i)return;try{return vE(DE,e,i?t:UE&&DE[e]||t)}catch(pV){}}for(r in BE)!(n=uE[r])||n[e]&&!i||vE(n,e,t)}},getTypedArrayConstructor:HE,isView:function(e){if(!pE(e))return!1;var t=_E(e);return"DataView"===t||mE(BE,t)||mE(jE,t)},isTypedArray:GE,TypedArray:DE,TypedArrayPrototype:NE},JE=R,zE=t,KE=bd,qE=WE.NATIVE_ARRAY_BUFFER_VIEWS,QE=JE.ArrayBuffer,YE=JE.Int8Array,XE=!qE||!zE((function(){YE(1)}))||!zE((function(){new YE(-1)}))||!KE((function(e){new YE,new YE(null),new YE(1.5),new YE(e)}),!0)||zE((function(){return 1!==new YE(new QE(2),1,void 0).length})),$E=ye,ZE=Math.floor,eI=Number.isInteger||function(e){return!$E(e)&&isFinite(e)&&ZE(e)===e},tI=Ot,iI=RangeError,rI=function(e){var t=tI(e);if(t<0)throw iI("The argument can't be less than 0");return t},nI=RangeError,oI=function(e,t){var i=rI(e);if(i%t)throw nI("Wrong offset");return i},aI=Ma,sI=_t,cI=TypeError,lI=function(e){var t=sI(e,"number");if("number"==typeof t)throw cI("Can't convert number to bigint");return BigInt(t)},dI=Ts,uI=Ue,hI=is,pI=F,mI=Ht,_I=nd,fI=Xl,gI=Jl,vI=function(e){var t=aI(e);return"BigInt64Array"==t||"BigUint64Array"==t},TI=WE.aTypedArrayConstructor,SI=lI,yI=Mn,EI=R,II=Ue,CI=be,RI=XE,AI=WE,bI=py,kI=Aa,wI=ji,PI=Wi,DI=eI,NI=Bt,OI=ZT,MI=oI,LI=vt,xI=H,VI=Ma,UI=ye,FI=qe,BI=bi,jI=Ge,HI=To,GI=Zr.f,WI=function(e){var t,i,r,n,o,a,s,c,l=hI(this),d=pI(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=fI(d);if(m&&!gI(m))for(c=(s=_I(d,m)).next,d=[];!(a=uI(c,s)).done;)d.push(a.value);for(p&&u>2&&(h=dI(h,arguments[2])),i=mI(d),r=new(TI(l))(i),n=vI(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?SI(o):+o;return r},JI=wh.forEach,zI=Ia,KI=va,qI=we,QI=or,YI=Kp,XI=nr.get,$I=nr.set,ZI=nr.enforce,eC=qI.f,tC=QI.f,iC=Math.round,rC=EI.RangeError,nC=bI.ArrayBuffer,oC=nC.prototype,aC=bI.DataView,sC=AI.NATIVE_ARRAY_BUFFER_VIEWS,cC=AI.TYPED_ARRAY_TAG,lC=AI.TypedArray,dC=AI.TypedArrayPrototype,uC=AI.aTypedArrayConstructor,hC=AI.isTypedArray,pC="BYTES_PER_ELEMENT",mC="Wrong length",_C=function(e,t){uC(e);for(var i=0,r=t.length,n=new e(r);r>i;)n[i]=t[i++];return n},fC=function(e,t){KI(e,t,{configurable:!0,get:function(){return XI(this)[t]}})},gC=function(e){var t;return jI(oC,e)||"ArrayBuffer"==(t=VI(e))||"SharedArrayBuffer"==t},vC=function(e,t){return hC(e)&&!FI(t)&&t in e&&DI(+t)&&t>=0},TC=function(e,t){return t=LI(t),vC(e,t)?wI(2,e[t]):tC(e,t)},SC=function(e,t,i){return t=LI(t),!(vC(e,t)&&UI(i)&&xI(i,"value"))||xI(i,"get")||xI(i,"set")||i.configurable||xI(i,"writable")&&!i.writable||xI(i,"enumerable")&&!i.enumerable?eC(e,t,i):(e[t]=i.value,e)};CI?(sC||(QI.f=TC,qI.f=SC,fC(dC,"buffer"),fC(dC,"byteOffset"),fC(dC,"byteLength"),fC(dC,"length")),yI({target:"Object",stat:!0,forced:!sC},{getOwnPropertyDescriptor:TC,defineProperty:SC}),cE.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,a="set"+e,s=EI[n],c=s,l=c&&c.prototype,d={},u=function(e,t){eC(e,t,{get:function(){return function(e,t){var i=XI(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=XI(e);i&&(n=(n=iC(n))<0?0:n>255?255:255&n),o.view[a](t*r+o.byteOffset,n,!0)}(this,t,e)},enumerable:!0})};sC?RI&&(c=t((function(e,t,i,n){return kI(e,l),YI(UI(t)?gC(t)?void 0!==n?new s(t,MI(i,r),n):void 0!==i?new s(t,MI(i,r)):new s(t):hC(t)?_C(c,t):II(WI,c,t):new s(OI(t)),e,c)})),HI&&HI(c,lC),JI(GI(s),(function(e){e in c||PI(c,e,s[e])})),c.prototype=l):(c=t((function(e,t,i,n){kI(e,l);var o,a,s,d=0,h=0;if(UI(t)){if(!gC(t))return hC(t)?_C(c,t):II(WI,c,t);o=t,h=MI(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw rC(mC);if((a=p-h)<0)throw rC(mC)}else if((a=NI(n)*r)+h>p)throw rC(mC);s=a/r}else s=OI(t),o=new nC(a=s*r);for($I(e,{buffer:o,byteOffset:h,byteLength:a,length:s,view:new aC(o)});d<s;)u(e,d++)})),HI&&HI(c,lC),l=c.prototype=BI(dC)),l.constructor!==c&&PI(l,"constructor",c),ZI(l).TypedArrayConstructor=c,cC&&PI(l,cC,n);var h=c!=s;d[n]=c,yI({global:!0,constructor:!0,forced:h,sham:!sC},d),pC in c||PI(c,pC,r),pC in l||PI(l,pC,r),zI(n)}):cE.exports=function(){},sE("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var yC=dS,EC=lI,IC=Ma,CC=Ue,RC=t,AC=WE.aTypedArray,bC=WE.exportTypedArrayMethod,kC=s("".slice);bC("fill",(function(e){var t=arguments.length;AC(this);var i="Big"===kC(IC(this),0,3)?EC(e):+e;return CC(yC,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),RC((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var wC=R,PC=Ue,DC=WE,NC=Ht,OC=oI,MC=F,LC=t,xC=wC.RangeError,VC=wC.Int8Array,UC=VC&&VC.prototype,FC=UC&&UC.set,BC=DC.aTypedArray,jC=DC.exportTypedArrayMethod,HC=!LC((function(){var e=new Uint8ClampedArray(2);return PC(FC,e,{length:1,0:3},1),3!==e[1]})),GC=HC&&DC.NATIVE_ARRAY_BUFFER_VIEWS&&LC((function(){var e=new VC(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));jC("set",(function(e){BC(this);var t=OC(arguments.length>1?arguments[1]:void 0,1),i=MC(e);if(HC)return PC(FC,this,i,t);var r=this.length,n=NC(i),o=0;if(n+t>r)throw xC("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!HC||GC);var WC=_s,JC=t,zC=et,KC=q_,qC=Oy,QC=My,YC=te,XC=xy,$C=WE.aTypedArray,ZC=WE.exportTypedArrayMethod,eR=R.Uint16Array,tR=eR&&WC(eR.prototype.sort),iR=!(!tR||JC((function(){tR(new eR(2),null)}))&&JC((function(){tR(new eR(2),{})}))),rR=!!tR&&!JC((function(){if(YC)return YC<74;if(qC)return qC<67;if(QC)return!0;if(XC)return XC<602;var e,t,i=new eR(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(tR(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));ZC("sort",(function(e){return void 0!==e&&zC(e),rR?tR(this,e):KC($C(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))}),!rR||iR);var nR=Mn,oR=_h,aR=s([].reverse),sR=[1,2];nR({target:"Array",proto:!0,forced:String(sR)===String(sR.reverse())},{reverse:function(){return oR(this)&&(this.length=this.length),aR(this)}});var cR=Object.create,lR=Object.defineProperty,dR=Object.defineProperties,uR=Object.getOwnPropertyDescriptor,hR=Object.getOwnPropertyDescriptors,pR=Object.getOwnPropertyNames,mR=Object.getOwnPropertySymbols,_R=Object.getPrototypeOf,fR=Object.prototype.hasOwnProperty,gR=Object.prototype.propertyIsEnumerable,vR=Reflect.get,TR=Math.pow,SR=(e,t,i)=>t in e?lR(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,yR=(e,t)=>{for(var i in t||(t={}))fR.call(t,i)&&SR(e,i,t[i]);if(mR)for(var i of mR(t))gR.call(t,i)&&SR(e,i,t[i]);return e},ER=(e,t)=>dR(e,hR(t)),IR=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),CR=(e,t)=>{for(var i in t)lR(e,i,{get:t[i],enumerable:!0})},RR=(e,t,i)=>(i=null!=e?cR(_R(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of pR(t))!fR.call(e,n)&&n!==i&&lR(e,n,{get:()=>t[n],enumerable:!(r=uR(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:lR(i,"default",{value:e,enumerable:!0}),e)),AR=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?uR(t,i):t,a=e.length-1;a>=0;a--)(n=e[a])&&(o=(r?n(t,i,o):n(o))||o);return r&&o&&lR(t,i,o),o},bR=(e,t,i)=>(SR(e,"symbol"!=typeof t?t+"":t,i),i),kR=(e,t,i)=>vR(_R(e),i,t),wR=(e,t,i)=>new Promise(((r,n)=>{var o=e=>{try{s(i.next(e))}catch(t){n(t)}},a=e=>{try{s(i.throw(e))}catch(t){n(t)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,a);s((i=i.apply(e,t)).next())})),PR=IR((e=>{RR(zR()),Object.defineProperty(e,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};e.extractVersion=n,e.wrapPeerConnectionEvent=function(e,t,i){if(e.RTCPeerConnection){var r=e.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return n.apply(this,arguments);var o=function(e){var 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])};var 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);var 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:function(){return this["_on"+t]},set:function(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})}},e.disableLog=function(e){return"boolean"!=typeof e?new Error("Argument type: "+(void 0===e?"undefined":t(e))+". Please use a boolean."):(i=e,e?"adapter.js logging disabled":"adapter.js logging enabled")},e.disableWarnings=function(e){return"boolean"!=typeof e?new Error("Argument type: "+(void 0===e?"undefined":t(e))+". Please use a boolean."):(r=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))},e.log=function(){if("object"===("undefined"==typeof window?"undefined":t(window))){if(i)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}},e.deprecated=function(e,t){!r||console.warn(e+" is deprecated, please use "+t+" instead.")},e.detectBrowser=function(e){var t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;var i=e.navigator;if(i.mozGetUserMedia)t.browser="firefox",t.version=n(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=n(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(i.mediaDevices&&i.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=n(i.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=n(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t},e.compactObject=function e(t){return o(t)?Object.keys(t).reduce((function(i,r){var n=o(t[r]),a=n?e(t[r]):t[r],s=n&&!Object.keys(a).length;return void 0===a||s?i:Object.assign(i,function(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}({},r,a))}),{}):t},e.walkStats=a,e.filterStats=function(e,t,i){var r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;var o=[];return e.forEach((function(e){"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((function(t){e.forEach((function(i){i.type===r&&i.trackId===t.id&&a(e,i,n)}))})),n};var i=!0,r=!0;function n(e,t,i){var r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function o(e){return"[object Object]"===Object.prototype.toString.call(e)}function a(e,t,i){!t||i.has(t.id)||(i.set(t.id,t),Object.keys(t).forEach((function(r){r.endsWith("Id")?a(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((function(t){a(e,e.get(t),i)}))})))}})),DR=IR((e=>{RR(zR()),Object.defineProperty(e,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};e.shimGetUserMedia=function(e,r){var n=e&&e.navigator;if(n.mediaDevices){var o=function(e){if("object"!==(void 0===e?"undefined":t(e))||e.mandatory||e.optional)return e;var i={};return Object.keys(e).forEach((function(r){if("require"!==r&&"advanced"!==r&&"mediaSource"!==r){var n="object"===t(e[r])?e[r]:{ideal:e[r]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);var o=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){i.optional=i.optional||[];var a={};"number"==typeof n.ideal?(a[o("min",r)]=n.ideal,i.optional.push(a),(a={})[o("max",r)]=n.ideal,i.optional.push(a)):(a[o("",r)]=n.ideal,i.optional.push(a))}void 0!==n.exact&&"number"!=typeof n.exact?(i.mandatory=i.mandatory||{},i.mandatory[o("",r)]=n.exact):["min","max"].forEach((function(e){void 0!==n[e]&&(i.mandatory=i.mandatory||{},i.mandatory[o(e,r)]=n[e])}))}})),e.advanced&&(i.optional=(i.optional||[]).concat(e.advanced)),i},a=function(e,a){if(r.version>=61)return a(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"===t(e.audio)){var s=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};s((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),s(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=o(e.audio)}if(e&&"object"===t(e.video)){var c=e.video.facingMode;c=c&&("object"===(void 0===c?"undefined":t(c))?c:{ideal:c});var l=r.version<66;if(c&&("user"===c.exact||"environment"===c.exact||"user"===c.ideal||"environment"===c.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||l)){delete e.video.facingMode;var d=void 0;if("environment"===c.exact||"environment"===c.ideal?d=["back","rear"]:("user"===c.exact||"user"===c.ideal)&&(d=["front"]),d)return n.mediaDevices.enumerateDevices().then((function(t){var r=(t=t.filter((function(e){return"videoinput"===e.kind}))).find((function(e){return d.some((function(t){return e.label.toLowerCase().includes(t)}))}));return!r&&t.length&&d.includes("back")&&(r=t[t.length-1]),r&&(e.video.deviceId=c.exact?{exact:r.deviceId}:{ideal:r.deviceId}),e.video=o(e.video),i("chrome: "+JSON.stringify(e)),a(e)}))}e.video=o(e.video)}return i("chrome: "+JSON.stringify(e)),a(e)},s=function(e){return r.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:function(){return this.name+(this.message&&": ")+this.message}}};if(n.getUserMedia=function(e,t,i){a(e,(function(e){n.webkitGetUserMedia(e,t,(function(e){i&&i(s(e))}))}))}.bind(n),n.mediaDevices.getUserMedia){var c=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(e){return a(e,(function(e){return c(e).then((function(t){if(e.audio&&!t.getAudioTracks().length||e.video&&!t.getVideoTracks().length)throw t.getTracks().forEach((function(e){e.stop()})),new DOMException("","NotFoundError");return t}),(function(e){return Promise.reject(s(e))}))}))}}}};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(PR()).log})),NR=IR((e=>{RR(zR()),Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetDisplayMedia=function(e,t){if((!e.navigator.mediaDevices||!("getDisplayMedia"in e.navigator.mediaDevices))&&e.navigator.mediaDevices){if("function"!=typeof t)return void console.error("shimGetDisplayMedia: getSourceId argument is not a function");e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((function(t){var 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)}))}}}})),OR=IR((e=>{RR(zR()),Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetDisplayMedia=e.shimGetUserMedia=void 0;var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=DR();Object.defineProperty(e,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}});var r=NR();Object.defineProperty(e,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}}),e.shimMediaStream=function(e){e.MediaStream=e.MediaStream||e.webkitMediaStream},e.shimOnTrack=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});var i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var t=this;return this._ontrackpoly||(this._ontrackpoly=function(i){i.stream.addEventListener("addtrack",(function(r){var n=void 0;n=e.RTCPeerConnection.prototype.getReceivers?t.getReceivers().find((function(e){return e.track&&e.track.id===r.track.id})):{track:r.track};var o=new Event("track");o.track=r.track,o.receiver=n,o.transceiver={receiver:n},o.streams=[i.stream],t.dispatchEvent(o)})),i.stream.getTracks().forEach((function(r){var n=void 0;n=e.RTCPeerConnection.prototype.getReceivers?t.getReceivers().find((function(e){return e.track&&e.track.id===r.id})):{track:r};var o=new Event("track");o.track=r,o.receiver=n,o.transceiver={receiver:n},o.streams=[i.stream],t.dispatchEvent(o)}))},this.addEventListener("addstream",this._ontrackpoly)),i.apply(this,arguments)}}else n.wrapPeerConnectionEvent(e,"track",(function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e}))},e.shimGetSendersWithDtmf=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){var i=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()};var r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,t){var n=r.apply(this,arguments);return n||(n=i(this,e),this._senders.push(n)),n};var n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);var t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}var o=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var t=this;this._senders=this._senders||[],o.apply(this,[e]),e.getTracks().forEach((function(e){t._senders.push(i(t,e))}))};var a=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._senders=this._senders||[],a.apply(this,[e]),e.getTracks().forEach((function(e){var i=t._senders.find((function(t){return t.track===e}));i&&t._senders.splice(t._senders.indexOf(i),1)}))}}else if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){var s=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){var e=this,t=s.apply(this,[]);return t.forEach((function(t){return t._pc=e})),t},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}},e.shimGetStats=function(e){if(e.RTCPeerConnection){var t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){var e=this,i=Array.prototype.slice.call(arguments),r=i[0],n=i[1],o=i[2];if(arguments.length>0&&"function"==typeof r)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof r))return t.apply(this,[]);var a=function(e){var t={};return e.result().forEach((function(e){var i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((function(t){i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((function(t){return[t,e[t]]})))};if(arguments.length>=2){var c=function(e){n(s(a(e)))};return t.apply(this,[c,r])}return new Promise((function(i,r){t.apply(e,[function(e){i(s(a(e)))},r])})).then(n,o)}}},e.shimSenderReceiverGetStats=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver){if(!("getStats"in e.RTCRtpSender.prototype)){var i=e.RTCPeerConnection.prototype.getSenders;i&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,t=i.apply(this,[]);return t.forEach((function(t){return t._pc=e})),t});var r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){var e=this;return this._pc.getStats().then((function(t){return n.filterStats(t,e.track,!0)}))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){var o=e.RTCPeerConnection.prototype.getReceivers;o&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,t=o.apply(this,[]);return t.forEach((function(t){return t._pc=e})),t}),n.wrapPeerConnectionEvent(e,"track",(function(e){return e.receiver._pc=e.srcElement,e})),e.RTCRtpReceiver.prototype.getStats=function(){var e=this;return this._pc.getStats().then((function(t){return n.filterStats(t,e.track,!1)}))}}if("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype){var a=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){var t=arguments[0],i=void 0,r=void 0,n=void 0;return this.getSenders().forEach((function(e){e.track===t&&(i?n=!0:i=e)})),this.getReceivers().forEach((function(e){return e.track===t&&(r?n=!0:r=e),e.track===t})),n||i&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return a.apply(this,arguments)}}}},e.shimAddTrackRemoveTrackWithNative=a,e.shimAddTrackRemoveTrack=function(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return a(e);var i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this,t=i.apply(this);return this._reverseStreams=this._reverseStreams||{},t.map((function(t){return e._reverseStreams[t.id]}))};var r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){var i=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((function(e){if(i.getSenders().find((function(t){return t.track===e})))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){var n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}r.apply(this,[t])};var n=e.RTCPeerConnection.prototype.removeStream;function s(e,t){var i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((function(t){var 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})}function c(e,t){var i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((function(t){var 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})}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){var r=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((function(e){return e===t})))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");var o=this.getSenders().find((function(e){return e.track===t}));if(o)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var a=this._streams[i.id];if(a)a.addTrack(t),Promise.resolve().then((function(){r.dispatchEvent(new Event("negotiationneeded"))}));else{var s=new e.MediaStream([t]);this._streams[i.id]=s,this._reverseStreams[s.id]=i,this.addStream(s)}return this.getSenders().find((function(e){return e.track===t}))},["createOffer","createAnswer"].forEach((function(t){var i=e.RTCPeerConnection.prototype[t],r=o({},t,(function(){var e=this,t=arguments,r=arguments.length&&"function"==typeof arguments[0];return r?i.apply(this,[function(i){var r=s(e,i);t[0].apply(null,[r])},function(e){t[1]&&t[1].apply(null,e)},arguments[2]]):i.apply(this,arguments).then((function(t){return s(e,t)}))}));e.RTCPeerConnection.prototype[t]=r[t]}));var l=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=c(this,arguments[0]),l.apply(this,arguments)):l.apply(this,arguments)};var d=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get:function(){var e=d.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){var t=this;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");this._streams=this._streams||{};var i=void 0;Object.keys(this._streams).forEach((function(r){t._streams[r].getTracks().find((function(t){return e.track===t}))&&(i=t._streams[r])})),i&&(1===i.getTracks().length?this.removeStream(this._reverseStreams[i.id]):i.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}},e.shimPeerConnection=function(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){var i=e.RTCPeerConnection.prototype[t],r=o({},t,(function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}));e.RTCPeerConnection.prototype[t]=r[t]}))},e.fixNegotiationNeeded=function(e,t){n.wrapPeerConnectionEvent(e,"negotiationneeded",(function(e){var i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))};var n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(PR());function o(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function a(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((function(t){return e._shimmedLocalStreams[t][0]}))};var t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var 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};var i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var t=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((function(e){if(t.getSenders().find((function(t){return t.track===e})))throw new DOMException("Track already exists.","InvalidAccessError")}));var r=this.getSenders();i.apply(this,arguments);var n=this.getSenders().filter((function(e){return-1===r.indexOf(e)}));this._shimmedLocalStreams[e.id]=[e].concat(n)};var 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)};var n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){var t=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((function(i){var r=t._shimmedLocalStreams[i].indexOf(e);-1!==r&&t._shimmedLocalStreams[i].splice(r,1),1===t._shimmedLocalStreams[i].length&&delete t._shimmedLocalStreams[i]})),n.apply(this,arguments)}}})),MR=IR((e=>{RR(zR()),Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetUserMedia=function(e){var t=e&&e.navigator,i=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(e){return i(e).catch((function(e){return Promise.reject(function(e){return{name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString:function(){return this.name}}}(e))}))}}})),LR=IR((e=>{RR(zR()),Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetDisplayMedia=function(e){"getDisplayMedia"in e.navigator&&(!e.navigator.mediaDevices||e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=e.navigator.getDisplayMedia.bind(e.navigator)))}})),xR=IR((e=>{RR(zR()),Object.defineProperty(e,"__esModule",{value:!0}),e.filterIceServers=function(e,i){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var i=e.urls||e.url;e.url&&!e.urls&&t.deprecated("RTCIceServer.url","RTCIceServer.urls");var n="string"==typeof i;return n&&(i=[i]),i=i.filter((function(e){if(0===e.indexOf("stun:"))return!1;var t=e.startsWith("turn")&&!e.startsWith("turn:[")&&e.includes("transport=udp");return t&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=n?i[0]:i,!!i.length}}))};var t=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(PR())})),VR=IR(((e,t)=>{RR(zR());var i={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};i.localCName=i.generateIdentifier(),i.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},i.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},i.getDescription=function(e){var t=i.splitSections(e);return t&&t[0]},i.getMediaSections=function(e){var t=i.splitSections(e);return t.shift(),t},i.matchPrefix=function(e,t){return i.splitLines(e).filter((function(e){return 0===e.indexOf(t)}))},i.parseCandidate=function(e){for(var t,i={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},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:i[t[r]]=t[r+1]}return i},i.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var i=e.type;return t.push("typ"),t.push(i),"host"!==i&&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(" ")},i.parseIceOptions=function(e){return e.substr(14).split(" ")},i.parseRtpMap=function(e){var t=e.substr(9).split(" "),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},i.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},i.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},i.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},i.parseFmtp=function(e){for(var t,i={},r=e.substr(e.indexOf(" ")+1).split(";"),n=0;n<r.length;n++)i[(t=r[n].trim().split("="))[0].trim()]=t[1];return i},i.writeFmtp=function(e){var t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var r=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+i+" "+r.join(";")+"\r\n"}return t},i.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},i.writeRtcpFb=function(e){var t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},i.parseSsrcMedia=function(e){var t=e.indexOf(" "),i={ssrc:parseInt(e.substr(7,t-7),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substr(t+1,r-t-1),i.value=e.substr(r+1)):i.attribute=e.substr(t+1),i},i.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},i.getMid=function(e){var t=i.matchPrefix(e,"a=mid:")[0];if(t)return t.substr(6)},i.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},i.getDtlsParameters=function(e,t){return{role:"auto",fingerprints:i.matchPrefix(e+t,"a=fingerprint:").map(i.parseFingerprint)}},i.writeDtlsParameters=function(e,t){var i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},i.parseCryptoLine=function(e){var t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},i.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?i.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},i.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;var t=e.substr(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}},i.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},i.getCryptoParameters=function(e,t){return i.matchPrefix(e+t,"a=crypto:").map(i.parseCryptoLine)},i.getIceParameters=function(e,t){var r=i.matchPrefix(e+t,"a=ice-ufrag:")[0],n=i.matchPrefix(e+t,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substr(12),password:n.substr(10)}:null},i.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},i.parseRtpParameters=function(e){for(var t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=i.splitLines(e)[0].split(" "),n=3;n<r.length;n++){var o=r[n],a=i.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(a){var s=i.parseRtpMap(a),c=i.matchPrefix(e,"a=fmtp:"+o+" ");switch(s.parameters=c.length?i.parseFmtp(c[0]):{},s.rtcpFeedback=i.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(i.parseRtcpFb),t.codecs.push(s),s.name.toUpperCase()){case"RED":case"ULPFEC":t.fecMechanisms.push(s.name.toUpperCase())}}}return i.matchPrefix(e,"a=extmap:").forEach((function(e){t.headerExtensions.push(i.parseExtmap(e))})),t},i.writeRtpDescription=function(e,t){var r="";r+="m="+e+" ",r+=t.codecs.length>0?"9":"0",r+=" UDP/TLS/RTP/SAVPF ",r+=t.codecs.map((function(e){return 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",t.codecs.forEach((function(e){r+=i.writeRtpMap(e),r+=i.writeFmtp(e),r+=i.writeRtcpFb(e)}));var n=0;return t.codecs.forEach((function(e){e.maxptime>n&&(n=e.maxptime)})),n>0&&(r+="a=maxptime:"+n+"\r\n"),r+="a=rtcp-mux\r\n",t.headerExtensions&&t.headerExtensions.forEach((function(e){r+=i.writeExtmap(e)})),r},i.parseRtpEncodingParameters=function(e){var t,r=[],n=i.parseRtpParameters(e),o=-1!==n.fecMechanisms.indexOf("RED"),a=-1!==n.fecMechanisms.indexOf("ULPFEC"),s=i.matchPrefix(e,"a=ssrc:").map((function(e){return i.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute})),c=s.length>0&&s[0].ssrc,l=i.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));l.length>0&&l[0].length>1&&l[0][0]===c&&(t=l[0][1]),n.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var i={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&t&&(i.rtx={ssrc:t}),r.push(i),o&&((i=JSON.parse(JSON.stringify(i))).fec={ssrc:c,mechanism:a?"red+ulpfec":"red"},r.push(i))}})),0===r.length&&c&&r.push({ssrc:c});var d=i.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substr(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substr(5),10)*.95-16e3:void 0,r.forEach((function(e){e.maxBitrate=d}))),r},i.parseRtcpParameters=function(e){var t={},r=i.matchPrefix(e,"a=ssrc:").map((function(e){return i.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];r&&(t.cname=r.value,t.ssrc=r.ssrc);var n=i.matchPrefix(e,"a=rtcp-rsize");t.reducedSize=n.length>0,t.compound=0===n.length;var o=i.matchPrefix(e,"a=rtcp-mux");return t.mux=o.length>0,t},i.parseMsid=function(e){var t,r=i.matchPrefix(e,"a=msid:");if(1===r.length)return{stream:(t=r[0].substr(7).split(" "))[0],track:t[1]};var n=i.matchPrefix(e,"a=ssrc:").map((function(e){return i.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return n.length>0?{stream:(t=n[0].value.split(" "))[0],track:t[1]}:void 0},i.parseSctpDescription=function(e){var t,r=i.parseMLine(e),n=i.matchPrefix(e,"a=max-message-size:");n.length>0&&(t=parseInt(n[0].substr(19),10)),isNaN(t)&&(t=65536);var o=i.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substr(12),10),protocol:r.fmt,maxMessageSize:t};if(i.matchPrefix(e,"a=sctpmap:").length>0){var a=i.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(a[0],10),protocol:a[1],maxMessageSize:t}}},i.writeSctpDescription=function(e,t){var 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("")},i.generateSessionId=function(){return Math.random().toString().substr(2,21)},i.writeSessionBoilerplate=function(e,t,r){var n=void 0!==t?t:2;return"v=0\r\no="+(r||"thisisadapterortc")+" "+(e||i.generateSessionId())+" "+n+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},i.writeMediaSection=function(e,t,r,n){var o=i.writeRtpDescription(e.kind,t);if(o+=i.writeIceParameters(e.iceGatherer.getLocalParameters()),o+=i.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":"active"),o+="a=mid:"+e.mid+"\r\n",e.direction?o+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?o+="a=sendrecv\r\n":e.rtpSender?o+="a=sendonly\r\n":e.rtpReceiver?o+="a=recvonly\r\n":o+="a=inactive\r\n",e.rtpSender){var a="msid:"+n.id+" "+e.rtpSender.track.id+"\r\n";o+="a="+a,o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,o+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+"\r\n"),o},i.getDirection=function(e,t){for(var r=i.splitLines(e),n=0;n<r.length;n++)switch(r[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[n].substr(2)}return t?i.getDirection(t):"sendrecv"},i.getKind=function(e){return i.splitLines(e)[0].split(" ")[0].substr(2)},i.isRejected=function(e){return"0"===e.split(" ",2)[1]},i.parseMLine=function(e){var t=i.splitLines(e)[0].substr(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}},i.parseOLine=function(e){var t=i.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:t[0],sessionId:t[1],sessionVersion:parseInt(t[2],10),netType:t[3],addressType:t[4],address:t[5]}},i.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var t=i.splitLines(e),r=0;r<t.length;r++)if(t[r].length<2||"="!==t[r].charAt(1))return!1;return!0},"object"==typeof t&&(t.exports=i)})),UR=IR(((e,t)=>{RR(zR());var i=VR();function r(e,t,r,n,o){var a=i.writeRtpDescription(e.kind,t);if(a+=i.writeIceParameters(e.iceGatherer.getLocalParameters()),a+=i.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":o||"active"),a+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?a+="a=sendrecv\r\n":e.rtpSender?a+="a=sendonly\r\n":e.rtpReceiver?a+="a=recvonly\r\n":a+="a=inactive\r\n",e.rtpSender){var s=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=s;var c="msid:"+(n?n.id:"-")+" "+s+"\r\n";a+="a="+c,a+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+c,e.sendEncodingParameters[0].rtx&&(a+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+c,a+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return a+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(a+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+"\r\n"),a}function n(e,t){var i={codecs:[],headerExtensions:[],fecMechanisms:[]},r=function(e,t){e=parseInt(e,10);for(var i=0;i<t.length;i++)if(t[i].payloadType===e||t[i].preferredPayloadType===e)return t[i]},n=function(e,t,i,n){var o=r(e.parameters.apt,i),a=r(t.parameters.apt,n);return o&&a&&o.name.toLowerCase()===a.name.toLowerCase()};return e.codecs.forEach((function(r){for(var o=0;o<t.codecs.length;o++){var a=t.codecs[o];if(r.name.toLowerCase()===a.name.toLowerCase()&&r.clockRate===a.clockRate){if("rtx"===r.name.toLowerCase()&&r.parameters&&a.parameters.apt&&!n(r,a,e.codecs,t.codecs))continue;(a=JSON.parse(JSON.stringify(a))).numChannels=Math.min(r.numChannels,a.numChannels),i.codecs.push(a),a.rtcpFeedback=a.rtcpFeedback.filter((function(e){for(var t=0;t<r.rtcpFeedback.length;t++)if(r.rtcpFeedback[t].type===e.type&&r.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var r=0;r<t.headerExtensions.length;r++){var n=t.headerExtensions[r];if(e.uri===n.uri){i.headerExtensions.push(n);break}}})),i}function o(e,t,i){return-1!=={offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[t][e].indexOf(i)}function a(e,t){var i=e.getRemoteCandidates().find((function(e){return t.foundation===e.foundation&&t.ip===e.ip&&t.port===e.port&&t.priority===e.priority&&t.protocol===e.protocol&&t.type===e.type}));return i||e.addRemoteCandidate(t),!i}function s(e,t){var i=new Error(t);return i.name=e,i.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[e],i}t.exports=function(e,t){function c(t,i){i.addTrack(t),i.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function l(t,i,r,n){var o=new Event("track");o.track=i,o.receiver=r,o.transceiver={receiver:r},o.streams=n,e.setTimeout((function(){t._dispatchEvent("track",o)}))}var d=function(r){var n=this,o=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){n[e]=o[e].bind(o)})),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",r=JSON.parse(JSON.stringify(r||{})),this.usingBundle="max-bundle"===r.bundlePolicy,"negotiate"===r.rtcpMuxPolicy)throw s("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var i=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var r=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var n="string"==typeof r;return n&&(r=[r]),r=r.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||i?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(i=!0,!0)})),delete e.url,e.urls=n?r[0]:r,!!r.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var a=r.iceCandidatePoolSize;a>0;a--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=i.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(d.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(d.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),d.prototype.onicecandidate=null,d.prototype.onaddstream=null,d.prototype.ontrack=null,d.prototype.onremovestream=null,d.prototype.onsignalingstatechange=null,d.prototype.oniceconnectionstatechange=null,d.prototype.onconnectionstatechange=null,d.prototype.onicegatheringstatechange=null,d.prototype.onnegotiationneeded=null,d.prototype.ondatachannel=null,d.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},d.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},d.prototype.getConfiguration=function(){return this._config},d.prototype.getLocalStreams=function(){return this.localStreams},d.prototype.getRemoteStreams=function(){return this.remoteStreams},d.prototype._createTransceiver=function(e,t){var i=this.transceivers.length>0,r={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&i)r.iceTransport=this.transceivers[0].iceTransport,r.dtlsTransport=this.transceivers[0].dtlsTransport;else{var n=this._createIceAndDtlsTransports();r.iceTransport=n.iceTransport,r.dtlsTransport=n.dtlsTransport}return t||this.transceivers.push(r),r},d.prototype.addTrack=function(t,i){if(this._isClosed)throw s("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");if(this.transceivers.find((function(e){return e.track===t})))throw s("InvalidAccessError","Track already exists.");for(var r,n=0;n<this.transceivers.length;n++)!this.transceivers[n].track&&this.transceivers[n].kind===t.kind&&(r=this.transceivers[n]);return r||(r=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(i)&&this.localStreams.push(i),r.track=t,r.stream=i,r.rtpSender=new e.RTCRtpSender(t,r.dtlsTransport),r.rtpSender},d.prototype.addStream=function(e){var i=this;if(t>=15025)e.getTracks().forEach((function(t){i.addTrack(t,e)}));else{var r=e.clone();e.getTracks().forEach((function(e,t){var i=r.getTracks()[t];e.addEventListener("enabled",(function(e){i.enabled=e.enabled}))})),r.getTracks().forEach((function(e){i.addTrack(e,r)}))}},d.prototype.removeTrack=function(t){if(this._isClosed)throw s("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(t instanceof e.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var i=this.transceivers.find((function(e){return e.rtpSender===t}));if(!i)throw s("InvalidAccessError","Sender was not created by this connection.");var r=i.stream;i.rtpSender.stop(),i.rtpSender=null,i.track=null,i.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(r)&&this.localStreams.indexOf(r)>-1&&this.localStreams.splice(this.localStreams.indexOf(r),1),this._maybeFireNegotiationNeeded()},d.prototype.removeStream=function(e){var t=this;e.getTracks().forEach((function(e){var i=t.getSenders().find((function(t){return t.track===e}));i&&t.removeTrack(i)}))},d.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},d.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},d.prototype._createIceGatherer=function(t,i){var r=this;if(i&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var n=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(n,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(e){var i=!e.candidate||0===Object.keys(e.candidate).length;n.state=i?"completed":"gathering",null!==r.transceivers[t].bufferedCandidateEvents&&r.transceivers[t].bufferedCandidateEvents.push(e)},n.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),n},d.prototype._gather=function(t,r){var n=this,o=this.transceivers[r].iceGatherer;if(!o.onlocalcandidate){var a=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,o.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),o.onlocalcandidate=function(e){if(!(n.usingBundle&&r>0)){var a=new Event("icecandidate");a.candidate={sdpMid:t,sdpMLineIndex:r};var s=e.candidate,c=!s||0===Object.keys(s).length;if(c)("new"===o.state||"gathering"===o.state)&&(o.state="completed");else{"new"===o.state&&(o.state="gathering"),s.component=1,s.ufrag=o.getLocalParameters().usernameFragment;var l=i.writeCandidate(s);a.candidate=Object.assign(a.candidate,i.parseCandidate(l)),a.candidate.candidate=l,a.candidate.toJSON=function(){return{candidate:a.candidate.candidate,sdpMid:a.candidate.sdpMid,sdpMLineIndex:a.candidate.sdpMLineIndex,usernameFragment:a.candidate.usernameFragment}}}var d=i.getMediaSections(n._localDescription.sdp);d[a.candidate.sdpMLineIndex]+=c?"a=end-of-candidates\r\n":"a="+a.candidate.candidate+"\r\n",n._localDescription.sdp=i.getDescription(n._localDescription.sdp)+d.join("");var u=n.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==n.iceGatheringState&&(n.iceGatheringState="gathering",n._emitGatheringStateChange()),c||n._dispatchEvent("icecandidate",a),u&&(n._dispatchEvent("icecandidate",new Event("icecandidate")),n.iceGatheringState="complete",n._emitGatheringStateChange())}},e.setTimeout((function(){a.forEach((function(e){o.onlocalcandidate(e)}))}),0)}},d.prototype._createIceAndDtlsTransports=function(){var t=this,i=new e.RTCIceTransport(null);i.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var r=new e.RTCDtlsTransport(i);return r.ondtlsstatechange=function(){t._updateConnectionState()},r.onerror=function(){Object.defineProperty(r,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:i,dtlsTransport:r}},d.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var i=this.transceivers[e].iceTransport;i&&(delete i.onicestatechange,delete this.transceivers[e].iceTransport);var r=this.transceivers[e].dtlsTransport;r&&(delete r.ondtlsstatechange,delete r.onerror,delete this.transceivers[e].dtlsTransport)},d.prototype._transceive=function(e,r,o){var a=n(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(a.encodings=e.sendEncodingParameters,a.rtcp={cname:i.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(a.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(a)),o&&e.rtpReceiver&&a.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?a.encodings=e.recvEncodingParameters:a.encodings=[{}],a.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(a.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(a.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(a))},d.prototype.setLocalDescription=function(e){var t,r,a=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(s("TypeError",'Unsupported type "'+e.type+'"'));if(!o("setLocalDescription",e.type,a.signalingState)||a._isClosed)return Promise.reject(s("InvalidStateError","Can not set local "+e.type+" in state "+a.signalingState));if("offer"===e.type)t=i.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=i.parseRtpParameters(e);a.transceivers[t].localCapabilities=r})),a.transceivers.forEach((function(e,t){a._gather(e.mid,t)}));else if("answer"===e.type){t=i.splitSections(a._remoteDescription.sdp),r=t.shift();var c=i.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var o=a.transceivers[t],s=o.iceGatherer,l=o.iceTransport,d=o.dtlsTransport,u=o.localCapabilities,h=o.remoteCapabilities;if(!(i.isRejected(e)&&0===i.matchPrefix(e,"a=bundle-only").length)&&!o.rejected){var p=i.getIceParameters(e,r),m=i.getDtlsParameters(e,r);c&&(m.role="server"),(!a.usingBundle||0===t)&&(a._gather(o.mid,t),"new"===l.state&&l.start(s,p,c?"controlling":"controlled"),"new"===d.state&&d.start(m));var _=n(u,h);a._transceive(o,_.codecs.length>0,!1)}}))}return a._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?a._updateSignalingState("have-local-offer"):a._updateSignalingState("stable"),Promise.resolve()},d.prototype.setRemoteDescription=function(r){var d=this;if(-1===["offer","answer"].indexOf(r.type))return Promise.reject(s("TypeError",'Unsupported type "'+r.type+'"'));if(!o("setRemoteDescription",r.type,d.signalingState)||d._isClosed)return Promise.reject(s("InvalidStateError","Can not set remote "+r.type+" in state "+d.signalingState));var u={};d.remoteStreams.forEach((function(e){u[e.id]=e}));var h=[],p=i.splitSections(r.sdp),m=p.shift(),_=i.matchPrefix(m,"a=ice-lite").length>0,f=i.matchPrefix(m,"a=group:BUNDLE ").length>0;d.usingBundle=f;var g=i.matchPrefix(m,"a=ice-options:")[0];return d.canTrickleIceCandidates=!!g&&g.substr(14).split(" ").indexOf("trickle")>=0,p.forEach((function(o,s){var l=i.splitLines(o),p=i.getKind(o),g=i.isRejected(o)&&0===i.matchPrefix(o,"a=bundle-only").length,v=l[0].substr(2).split(" ")[2],T=i.getDirection(o,m),S=i.parseMsid(o),y=i.getMid(o)||i.generateIdentifier();if(g||"application"===p&&("DTLS/SCTP"===v||"UDP/DTLS/SCTP"===v))d.transceivers[s]={mid:y,kind:p,protocol:v,rejected:!0};else{!g&&d.transceivers[s]&&d.transceivers[s].rejected&&(d.transceivers[s]=d._createTransceiver(p,!0));var E,I,C,R,A,b,k,w,P,D,N,O=i.parseRtpParameters(o);g||(D=i.getIceParameters(o,m),(N=i.getDtlsParameters(o,m)).role="client"),k=i.parseRtpEncodingParameters(o);var M=i.parseRtcpParameters(o),L=i.matchPrefix(o,"a=end-of-candidates",m).length>0,x=i.matchPrefix(o,"a=candidate:").map((function(e){return i.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===r.type||"answer"===r.type)&&!g&&f&&s>0&&d.transceivers[s]&&(d._disposeIceAndDtlsTransports(s),d.transceivers[s].iceGatherer=d.transceivers[0].iceGatherer,d.transceivers[s].iceTransport=d.transceivers[0].iceTransport,d.transceivers[s].dtlsTransport=d.transceivers[0].dtlsTransport,d.transceivers[s].rtpSender&&d.transceivers[s].rtpSender.setTransport(d.transceivers[0].dtlsTransport),d.transceivers[s].rtpReceiver&&d.transceivers[s].rtpReceiver.setTransport(d.transceivers[0].dtlsTransport)),"offer"!==r.type||g){if("answer"===r.type&&!g){I=(E=d.transceivers[s]).iceGatherer,C=E.iceTransport,R=E.dtlsTransport,A=E.rtpReceiver,b=E.sendEncodingParameters,w=E.localCapabilities,d.transceivers[s].recvEncodingParameters=k,d.transceivers[s].remoteCapabilities=O,d.transceivers[s].rtcpParameters=M,x.length&&"new"===C.state&&(!_&&!L||f&&0!==s?x.forEach((function(e){a(E.iceTransport,e)})):C.setRemoteCandidates(x)),(!f||0===s)&&("new"===C.state&&C.start(I,D,"controlling"),"new"===R.state&&R.start(N)),!n(E.localCapabilities,E.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&E.sendEncodingParameters[0].rtx&&delete E.sendEncodingParameters[0].rtx,d._transceive(E,"sendrecv"===T||"recvonly"===T,"sendrecv"===T||"sendonly"===T),!A||"sendrecv"!==T&&"sendonly"!==T?delete E.rtpReceiver:(P=A.track,S?(u[S.stream]||(u[S.stream]=new e.MediaStream),c(P,u[S.stream]),h.push([P,A,u[S.stream]])):(u.default||(u.default=new e.MediaStream),c(P,u.default),h.push([P,A,u.default])))}}else{(E=d.transceivers[s]||d._createTransceiver(p)).mid=y,E.iceGatherer||(E.iceGatherer=d._createIceGatherer(s,f)),x.length&&"new"===E.iceTransport.state&&(!L||f&&0!==s?x.forEach((function(e){a(E.iceTransport,e)})):E.iceTransport.setRemoteCandidates(x)),w=e.RTCRtpReceiver.getCapabilities(p),t<15019&&(w.codecs=w.codecs.filter((function(e){return"rtx"!==e.name}))),b=E.sendEncodingParameters||[{ssrc:1001*(2*s+2)}];var V,U=!1;if("sendrecv"===T||"sendonly"===T){if(U=!E.rtpReceiver,A=E.rtpReceiver||new e.RTCRtpReceiver(E.dtlsTransport,p),U)P=A.track,S&&"-"===S.stream||(S?(u[S.stream]||(u[S.stream]=new e.MediaStream,Object.defineProperty(u[S.stream],"id",{get:function(){return S.stream}})),Object.defineProperty(P,"id",{get:function(){return S.track}}),V=u[S.stream]):(u.default||(u.default=new e.MediaStream),V=u.default)),V&&(c(P,V),E.associatedRemoteMediaStreams.push(V)),h.push([P,A,V])}else E.rtpReceiver&&E.rtpReceiver.track&&(E.associatedRemoteMediaStreams.forEach((function(t){var i=t.getTracks().find((function(e){return e.id===E.rtpReceiver.track.id}));i&&function(t,i){i.removeTrack(t),i.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(i,t)})),E.associatedRemoteMediaStreams=[]);E.localCapabilities=w,E.remoteCapabilities=O,E.rtpReceiver=A,E.rtcpParameters=M,E.sendEncodingParameters=b,E.recvEncodingParameters=k,d._transceive(d.transceivers[s],!1,U)}}})),void 0===d._dtlsRole&&(d._dtlsRole="offer"===r.type?"active":"passive"),d._remoteDescription={type:r.type,sdp:r.sdp},"offer"===r.type?d._updateSignalingState("have-remote-offer"):d._updateSignalingState("stable"),Object.keys(u).forEach((function(t){var i=u[t];if(i.getTracks().length){if(-1===d.remoteStreams.indexOf(i)){d.remoteStreams.push(i);var r=new Event("addstream");r.stream=i,e.setTimeout((function(){d._dispatchEvent("addstream",r)}))}h.forEach((function(e){var t=e[0],r=e[1];i.id===e[2].id&&l(d,t,r,[i])}))}})),h.forEach((function(e){e[2]||l(d,e[0],e[1],[])})),e.setTimeout((function(){!d||!d.transceivers||d.transceivers.forEach((function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},d.prototype.close=function(){this.transceivers.forEach((function(e){e.iceTransport&&e.iceTransport.stop(),e.dtlsTransport&&e.dtlsTransport.stop(),e.rtpSender&&e.rtpSender.stop(),e.rtpReceiver&&e.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},d.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},d.prototype._maybeFireNegotiationNeeded=function(){var t=this;"stable"!==this.signalingState||!0===this.needNegotiation||(this.needNegotiation=!0,e.setTimeout((function(){if(t.needNegotiation){t.needNegotiation=!1;var e=new Event("negotiationneeded");t._dispatchEvent("negotiationneeded",e)}}),0))},d.prototype._updateIceConnectionState=function(){var e,t={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&!e.rejected&&t[e.iceTransport.state]++})),e="new",t.failed>0?e="failed":t.checking>0?e="checking":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0?e="connected":t.completed>0&&(e="completed"),e!==this.iceConnectionState){this.iceConnectionState=e;var i=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",i)}},d.prototype._updateConnectionState=function(){var e,t={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&e.dtlsTransport&&!e.rejected&&(t[e.iceTransport.state]++,t[e.dtlsTransport.state]++)})),t.connected+=t.completed,e="new",t.failed>0?e="failed":t.connecting>0?e="connecting":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0&&(e="connected"),e!==this.connectionState){this.connectionState=e;var i=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",i)}},d.prototype.createOffer=function(){var n=this;if(n._isClosed)return Promise.reject(s("InvalidStateError","Can not call createOffer after close"));var o=n.transceivers.filter((function(e){return"audio"===e.kind})).length,a=n.transceivers.filter((function(e){return"video"===e.kind})).length,c=arguments[0];if(c){if(c.mandatory||c.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==c.offerToReceiveAudio&&(o=!0===c.offerToReceiveAudio?1:!1===c.offerToReceiveAudio?0:c.offerToReceiveAudio),void 0!==c.offerToReceiveVideo&&(a=!0===c.offerToReceiveVideo?1:!1===c.offerToReceiveVideo?0:c.offerToReceiveVideo)}for(n.transceivers.forEach((function(e){"audio"===e.kind?--o<0&&(e.wantReceive=!1):"video"===e.kind&&(--a<0&&(e.wantReceive=!1))}));o>0||a>0;)o>0&&(n._createTransceiver("audio"),o--),a>0&&(n._createTransceiver("video"),a--);var l=i.writeSessionBoilerplate(n._sdpSessionId,n._sdpSessionVersion++);n.transceivers.forEach((function(r,o){var a=r.track,s=r.kind,c=r.mid||i.generateIdentifier();r.mid=c,r.iceGatherer||(r.iceGatherer=n._createIceGatherer(o,n.usingBundle));var l=e.RTCRtpSender.getCapabilities(s);t<15019&&(l.codecs=l.codecs.filter((function(e){return"rtx"!==e.name}))),l.codecs.forEach((function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1"),r.remoteCapabilities&&r.remoteCapabilities.codecs&&r.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),l.headerExtensions.forEach((function(e){(r.remoteCapabilities&&r.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=r.sendEncodingParameters||[{ssrc:1001*(2*o+1)}];a&&t>=15019&&"video"===s&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),r.wantReceive&&(r.rtpReceiver=new e.RTCRtpReceiver(r.dtlsTransport,s)),r.localCapabilities=l,r.sendEncodingParameters=d})),"max-compat"!==n._config.bundlePolicy&&(l+="a=group:BUNDLE "+n.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),l+="a=ice-options:trickle\r\n",n.transceivers.forEach((function(e,t){l+=r(e,e.localCapabilities,"offer",e.stream,n._dtlsRole),l+="a=rtcp-rsize\r\n",e.iceGatherer&&"new"!==n.iceGatheringState&&(0===t||!n.usingBundle)&&(e.iceGatherer.getLocalCandidates().forEach((function(e){e.component=1,l+="a="+i.writeCandidate(e)+"\r\n"})),"completed"===e.iceGatherer.state&&(l+="a=end-of-candidates\r\n"))}));var d=new e.RTCSessionDescription({type:"offer",sdp:l});return Promise.resolve(d)},d.prototype.createAnswer=function(){var o=this;if(o._isClosed)return Promise.reject(s("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==o.signalingState&&"have-local-pranswer"!==o.signalingState)return Promise.reject(s("InvalidStateError","Can not call createAnswer in signalingState "+o.signalingState));var a=i.writeSessionBoilerplate(o._sdpSessionId,o._sdpSessionVersion++);o.usingBundle&&(a+="a=group:BUNDLE "+o.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),a+="a=ice-options:trickle\r\n";var c=i.getMediaSections(o._remoteDescription.sdp).length;o.transceivers.forEach((function(e,i){if(!(i+1>c)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?a+="m=application 0 DTLS/SCTP 5000\r\n":a+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?a+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(a+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(a+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var s;if(e.stream)"audio"===e.kind?s=e.stream.getAudioTracks()[0]:"video"===e.kind&&(s=e.stream.getVideoTracks()[0]),s&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1});var l=n(e.localCapabilities,e.remoteCapabilities);!l.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,a+=r(e,l,"answer",e.stream,o._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(a+="a=rtcp-rsize\r\n")}}));var l=new e.RTCSessionDescription({type:"answer",sdp:a});return Promise.resolve(l)},d.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(n,o){if(!r._remoteDescription)return o(s("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var c=e.sdpMLineIndex;if(e.sdpMid)for(var l=0;l<r.transceivers.length;l++)if(r.transceivers[l].mid===e.sdpMid){c=l;break}var d=r.transceivers[c];if(!d)return o(s("OperationError","Can not add ICE candidate"));if(d.rejected)return n();var u=Object.keys(e.candidate).length>0?i.parseCandidate(e.candidate):{};if("tcp"===u.protocol&&(0===u.port||9===u.port)||u.component&&1!==u.component)return n();if((0===c||c>0&&d.iceTransport!==r.transceivers[0].iceTransport)&&!a(d.iceTransport,u))return o(s("OperationError","Can not add ICE candidate"));var h=e.candidate.trim();0===h.indexOf("a=")&&(h=h.substr(2)),(t=i.getMediaSections(r._remoteDescription.sdp))[c]+="a="+(u.type?h:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=i.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var p=0;p<r.transceivers.length&&(r.transceivers[p].rejected||(r.transceivers[p].iceTransport.addRemoteCandidate({}),(t=i.getMediaSections(r._remoteDescription.sdp))[p]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=i.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));p++);n()}))},d.prototype.getStats=function(t){if(t&&t instanceof e.MediaStreamTrack){var i=null;if(this.transceivers.forEach((function(e){e.rtpSender&&e.rtpSender.track===t?i=e.rtpSender:e.rtpReceiver&&e.rtpReceiver.track===t&&(i=e.rtpReceiver)})),!i)throw s("InvalidAccessError","Invalid selector.");return i.getStats()}var r=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&r.push(e[t].getStats())}))})),Promise.all(r).then((function(e){var t=new Map;return e.forEach((function(e){e.forEach((function(e){t.set(e.id,e)}))})),t}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(t){var i=e[t];if(i&&i.prototype&&i.prototype.getStats){var r=i.prototype.getStats;i.prototype.getStats=function(){return r.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(i){e[i].type=function(e){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type}(e[i]),t.set(i,e[i])})),t}))}}}));var u=["createOffer","createAnswer"];return u.forEach((function(e){var t=d.prototype[e];d.prototype[e]=function(){var e=arguments;return"function"==typeof e[0]||"function"==typeof e[1]?t.apply(this,[arguments[2]]).then((function(t){"function"==typeof e[0]&&e[0].apply(null,[t])}),(function(t){"function"==typeof e[1]&&e[1].apply(null,[t])})):t.apply(this,arguments)}})),(u=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=d.prototype[e];d.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]||"function"==typeof e[2]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)}),(function(t){"function"==typeof e[2]&&e[2].apply(null,[t])})):t.apply(this,arguments)}})),["getStats"].forEach((function(e){var t=d.prototype[e];d.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)})):t.apply(this,arguments)}})),d}})),FR=IR((e=>{RR(zR()),Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetDisplayMedia=e.shimGetUserMedia=void 0;var t=MR();Object.defineProperty(e,"shimGetUserMedia",{enumerable:!0,get:function(){return t.shimGetUserMedia}});var i=LR();Object.defineProperty(e,"shimGetDisplayMedia",{enumerable:!0,get:function(){return i.shimGetDisplayMedia}}),e.shimPeerConnection=function(e,t){if(e.RTCIceGatherer&&(e.RTCIceCandidate||(e.RTCIceCandidate=function(e){return e}),e.RTCSessionDescription||(e.RTCSessionDescription=function(e){return e}),t.version<15025)){var i=Object.getOwnPropertyDescriptor(e.MediaStreamTrack.prototype,"enabled");Object.defineProperty(e.MediaStreamTrack.prototype,"enabled",{set:function(e){i.set.call(this,e);var t=new Event("enabled");t.enabled=e,this.dispatchEvent(t)}})}e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)&&Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new e.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),e.RTCDtmfSender&&!e.RTCDTMFSender&&(e.RTCDTMFSender=e.RTCDtmfSender);var r=(0,s.default)(e,t.version);e.RTCPeerConnection=function(e){return e&&e.iceServers&&(e.iceServers=(0,o.filterIceServers)(e.iceServers,t.version),n.log("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype},e.shimReplaceTrack=function(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)};var r,n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(PR()),o=xR(),a=UR(),s=(r=a)&&r.__esModule?r:{default:r}})),BR=IR((e=>{RR(zR()),Object.defineProperty(e,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};e.shimGetUserMedia=function(e,r){var n=e&&e.navigator,o=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){i.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(e).then(t,r)},!(r.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){var a=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},s=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(e){return"object"===(void 0===e?"undefined":t(e))&&"object"===t(e.audio)&&(e=JSON.parse(JSON.stringify(e)),a(e.audio,"autoGainControl","mozAutoGainControl"),a(e.audio,"noiseSuppression","mozNoiseSuppression")),s(e)},o&&o.prototype.getSettings){var c=o.prototype.getSettings;o.prototype.getSettings=function(){var e=c.apply(this,arguments);return a(e,"mozAutoGainControl","autoGainControl"),a(e,"mozNoiseSuppression","noiseSuppression"),e}}if(o&&o.prototype.applyConstraints){var l=o.prototype.applyConstraints;o.prototype.applyConstraints=function(e){return"audio"===this.kind&&"object"===(void 0===e?"undefined":t(e))&&(e=JSON.parse(JSON.stringify(e)),a(e,"autoGainControl","mozAutoGainControl"),a(e,"noiseSuppression","mozNoiseSuppression")),l.apply(this,[e])}}}};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(PR())})),jR=IR((e=>{RR(zR()),Object.defineProperty(e,"__esModule",{value:!0}),e.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){var r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}})),HR=IR((e=>{RR(zR()),Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetDisplayMedia=e.shimGetUserMedia=void 0;var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=BR();Object.defineProperty(e,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}});var r=jR();Object.defineProperty(e,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}}),e.shimOnTrack=function(e){"object"===(void 0===e?"undefined":t(e))&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},e.shimPeerConnection=function(e,i){if("object"===(void 0===e?"undefined":t(e))&&(e.RTCPeerConnection||e.mozRTCPeerConnection)){!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),i.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){var i=e.RTCPeerConnection.prototype[t],r=function(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}({},t,(function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}));e.RTCPeerConnection.prototype[t]=r[t]}));var r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){var e=Array.prototype.slice.call(arguments),t=e[0],o=e[1],a=e[2];return n.apply(this,[t||null]).then((function(e){if(i.version<53&&!o)try{e.forEach((function(e){e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach((function(t,i){e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(o,a)}}},e.shimSenderGetStats=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&(!e.RTCRtpSender||!("getStats"in e.RTCRtpSender.prototype))){var i=e.RTCPeerConnection.prototype.getSenders;i&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,t=i.apply(this,[]);return t.forEach((function(t){return t._pc=e})),t});var r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=r.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)}}},e.shimReceiverGetStats=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&(!e.RTCRtpSender||!("getStats"in e.RTCRtpReceiver.prototype))){var i=e.RTCPeerConnection.prototype.getReceivers;i&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,t=i.apply(this,[]);return t.forEach((function(t){return t._pc=e})),t}),n.wrapPeerConnectionEvent(e,"track",(function(e){return e.receiver._pc=e.srcElement,e})),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}},e.shimRemoveStream=function(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;n.deprecated("removeStream","removeTrack"),this.getSenders().forEach((function(i){i.track&&e.getTracks().includes(i.track)&&t.removeTrack(i)}))})},e.shimRTCDataChannel=function(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)},e.shimAddTransceiver=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection){var i=e.RTCPeerConnection.prototype.addTransceiver;i&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var e=arguments[1],t=e&&"sendEncodings"in e;t&&e.sendEncodings.forEach((function(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")}));var r=i.apply(this,arguments);if(t){var n=r.sender,o=n.getParameters();(!("encodings"in o)||1===o.encodings.length&&0===Object.keys(o.encodings[0]).length)&&(o.encodings=e.sendEncodings,n.sendEncodings=e.sendEncodings,this.setParametersPromises.push(n.setParameters(o).then((function(){delete n.sendEncodings})).catch((function(){delete n.sendEncodings}))))}return r})}},e.shimGetParameters=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCRtpSender){var i=e.RTCRtpSender.prototype.getParameters;i&&(e.RTCRtpSender.prototype.getParameters=function(){var e=i.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}},e.shimCreateOffer=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection){var i=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){var e=this,t=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return i.apply(e,t)})).finally((function(){e.setParametersPromises=[]})):i.apply(this,arguments)}}},e.shimCreateAnswer=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection){var i=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){var e=this,t=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return i.apply(e,t)})).finally((function(){e.setParametersPromises=[]})):i.apply(this,arguments)}}};var n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(PR())})),GR=IR((e=>{RR(zR()),Object.defineProperty(e,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};e.shimLocalStreamsAPI=function(e){if("object"===(void 0===e?"undefined":t(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)){var i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){var t=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((function(r){return i.call(t,r,e)})),e.getVideoTracks().forEach((function(r){return i.call(t,r,e)}))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var t=this,r=arguments.length,n=Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return n&&n.forEach((function(e){t._localStreams?t._localStreams.includes(e)||t._localStreams.push(e):t._localStreams=[e]})),i.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._localStreams||(this._localStreams=[]);var i=this._localStreams.indexOf(e);if(-1!==i){this._localStreams.splice(i,1);var r=e.getTracks();this.getSenders().forEach((function(e){r.includes(e.track)&&t.removeTrack(e)}))}})}},e.shimRemoteStreamsAPI=function(e){if("object"===(void 0===e?"undefined":t(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:function(){return this._onaddstream},set:function(e){var t=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((function(e){if(t._remoteStreams||(t._remoteStreams=[]),!t._remoteStreams.includes(e)){t._remoteStreams.push(e);var i=new Event("addstream");i.stream=e,t.dispatchEvent(i)}}))})}});var i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((function(t){if(e._remoteStreams||(e._remoteStreams=[]),!(e._remoteStreams.indexOf(t)>=0)){e._remoteStreams.push(t);var i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}}))}),i.apply(e,arguments)}}},e.shimCallbacksAPI=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection){var i=e.RTCPeerConnection.prototype,r=i.createOffer,n=i.createAnswer,o=i.setLocalDescription,a=i.setRemoteDescription,s=i.addIceCandidate;i.createOffer=function(e,t){var i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},i.createAnswer=function(e,t){var i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};var c=function(e,t,i){var r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r};i.setLocalDescription=c,c=function(e,t,i){var r=a.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},i.setRemoteDescription=c,c=function(e,t,i){var r=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},i.addIceCandidate=c}},e.shimGetUserMedia=function(e){var t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){var i=t.mediaDevices,n=i.getUserMedia.bind(i);t.mediaDevices.getUserMedia=function(e){return n(r(e))}}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))},e.shimConstraints=r,e.shimRTCIceServerUrls=function(e){if(e.RTCPeerConnection){var t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){for(var n=[],o=0;o<e.iceServers.length;o++){var a=e.iceServers[o];!a.hasOwnProperty("urls")&&a.hasOwnProperty("url")?(i.deprecated("RTCIceServer.url","RTCIceServer.urls"),(a=JSON.parse(JSON.stringify(a))).urls=a.url,delete a.url,n.push(a)):n.push(e.iceServers[o])}e.iceServers=n}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:function(){return t.generateCertificate}})}},e.shimTrackEventTransceiver=function(e){"object"===(void 0===e?"undefined":t(e))&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},e.shimCreateOfferLegacy=function(e){var t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);var i=this.getTransceivers().find((function(e){return"audio"===e.receiver.track.kind}));!1===e.offerToReceiveAudio&&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.offerToReceiveAudio&&!i&&this.addTransceiver("audio"),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);var r=this.getTransceivers().find((function(e){return"video"===e.receiver.track.kind}));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0===e.offerToReceiveVideo&&!r&&this.addTransceiver("video")}return t.apply(this,arguments)}},e.shimAudioContext=function(e){"object"!==(void 0===e?"undefined":t(e))||e.AudioContext||(e.AudioContext=e.webkitAudioContext)};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(PR());function r(e){return e&&void 0!==e.video?Object.assign({},e,{video:i.compactObject(e.video)}):e}})),WR=IR((e=>{RR(zR()),Object.defineProperty(e,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};e.shimRTCIceCandidate=function(e){if(!(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)){var i=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){var r=new i(e),o=n.default.parseCandidate(e.candidate),a=Object.assign(r,o);return a.toJSON=function(){return{candidate:a.candidate,sdpMid:a.sdpMid,sdpMLineIndex:a.sdpMLineIndex,usernameFragment:a.usernameFragment}},a}return new i(e)},e.RTCIceCandidate.prototype=i.prototype,o.wrapPeerConnectionEvent(e,"icecandidate",(function(t){return t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t}))}},e.shimMaxMessageSize=function(e,t){if(e.RTCPeerConnection){"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp}});var i=function(e){if(!e||!e.sdp)return!1;var t=n.default.splitSections(e.sdp);return t.shift(),t.some((function(e){var t=n.default.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},r=function(e){var t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;var i=parseInt(t[1],10);return i!=i?-1:i},o=function(e){var i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i},a=function(e,i){var r=65536;"firefox"===t.browser&&57===t.version&&(r=65535);var o=n.default.matchPrefix(e.sdp,"a=max-message-size:");return o.length>0?r=parseInt(o[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(r=2147483637),r},s=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){var e=this.getConfiguration(),n=e.sdpSemantics;"plan-b"===n&&Object.defineProperty(this,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){var c=r(arguments[0]),l=o(c),d=a(arguments[0],c),u=void 0;u=0===l&&0===d?Number.POSITIVE_INFINITY:0===l||0===d?Math.max(l,d):Math.min(l,d);var h={};Object.defineProperty(h,"maxMessageSize",{get:function(){return u}}),this._sctp=h}return s.apply(this,arguments)}}},e.shimSendThrowTypeError=function(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){var i=e.send;e.send=function(){var 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)}}var i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){var e=i.apply(this,arguments);return t(e,this),e},o.wrapPeerConnectionEvent(e,"datachannel",(function(e){return t(e.channel,e.target),e}))},e.shimConnectionState=function(e){if(e.RTCPeerConnection&&!("connectionState"in e.RTCPeerConnection.prototype)){var t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(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((function(e){var i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;var i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}},e.removeExtmapAllowMixed=function(e,t){if(e.RTCPeerConnection&&!("chrome"===t.browser&&t.version>=71)&&!("safari"===t.browser&&t.version>=605)){var i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){var r=t.sdp.split("\n").filter((function(e){return"a=extmap-allow-mixed"!==e.trim()})).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return i.apply(this,arguments)}}},e.shimAddIceCandidateNullOrEmpty=function(e,t){if(e.RTCPeerConnection&&e.RTCPeerConnection.prototype){var 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())})}};var i,r=VR(),n=(i=r)&&i.__esModule?i:{default:i},o=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(PR())})),JR=IR((e=>{RR(zR()),Object.defineProperty(e,"__esModule",{value:!0}),e.adapterFactory=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=e.window,c=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},l=t.log,d=t.detectBrowser(s),u={browserDetails:d,commonShim:a,extractVersion:t.extractVersion,disableLog:t.disableLog,disableWarnings:t.disableWarnings};switch(d.browser){case"chrome":if(!i||!i.shimPeerConnection||!c.shimChrome)return l("Chrome shim is not included in this adapter release."),u;if(null===d.version)return l("Chrome shim can not determine version, not shimming."),u;l("adapter.js shimming chrome."),u.browserShim=i,a.shimAddIceCandidateNullOrEmpty(s,d),i.shimGetUserMedia(s,d),i.shimMediaStream(s,d),i.shimPeerConnection(s,d),i.shimOnTrack(s,d),i.shimAddTrackRemoveTrack(s,d),i.shimGetSendersWithDtmf(s,d),i.shimGetStats(s,d),i.shimSenderReceiverGetStats(s,d),i.fixNegotiationNeeded(s,d),a.shimRTCIceCandidate(s,d),a.shimConnectionState(s,d),a.shimMaxMessageSize(s,d),a.shimSendThrowTypeError(s,d),a.removeExtmapAllowMixed(s,d);break;case"firefox":if(!n||!n.shimPeerConnection||!c.shimFirefox)return l("Firefox shim is not included in this adapter release."),u;l("adapter.js shimming firefox."),u.browserShim=n,a.shimAddIceCandidateNullOrEmpty(s,d),n.shimGetUserMedia(s,d),n.shimPeerConnection(s,d),n.shimOnTrack(s,d),n.shimRemoveStream(s,d),n.shimSenderGetStats(s,d),n.shimReceiverGetStats(s,d),n.shimRTCDataChannel(s,d),n.shimAddTransceiver(s,d),n.shimGetParameters(s,d),n.shimCreateOffer(s,d),n.shimCreateAnswer(s,d),a.shimRTCIceCandidate(s,d),a.shimConnectionState(s,d),a.shimMaxMessageSize(s,d),a.shimSendThrowTypeError(s,d);break;case"edge":if(!r||!r.shimPeerConnection||!c.shimEdge)return l("MS edge shim is not included in this adapter release."),u;l("adapter.js shimming edge."),u.browserShim=r,r.shimGetUserMedia(s,d),r.shimGetDisplayMedia(s,d),r.shimPeerConnection(s,d),r.shimReplaceTrack(s,d),a.shimMaxMessageSize(s,d),a.shimSendThrowTypeError(s,d);break;case"safari":if(!o||!c.shimSafari)return l("Safari shim is not included in this adapter release."),u;l("adapter.js shimming safari."),u.browserShim=o,a.shimAddIceCandidateNullOrEmpty(s,d),o.shimRTCIceServerUrls(s,d),o.shimCreateOfferLegacy(s,d),o.shimCallbacksAPI(s,d),o.shimLocalStreamsAPI(s,d),o.shimRemoteStreamsAPI(s,d),o.shimTrackEventTransceiver(s,d),o.shimGetUserMedia(s,d),o.shimAudioContext(s,d),a.shimRTCIceCandidate(s,d),a.shimMaxMessageSize(s,d),a.shimSendThrowTypeError(s,d),a.removeExtmapAllowMixed(s,d);break;default:l("Unsupported browser!")}return u};var t=s(PR()),i=s(OR()),r=s(FR()),n=s(HR()),o=s(GR()),a=s(WR());function s(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}})),zR=IR((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=(0,JR().adapterFactory)({window:"undefined"==typeof window?void 0:window});e.default=t})),KR=IR(((e,t)=>{RR(zR());var i=Object.prototype.hasOwnProperty,r="~";function n(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var s=new o(i,n||e,a),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(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,a=new Array(o);n<o;n++)a[n]=i[n].fn;return a},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,a){var s=r?r+e:e;if(!this._events[s])return!1;var c,l,d=this._events[s],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,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,a),!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 a(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return a(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 s(this,o),this;var a=this._events[o];if(a.fn)a.fn===t&&(!n||a.once)&&(!i||a.context===i)&&s(this,o);else{for(var c=0,l=[],d=a.length;c<d;c++)(a[c].fn!==t||n&&!a[c].once||i&&a[c].context!==i)&&l.push(a[c]);l.length?this._events[o]=1===l.length?l[0]:l:s(this,o)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(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)})),qR=IR(((e,t)=>{RR(zR());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")}))}))})),QR=IR((e=>{RR(zR());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=qR(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],a=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:[]}),a=o[o.length-1]);for(var s=0;s<(r[t]||[]).length;s+=1){var c=r[t][s];if(c.reg.test(n))return i(c,a,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}}))}))}})),YR=IR(((e,t)=>{RR(zR());var i=qR(),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 a=t.names[o];t.name?r.push(i[t.name][a]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||a,n=t.innerOrder||s,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"}})),XR=IR((e=>{RR(zR());var t=QR(),i=YR();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})),$R=IR(((e,t)=>{RR(zR()),function(e){function i(e,t){var i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function r(e,t,r,n,o,a){return i(function(e,t){return e<<t|e>>>32-t}(i(i(t,e),i(n,a)),o),r)}function n(e,t,i,n,o,a,s){return r(t&i|~t&n,e,t,o,a,s)}function o(e,t,i,n,o,a,s){return r(t&n|i&~n,e,t,o,a,s)}function a(e,t,i,n,o,a,s){return r(t^i^n,e,t,o,a,s)}function s(e,t,i,n,o,a,s){return r(i^(t|~n),e,t,o,a,s)}function c(e,t){e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var r,c,l,d,u,h=1732584193,p=-271733879,m=-1732584194,_=271733878;for(r=0;r<e.length;r+=16)c=h,l=p,d=m,u=_,h=n(h,p,m,_,e[r],7,-680876936),_=n(_,h,p,m,e[r+1],12,-389564586),m=n(m,_,h,p,e[r+2],17,606105819),p=n(p,m,_,h,e[r+3],22,-1044525330),h=n(h,p,m,_,e[r+4],7,-176418897),_=n(_,h,p,m,e[r+5],12,1200080426),m=n(m,_,h,p,e[r+6],17,-1473231341),p=n(p,m,_,h,e[r+7],22,-45705983),h=n(h,p,m,_,e[r+8],7,1770035416),_=n(_,h,p,m,e[r+9],12,-1958414417),m=n(m,_,h,p,e[r+10],17,-42063),p=n(p,m,_,h,e[r+11],22,-1990404162),h=n(h,p,m,_,e[r+12],7,1804603682),_=n(_,h,p,m,e[r+13],12,-40341101),m=n(m,_,h,p,e[r+14],17,-1502002290),h=o(h,p=n(p,m,_,h,e[r+15],22,1236535329),m,_,e[r+1],5,-165796510),_=o(_,h,p,m,e[r+6],9,-1069501632),m=o(m,_,h,p,e[r+11],14,643717713),p=o(p,m,_,h,e[r],20,-373897302),h=o(h,p,m,_,e[r+5],5,-701558691),_=o(_,h,p,m,e[r+10],9,38016083),m=o(m,_,h,p,e[r+15],14,-660478335),p=o(p,m,_,h,e[r+4],20,-405537848),h=o(h,p,m,_,e[r+9],5,568446438),_=o(_,h,p,m,e[r+14],9,-1019803690),m=o(m,_,h,p,e[r+3],14,-187363961),p=o(p,m,_,h,e[r+8],20,1163531501),h=o(h,p,m,_,e[r+13],5,-1444681467),_=o(_,h,p,m,e[r+2],9,-51403784),m=o(m,_,h,p,e[r+7],14,1735328473),h=a(h,p=o(p,m,_,h,e[r+12],20,-1926607734),m,_,e[r+5],4,-378558),_=a(_,h,p,m,e[r+8],11,-2022574463),m=a(m,_,h,p,e[r+11],16,1839030562),p=a(p,m,_,h,e[r+14],23,-35309556),h=a(h,p,m,_,e[r+1],4,-1530992060),_=a(_,h,p,m,e[r+4],11,1272893353),m=a(m,_,h,p,e[r+7],16,-155497632),p=a(p,m,_,h,e[r+10],23,-1094730640),h=a(h,p,m,_,e[r+13],4,681279174),_=a(_,h,p,m,e[r],11,-358537222),m=a(m,_,h,p,e[r+3],16,-722521979),p=a(p,m,_,h,e[r+6],23,76029189),h=a(h,p,m,_,e[r+9],4,-640364487),_=a(_,h,p,m,e[r+12],11,-421815835),m=a(m,_,h,p,e[r+15],16,530742520),h=s(h,p=a(p,m,_,h,e[r+2],23,-995338651),m,_,e[r],6,-198630844),_=s(_,h,p,m,e[r+7],10,1126891415),m=s(m,_,h,p,e[r+14],15,-1416354905),p=s(p,m,_,h,e[r+5],21,-57434055),h=s(h,p,m,_,e[r+12],6,1700485571),_=s(_,h,p,m,e[r+3],10,-1894986606),m=s(m,_,h,p,e[r+10],15,-1051523),p=s(p,m,_,h,e[r+1],21,-2054922799),h=s(h,p,m,_,e[r+8],6,1873313359),_=s(_,h,p,m,e[r+15],10,-30611744),m=s(m,_,h,p,e[r+6],15,-1560198380),p=s(p,m,_,h,e[r+13],21,1309151649),h=s(h,p,m,_,e[r+4],6,-145523070),_=s(_,h,p,m,e[r+11],10,-1120210379),m=s(m,_,h,p,e[r+2],15,718787259),p=s(p,m,_,h,e[r+9],21,-343485551),h=i(h,c),p=i(p,l),m=i(m,d),_=i(_,u);return[h,p,m,_]}function l(e){var t,i="",r=32*e.length;for(t=0;t<r;t+=8)i+=String.fromCharCode(e[t>>5]>>>t%32&255);return i}function d(e){var t,i=[];for(i[(e.length>>2)-1]=void 0,t=0;t<i.length;t+=1)i[t]=0;var r=8*e.length;for(t=0;t<r;t+=8)i[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return i}function u(e){var t,i,r="0123456789abcdef",n="";for(i=0;i<e.length;i+=1)t=e.charCodeAt(i),n+=r.charAt(t>>>4&15)+r.charAt(15&t);return n}function h(e){return unescape(encodeURIComponent(e))}function p(e){return function(e){return l(c(d(e),8*e.length))}(h(e))}function m(e,t){return function(e,t){var i,r,n=d(e),o=[],a=[];for(o[15]=a[15]=void 0,n.length>16&&(n=c(n,8*e.length)),i=0;i<16;i+=1)o[i]=909522486^n[i],a[i]=1549556828^n[i];return r=c(o.concat(d(t)),512+8*t.length),l(c(a.concat(r),640))}(h(e),h(t))}function _(e,t,i){return t?i?m(t,e):function(e,t){return u(m(e,t))}(t,e):i?p(e):function(e){return u(p(e))}(e)}"function"==typeof define&&define.amd?define((function(){return _})):"object"==typeof t&&t.exports?t.exports=_:e.md5=_}(e)}));RR(zR()),RR(zR()),RR(zR(),1),RR(zR(),1);var ZR="4.15.00.1600",eA="5.0.0";var tA,iA="undefined"!=typeof importScripts,rA="undefined"!=typeof registerProcessor,nA="",oA=e=>nA=e,aA="web.sdk.qcloud.com",sA="web.sdk.tencent.cn",cA="web.sdk.cloud.tencent.cn",lA="https://console.cloud.tencent.com/trtc",dA="https://".concat(aA,"/trtc/webrtc/v5/doc"),uA="".concat(dA,"/zh-cn/"),hA="jssdk_log",pA="jssdk_new_endreport",mA="qcloud",_A="trtc",fA="webrtc",gA=((tA=gA||{})[tA.TRACE=0]="TRACE",tA[tA.DEBUG=1]="DEBUG",tA[tA.INFO=2]="INFO",tA[tA.WARN=3]="WARN",tA[tA.ERROR=4]="ERROR",tA[tA.NONE=5]="NONE",tA),vA={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5},TA={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:192},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},SA={"120p":{width:160,height:120,frameRate:15,bitrate:200},"180p":{width:320,height:180,frameRate:15,bitrate:350},"240p":{width:320,height:240,frameRate:15,bitrate:400},"360p":{width:640,height:360,frameRate:15,bitrate:800},"480p":{width:640,height:480,frameRate:15,bitrate:900},"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}},yA={"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}},EA="canvas",IA="audio",CA="video",RA="screen",AA="small",bA="big",kA="auxiliary",wA="smallVideo",PA="user",DA="environment",NA="mute",OA="unmute",MA="ended",LA="playing",xA="pause",VA="error",UA="loadeddata",FA="audioinput",BA="videoinput",jA="main",HA="backup",GA="subscribe",WA="unsubscribe",JA="sendonly",zA="recvonly",KA="inactive",qA="sendonly",QA="recvonly",YA="wss://trtc.rtc.qq.com",XA="wss://webrtc.qq.com",$A="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",ZA=jA,eb=kA,tb="unknown",ib="new",rb="connecting",nb="failed",ob="closed",ab="disconnected",sb="connected",cb="completed",lb=1/0;function db(){return lb}var ub="rejoin",hb="iceConnectionState",pb="player-error",mb="load-worklet",_b="unified-plan",fb="plan-b",gb={MANUAL:"manual",PRESET_LAYOUT:"preset-layout"},vb={REMOTE:"$PLACE_HOLDER_REMOTE$"},Tb={IT_AUDIO_VIDEO:0,IT_PICTURE:2,IT_CANVAS:3,IT_PURE_AUDIO:4,IT_PURE_VIDEO:5},Sb="string",yb="number",Eb="boolean",Ib="array",Cb="object",Rb=1028,Ab="schedule.rtc.qq.com",bb="schedule.rtc.qcloud.com",kb="schedule.rtc.tencentcloud.com",wb="schedule-ecdn.rtc.tencentcloud.com",Pb="default",Db=Pb,Nb=["normal leave","timeout leave","kick","role change"],Ob=2e3,Mb="ric",Lb="raf",xb="timeout";RR(zR(),1),RR(zR(),1);(new Date).getTime();var Vb=0,Ub=function(){return(new Date).getTime()+Vb},Fb=function(){let e=new Date;return e.setTime(Ub()),e.toLocaleString()},Bb={};CR(Bb,{bytes2ms:()=>sP,catchEmitterError:()=>NP,copyProperties:()=>aP,deepMerge:()=>HP,fibonacci:()=>mP,formatedTime:()=>JP,getConstructorName:()=>kP,getContainerFromElement:()=>GP,getEnv:()=>$w,getInternalVersion:()=>MP,getLoggerUrl:()=>eP,getMuteStateFromFlag:()=>VP,getNetworkQuality:()=>UP,getNetworkType:()=>rP,getOSType:()=>iP,getReconnectionTimeout:()=>_P,getSysInfo:()=>nP,getTerminalType:()=>tP,getTurnServer:()=>FP,getValueType:()=>fP,glog:()=>uP,ipv4ToUint32:()=>BP,isArray:()=>IP,isArrayOrObject:()=>jP,isAudioWorkletSupported:()=>wP,isBoolean:()=>yP,isConstructor:()=>bP,isEmpty:()=>xP,isFunction:()=>gP,isLangChinese:()=>hP,isMediaStreamTrack:()=>CP,isNumber:()=>SP,isObject:()=>EP,isOverseaSdkAppId:()=>Zw,isPlainObject:()=>pP,isPromise:()=>AP,isRemoteTrack:()=>RP,isString:()=>TP,isUndefined:()=>vP,ms2bytes:()=>lP,ms2samples:()=>dP,performanceNow:()=>DP,promiseAny:()=>PP,samples2ms:()=>cP,tryCatchFunction:()=>oP}),RR(zR(),1),RR(zR(),1);var jb="undefined"==typeof navigator?"":navigator.userAgent,Hb=e=>new RegExp(e,"i").test(jb),Gb=e=>{if(Hb(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=jb.match(t);if(i&&i[1])return i[1]}return""},Wb=e=>{if(Hb(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=jb.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},Jb=/AppleWebKit\/([\d.]+)/i.exec(jb);Jb&&parseFloat(Jb[1]);var zb=Hb("iPad"),Kb="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Hb("Macintosh"),qb=Hb("iPhone")&&!zb,Qb=Hb("iPod"),Yb=qb||zb||Qb||Kb,Xb=Hb("Android");!function(){if(Xb){let e=jb.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}}}();Xb&&Hb("webkit");var $b=Hb("Firefox"),Zb=Gb("Firefox"),ek=Wb("Firefox"),tk=Hb("Edge"),ik=Gb("Edge"),rk=Hb("Edg"),nk=Gb("Edg"),ok=Wb("Edg"),ak=Hb("SogouMobileBrowser"),sk=Gb("SogouMobileBrowser"),ck=Hb("MetaSr\\s"),lk=Gb("MetaSr\\s"),dk=Hb("TBS"),uk=Gb("TBS"),hk=Hb("XWEB"),pk=Gb("XWEB");Hb("MSIE\\s8\\.0");var mk=Hb("MSIE\\/\\d+");!function(){if(mk){let e=/MSIE\s(\d+)\.\d/.exec(jb),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(jb)&&/rv:11.0/.test(jb)&&(t=11),t}}();var _k=Hb("(micromessenger|webbrowser)"),fk=Gb("MicroMessenger"),gk=!dk&&Hb("MQQBrowser")&&Hb("COVC"),vk=!dk&&Hb("MQQBrowser")&&!Hb("COVC"),Tk=vk||gk?Gb("MQQBrowser"):"",Sk=!dk&&Hb(" QQBrowser"),yk=Gb(" QQBrowser"),Ek=!dk&&Hb("QQBrowserLite"),Ik=Gb("QQBrowserLite"),Ck=!dk&&Hb("MQBHD"),Rk=Gb("MQBHD"),Ak=Hb("Windows"),bk=!Yb&&Hb("MAC OS X"),kk=!Xb&&Hb("Linux");Hb("MicroMessenger");var wk=Hb("UCBrowser");Hb("Electron");var Pk=Hb("MiuiBrowser"),Dk=Gb("MiuiBrowser"),Nk=Hb("HuaweiBrowser");Hb("Huawei");var Ok=Gb("HuaweiBrowser"),Mk=Hb("SamsungBrowser"),Lk=Gb("SamsungBrowser"),xk=Hb("HeyTapBrowser"),Vk=Gb("HeyTapBrowser"),Uk=Hb("VivoBrowser"),Fk=Gb("VivoBrowser"),Bk=()=>Wb("Chrome"),jk=Hb("Chrome"),Hk=!tk&&!ck&&!ak&&!dk&&!hk&&!rk&&!Sk&&!Pk&&!Nk&&!Mk&&!xk&&!Uk&&jk,Gk=Hb("HeadlessChrome"),Wk=Bk(),Jk=Gb("Chrome"),zk=!jk&&!vk&&!gk&&!Ek&&!Ck&&Hb("Safari"),Kk=Gb("Safari");/Android.*(wv|.0.0.0)/.test(jb);var qk=(()=>{if(Kb)return Kk;if(Yb){let e=jb.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),Qk="15.1"===Kk,Yk="15.1"===qk;(()=>{let e=Number(qk.split(".")[0])})();var Xk="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),$k=(()=>{let e;return()=>{if(vP(e))try{e=!!window.localStorage}catch(KO){e=!1}return e}})(),Zk=function(){let e=new Map([[$b,["Firefox",Zb]],[rk,["Edg",nk]],[Hk,["Chrome",Jk]],[zk,["Safari",Kk]],[dk,["TBS",uk]],[hk,["XWEB",pk]],[_k&&qb,["WeChat",fk]],[Sk,["QQ(Win)",yk]],[vk,["QQ(Mobile)",Tk]],[gk,["QQ(Mobile X5)",Tk]],[Ek,["QQ(Mac)",Ik]],[Ck,["QQ(iPad)",Rk]],[Pk,["MI",Dk]],[Nk,["HW",Ok]],[Mk,["Samsung",Lk]],[xk,["OPPO",Vk]],[Uk,["VIVO",Fk]],[tk,["EDGE",ik]],[ak,["SogouMobile",sk]],[ck,["Sogou",lk]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}();RR(zR(),1),RR(zR(),1),RR(zR(),1);var ew=1e8,tw="API_CALL_TIMEOUT",iw="SIGNAL_CHANNEL_RECONNECTION_FAILED",rw="SIGNAL_CHANNEL_SETUP_FAILED",nw="ERROR_MESSAGE",ow="DOWNLINK_RECONNECTION_FAILED",aw="EXCHANGE_SDP_FAILED",sw="UPLINK_RECONNECTION_FAILED",cw="INVALID_PURE_AUDIO",lw="INVALID_STREAMID",dw="INVALID_USER_DEFINE_RECORDID",uw="INVALID_USER_DEFINE_PUSH_ARGS",hw="INVALID_JOIN",pw="JOIN_ROOM_TIMEOUT",mw="JOIN_ROOM_FAILED",_w="REJOIN_ROOM_FAILED",fw="INVALID_DESTROY",gw="SUBSCRIBE_FAILED",vw="SWITCH_ROLE_TIMEOUT",Tw="SWITCH_ROLE_FAILED",Sw="INVALID_OPERATION_START_PUBLISH_CDN",yw="INVALID_OPERATION_STOP_PUBLISH_CDN",Ew="START_PUBLISH_CDN_FAILED",Iw="STOP_PUBLISH_CDN_FAILED",Cw="REPEAT_JOIN",Rw="CLIENT_DESTROYED",Aw="START_MIX_TRANSCODE_FAILED",bw="STOP_MIX_TRANSCODE_FAILED",kw="MIX_TRANSCODE_NOT_STARTED",ww="PLAY_FAILED",Pw="NOT_SUPPORTED_HTTP",Dw="NOT_SUPPORTED_WEBRTC",Nw="NOT_SUPPORTED_H264ENCODE",Ow="NOT_SUPPORTED_H264DECODE",Mw="MICROPHONE_NOT_FOUND",Lw="CAMERA_NOT_FOUND",xw="SIGNAL_RESPONSE_FAILED",Vw="CATCH_HANDLER_ERROR",Uw="CONNECTION_CLOSED",Fw="SEI_DISABLED",Bw="SEI_EMPTY",jw="SEI_OVERSIZE",Hw="SEI_BEFORE_PUBLISH",Gw="CALL_FREQUENCY_LIMIT",Ww="CONNECTION_ABORTED",Jw="API_CALL_ABORTED",zw={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),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(a," when calling ").concat(r,"(), received type: ").concat(fP(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),a="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(a," when calling ").concat(r,"(), received type: ").concat(fP(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:r,value:n}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(n,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,fnName:r,value:n}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(n,".")},API_CALL_TIMEOUT:e=>"".concat(e.commandDesc||e.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," })."),ERROR_MESSAGE(e){let t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>"exchange sdp failed ".concat(e.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>"'".concat(e,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:e=>"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(e){let{error:t,code:i}=e;return"Failed to join room - ".concat(t," code: ").concat(i)},REJOIN_ROOM_FAILED:e=>"reJoin room: ".concat(e.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:"no permission to publish() under live/".concat("audience",', please call switchRole("',"anchor",'") firstly before publish().'),INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>"duplicate ".concat(e," stream publishing, please unpublish your prev ").concat(e," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(e){let{message:t,userId:i,streamType:r}=e;return"failed to subscribe ".concat(i," ").concat(r," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as ".concat("anchor"," or ","audience","."),INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,"."),CLIENT_BANNED:e=>"client was banned because of ".concat(e.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>"startPublishCDNStream failed, errMsg: ".concat(e.message,"."),STOP_PUBLISH_CDN_FAILED:e=>"stopPublishCDNStream failed, errMsg: ".concat(e.message,"."),INVALID_STREAM_ID:e=>"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>"cannot replace ".concat(e.kind," track because stream has not ").concat(e.kind," track"),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 and publish streams, please use the https protocol.",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 and the configuration on TRTC.createStream.",CAMERA_NOT_FOUND:"no camera detected, please check your camera and the configuration on TRTC.createStream.",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 on ".concat(t,".on('").concat(i,"', handler), please check your code on 'handler'.")},API_NOT_EXIST(e){let{name:t}=e;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:e=>"[".concat(e,"] is calling client.join api or has already joined room, 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, to enable SEI: TRTC.createClient({ enableSEI: true })",SEI_EMPTY:"buffer cannot be empty",SEI_OVERSIZE:e=>"buffer size(".concat(e,") is over 1000 Bytes"),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,"()")};function Kw(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}RR(zR());var qw={AVOID_REPEATED_CALL:e=>"前一个 ".concat(e.name,"() 调用正在进行中, 请避免重复调用。"),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"调用 ".concat(r,"() 方法的时候 '").concat(t||i.name,"' 是必须的参数, 收到的值为: ").concat(n,"。")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"调用 ".concat(r,"() 方法的时候 '").concat(o,"' 必须是 ").concat(a," 类型, 收到的类型是: ").concat(Kw(n),"。")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"调用 ".concat(r,"() 的时候 '").concat(t||i.name,"' 不能是 '").concat(n,"'。")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),a="".concat(i.instanceOf.name||i.instanceOf);return"调用 ".concat(r,"() 的时候 '").concat(o,"' 原型必须是 ").concat(a," , 收到的是: ").concat(Kw(n),"。")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"调用 ".concat(r,"() 的时候 '").concat(t||i.name,"' 必须是 ").concat(i.values.join("|")," 的其中一种, 收到的是: ").concat(n,"。")},API_CALL_TIMEOUT:e=>"".concat(e.commandDesc||e.command," 超时。"),SIGNAL_CHANNEL_RECONNECTION_FAILED:"信令通道重连失败,请检查你的网络。",SIGNAL_CHANNEL_SETUP_FAILED:e=>"信令通道建立失败: (错误码: ".concat(e.errorCode,", 错误信息: ").concat(e.errorMsg," })。"),ERROR_MESSAGE(e){let t="".concat(e.type," 失败。");return e.message&&(t="".concat(t,": ").concat(e.message,"。")),t},SUBSCRIPTION_TIMEOUT:"远程服务器不响应订阅行为。",EXCHANGE_SDP_TIMEOUT:"交换 sdp 超时,请刷新网络重试。",DOWNLINK_RECONNECTION_FAILED:"下行重连失败,请检查您的网络并重新加入房间。",EXCHANGE_SDP_FAILED:e=>"交换 SDP 失败,原因 ".concat(e.errMsg,"。"),REPLACE_TRACK_INVALID:"LocalStream 发布之后才可以调用 replaceTrack。",UPDATE_OFFER_TIMEOUT:"更新 offer 超时,请刷新网络重试。",UPLINK_RECONNECTION_FAILED:"上行重连失败,请检查您的网络并重新推流。",INVALID_RECORDID:"recordId 必须是数字。",INVALID_PURE_AUDIO:"pureAudioPushMode 必须是数字1或2。",INVALID_STREAMID:"streamId 必须是 64 字节以内的字符串,并且不能为空。",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId 必须是包含 (a-zA-Z)、(0-9)、下划线和连字符的字符串字面量,64 个字节以内,且不为空。",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs 必须是 256 字节以内的字符串文字,并且不能为空。",INVALID_PROXY:"代理服务器 url 必须以“wss://”开头。",INVALID_JOIN:"join() 方法不能被重复调用。",INVALID_ROOMID_STRING:e=>"当 useStringRoomId 为 true 时,'".concat(e,"' 必须是合法字符串。"),INVALID_ROOMID_INTEGER:e=>"当 useStringRoomId 为 false 时,'".concat(e,"' 必须是合法整数在区间[1, 4294967294]。"),INVALID_SIGNAL_CHANNEL:"SignalChannel 还未初始化好。",JOIN_ROOM_TIMEOUT:"进房超时。",JOIN_ROOM_FAILED:e=>"进房失败,原因:".concat(e.error,"。"),REJOIN_ROOM_FAILED:e=>"重进房: ".concat(e.roomId," 失败,请检查网络状况。"),INVALID_LEAVE:"请在调用 destroy() 方法之前调用 leave()。",INVALID_PUBLISH:"请在调用 publish() 方法之前调用 join()。",INVALID_UNPUBLISH:"还没有被 publish。",INVALID_AUDIENCE:"在观众模式下不允许调用 publish(),请先切换成主播模式。",INVALID_INITIALIZE:"无法发布 stream,原因:localStream 未初始化、正在切换设备、已经调用 localStream.close() 关闭采集",INVALID_DUPLICATE_PUBLISHING:"重复发布,请先 unpublish 之后,再重新 publish。",INVALID_SUBSCRIBE_UNDEFINED:"stream 参数是 undefined 或者 null。",INVALID_SUBSCRIBE_LOCAL:"stream 参数不能为本地流。",INVALID_REMOTE_STREAM:"remoteStream 不存在,已被远端 client 取消发布。",SUBSCRIBE_FAILED(e){let t="订阅流失败,原因: ";return e.message.includes("REMOTE_STREAM_NOT_EXIST")?t+="远端用户已取消推流,无法订阅该远端流。":t+="".concat(e.message,"。"),t},INVALID_ROLE:"只有直播模式才可以进行角色切换。",INVALID_PARAMETER_SWITCH_ROLE:"role 只能设置为 anchor 或者 audience。",INVALID_OPERATION_SWITCH_ROLE:"请在使用 switchRole() 方法前先进房。",SWITCH_ROLE_TIMEOUT:"切换角色超时。",SWITCH_ROLE_FAILED:e=>"切换角色失败。错误码: ".concat(e.code," 错误信息: ").concat(e.message,"。"),CLIENT_BANNED:e=>"您被动退房了,原因为:".concat(e.reason,"。"),INVALID_OPERATION_START_PUBLISH_CDN:"请在进房前或者进房并成功发布本地流后调用 startPublishCDNStream() 方法。",INVALID_OPERATION_STOP_PUBLISH_CDN:"在调用 stopPublishCDNStream() 方法前需要先 startPublishCDNStream()。",INVALID_STREAM_ID:e=>"'".concat(e,"' 只能由大小写字母(a-zA-z), 数字(0-9), 连字符和下划线组成"),START_PUBLISH_CDN_FAILED:e=>"startPublishCDNStream 调用失败,错误信息: ".concat(e.message,"。"),STOP_PUBLISH_CDN_FAILED:e=>"stopPublishCDNStream 调用失败,错误信息: ".concat(e.message,"。"),START_MIX_TRANSCODE:"调用 startMixTranscode() 方法前需要先调用 join()。",STOP_MIX_TRANSCODE:"调用 stopMixTranscode 之前需要调用 startMixTranscode。",INVALID_AUDIO_VOLUME:"interval 必须是数字。",ENABLE_SMALL_STREAM_PUBLISHED:"发布 localStream 之后不允许开启小流。",DISABLE_SMALL_STREAM_PUBLISHED:"发布 localStream 之后不允许关闭小流。",NOT_SUPPORTED_SMALL_STREAM:"您的浏览器不支持开启小流。",INVALID_SMALL_STREAM_PROFILE:"小流参数不合法。",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream 不合法。",REMOTE_NOT_PUBLISH_SMALL_STREAM:"远端用户没有发布小流。",INVALID_SWITCH_DEVICE:"当前的流不可以调用 switchDevice。",INVALID_SWITCH_DEVICE_PUBLISHING:"发布本地流时不能切换设备。",INVALID_REPLACE_TRACK:"client.publish 接口尚未调用完成,请等其调用完成后再调用 replaceTrack 接口。",INVALID_INITIALIZE_LOCAL_STREAM:"本地流还没有初始化。",INVALID_ADD_TRACK_REPETITIVE:"前一个 addTrack 正在进行,请避免重复调用。",INVALID_ADD_TRACK_REMOVING:"track 在移动的时候不能添加新的 track。",INVALID_ADD_TRACK_PUBLISHING:"在发布本地流的时候不能添加新的 track。",INVALID_STREAM_INITIALIZED:"您的本地流还没有初始化。",INVALID_ADD_TRACK_NUMBER:"一条流最多有一个音频轨道和一个视频轨道。",INVALID_REMOVE_AUDIO_TRACK:"remove audio track 是不允许的。",INVALID_REMOVE_AUDIO_ADDING:"当一个 track 被 addTrack 的时候不能对流进行 removeTrack 操作。",INVALID_REMOVE_AUDIO_ON:"前一次调用的 removeTrack 正在进行中,请避免重复操作。",INVALID_REMOVE_TRACK_PUBLISHING:"发布流的过程中不能进行 removeTrack 操作。",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"被 remove 的 track 没有被发布。",INVALID_REMOVE_TRACK_NUMBER:"不支持移除唯一的视频轨道,请使用 replaceTrack 或者 muteVideo 方法。",INVALID_REPLACE_TRACK_NO_TRACK:e=>"LocalStream 没有 ".concat(e.kind," track,无法进行替换。"),START_MIX_TRANSCODE_FAILED:e=>"startMixTranscode 调用失败,错误信息: ".concat(e.message,"。"),STOP_MIX_TRANSCODE_FAILED:e=>"stopMixTranscode 调用失败,错误信息: ".concat(e.message,"。"),MIX_TRANSCODE_NOT_STARTED:"还没有开始 mixTranscode。",CANNOT_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r}=e;return"'当调用 ".concat(r,"() 函数时,要求参数 ").concat(t||i.name,"' 必须大于等于0")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' 应该是 (0, 30] 区间内的整数。",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' 应该是 [1, 8] 区间内的整数。",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' 应该是 [32, 192] 区间内的整数。",MIX_PARAMS_USER_Z_ORDER:e=>"'".concat(e,"' 是必传的,且要求为 [1 ,15] 之间的整数。"),MIX_PARAMS_NOT_SELF:"'config.mixUsers' 必须包含发起混流的用户信息。",MIX_PARAMS_USER_STREAM:"输出流的 'config.videoWidth' 和 'config.videoHeight' 应该容纳所有混入流。",INVALID_PLAY:"play() 被重复调用,请先 stop(),然后再重新调用 play。",INVALID_ELEMENT_ID:e=>{let{key:t,fnName:i}=e;return"在调用 ".concat(i,"() 时,document 对象中找不到 ").concat(t," 对应的元素,请检查。")},INVALID_ELEMENT_ID_TYPE:e=>{let{key:t,type:i,fnName:r}=e;return"在调用 ".concat(r,"() 方法时,").concat(t," 参数对应的 HTML 标签元素必须是 HTMLElement 实例,您传入的是:").concat(i,"。")},PLAY_FAILED:e=>"".concat(e.media," 播放被中断,浏览器异常原因:").concat(e.error.toString()),INVALID_USERID:"userId 不能为空格。",INVALID_CREATE_STREAM_SOURCE:"createStream() 生成 LocalStream 可以使用 audio & video 或 audioSource & videoSource 创建,但不能混合使用。",INVALID_CREATE_STREAM_SCREEN:"screen 和 video 不能同时为 true。",INVALID_CREATE_STREAM_AUDIO:"audio 和 screenAudio 不能同时为 true。",INVALID_CREATE_STREAM_SCREEN_AUDIO:"screen 为 true 时,不能设置 screenAudio。",NOT_SUPPORTED_HTTP:"由于浏览器安全策略限制,不支持在 http 协议下使用采集、推流等能力,请使用 https 协议。",NOT_SUPPORTED_WEBRTC:"当前浏览器或环境不完全支持 WebRTC 能力,请检查浏览器版本和页面访问协议是否满足条件。",NOT_SUPPORTED_PROFILE:"您的浏览器不支持 setVideoProfile 方法。请检查浏览器版本是否满足条件。",NOT_SUPPORTED_MEDIA:"当前浏览器或环境不支持 navigator.mediaDevices,请检查浏览器版本和页面访问协议是否满足条件。",NOT_SUPPORTED_H264ENCODE:"当前的设备或环境不支持 H264 编码,不支持 H264 格式进行推流。",NOT_SUPPORTED_H264DECODE:"当前的设备或环境不支持 H264 解码,不支持 H264 格式进行拉流。",NOT_SUPPORTED_TRACK:e=>"您的浏览器不支持 ".concat(e,"Track 方法。"),NOT_SUPPORTED_REPLACE_TRACK:"您的浏览器不支持 replaceTrack 方法,请使用 switchDevice 或者 addTrack。",NOT_SUPPORTED_CAPTURE:"您当前的浏览器不支持屏幕分享,请检查浏览器版本和页面访问协议是否满足条件。",NOT_SUPPORTED_AUX:"您当前的浏览器不支持推辅流,请检查浏览器版本是否满足条件(Chrome 69+, Safari 11+, Firefox 59+)。",MICROPHONE_NOT_FOUND:"未检测到麦克风,请检查您的麦克风和 TRTC.createStream 上的配置。",CAMERA_NOT_FOUND:"未检测到摄像头,请检查您的摄像头和 TRTC.createStream 上的配置。",CATCH_HANDLER_ERROR:e=>{let{name:t,event:i}=e;return" 在 ".concat(t,".on('").concat(i,"', handler) 事件中捕获到业务侧错误,请根据下述错误信息,检查您在 handler 中的业务代码。")},REPEAT_JOIN:e=>"用户 [".concat(e,"] 正在调用进房接口或者已经在房间内,请勿重复创建相同 userId 的 client 进入同一个房间。"),CLIENT_DESTROYED:e=>{let{funName:t}=e;return"client 已经被销毁,调用 ".concat(t,"() 方法失败。")},API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?"中断订阅用户 ".concat(e.userId," 的 ").concat(e.streamType," stream, 原因: 在您订阅过程中,远端用户 ").concat(e.userId," 取消了推流,您可以在下次远端推流时再进行订阅。"):"中断接口调用, 原因: ".concat(e.message,"。"),t},SEI_BEFORE_PUBLISH:"当前 client 没有推 localStream(主流,非屏幕分享流),无法调用 client.sendSEIMessage() 接口。"},Qw={INVALID_USER_DEFINE_RECORDID:"TRTC.html#createClient",INVALID_PROXY:"Client.html#setProxyServer",INVALID_JOIN:"Client.html#join",INVALID_ROOMID_STRING:"Client.html#join",INVALID_ROOMID_INTEGER:"Client.html#join",INVALID_PUBLISH:"Client.html#publish",INVALID_UNPUBLISH:"Client.html#unpublish",INVALID_AUDIENCE:"Client.html#switchRole",INVALID_INITIALIZE:"Client.html#publish",INVALID_DUPLICATE_PUBLISHING:"Client.html#publish",INVALID_SUBSCRIBE_UNDEFINED:"Client.html#subscribe",INVALID_SUBSCRIBE_LOCAL:"Client.html#subscribe",INVALID_REMOTE_STREAM:"Client.html#subscribe",INVALID_ROLE:"Client.html#switchRole",INVALID_PARAMETER_SWITCH_ROLE:"Client.html#switchRole",INVALID_OPERATION_SWITCH_ROLE:"Client.html#switchRole",CLIENT_BANNED:"module-ClientEvent.html#.CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"Client.html#startPublishCDNStream",INVALID_OPERATION_STOP_PUBLISH_CDN:"Client.html#stopPublishCDNStream",START_MIX_TRANSCODE:"Client.html#startMixTranscode",STOP_MIX_TRANSCODE:"Client.html#stopMixTranscode",INVALID_AUDIO_VOLUME:"Client.html#enableAudioVolumeEvaluation",ENABLE_SMALL_STREAM_PUBLISHED:"Client.html#enableSmallStream",DISABLE_SMALL_STREAM_PUBLISHED:"Client.html#disableSmallStream",NOT_SUPPORTED_SMALL_STREAM:"tutorial-27-advanced-small-stream.html#h2-4",INVALID_SMALL_STREAM_PROFILE:"Client.html#setSmallStreamProfile",REMOTE_NOT_PUBLISH_SMALL_STREAM:"Client.html#setRemoteVideoStreamType",INVALID_SWITCH_DEVICE:"LocalStream.html#switchDevice",INVALID_SWITCH_DEVICE_PUBLISHING:"LocalStream.html#switchDevice",INVALID_REPLACE_TRACK:"LocalStream.html#replaceTrack",INVALID_INITIALIZE_LOCAL_STREAM:"LocalStream.html#replaceTrack",INVALID_ADD_TRACK_REPETITIVE:"LocalStream.html#addTrack",INVALID_ADD_TRACK_REMOVING:"LocalStream.html#addTrack",INVALID_ADD_TRACK_PUBLISHING:"LocalStream.html#addTrack",INVALID_STREAM_INITIALIZED:"LocalStream.html#addTrack",INVALID_ADD_TRACK_NUMBER:"LocalStream.html#addTrack",INVALID_REMOVE_AUDIO_TRACK:"LocalStream.html#removeTrack",INVALID_REMOVE_AUDIO_ADDING:"LocalStream.html#removeTrack",INVALID_REMOVE_AUDIO_ON:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_PUBLISHING:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NUMBER:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NOT_PUBLISHED:"LocalStream.html#removeTrack",START_MIX_TRANSCODE_TIMEOUT:"Client.html#startMixTranscode",START_MIX_TRANSCODE_FAILED:"Client.html#startMixTranscode",STOP_MIX_TRANSCODE_FAILED:"Client.html#stopMixTranscode",MIX_TRANSCODE_NOT_STARTED:"Client.html#startMixTranscode",MIX_PARAMS_VIDEO_FRAMERATE:"Client.html#startMixTranscode",MIX_PARAMS_VIDEO_GOP:"Client.html#startMixTranscode",MIX_PARAMS_AUDIO_BITRATE:"Client.html#startMixTranscode",MIX_PARAMS_USER_Z_ORDER:"Client.html#startMixTranscode",MIX_PARAMS_NOT_SELF:"Client.html#startMixTranscode",MIX_PARAMS_USER_STREAM:"Client.html#startMixTranscode",INVALID_PLAY:"Stream.html#play",PLAY_FAILED:"Stream.html#play",INVALID_USERID:"TRTC.html#createClient",INVALID_CREATE_STREAM_SOURCE:"TRTC.html#createStream",INVALID_CREATE_STREAM_SCREEN:"TRTC.html#createStream",INVALID_CREATE_STREAM_AUDIO:"TRTC.html#createStream",INVALID_CREATE_STREAM_SCREEN_AUDIO:"TRTC.html#createStream",NOT_SUPPORTED_HTTP:"tutorial-05-info-browser.html#h2-2",NOT_SUPPORTED_WEBRTC:"tutorial-05-info-browser.html",NOT_SUPPORTED_TRTC:"tutorial-05-info-browser.html",NOT_SUPPORTED_PROFILE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_MEDIA:"tutorial-05-info-browser.html",NOT_SUPPORTED_H264ENCODE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_H264DECODE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_TRACK:"LocalStream.html#addTrack",NOT_SUPPORTED_REPLACE_TRACK:"LocalStream.html#replaceTrack",NOT_SUPPORTED_CAPTURE:"tutorial-05-info-browser.html",MICROPHONE_NOT_FOUND:"TRTC.html#createStream",CAMERA_NOT_FOUND:"TRTC.html#createStream",SUBSCRIBE_FAILED:"Client.html#subscribe",API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?"Client.html#subscribe":"module-ErrorCode.html#.API_CALL_ABORTED",t}};"undefined"!=typeof window&&(window.TRTC_ERROR_INFO=qw,window.TRTC_ERROR_LINK=Qw);var Yw=(e,t)=>t?"".concat(dA,"/").concat(e,"/").concat(t):"".concat(dA,"/").concat(e,"/index.html");function Xw(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",a="",s="";gP(zw[t])?o=zw[t](i):TP(zw[t])&&(o=zw[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=(()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let e=localStorage.getItem("trtc_error_assistance");if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let i=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:r}}return{}})();r?s="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(gP(l[t])?s=l[t](i):TP(l[t])&&(s=l[t]));let d=o;return hP()&&(c&&c[t]&&(gP(c[t])?a=c[t](i):TP(c[t])&&(a=c[t])),a&&(d=n?"".concat(a,"\n请查看文档: ").concat(Yw("zh-cn",s),"\n\n"):"".concat(a,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(Yw("en",s),"\n")),d}var $w=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Zw=e=>Number(e)<14e8,eP=function(e,t){let i;i=nA||(Zw(e)?"https://videoapi-sgp.im.qcloud.com":"https://yun.tim.qq.com");let r=Math.floor(Math.random()*TR(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)};function tP(){return Xb?4:qb?2:zb?3:bk?12:Ak?5:kk?13:1}function iP(){return Xb?"Android":qb?"iPhone":zb?"iPad":bk?"Mac":Ak?"Windows":kk?"Linux":"unknown"}function rP(){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();"slow-2"===n&&(n="2g");let o=i||"unknown";if(r)switch(r){case"cellular":case"wimax":o=n||"unknown";break;case"wifi":o="wifi";break;case"ethernet":o="wired";break;default:o="unknown"}return o}var nP=function(e){return{AbilityOption:{AVLimit:e,GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:String(navigator.platform),uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:tP(),uint32_device_type:0,str_os_verion:iP(),uint32_link_type:1,str_client_version:ZR,uint32_net_type:vA[rP()],ua:navigator.userAgent,version:""}}}};function oP(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||this,r);return AP(o)?o.catch((e=>ZP.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(o){ZP.error("".concat(t.name,"() error observed ").concat(o))}}}function aP(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 sP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3;return cP(e/4,t)}function cP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3;return 1e3*e/t}function lP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3;return 4*dP(e,t)}function dP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3;return e*t/1e3}var uP="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},hP=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},pP=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 mP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?i:mP(e-1,i,t+i)}function _P(e){return e>8?3e4:1e3*mP(e)}function fP(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var gP=e=>"function"==typeof e,vP=e=>void 0===e,TP=e=>"string"==typeof e,SP=e=>"number"==typeof e,yP=e=>"boolean"==typeof e,EP=e=>"object"===fP(e),IP=e=>"array"===fP(e),CP=e=>fP(e)==="MediaStreamTrack".toLowerCase(),RP=e=>e.isRemote,AP=e=>"promise"===fP(e),bP=e=>gP(e)&&e.prototype.constructor===e,kP=e=>bP(e)?e.prototype.constructor.name:"",wP="undefined"!=typeof AudioWorkletNode;function PP(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 DP(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var NP=(e,t)=>{let{emit:i}=e;return 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(a){let e=Xw({key:Vw,data:{name:t,event:n[0]},addDocLink:!1});return ZP.warn("".concat(e,"\n\n").concat(a.stack)),!1}},e},OP=e=>+e<10?"0".concat(e):e,MP=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=OP(i[1])+OP(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},LP=Object.prototype.hasOwnProperty;function xP(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(pP(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(LP.call(e,t))return!1;return!0}return!1}function VP(e,t){return{userId:t,hasAudio:!!(8&e),hasVideo:!!(1&e),hasAuxiliary:!!(4&e),hasSmall:!!(2&e),audioMuted:!!(64&e),videoMuted:!!(16&e),audioAvailable:!(!(8&e)||64&e),videoAvailable:!(!(1&e)||16&e)}}function UP(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}function FP(e){let t={urls:"turn:".concat(e.url)};return!vP(e.username)&&!vP(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",vP(e.credentialType)||(t.credentialType=e.credentialType)),t}function BP(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!TP(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 jP=function(e){return IP(e)||EP(e)},HP=function(e,t,i,r){if(!jP(e)||!jP(t))return 0;let n,o=0,a=Object.keys(t);for(let s=0,c=a.length;s<c;s++)if(n=a[s],!(vP(t[n])||i&&i.includes(n)))if(jP(e[n])&&jP(t[n]))o+=HP(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=t[n],o+=1)}return o},GP=e=>TP(e)?document.getElementById(e):e,WP=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),JP=()=>WP.format(new Date);function zP(e){let{url:t,body:i,method:r,timeout:n}=e,o=new XMLHttpRequest;return new Promise(((e,a)=>{o.onreadystatechange=()=>{if(4===o.readyState)if(o.status>=200&&o.status<300)try{let t=JSON.parse(o.response);e({data:t})}catch(Wx){e({data:o.response})}else a({status:o.status,statusText:o.statusText||"request failed!"})},o.timeout=n||5e3,o.open(r||"POST",t,!0),o.send(i)}))}RR(zR(),1),RR(zR(),1);var KP=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:n,onRetryFailed:o,context:a}=e;return function(){for(var e=arguments.length,s=new Array(e),c=0;c<e;c++)s[c]=arguments[c];let{retries:l=5,timeout:d=1e3}=i,u=0,h=-1,p=0,m=(e,i)=>wR(this,null,(function*(){let c=a||this;try{let i=yield t.apply(c,s);u=0,e(i)}catch(_){let t=()=>{clearTimeout(h),u=0,p=2,i(_)},a=()=>{2!==p&&u<(gP(l)?l():l)?(u++,p=1,gP(n)&&n.call(this,u,t),h=window.setTimeout((()=>{h=-1,m(e,i)}),gP(d)?d(u):d)):(t(),gP(o)&&o.call(this,_))};gP(r)?r.call(c,_,a,i,s):a()}}));return new Promise(m)}};RR(zR(),1);RR(zR(),1);var qP=new(RR(KR(),1).default);RR(zR(),1);var QP,YP=((QP=YP||{}).ROOM_DESTROY="1",QP.JOIN_START="21",QP.JOIN_SCHEDULE_SUCCESS="22",QP.JOIN_SIGNAL_CONNECTION_START="23",QP.JOIN_SIGNAL_CONNECTION_END="24",QP.JOIN_SEND_CMD="25",QP.JOIN_RECEIVED_CMD_RES="26",QP.JOIN_SUCCESS="27",QP.JOIN_FAILED="28",QP.LEAVE_START="51",QP.LEAVE_SEND_CMD="52",QP.LEAVE_SUCCESS="53",QP.PUBLISH_START="61",QP.SEND_FIRST_VIDEO_FRAME="62",QP.SUBSCRIBE_START="81",QP.SUBSCRIBE_SUCCESS="82",QP.UNSUBSCRIBE_SUCCESS="83",QP.LOCAL_TRACK_CAPTURE_START="101",QP.LOCAL_TRACK_CAPTURE_SUCCESS="102",QP.LOCAL_TRACK_CAPTURE_FAILED="103",QP.LOCAL_TRACK_PUBLISHED="104",QP.LOCAL_TRACK_UNPUBLISHED="105",QP.LOCAL_TRACK_REPLACED="106",QP.SWITCH_DEVICE_SUCCESS="107",QP.TRACK_MUTED="108",QP.TRACK_UNMUTED="109",QP.REMOTE_TRACK_SUBSCRIBED="110",QP.REMOTE_TRACK_UNSUBSCRIBED="111",QP.PLAY_TRACK_START="151",QP.PLAYER_STATE_CHANGED="152",QP.VIDEO_LOADED_DATA="153",QP.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",QP.WORKLET_LOADED_SUCCESS="155",QP.WORKLET_LOADED_FAILED="156",QP.SIGNAL_CONNECTION_STATE_CHANGED="201",QP.PEER_CONNECTION_STATE_CHANGED="202",QP.HEARTBEAT_REPORT="251",QP.RECEIVED_PUBLISHED_USER_LIST="252",QP.REMOTE_PUBLISH_STATE_CHANGED="253",QP.AUDIO_LEVEL_INTERVAL="260",QP.NETWORK_QUALITY="261",QP.API_SUCCESS_RATE="262",QP),XP=YP,$P=!(Yb||Xb||Gk),ZP=new class{constructor(){bR(this,"_isEnableUploadLog",!0),bR(this,"_localJoinedUser",new Map),bR(this,"_queue",[]),bR(this,"_timeoutId",-1),bR(this,"_logLevel",1),bR(this,"_logLevelToUpload",2),!iA&&!rA&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){qP.on(XP.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&gA[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),qP.on(XP.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),qP.once(XP.JOIN_FAILED,(()=>{this.startUpload()})),qP.on(XP.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.deleteJoinedUser(t.userId)}))}startUpload(){-1===this._timeoutId&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch((()=>{})),this._timeoutId=window.setTimeout((()=>this.uploadInterval()),2e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&0===this._localJoinedUser.size)return e;let t=0;for(;t<this._queue.length&&50!==t;t++){let i=this._queue[t];if(i.forAllJoinedClients)this._localJoinedUser.forEach((t=>{let{userId:r,sdkAppId:n}=t;e.map.has(r)?e.map.get(r).logs.push(i):e.map.set(r,{userId:r,sdkAppId:n,logs:[i]})}));else if(TP(i.userId)&&SP(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 wR(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:Fb(),sdkAppId:String(r),userId:i,version:eA,log:n.map((e=>e.log)).join("\n")}),r),n.forEach((e=>e.uploaded=!0))}}catch(r){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return KP({retryFunction:()=>zP({url:eP(t,hA),body:e,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:(e,t)=>{t()}})()}getPrefix(e){let t=new Date;t.setTime(Ub());let i=String(t.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),"[".concat(t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(i,"] <").concat(gA[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){vP(gA[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(TP(e))return e;try{return JSON.stringify(e)}catch(t){return""}}log(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;var o;if(t.unshift(this.getPrefix(e)),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push({log:t.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:e,userId:r,sdkAppId:n,forAllJoinedClients:i}),e<this._logLevel)return;let a=(null==(o=gA[e])?void 0:o.toLowerCase())||"info";$P?console[a]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...t):console[a](...t)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}createLogger(e){return new class{constructor(e){bR(this,"userId"),bR(this,"remoteUserId"),bR(this,"id"),bR(this,"sdkAppId"),bR(this,"type"),bR(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!yP(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):"","]")),ZP.log(e,t,vP(this.userId)||xP(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)}}(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;gA[t]&&(this._logLevelToUpload=t)}},eD=!0,tD=RR(KR());RR(zR());var iD={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",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",SEI_MESSAGE:"sei-message"},rD={};CR(rD,{HTTPS_API:()=>ID,IS_GET_CAPABILITIES_SUPPORTED:()=>HD,IS_GET_SETTINGS_SUPPORTED:()=>jD,IS_SEI_SUPPORTED:()=>GD,IS_SPC_SUPPORTED:()=>VD,basis:()=>qD,checkSystemRequirementsInternal:()=>SD,decodeSupportStatus:()=>TD,encodeSupportStatus:()=>vD,getBrowserInfo:()=>uD,getDisplayResolution:()=>bD,getOSName:()=>AD,isAddTransceiverSupported:()=>xD,isBrowserSupported:()=>hD,isGetReceiversSupported:()=>OD,isGetSendersSupported:()=>MD,isGetTransceiversSupported:()=>LD,isGetUserMediaSupported:()=>kD,isMediaDevicesSupported:()=>mD,isMediaSessionSupported:()=>zD,isMediaStreamTrackProcessorSupported:()=>gD,isReplaceTrackSupported:()=>FD,isScreenCaptureApiAvailable:()=>ED,isSelectedCandidatePair:()=>CD,isSetParametersSupported:()=>BD,isSmallStreamAPISupported:()=>PD,isSmallStreamSupported:()=>DD,isStopTransceiverSupported:()=>UD,isTRTCSupported:()=>yD,isUnifiedPlanDefault:()=>ND,isUsedInHttpProtocol:()=>fD,isWebAudioSupported:()=>wD,isWebCodecSupported:()=>JD,isWebCodecsSupported:()=>pD,isWebRTCSupported:()=>WD,isWebTransportSupported:()=>KD}),RR(zR(),1),RR(zR(),1),RR(zR(),1);var nD,oD=((nD=oD||{})[nD.INVALID_PARAMETER=4096]="INVALID_PARAMETER",nD[nD.INVALID_OPERATION=4097]="INVALID_OPERATION",nD[nD.NOT_SUPPORTED=4098]="NOT_SUPPORTED",nD[nD.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",nD[nD.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",nD[nD.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",nD[nD.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",nD[nD.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",nD[nD.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",nD[nD.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",nD[nD.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",nD[nD.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",nD[nD.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",nD[nD.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",nD[nD.CLIENT_BANNED=16448]="CLIENT_BANNED",nD[nD.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",nD[nD.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",nD[nD.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",nD[nD.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",nD[nD.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",nD[nD.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",nD[nD.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",nD[nD.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",nD[nD.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",nD[nD.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",nD[nD.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",nD[nD.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",nD[nD.API_CALL_ABORTED=16461]="API_CALL_ABORTED",nD[nD.UNKNOWN=65535]="UNKNOWN",nD),aD=oD,sD=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=aD.UNKNOWN,extraCode:n=0,constraint:o}=e,a="<".concat(function(e){for(let t in aD)if(aD[t]===e)return t;return"UNKNOWN"}(r)," 0x").concat(r.toString(16),">"),s="".concat(i).concat(o?" constraint: ".concat(o):"").concat(null!=i&&i.includes(a)?"":" ".concat(a));super(s),bR(this,"code"),bR(this,"extraCode"),bR(this,"message"),bR(this,"originMessage"),bR(this,"name"),bR(this,"constraint"),this.code=r,this.extraCode=n,this.name=t,this.message=s,this.constraint=o,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},cD=sD,lD={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},dD=new Map([[$b,["Firefox",Zb]],[rk,["Edg",nk]],[Hk,["Chrome",Jk]],[zk,["Safari",Kk]],[dk,["TBS",uk]],[hk,["XWEB",pk]],[_k&&qb,["WeChat",fk]],[Sk,["QQ(Win)",yk]],[vk,["QQ(Mobile)",Tk]],[gk,["QQ(Mobile X5)",Tk]],[Ek,["QQ(Mac)",Ik]],[Ck,["QQ(iPad)",Rk]],[Pk,["MI",Dk]],[Nk,["HW",Ok]],[Mk,["Samsung",Lk]],[xk,["OPPO",Vk]],[Uk,["VIVO",Fk]],[tk,["EDGE",ik]],[ak,["SogouMobile",sk]],[ck,["Sogou",lk]]]);function uD(){let e=dD.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var hD=function(){return!(wk||tk||rk&&ok<80||$b&&ek<56)},pD=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},mD=function(){if(!navigator.mediaDevices)return ZP.error(zw.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},_D=!1;function fD(){return"http:"===location.protocol&&!Xk&&!_D&&(_D=!0,ZP.warn(Xw({key:Pw})),!0)}var gD=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},vD=function(){return wR(this,null,(function*(){if(lD.detail.isH264EncodeSupported||lD.detail.isVp8EncodeSupported)return{isH264EncodeSupported:lD.detail.isH264EncodeSupported,isVp8EncodeSupported:lD.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection,n=document.createElement(EA);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(),lD.detail.isH264EncodeSupported=t,lD.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:lD.detail.isH264EncodeSupported,isVp8EncodeSupported:lD.detail.isVp8EncodeSupported}}catch(r){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},TD=function(){return wR(this,null,(function*(){if(lD.detail.isH264DecodeSupported&&lD.detail.isVp8DecodeSupported)return{isH264DecodeSupported:lD.detail.isH264DecodeSupported,isVp8DecodeSupported:lD.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(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},SD=function(){return wR(this,null,(function*(){if(lD.result)return lD;let e=hD(),t=WD(),i=pD(),r=mD(),{isH264EncodeSupported:n,isVp8EncodeSupported:o}=yield vD(),{isH264DecodeSupported:a,isVp8DecodeSupported:s}=yield TD();return lD.result=e&&t&&r&&(n||o)&&(a||s),lD.detail.isBrowserSupported=e,lD.detail.isWebRTCSupported=t,lD.detail.isWebCodecsSupported=i,lD.detail.isMediaDevicesSupported=r,lD.detail.isScreenShareSupported=ED(),lD.detail.isSmallStreamSupported=DD(),lD.detail.isH264EncodeSupported=n,lD.detail.isVp8EncodeSupported=o,lD.detail.isH264DecodeSupported=a,lD.detail.isVp8DecodeSupported=s,lD.result||ZP.error("".concat(navigator.userAgent," isBrowserSupported: ").concat(e,"isWebCodecsSupported: ").concat(i," isMediaSupported: ").concat(r," isH264EncodeSupported: ").concat(n," isVp8EncodeSupported: ").concat(o," isH264DecodeSupported: ").concat(a," isVp8DecodeSupported: ").concat(s," ")),lD}))},yD=function(){return lD.result},ED=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},ID=(e,t,i)=>{"http:"===location.protocol&&!Xk&&(e[t]=()=>{throw new cD({code:aD.INVALID_OPERATION,message:zw.NOT_SUPPORTED_HTTP})})},CD=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(yP(e.selected)&&!e.selected)},RD=new Map([[Xb,"Android"],[Yb,"iOS"],[Ak,"Windows"],[bk,"MacOS"],[kk,"Linux"]]),AD=function(){return RD.get(!0)?RD.get(!0):"unknown"};function bD(){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 kD(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function wD(){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 PD(){return"captureStream"in HTMLCanvasElement.prototype}function DD(){return!(_k||Yb||Wk&&Wk<63)&&!(!hD()||!PD())}var ND=function(){if(vP(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:_b}),e.addTransceiver(IA),t=!0}catch(i){}return null==e||e.close(),t};function OD(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function MD(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function LD(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function xD(){return"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var VD=xD();function UD(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function FD(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function BD(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&MD()}var jD=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,HD=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,GD="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Bk()>=86,WD=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function JD(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return vP(window.AudioDecoder)||(e.AudioDecoder=!0),vP(window.AudioEncoder)||(e.AudioEncoder=!0),vP(window.VideoDecoder)||(e.VideoDecoder=!0),vP(window.VideoEncoder)||(e.VideoEncoder=!0),vP(window.ImageDecoder)||(e.ImageDecoder=!0),e}function zD(){return"mediaSession"in navigator&&!vP(navigator.mediaSession.setActionHandler)}function KD(){return!vP(window.WebTransport)}function qD(){let e={browser:"".concat(Zk.name,"/").concat(Zk.version),os:AD(),displayResolution:bD(),isScreenShareSupported:ED(),isWebRTCSupported:WD(),isGetUserMediaSupported:kD(),isWebAudioSupported:wD(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:JD(),isMediaSessionSupported:zD(),isWebTransportSupported:KD()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}RR(zR(),1),RR(zR(),1);var QD=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)}))};RR(zR(),1);var YD=new class{constructor(){bR(this,"_prefix","TRTC"),bR(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){$k()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix)){let t=JSON.parse(localStorage.getItem(e));if(t&&t.expiresIn<Date.now())return!0}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if($k())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(KO){ZP.warn(KO)}}getItem(e){if(!$k())return null;try{let t=JSON.parse(localStorage.getItem(this.getRealKey(e)));return t&&t.expiresIn>=Date.now()?t.value:null}catch(t){ZP.warn(t)}}setItem(e,t){if($k())try{let i={expiresIn:Date.now()+6048e5,value:t};this._queue.set(this.getRealKey(e),i)}catch(i){ZP.warn(i)}}deleteItem(e){if(!$k())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(t){return ZP.warn(t),!1}}clear(){if($k())try{localStorage.clear()}catch(KO){ZP.warn(KO)}}};RR(zR(),1),RR(zR(),1);var XD=RR(KR(),1),$D=Symbol("instance"),ZD=Symbol("abortCtrl"),eN=Symbol("cacheResult"),tN=class{constructor(e,t,i){bR(this,"oldState"),bR(this,"newState"),bR(this,"action"),bR(this,"error"),this.oldState=e,this.newState=t,this.action=i}toString(){return"".concat(this.action,"ing")}},iN=class extends Error{constructor(e,t,i){super(t),bR(this,"state"),bR(this,"message"),bR(this,"cause"),this.state=e,this.message=t,this.cause=i}},rN=new Map,nN=Object.getPrototypeOf(wR(void 0,null,(function*(){}))).constructor;function oN(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,n,o)=>{let a=i.action||n;if(!i.context){let i=rN.get(r)||[];rN.has(r)||rN.set(r,i),i.push({from:e,to:t,action:a})}let s=o.value;o.value=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return wR(this,null,(function*(){var r;let o=this;if(i.context&&(o=uN.get("function"==typeof i.context?i.context.call(this,...n):i.context)),o.state===t)return o[eN];let c=null;if(Array.isArray(e)?0==e.length?o[ZD]&&(o[ZD].aborted=!0):("string"!=typeof o.state||!e.includes(o.state))&&(c=new iN(o._state,"".concat(o.name," ").concat(a," to ").concat(t," failed: current state ").concat(o._state," not in from config"))):e!==o.state&&(c=new iN(o._state,"".concat(o.name," ").concat(a," to ").concat(t," failed: current state ").concat(o._state," not from ").concat(e))),c){if(!i.fail){if(i.ignoreError)return c;throw c}i.fail.call(this,c)}let l=o.state;sN.call(o,new tN(l,t,a));let d={aborted:!1};o[ZD]=d;try{let e=s.apply(this,n);return o[eN]=e instanceof nN?yield e:e,d.aborted||(o[ZD]=void 0,sN.call(o,t),null==(r=i.success)||r.call(this,o[eN])),o[eN]}catch(u){let e=u instanceof Error?u.message:String(u);if(sN.call(o,l,e),!i.fail){if(i.ignoreError)return u;throw u}i.fail.call(this,new iN(o._state,"action '".concat(a,"' failed :").concat(e),u instanceof Error?u:new Error(e)))}}))}}}var aN="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 sN(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(uN.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t})}var cN,lN,dN=class extends XD.default{constructor(e,t,i){super(),bR(this,"name"),bR(this,"groupName"),bR(this,"_state",dN.INIT),bR(this,cN),bR(this,lN),this.name=e,this.groupName=t,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let r=i[$D];r?this.name=r.name+"-"+r.count++:i[$D]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=rN.get(e)||[],i=new Set,r=[],n=[],o=new Set,a=Object.getPrototypeOf(e);rN.has(a)&&(a.stateDiagram.forEach((e=>i.add(e))),a.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 s=[...i];return Object.defineProperties(e,{stateDiagram:{value:s},allStates:{value:o}}),s}static get(e){let t;return"string"==typeof e?(t=dN.instances.get(e),t||dN.instances.set(e,t=new dN(e,void 0,Object.create(dN.prototype)))):(t=dN.instances2.get(e),t||dN.instances2.set(e,t=new dN(e.constructor.name,void 0,Object.create(dN.prototype)))),t}static getState(e){var t;return null==(t=dN.get(e))?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};aN(dN.UPDATEAFSM,yR({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){sN.call(this,e)}},uN=dN;cN=eN,lN=ZD,bR(uN,"STATECHANGED","stateChanged"),bR(uN,"UPDATEAFSM","updateAFSM"),bR(uN,"INIT","[*]"),bR(uN,"ON","on"),bR(uN,"OFF","off"),bR(uN,"instances",new Map),bR(uN,"instances2",new WeakMap),RR(zR(),1),RR(zR(),1),RR(zR(),1),RR(zR(),1),RR(zR(),1);var hN=(null==window?void 0:window.requestIdleCallback)||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},pN=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},mN=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),_N=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:xb,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=yR("interval"===e?{delay:2e3,count:0,backgroundTask:!0}:e===Mb?{delay:1e4,count:0}:e===Lb?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),EP(t)&&(i=yR(yR({},i),t)),gP(e)&&(t=e,e=xb);let r=yR({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i);return this.taskMap.set(r.taskID,r),this[e](r),r.taskID}static interval(e){return e.intervalID=setInterval((()=>{e.callback(),e.loopCount+=1,this.isBreakLoop(e)}),e.delay)}static timeout(e){let t=()=>{if(e.callback(),e.loopCount+=1,!this.isBreakLoop(e))return e.timeoutID=setTimeout(t,e.delay)};return e.timeoutID=setTimeout(t,e.delay)}static ric(e){let t,i=DP(),r=()=>{if(t=DP()-i,t>=e.delay&&(i=DP()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=hN(r,{timeout:e.delay})};return e.ricID=hN(r,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=DP(),r=()=>document.hidden&&e.backgroundTask?(t=DP()-i,i=DP(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(r,e.delay-Math.floor(t%e.delay))):(t=DP()-i,t>=e.delay&&(i=DP()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),this.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(r));if(e.rafID=requestAnimationFrame(r),e.backgroundTask){let t=()=>{if(document.hidden){let t=DP()-i;t>=e.delay?r():e.timeoutID=setTimeout(r,e.delay-t)}};document.addEventListener("visibilitychange",t),e.onVisibilitychange=t,document.hidden&&t()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:t,timeoutID:i,rafID:r,ricID:n,onVisibilitychange:o}=this.taskMap.get(e);return t&&clearInterval(t),i&&clearTimeout(i),r&&mN(r),n&&pN(n),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.taskMap.has(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};_N.taskMap=new Map,_N.currentTaskID=1;var fN=_N;RR(zR(),1);var gN="connection-state-changed",vN={LOADED_DATA:UA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed"};RR(zR(),1),RR(zR(),1);var TN=new class{constructor(){this._roomIdMap=new Map,"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:eA,env:mA,browserVersion:Zk.name+Zk.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){Xk||!ZP.isAbleToUpload||this._configs.env===mA&&this.uploadEventToKibana(ER(yR({},e),{result:"success"}))}logFailedEvent(e){if(Xk||!ZP.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)||aD.UNKNOWN};this._configs.env===mA&&this.uploadEventToKibana(ER(yR({},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:Fb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:eA,log:t};r&&(n.errorInfo=r.message),this.sendRequest(eP(this._configs.sdkAppId,hA),n)}sendRequest(e,t){ZP.isAbleToUpload?zP({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},SN="trtc_autoplay",yN="".concat(SN,"_mask"),EN="".concat(SN,"_wrapper"),IN="".concat(SN,"_header"),CN="".concat(SN,"_content"),RN="".concat(SN,"_action_wrapper"),AN="".concat(SN,"_question"),bN="".concat(SN,"_collapse"),kN="".concat(SN,"_action_confirm"),wN="".concat(SN,"_detail"),PN="#2473E8",DN="dialog",NN="".concat(DN,"-show"),ON="".concat(DN,"-1"),MN="".concat(DN,"-2"),LN=!1,xN=()=>!!document.querySelector(".".concat(EN)),VN="".concat(dA,"/").concat(hP()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),UN="<br><a href='".concat(VN,"' target='_blank'>").concat(hP()?"其他方案?":"Any other solution?","</a>"),FN="".concat(hP()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(UN):"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(UN)),BN=class{constructor(){if(bR(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),bR(this,"_dialogNode",null),bR(this,"_bodyPosition",""),bR(this,"_showDetail",!1),bR(this,"_isCollapseClicked",!1),bR(this,"_isQuestionClicked",!1),hP()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!LN){let e=document.createElement("style");e.innerHTML=".".concat(yN,"{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(yN," div:not(.").concat(RN,"){display:block !important;}.").concat(EN,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(EN," a{color:").concat(PN,";}.").concat(IN,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(CN,"{margin:8px 0;}.").concat(RN,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(bN,"{margin-right:auto;cursor:pointer}.").concat(AN,"{height:100%;line-height:16px;cursor:pointer;}.").concat(kN,"{margin-left:8px;color:#fff;background:").concat(PN,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(kN,":hover{opacity:0.9;}.").concat(bN,",.").concat(kN,",.").concat(CN,",.").concat(AN,"{font-size:14px;}@media screen and (max-width:750px){.").concat(EN,"{width:80vw;}}"),document.head.appendChild(e),LN=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(yN,"\"><div class='").concat(EN,"'><div class='").concat(IN,"'>").concat(location.host,"</div><div class='").concat(CN,"'>").concat(this.content,"</div><div class='").concat(wN,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(FN,"</div><div class='").concat(RN,"'></div></div></div>").trim();let t=document.createElement("button");t.className=kN,t.innerText=hP()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=AN,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=bN,r.innerText="".concat(hP()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(RN));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){xN()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(EN)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",ZP.info("show autoplay dialog"),TN.uploadEvent({log:NN}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){ZP.warn("confirm clicked, try resume stream"),qP.emit(XP.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(wN));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||TN.uploadEvent({log:ON}),this._isCollapseClicked=!0}onQuestionClick(){window.open(VN,"_blank"),this._isQuestionClicked||TN.uploadEvent({log:MN}),this._isQuestionClicked=!0}},jN={};CR(jN,{create:()=>GN,remove:()=>WN}),RR(zR(),1);var HN=new WeakMap;function GN(e,t){HN.has(e)||HN.set(e,[]);let i=HN.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 WN(e){let t=HN.get(e);t&&(t.forEach((e=>e())),HN.delete(e))}var JN=class extends uN{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,bR(this,"id"),bR(this,"element",null),bR(this,"container",null),bR(this,"mediaStream",new MediaStream),bR(this,"track"),bR(this,"url"),bR(this,"attr"),bR(this,"muted"),bR(this,"_log"),bR(this,"_pausedRetryCount"),bR(this,"_isElementPlayingFired",!1),bR(this,"_interval"),this.id=e.id,this._log=e.log,this.track=e.track,this.container=e.container,this.muted=e.muted,this._pausedRetryCount=5,this._state="STOPPED",this.bindTrackEvents()}get isPlaying(){return"PLAYING"===this._state}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setTrack(e){if(e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(vN.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element))){let t=new MediaStream;t.addTrack(e),this.element.srcObject=t}}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))}setContainer(e){this.container=e,this.track&&this.element&&this.container&&this.container.appendChild(this.element)}play(){return wR(this,null,(function*(){if(this.element&&this.element.parentElement!==this.container&&this.container&&this.container.append(this.element),!this.isPlaying)try{this.bindAutoPlayEvent(),yield this.element.play()}catch(e){let t=Xw({key:ww,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw new cD({code:aD.PLAY_NOT_ALLOWED,message:t})}}))}stop(){this.unbindEvents(),this._isElementPlayingFired=!1,this.element&&(this.container&&this.container.removeChild(this.element),this.element.srcObject=null,this.element=null),this.handleStopped(MA),this._interval>0&&fN.clearTask(this._interval)}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this.isPlaying?Promise.resolve():Yk?this.replay():this.play().catch((()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}setRect(e,t){this.element&&(this.element.style.width="".concat(e,"px"),this.element.style.height="".concat(t,"px"))}replay(){return this.stop(),this.play().catch((()=>{}))}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);GN(this.element,this.element).add(LA,e).add(MA,e).add(xA,e).add(VA,e).add(UA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==jN||jN.create(this.track,this.track).add(MA,e).add(NA,e).add(OA,e),this.track.readyState===MA&&this.handleTrackEvent({type:MA}),this.track.muted&&this.handleTrackEvent({type:NA})}}bindAutoPlayEvent(){qP.on(XP.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&WN(this.track)}unbindEvents(){this.element&&WN(this.element),this.unbindTrackEvents(),qP.off(XP.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){var t;switch(e.type){case LA:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(LA),this._interval&&(fN.clearTask(this._interval),this._interval=-1);break;case MA:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(MA);break;case xA:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(xA);let e=this.container&&document.getElementById(this.container.id);e||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id));let i=Bk();this._pausedRetryCount>0&&(this.kind===CA&&!xN()||this.kind===IA&&(SP(i)&&i<=70||!e))&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--),Yb&&(this._interval=fN.run(xb,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case VA:if(this.element&&this.element.error){let{code:e,message:t}=this.element.error;this._log.error("".concat(this.kind," player error observed. code: ").concat(e," message: ").concat(t," userAgent: ").concat(navigator.userAgent)),TN.uploadEvent({log:"stat-".concat(this.kind,"-").concat(pb,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error})}break;case UA:this.kind===CA&&this.emit(vN.LOADED_DATA)}}handleTrackEvent(e){switch(e.type){case MA:this._log.info("".concat(this.kind," track is ended")),this.handleStopped(MA);break;case NA:this._log.info("".concat(this.kind," track is unable to provide media output")),this.handlePaused(NA);break;case OA:this._log.info("".concat(this.kind," track is able to provide media output")),this._isElementPlayingFired&&this.handlePlaying(OA)}}handlePlaying(e){this.emit(vN.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(vN.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(vN.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};AR([oN([],"PLAYING")],JN.prototype,"handlePlaying",1),AR([oN("PLAYING","PAUSED",{ignoreError:!0})],JN.prototype,"handlePaused",1),AR([oN([],"STOPPED")],JN.prototype,"handleStopped",1);var zN=class extends JN{constructor(e){super(e,CA),bR(this,"mirror"),bR(this,"objectFit"),vP(e.mirror)||(this.mirror=e.mirror),vP(e.objectFit)||(this.objectFit=e.objectFit)}initializeElement(){var e;let t=document.createElement(CA);if(this.track){let e=new MediaStream;e.addTrack(this.track),t.srcObject=e}t.muted=!0;let i="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");this.mirror&&(i+="transform: scaleX(-1);"),t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",i),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),null==(e=this.container)||e.appendChild(t),this.element=t,this.bindElementEvents()}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)}setMirror(e){this.element&&(this.element.style.transform=e?"scaleX(-1)":""),this.mirror=e}setObjectFit(e){this.element&&(this.element.style.objectFit="".concat(e)),this.objectFit=e}play(){return this.element||this.initializeElement(),super.play()}getVideoFrame(){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}};RR(zR(),1),RR(zR(),1),RR(zR(),1);var KN=!1,qN=class{constructor(e){bR(this,"context_"),bR(this,"blob_"),this.context_=e.context,this.blob_=new Blob(["class VolumeMeter extends AudioWorkletProcessor{constructor(){super();this.volume=0;this.intervalTime=200;this.tick=this.intervalTime;this.isStop=false;this.port.onmessage=event=>{const{data}=event;switch(data.name){case'setIntervalTime':this.intervalTime=data.intervalTime;break;case'stop':this.isStop=true;break}}}process(inputs){const input=inputs[0];if(this.isStop){return false}if(input.length>0){const firstChannel=input[0];let sum=0;let rms;for(let i=0;i<firstChannel.length;++i){sum+=firstChannel[i]*firstChannel[i]}rms=Math.sqrt(sum/firstChannel.length);this.volume=Math.max(rms,this.volume*0.95);this.tick-=firstChannel.length;if(this.tick<0){this.tick+=(this.intervalTime/1000)*sampleRate;this.port.postMessage({volume:this.volume})}}return true}}registerProcessor('volume-meter',VolumeMeter);"],{type:"application/javascript"}),this.addModuleToContext()}addModuleToContext(){return wR(this,null,(function*(){try{yield this.context_.audioWorklet.addModule(URL.createObjectURL(this.blob_)),ZP.info("worklet addModule success"),qP.emit(XP.WORKLET_LOADED_SUCCESS),KN=!0}catch(KO){ZP.info("worklet addModule catch error. ".concat(KO.message)),qP.emit(XP.WORKLET_LOADED_FAILED)}}))}get initWorkletSuccess(){return KN}};RR(zR(),1),"undefined"!=typeof window&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var QN,YN,XN=()=>{let e=new window.AudioContext,t=()=>{"suspended"===e.state?(e.resume(),document.addEventListener("click",t)):"interrupted"===e.state?e.resume():document.removeEventListener("click",t)};return document.addEventListener("click",t),e.onstatechange=()=>{ZP.info("audioSource context state: ".concat(e.state)),t()},e},$N=0,ZN=class{constructor(e){bR(this,"_volume"),bR(this,"_log"),bR(this,"_track"),bR(this,"_stream"),bR(this,"_audioCtx"),bR(this,"_destination"),bR(this,"_streamSource"),bR(this,"_scriptProcessorNode"),bR(this,"_audioWorkletNode"),bR(this,"_interval");let{track:t,log:i}=e;this._volume=0,this._log=i,this._track=t,QN||(QN=XN()),this._audioCtx=QN,this._destination=this._audioCtx.destination;let r=new MediaStream;r.addTrack(this._track),this._streamSource=this._audioCtx.createMediaStreamSource(r),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._interval=200,qP.on(XP.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),wP?(qP.on(XP.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),qP.on(XP.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),this.preload()):this.initScriptProcessor(),$N+=1}preload(){YN?YN.initWorkletSuccess&&this.initAudioWorklet():YN=new qN({context:QN})}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(this._audioCtx,"volume-meter"),this._audioWorkletNode.port.onmessage=e=>{this._volume=e.data.volume||0},this._streamSource.connect(this._audioWorkletNode).connect(this._destination),this.handleAudioLevelInterval({interval:this._interval})}catch(KO){TN.logFailedEvent({userId:this._log.userId,eventType:mb,error:KO}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=this._audioCtx.createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{let t=e.inputBuffer.getChannelData(0),i=0;for(let r=0;r<t.length;++r)i+=t[r]*t[r];this._volume=Math.sqrt(i/t.length)||0},this._streamSource.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._destination)}catch(KO){this._log.error("volumeMeter init script processor error: ".concat(KO))}}destroy(){this._streamSource&&this._streamSource.disconnect(),this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null,this._scriptProcessorNode.disconnect()),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null,this._audioWorkletNode.disconnect()),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._audioCtx=null,qP.off(XP.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),qP.off(XP.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),qP.off(XP.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),$N>0&&($N-=1),0===$N&&(null==QN||QN.close(),QN=null,YN=null)}resume(){null==QN||QN.resume()}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(e){var t;let{interval:i}=e;this._interval=i,null==(t=this._audioWorkletNode)||t.port.postMessage({name:"setIntervalTime",intervalTime:i})}},eO=class extends JN{constructor(e){super(e,IA),bR(this,"_volumeMeter"),bR(this,"gainedTrack"),bR(this,"_outputDeviceId"),bR(this,"_volume",1),bR(this,"_loop",!1),e.gainedTrack&&(this.gainedTrack=e.gainedTrack),this._outputDeviceId=e.outputDeviceId,this.track&&this.initVolumeMeter(this.track)}setTrack(e){this.track!==e&&(this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),null!==e&&this.initVolumeMeter(e)),super.setTrack(e)}initVolumeMeter(e){this._volumeMeter=new ZN({track:this.gainedTrack||e,log:this._log})}initializeElement(){if(("15.2"===qk||"15.3"===qk||"15.4"===qk)&&this.muted)return void this._log.info("audioElement is muted.");let e=document.createElement(IA);if(this.gainedTrack||this.track){let t=new MediaStream;t.addTrack(this.gainedTrack||this.track),e.srcObject=t}e.muted=this.muted,e.setAttribute("id","audio_".concat(this.id)),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,this.bindElementEvents()}play(){return wR(this,null,(function*(){this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),!this._volumeMeter&&this.track&&this.initVolumeMeter(this.track),this.setVolume(this._volume),yield kR(eO.prototype,this,"play").call(this)}))}stop(){this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),super.stop()}resume(){return wR(this,null,(function*(){yield kR(eO.prototype,this,"resume").call(this),this._volumeMeter&&this._volumeMeter.resume()}))}setSinkId(e){return wR(this,null,(function*(){this._outputDeviceId!==e&&(this.element&&(yield this.element.setSinkId(e)),this._outputDeviceId=e)}))}setVolume(e){!this.element||(this.element.volume=e,this._volume=e)}setLoop(e){!this.element||(this.element.loop=e,this._loop=e)}getAudioLevel(){var e;return(null==(e=this._volumeMeter)?void 0:e.getCalculatedVolume())||0}getInternalAudioLevel(){var e;return null==(e=this._volumeMeter)?void 0:e.getInternalAudioLevel()}},tO=class extends uN{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n}=e;var o;super(),bR(this,"id",QD()),bR(this,"userId"),bR(this,"isRemote"),bR(this,"mediaType"),bR(this,"room"),bR(this,"user"),bR(this,"_log"),bR(this,"isPlayCalled"),bR(this,"mediaTrack",null),bR(this,"mediaStream"),bR(this,"container",null),bR(this,"subVideoPlayerMap"),bR(this,"playerMuted",!1),bR(this,"abortCtrl"),bR(this,"audioOutputDeviceId"),bR(this,"audioVolume"),bR(this,"objectFit","cover"),bR(this,"mirror",!1),bR(this,"gain"),bR(this,"isScreen",!1),vP(t)||(this.userId=t),this.mediaType=r,this._log=ZP.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(o=n||this.room)?void 0:o.userId,remoteUserId:this instanceof EO?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof EO}),this.initPlayer()}get log(){return this._log||ZP}get kind(){return 1===this.mediaType?IA:CA}get muted(){return!(!this.mediaTrack||this.mediaTrack.enabled)}get strMediaType(){return 4===this.mediaType?CA:2===this.mediaType?RA:IA}uninstallEvents(){}play(e,t){return wR(this,null,(function*(){let i=IP(e)?e[0]:e;if(this.isPlayCalled)return t&&!vP(t.muted)&&this.setPlayerMute(t.muted),t&&!vP(t.objectFit)&&(this.objectFit=t.objectFit),this.isScreen?this.mirror=!1:t&&!vP(t.mirror)&&(this.mirror=t.mirror),void(this.kind===CA&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),IP(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if((!this.isRemote||this.kind===CA)&&this.setPlayerMute(!0),t&&!vP(t.muted)&&this.setPlayerMute(t.muted),t&&!vP(t.objectFit)&&(this.objectFit=t.objectFit),this.isRemote||(this.mirror=!0),this.isScreen?this.mirror=!1:t&&!vP(t.mirror)&&(this.mirror=t.mirror),this.kind===CA&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror)),this.isPlayCalled=!0,i&&(this.container=i,this.player.setContainer(i)),qP.emit(XP.PLAY_TRACK_START,{track:this}),this.mediaTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{yield this.player.play(),IP(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(r){throw this.handleAutoPlayFailed(),this.emit("error",r),r}}}))}playSubContainer(e,t){return wR(this,null,(function*(){if(!this.mediaTrack||this.kind===IA)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,i)=>{var r;e.find((e=>i===e))||(t.stop(),t.setContainer(null),null==(r=this.subVideoPlayerMap)||r.delete(i))}));for(let[r,n]of e.entries()){let e=this.subVideoPlayerMap.get(n);e?t&&(vP(t.mirror)||e.setMirror(t.mirror),vP(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new zN({id:this.userId||this.id,track:this.mediaTrack,container:n,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log.createChild({id:"vp-sub".concat(r+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let e of i)yield e.play()}))}initPlayer(){var e;this.log.info("create ".concat(this.kind,"Player")),this.kind===IA?this.player=new eO({id:this.userId||this.id,track:this.mediaTrack,gainedTrack:null==(e=this.gain)?void 0:e.audioTrack,container:this.container||null,muted:this.playerMuted,outputDeviceId:this.audioOutputDeviceId,log:this.log}):(this.player=new zN({id:this.userId||this.id,track:this.mediaTrack,container:this.container||null,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log}),this.player.on(vN.LOADED_DATA,(()=>{qP.emit(XP.VIDEO_LOADED_DATA,{track:this})})),this.player.on(vN.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))}))),this.player.on(vN.PLAYER_STATE_CHANGED,(e=>{qP.emit(XP.PLAYER_STATE_CHANGED,yR({track:this},e)),this.emit("player-state-changed",e)}))}setAudioOutput(e){return wR(this,null,(function*(){var t;this.audioOutputDeviceId=e,yield null==(t=this.player)?void 0:t.setSinkId(e)}))}setAudioVolume(e){var t;this.audioVolume=e,this.log.info("setAudioVolume to ".concat(e)),null==(t=this.player)||t.setVolume(e)}getAudioLevel(){var e;return(null==(e=this.player)?void 0:e.getAudioLevel())||0}getInternalAudioLevel(){var e;return(null==(e=this.player)?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(),this.player.setContainer(null)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop(),e.setContainer(null)})),this.container=null)}resume(){return wR(this,null,(function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume())}))}close(){var e;this.log.info("close"),this.isPlayCalled&&this.stop(),!this.isRemote&&(null==(e=this.mediaTrack)||e.stop(),this.mediaTrack=null,this.uninstallEvents())}setMute(e){return!!this.mediaTrack&&(this.mediaTrack.enabled=!e,this.emit(e?"mute":"unmute",this),qP.emit(e?XP.TRACK_MUTED:XP.TRACK_UNMUTED,{track:this}),!0)}setPlayerMute(e){this.playerMuted=e,this.player.setMuted(e)}setMediaStream(e){e!==this.mediaStream&&(this.mediaStream=e)}setMediaStreamTrack(e){this.mediaStream||(this.mediaStream=new MediaStream),this.mediaTrack&&this.mediaStream.removeTrack(this.mediaTrack);let t=this.mediaTrack;this.mediaTrack=e,this.mediaTrack&&(this.mediaTrack.enabled=!this.muted,this.mediaStream.addTrack(this.mediaTrack),this.isRemote||this.player.setTrack(this.mediaTrack)),this.updatePlayingState(!!e),this.emit("media-track-changed",this.mediaTrack,t)}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(!(!this.isPlayCalled||e&&!this.player.isStopped||!e&&this.player.isStopped)&&this.isPlayCalled&&this.player.isStopped===e){if(this.log.info("playing state updated, ".concat(e?"play":"stop"," ").concat(this.kind)),e&&this.player.isStopped){if(this instanceof DO&&(!this.isSubscribed||!this.hasFlag))return;this.player.play().catch((()=>this.handleAutoPlayFailed()))}!e&&!this.player.isStopped&&this.player.stop()}}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new BN;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0),document.removeEventListener("touchstart",e,!0)}))};document.addEventListener("click",e,!0),document.addEventListener("touchstart",e,!0)}}};AR([oN([],uN.INIT)],tO.prototype,"close",1),RR(zR(),1),RR(zR(),1);var iO=Object.prototype.hasOwnProperty;var rO=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(pP(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(iO.call(e,t))return!1;return!0}return!1};RR(zR(),1);var nO=RR(KR(),1),oO=e=>t=>t.deviceId===e,aO=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";bR(this,"kind"),bR(this,"type"),bR(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())));t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(oO(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");ZP.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(oO(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");ZP.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},sO=class extends nO.EventEmitter{constructor(){super(),bR(this,"audioInputs",new aO(IA)),bR(this,"videoInputs",new aO(CA)),bR(this,"audioOutputs",new aO(IA,"Output")),this.init(),navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",this.update.bind(this))}init(){lO().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return wR(this,null,(function*(){let e=yield lO();return this.audioInputs.update(e,this),this.videoInputs.update(e,this),this.audioOutputs.update(e,this),this}))}},cO=rA||iA?null:new sO;function lO(){return wR(this,null,(function*(){return fD()||!mD()?[]:(yield navigator.mediaDevices.enumerateDevices()).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&&pO.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}))}function dO(){return cO.update().then((e=>e.audioInputs.devices))}function uO(){return cO.update().then((e=>e.videoInputs.devices))}function hO(){return wR(this,null,(function*(){return cO.update().then((e=>e.audioOutputs.devices))}))}var pO=new Set;function mO(e,t){return wR(this,null,(function*(){let i=(yield dO()).find((e=>e.deviceId===Pb));return(null==i?void 0:i.groupId)===e&&i.label===t}))}var _O=KP({retryFunction:function(e){return wR(this,null,(function*(){let t,i,r=function(e){return{audio:fO(e),video:gO(e)}}(e);ZP.info("getUserMedia with constraints: ".concat(JSON.stringify(r))),r.audio&&(t=yield dO(),ZP.info("microphones: ".concat(JSON.stringify(t)))),r.video&&(i=yield uO(),ZP.info("cameras: ".concat(JSON.stringify(i))));try{let e=yield navigator.mediaDevices.getUserMedia(r);return HD&&e.getTracks().forEach((e=>{ZP.info("".concat(e.kind," settings: ").concat(JSON.stringify((null==e?void 0:e.getSettings())||{}),"\r\ncapabilities: ").concat(JSON.stringify(e.getCapabilities())))})),e}catch(n){if("NotFoundError"===n.name){if(i&&0===i.length)throw new cD({code:aD.DEVICE_NOT_FOUND,message:Xw({key:Lw})});if(t&&0===t.length)throw new cD({code:aD.DEVICE_NOT_FOUND,message:Xw({key:Mw})})}throw new cD({code:aD.INITIALIZE_FAILED,name:n.name,message:n.message,constraint:n.constraint})}}))},settings:{retries:3,timeout:500},onError:(e,t,i,r)=>{"NotReadableError"===e.name?(r[0].video&&(r[0].maxResolution=!1,r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)),t()):i(e)},onRetrying:e=>{ZP.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))}});function fO(e){if(!e.audio)return!1;let t={};return rO(e.microphoneId)||(t.deviceId=e.useExact?{exact:e.microphoneId}:e.microphoneId),SP(e.channelCount)&&e.channelCount>1&&(t.channelCount=e.channelCount),yP(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),yP(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),yP(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!rO(t)||t}function gO(e){if(!e.video)return!1;let{maxResolution:t=!0}=e,i={};return e.cameraId?i.deviceId=e.useExact?{exact:e.cameraId}:e.cameraId:e.facingMode&&(i.facingMode=e.facingMode),e.width&&(i.width={ideal:e.width},t&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&(i.height.max=e.height)),$b&&bk&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!rO(i)||i}var vO=_O;function TO(e){return yO(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return wR(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function SO(e){return yO(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return wR(this,null,(function*(){return e.call(this,t.apply(this,r))}))}))}function yO(e){return function(t,i,r){return r.value=e(r.value,i),r}}RR(zR(),1);var EO=class extends tO{constructor(e){super({mediaType:e}),bR(this,"isRemote",!1),bR(this,"deviceId"),bR(this,"groupId",""),bR(this,"label",""),bR(this,"_isRecapturing",!1),bR(this,"_lastRecaptureTime",0),bR(this,"_onMuteTimeoutId",-1),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}installTrackEvent(e){e.addEventListener(NA,this.onTrackMuted),e.addEventListener(OA,this.onTrackUnmuted),e.addEventListener(MA,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===MA&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(NA,this.onTrackMuted),e.removeEventListener(OA,this.onTrackUnmuted),e.removeEventListener(MA,this.onTrackEnded)}setStateToCapture(){}capture(e){return wR(this,null,(function*(){try{let t;qP.emit(XP.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(t=new MediaStream,t.addTrack(e.customSource)):t=yield vO(e);let i=t.getTracks()[0];return this.setMediaStream(t),this.setMediaStreamTrack(i),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),qP.emit(XP.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this}),t}catch(t){throw qP.emit(XP.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:t}),this.log.error("getUserMedia error observed ".concat(t)),t}}))}setMediaStreamTrack(e){this.state===uN.INIT&&this.setStateToCapture(),this.mediaTrack&&this.uninstallTrackEvent(this.mediaTrack),super.setMediaStreamTrack(e),e&&this.installTrackEvent(e)}setPublishStarting(e){this.room=e}setPublishStarted(){}setPublishStopped(e,t){}publish(e){this.room=e,this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),qP.emit(XP.LOCAL_TRACK_PUBLISHED,{track:this}),this.setPublishStarted()}unpublish(){this.room=void 0,2===this.mediaType&&(this.mediaType=4),qP.emit(XP.LOCAL_TRACK_UNPUBLISHED,{track:this}),this.setPublishStopped("api-call")}get isPublishing(){return"publish"===this.state}updateDeviceIdInUse(){return wR(this,null,(function*(){if(this.mediaTrack&&jD){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return wR(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==IA||t!==Pb||(yield mO(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),lO().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===IA&&!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(FA);return!!pO.has(i)}(this.mediaTrack)||this.kind===CA&&!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(BA);return!!pO.has(i)}(this.mediaTrack)||this._isRecapturing||e&&bk&&zk)}onTrackMuted(){if(this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Ob)return void setTimeout((()=>this.onTrackMuted()),Ob);this._onMuteTimeoutId=setTimeout((()=>wR(this,null,(function*(){var e;(null==(e=this.mediaTrack)?void 0:e.muted)&&"visible"===document.visibilityState&&this.recapture(yield this.getRecoverCaptureDeviceId())}))),5e3)}}onTrackUnmuted(){this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return wR(this,null,(function*(){if(this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Ob)return void setTimeout((()=>this.onTrackEnded()),Ob);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return wR(this,null,(function*(){var t;if(this._isRecapturing||!this.mediaTrack)return;let i;return this.log.warn("recapture trying"),null==(t=this.mediaTrack)||t.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now(),("audio"===this.kind?yield dO():yield uO()).find((t=>t.deviceId===e))&&(i=e),this.capture({deviceId:i,useExact:!0}).then((()=>{var e;return null==(e=this.room)?void 0:e.replaceTrack(this)})).then((()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e)}))}))}getRecoverCaptureDeviceId(){return wR(this,null,(function*(){let{deviceId:e}=this;if(e){let t=(IO.get(e)||0)+1;if(IO.set(e,t),t>=3){let i="video"===this.kind?(yield uO()).find((e=>!IO.has(e.deviceId))):(yield dO()).find((e=>!IO.has(e.deviceId)));i&&(this.log.warn("".concat(e," capture fail ").concat(t," times, change new ").concat(i.deviceId)),e=i.deviceId)}}return e}))}};AR([oN(uN.INIT,"capture")],EO.prototype,"setStateToCapture",1),AR([oN("capture","publish_starting",{success(){this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"})}})],EO.prototype,"setPublishStarting",1),AR([oN("publish_starting","publish",{success(){this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})}})],EO.prototype,"setPublishStarted",1),AR([yO((e=>function(t,i){let r=this.state.oldState||this.state;e.call(this,t,i),"capture"!==r&&this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"publish_starting"===this.state.oldState?"starting":"started",reason:t,error:i})})),oN(["publish","publish_starting"],"capture",{ignoreError:!0})],EO.prototype,"setPublishStopped",1);var IO=new Map;qP.on(XP.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&IO.delete(e.track.deviceId)})),RR(zR(),1);var CO=class extends EO{constructor(){super(1),bR(this,"mediaType",1),bR(this,"volume",0),bR(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),bR(this,"playerMuted",!0)}getAudioLevel(){return this.volume||super.getAudioLevel()}capture(){let{deviceId:e,useExact:t=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExact:t})}switchDevice(e){return wR(this,null,(function*(){if(this.mediaStream&&this.mediaTrack){if(this.deviceId===e){if(e!==Pb)return;if(yield mO(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExact:!0}),this.room&&(yield this.room.replaceTrack(this)),qP.emit(XP.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error("switch microphone failed ".concat(t)),this.deviceId&&this.recapture(this.deviceId),t}}}))}listenDeviceChange(){cO&&!cO.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&cO.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return wR(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e)));let t=yield dO();t[0]?this.recapture(t[0].deviceId):cO.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){return wR(this,null,(function*(){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}close(){cO.off("audioInputAdded",this.handleMicrophoneAdded,this),cO.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}};RR(zR(),1);var RO=class extends EO{constructor(){super(4),bR(this,"mediaType",4),bR(this,"profile",{width:640,height:480,frameRate:15,bitrate:900}),bR(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0}),bR(this,"small"),bR(this,"facingMode"),bR(this,"_canvas"),bR(this,"_canvasInterval"),bR(this,"canvasTrack")}capture(){let{deviceId:e,facingMode:t,useExact:i=!1,customSource:r}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExact:i,customSource:r})}genCanvasTrack(){if(this.canvasTrack||!this.mediaTrack)return;this.log.info("gen canvas track");let{width:e,height:t,frameRate:i}=this.mediaTrack.getSettings();this._canvas=document.createElement("canvas");let r=this._canvas.getContext("2d");e&&t&&(this._canvas.width=e,this._canvas.height=t),this._canvasInterval=fN.run(Lb,(()=>{if(!this._canvas)return;if(this.mediaTrack){let e=this.mediaTrack.getSettings();(e.width!==this._canvas.width||e.height!==this._canvas.height)&&(this._canvas.width=e.width,this._canvas.height=e.height)}let e=this.player.getElement();e&&(null==r||r.drawImage(e,0,0,this._canvas.width,this._canvas.height))}),{fps:Math.max(15,i||0)});let n=this._canvas.captureStream();this.canvasTrack=n.getVideoTracks()[0]}destoryCanvasTrack(){this._canvasInterval&&(fN.clearTask(this._canvasInterval),this._canvasInterval=void 0,this._canvas=void 0,this.canvasTrack=void 0)}setPublishStarting(e){super.setPublishStarting(e),this.isNeedToResetVideoProfile(this.profile)&&this.setProfile(this.profile)}setMediaStreamTrack(e){super.setMediaStreamTrack(e),this.isNeedToResetVideoProfile(this.profile)&&this.setProfile(this.profile)}setProfile(e){var t;if(!e)return;let i=e.bitrate&&e.bitrate!==this.profile.bitrate;return this.isNeedToResetVideoProfile(e)&&(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),e.width=1920,e.height=1080),super.setProfile(e),null==(t=this.mediaTrack)?void 0:t.applyConstraints({width:e.width,height:e.height,frameRate:e.frameRate}).then((()=>{if(i&&this.room&&this.room.setBandWidth)return this.room.setBandWidth({bandwidth:e.bitrate,type:CA,videoType:bA})}))}isNeedToResetVideoProfile(e){return!!(this.room&&this.room.scheduleResult&&1!==(this.room.scheduleResult.trtcAutoConf||{})["2k4k"]&&!this.isScreen&&e.height*e.width>=3686400)}switchDevice(e){return wR(this,null,(function*(){try{if(!this.mediaStream||this.deviceId===e||this.facingMode===e)return;(e===PA||e===DA)&&(this.facingMode=e,e=void 0),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExact:!0}),this.room&&(yield this.room.replaceTrack(this)),qP.emit(XP.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error("switch camera failed ".concat(t)),this.deviceId&&this.recapture(this.deviceId),t}}))}listenDeviceChange(){cO&&!cO.listeners("audioInputRemoved").includes(this.handleCameraRemoved)&&cO.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return wR(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e)));let t=yield uO();t[0]?this.recapture(t[0].deviceId):cO.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return wR(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}close(){cO.off("videoInputAdded",this.handleCameraAdded,this),cO.off("videoInputRemoved",this.handleCameraRemoved,this),this.destoryCanvasTrack(),super.close()}};RR(zR(),1),RR(zR(),1);var AO=function(e){return wR(this,null,(function*(){let t=null,i=function(e){let t={systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:zk?{max:e.width}:{ideal:e.width,max:e.width},height:zk?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:"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);ZP.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);if(e.systemAudio&&0===r.getAudioTracks().length&&(Hk&&Wk<74||zk||$b)&&ZP.warn("Your browser not support capture system audio"),e.frameRate&&r.getVideoTracks()[0]&&r.getVideoTracks()[0].applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate}}).catch((e=>{ZP.warn("screen applyConstraints failed: ".concat(e))})),e.audio){let i=function(e){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return vP(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);ZP.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},bO=class extends RO{constructor(){super(),bR(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),bR(this,"objectFit","contain"),bR(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(){return wR(this,arguments,(function(){var e=this;let{systemAudio:t=!1,autoGainControl:i,echoCancellation:r,noiseSuppression:n,audioTrack:o,videoTrack:a}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){try{let s;return a||o?(s=new MediaStream,a&&s.addTrack(a),o&&s.addTrack(o)):s=yield AO({audio:!1,systemAudio:t,width:e.profile.width,height:e.profile.height,frameRate:e.profile.frameRate,autoGainControl:i,echoCancellation:r,noiseSuppression:n}),e.setMediaStream(s),e.setMediaStreamTrack(s.getVideoTracks()[0]),s}catch(s){throw e.log.error("getDisplayMedia error observed ".concat(s)),s instanceof cD?s:new cD({code:aD.INITIALIZE_FAILED,name:s.name,message:s.message})}}()}))}switchDevice(e){return wR(this,null,(function*(){throw new Error("Method not implemented.")}))}};RR(zR(),1);var kO=class extends CO{constructor(){super(),this._log.id="s-".concat(this._log.id)}setScreenAudioTrack(e,t){this.setMediaStream(t),this.setMediaStreamTrack(e)}};RR(zR(),1),RR(zR(),1);var wO=class extends EO{constructor(e){super(1),bR(this,"musicId"),bR(this,"mediaType",1),bR(this,"volume",0),bR(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),bR(this,"playerMuted",!1),bR(this,"_audioContext"),bR(this,"_destination"),bR(this,"_source",null),this.initAudioContext(),this._destination=this._audioContext.createMediaStreamDestination(),this._destination.channelCount=1,this.setPlayerMute(!1),this.player.initializeElement(),this.player.setUrl(e.url),yP(e.loop)&&this.player.setLoop(e.loop),SP(e.volume)&&this.player.setVolume(e.volume),e.id&&(this.musicId=e.id),this._source=this._audioContext.createMediaElementSource(this.player.getElement()),this._source.connect(this._destination),this.setMediaStream(this._destination.stream)}initAudioContext(){this._audioContext=XN(),"running"!==this._audioContext.state&&this._log.warn("local music ".concat(this.musicId," context state: ").concat(this._audioContext.state))}destroy(){var e,t;null==(e=this._source)||e.disconnect(),null==(t=this._destination)||t.disconnect(),this.player.stop(),this._audioContext.close().then((()=>{this._source=null,this._destination=null,this._audioContext=null}))}getStream(){var e;return(null==(e=this._destination)?void 0:e.stream)||null}setPosition(e){e<0&&e>this.duration()?ZP.warn("Time beyond song duration."):this.player&&this.player.getElement()&&(this.player.getElement().currentTime=e)}getPosition(){var e;if(this.player)return(null==(e=this.player.getElement())?void 0:e.currentTime)||0}setVolume(e){e>1&&e<0?this.log.warn("volume is out of range"):this.player.setVolume(e)}getVolume(){let e=this.player.getElement();return(null==e?void 0:e.volume)||0}setPlayBackRate(e){if(e>8&&e<0)return void this.log.warn("rate is out of range");let t=this.player.getElement();t&&(t.playbackRate=e)}getPlayBackRate(){let e=this.player.getElement();return(null==e?void 0:e.playbackRate)||0}duration(){let e=this.player.getElement();return(null==e?void 0:e.duration)||0}loop(e){let t=this.player.getElement();return t&&yP(e)&&(t.loop=e),(null==t?void 0:t.loop)||!1}setOperation(e){"pause"===e&&this.player.pause(),"resume"===e&&this.player.resume(),"stop"===e&&this.player.stop()}listenDeviceChange(){}};RR(zR(),1),RR(zR(),1);var PO=class extends tO{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,bR(this,"userId"),bR(this,"tinyId"),bR(this,"isRemote",!0),this.tinyId=t.tinyId,this.userId=t.userId}play(e,t){return this.hasFlag?super.play(e,t):(this.isPlayCalled=!0,this.container=e,e&&this.player.setContainer(e),Promise.resolve())}setMute(e){return this.hasFlag&&super.setMute(e)}setMediaStreamTrack(e){super.setMediaStreamTrack(e),this.mediaTrack&&this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.mediaTrack)}get isSubscribed(){return this.state===PO.STATE_SUBSCRIBE}get streamType(){return 0==(2&this.mediaType)?"main":"auxiliary"}subscribe(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.mediaTrack&&this.hasFlag&&this.player.setTrack(this.mediaTrack),e&&qP.emit(XP.REMOTE_TRACK_SUBSCRIBED,{track:this})}unsubscribe(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.player.setTrack(null),e&&qP.emit(XP.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}onFlagChanged(){this.updatePlayingState(this.hasFlag),this.mediaTrack&&this.hasFlag&&this.player.setTrack(this.mediaTrack)}},DO=PO;bR(DO,"STATE_SUBSCRIBE","subscribe"),AR([oN(uN.INIT,DO.STATE_SUBSCRIBE,{success(){this.updatePlayingState(!0)}})],DO.prototype,"subscribe",1),AR([oN(DO.STATE_SUBSCRIBE,uN.INIT,{success(){this.updatePlayingState(!1)}})],DO.prototype,"unsubscribe",1);var NO=class extends DO{constructor(e,t){super(e,t,1),bR(this,"volume",0),bR(this,"mediaType",1),bR(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0})}getAudioLevel(){return this.volume||super.getAudioLevel()}get hasFlag(){return this.user.muteState.hasAudio&&!this.user.muteState.audioMuted}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}};RR(zR(),1);var OO=class extends DO{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),bR(this,"mediaType",4),bR(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0})}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}},MO=class extends OO{constructor(e,t){super(e,t,2),bR(this,"mediaType",2),bR(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function LO(){}RR(zR(),1),RR(zR()),RR(zR());var xO=e=>e(),VO=1,UO=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new GO(e,this,this.streamId++);return WO.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},FO=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=LO,this.error=LO,this.next=LO,this.dispose=LO,this.subscribe=LO,this.doDefer()}subscribe(e){return e instanceof UO?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(xO),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}},BO=class extends FO{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)}};function jO(e,t,i){if("undefined"!=typeof __FASTRX_DEVTOOLS__){let r=Object.defineProperties(Object.setPrototypeOf(e,UO.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}});WO.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof UO&&WO.addSource(r,t)}return r}return e}function HO(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var GO=class extends BO{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{WO.defer(this.source,this.id)}))}next(e){WO.next(this.source,this.id,e),this.sink.next(e)}complete(){WO.complete(this.source,this.id),this.sink.complete()}error(e){WO.complete(this.source,this.id,e),this.sink.error(e)}},WO={addSource(e,t){HO("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){HO("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;HO("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){HO("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){HO("defer",{id:e.id,streamId:t})},pipe(e){HO("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){HO("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=VO++),HO("create",{name:e.toString(),id:e.id})}};RR(zR()),RR(zR());var JO=class extends FO{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()}};RR(zR()),RR(zR()),RR(zR());var zO,KO,qO=(zO=class extends BO{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},KO="map",function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>{if(e instanceof UO){let i=jO((r=>{let n=new zO(r,...t);n.sourceId=i.id,n.subscribe(e)}),KO,arguments);return i.source=e,WO.pipe(i),i}return i=>e(new zO(i,...t))}});RR(zR()),function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];i.reduce(((e,t)=>t(e)),e)}(function(e){return jO((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}(250),qO((()=>performance.now())),function(){return e=>{let t=new JO(e);if(e instanceof UO){let i=jO((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,WO.pipe(i),i}return jO(t.add.bind(t),"share",arguments)}}()),RR(zR(),1);var QO=new Map;function YO(e,t){let i=ER(yR({},t),{timestamp:Ub()});QO.has(e)?QO.get(e).push(i):QO.set(e,[i])}qP.on(XP.JOIN_SUCCESS,(e=>{let{room:t}=e;YO(t.userId,{eventId:32788,eventDesc:"join room"})})),qP.on(XP.LEAVE_START,(e=>{let{room:t}=e;YO(t.userId,{eventId:32789,eventDesc:"leave room"})})),qP.on(XP.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;t.room&&YO(t.room.userId,{eventId:t.kind===IA?32769:32768,eventDesc:"publish ".concat(t.kind)})})),qP.on(XP.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;t.room&&YO(t.room.userId,{eventId:t.kind===IA?32771:32770,eventDesc:"unpublish ".concat(t.kind)})})),qP.on(XP.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===IA?YO(t.room.userId,{eventId:t.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:t.isRemote?t.userId:void 0}):YO(t.room.userId,{eventId:t.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:t.isRemote?t.userId:void 0}))})),qP.on(XP.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===IA?YO(t.room.userId,{eventId:t.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:t.isRemote?t.userId:void 0}):YO(t.room.userId,{eventId:t.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:t.isRemote?t.userId:void 0}))})),qP.on(XP.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;1===t.mediaType&&YO(t.room.userId,{eventId:32777,eventDesc:"".concat(GA," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&YO(t.room.userId,{eventId:32776,eventDesc:"".concat(GA," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&YO(t.room.userId,{eventId:32803,eventDesc:"".concat(GA," ").concat(wA),remoteUserId:t.userId})})),qP.on(XP.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;1===t.mediaType&&YO(t.room.userId,{eventId:32779,eventDesc:"".concat(WA," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&YO(t.room.userId,{eventId:32778,eventDesc:"".concat(WA," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&YO(t.room.userId,{eventId:32804,eventDesc:"".concat(WA," ").concat(wA),remoteUserId:t.userId})})),qP.on(XP.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&YO(t.room.userId,{eventId:t.kind===CA?32780:32781,eventDesc:"switch ".concat(t.kind===CA?"camera":"microphone")})})),qP.on(XP.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&YO(t.room.userId,{eventId:t.kind===CA?32782:32783,eventDesc:"replace ".concat(t.kind)})})),qP.on(XP.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:r,prevState:n,state:o}=e;switch(o){case"CONNECTED":"RECONNECTING"===n?(t=32795,i="signal reconnected"):(t=32791,i="signal connected");break;case"DISCONNECTED":"RECONNECTING"===n?(t=32796,i="signal reconnect fail"):(t=32790,i="signal disconnected");break;case"RECONNECTING":t=32794,i="signal reconnecting"}t&&i&&YO(r.userId,{eventId:t,eventDesc:i})})),qP.on(XP.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:r,prevState:n,state:o,remoteUserId:a}=e,s=!!a,c=s?"downlink":"uplink";switch(o){case"CONNECTED":"RECONNECTING"===n?(t=s?32801:32798,i="".concat(c," reconnected")):(t=s?32793:32792,i="".concat(c," connected"));break;case"DISCONNECTED":"RECONNECTING"===n&&(t=s?32802:32799,i="".concat(c," reconnect fail"));break;case"RECONNECTING":t=s?32800:32797,i="".concat(c," reconnecting")}t&&i&&YO(r.userId,{eventId:t,eventDesc:i,remoteUserId:a})})),RR(zR(),1),RR(zR(),1);var XO=RR(KR(),1),$O=class extends XO.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,bR(this,"userMap",new Map),bR(this,"remotePublishedUserMap",new Map)}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,"]");vP(t)||(r+=":".concat(Nb[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,a=VP(r,n),s=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(s){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:s,muteState:a,flag:r}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(a))),this.addUser({userId:n,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:VP(0,n),muteState:a,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};RR(zR());var ZO={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"};RR(zR()),RR(zR(),1);var eM=class extends Error{};function tM(e,t){let i=[];return HP(i,e),HP(i,t),i}function iM(e){this._resolve=Promise.resolve(e)}function rM(e){this._reject=Promise.reject(e)}var nM=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=tM;let i=nM.instances.get(e);i?i.set(t,this):nM.instances.set(e,new Map([[t,this]]))}static get(e,t){let i=nM.instances.get(e);return i&&i.get(t)||new nM(e,t)}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 eM("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:iM,reject:rM};try{switch(this.state){case 1:if(0===e)throw new eM("already started");break;case 4:if(2===e)throw new eM("not started");break;default:return this.cacheOp(o)}}catch(Wx){return Promise.reject(Wx)}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 eM("already start");break;case 3:switch(e.type){case 2:throw new eM("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new eM("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new eM("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 eM("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new eM("start not allowed after update");case 0:throw new eM("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new eM("keep start")),new eM("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}},oM=nM;oM.instances=new WeakMap,RR(zR()),RR(zR());var aM,sM={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},cM=((aM=cM||{})[aM.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",aM[aM.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",aM[aM.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",aM[aM.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",aM[aM.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",aM[aM.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",aM[aM.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",aM[aM.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",aM[aM.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",aM[aM.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",aM[aM.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",aM[aM.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",aM[aM.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",aM[aM.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",aM[aM.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",aM[aM.MIX_PARAMS_USER_Z_ORDER=5015]="MIX_PARAMS_USER_Z_ORDER",aM[aM.MIX_PARAMS_VIDEO_FRAMERATE=5016]="MIX_PARAMS_VIDEO_FRAMERATE",aM[aM.MIX_PARAMS_VIDEO_GOP=5017]="MIX_PARAMS_VIDEO_GOP",aM[aM.MIX_PARAMS_AUDIO_BITRATE=5018]="MIX_PARAMS_AUDIO_BITRATE",aM[aM.MIX_PARAMS_NOT_SELF=5019]="MIX_PARAMS_NOT_SELF",aM[aM.MIX_PARAMS_USER_STREAM=5020]="MIX_PARAMS_USER_STREAM",aM[aM.INVALID_OPERATION=5100]="INVALID_OPERATION",aM[aM.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",aM[aM.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",aM[aM.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",aM[aM.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",aM[aM.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",aM[aM.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",aM[aM.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",aM[aM.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",aM[aM.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",aM[aM.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",aM[aM.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",aM[aM.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",aM[aM.DEVICE_ERROR=5300]="DEVICE_ERROR",aM[aM.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",aM[aM.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",aM[aM.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",aM[aM.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",aM[aM.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",aM[aM.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",aM[aM.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",aM[aM.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",aM[aM.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",aM[aM.SERVER_ERROR=5400]="SERVER_ERROR",aM[aM.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",aM[aM.OPERATION_FAILED=5500]="OPERATION_FAILED",aM[aM.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",aM[aM.REJOIN_FAILED=5502]="REJOIN_FAILED",aM[aM.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",aM[aM.OPERATION_ABORT=5998]="OPERATION_ABORT",aM[aM.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",aM);RR(zR());var 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),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(a," when calling ").concat(r,"(), received type: ").concat(fP(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),a="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(a," when calling ").concat(r,"(), received type: ").concat(fP(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 validate string when useStringRoomId is true.")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return"'".concat(t,"' must be an integer between [1, 4294967294] when useStringRoomId is false.")},INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},MIX_PARAMS_USER_Z_ORDER(e){let{key:t}=e;return"'".concat(t,"' is required and must be between 1 and 15.")},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_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_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,"'.")},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_HTTP:"http protocol does not support the ability to capture and publish streams, please use the https protocol.",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.",DEVICE_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got server exception").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:i=dM(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=dM(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=dM(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=dM(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=dM(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=dM(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=dM(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'.")},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.")},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 dM(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var uM=class extends Error{constructor(e){let t,{code:i,extraCode:r,message:n="",messageParams:o,fnName:a="",originError:s}=e;t=n||function(e){let t,{code:i,params:r,enableDocLink:n=!1}=e,o="",s=cM[i];try{t=lM[s]}catch(a){t=lM.UNKNOWN_ERROR}return gP(t)?o=t(r):TP(t)&&(o=t),n&&(o+=" doc:"),o}({code:r||i,params:yR({fnName:a,error:s},o)}),super(t),bR(this,"name","RtcError"),bR(this,"code"),bR(this,"extraCode"),bR(this,"functionName"),bR(this,"message"),bR(this,"originError"),this.name=cM[i],this.code=i,this.extraCode=r,this.functionName=a,this.originError=s,this.message=t}static convertFrom(e,t,i){let r=e;if(e instanceof cD){let{stack:n}=e,o={code:sM.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case aD.INVALID_PARAMETER:o.code=sM.INVALID_PARAMETER;break;case aD.INVALID_OPERATION:o.code=sM.INVALID_OPERATION;break;case aD.NOT_SUPPORTED:case aD.NOT_SUPPORTED_H264:o.code=sM.ENV_NOT_SUPPORTED,e.getCode()===aD.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(zw.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case aD.DEVICE_NOT_FOUND:case aD.DEVICE_AUTO_RECOVER_FAILED:o.code=sM.DEVICE_ERROR;break;case aD.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case aD.SERVER_TIMEOUT:case aD.SWITCH_ROLE_FAILED:o.code=sM.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case aD.API_CALL_ABORTED:o.code=sM.OPERATION_ABORT;break;case aD.INITIALIZE_FAILED:o.code=5300,o.extraCode=function(e){let t;switch(e){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}(e.name);break;case aD.UNKNOWN:break;default:o.code=sM.OPERATION_FAILED}r=new uM(o),n&&(r.stack+=n.substr(n.indexOf("\n")))}else r=new uM({code:sM.UNKNOWN_ERROR,fnName:t,originError:e});return r}};var hM=uM,pM=(e,t)=>{if(t instanceof eM){let{stack:i}=t;t=new hM({code:sM.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function mM(e,t){return yO(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),a=0;a<n;a++)o[a]=arguments[a];let s=oM.get(this,"string"==typeof e?e:e(...o));return t&&(s.startSame=t.bind(this)),s.action(0,i.bind(this),o).catch(pM.bind(null,r))}))}function _M(e,t){return yO(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),a=0;a<n;a++)o[a]=arguments[a];let s=oM.get(this,"string"==typeof e?e:e(...o));return t&&(s.mergeUpdate=t.bind(this)),s.action(2,i.bind(this),o).catch(pM.bind(null,r))}))}function fM(e){return yO(((t,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return oM.get(this,"string"==typeof e?e:e(...n)).action(3,t.bind(this),n).catch(pM.bind(null,i))}))}RR(zR());var gM={type:Cb,properties:{cameraId:{type:Sb},useFrontCamera:{type:Eb},fillMode:{type:Sb,values:["contain","cover","fill"]},mirror:{type:Eb},small:{properties:{width:{type:yb},height:{type:yb},frameRate:{type:yb},bitrate:{type:yb}}},videoTrack:{instanceOf:MediaStreamTrack}}},vM={type:Cb,properties:{systemAudio:{type:Eb},fillMode:{type:Sb,values:["contain","cover","fill"]},profile:{type:[Sb,Cb],properties:{width:{type:yb},height:{type:yb},frameRate:{type:yb},bitrate:{type:yb}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},TM={type:[Sb,HTMLElement,null,Ib],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(TP(e)){let r=document.getElementById(e);if(!r)throw new hM({code:sM.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}});if(!(r instanceof HTMLElement))throw new hM({code:sM.INVALID_PARAMETER,extraCode:5010,fnName:i,messageParams:{key:t,type:fP(r)}})}}},SM={name:"userId",required:!0,type:Sb},yM={type:Cb,properties:{microphoneId:{type:Sb},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:yb,min:0,max:100},earMonitorVolume:{type:yb,min:0,max:100},echoCancellation:{type:Eb},autoGainControl:{type:Eb},noiseSuppression:{type:Eb}}};function EM(e,t,i,r){if(!/^[A-Za-z\d_-]*$/.test(e))throw new hM({code:sM.INVALID_PARAMETER,extraCode:5011,fnName:i,messageParams:{key:t}})}function IM(e,t,i,r){if(TP(e)){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new hM({code:sM.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}})}else if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new hM({code:sM.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}function CM(e,t){if(!e)throw new hM({code:sM.INVALID_OPERATION,extraCode:5101,fnName:t})}function RM(e,t,i){if(!e)throw new hM({code:sM.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var AM={type:yb,notLessThanZero:!0},bM={enterRoom:{name:"EnterRoomConfig",type:Cb,required:!0,validate(e,t,i){if(this._room.isJoined)throw new hM({code:sM.INVALID_OPERATION,extraCode:5104,fnName:i})},properties:{sdkAppId:{required:!0,type:yb,allowEmpty:!1},userId:{required:!0,type:Sb,allowEmpty:!1},userSig:{required:!0,type:Sb,allowEmpty:!1},scene:{type:Sb,values:["live","rtc"]},role:{type:Sb,values:["audience","anchor"]},roomId:{required:!0,type:[Sb,yb],validate:IM},proxy:{type:[Cb,Sb],properties:{websocketProxy:{type:Sb},turnServer:{type:[Cb,Ib],properties:{url:{required:!0,type:Sb},username:{type:Sb},credential:{type:Sb},credentialType:{type:Sb,values:["password"]}}},loggerProxy:{type:Sb},webtransportProxy:{type:Sb}}},enableAutoPlayDialog:{type:Eb},streamId:{type:Sb},userDefineRecordId:{type:Sb}}},startLocalVideo:{name:"LocalVideoConfig",type:Cb,properties:{view:TM,publish:{type:Eb},option:gM}},updateLocalVideo:{name:"updateLocalVideoConfig",type:Cb,required:!0,properties:{view:ER(yR({},TM),{required:!1}),publish:{type:Eb},mute:{type:Eb},option:gM}},startLocalAudio:{name:"LocalAudioConfig",type:Cb,properties:{publish:{type:Eb},option:yM}},updateLocalAudio:{name:"updateLocalAudioConfig",type:Cb,required:!0,properties:{publish:{type:Eb},mute:{type:Eb},option:yM}},startScreenShare:{name:"ScreenShareConfig",type:Cb,properties:{view:TM,publish:{type:Eb},option:vM}},updateScreenShare:{name:"updateScreenShareConfig",type:Cb,required:!0,properties:{view:TM,publish:{type:Eb},option:vM}},muteRemoteAudio:[SM,{name:"mute",required:!0,type:Eb}],setRemoteAudioVolume:[SM,{name:"volume",required:!0,type:yb,min:0,max:100}],startRemoteVideo:{name:"startRemoteVideoConfig",type:Cb,required:!0,properties:{view:TM,userId:{type:Sb,required:!0},streamType:{values:["main","sub"],required:!0},option:{type:Cb,properties:{fillMode:{type:Sb,values:["contain","cover","fill"]},mirror:{type:Eb}}}},validate(e,t,i){CM(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(RM(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new hM({code:sM.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:Cb,required:!0,properties:{view:ER(yR({},TM),{required:!1}),userId:{type:Sb,required:!0},streamType:{values:["main","sub"],required:!0},option:{type:Cb,properties:{fillMode:{type:Sb,values:["contain","cover","fill"]},mirror:{type:Eb}}}},validate(e,t,i){CM(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(RM(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new hM({code:sM.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:Cb,required:!0,properties:{userId:{type:Sb,required:!0},streamType:{values:["main","sub"]}},validate(e,t,i){if("*"!==e.userId&&vP(e.streamType))throw new hM({code:sM.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){CM(this._room.isJoined,i)}},enableAudioVolumeEvaluation:[{name:"interval",type:yb},{name:"enableInBackground",type:Eb}],startMixTranscode:{name:"config",required:!0,type:Cb,properties:{mode:{type:Sb,values:["preset-layout","manual"]},streamId:{type:Sb,validate:EM},videoWidth:AM,videoHeight:AM,videoBitrate:ER(yR({},AM),{allowEmpty:!1}),videoFramerate:{type:yb,validate(e,t,i,r){if(e<=0||e>30)throw new hM({code:sM.INVALID_PARAMETER,extraCode:5016,fnName:i})}},videoGop:{type:yb,validate(e,t,i,r){if(e<1||e>8)throw new hM({code:sM.INVALID_PARAMETER,extraCode:5017,fnName:i})}},audioSampleRate:AM,audioBitrate:{type:yb,validate(e,t,i,r){if(e<32||e>192)throw new hM({code:sM.INVALID_PARAMETER,extraCode:5018,fnName:i})}},audioChannels:{type:yb,values:[1,2]},backgroundColor:{type:yb},backgroundImage:{type:Sb},mixUsers:{required:!0,type:Ib,arrayItem:{require:!0,type:Cb,properties:{userId:{required:!0,type:Sb},roomId:{type:[Sb,yb],validate:IM},pureAudio:{type:Eb},width:AM,height:AM,locationX:AM,locationY:AM,zOrder:{type:yb},streamType:{values:["main","sub"]},renderMode:{type:yb,values:[0,1,2,4]}}}}},validate(e,t,i,r){let n=0,o=0,{mixUsers:a}=e,s=[];if(a.forEach(((e,t)=>{if(s.push(e.userId),!e.pureAudio){if(!e.zOrder||e.zOrder<1||e>15)throw new hM({code:sM.INVALID_PARAMETER,extraCode:5015,fnName:i,messageParams:{key:"config.mixUsers[".concat(t,"].zOrder")}});e.width+e.locationX>n&&(n=e.width+e.locationX),e.height+e.locationY>o&&(o=e.height+e.locationY)}})),s.indexOf(this._room.userId)<0)throw new hM({code:sM.INVALID_PARAMETER,extraCode:5019,fnName:i});if(e.videoWidth<n||e.videoHeight<o)throw new hM({code:sM.INVALID_PARAMETER,extraCode:5020,fnName:i})}},startPublishCDNStream:{name:"options",required:!1,properties:{streamId:{type:Sb,validate:EM},streamType:{values:["main","sub"]},appId:{type:yb,allowEmpty:!1},bizId:{type:yb,allowEmpty:!1},url:{type:Sb,allowEmpty:!1}}},sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(e,t,i,r){if(!GD)throw new hM({code:sM.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new hM({code:sM.INVALID_OPERATION,messageParams:{key:Fw}});if(e.byteLength>1e3)throw new hM({code:sM.INVALID_PARAMETER,messageParams:{key:jw,data:e.byteLength}});if(0===e.byteLength)throw new hM({code:sM.INVALID_PARAMETER,messageParams:{key:Bw}});if(CM(this._room.isJoined,i),!this._room.isMainStreamPublished)throw new hM({code:sM.INVALID_PARAMETER,messageParams:{key:Hw}})}},{name:"options",type:Cb,properties:{seiPayloadType:{type:yb,values:[5,243]}}}]},kM={TRTC:bM};function wM(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function PM(e){return e===ZO.QOS_PREFERENCE_CLEAR?"detail":e===ZO.QOS_PREFERENCE_SMOOTH?"motion":""}RR(zR(),1),RR(zR());function DM(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return yO(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{OM.call(this,t,n,i,this._name)}catch(a){return Promise.reject(a)}return e.apply(this,n)}))}function NM(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return yO(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{OM.call(this,t,n,i,this._name)}catch(a){throw a}return e.apply(this,n)}))}function OM(e,t,i,r){if(IP(e))for(let n=0;n<e.length;n++)MM.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else MM.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function MM(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function a(e){return{code:sM.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(vP(i)){if(t.required)throw new hM(a(5001));if(vP(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),gP(t.type[r])&&i instanceof t.type[r]&&(e=!0),TP(t.type[r])&&fP(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new hM({code:sM.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>bP(e)?kP(e):TP(e)?e:fP(e)))},value:i}})}else if(!vP(t.type)&&fP(i)!==t.type)throw new hM(a(5002));if(!1===t.allowEmpty){let e=SP(i)&&(0===i||Number.isNaN(i)),t=TP(i)&&""===i.trim();if(e||t)throw new hM(a(5003))}if(t.notLessThanZero&&SP(i)&&i<0)throw new hM(a(5006));if(!vP(t.min)&&SP(i)&&i<t.min)throw new hM(a(5007));if(!vP(t.max)&&SP(i)&&i>t.max)throw new hM(a(5008));if(TP(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new hM(a(5004))}else if(gP(t.instanceOf)&&!(i instanceof t.instanceOf))throw new hM(a(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new hM(a(5005));let{properties:s}=t;pP(s)&&EP(i)&&Object.keys(s).forEach((e=>{MM.call(this,{rule:s[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;pP(c)&&IP(i)&&i.forEach(((e,t)=>{MM.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),gP(t.validate)&&t.validate.call(this,i,r,n,o,this)}function LM(){return yO(((e,t)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];let o=this._log||loggerManager;r.length>0?o.info("".concat(t,"() ").concat(JSON.stringify(r,((e,t)=>{if(t===r||e in r)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(fP(t)):(JSON.stringify(t),t)}catch(tA){return"type:".concat(fP(t))}})))):o.info("".concat(t,"()"));try{let i=e.apply(this,r),n=DP();return AP(i)?i.then((e=>(o.info("".concat(t,"() success")),qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:t,cost:DP()-n}),e))).catch((e=>{throw e=hM.convertFrom.call(this,e,t,1===r.length?r[0]:r),o.error("".concat(t,"() failed ").concat(e)),qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:t,error:e}),e})):(qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:t,cost:DP()-n}),i)}catch(a){throw a=hM.convertFrom.call(this,a,t),o.error("".concat(t,"() failed ").concat(a)),qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:t,error:a}),a}}))}RR(zR()),RR(zR()),RR(zR(),1);var xM=new WeakMap;var VM=0,UM=new Set,FM=null;!function(e){eA=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));ZR="".concat(t,".").concat(Math.min(15,i),".").concat(Math.min(15,r),".").concat(i.toString().padStart(2,"0")).concat(r.toString().padStart(2,"0"))}("5.0.2");var BM=class extends tD.EventEmitter{constructor(e,t){super(),bR(this,"_room"),bR(this,"_eventListened",new Set),bR(this,"_localVideoTrack",null),bR(this,"_localAudioTrack",null),bR(this,"_localScreenTrack",null),bR(this,"_localScreenAudioTrack",null),bR(this,"_localVideoConfig",null),bR(this,"_localScreenConfig",null),bR(this,"_localAudioConfig",null),bR(this,"_remoteVideoConfigMap",new Map),bR(this,"_remoteAudioConfigMap",new Map),bR(this,"_remoteAudioMuteMap",new Map),bR(this,"_log",ZP.createLogger({id:"t".concat(++VM)})),this._room=new e(yR({logger:this._log,frameWorkType:BM.frameWorkType},t)),this._room.on("audio-volume",(e=>{!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*this._localAudioTrack.getAudioLevel())}),this.emit(iD.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this.on(iD.REMOTE_AUDIO_UNAVAILABLE,(e=>{let{userId:t}=e;this._stopRemoteAudio({userId:t},!1).catch((()=>{}))})),this.on(iD.REMOTE_VIDEO_UNAVAILABLE,(e=>{let{userId:t,streamType:i}=e;this._stopRemoteVideo({userId:t,streamType:i},!1).catch((()=>{}))})),GN(cO,cO).add("audioInputAdded",(e=>{this.emit(iD.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(iD.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(iD.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(iD.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>wR(this,null,(function*(){if(this.emit(iD.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),FM&&FM.deviceId===Db){let e=(yield hO()).find((e=>e.deviceId===Db));e&&FM.groupId!==e.groupId&&(FM=e,this.emit(iD.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>wR(this,null,(function*(){this.emit(iD.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield hO())[0];t&&FM&&(FM.deviceId===e.deviceId||FM.deviceId===Db&&FM.groupId!==t.groupId)&&(FM=t,this.emit(iD.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})))),NP(this,"trtc")}static create(){}static _create(e,t){!function(){var e;eD&&(eD=!1,5!==ZP.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(uA,"index.html")),console.info("* Changelog: https://cloud.tencent.com/document/product/647/38958"),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),ZP.info("TRTC Web SDK Version:",eA),ZP.info("UA:",navigator.userAgent),ZP.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")))}();let i=new BM(e,t);return UM.add(i),FM?i.emit(iD.DEVICE_CHANGED,{type:"speaker",action:"active",device:FM}):hO().then((e=>{e[0]&&(FM=e[0],i.emit(iD.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]}))})),i}enterRoom(e){return wR(this,null,(function*(){var t,i;let{scene:r="rtc",enableAutoPlayDialog:n=!0,autoReceiveAudio:o=!0,autoReceiveVideo:a=!0}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!TP(e.proxy)&&e.proxy.turnServer&&(null==(i=(t=this._room).setTurnServer)||i.call(t,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=n,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=a;let s={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,role:"audience"===e.role?21:20,roomId:0,strRoomId:"",businessInfo:e.businessInfo||null,streamId:e.streamId||null,userDefineRecordId:e.userDefineRecordId||null};TP(e.roomId)?(s.strRoomId=e.roomId,this._room.useStringRoomId=!0):s.roomId=e.roomId,GN(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(iD.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(iD.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(iD.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(iD.ERROR,hM.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(iD.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this.emit(iD.NETWORK_QUALITY,e)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{GN(t,t).add("player-state-changed",(i=>{let r=ER(yR({},i),{userId:e.userId});t.kind===CA&&(r.streamType=wM(t.streamType)),this.emit(t.kind===IA?iD.AUDIO_PLAY_STATE_CHANGED:iD.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===aD.PLAY_NOT_ALLOWED&&this.emit(iD.AUTOPLAY_FAILED)}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{WN(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:r}=i;this._room.remotePublishedUserMap.get(r);let n=t.audioAvailable,o=t.videoAvailable,{audioAvailable:a,videoAvailable:s}=i;a||this._remoteAudioConfigMap.delete(r),s||this._remoteVideoConfigMap.delete("".concat(r,"_","main")),i.hasAuxiliary||this._remoteVideoConfigMap.delete("".concat(r,"_","sub")),n!==a&&this.emit(a?iD.REMOTE_AUDIO_AVAILABLE:iD.REMOTE_AUDIO_UNAVAILABLE,{userId:r}),o!==s&&this.emit(s?iD.REMOTE_VIDEO_AVAILABLE:iD.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"}),t.hasAuxiliary!==i.hasAuxiliary&&this.emit(i.hasAuxiliary?iD.REMOTE_VIDEO_AVAILABLE:iD.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"})})).add("firewall-restriction",(()=>{this.emit(iD.ERROR,new hM({code:sM.OPERATION_FAILED,extraCode:5501}))})).add("sei-message",(e=>{this.emit(iD.SEI_MESSAGE,e)})),this._handleReceiveMode(),yield this._room.join(s,r,BM.frameWorkType),this._checkTrackToPublish()}))}exitRoom(){return wR(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e){return wR(this,null,(function*(){yield this._room.switchRole(e),"anchor"===e&&this._checkTrackToPublish()}))}destroy(){WN(cO),this.removeAllListeners(),this._room.destroy(),UM.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare()}startLocalAudio(){return wR(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,option:r}=t,n=new CO,o={},a={muted:!0};r&&(vP(r.microphoneId)?vP(r.audioTrack)||(o.customSource=r.audioTrack):o.deviceId=r.microphoneId,vP(r.captureVolume),vP(r.profile)||(TP(r.profile)?TA[r.profile]&&n.setProfile(TA[r.profile]):n.setProfile(r.profile)),SP(r.earMonitorVolume)&&(a.muted=!(r.earMonitorVolume>0),a.volume=r.earMonitorVolume),vP(r.echoCancellation)||(n.profile.echoCancellation=r.echoCancellation),vP(r.noiseSuppression)||(n.profile.noiseSuppression=r.noiseSuppression),vP(r.autoGainControl)||(n.profile.autoGainControl=r.autoGainControl)),n.on("5",(t=>{e.emit(iD.ERROR,new hM({code:sM.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),n.on("2",(t=>{e.emit(iD.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),n.on("4",(t=>{let i;t.error&&(i=hM.convertFrom(t.error)),e.emit(iD.PUBLISH_STATE_CHANGED,ER(yR({},t),{error:i}))})),yield n.capture(o),GN(n,n).add("player-state-changed",(t=>{e.emit(iD.AUDIO_PLAY_STATE_CHANGED,ER(yR({},t),{userId:""}))})),yield e._updateAudioPlayOption({playOption:a,track:n}),i&&e._room.isJoined&&e._room.publish(n).catch((()=>{})),e._localAudioTrack=n,e._localAudioConfig=ER(yR({},t),{publish:i})}()}))}updateLocalAudio(e){return wR(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):vP(r.audioTrack)||(this._localAudioTrack.setMediaStreamTrack(r.audioTrack),yield this._room.replaceTrack(this._localAudioTrack)),vP(r.captureVolume),vP(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume)),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),this._room.isJoined&&!vP(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),vP(i)||this._localAudioTrack.setMute(i),HP(this._localAudioConfig,e)}))}stopLocalAudio(){return wR(this,null,(function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),this._localAudioTrack.stop(),this._localAudioTrack.close(),WN(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return wR(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,option:n}=t,o=new RO,a={},s={};if(n&&(n.cameraId?a.deviceId=n.cameraId:vP(n.useFrontCamera)?vP(n.videoTrack)||(a.customSource=n.videoTrack):a.facingMode=n.useFrontCamera?PA:DA,vP(n.profile)||(TP(n.profile)?SA[n.profile]&&o.setProfile(SA[n.profile]):o.setProfile(n.profile)),vP(n.fillMode)||(s.objectFit=n.fillMode),vP(n.mirror)||(s.mirror=n.mirror),vP(n.small)||(DD()?TP(n.small)?o.small=SA[n.small]:o.small=n.small:e._log.warn("small stream is not supported"))),o.on("5",(t=>{e.emit(iD.ERROR,new hM({code:sM.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(iD.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=hM.convertFrom(t.error)),e.emit(iD.PUBLISH_STATE_CHANGED,ER(yR({},t),{error:i}))})),yield o.capture(a),(null==n?void 0:n.qosPreference)&&o.mediaTrack){let e=PM(n.qosPreference);o.mediaTrack.contentHint=e}GN(o,o).add("player-state-changed",(t=>{e.emit(iD.VIDEO_PLAY_STATE_CHANGED,ER(yR({},t),{userId:"",streamType:"main"}))})),yield e._updateVideoPlayOption({view:i,playOption:s,track:o}),r&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localVideoTrack=o,e._localVideoConfig=ER(yR({},t),{view:i,publish:r})}()}))}updateLocalVideo(e){return wR(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:r,option:n}=e,o={};if(n&&(n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):vP(n.useFrontCamera)?vP(n.videoTrack)||(this._localVideoTrack.setMediaStreamTrack(n.videoTrack),yield this._room.replaceTrack(this._localVideoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?PA:DA),vP(n.profile)||(TP(n.profile)?SA[n.profile]&&this._localVideoTrack.setProfile(SA[n.profile]):this._localVideoTrack.setProfile(n.profile)),vP(n.fillMode)||(o.objectFit=n.fillMode),vP(n.mirror)||(o.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack)){let e=PM(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e}yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),this._room.isJoined&&!vP(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),vP(r)||this._localVideoTrack.setMute(r),HP(this._localVideoConfig,e)}))}stopLocalVideo(){return wR(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),WN(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return wR(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 bO;o.on("4",(t=>{let i;t.error&&(i=hM.convertFrom(t.error)),e.emit(iD.PUBLISH_STATE_CHANGED,ER(yR({},t),{error:i}))}));let a=null;o.setMediaType(2);let s={},c={};n&&(vP(n.profile)||(TP(n.profile)?yA[n.profile]&&o.setProfile(yA[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(s.systemAudio=!0,s.echoCancellation=n.echoCancellation,s.noiseSuppression=n.noiseSuppression,s.autoGainControl=n.autoGainControl),vP(n.fillMode)||(c.objectFit=n.fillMode),n.videoTrack&&(s.videoTrack=n.videoTrack),n.audioTrack&&(s.audioTrack=n.audioTrack));let l=yield o.capture(s);if(null!=n&&n.qosPreference){let e=PM(n.qosPreference);o.mediaTrack.contentHint=e}if(o.mediaTrack.addEventListener(MA,(()=>{e._stopScreenShare(),e.emit(iD.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(a=new kO,a.setScreenAudioTrack(l.getAudioTracks()[0],l)),GN(o,o).add("player-state-changed",(t=>{e.emit(iD.VIDEO_PLAY_STATE_CHANGED,ER(yR({},t),{userId:"",streamType:"sub"}))})),yield e._updateVideoPlayOption({view:i,playOption:c,track:o}),r&&e._room.isJoined){let t=[o];a&&t.push(a),e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=o,e._localScreenAudioTrack=a,e._localScreenConfig=ER(yR({},t),{view:i,publish:r})}()}))}updateScreenShare(e){return wR(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(vP(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let e=PM(r.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),this._room.isJoined&&!vP(i)&&(i&&!this._localScreenConfig.publish&&this._room.publish(this._localScreenTrack).catch((()=>{})),this._localScreenConfig.publish&&!i&&this._room.unpublish(this._localScreenTrack).catch((()=>{}))),HP(this._localScreenConfig,e)}))}stopScreenShare(){return wR(this,null,(function*(){return yield this._stopScreenShare()}))}startPlugin(e,t){return wR(this,null,(function*(){"AudioMixer"===e&&(yield this._room.startPlugin("AudioMixer",t)),"AIDenoiser"===e&&(yield this._room.startPlugin("AIDenoiser",t))}))}updatePlugin(e,t){return wR(this,null,(function*(){"AudioMixer"===e&&(yield this._room.updatePlugin("AudioMixer",t))}))}stopPlugin(e,t){return wR(this,null,(function*(){"AudioMixer"===e&&(yield this._room.stopPlugin("AudioMixer",t)),"AIDenoiser"===e&&(yield this._room.stopPlugin("AIDenoiser",t))}))}startRemoteVideo(e){return wR(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 a=this._room.remotePublishedUserMap.get(i);if(!a)return;let s={},c="main"===r?a.remoteVideoTrack:a.remoteAuxiliaryTrack;n&&(vP(n.fillMode)||(s.objectFit=n.fillMode),vP(n.mirror)||(s.mirror=n.mirror),"main"===r&&!vP(n.small)&&this._room.changeType(n.small,c.user)),yield this._room.subscribe(c),yield this._updateVideoPlayOption({view:t,playOption:s,track:c}),this._remoteVideoConfigMap.set(o,e)}))}updateRemoteVideo(e){return wR(this,null,(function*(){let{view:t,userId:i,streamType:r,option:n}=e,o="".concat(i,"_").concat(r);if(!this._remoteVideoConfigMap.has(o)||!this._room.remotePublishedUserMap.has(i))return;let a={};n&&(vP(n.fillMode)||(a.objectFit=n.fillMode),vP(n.mirror)||(a.mirror=n.mirror));let s=null,c=this._room.remotePublishedUserMap.get(i);"main"===r&&(null==c?void 0:c.muteState.hasVideo)&&(s=c.remoteVideoTrack),"sub"===r&&(null==c?void 0:c.muteState.hasAuxiliary)&&(s=c.remoteAuxiliaryTrack);let l=this._remoteVideoConfigMap.get(o);s&&("main"===r&&n&&!vP(n.small)&&this._room.changeType(n.small,s.user),yield this._updateVideoPlayOption({view:t,playOption:a,track:s,prevConfig:l})),HP(l,e)}))}stopRemoteVideo(e){return wR(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return wR(this,null,(function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:n,remoteAuxiliaryTrack:o}=r;n.stop(),t.hasVideo&&"main"===e.streamType&&i.push(n),o.stop(),t.hasAuxiliary&&"sub"===e.streamType&&i.push(o)}for(let e of i)t&&(yield this._room.unsubscribe(e));this._remoteVideoConfigMap.delete("".concat(e.userId,"_").concat(e.streamType))}))}muteRemoteAudio(e,t){return wR(this,null,(function*(){if("*"===e)if(t)yield this._stopRemoteAudio({userId:e});else{let e=[...this._room.remotePublishedUserMap.values()];for(let t of e)t.muteState.hasAudio&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):yield this._startRemoteAudio({userId:e});this._remoteAudioMuteMap.set(e,t)}))}setRemoteAudioVolume(e,t){if("*"===e){let e=[...this._room.remotePublishedUserMap.values()];for(let i of e)this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);i&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}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)}startMixTranscode(e){let t=yR({},e);return t.mixUsers=e.mixUsers.map((e=>{let t=yR({},e);return vP(e.streamType)||(t.streamType=wM(e.streamType)),t})),this._room.startMixTranscode(t)}stopMixTranscode(){return this._room.stopMixTranscode()}startPublishCDNStream(e){let t=yR({},e);return vP(e.streamType)||(t.streamType=wM(e.streamType)),this._room.startPublishCDNStream(t)}stopPublishCDNStream(){return this._room.stopPublishCDNStream()}on(e,t,i){return super.on(e,t,i),this._eventListened.add(e),this}off(e,t,i){return"*"===e?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,i),this}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main"}=e;if(""===t){if("main"===i&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let e=this._room.remotePublishedUserMap.get(t);if(e)return"main"===i?e.remoteVideoTrack.mediaTrack:e.remoteAuxiliaryTrack.mediaTrack}return null}getAudioTrack(e){if(e){let t=this._room.remotePublishedUserMap.get(e);if(t)return t.remoteAudioTrack.mediaTrack}else if(this._localAudioTrack)return this._localAudioTrack.mediaTrack;return null}setCurrentSpeaker(e){var t;null==(t=this._localAudioTrack)||t.setAudioOutput(e),this._room.remotePublishedUserMap.forEach((t=>t.remoteAudioTrack.setAudioOutput(e)))}_startRemoteAudio(e){return wR(this,null,(function*(){let{userId:t,option:i}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let n={};i&&(vP(i.volume)||(n.volume=i.volume));let o=r.remoteAudioTrack;yield this._room.subscribe(o),yield this._updateAudioPlayOption({playOption:n,track:o}),this._remoteAudioConfigMap.set(t,e)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return wR(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._remoteAudioConfigMap.delete("".concat(e.userId))}))}_updateVideoPlayOption(e){return wR(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(vP(t)&&n&&n.view&&!xP(i)){let e;e=IP(n.view)?n.view:GP(n.view),e&&(yield r.play(e,i))}if(!vP(t)){let e;e=IP(t)?t:GP(t),e?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return wR(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:r}=e;return function*(){i.isPlayCalled||(yield i.play(null,t)),vP(t.muted)||i.setPlayerMute(t.muted),vP(t.volume)||i.setAudioVolume(t.volume/100)}()}))}_checkTrackToPublish(){var e,t,i;let r=[];if((null==(e=this._localAudioConfig)?void 0:e.publish)&&this._localAudioTrack&&r.push(this._localAudioTrack),(null==(t=this._localVideoConfig)?void 0:t.publish)&&this._localVideoTrack&&r.push(this._localVideoTrack),null!=(i=this._localScreenConfig)&&i.publish&&(this._localScreenTrack&&r.push(this._localScreenTrack),this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack)),0!==r.length)return this._room.publish(...r).catch((()=>{}))}_handleReceiveMode(){this._room.autoReceiveAudio&&GN(this,this).add(iD.REMOTE_AUDIO_AVAILABLE,(e=>wR(this,[e],(function(e){var t=this;let{userId:i}=e;return function*(){if(t._remoteAudioMuteMap.get("*")||t._remoteAudioMuteMap.get(i))return;let e=t._room.remotePublishedUserMap.get(i);e&&(yield t._room.subscribe(e.remoteAudioTrack).catch((()=>{})),yield t._updateAudioPlayOption({track:e.remoteAudioTrack}).catch((()=>{})),t._remoteAudioConfigMap.set(i,{userId:i}))}()})))),this._room.autoReceiveVideo&&GN(this,this).add(iD.REMOTE_VIDEO_AVAILABLE,(e=>{let{userId:t,streamType:i}=e,r=this._room.remotePublishedUserMap.get(t);r&&("main"===i?this._room.subscribe(r.remoteVideoTrack).catch((()=>{})):"sub"===i&&this._room.subscribe(r.remoteAuxiliaryTrack).catch((()=>{})))}))}_exitRoom(){return wR(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),[...this._remoteAudioConfigMap.keys()].forEach((e=>{this._stopRemoteAudio({userId:e}).catch()})),[...this._remoteVideoConfigMap.keys()].forEach((e=>{let t=e.includes("main")?"main":"sub",i=e.split("_".concat(t))[0];i&&this._stopRemoteVideo({userId:i,streamType:t}).catch()})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach((e=>{WN(e.remoteAudioTrack),WN(e.remoteVideoTrack),WN(e.remoteAuxiliaryTrack)})),WN(this)}))}_stopScreenShare(){return wR(this,null,(function*(){var e,t,i;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(),null==(t=this._localScreenAudioTrack)||t.stop(),null==(i=this._localScreenAudioTrack)||i.close(),WN(this._localScreenTrack),this._localScreenTrack=null,this._localScreenAudioTrack=null,this._localScreenConfig=null}}))}sendSEIMessage(e,t){this._room.sendSEI(e,t||{seiPayloadType:243})}static setLogLevel(e,t){ZP.setLogLevel(e),vP(t)||(t?ZP.enableUploadLog():ZP.disableUploadLog())}static isSupported(){return SD()}static getCameraList(){return uO()}static getMicrophoneList(){return dO()}static getSpeakerList(){return hO()}static setCurrentSpeaker(e){return wR(this,null,(function*(){(yield hO()).forEach((t=>{t.deviceId===e&&(UM.forEach((i=>{i.setCurrentSpeaker(e),i.emit(iD.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),FM=t)}))}))}},jM=BM;bR(jM,"_loggerManager",ZP),bR(jM,"EVENT",iD),bR(jM,"ERROR_CODE",sM),bR(jM,"TYPE",ZO),bR(jM,"frameWorkType",30),AR([DM(kM.TRTC.enterRoom),mM("room",((e,t)=>{let[i]=e,[r]=t;return i.roomId===r.roomId&&i.userId===r.userId&&i.sdkAppId===r.sdkAppId})),yO((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t).catch((e=>{throw WN(this),e}))})),LM()],jM.prototype,"enterRoom",1),AR([LM()],jM.prototype,"exitRoom",1),AR([DM(kM.TRTC.switchRole),_M("room",((e,t)=>t)),LM()],jM.prototype,"switchRole",1),AR([LM()],jM.prototype,"destroy",1),AR([DM(kM.TRTC.startLocalAudio),mM("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)})),LM()],jM.prototype,"startLocalAudio",1),AR([DM(kM.TRTC.updateLocalAudio),_M("audio"),LM()],jM.prototype,"updateLocalAudio",1),AR([fM("audio"),LM()],jM.prototype,"stopLocalAudio",1),AR([DM(kM.TRTC.startLocalVideo),mM("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)})),LM()],jM.prototype,"startLocalVideo",1),AR([DM(kM.TRTC.updateLocalVideo),_M("video"),LM()],jM.prototype,"updateLocalVideo",1),AR([fM("video"),LM()],jM.prototype,"stopLocalVideo",1),AR([DM(kM.TRTC.startScreenShare),mM("screen",(()=>!0)),LM()],jM.prototype,"startScreenShare",1),AR([DM(kM.TRTC.updateScreenShare),_M("screen"),LM()],jM.prototype,"updateScreenShare",1),AR([LM()],jM.prototype,"stopScreenShare",1),AR([DM(kM.TRTC.startRemoteVideo),mM((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),LM()],jM.prototype,"startRemoteVideo",1),AR([DM(kM.TRTC.updateRemoteVideo),_M((e=>"v".concat(e.userId).concat(e.streamType))),LM()],jM.prototype,"updateRemoteVideo",1),AR([DM(kM.TRTC.stopRemoteVideo),yO((e=>function(t){return wR(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)}))})),LM()],jM.prototype,"stopRemoteVideo",1),AR([fM((e=>"v".concat(e.userId).concat(e.streamType)))],jM.prototype,"_stopRemoteVideo",1),AR([DM(...kM.TRTC.muteRemoteAudio),LM()],jM.prototype,"muteRemoteAudio",1),AR([NM(...kM.TRTC.setRemoteAudioVolume),function(e,t){return yO(((i,r)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];var a,s;let c=null==(a=xM.get(this))?void 0:a.get(t(...n));c&&c>0&&clearTimeout(c);let l=window.setTimeout((()=>{i.apply(this,n)}),e);xM.has(this)?null==(s=xM.get(this))||s.set(t(...n),l):xM.set(this,new Map([[t(...n),l]]))}))}(200,(e=>e)),LM()],jM.prototype,"setRemoteAudioVolume",1),AR([NM(...kM.TRTC.enableAudioVolumeEvaluation)],jM.prototype,"enableAudioVolumeEvaluation",1),AR([DM(kM.TRTC.startMixTranscode)],jM.prototype,"startMixTranscode",1),AR([mM((e=>"a".concat(e.userId)),(()=>!0))],jM.prototype,"_startRemoteAudio",1),AR([yO((e=>function(t){return wR(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(ER(yR({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),fM((e=>"a".concat(e.userId)))],jM.prototype,"_stopRemoteAudio",1),AR([fM("room")],jM.prototype,"_exitRoom",1),AR([fM("screen")],jM.prototype,"_stopScreenShare",1),AR([DM(kM.TRTC.sendSEIMessage),function(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return yO(((e,n)=>{let o=new Map;return qP.on(XP.ROOM_DESTROY,(e=>{let{room:t}=e;return o.delete(t)})),function(){let a=o.get(this);for(var s=arguments.length,c=new Array(s),l=0;l<s;l++)c[l]=arguments[l];if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),0===a.timestamp?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),r&&(a.totalSizeInSecond+=r(...c)),0!==a.timestamp&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=t||a.totalSizeInSecond>i))throw new cD({code:aD.INVALID_OPERATION,message:Xw({key:Gw,data:{isTimes:a.callCountInSecond>=t,isSize:a.totalSizeInSecond>i,name:n,timesInSecond:t,maxSizeInSecond:i}})});a.callCountInSecond++,e.call(this,...c)}}))}({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}})],jM.prototype,"sendSEIMessage",1);var HM=jM;RR(zR()),RR(zR(),1);function GM(){return wR(this,null,(function*(){let e,t;try{let t=yield dO();e=t&&t.length}catch(u){}try{let e=yield uO();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:a}=this.checkSystemResult.detail,s=rD.basis(),c={webRTC:s.isWebRTCSupported,getUserMedia:s.isGetUserMediaSupported,webSocket:s.isWebSocketsSupported,screenShare:s.isScreenShareSupported,webAudio:s.isWebAudioSupported,h264Encode:r,h264Decode:o,vp8Encode:n,vp8Decode:a},l={browser:s.browser,os:s.os,trtc:c,devices:i},d={isWebCodecSupported:s.isWebCodecSupported,isMediaSessionSupported:s.isMediaSessionSupported,isWebTransportSupported:s.isWebTransportSupported};TN.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),TN.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}RR(zR(),1);RR(zR());var WM=RR(KR());RR(zR());var JM="1",zM="5",KM="2",qM="3",QM="4",YM="DISCONNECTED",XM="CONNECTING",$M="CONNECTED",ZM={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,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},eL=[ZM.UPDATE_REMOTE_MUTE_STAT,ZM.UPLINK_NETWORK_STATS,ZM.USER_LIST_RES,ZM.MUTE_RESULT],tL={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",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"},iL="publish_change",rL="join",nL="leave",oL="quality_report",aL="mute_uplink",sL="publish",cL="publish_state_change",lL="unpublish",dL="subscribe",uL="unsubscribe",hL="subscribe_change",pL="start_publishing",mL="stop_publishing",_L="start_push_user_cdn",fL="stop_push_user_cdn",gL="start_mcu_mix",vL="stop_mcu_mix",TL="get_user_list",SL="change_role",yL="update_constraint_config",EL="rebuild_pc",IL="join/v2",CL="publish/v2",RL="subscribe/v3";RR(zR()),RR(zR());var AL=RR(KR());RR(zR()),RR(zR(),1);var bL=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}},kL=class{constructor(e,t,i){this._connection=e,this._log=t,this._isUplink=i,bR(this,"_seiMessageList",[]),bR(this,"_seiPayloadType",243),bR(this,"_mainVideoSenderOrReceiver",null),bR(this,"_mainVideoAbortController",null),bR(this,"_abortMap",new Map),bR(this,"onSEIMessage")}get isRunning(){return!!this._mainVideoAbortController}start(e){this._mainVideoSenderOrReceiver=e;let t=e.createEncodedStreams(),i=t.readable,r=t.writable,n=new TransformStream({transform:this._isUplink?this.encodeVideoFrame.bind(this):this.decodeVideoFrame.bind(this)});this._mainVideoAbortController=new AbortController,i.pipeThrough(n).pipeTo(r,this._mainVideoAbortController).catch((()=>{}))}restart(e){this.stop(),this.start(e)}stop(){var e;null==(e=this._mainVideoAbortController)||e.abort(),this._mainVideoAbortController=null}destroy(){this.stop(),this._abortMap.forEach((e=>e.abort())),this._abortMap.clear(),this._log=null,this.onSEIMessage=null,this._mainVideoSenderOrReceiver=null,this._connection=null}handleEncodedStreams(){try{let e=this._connection.getPeerConnection();this.clearUnusedSenderOrReceiver(e),this._isUplink?e.getSenders().forEach(((e,t)=>{if(1===t){if(e===this._mainVideoSenderOrReceiver)return;this.isRunning?this.restart(e):this.start(e)}else{if(this._abortMap.has(e))return;this.pipeSenderOrReceiver(e)}})):e.getReceivers().forEach(((e,t)=>{var i;this._abortMap.has(e)||e===this._mainVideoSenderOrReceiver||(1===t&&(null==(i=e.track)?void 0:i.kind)===CA?this.isRunning?this.restart(e):this.start(e):this.pipeSenderOrReceiver(e))}))}catch(KO){this._log.warn(KO)}}pipeSenderOrReceiver(e){let{readable:t,writable:i}=e.createEncodedStreams(),r=new AbortController;this._abortMap.set(e,r),t.pipeTo(i,r).catch((()=>{}))}clearUnusedSenderOrReceiver(e){this._abortMap.forEach(((t,i)=>{(this._isUplink?e.getSenders():e.getReceivers()).find((e=>e===i))||(t.abort(),this._abortMap.delete(i))}))}push(e,t){t&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e)}hasSEI(e){let t=new DataView(e);return 1===t.getInt32(0)&&6===t.getInt8(4)}isEmptyFrame(e){return"empty"===e.type||0===e.data.byteLength}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}encodeVideoFrame(e,t){try{if(this._connection.isH264&&this._seiMessageList.length>0&&!this.isEmptyFrame(e)){let t=9-this.getNaluCount(e.data);if(t<=0)return;let i=this._seiMessageList.splice(0,t).reverse().map(this.encodeSEINalu.bind(this)),r=i.reduce(((e,t)=>e+t.dataView.byteLength),0),n=new ArrayBuffer(r+e.data.byteLength),o=new DataView(n),a=new DataView(e.data),s=0;for(let e=0;e<i.length;e++)for(let t=0;t<i[e].dataView.byteLength;t++)o.setInt8(s++,i[e].dataView.getInt8(t));for(let c=0;c<e.data.byteLength;c++)o.setInt8(s++,a.getInt8(c));e.data=n,this._log.debug("".concat(i.length," sei sent"))}}catch(i){this._log.warn(i)}t.enqueue(e)}decodeVideoFrame(e,t){try{if(this._connection.isH264&&!this.isEmptyFrame(e)&&this.hasSEI(e.data)){let t=[],i=new DataView(e.data),r=0,n=-1,o=-1;for(let a=0;a<e.data.byteLength;a++){let s=i.getUint8(a);if(0===s)r++;else if(1===s){if(2===r||3===r){let s=a-r;if(-1===n?n=s:-1===o&&(o=s,t.push(new bL(new DataView(i.buffer.slice(n,o)))),n=s,o=-1),6!==i.getUint8(a+1)){e.data=new DataView(i.buffer.slice(s)).buffer;break}}r=0}else r=0}this._log.debug("".concat(t.length," sei received")),gP(this.onSEIMessage)&&t.reverse().forEach((e=>{this.onSEIMessage({seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer})}))}}catch(i){this._log.warn(i)}t.enqueue(e)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(t/255),r=t%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<i;a++)n.push(255);n.push(r);let o=new DataView(e);return n.push(...new Uint8Array(o.buffer)),n.push(128),new bL(new DataView(new Uint8Array(n).buffer),!0)}},wL=0,PL=!1,DL=new Set,NL=!1,OL=class{constructor(e){bR(this,"userId"),bR(this,"tinyId"),bR(this,"_sdpSemantics"),bR(this,"_isUplink"),bR(this,"_room"),bR(this,"_log"),bR(this,"_signalChannel"),bR(this,"_isErrorObserved",!1),bR(this,"_waitForPeerConnectionConnectedPromise"),bR(this,"_waitForPeerConnectionConnectedPromiseReject",null),bR(this,"_peerConnection",null),bR(this,"_emitter",new AL.default),bR(this,"_currentState","DISCONNECTED"),bR(this,"_isReconnecting",!1),bR(this,"_reconnectionCount",0),bR(this,"_reconnectionTimer",-1),bR(this,"_isFirstConnection",!0),bR(this,"_prevTime",-1),bR(this,"_enableSEI"),bR(this,"_sei"),bR(this,"_localAddress"),bR(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=ZP.createLogger({id:"n",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&GD&&(this._sei=new kL(this,this._log,this._isUplink))}beforeConnect(){this._prevTime<0&&(this._prevTime=DP())}afterConnect(e){return wR(this,null,(function*(){try{yield e,this._isFirstConnection?(this._isFirstConnection=!1,qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",cost:Math.min(DP()-this._prevTime,3e4)})):this._isReconnecting&&qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",cost:DP()-this._prevTime}),this._prevTime=-1}catch(t){throw this._isFirstConnection?(this._isFirstConnection=!1,qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",error:t})):this._isReconnecting&&this._reconnectionCount>=3&&qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",error:t}),t}}))}initialize(){let e={encodedInsertableStreams:this._enableSEI&&GD,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(),this._sei&&(this._sei.destroy(),this._sei=null),DL.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 cD({code:aD.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return tb;let e=null;if(this._isUplink){if(!MD()||0===this._peerConnection.getSenders().length)return tb;e=this._peerConnection.getSenders()[0].transport}else{if(!OD()||0===this._peerConnection.getReceivers().length)return tb;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:tb}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===rb&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===nb||e.target.connectionState===ob){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new cD({message:r,code:aD.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===sb||e.target.connectionState===cb)&&(this.logSelectedCandidate(),TN.logSuccessEvent({userId:this._room.userId,eventType:hb}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(wL=0,PL=!1,NL=!0,DL.add(this)):DL.delete(this),qP.emit(XP.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 wR(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(CD(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 cD({code:aD.API_CALL_ABORTED,message:Xw({key:Ww,data:"leave room"})})))},n=()=>{qP.off(XP.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new cD({code:aD.API_CALL_TIMEOUT,message:"connection timeout"});wL+=1,(e=>wL>2&&!PL&&0===DL.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),PL=!0,this._emitter.emit("firewall-restriction")),t(e)}),1e4);qP.on(XP.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(qM,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=db()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new cD({code:this._isUplink?aD.UPLINK_RECONNECTION_FAILED:aD.DOWNLINK_RECONNECTION_FAILED,message:Xw({key:this._isUplink?sw:ow})});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(qM,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"))}};RR(zR());var ML=RR(XR()),LL=function(e){return ML.default.parse(e)},xL=function(e){return ML.default.write(e)};function VL(e){return Object.keys(e).filter((t=>e[t]))}RR(zR());var UL=class extends OL{constructor(e){super(ER(yR({},e),{isUplink:!1})),bR(this,"_flag",0),bR(this,"role","anchor"),bR(this,"remoteAudioTrack"),bR(this,"remoteVideoTrack"),bR(this,"remoteAuxiliaryTrack"),bR(this,"ssrc",{audio:0,video:0,auxiliary:0}),bR(this,"_isSDPExchanging",!1),this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new NO(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new OO(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new MO(this._room,this)}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 VP(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===jA?!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===$A?jA:kA;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=IA;i.kind===CA&&(n=r===jA?CA:kA);let o=this.remoteAudioTrack;n===CA?o=this.remoteVideoTrack:n===kA&&(o=this.remoteAuxiliaryTrack),o.setMediaStream(t),o.setMediaStreamTrack(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=LL(e);return t.media.forEach((e=>{e.type===CA&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),xL(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=LL(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),xL(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return wR(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===ib||(null==(r=this._peerConnection)?void 0:r.connectionState)===rb)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(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(tA){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(tA.message," ").concat(JSON.stringify(this.muteState))),new cD({code:aD.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):tA}}))}unsubscribe(e){return wR(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=yR({},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(VL(e),"]")),yield t.sendSubscription(n,e),"unsubscribe"===n&&(t.remoteAudioTrack.setMediaStreamTrack(null),t.remoteVideoTrack.setMediaStreamTrack(null),t.remoteAuxiliaryTrack.setMediaStreamTrack(null),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=uL,n=tL.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=hL,n=tL.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 cD({code:i.code,message:Xw({key:nw,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return wR(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(i){throw e.closePeerConnection(!0),i}}()}))}exchangeSDP(e){return wR(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:dL,commandDesc:"exchange sdp",data:r,responseCommand:tL.SUBSCRIBE_RESULT,timeout:1e4});if(!this._peerConnection){let e=new cD({code:aD.INVALID_OPERATION,message:Xw({key:Uw})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}}))}createOffer(){return wR(this,null,(function*(){let e={voiceActivityDetection:!1};xD()&&this._sdpSemantics===_b?(this._peerConnection.addTransceiver(IA,{direction:QA}),this._peerConnection.addTransceiver(CA,{direction:QA}),this._peerConnection.addTransceiver(CA,{direction:QA})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield TD();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=LL(e);return t.media.forEach((e=>{var t,i;if(e.type===CA){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(" ")}})),xL(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=LL(e);return t.media.forEach((e=>{e.type===IA&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),xL(t)}(t.sdp),this._sdpSemantics===_b&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)}))}onSubscribeResult(e){return wR(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===Rb)throw new cD({code:aD.NOT_SUPPORTED_H264,message:Xw({key:Ow})});try{if(0!==t)throw new cD({code:t,message:Xw({key:aw,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(n)),yield this._peerConnection.setRemoteDescription({type:r,sdp:n}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=e=>{this._emitter.emit("sei-message",ER(yR({},e),{userId:this.userId}))}),this.updateSSRC(n)}catch(Wx){throw this._log.error(Wx),Wx}}))}updateSSRC(e){try{LL(e).media.forEach((e=>{if(e.ssrcs)if(e.type===IA){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes($A)}));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($A)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes("224d130c-7b5c-415b-aaa2-79c2eb5a6df2")}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return wR(this,null,(function*(){if(!(kR(UL.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(e){let t=_P(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}},FL=UL;AR([yO((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 cD({code:aD.API_CALL_ABORTED,message:Xw({key:Ww,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],FL.prototype,"subscribe",1),AR([SO(OL.prototype.afterConnect),TO(OL.prototype.beforeConnect)],FL.prototype,"connect",1);var BL=FL;RR(zR()),RR(zR()),RR(zR());var jL=new Blob(["let width,height,offscreen,ctx;onmessage=function(e){const{action,data}=e.data;switch(action){case'render':offscreen=data.canvas;width=offscreen.width;height=offscreen.height;ctx=offscreen.getContext('2d');draw(data.readable,data.writable);break}};function draw(readable,writable){const transformer=new TransformStream({async transform(cameraFrame,controller){ctx.drawImage(cameraFrame,0,0,width,height);const frame=new VideoFrame(offscreen,{timestamp:cameraFrame.timestamp});cameraFrame.close();controller.enqueue(frame)}});readable.pipeThrough(transformer).pipeTo(writable)}"],{type:"application/javascript"}),HL=class{constructor(e){bR(this,"width"),bR(this,"height"),bR(this,"canvas"),bR(this,"offscreen"),bR(this,"smallGenerator"),bR(this,"smallWritable"),bR(this,"bigProcessor"),bR(this,"bigReadable"),bR(this,"worker");let{videoTrack:t}=e;this.width=void 0,this.height=void 0,this.canvas=null,this.offscreen=null,this.smallGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.smallWritable=this.smallGenerator.writable,this.bigProcessor=new MediaStreamTrackProcessor({track:t}),this.bigReadable=this.bigProcessor.readable,this.initWorker()}initWorker(){try{this.worker=new Worker(URL.createObjectURL(jL)),ZP.info("init worker processor success")}catch(KO){ZP.warn("init worker processor failed. ".concat(KO.error))}}setCanvasRect(e,t){this.width=e,this.height=t,this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t,this.offscreen=this.canvas.transferControlToOffscreen(),this.worker.postMessage({action:"render",data:{canvas:this.offscreen,readable:this.bigReadable,writable:this.smallWritable}},[this.offscreen,this.bigReadable,this.smallWritable])}generateVideoTrack(){let e=new MediaStream([this.smallGenerator]);return null==e?void 0:e.getTracks()[0]}destroy(){this.worker.terminate()}};RR(zR());var GL=class{constructor(e){bR(this,"_player"),bR(this,"_canvas"),bR(this,"_canvasCtx"),this._player=e,this._canvas=document.createElement("canvas"),this._canvasCtx=this._canvas.getContext("2d")}setCanvasRect(e,t){!this._canvas||(this._canvas.width=e,this._canvas.height=t)}drawVideoToCanvas(){let e=this._player.getElement();this._canvas&&this._canvasCtx&&e&&this._canvasCtx.drawImage(e,0,0,this._canvas.width,this._canvas.height)}generateVideoTrack(e){return this._canvas.captureStream(e).getVideoTracks()[0]}generateStreamFromTrack(e){let t=new MediaStream;return t.addTrack(e),t}destroy(){var e;null==(e=this._player)||e.stop(),this._canvas&&(this._canvas.width=0,this._canvas.height=0,this._canvas=null,this._canvasCtx=null)}get canvas(){return this._canvas}get canvasCtx(){return this._canvasCtx}get canDrawVideoToCanvas(){if(this._player){let e=this._player.getElement();if(e)return e.readyState===e.HAVE_ENOUGH_DATA}return!1}},WL=class{constructor(e){bR(this,"_player"),bR(this,"_processor"),bR(this,"_initOffscreenSuccess"),bR(this,"_localVideoTrack"),bR(this,"_interval"),this._localVideoTrack=e,this._player=e.player,this._processor=null,this._initOffscreenSuccess=!1}initialize(){return wR(this,null,(function*(){if(gD()&&(null==navigator?void 0:navigator.hardwareConcurrency)>=6)try{yield this.initOffscreen(),this._initOffscreenSuccess=!0,ZP.info("Initialize VideoGenerator successfully!")}catch(KO){this.initCanvas()}else this.initCanvas()}))}generateSmallVideoTrack(e){let t,i=this.getSmallVideoProfile(e);return this._initOffscreenSuccess?(this._processor.setCanvasRect(i.width,i.height),t=this._processor.generateVideoTrack(i.frameRate)):(this._processor.setCanvasRect(i.width,i.height),this._player.setRect(i.width,i.height),t=this._processor.generateVideoTrack(i.frameRate),this._interval=fN.run(Lb,this.render.bind(this),{fps:i.frameRate})),t}render(){this._processor instanceof GL&&this._processor.drawVideoToCanvas()}destroy(){fN.clearTask(this._interval),this._processor&&this._processor.destroy()}initOffscreen(){this._processor=new HL({videoTrack:this._localVideoTrack.mediaTrack})}initCanvas(){this._player=new zN({track:this._localVideoTrack.mediaTrack,muted:!0,objectFit:"cover",mirror:!1,container:null,id:"video-player",log:this._localVideoTrack.log}),this._player.play().then((()=>{ZP.info("VideoGenerator: play local video success")})).catch((()=>{ZP.error("VideoGenerator: Failed to play local video")})),this._processor=new GL(this._player)}getSmallVideoProfile(e){let t=this._localVideoTrack.mediaTrack,i=this._localVideoTrack.profile;if(jD){let e=t.getSettings();e&&e.width&&e.height&&(i.width=e.width,i.height=e.height)}let r,n=i.width*i.height,o=e.width*e.height;return ZP.info("big res: ".concat(i.width,"*").concat(i.height," small res: ").concat(e.width,"*").concat(e.height," ")),n>o?r=n/o:(ZP.warn("Small stream resolution is larger than big stream, which is invalid. big: ".concat(i.width," * ").concat(i.height," small: ").concat(e.width," * ").concat(e.height)),r=n/19200),{width:i.width/Math.sqrt(r),height:i.height/Math.sqrt(r),frameRate:e.frameRate}}},JL={voiceActivityDetection:!1},zL=class extends OL{constructor(e){super(ER(yR({},e),{isUplink:!0})),bR(this,"localMainAudioTrack",null),bR(this,"localMainVideoTrack",null),bR(this,"localAuxAudioTrack",null),bR(this,"localAuxVideoTrack",null),bR(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),bR(this,"_isPublishingAux",!1),bR(this,"_publishingLocalAudioTrack"),bR(this,"_publishingLocalVideoTrack"),bR(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}),bR(this,"_smallGenerator"),bR(this,"_audioManager"),this._audioManager=e.audioManager,this._smallGenerator=null}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&&(LD()?(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===IA?n.audio=!0:(n.bigVideo=!0,this._smallGenerator&&(n.smallVideo=!0)))})))}return n}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents(),this.localMainVideoTrack&&this.localMainVideoTrack.canvasTrack&&this.localMainVideoTrack.destoryCanvasTrack()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null)}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,a=super.emitConnectionStateChangedEvent(e);return a&&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}))),a}publish(e){return wR(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e;let o;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),r&&(t._publishingLocalVideoTrack=r),t._isPublishingAux=n,r&&!n&&r.small&&(t._smallGenerator=new WL(r),yield t._smallGenerator.initialize(),o=t._smallGenerator.generateSmallVideoTrack(r.small)),t.sendMediaSettings(),xD()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:o,isAuxiliary:n}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:r,smallTrack:o}),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)),null==(e=t._sei)||e.handleEncodedStreams(),t.installTrackMuteEvents(i,r),t.sendMutedFlag()}()}))}publishByTransceiver(e){return wR(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;r&&Yk&&Qk&&r.genCanvasTrack();let a=(null==r?void 0:r.canvasTrack)||(null==r?void 0:r.mediaTrack),s=t._audioManager.mediaStreamTrack;s&&e.addTrack(s),a&&e.addTrack(a);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(s||IA,{direction:qA,streams:[e]}),t._peerConnection.addTransceiver(o?CA:a||CA,{direction:qA,streams:[e]}),t._peerConnection.addTransceiver(n||CA,{direction:qA,streams:[e]}),t._peerConnection.addTransceiver(o&&a||CA,{direction:qA,streams:[e]}),yield t.connect();else{let e=[];if(s&&(c[0].sender.track||e.push(0),yield c[0].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:(null==i?void 0:i.profile.bitrate)||40,type:IA})),a){let i=o?3:1;yield c[i].sender.replaceTrack(a),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:CA,videoType:o?kA:bA}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:CA,videoType:AA}),e.push(2))}yield t.setTransceiverDirection(qA,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 wR(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.mediaTrack,o=null!=i&&i.mediaTrack?t._audioManager.mediaStreamTrack:null;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return o&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(r)));let a=new MediaStream;if(o&&a.addTrack(o),e&&a.addTrack(e),o&&t._peerConnection.addTrack(o,a),e&&(t._peerConnection.addTrack(e,a),n)){let e=new MediaStream;e.addTrack(n),t._peerConnection.addTrack(n,e)}yield t.connect()}()}))}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 wR(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!LD())return i&&i.mediaTrack&&!r&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):r&&r.mediaTrack&&!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==i?void 0:i.mediaTrack,o=null==r?void 0:r.mediaTrack,a=t._peerConnection.getSenders(),s=[];n&&(t._audioManager.removeAudioTrack(i),t._audioManager.isMixed||(yield a[0].replaceTrack(null),s.push(0),t.localMainAudioTrack=null)),o&&(e?(yield a[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=ER(yR({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=ER(yR({},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(KA,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 wR(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:cL,data:t,responseCommand:tL.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:lL,commandDesc:"unpublish",responseCommand:tL.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===aD.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),jD){if(i&&i.mediaTrack){let e=i.mediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(r&&r.mediaTrack){let e=r.mediaTrack.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.mediaTrack){let e=n.mediaTrack.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.mediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),r&&r.mediaTrack&&(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:yL,data:this._mediaSettings,responseCommand:tL.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return wR(this,null,(function*(){var t;if(!this._peerConnection)return;let i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(i?kA:jA," stream")),null==(t=this._sei)||t.handleEncodedStreams(),LD()?yield this.addTrackByTransceiver(e,i):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return wR(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers(),n=e.mediaTrack;if(e.kind===IA)this._audioManager.addAudioTrack(e),n=this._audioManager.mediaStreamTrack,yield r[0].sender.replaceTrack(n);else{let e=t?3:1;if(yield r[e].sender.replaceTrack(n),1===e&&(null==(i=this.localMainVideoTrack)?void 0:i.small)){this._smallGenerator=new WL(this.localMainVideoTrack),yield this._smallGenerator.initialize();let e=this._smallGenerator.generateSmallVideoTrack(this.localMainVideoTrack.small);yield r[2].sender.replaceTrack(e)}r[e].direction===KA&&(yield this.setTransceiverDirection(qA,[e]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return wR(this,null,(function*(){if(!e.mediaTrack)return;let t=e.mediaTrack;LD()&&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)}let{mediaStream:r}=e;if(this._peerConnection.addTrack(t,r),t.kind===CA&&e instanceof RO&&e.small){this._smallGenerator=new WL(e),yield this._smallGenerator.initialize();let t=this._smallGenerator.generateSmallVideoTrack(e.small),i=new MediaStream;i.addTrack(t),this._peerConnection.addTrack(t,i)}yield this.updateOffer("add",t)}))}isNeedToResetOfferOrder(){if(this._sdpSemantics===fb||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=LL(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===CA)return!0;return!1}removeSender(e){let t=null;LD()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&gP(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return wR(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?kA:jA," stream")),LD()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return wR(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===IA)this._audioManager.removeAudioTrack(e),this._audioManager.isMixed||(yield i[0].sender.replaceTrack(null));else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(KA,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return wR(this,null,(function*(){if(!$b)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._peerConnection.setLocalDescription(e)}let o=-1,a=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(KA,"|").concat(QA,"|").concat(qA,")")))&&o++,t.includes(o)){if(e===KA&&i.includes("a=".concat(QA)))return r=!0,"a=".concat(e);if(e===qA&&i.includes("a=".concat(KA)))return r=!0,"a=".concat(QA)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:a}))}))}removeTrackBySender(e){return wR(this,null,(function*(){var t,i;if(!e.mediaTrack)return;if(e.kind===CA&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),null==(i=null==(t=this.localMainVideoTrack)?void 0:t.mediaStream)||i.removeTrack(e.mediaTrack),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let r=this._peerConnection.getSenders().find((t=>t.track===e.mediaTrack));r&&(this.removeSender(r),e.kind===CA&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===CA&&this.removeSender(e)})))),yield this.updateOffer("remove",e.mediaTrack)}))}replaceTrack(e){return wR(this,null,(function*(){var t,i;let r=null==(t=this._peerConnection)?void 0:t.getSenders();if(!r||0===r.length||!e.mediaTrack)return;let n=e.mediaTrack,o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;if(this._log.info("is replacing ".concat(n.kind," track on ").concat(o?kA:jA," stream")),n.kind===IA&&r[0])this._audioManager.addAudioTrack(e),this._audioManager.isMixed&&(n=this._audioManager.mediaStreamTrack),yield r[0].replaceTrack(n);else if(n.kind===CA){if(!o&&r[1]&&(yield r[1].replaceTrack(n),this._smallGenerator&&r[2])){this._log.info("replacing smallVideo"),this._smallGenerator.destroy(),this._smallGenerator=new WL(this.localMainVideoTrack),yield this._smallGenerator.initialize();let e=this._smallGenerator.generateSmallVideoTrack((null==(i=this.localMainVideoTrack)?void 0:i.small)||this._room.smallStreamConfig);yield r[2].replaceTrack(e)}o&&r[3]&&(yield r[3].replaceTrack(n))}}))}updateOffer(e,t){return wR(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(JL);$b&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(i);let r=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===CA?"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:iL,data:n,responseCommand:tL.UPDATE_OFFER_RESULT,timeout:1e4,commandDesc:"update offer"}),{code:a,message:s}=o.data;0!==a&&this.checkPublishResultCode(a,s),yield this.acceptAnswer(o.data.data),i.sdp&&this.updateSSRC(i.sdp)}catch(i){throw this._log.error(i),i}}))}setBandwidth(e){return wR(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!BD())return o?r===CA?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e=0;r===CA&&(e=n===AA?2:n===kA?3:1);let a=t._peerConnection.getSenders()[e];if(a){let e=a.getParameters();(!e.encodings||0===e.encodings.length)&&(e.encodings=[{}]),e.encodings[0].maxBitrate=1e3*i;try{return yield a.setParameters(e),t._log.info("".concat(n||"").concat(r," bandwidth ").concat(i," kbps")),o}catch(s){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(s)),o)return r===CA?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";$b&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===AA?n=1:i===kA&&(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 $b&&(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 wR(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}}))}exchangeSDP(){return wR(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}}))}createOffer(){return wR(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(JL);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}}))}doExchangeSDP(){let e={command:sL,responseCommand:tL.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof bO||this.localAuxVideoTrack instanceof bO,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=LL(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),xL(r)}acceptAnswer(e){return wR(this,null,(function*(){var t,i,r,n,o;try{let a;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?kA:bA;a=yield this.setBandwidth({bandwidth:e,type:CA,sdp:a,videoType:t})}o&&(a=yield this.setBandwidth({bandwidth:o,type:IA,sdp:a}))}if(a=this.removeVideoOrientation(e.sdp),null!=(o=this._publishingLocalVideoTrack)&&o.small){let{smallStreamConfig:e}=this._room;a=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:CA,videoType:AA,sdp:a})}let s={type:e.type,sdp:a};yield this._peerConnection.setRemoteDescription(s),this._log.debug("accepted answer: ".concat(a))}catch(a){throw this._log.error("failed to accept remote answer ".concat(a)),a}}))}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(aL,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return wR(this,null,(function*(){if(!(kR(zL.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:lL,responseCommand:tL.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(e){let t=_P(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)&&qP.emit(XP.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{LL(e).media.forEach(((e,t)=>{if(e.type===IA){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===fb&&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(t){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:CA;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===kA&&t[3]&&t[3].track)return t[3].track.id;if(e===CA&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===CA){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===kA){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Rb?(this._log.error(zw.NOT_SUPPORTED_H264ENCODE),new cD({code:aD.NOT_SUPPORTED_H264,message:Xw({key:Nw})})):new cD({code:aD.UNKNOWN,message:Xw({key:xw,data:{signalResponse:tL.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}},KL=zL;AR([yO((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 cD({code:aD.API_CALL_ABORTED,message:Xw({key:Ww,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],KL.prototype,"publish",1),AR([SO(OL.prototype.afterConnect),TO(OL.prototype.beforeConnect)],KL.prototype,"connect",1);var qL=KL;RR(zR());RR(zR());var QL=RR(KR()),YL=class extends QL.default{constructor(e){let{signalChannel:t,room:i}=e;super(),bR(this,"_room"),bR(this,"_signalChannel"),bR(this,"_log"),bR(this,"_uplinkRTT",0),bR(this,"_uplinkLoss",0),bR(this,"_downlinkRTT",0),bR(this,"_downlinkLoss",0),bR(this,"_downlinkPrevStatMap",new Map),bR(this,"_downlinkLossAndRTTMap",new Map),bR(this,"_interval",-1),bR(this,"_uplinkNetworkQuality",0),bR(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=ZP.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 network quality change ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this._uplinkRTT,", loss: ").concat(this._uplinkLoss)),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 network quality change ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(t,", loss: ").concat(i))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(tL.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(KM,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.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,a=r.recvAudPkg+r.recvVidPkg,s=o-a;0===o&&0===a||(this._uplinkLoss=s<=0?0:Math.round(s/o*100),this._uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return wR(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)===sb}));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 a=0,s=this._downlinkPrevStatMap.get(e),c=r-s.totalPacketsLost,l=o-s.totalPacketsReceived;a=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:a,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;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 wR(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!OD())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&&SP(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===IA||e.mediaType===CA)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return t}catch(r){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state===YM?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state===$M&&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!==ab&&e.connectionState!==nb&&e.connectionState!==ob)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on(gN,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=fN.run(Mb,(()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];qP.emit(XP.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(YL.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss,downlinkInfo:e})}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.info("stop network quality calculating"),-1!==this._interval&&(fN.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})}}))}},XL=YL;bR(XL,"EVENT_NETWORK_QUALITY","0"),RR(zR(),1),RR(zR(),1),RR(zR(),1);var $L=new WeakMap;function ZL(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,a){let s=KP({retryFunction:a.value,settings:t,onError(t,r,n){i&&i.call(this,t,(()=>{var i;null!=(i=$L.get(e))&&i.has(o)?r():n(t)}),n)},onRetrying:(t,i)=>{var n;gP(r)&&r(t,i),null!=(n=$L.get(e))&&n.has(o)&&($L.get(e).get(o).stopRetry=i)},onRetryFailed:n});return a.value=function(){let t=$L.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}):$L.set(e,new Map([[o,{args:r}]])),s.apply(this,r).finally((()=>{var t;return null==(t=$L.get(e))?void 0:t.delete(o)}))},a}}function ex(e){let{fnName:t,callback:i,validateArgs:r=!0}=e;return function(e,n,o){let a=o.value;return o.value=function(){for(var n,o,s=arguments.length,c=new Array(s),l=0;l<s;l++)c[l]=arguments[l];if(null!=(n=$L.get(e))&&n.has(t)){let{stopRetry:n,args:a}=$L.get(e).get(t),s=!0;if(r)for(let e of a)if(!c.find((t=>t===e))){s=!1;break}s&&(i&&i.apply(this,c),n&&n(),null==(o=$L.get(e))||o.delete(t))}return a.apply(this,c)},o}}var tx=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._apiSuccessRateMap=new Map,this._eventMap=new Map,this._frameWorkType=e.frameWorkType||30,this._component=e.component||0,this.connectionType=e.connectionType||1,this._room=e.room,this._keyPrefix="key_point",this._log=ZP.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&gP(this[e])&&(this[e]=oP({fn:this[e],context:this}))})),this.initData(),this.installEvents(),this._intervalId=fN.run(Mb,this.setStorage.bind(this),{delay:2e4})}get _storageKey(){return"".concat(this._keyPrefix,"_").concat(this._room.userId)}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:eA,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:vA[rP()],uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType},this._pathJoinRoom={uint64_start_time:0,uint64_init_audio_start_time:0,uint64_init_audio_end_time:0,uint64_init_camera_start_time:0,uint64_init_camera_end_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_init_audio_ret:0,int32_init_camera_ret: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,this._apiSuccessRateMap.clear()}addEvent(e,t){return this._eventMap.set(e,t),qP.on(e,t),this}installEvents(){this._room.once("banned",(()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId}))),this.addEvent(XP.JOIN_START,this.handleJoinStart).addEvent(XP.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(XP.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(XP.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(XP.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(XP.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(XP.JOIN_FAILED,this.handleJoinFailed).addEvent(XP.LEAVE_START,this.handleLeaveStart).addEvent(XP.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(XP.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(XP.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(XP.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(XP.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(XP.PUBLISH_START,this.handlePublishStart).addEvent(XP.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(XP.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(XP.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(XP.PLAY_TRACK_START,this.handlePlayStart).addEvent(XP.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(XP.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!RP(t)||!this.hitTest(t.room)||"PLAYING"===i&&(r===IA?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(XP.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(XP.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(XP.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(XP.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,a=r.hasAudio||r.hasVideo||r.hasSmall,s=r.hasAuxiliary;!n&&a&&this.handleRemoteStreamAdded(r.userId,"main"),!o&&s&&this.handleRemoteStreamAdded(r.userId,"auxiliary")})).addEvent(XP.API_SUCCESS_RATE,this.handleAPISuccessRate)}uninstallEvents(){this._eventMap.forEach(((e,t)=>qP.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),fN.clearTask(this._intervalId)}handleJoinStart(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage())}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 cD?Number(i.getExtraCode()||i.getCode()):aD.UNKNOWN,this._pathJoinRoom.int32_end_ret=2))}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=3))}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}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=3),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:ER(yR({},nx),{msg_user_info:new ox({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:a,role:s}=i,c=new ox({userId:o,tinyId:a,role:"anchor"===s?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(!RP(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._remoteStreamStatMap.get(i);0===(null==r?void 0:r.playStreamTime)&&(r.playStreamTime=Date.now())}handleVideoLoadedData(e){let{track:t}=e;if(!RP(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._pathMainVideoMap.get(i);r&&0===r.statsToReport.uint64_combine_first_frame_time&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=Date.now(),r=this._pathMainVideoMap.get(t),n=this._remoteStreamStatMap.get(t);if(r&&(0===r.statsToReport.uint64_render_first_frame_time&&(r.statsToReport.uint64_render_first_frame_time=i),n)){let{statsToReport:e,playStreamTime:t,subscribedTime:o}=n;0===e.uint32_video_render_first&&t-o<=100&&(e.uint32_video_render_first=i-r.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(t);if(o&&n){let{statsToReport:e,playStreamTime:t,subscribedTime:r}=n;0===e.uint32_video_render_first&&t-r<=100&&(e.uint32_video_render_first=i-o.sendSubscribeCMDTime)}}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=this._pathMainAudioMap.get(t);i&&0===i.statsToReport.uint64_play_first_frame_time&&(i.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(e){this.hitTest(e.room)&&(this._networkQuality.totalUplinkLoss+=e.uplink.loss,this._networkQuality.totalUplinkRTT+=e.uplink.rtt,this._networkQuality.count++,e.downlinks.forEach((e=>{let{rtt:t,loss:i,userId:r,videoDelay:n,audioDelay:o}=e,a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=t,a.totalLoss+=i,n&&(a.totalVideoDelay=(a.totalVideoDelay||0)+n,a.videoDelayCount=(a.videoDelayCount||0)+1),o&&(a.totalAudioDelay=(a.totalAudioDelay||0)+o,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let e,a,s,c;n&&(a=n,s=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:a,audioDelayCount:c,videoDelayCount:s})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_up_stream_info:t,msg_down_stream_info:i}=e.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:i,uint32_video_width:r,uint32_video_height:n}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=i,this._localStreamStat.totalVideoWidth+=r,this._localStreamStat.totalVideoHeight+=n,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:e}=t.msg_audio_status;Math.floor(e/ew*100)>0&&(this._localStreamStat.totalAudioLevel+=e/ew,this._localStreamStat.audioLevelCount++)}i.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"),a=this._remoteStreamStatMap.get(r);if(a&&(t&&(null==o?void 0:o.remoteVideoTrack.isSubscribed)||i&&(null==o?void 0:o.remoteAuxiliaryTrack))){a.totalVideoFPS+=e.uint32_video_receive_fps,a.totalVideoBitrate+=e.uint32_video_codec_bitrate,a.videoCount++,0===a.statsToReport.uint32_video_width&&(a.statsToReport.uint32_video_width=e.uint32_video_width),0===a.statsToReport.uint32_video_height&&(a.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(a.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(a.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*TR(10,6)))}})),i){let e="".concat(n,"_","main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&(null==o?void 0:o.remoteAudioTrack.isSubscribed)&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,o.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=o.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/ew*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/ew,t.audioLevelCount++))}}))}}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&&0===this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&0===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&&0===this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&0===this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,r=i instanceof cD?i.getExtraCode()||i.getCode():{NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5}[i.name]||aD.UNKNOWN;1===t.mediaType&&0===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&&0===this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleAPISuccessRate(e){let{room:t,apiName:i,error:r,cost:n}=e;if(!this.hitTest(t))return;let o=ax[i],a={uint32_function_request_type:o,uint32_avg_value:0,uint32_max_value:0,uint32_request_count:1,uint32_success_count:0,msg_error_code:[]};if(r){let e=aD.UNKNOWN;r instanceof cD&&(e=r.extraCode||r.code),TN.uploadEvent({log:"stat-".concat(i,"-failed-").concat(e),userId:this._room.userId,error:r});let t={int32_error_code:e,error_count:1};a.msg_error_code.push(t)}else SP(n)&&(a.uint32_avg_value=n,a.uint32_max_value=n,a.uint32_success_count=1);let s=this._apiSuccessRateMap.get(o);s?(s.uint32_success_count+a.uint32_success_count>0&&(s.uint32_avg_value=(s.uint32_avg_value*s.uint32_success_count+a.uint32_avg_value)/(s.uint32_success_count+a.uint32_success_count)),s.uint32_max_value=Math.max(s.uint32_max_value,a.uint32_max_value),s.uint32_request_count+=1,s.uint32_success_count=s.uint32_success_count+a.uint32_success_count,a.msg_error_code.forEach((e=>{let t=s.msg_error_code.find((t=>t.int32_error_code===e.int32_error_code));t?t.error_count+=1:s.msg_error_code.push(e)}))):this._apiSuccessRateMap.set(o,a)}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&1&t.flag))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&8&t.flag))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&4&t.flag))>=0}hitTest(e){return e===this._room}checkStorage(){return wR(this,null,(function*(){try{let e=YD.getItem(this._storageKey);e&&(yield this.upload(e),YD.deleteItem(this._storageKey))}catch(KO){this._log.warn(KO)}}))}setStorage(){this.prepareReport();let e=this.getReportData();0!==e.msg_path_enter_room.uint64_start_time&&YD.setItem(this._storageKey,e)}prepareReport(){if(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:a,totalVideoDelay:s}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),n&&a&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(a/n),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&s&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(s/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,IA),e.statsToReport.uint32_video_play_time=n.getDuration(t,CA)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,rx);let{badCaseDetector:o}=this._room,{dataFreeze:a,count:s}=o.getDataFreezeDuration(t),{renderFreeze:c}=o.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=s,e.statsToReport.uint32_video_block_time=Math.min(a,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),o.isBlackStream(t)&&0===e.statsToReport.uint32_video_avg_fps?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0,(0===e.subscribeStartTime||e.subscribeStartTime-e.streamAddedTime>100||0===e.playStreamTime)&&(this._pathMainAudioMap.delete(t),this._pathMainVideoMap.delete(t),e.statsToReport.uint32_video_render_first=0)})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>rx&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+rx):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>rx&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+rx):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>rx&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+rx)}getReportData(){return{uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new ox({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:BP(this._signalInfo.relayIp),uint32_client_ip:BP(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(2147483648*Math.random()),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:BP(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,msg_function_request_stats:[...this._apiSuccessRateMap.values()]}}report(){return wR(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),YD.deleteItem(this._storageKey),this.initData()}catch(KO){this._log.warn(KO)}}))}upload(e){return wR(this,null,(function*(){if(Xk||0===e.msg_path_enter_room.uint64_start_time||[aA,sA,cA].findIndex((e=>e===location.host))>=0)return;let t=Number(this._room.sdkAppId),i=eP(t,pA),r=yield zP({url:i,body:JSON.stringify(e)});if("ok"!==r.data)throw"key point upload failed: ".concat(r.data)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}};AR([ZL({settings:{timeout:500,retries:3}})],tx.prototype,"upload",1);var ix,rx=5e3,nx={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},ox=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},ax=((ix=ax||{})[ix.enterRoom=50001]="enterRoom",ix[ix.exitRoom=50002]="exitRoom",ix[ix.switchRole=50003]="switchRole",ix[ix.destroy=50004]="destroy",ix[ix.startLocalAudio=50005]="startLocalAudio",ix[ix.updateLocalAudio=50006]="updateLocalAudio",ix[ix.stopLocalAudio=50007]="stopLocalAudio",ix[ix.startLocalVideo=50008]="startLocalVideo",ix[ix.updateLocalVideo=50009]="updateLocalVideo",ix[ix.stopLocalVideo=50010]="stopLocalVideo",ix[ix.startScreenShare=50011]="startScreenShare",ix[ix.updateScreenShare=50012]="updateScreenShare",ix[ix.stopScreenShare=50013]="stopScreenShare",ix[ix.enableAudioVolumeEvaluation=50014]="enableAudioVolumeEvaluation",ix[ix.startRemoteVideo=50015]="startRemoteVideo",ix[ix.updateRemoteVideo=50016]="updateRemoteVideo",ix[ix.stopRemoteVideo=50017]="stopRemoteVideo",ix[ix.muteRemoteAudio=50018]="muteRemoteAudio",ix[ix.setRemoteAudioVolume=50019]="setRemoteAudioVolume",ix[ix.startMixTranscode=50020]="startMixTranscode",ix[ix.stopMixTranscode=50021]="stopMixTranscode",ix[ix.startPublishCDNStream=50022]="startPublishCDNStream",ix[ix.stopPublishCDNStream=50023]="stopPublishCDNStream",ix[ix.PeerConnectionConnect=50024]="PeerConnectionConnect",ix[ix.PeerConnectionReconnect=50025]="PeerConnectionReconnect",ix[ix.WebsocketConnect=50026]="WebsocketConnect",ix[ix.WebsocketReconnect=50027]="WebsocketReconnect",ix[ix.schedule=50028]="schedule",ix[ix.SPCConnect=50029]="SPCConnect",ix[ix.SPCReconnect=50030]="SPCReconnect",ix),sx=tx;RR(zR(),1),RR(zR(),1);var cx=class{constructor(){bR(this,"_startTime"),bR(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=DP())}stop(){0===this._endTime&&(this._endTime=DP())}getDuration(){return 0===this._endTime?DP()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},lx=class{constructor(e){bR(this,"_room",null),bR(this,"_durationMap"),bR(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(XP.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(XP.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(XP.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"),IA),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_","main"),CA),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_","auxiliary"),CA);let a=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);!a||(!i.hasAudio&&r.hasAudio&&a.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,IA,"main"),!i.hasVideo&&r.hasVideo&&a.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,CA,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&a.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,CA,"auxiliary"))})),this._eventMap.forEach(((e,t)=>qP.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>qP.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);if(r.muteState.hasAudio&&"main"===i)if(r.remoteAudioTrack.isSubscribed){let e=new cx,t=this._durationMap.get(o);t?this.isRecording(t.audio)||t.audio.push(e):this._durationMap.set(o,{userId:n,type:i,audio:[e],video:[]})}else this.stopDurationItem(o,IA);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let e=new cx,t=this._durationMap.get(o);t?this.isRecording(t.video)||t.video.push(e):this._durationMap.set(o,{userId:n,type:i,audio:[],video:[e]})}else this.stopDurationItem(o,CA)}handleStreamStopped(e){let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);this.stopDurationItem(o,IA),this.stopDurationItem(o,CA)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new cx,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===IA?[n]:[],video:t===IA?[]:[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()}};RR(zR(),1);var dx=class{constructor(e){bR(this,"_room"),bR(this,"_renderFreezeMap",new Map),bR(this,"_isVideoPlayingEventFiredMap",new Map),bR(this,"_dataFreezeMap",new Map),bR(this,"_monitorFreezeData",new Map),bR(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(XP.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(XP.PLAY_TRACK_START,this.onPlayTrackStart).set(XP.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(XP.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(XP.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(RP(t)&&this.hitTest(t.room)&&n===CA){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===NA?this.onVideoTrackMuted(t):r===OA&&this.onVideoTrackUnmuted(t)}})).set(XP.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>qP.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>qP.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 cx;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 a=o.getDuration();a>500?this._monitorFreezeData.set(t,{userId:i,type:r,duration:a}):n.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return wR(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=DP();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=DP();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!RP(t)||!this.hitTest(t.room)||t.kind!==CA||t.hasFlag)return;let i="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(i)||this._isVideoPlayingEventFiredMap.set(i,!1)}getDataFreezeDuration(e){let t={dataFreeze:0,count:0},i=this._dataFreezeMap.get(e);if(i){if(i.isFreezing()){let e=i.durationItemList[i.durationItemList.length-1];e.stop(),e.getDuration()<500&&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=DP()-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()}};RR(zR(),1);var ux=RR($R(),1),hx=class{constructor(e){bR(this,"_room"),bR(this,"_log"),bR(this,"_config",null),bR(this,"_data"),bR(this,"_remoteVideoTrackMap",new Map),this._room=e,this._log=ZP.createLogger({id:"mix",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.installEvents()}get isPresetLayoutMode(){return this._config&&this._config.mode===gb.PRESET_LAYOUT}get isMixing(){return!!this._data}installEvents(){qP.on(XP.REMOTE_TRACK_SUBSCRIBED,this.onSubscribed,this),qP.on(XP.REMOTE_TRACK_UNSUBSCRIBED,this.onUnSubscribed,this),qP.on(XP.REMOTE_PUBLISH_STATE_CHANGED,this.onRemotePublishedChanged,this)}uninstallEvents(){qP.off(XP.REMOTE_TRACK_SUBSCRIBED,this.onSubscribed,this),qP.off(XP.REMOTE_TRACK_UNSUBSCRIBED,this.onUnSubscribed,this),qP.off(XP.REMOTE_PUBLISH_STATE_CHANGED,this.onRemotePublishedChanged,this)}reset(){this.uninstallEvents(),this._config=null}onSubscribed(e){let{track:t}=e;t.room!==this._room||t.kind!==CA||(this._remoteVideoTrackMap.set("".concat(t.userId,"_").concat(t.streamType),!1),this.isMixing&&this.hasAvailablePlaceHolder()&&this._config&&this.startMixTranscode(this._config))}onUnSubscribed(e){let{track:t}=e;t.room!==this._room||t.kind!==CA||this.handleRemoteTrackUnavailable("".concat(t.userId,"_").concat(t.streamType))}onRemotePublishedChanged(e){let{room:t,prevMuteState:i,muteState:r}=e;t===this._room&&(i.hasVideo&&!r.hasVideo&&this.handleRemoteTrackUnavailable("".concat(r.userId,"_","main")),i.hasAuxiliary&&!r.hasAuxiliary&&this.handleRemoteTrackUnavailable("".concat(r.userId,"_","auxiliary")))}handleRemoteTrackUnavailable(e){if(this._remoteVideoTrackMap.has(e)){let t=this._remoteVideoTrackMap.get(e);this._remoteVideoTrackMap.delete(e),this.isMixing&&this.isPresetLayoutMode&&t&&this._config&&this.startMixTranscode(this._config)}}startMixTranscode(e){return wR(this,null,(function*(){try{this.resetIsUsedFlag(),this._config=e;let t=this.getInputParam(e),i=this.getOutputParam(e),r=this.getOutputSessionId({config:e,roomId:this._room.roomId,userId:this._room.userId});this.isMixing&&this._data&&r!==this._data.outputSessionId&&(this._log.info("startMixTranscode() streamId changed, stop mixing before start"),yield this.doStopMixTranscode()),yield this.doStartMixTranscode({outputSessionId:r,inputParam:t,outputParam:i})}catch(t){throw this.resetIsUsedFlag(),t}}))}doStartMixTranscode(e){return wR(this,arguments,(function(e){var t=this;let{outputSessionId:i,inputParam:r,outputParam:n}=e;return function*(){let e={roomId:String(t._room.roomId),mcuRequestTime:Date.now(),outputSessionId:i,inputParam:r,outputParam:n};t._log.info("startMixTranscode: ".concat(JSON.stringify(e)));let o=yield t._room.sendStartMixTranscode(e),{code:a}=o.data,{message:s}=o.data;if(0!==a)throw-102083===a&&(s="Please enable relayed-push in ".concat(lA," and try later, refer to ").concat(uA,"tutorial-26-advanced-publish-cdn-stream.html")),t._log.error("startMixTranscode failed, errCode: ".concat(a," errMsg: ").concat(s)),new cD({code:aD.START_MIX_TRANSCODE_FAILED,message:Xw({key:Aw,data:{message:s},link:{className:"Client",fnName:"startMixTranscode"}})});t._data=e}()}))}reStartMixTranscode(){!this.isMixing||this._config&&this.startMixTranscode(this._config)}stopMixTranscode(){return wR(this,null,(function*(){if(!this.isMixing)throw new cD({code:aD.INVALID_OPERATION,message:Xw({key:kw})});yield this.doStopMixTranscode(),this.resetIsUsedFlag()}))}doStopMixTranscode(){return wR(this,null,(function*(){let e={mcuRequestTime:Date.now(),outputSessionId:this._data.outputSessionId,streamType:this._data.outputParam.streamType};this._log.info("stopMixTranscode: ".concat(JSON.stringify(e)));let t=yield this._room.sendStopMixTranscode(e),{code:i,message:r}=t.data;if(0!==i)throw this._log.error("stopMixTranscode failed, errCode: ".concat(i," errMsg: ").concat(r)),new cD({code:aD.STOP_MIX_TRANSCODE_FAILED,message:Xw({key:bw,data:{message:r},link:{className:"Client",fnName:"stopMixTranscode"}})});this._data=void 0}))}getOutputSessionId(e){let{config:t,userId:i,roomId:r}=e;return TP(t.streamId)&&t.streamId.length>0?t.streamId:(0,ux.default)("".concat(r,"_").concat(i,"_main"))}getInputParam(e){let t=e.mixUsers.map((e=>({userId:e.userId,roomId:String(e.roomId||this._room.roomId),width:e.width||0,height:e.height||0,locationX:e.locationX||0,locationY:e.locationY||0,zOrder:e.zOrder,streamType:vP(e.streamType)||e.streamType!==eb?0:1,inputType:e.pureAudio?Tb.IT_PURE_AUDIO:Tb.IT_AUDIO_VIDEO,renderMode:e.renderMode||0})));return e.mode===gb.PRESET_LAYOUT&&(t.forEach((e=>{if(e.userId===vb.REMOTE){let t=[...this._remoteVideoTrackMap.entries()].find((e=>{let[,t]=e;return!t}));if(t){let[i]=t,r=i.split("_");e.userId=r.slice(0,r.length-1).join("_"),e.streamType="auxiliary"===r.splice(-1)[0]?1:0,this._remoteVideoTrackMap.set(i,!0)}}})),t=t.filter((e=>e.userId!==vb.REMOTE))),t}getOutputParam(e){let t=e.streamId||"";return{streamId:t,streamType:t.length>0?1:0,width:vP(e.videoWidth)?640:e.videoWidth,height:vP(e.videoHeight)?480:e.videoHeight,videoBps:e.videoBitrate||0,fps:e.videoFramerate||15,gop:e.videoGOP||2,audioSampleRate:e.audioSampleRate||48e3,audioBps:e.audioBitrate||64,audioChannels:e.audioChannels||1,backgroundColor:e.backgroundColor||0,backgroundImg:e.backgroundImage||"",extraInfo:"",videoCodec:2,audioCodec:0}}hasAvailablePlaceHolder(){var e,t;return!(!this.isPresetLayoutMode||(null==(e=this._data)?void 0:e.inputParam.length)===(null==(t=this._config)?void 0:t.mixUsers.length))}resetIsUsedFlag(){this._remoteVideoTrackMap.forEach(((e,t)=>{this._remoteVideoTrackMap.set(t,!1)}))}};RR(zR(),1);var px=RR($R(),1);function mx(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:jA;return t=Zw(e)?i===jA?kb:wb:i===jA?Ab:bb,"https://".concat(t,"/api/v1/config")}function _x(e,t,i){return new Promise(((r,n)=>{zP({url:e,body:t,timeout:i.timeout}).then((e=>{0===e.data.code?r(e.data.data):n({code:e.data.code,message:e.data.msg})})).catch(n)}))}RR(zR(),1);var fx=(e,t)=>KP({retryFunction:_x,settings:{retries:3,timeout:0},onError:t,onRetrying:e});function gx(e,t,i){return new Promise(((r,n)=>{let o=null;PP([fx((e=>t.count[0]=e+1),((e,i)=>{t.msg[0]=e.message,o||i()}))(mx(i,jA),e,{get timeout(){return 1e3*mP(2+t.count[0])}}),fx((e=>t.count[1]=e+1),((e,i)=>{t.msg[1]=e.message,o||i()}))(mx(i,HA),e,{get timeout(){return 1e3*mP(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}var vx=0,Tx=class extends uN{constructor(e){super("room"),this.seq=++vx,this.role="anchor",this.localTracks=new Set,this.enableAutoPlayDialog=!0,this.autoReceiveAudio=!0,this.autoReceiveVideo=!0,this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this._log=ZP.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this._isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,yP(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),yP(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),yP(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this.keyPointManager=new sx({room:this,frameWorkType:e.frameWorkType,component:e.component}),this.callDurationCalculator=new lx({room:this}),this.badCaseDetector=new dx({room:this}),this.mixTranscodeManager=new hx(this),this.publishCDNManager=new class{constructor(e){bR(this,"_room"),bR(this,"_publishTencentMainStreamObj",{params:null,streamId:void 0,isPublishing:!1}),bR(this,"_publishTencentAuxStreamObj",{params:null,streamId:void 0,isPublishing:!1}),bR(this,"_publishGivenCDNData",null),bR(this,"_isPublishingGivenCDN",!1),this._room=e}get _isPublishingTencentCDN(){return this._publishTencentMainStreamObj.isPublishing||this._publishTencentAuxStreamObj.isPublishing}generatePublishCDNStreamId(e,t){if(!e){let e="".concat(this._room.roomId,"_").concat(this._room.userId,"_").concat(this.convertStreamType(t));return/^[A-Za-z\d_-]*$/.test(e)||(e=(0,px.default)(e)),"".concat(this._room.sdkAppId,"_").concat(e)}return e}convertStreamType(e){return"main"===e?e:"aux"}generatePublishCDNSessionId(e){return(0,px.default)("".concat(this._room.roomId,"_").concat(this._room.userId,"_").concat(this.convertStreamType(e)))}startPublishCDN(e){return wR(this,null,(function*(){let{streamId:t="",streamType:i="main",appId:r,bizId:n,url:o}=e;yield this.startPublishTencentCDN({streamId:t,streamType:i}),r&&n&&o&&(yield this.startPublishGivenCDN({streamType:i,appId:r,bizId:n,url:o}))}))}stopPublishCDN(){return wR(this,null,(function*(){if(!this._isPublishingTencentCDN)throw new cD({code:aD.INVALID_OPERATION,message:Xw({key:yw})});yield this.stopPublishTencentCDN(),this._isPublishingGivenCDN&&(yield this.stopPublishGivenCDN())}))}startPublishTencentCDN(e){return wR(this,null,(function*(){if("auxiliary"===e.streamType?(this._publishTencentAuxStreamObj.params=e,this._publishTencentAuxStreamObj.isPublishing=!0):(this._publishTencentMainStreamObj.params=e,this._publishTencentMainStreamObj.isPublishing=!0),!this._room.isJoined)return;let t=this.generatePublishCDNStreamId(e.streamId,e.streamType),i=this.generatePublishCDNSessionId(e.streamType),r="auxiliary"===e.streamType?1:0,n={requestTime:Date.now(),sessionId:i,streamId:t,streamType:r};yield this.doStartPublishTencentCDN(n,e.streamType)}))}doStartPublishTencentCDN(e,t){return wR(this,null,(function*(){try{ZP.info("startPublishTencentCDN: ".concat(JSON.stringify(e)));let i=yield this._room.sendStartPublishCDN(e,!0),{code:r}=i.data,{message:n}=i.data;if(0!==r)throw"auxiliary"===t?this._publishTencentAuxStreamObj.isPublishing=!1:this._publishTencentMainStreamObj.isPublishing=!1,-102083===r&&(n="Please enable relayed-push in ".concat(lA," and try later, refer to ").concat(uA,"tutorial-26-advanced-publish-cdn-stream.html")),ZP.error("startPublishTencentCDN failed, errCode: ".concat(r,", errMsg: ").concat(n)),new cD({code:aD.START_PUBLISH_CDN_FAILED,message:Xw({key:Ew,data:{message:n},link:{className:"Client",fnName:"startPublishCDNStream"}})});"auxiliary"===t?this._publishTencentAuxStreamObj.streamId=e.streamId:this._publishTencentMainStreamObj.streamId=e.streamId}catch(i){throw"auxiliary"===t?this._publishTencentAuxStreamObj.isPublishing=!1:this._publishTencentMainStreamObj.isPublishing=!1,i}}))}resetPublishTencentParam(e){"main"===e&&(this._publishTencentMainStreamObj={params:null,streamId:void 0,isPublishing:!1}),"auxiliary"===e&&(this._publishTencentAuxStreamObj={params:null,streamId:void 0,isPublishing:!1})}stopPublishTencentCDN(){return wR(this,null,(function*(){if(!this._room.isJoined)return this.resetPublishTencentParam("main"),void this.resetPublishTencentParam("auxiliary");this._publishTencentMainStreamObj.isPublishing&&(yield this.doStopPublishTencentCDN("main")),this._publishTencentAuxStreamObj.isPublishing&&(yield this.doStopPublishTencentCDN("auxiliary"))}))}doStopPublishTencentCDN(e){return wR(this,null,(function*(){let t={requestTime:Date.now(),sessionId:(0,px.default)("".concat(this._room.roomId,"_").concat(this._room.userId,"_").concat(this.convertStreamType(e)))};ZP.info("stopPublishTencentCDN: ".concat(JSON.stringify(t)));let i=yield this._room.sendStopPublishCDN(t,!0),{code:r,message:n}=i.data;if(0===r)this.resetPublishTencentParam(e);else{if(-102069!==r)throw ZP.error("stopPublishTencentCDN failed, errCode: ".concat(r," errMsg: ").concat(n)),new cD({code:aD.STOP_PUBLISH_CDN_FAILED,message:Xw({key:Iw,data:{message:n},link:{className:"Client",fnName:"stopPublishCDNStream"}})});ZP.warn("stopPublishTencentCDN failed, can not stopPublishTencentCDN in auto relayed-push mode"),this.resetPublishTencentParam(e)}}))}startPublishGivenCDN(e){return wR(this,null,(function*(){let t="main"===e.streamType?this._publishTencentMainStreamObj.streamId:this._publishTencentAuxStreamObj.streamId,i={pushRequestTime:Date.now(),pushAppId:e.appId,pushBizId:e.bizId,pushCdnUrl:e.url,pushStreamType:this.convertStreamType(e.streamType),pushStreamId:t};if(ZP.info("startPublishGivenCDN: ".concat(JSON.stringify(i))),this._publishGivenCDNData=i,this._isPublishingGivenCDN=!0,this._room.isJoined)try{let e=yield this._room.sendStartPublishCDN(i,!1),{code:t,message:r}=e.data;if(0!==t)throw ZP.error("startPublishGivenCDN failed, errCode: ".concat(t,", errMsg: ").concat(r)),this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1,new cD({code:aD.START_PUBLISH_CDN_FAILED,message:Xw({key:Ew,data:{message:r},link:{className:"Client",fnName:"startPublishCDNStream"}})})}catch(r){throw this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1,r}}))}stopPublishGivenCDN(){return wR(this,null,(function*(){if(!this._room.isJoined||!this._publishGivenCDNData)return this._publishGivenCDNData=null,void(this._isPublishingGivenCDN=!1);let{pushAppId:e,pushBizId:t,pushCdnUrl:i,pushStreamType:r}=this._publishGivenCDNData,n={pushRequestTime:Date.now(),pushAppId:e,pushBizId:t,pushCdnUrl:i,pushStreamType:r};ZP.info("stopPublishGivenCDN: ".concat(JSON.stringify(n)));let o=yield this._room.sendStopPublishCDN(n,!1),{code:a,message:s}=o.data;if(0!==a)throw ZP.error("stopPublishGivenCDN failed, errCode: ".concat(a," errMsg: ").concat(s)),new cD({code:aD.STOP_PUBLISH_CDN_FAILED,message:Xw({key:Iw,data:{message:s},link:{className:"Client",fnName:"stopPublishCDNStream"}})});this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1}))}handleCDNConfigForJoinData(e){let t,i=e;if(this._publishTencentMainStreamObj.isPublishing||this._publishTencentAuxStreamObj.isPublishing){let e={};TP(i)&&(e=JSON.parse(i)),e.Str_uc_params||(e.Str_uc_params={}),this._publishTencentMainStreamObj.isPublishing&&(this._publishTencentMainStreamObj.streamId?e.Str_uc_params.userdefine_streamid_main=this._publishTencentMainStreamObj.streamId:this._publishTencentMainStreamObj.params&&(e.Str_uc_params.userdefine_streamid_main=this.generatePublishCDNStreamId(this._publishTencentMainStreamObj.params.streamId,"main"))),this._publishTencentAuxStreamObj.isPublishing&&(this._publishTencentAuxStreamObj.streamId?e.Str_uc_params.userdefine_streamid_aux=this._publishTencentAuxStreamObj.streamId:this._publishTencentAuxStreamObj.params&&(e.Str_uc_params.userdefine_streamid_aux=this.generatePublishCDNStreamId(this._publishTencentAuxStreamObj.params.streamId,"auxiliary"))),i=JSON.stringify(e)}if(this._isPublishingGivenCDN&&this._publishGivenCDNData){let{pushAppId:e,pushBizId:i,pushCdnUrl:r,pushStreamType:n,pushStreamId:o}=this._publishGivenCDNData;t={pushRequestTime:Date.now(),pushAppId:e,pushBizId:i,pushCdnUrl:r,pushStreamType:n,pushStreamId:o}}return{bussinessInfo:i,pushUserCdnInfo:t}}reset(){this.resetPublishTencentParam("main"),this.resetPublishTencentParam("auxiliary"),this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1}}(this)}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}getLogger(){return this._log}get isJoined(){return"joined"===this.state}addTrack(e){return wR(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return wR(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return wR(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}getRemoteAudioStats(){return wR(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return wR(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 wR(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 cD({code:aD.INVALID_OPERATION,message:Xw({key:Rw,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(zw.INVALID_DESTROY),new cD({code:aD.INVALID_OPERATION,message:Xw({key:fw})});this._log.info("destroy room"),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this._isDestroyed=!0,qP.emit(XP.ROOM_DESTROY,{room:this})}startMixTranscode(e){return this.mixTranscodeManager.startMixTranscode(e)}stopMixTranscode(){return this.mixTranscodeManager.stopMixTranscode()}startPublishCDNStream(){return wR(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){if(e._log.info("startPublishCDNStream with params: ".concat(JSON.stringify(t),"; isJoined: ").concat(e.isJoined,"; hasMainStream: ").concat(e.isMainStreamPublished,"; hasAuxStream: ").concat(!!e.isAuxStreamPublished,";")),e.isJoined){if("main"===t.streamType&&!e.isMainStreamPublished)throw new cD({code:aD.INVALID_OPERATION,message:Xw({key:Sw})});if("auxiliary"===t.streamType&&!e.isAuxStreamPublished)throw new cD({code:aD.INVALID_OPERATION,message:Xw({key:Sw})})}yield e.publishCDNManager.startPublishCDN(t)}()}))}stopPublishCDNStream(){return this.publishCDNManager.stopPublishCDN()}schedule(e,t,i){return wR(this,null,(function*(){var r,n;let o=DP();try{let a=yield function(e){return wR(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:n,userSig:o,version:a,frameWorkType:s}=e;return function*(){let e={delta:0,count:[1,1],msg:[]};try{let c=new FormData;c.append("userId",String(t)),c.append("sdkAppId",String(i)),c.append("isStrGroupId",String(r)),c.append("groupId",String(n)),c.append("sdkVersion",a),c.append("userSig",String(o)),c.append("frameWorkType",String(s));let l=DP(),d=yield gx(c,e,i);return e.delta=DP()-l,d}catch(c){let e=IP(c)?c[0]:c,t=SP(e.code)?e.code:0,i="get websocket url failed: ".concat(e.message.includes("timeout")?"timeout":e.message),r=new cD({code:aD.SCHEDULE_FAILED,extraCode:t,message:Xw({key:mw,data:{error:i,code:t}})});throw ZP.error(r),r}}()}))}({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:i,userSig:this.userSig,frameWorkType:t});this._log.info("schedule: ".concat(JSON.stringify(a))),this.scheduleResult=yR(yR({},this.scheduleResult),a),SP(null==(r=a.config)?void 0:r.retryCount)&&function(e){lb=e}(a.config.retryCount),TP(null==(n=a.config)?void 0:n.loggerDomain)&&oA(a.config.loggerDomain),qP.emit(XP.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult}),qP.emit(XP.API_SUCCESS_RATE,{room:this,apiName:"schedule",cost:DP()-o})}catch(a){throw qP.emit(XP.API_SUCCESS_RATE,{room:this,apiName:"schedule",error:a}),a}}))}};RR(zR(),1);var Sx=new WeakMap,yx=new WeakMap;function Ex(){return function(e,t,i){let r=i.value,n=e=>{let{fn:t,args:i,context:r,resolve:n,reject:o}=e;t.apply(r,i).then(n,o)};return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return new Promise(((e,i)=>{if(Sx.has(this)){let o=Sx.get(this),{length:a}=o;o.push({fn:r,args:t,context:this,resolve:e,reject:i}),0===a&&n({fn:r,args:t,context:this,resolve:e,reject:i})}else Sx.set(this,[{fn:r,args:t,context:this,resolve:e,reject:i}]),n({fn:r,args:t,context:this,resolve:e,reject:i})})).finally((()=>{let e=Sx.get(this);e&&(e.shift(),e[0]&&n(yR({},e[0])))}))},i}}function Ix(e){return function(t,i,r){let n=r.value,o=t=>SP(e)?t[e]:e(...t),a=e=>{let{fn:t,args:i,context:r,resolve:n,reject:s}=e;t.apply(r,i).then(n,s).finally((()=>{if(yx.has(r)&&yx.get(r).has(o(i))){let e=yx.get(r).get(o(i));e&&(e.shift(),e[0]&&a(yR({},e[0])))}}))};return r.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return new Promise(((e,i)=>{if(yx.has(this))if(yx.get(this).has(o(t))){let r=yx.get(this).get(o(t));if(r){let{length:o}=r;r.push({fn:n,args:t,context:this,resolve:e,reject:i}),0===o&&a({fn:n,args:t,context:this,resolve:e,reject:i})}}else yx.get(this).set(o(t),[{fn:n,args:t,context:this,resolve:e,reject:i}]),a({fn:n,args:t,context:this,resolve:e,reject:i});else{let r=new Map;r.set(o(t),[{fn:n,args:t,context:this,resolve:e,reject:i}]),yx.set(this,r),a({fn:n,args:t,context:this,resolve:e,reject:i})}}))},r}}RR(zR(),1);var Cx=RR(KR(),1),Rx=Symbol("instance"),Ax=Symbol("abortCtrl"),bx=Symbol("cacheResult"),kx=class{constructor(e,t,i){bR(this,"oldState"),bR(this,"newState"),bR(this,"action"),bR(this,"error"),this.oldState=e,this.newState=t,this.action=i}toString(){return"".concat(this.action,"ing")}},wx=class extends Error{constructor(e,t,i){super(t),bR(this,"state"),bR(this,"message"),bR(this,"cause"),this.state=e,this.message=t,this.cause=i}},Px=new Map,Dx=Object.getPrototypeOf(wR(void 0,null,(function*(){}))).constructor;function Nx(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,n,o)=>{let a=i.action||n;if(!i.context){let i=Px.get(r)||[];Px.has(r)||Px.set(r,i),i.push({from:e,to:t,action:a})}let s=o.value;o.value=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return wR(this,null,(function*(){var r;let o=this;if(i.context&&(o=Ux.get("function"==typeof i.context?i.context.call(this,...n):i.context)),o.state===t)return o[bx];let c=null;if(Array.isArray(e)?0==e.length?o[Ax]&&(o[Ax].aborted=!0):("string"!=typeof o.state||!e.includes(o.state))&&(c=new wx(o._state,"".concat(o.name," ").concat(a," to ").concat(t," failed: current state ").concat(o._state," not in from config"))):e!==o.state&&(c=new wx(o._state,"".concat(o.name," ").concat(a," to ").concat(t," failed: current state ").concat(o._state," not from ").concat(e))),c){if(!i.fail){if(i.ignoreError)return c;throw c}i.fail.call(this,c)}let l=o.state;Mx.call(o,new kx(l,t,a));let d={aborted:!1};o[Ax]=d;try{let e=s.apply(this,n);return o[bx]=e instanceof Dx?yield e:e,d.aborted||(o[Ax]=void 0,Mx.call(o,t),null==(r=i.success)||r.call(this,o[bx])),o[bx]}catch(u){let e=u instanceof Error?u.message:String(u);if(Mx.call(o,l,e),!i.fail){if(i.ignoreError)return u;throw u}i.fail.call(this,new wx(o._state,"action '".concat(a,"' failed :").concat(e),u instanceof Error?u:new Error(e)))}}))}}}var Ox="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 Mx(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(Ux.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t})}var Lx,xx,Vx=class extends Cx.default{constructor(e,t,i){super(),bR(this,"name"),bR(this,"groupName"),bR(this,"_state",Vx.INIT),bR(this,Lx),bR(this,xx),this.name=e,this.groupName=t,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let r=i[Rx];r?this.name=r.name+"-"+r.count++:i[Rx]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=Px.get(e)||[],i=new Set,r=[],n=[],o=new Set,a=Object.getPrototypeOf(e);Px.has(a)&&(a.stateDiagram.forEach((e=>i.add(e))),a.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 s=[...i];return Object.defineProperty(this,"stateDiagram",{value:s}),s}static get(e){let t;return"string"==typeof e?(t=Vx.instances.get(e),t||Vx.instances.set(e,t=new Vx(e,void 0,Object.create(Vx.prototype)))):(t=Vx.instances2.get(e),t||Vx.instances2.set(e,t=new Vx(e.constructor.name,void 0,Object.create(Vx.prototype)))),t}static getState(e){var t;return null==(t=Vx.get(e))?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Ox(Vx.UPDATEAFSM,yR({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){Mx.call(this,e)}},Ux=Vx;Lx=bx,xx=Ax,bR(Ux,"STATECHANGED","stateChanged"),bR(Ux,"UPDATEAFSM","updateAFSM"),bR(Ux,"INIT","[*]"),bR(Ux,"ON","on"),bR(Ux,"OFF","off"),bR(Ux,"instances",new Map),bR(Ux,"instances2",new WeakMap),RR(zR());var Fx=RR(KR());RR(zR());var Bx=RR(XR()),jx=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,o=LL(r),a={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},s={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:zA,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:IA,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 a.media.push(s),[1,2,3].forEach((e=>{a.media.push(Hx({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),n&&a.media.push(o.media.find((e=>"dc"===e.mid))),xL(a)},Hx=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,useAllCodec:o=!1}=e,a={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:zA,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:CA,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(i.video.codecs.length>0)if(o)for(let s=0;s<i.video.codecs.length;s++)Gx(a,i.video.codecs[s]);else{let e=i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264")));Gx(a,i.video.codecs[e])}else if(o)for(let s=0;s<r.video.codecs.length;s++)Gx(a,r.video.codecs[s]);else Gx(a,r.video.codecs[0]);return a.payloads=a.payloads.trim(),a},Gx=(e,t)=>{e.payloads="".concat(e.payloads," ").concat(t.payload),e.fmtp.push({payload:t.payload,config:t.fmtp}),e.rtcpFb=[...e.rtcpFb||[],...(t.rtcpfb||t.rtcpFb).map((e=>({payload:t.payload,type:e.id,subtype:e.params[0]})))],e.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(e.payloads="".concat(e.payloads," ").concat(t.rtx),e.fmtp.push({payload:t.rtx,config:"apt=".concat(t.payload)}),e.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))};var Wx,Jx=e=>{let t=Bx.default.parse(e);return t.media.forEach((e=>{var i;(e.type===IA||e.type===CA)&&(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===CA&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===IA&&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)),(null==(i=e.payloads)?void 0:i.includes("datachannel"))&&t.groups&&e.mid&&(t.groups[0].mids=t.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),Bx.default.write(t)},zx=((Wx=zx||{}).TRACK="track",Wx.DATA_CHANNEL_MESSAGE="data_channel_msg",Wx[Wx.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",Wx[Wx.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",Wx.RECONNECTED="spc-reconnected",Wx.RECONNECT_FAILED="spc-reconnect-failed",Wx.ERROR="error",Wx),Kx=0,qx=!1,Qx=new Set,Yx=class extends Fx.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),bR(this,"currentState","DISCONNECTED"),bR(this,"_room"),bR(this,"_signalChannel"),bR(this,"_peerConnection",null),bR(this,"_datachannel",null),bR(this,"_enableCustomMessage"),bR(this,"_log"),bR(this,"_downlinkMIDMap",new Map),bR(this,"_reconnectionTimer",-1),bR(this,"reconnectionCount",0),bR(this,"_clientAbility",null),bR(this,"_serverAbility",null),bR(this,"addDownlinkQueue",new Set),bR(this,"removeDownlinkQueue",new Set),bR(this,"_parsedAnswer",null),bR(this,"_updateSDPPromise",null),bR(this,"_waitForPCConnectedPromise"),bR(this,"_waitForPCConnectedPromiseReject",null),bR(this,"_isSDPLogged",!1),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=ZP.createLogger({id:"spc",userId:this._room.userId,sdkAppId:this._room.sdkAppId})}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}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.useVp8),e}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=LL(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&&!vP(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}}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0}initialize(){return wR(this,null,(function*(){try{this._peerConnection=new RTCPeerConnection({offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.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 $x(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(IA,{direction:JA}),this._peerConnection.addTransceiver(CA,{direction:JA}),this._peerConnection.addTransceiver(CA,{direction:JA}),this._peerConnection.addTransceiver(CA,{direction:JA});let e=yield this._peerConnection.createOffer();return yield this.setOffer(e),this._clientAbility=((e,t)=>{var i,r;let n=LL(e),o={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:t};o.ice.ufrag=String(n.media[0].iceUfrag),o.ice.password=n.media[0].icePwd||"",n.fingerprint&&(o.dtls.hash=n.fingerprint.type,o.dtls.fingerprint=n.fingerprint.hash,o.dtls.setup=n.setup||""),n.media[0].fingerprint&&(o.dtls.hash=n.media[0].fingerprint.type,o.dtls.fingerprint=n.media[0].fingerprint.hash),o.dtls.setup=n.media[0].setup||"";let a=n.media[0],s=n.media[1];a.ext&&(o.audio.extensions=a.ext.map((e=>({id:e.value,uri:e.uri})))),s.ext&&(o.video.extensions=s.ext.map((e=>({id:e.value,uri:e.uri}))));let c={codec:a.rtp[0].codec,fmtp:a.fmtp[0].config,payload:a.fmtp[0].payload,rate:a.rtp[0].rate,channel:a.rtp[0].encoding,rtcpFb:[],rtx:0};null==(i=a.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:r}=e;if(t===c.payload){let e={id:i,params:[]};r&&e.params.push(r),c.rtcpFb.push(e)}})),o.audio.codecs.push(c);for(let l=0;l<s.rtp.length;l++){if(["rtx","red","ulpfec"].includes(s.rtp[l].codec))continue;let e=s.fmtp.filter((e=>e.payload===s.rtp[l].payload))[0];o.video.codecs.push({payload:s.rtp[l].payload,codec:s.rtp[l].codec,fmtp:e?e.config:"",rate:s.rtp[l].rate,rtx:"rtx"===(null==(r=s.rtp[l+1])?void 0:r.codec)?s.rtp[l+1].payload:0,rtcpFb:((null==s?void 0:s.rtcpFb)||[]).filter((e=>e.payload===s.rtp[l].payload)).map((e=>{let{type:t,subtype:i}=e;return{id:t,params:i?[i]:[]}}))})}return o})(e.sdp,this._enableCustomMessage),this._clientAbility}catch(e){throw this._log.error("initialize failed ".concat(e)),e}}))}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return wR(this,null,(function*(){try{if("CONNECTED"===this.currentState)return;let i=DP(),r={type:"answer",sdp:jx({serverAbility:e,clientAbility:this._clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(r),yield this.waitForPeerConnectionConnected(),t||qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:"SPCConnect",cost:Math.min(DP()-i,3e4)})}catch(i){let t=i instanceof cD&&i.code===aD.API_CALL_ABORTED;throw t||this._log.error("connect failed: ".concat(i," ").concat(e)),this.reset(),!t&&!this.isReconnecting&&(qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:"SPCConnect",error:i}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),i}}))}reconnect(){return wR(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(qM,this.reconnect,this);try{this.reconnectionCount++,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:EL,responseCommand:tL.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});yield this.connect(t.data.data.ability,!0),this._log.warn("reconnect() successfully"),this.stopReconnection(),this.emit("spc-reconnected")}catch(e){if(e)if(e.message.includes("timeout")){let e=_P(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),this._reconnectionTimer=window.setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),e)}else this._log.error("reconnect() failed ".concat(e)),qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:"SPCReconnect",error:e}),this.reconnectionCount>=db()&&this._log.warn("SDK has tried reconnect for ".concat(db()," 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 wR(this,null,(function*(){this._log.warn("start reconnect"),this.emitConnectionStateChangedEvent("RECONNECTING");let e=DP();yield this.reconnect(),qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:"SPCReconnect",cost:Math.min(DP()-e,3e4)})}))}stopReconnection(){-1!==this._reconnectionTimer&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(qM,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===ob&&this.startReconnection()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}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===rb&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===nb||e.target.connectionState===ob){let r="ICE/DTLS Transport connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i);new cD({message:r,code:aD.ICE_TRANSPORT_ERROR}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()}(e.target.connectionState===sb||e.target.connectionState===cb)&&(this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return tb;let e=null;return MD()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,OD()&&0!==this._peerConnection.getReceivers().length&&e?e.state:tb):tb}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(zx.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return wR(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(CD(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):"")),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();this._waitForPCConnectedPromiseReject=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 cD({code:aD.API_CALL_ABORTED,message:Xw({key:Ww,data:"leave room"})})))},n=()=>{qP.off(XP.LEAVE_SUCCESS,r,this),this.off(zx.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{n();let e=new cD({code:aD.API_CALL_TIMEOUT,message:"connection timeout"});Kx+=1,(e=>Kx>2&&!qx&&0===Qx.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),qx=!0,this.emit(zx.FIREWALL_RESTRICTION)),t(e)}),1e4);qP.on(XP.LEAVE_SUCCESS,r,this),this.on(zx.CONNECTION_STATE_CHANGED,i,this)})),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally((()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null}))),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise(((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)})):Promise.resolve()}addDownlink(e){return wR(this,null,(function*(){if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this.updateLocalAndRemoteSDPConfig(e),0===this.addDownlinkQueue.size)try{yield this.updateSDP({isNeedToCreateOffer:!0}),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(t){this._log.info("addDownlink(".concat(e.userId,") failed")),yield this.startReconnection()}}))}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,tinyId:i}=e;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(JSON.stringify(t)," ").concat(i));let r,n,o,a=this._peerConnection.getTransceivers().filter((e=>"inactive"===e.direction)).slice(0,3).map((e=>(e.direction=zA,Number(e.mid))));if(0===a.length&&(this._peerConnection.addTransceiver(IA,{direction:zA}),this._peerConnection.addTransceiver(CA,{direction:zA}),this._peerConnection.addTransceiver(CA,{direction:zA})),this._parsedAnswer||(this._parsedAnswer=LL(this._peerConnection.remoteDescription.sdp)),3===a.length)r=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[0]))),n=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[1]))),o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[2])));else{r=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=Hx({mid:1,serverAbility:this._serverAbility,clientAbility:this._clientAbility,parsedOffer:LL(this._peerConnection.localDescription.sdp),useAllCodec:!0});n=JSON.parse(JSON.stringify(e)),o=JSON.parse(JSON.stringify(e)),r.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(r),n.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(n),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o)}r.direction=JA,r.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(i)},{id:t.audio,attribute:"msid",value:"".concat(i,"-").concat(jA," ").concat(i,"-audio")}],n.direction=JA,n.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(i)},{id:t.video,attribute:"msid",value:"".concat(i,"-").concat(jA," ").concat(i,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(i)},{id:t.videoRtx,attribute:"msid",value:"".concat(i,"-").concat(jA," ").concat(i,"-bigvideo")}],n.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],o.direction=JA;let s="".concat(i,"-aux");o.ssrcs=[{id:t.auxiliary,attribute:"cname",value:s},{id:t.auxiliary,attribute:"msid",value:"".concat(s," ").concat(i,"-aux").concat(CA)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(s," ").concat(i,"-aux").concat(CA)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(s," ").concat(i,"-aux").concat(CA)}],o.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,[r.mid,n.mid,o.mid])}removeDownlink(e,t){return wR(this,null,(function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(t,") trying")),this.isReconnecting&&(yield this.waitForReconnected());let i=this._downlinkMIDMap.get(e),r=!1;this._peerConnection.getTransceivers().forEach((e=>{null!=i&&i.includes(Number(e.mid))&&(r=!0,e.direction="inactive")})),this._parsedAnswer||(this._parsedAnswer=LL(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((e=>{null!=i&&i.includes(Number(e.mid))&&(r=!0,e.direction="inactive",e.ssrcs=[],e.ssrcGroups=[])})),0===this.removeDownlinkQueue.size&&r&&(yield this.updateSDP({isNeedToCreateOffer:!0,tinyIdRemoving:e})),this._downlinkMIDMap.delete(e),this._log.info("removeDownlink(".concat(t,") done"))}))}getDownlinkMids(e){return this._downlinkMIDMap.get(e)}setBandwidth(e){return wR(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(BD()){let e=this._peerConnection.getSenders().slice(0,4);for(let o=0;o<e.length;o++){let a,s=e[o];0===o&&t?a=t:1===o&&i?a=i:2===o&&r?a=r:3===o&&n&&(a=n),a&&(yield this.setSenderMaxBitrate(s,a))}}else yield this.setBandwidthBySDP(e);Object.keys(e).forEach((t=>{e[t]&&this._log.info("".concat(t," bandwidth was set to ").concat(e[t]," kbps"))}))}catch(Wx){this._log.error("failed to set bandwidth".concat(Wx))}}))}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=LL(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=LL(this._peerConnection.remoteDescription.sdp));let a=$b?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:a,limit:$b?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:$b?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:a,limit:$b?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:$b?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:a,limit:$b?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:$b?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:a,limit:$b?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:$b?1e3*n:n}]);let s={type:"offer",sdp:xL(o)};return this.updateSDP({localDescription:s})}updateSDP(e){let{isNeedToCreateOffer:t=!1,localDescription:i,tinyIdRemoving:r}=e;if(!this._parsedAnswer)return;let n=xL(this._parsedAnswer);return this._updateSDPPromise=new Promise(((e,r)=>wR(this,null,(function*(){var o,a;try{t&&this._peerConnection&&(this._log.info("creating offer"),i=yield this._peerConnection.createOffer()),i&&(yield this.setOffer(i)),yield this.setAnswer({type:"answer",sdp:n}),this._updateSDPPromise=null,e()}catch(s){this._log.error(s),!this._isSDPLogged&&this._peerConnection&&(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._log.warn("local sdp: ".concat(null==i?void 0:i.sdp)||(null==(o=this._peerConnection.localDescription)?void 0:o.sdp)),this._log.warn("remote sdp: ".concat(n)||(null==(a=this._peerConnection.remoteDescription)?void 0:a.sdp)),this._isSDPLogged=!0),this._updateSDPPromise=null,r(s)}})))),this._updateSDPPromise}setOffer(e){return this._log.info("setting offer"),this._peerConnection.setLocalDescription({type:"offer",sdp:Jx(e.sdp)})}setAnswer(e){return this._log.info("setting answer"),this._peerConnection.setRemoteDescription(e)}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;null==(e=this._peerConnection)||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}};AR([Ex()],Yx.prototype,"updateSDP",1);var Xx=class{constructor(e){bR(this,"tag"),bR(this,"len"),bR(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}},$x=class{constructor(e){bR(this,"tinyId"),bR(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new Xx(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)}))}},Zx=new Set;function eV(){let e=Math.floor(4294967296*Math.random());return Zx.has(e)?eV():(Zx.add(e),e)}RR(zR()),RR(zR());var tV=RR(KR()),iV=class extends tV.default{constructor(e){super(),bR(this,"userId"),bR(this,"tinyId"),bR(this,"_sdpSemantics"),bR(this,"_isUplink"),bR(this,"_room"),bR(this,"_log"),bR(this,"_signalChannel"),bR(this,"_currentState","DISCONNECTED"),bR(this,"_prevTime",-1),bR(this,"_enableSEI"),bR(this,"_sei"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=ZP.createLogger({id:"n",userId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&GD&&(this._sei=new kL(this,this._log,this._isUplink))}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}close(e){this._log.info("close connection"),this.emit("closed",e),this._sei&&(this._sei.destroy(),this._sei=null)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(qP.emit(XP.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"))}},rV=class extends iV{constructor(e){super(ER(yR({},e),{isUplink:!0})),bR(this,"localMainAudioTrack",null),bR(this,"localMainVideoTrack",null),bR(this,"localAuxAudioTrack",null),bR(this,"localAuxVideoTrack",null),bR(this,"_isPublishingAux",!1),bR(this,"_publishingLocalAudioTrack"),bR(this,"_publishingLocalVideoTrack"),bR(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}),bR(this,"_smallGenerator"),bR(this,"_audioManager"),this._audioManager=e.audioManager,this._smallGenerator=null,this.initialize()}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:a}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:o||0,auxiliaryRtx:a||0}}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&&(LD()?(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===IA?n.audio=!0:(n.bigVideo=!0,this._smallGenerator&&(n.smallVideo=!0)))})))}return n}initialize(){this.installEvents()}reset(){this.uninstallEvents(),this.localMainVideoTrack&&this.localMainVideoTrack.canvasTrack&&this.localMainVideoTrack.destoryCanvasTrack()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null)}installEvents(){var e;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(e=this.singlePC)||e.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,a=super.emitConnectionStateChangedEvent(e);return a&&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}))),a}publish(e){return wR(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e,o,a,s,c,l;if(!t.singlePC)return;if(yield t.singlePC.waitForPeerConnectionConnected(),i&&(t._publishingLocalAudioTrack=i),r){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new cD({code:aD.NOT_SUPPORTED_H264,message:Xw({key:Nw})});t._publishingLocalVideoTrack=r}let d;t._isPublishingAux=n,r&&!n&&r.small&&(t._smallGenerator=new WL(r),yield t._smallGenerator.initialize(),d=t._smallGenerator.generateSmallVideoTrack(r.small)),xD()&&(yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:d,isAuxiliary:n})),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)),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==(a=t.localMainVideoTrack)?void 0:a.profile.bitrate,smallVideo:null==(c=null==(s=t.localMainVideoTrack)?void 0:s.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),yield t._signalChannel.sendWaitForResponse({command:CL,responseCommand:tL.SPC_PUBLISH_RESULT,data:ER(yR({},t.singlePC.uplinkSSRC),{state:t.publishState})}),t.sendMediaSettings(),t.installTrackMuteEvents(i,r),t.sendMutedFlag()}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;this._log.info("publish by transceiver");let o=new MediaStream;i&&Yk&&Qk&&i.genCanvasTrack();let a=(null==i?void 0:i.canvasTrack)||(null==i?void 0:i.mediaTrack),s=this._audioManager.mediaStreamTrack,c=this._peerConnection.getTransceivers(),l=[];if(s){o.addTrack(s);let e=c[0].sender.replaceTrack(s);l.push(e)}if(a)if(o.addTrack(a),n){let e=c[3].sender.replaceTrack(a);l.push(e)}else{let e=c[1].sender.replaceTrack(a);l.push(e)}if(r){let e=c[2].sender.replaceTrack(r);l.push(e)}return Promise.all(l)}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 wR(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){let e=r&&r===t.localAuxVideoTrack,n=null==i?void 0:i.mediaTrack,o=null==r?void 0:r.mediaTrack,a=t._peerConnection.getSenders(),s=[];n&&(t._audioManager.removeAudioTrack(i),t._audioManager.isMixed||(yield a[0].replaceTrack(null),s.push(0),t.localMainAudioTrack=null)),o&&(e?(yield a[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=ER(yR({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=ER(yR({},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(KA,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 wR(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:cL,data:t,responseCommand:tL.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:lL,commandDesc:"unpublish",responseCommand:tL.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===aD.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),jD){if(i&&i.mediaTrack){let e=i.mediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(r&&r.mediaTrack){let e=r.mediaTrack.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.mediaTrack){let e=n.mediaTrack.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.mediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),r&&r.mediaTrack&&(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:yL,data:this._mediaSettings,responseCommand:tL.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return wR(this,null,(function*(){var t;if(!this._peerConnection)return;let i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(i?kA:jA," stream")),null==(t=this._sei)||t.handleEncodedStreams(),LD()&&(yield this.addTrackByTransceiver(e,i))}))}addTrackByTransceiver(e,t){return wR(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers(),n=e.mediaTrack;if(e.kind===IA)this._audioManager.addAudioTrack(e),n=this._audioManager.mediaStreamTrack,yield r[0].sender.replaceTrack(n);else{let e=t?3:1;if(yield r[e].sender.replaceTrack(n),1===e&&(null==(i=this.localMainVideoTrack)?void 0:i.small)){this._smallGenerator=new WL(this.localMainVideoTrack),yield this._smallGenerator.initialize();let e=this._smallGenerator.generateSmallVideoTrack(this.localMainVideoTrack.small);yield r[2].sender.replaceTrack(e)}r[e].direction===KA&&(yield this.setTransceiverDirection(qA,[e]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return wR(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?kA:jA," stream")),LD()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return wR(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===IA)this._audioManager.removeAudioTrack(e),this._audioManager.isMixed||(yield i[0].sender.replaceTrack(null));else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(KA,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return wR(this,null,(function*(){if(!$b)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._peerConnection.setLocalDescription(e)}let o=-1,a=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(KA,"|").concat(QA,"|").concat(qA,")")))&&o++,t.includes(o)){if(e===KA&&i.includes("a=".concat(QA)))return r=!0,"a=".concat(e);if(e===qA&&i.includes("a=".concat(KA)))return r=!0,"a=".concat(QA)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:a}))}))}replaceTrack(e){return wR(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders();if(!i||0===i.length||!e.mediaTrack)return;let r=e.mediaTrack,n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;if(this._log.info("is replacing ".concat(r.kind," track on ").concat(n?kA:jA," stream")),r.kind===IA&&i[0]&&(this._audioManager.addAudioTrack(e),this._audioManager.isMixed&&(r=this._audioManager.mediaStreamTrack),yield i[0].replaceTrack(r)),r.kind===CA){if(!n&&i[1]&&(yield i[1].replaceTrack(r),this._smallGenerator&&i[2])){this._log.info("replacing smallVideo"),this._smallGenerator.destroy(),this._smallGenerator=new WL(this.localMainVideoTrack),yield this._smallGenerator.initialize();let e=this._smallGenerator.generateSmallVideoTrack(this._room.smallStreamConfig);yield i[2].replaceTrack(e)}n&&i[3]&&(yield i[3].replaceTrack(r))}}))}setBandwidth(e){return wR(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===IA?e.audio=i:"big"===n?e.bigVideo=i:"small"===n?e.smallVideo=i:e.auxVideo=i,yield t.singlePC.setBandwidth(e)}}()}))}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(aL,n)}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&qP.emit(XP.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:CA;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===kA&&t[3]&&t[3].track)return t[3].track.id;if(e===CA&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===CA){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===kA){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Rb?(this._log.error(zw.NOT_SUPPORTED_H264ENCODE),new cD({code:aD.NOT_SUPPORTED_H264,message:Xw({key:Nw})})):new cD({code:aD.UNKNOWN,message:Xw({key:xw,data:{signalResponse:tL.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}onSinglePCReconnected(){return wR(this,null,(function*(){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}))}))}};RR(zR());var nV=class extends iV{constructor(e){super(ER(yR({},e),{isUplink:!1})),bR(this,"_flag",0),bR(this,"role","anchor"),bR(this,"remoteAudioTrack"),bR(this,"remoteVideoTrack"),bR(this,"remoteAuxiliaryTrack"),bR(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),this.flag=e.flag,this.remoteAudioTrack=new NO(this._room,this),this.remoteVideoTrack=new OO(this._room,this),this.remoteAuxiliaryTrack=new MO(this._room,this),this.initialize()}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 VP(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===jA?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){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){let t=e.streams[0],{track:i}=e;if(t.id.split("-")[0]!==this.tinyId)return;let r=t.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=IA;i.kind===CA&&(n=r===jA?CA:kA);let o=this.remoteAudioTrack;n===CA?o=this.remoteVideoTrack:n===kA&&(o=this.remoteAuxiliaryTrack),o.setMediaStream(t),o.setMediaStreamTrack(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return wR(this,null,(function*(){try{if(this.isSubscriptionStateNotChanged(e))return;if(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)}catch(i){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(i.message," ").concat(JSON.stringify(this.muteState))),new cD({code:aD.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):i}}))}unsubscribe(e){return wR(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=yR({},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(function(e){return Object.keys(e).filter((t=>e[t]))}(n),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,n),"unsubscribe"===o&&(t.remoteAudioTrack.setMediaStreamTrack(null),t.remoteVideoTrack.setMediaStreamTrack(null),t.remoteAuxiliaryTrack.setMediaStreamTrack(null),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=uL,n=tL.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=hL,n=tL.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 cD({code:i.code,message:Xw({key:nw,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&this.doSubscribe(this.subscribeState,!1)}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return wR(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){if(e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected(),i||!e.hasSSRC){let i={audioSsrc:eV(),bigVideoSsrc:eV(),bigVideoRtxSsrc:eV(),auxVideoSsrc:eV(),auxVideoRtxSsrc:eV()},{audioSsrc:r,bigVideoSsrc:n,bigVideoRtxSsrc:o,auxVideoSsrc:a,auxVideoRtxSsrc:s}=i;e.ssrc={audio:r,video:n,videoRtx:o,auxiliary:a,auxiliaryRtx:s},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});let c=yield e._signalChannel.sendWaitForResponse({command:RL,responseCommand:tL.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!0,ssrc:i}});if(0!==c.data.code)throw yield e.removeDownlink(),new cD({code:c.data.code,message:c.data.message});return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}}()}))}removeDownlink(){return wR(this,null,(function*(){!this.singlePC||(this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),yield this.singlePC.removeDownlink(this.tinyId,this.userId))}))}};AR([yO((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 cD({code:aD.API_CALL_ABORTED,message:Xw({key:Ww,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],nV.prototype,"subscribe",1);var oV=nV,{isString:aV,isPlainObject:sV,isUndefined:cV,getNetworkType:lV,getTerminalType:dV,isEmpty:uV}=Bb,hV=class extends Tx{constructor(e){super(e),this.privateMapKey="",this._heartbeat=-1,this._lastHeartBeatTime=-1,this._joinTimeout=-1,this._firstPublishedList=null,this._joinReject=null,this._isPublishing=!1,this._isRelayChanged=!1,this.uplinkConnection=null,this.singlePC=null,this._enableSPC=!0,this._changeBigSmallRecords=new Map,this._networkQuality=null,this._networkType=lV(),this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=null,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this._stats=new class{constructor(e,t){this.room=e,bR(this,"_log"),bR(this,"_prevReportTime"),bR(this,"_prevReport",{}),bR(this,"_prevEncoderImplementation"),bR(this,"_prevQualityLimitationReason"),bR(this,"_prevAuxQualityLimitationReason"),bR(this,"_prevDecoderImplementationMap",new Map),bR(this,"_spcStats",null),this._log=t,this._prevReportTime=0,this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevAuxQualityLimitationReason=""}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return wR(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{(this._spcStats||(yield r.getStats())).forEach((t=>{if("outbound-rtp"===t.type)if(t.mediaType===CA){let e;if(t.ssrc===n.video?e=CA:t.ssrc===n.small?e=AA:t.ssrc===n.auxiliary&&(e=kA),!e)return;i[e].bytesSent=t.bytesSent,i[e].packetsSent=t.packetsSent,i[e].framesEncoded=t.framesEncoded,t.ssrc===n.video?(!vP(t.encoderImplementation)&&this._prevEncoderImplementation!==t.encoderImplementation&&(this._log.info("encoderImplementation change to ".concat(t.encoderImplementation)),this._prevEncoderImplementation=t.encoderImplementation),!vP(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),this._prevQualityLimitationReason=t.qualityLimitationReason)):t.ssrc===n.auxiliary&&!vP(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),this._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else t.mediaType===IA&&(i.audio.bytesSent=t.bytesSent,i.audio.packetsSent=t.packetsSent);else"candidate-pair"===t.type?CD(t)&&SP(t.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*t.currentRoundTripTime)):"media-source"===t.type&&(t.kind===IA?(i.audio.audioLevel=t.audioLevel||0,i.audio.totalAudioEnergy=t.totalAudioEnergy||0):t.kind===CA&&(t.trackIdentifier===e.getVideoTrackId(CA)?i.video.fpsCapture=t.framesPerSecond:t.trackIdentifier===e.getVideoTrackId(kA)?i.auxiliary.fpsCapture=t.framesPerSecond:i.small.fpsCapture=t.framesPerSecond));if(vP(t.audioLevel)||(i.audio.audioLevel=t.audioLevel||0),!vP(t.frameWidth)){let r=AA;t.trackIdentifier===e.getVideoTrackId(CA)||t.ssrc===n.video?r=CA:(t.trackIdentifier===e.getVideoTrackId(kA)||t.ssrc===n.auxiliary)&&(r=kA),i[r].frameWidth=t.frameWidth,i[r].frameHeight=t.frameHeight,i[r].framesSent=t.framesSent}})),0===i.audio.audioLevel&&(i.audio.audioLevel=(null==(t=e.localMainAudioTrack)?void 0:t.getInternalAudioLevel())||0)}catch(tA){this._log.warn("failed to getStats on sender connection ".concat(tA))}return i}))}getReceiverStats(e){return wR(this,null,(function*(){let t={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,jitter: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},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0}},i=e.getPeerConnection();if(i)try{let{ssrc:r}=e,{muteState:n}=e;(this._spcStats||(yield i.getStats())).forEach((i=>{if("inbound-rtp"===i.type){if(i.mediaType===IA&&i.ssrc===r.audio&&n.hasAudio){t.audio.packetsReceived=i.packetsReceived,t.audio.bytesReceived=i.bytesReceived,t.audio.packetsLost=i.packetsLost,i.insertedSamplesForDeceleration&&(t.audio.insertedSamplesForDeceleration=i.insertedSamplesForDeceleration),i.removedSamplesForAcceleration&&(t.audio.removedSamplesForAcceleration=i.removedSamplesForAcceleration);let{remoteAudioTrack:r}=e;r.stat.packetsReceived=i.packetsReceived,r.stat.bytesReceived=i.bytesReceived,r.stat.packetsLost=i.packetsLost,i.jitterBufferDelay&&(r.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)),t.hasAudio=!0}else if(i.mediaType===CA){if($b&&0===i.bytesReceived)return;let o;i.ssrc===r.video&&n.hasVideo&&(t.video.packetsReceived=i.packetsReceived,t.video.bytesReceived=i.bytesReceived,t.video.packetsLost=i.packetsLost,t.video.framesReceived=i.framesReceived,t.video.framesDecoded=i.framesDecoded,t.video.fpsDecoded=i.framesPerSecond,t.hasVideo=!0,o=e.remoteVideoTrack,i.decoderImplementation&&(!this._prevDecoderImplementationMap.has(t.userId)||this._prevDecoderImplementationMap.get(t.userId)!==i.decoderImplementation)&&(this._log.info("".concat(t.userId," decoderImplementation change to ").concat(i.decoderImplementation)),this._prevDecoderImplementationMap.set(t.userId,i.decoderImplementation))),i.ssrc===r.auxiliary&&n.hasAuxiliary&&(t.auxiliary.packetsReceived=i.packetsReceived,t.auxiliary.bytesReceived=i.bytesReceived,t.auxiliary.packetsLost=i.packetsLost,t.auxiliary.framesReceived=i.framesReceived,t.auxiliary.framesDecoded=i.framesDecoded,t.auxiliary.fpsDecoded=i.framesPerSecond,o=e.remoteAuxiliaryTrack,t.hasAuxiliary=!0),o&&(o.stat.packetsReceived=i.packetsReceived,o.stat.bytesReceived=i.bytesReceived,o.stat.packetsLost=i.packetsLost,o.stat.framesReceived=i.framesReceived,o.stat.framesDecoded=i.framesDecoded,i.jitterBufferDelay&&(o.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)))}}else"candidate-pair"===i.type&&CD(i)&&SP(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime));vP(i.frameWidth)||((i.trackIdentifier===e.getMainStreamVideoTrackId()||i.ssrc===r.video)&&(t.video.frameWidth=i.frameWidth,t.video.frameHeight=i.frameHeight,e.remoteVideoTrack.stat.frameWidth=i.frameWidth,e.remoteVideoTrack.stat.frameHeight=i.frameHeight),(i.trackIdentifier===e.getAuxStreamVideoTrackId()||i.ssrc===r.auxiliary)&&(t.auxiliary.frameWidth=i.frameWidth,t.auxiliary.frameHeight=i.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=i.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=i.frameHeight)),vP(i.audioLevel)||(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0)})),0===t.audio.audioLevel&&(t.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0)}catch(r){this._log.warn("failed to getStats on receiver connection ".concat(r))}return t}))}getStats(e,t){return wR(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=yield e.getStats(),n=[],o=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);t.forEach((e=>o.has(e.type)&&n.push(e))),this._spcStats=n}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(rO(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r}=e;if(!rO(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*ew,uint32_audio_energy:1e6*t.senderStats.audio.totalAudioEnergy,uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent},r=[],n={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};if(r.push(n),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};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};r.push(e)}let o={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:o}}let{statInterval:n}=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_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(ZA)),n=i?i.duration:0,o={uint32_video_stream_type: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};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=r.get("".concat(e.userId,"_").concat(eb)),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};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let o=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(i)),i.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let e=o.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status,r=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*r/n),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}let a=o.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=a.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,o=0,s=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(r=t.uint32_video_codec_bitrate,o=t.uint32_video_enc_fps,s=t.uint32_video_codec_fps);let c=this.getDifferenceValue(r,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*c/n),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_enc_fps)/n),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(s,e.uint32_video_codec_fps)/n)}));let s=i.msg_down_stream_info,c=o.msg_down_stream_info;return s.forEach((e=>{let t=c.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(t){if(rO(e.msg_audio_status)||rO(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,r=t.msg_audio_status;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 o=this.getDifferenceValue(r.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*o/n),i.uint32_audio_total_bitrate=Math.round(8*o/n)}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,o=t.uint32_video_origin_lost,a=t.uint32_video_codec_bitrate,s=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(o,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(a,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/n);let d=this.getDifferenceValue(s,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/n),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/n)}))}}})),i}getStatsReport(e){return wR(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:r,freezeMap:n}=e;return function*(){let e={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:0,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:[{uint32_video_stream_type:0,uint32_video_codec_fps:0,uint32_video_capture_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_final_lost:0,uint32_video_enc_fps:0}],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_format:0,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_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}}(this,this._log),this.userManager=new $O(this.userId,this._log),this._version=eA,this.sdpSemantics=fb,cV(e.sdpSemantics)?rD.isUnifiedPlanDefault()&&(this.sdpSemantics=_b):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(this._networkType)),this.audioManager=new class{constructor(e){let{room:t}=e;bR(this,"audioContext",null),bR(this,"_destination",null),bR(this,"_localAudioTrack",null),bR(this,"_localScreenAudioTrack",null),bR(this,"_localMediaStreamAudioTrack",null),bR(this,"_audioTrackStreamSource",null),bR(this,"_screenAudioTrackStreamSource",null),bR(this,"_mixedMusicSet",new Set),bR(this,"hasMusic",!1),bR(this,"mixedMusicMap",new Map),bR(this,"cacheMusicMap",new Map),bR(this,"_log"),bR(this,"_originTrack",null),this._log=ZP.createLogger({id:"am",userId:t.userId,sdkAppId:t.sdkAppId}),this.initAudioContext()}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}get isMixed(){return(this.hasMusic?1:0)+(this._localAudioTrack?1:0)+(this._localScreenAudioTrack?1:0)>=1}get mediaStreamTrack(){return this._destination.stream.getAudioTracks()[0]}addMusicSource(e){return wR(this,null,(function*(){this._log.info("add music source, id: ".concat(e.id," url: ").concat(e.url)),this.initAudioContext();let t,{id:i,url:r,loop:n,volume:o}=e;if(this.mixedMusicMap.has(i))return;t=this.cacheMusicMap.has(i)?this.cacheMusicMap.get(i).localMusicTrack:new wO(e);let{stream:a}=t._destination,s=document.createElement("audio");s.srcObject=a,t.play(),yield s.play(),this._log.info("start mix audio ".concat(i," success."));let c=this.audioContext.createMediaStreamSource(a),l=this.audioContext.createGain();return c.connect(l),l.connect(this._destination),this._mixedMusicSet.add(i),this.mixedMusicMap.set(i,{localMusicTrack:t,streamSource:c,gainNode:l,audioPlayer:s}),this.cacheMusicMap.set(i,{localMusicTrack:t}),this.hasMusic=!0,t}))}updateMusicSource(e){return wR(this,null,(function*(){let{id:t,volume:i,loop:r,operation:n}=e;if(this._log.info("update music source, id: ".concat(e.id," operation: ").concat(n)),this.mixedMusicMap.has(t)){let{localMusicTrack:e}=this.mixedMusicMap.get(t);vP(i)||e.setVolume(i),vP(r)||e.loop(r),vP(n)||e.setOperation(n)}}))}addAudioTrack(e){return wR(this,null,(function*(){var t;if(this._log.info("start add audioTrack, userId: ".concat(e.userId)),this.initAudioContext(),null==e||!e.mediaStream)return;if(this._localMediaStreamAudioTrack===e.mediaTrack)return void this._log.info("addAudioTrack duplicate.");let i=yield null==(t=e.mediaTrack)?void 0:t.getSettings();this._destination.channelCount=(null==i?void 0:i.channelCount)||1,this._localAudioTrack=e,this._localMediaStreamAudioTrack=e.mediaTrack,this._audioTrackStreamSource=this.audioContext.createMediaStreamSource(e.mediaStream),this._audioTrackStreamSource.connect(this._destination)}))}removeAudioTrack(e){var t,i,r,n;this._localAudioTrack===e&&(this._log.info("start remove audioTrack, userId: ".concat(e.userId)),null==(t=this._audioTrackStreamSource)||t.disconnect(),null==(i=this._localMediaStreamAudioTrack)||i.stop(),this._localMediaStreamAudioTrack=null,null==(r=this._localAudioTrack)||r.stop(),this._localAudioTrack=null),this._localScreenAudioTrack===e&&(this._log.info("start remove screenTrack, userId: ".concat(e.userId)),null==(n=this._screenAudioTrackStreamSource)||n.disconnect(),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack=null)}addScreenAudioTrack(e){this._log.info("start add screenAudioTrack, userId: ".concat(e.userId)),this.initAudioContext(),null!=e&&e.mediaStream&&this._localScreenAudioTrack!==e&&(this._localScreenAudioTrack=e,this._screenAudioTrackStreamSource=this.audioContext.createMediaStreamSource(e.mediaStream),this._screenAudioTrackStreamSource.connect(this._destination))}removeAudioTrackSource(e){var t,i;this._log.info("remove audio track source, type: ".concat(e)),"main"===e&&(null==(t=this._audioTrackStreamSource)||t.disconnect(),this._audioTrackStreamSource=null,this._localAudioTrack=null),"screen"===e&&(null==(i=this._screenAudioTrackStreamSource)||i.disconnect(),this._screenAudioTrackStreamSource=null,this._localScreenAudioTrack=null)}removeMusicSource(e){let{id:t}=e;if(this.mixedMusicMap.has(t)){this._log.info("start remove music source, music id: ".concat(t));let{localMusicTrack:e,streamSource:i,gainNode:r,audioPlayer:n}=this.mixedMusicMap.get(t);i.disconnect(),r.disconnect(),n.pause(),n.srcObject=null,e.stop(),this.mixedMusicMap.delete(t),this._mixedMusicSet.delete(t),0===this._mixedMusicSet.size&&(this.hasMusic=!1)}"*"===t&&this.destroyAllMusic()}destroyAllMusic(){this._log.info("destroy all music source."),this._mixedMusicSet.forEach((e=>{this.removeMusicSource({id:e})}))}destroyAllCache(){this._log.info("destroy all music cache."),this.cacheMusicMap.forEach((e=>{e.localMusicTrack.stop()}))}initAudioContext(){this.audioContext||(this.audioContext=XN(),"running"!==this.audioContext.state&&this._log.warn("context state: ".concat(this.audioContext.state)),this._destination=this.audioContext.createMediaStreamDestination(),this._destination.channelCount=1)}initDenoiser(e){return wR(this,arguments,(function(e){return function*(){}()}))}enableDenoiser(e){return wR(this,null,(function*(){}))}disableDenoiser(){return wR(this,null,(function*(){}))}destroy(){this.removeAudioTrackSource("main"),this.removeAudioTrackSource("aux"),this.audioContext.close(),this.destroyAllMusic(),this.destroyAllCache()}}({room:this}),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!cV(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!cV(e.enableSPC)&&VD&&(this._enableSPC=e.enableSPC),this._initBusinessInfo(e)}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.remotePublishedUserMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,i){return wR(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)fR.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&mR)for(var r of mR(e))t.indexOf(r)<0&&gR.call(e,r)&&(i[r]=e[r]);return i})(e,[]);qP.emit(XP.REMOTE_PUBLISH_STATE_CHANGED,yR({room:this},t)),this.emit("remote-publish-state-changed",yR({},t))})),String(e.roomId||e.strRoomId),this._joinOptions=e,new Promise(((t,i)=>wR(this,null,(function*(){this._joinReject=i;try{this.checkDestroy(),yield this.initialize(),yield this.doJoin(e),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(r){this.reset(),i(r)}this._joinReject=null}))))}))}doJoin(e){return new Promise(((t,i)=>wR(this,null,(function*(){var r,n,o;let a;if(cV(e.role)||(this.role=20===e.role?"anchor":"audience"),cV(e.privateMapKey)||(this.privateMapKey=e.privateMapKey),this._signalChannel.once(zM,(e=>{this.clearJoinTimeout(),qP.emit(XP.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),i(e)})),yP(null==(n=null==(r=this.scheduleResult)?void 0:r.config)?void 0:n.singlePC)&&VD&&(this._enableSPC=this.scheduleResult.config.singlePC),this._enableSPC&&!this.singlePC){this.singlePC=new Yx({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.once("error",(()=>this.fallbackToMPC()));try{a=yield this.singlePC.initialize()}catch(u){this.fallbackToMPC()}}this.keyPointManager.setConnectionType(this.singlePC?1:2);let s={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,trtcRole:"anchor"===this.role?20:21,trtcScene:"live"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:dV(),netType:vA[this._networkType],bussinessInfo:this._businessInfo,ability:a},{bussinessInfo:c,pushUserCdnInfo:l}=this.publishCDNManager.handleCDNConfigForJoinData(this._businessInfo);Object.assign(s,{bussinessInfo:c,pushUserCdnInfo:l}),this._log.debug("join room signal data: ".concat(JSON.stringify(s)));let d=5e3;(null==(o=this.scheduleResult.config)?void 0:o.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(d=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{this._log.error("join room timeout observed"),i(new cD({code:aD.JOIN_ROOM_FAILED,message:Xw({key:pw})}))}),d),qP.emit(XP.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?IL:rL,s),this._signalChannel.once(tL.JOIN_ROOM_RESULT,(e=>{this.clearJoinTimeout();let{code:r,message:n,data:o}=e.data;qP.emit(XP.JOIN_RECEIVED_CMD_RES,{room:this,code:r}),0===r?(this._log.info("Join room success, start heartbeat"),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=o.publishers,this.singlePC&&this.singlePC.connect(o.ability).catch((()=>{})),t()):(this._log.error("Join room failed result: ".concat(r," error: ").concat(n)),i(new cD({code:aD.JOIN_ROOM_FAILED,extraCode:r,message:Xw({key:mw,data:{error:n,code:r}})})))}))}))))}reJoin(){return wR(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this._joinOptions.roomId)),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this._signalChannel.close(),yield this._signalChannel.connect(),yield this.doJoin(ER(yR({},this._joinOptions),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey})),this._log.warn("reJoin success"),TN.logSuccessEvent({userId:this.userId,eventType:ub}),this.singlePC?(yield this.singlePC.waitForPeerConnectionConnected(),this.uplinkConnection instanceof rV&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.doSubscribe()}))):(this.checkConnectionsToReconnect(),this.uplinkConnection instanceof qL&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()),this.mixTranscodeManager.reStartMixTranscode()}catch(e){this._log.warn("reJoin fail ".concat(e)),this.reset(),TN.logFailedEvent({userId:this.userId,eventType:ub,error:e}),this.emit("error",new cD({code:aD.JOIN_ROOM_FAILED,message:Xw({key:_w,data:{roomId:this._joinOptions.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){this._log.info("setup signal channel");let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl();return this._signalChannel=new class{constructor(e){bR(this,"_room"),bR(this,"_sdkAppId"),bR(this,"_userId"),bR(this,"_userSig"),bR(this,"_url"),bR(this,"_backupUrl"),bR(this,"_urlWithParam"),bR(this,"_backupUrlWithParam"),bR(this,"_socketInUse"),bR(this,"_socket"),bR(this,"_backupSocket"),bR(this,"_backupTimer",-1),bR(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),bR(this,"_currentState",YM),bR(this,"_reconnectionCount",0),bR(this,"_reconnectionTimer",-1),bR(this,"_seq",0),bR(this,"_log"),bR(this,"_emitter"),bR(this,"_lastMessageTime",-1),bR(this,"_prevTime",-1),this._room=e.room,this._sdkAppId=e.sdkAppId,this._userId=e.userId,this._userSig=e.userSig,this._url=e.url,this._backupUrl=e.backupUrl;let t="?sdkAppId=".concat(encodeURIComponent(this._sdkAppId),"&userId=").concat(encodeURIComponent(this._userId),"&userSig=").concat(encodeURIComponent(this._userSig));this._urlWithParam="".concat(this._url).concat(t),this._backupUrlWithParam="".concat(this._backupUrl).concat(t),this._seq=0,this._log=ZP.createLogger({id:"ws",userId:this._userId,sdkAppId:this._sdkAppId}),this._emitter=new WM.default}get isConnected(){return this._currentState===$M}get isConnecting(){return this._currentState===XM}get isOnline(){return this._currentState===$M&&Date.now()-this._lastMessageTime<12e3}connect(){return new Promise(((e,t)=>{this._prevTime<0&&(this._prevTime=DP()),this._log.info("connect to ".concat(this._url)),this.emitConnectionStateChanged(XM),this._socket=new WebSocket(this._urlWithParam),this.bindSocket(this._socket),this._backupTimer=setTimeout((()=>{this.isConnected||(this._log.info("trying to connect to backupUrl"),this.tryConnectBackup())}),5e3),this.once(qM,e),this.once(QM,t)}))}tryConnectBackup(){this._backupSocket||(this.unbindAndCloseSocket(jA),this._log.debug("try to connect to url: ".concat(this._backupUrlWithParam)),this._backupSocket=new WebSocket(this._backupUrlWithParam),this.bindSocket(this._backupSocket))}bindSocket(e){e.onopen=this.onopen.bind(this),e.onclose=this.onclose.bind(this),e.onerror=this.onerror.bind(this),e.onmessage=this.onmessage.bind(this)}unbindSocket(e){this.clearBackupTimer(),e.onopen=()=>{},e.onclose=()=>{},e.onerror=()=>{},e.onmessage=()=>{}}unbindAndCloseSocket(t){if(t===jA){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(e){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(e){}this._backupSocket=null}}clearBackupTimer(){-1!==this._backupTimer&&(clearTimeout(this._backupTimer),this._backupTimer=-1)}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onopen(e){this.isConnected||(this.isReconnecting&&!this._signalInfo.tinyId&&this.stopReconnection(),this.clearBackupTimer(),e.target===this._socket?(this.unbindAndCloseSocket(HA),this._socketInUse=this._socket):(this.unbindAndCloseSocket(jA),this._socketInUse=this._backupSocket),this.emitConnectionStateChanged($M),this._emitter.emit(qM))}onclose(e){let{url:t}=e.target,i=e.target===this._socketInUse;this._log.info("websocket[".concat(t," InUse: ").concat(i,"] is closed with code: ").concat(e.code)),e.target===this._socketInUse&&(this.emitConnectionStateChanged(YM),(!e.wasClean||1e3!==e.code)&&(this._log.warn("onclose code:".concat(e.code," reason:").concat(e.reason)),this._log.warn("close current websocket and schedule a reconnect timeout"),this._socketInUse.onclose=()=>{},this._socketInUse.close(4011),this._socket=null,this._backupSocket=null,this._socketInUse=null,this.reconnect(jA)))}onerror(e){let{url:t}=e.target;this._log.error("websocket[".concat(t,"] error observed")),this.isConnected?e.target===this._socketInUse&&(this.unbindAndCloseSocket(jA),this.unbindAndCloseSocket(HA),this._socketInUse=null,this.reconnect(jA)):(this.isReconnecting||qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",error:new Error("ws onerror")}),e.target==this._socket?(this.unbindAndCloseSocket(jA),this.reconnect(HA)):(this.unbindAndCloseSocket(HA),this.reconnect(jA)))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now();let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values(ZM),o=Object.keys(ZM)[n.indexOf(i)],a=tL[o];switch(eL.includes(i)||(this._log.debug("received msg: ".concat(e.data)),this._log.info("Received event: [ ".concat(a||"unknown cmd: ".concat(i)," ]"))),i){case ZM.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,this._signalInfo.tinyId=t.tinyId,r.svrTime&&function(e){Vb=e-(new Date).getTime();let t=new Date;t.setTime(e),ZP.info("baseTime from server: ".concat(t," offset: ").concat(Vb))}(r.svrTime),this._log.info("ChannelSetup Success"),qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",cost:DP()-this._prevTime}),this._prevTime=-1,this._emitter.emit(JM,{signalInfo:this._signalInfo});else{let e=new cD({code:aD.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:Xw({key:rw,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",error:e}),this._emitter.emit(zM,e)}break;case ZM.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=r.relayOuterIp,this._signalInfo.relayInnerIp=r.relayInnerIp,this._signalInfo.relayPort=r.relayPort,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this._emitter.emit(a,{data:t});break;case ZM.CHANNEL_RECONNECT_RESULT:0===t.code?(this._log.warn("reconnect success"),this.stopReconnection(),qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketReconnect",cost:DP()-this._prevTime}),this._prevTime=-1,this._room.syncUserList(),this._room.checkConnectionsToReconnect()):(this._log.warn("reconnect failed, ".concat(t.code," ").concat(t.message)),this._room.reJoin());break;default:this._emitter.emit(a,{data:t})}}reconnect(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:jA;if(this.isReconnecting)return;if(this._reconnectionCount>=30){this._log.warn("SDK has tried reconnect signal channel for ".concat(30," times, but all failed. please check your network"));let e=new cD({code:aD.SIGNAL_CHANNEL_RECONNECTION_FAILED,message:Xw({key:iw})});return qP.emit(XP.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketReconnect",error:e}),void this._emitter.emit(QM,e)}this._reconnectionCount++,this._log.warn("reconnect ".concat(e," [").concat(this._reconnectionCount,"/").concat(30,"]"));let t=this.getReconnectionUrl(e);this.emitConnectionStateChanged(XM),this._prevTime<0&&(this._prevTime=DP()),e===jA?(this._socket=new WebSocket(t),this.bindSocket(this._socket)):(this._backupSocket=new WebSocket(t),this.bindSocket(this._backupSocket));let i=_P(this._reconnectionCount);this._reconnectionTimer=setTimeout((()=>{this._log.warn("reconnect ".concat(e," timeout(").concat(i/1e3,"s), try again")),this.clearReconnectionTimer(),this.unbindAndCloseSocket(jA),this.unbindAndCloseSocket(HA),this.reconnect(e===jA?HA:jA)}),i)}get isReconnecting(){return-1!==this._reconnectionTimer}getReconnectionUrl(e){let t=e===jA?this._urlWithParam:this._backupUrlWithParam;if(this._signalInfo.tinyId&&-1===t.indexOf("&rc=1")){let{roomId:e,useStringRoomId:i}=this._room;t+="&rc=1&relayInnerIp=".concat(this._signalInfo.relayInnerIp,"&relayOuterIp=").concat(this._signalInfo.relayIp,"&relayPort=").concat(this._signalInfo.relayPort,"&roomId=").concat(e,"&useStringRoomId=").concat(i)}return t}send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected){let i={cmd:e,data:t,userId:this._userId,tinyId:this._signalInfo.tinyId,seq:++this._seq};return this._socketInUse.send(JSON.stringify(i)),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:o,enableLog:a=!0}=e;return new Promise(((e,s)=>{let c=setTimeout((()=>{this.off(n,l);let e=new cD({code:aD.API_CALL_TIMEOUT,message:Xw({key:tw,data:{commandDesc:o,command:t}})});a&&this._log.warn(e),s(e)}),r),l=t=>{t.data.seq===d&&(clearTimeout(c),this.off(n,l),e(t))};this.on(n,l);let d=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:r=0,retryTimeout:n=0}=e;return KP({retryFunction:this.sendWaitForResponse,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&&(this._reconnectionCount=0,this.clearReconnectionTimer())}close(){this._log.info("close SignalChannel"),this.clearBackupTimer(),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.unbindAndCloseSocket(jA),this.unbindAndCloseSocket(HA),this.emitConnectionStateChanged(YM)}on(e,t,i){this._emitter.on(e,t,i)}removeListener(e,t,i){this._emitter.removeListener(e,t,i)}once(e,t,i){this._emitter.once(e,t,i)}off(e,t,i){this._emitter.off(e,t,i)}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this._emitter.emit(KM,{prevState:this._currentState,state:e}),this._currentState=e)}}({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this}),this._networkQuality||(this._networkQuality=new XL({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(XL.EVENT_NETWORK_QUALITY,(e=>{this.emit("network-quality",e)}))),this._signalChannel.on(KM,(e=>{qP.emit(XP.SIGNAL_CONNECTION_STATE_CHANGED,yR({room:this},e)),this.emit("signal-connection-state-changed",e)})),this._signalChannel.on(QM,(e=>{this.reset(),this.emit("error",e)})),this._signalChannel.once(JM,(e=>{this.tinyId=e.signalInfo.tinyId,qP.emit(XP.JOIN_SIGNAL_CONNECTION_END,{room:this})})),this._signalChannel.on(tL.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})),this._signalChannel.on(tL.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})),this._signalChannel.on(tL.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})),this._signalChannel.on(tL.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(TN.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})})),qP.emit(XP.JOIN_SIGNAL_CONNECTION_START,{room:this}),this._signalChannel.connect()}leave(){return wR(this,null,(function*(){try{yield this.doHeartbeat()}catch(e){}qP.emit(XP.LEAVE_SEND_CMD,{room:this}),this._log.info("leave() => leaving room"),this._signalChannel.send(nL),this.reset()}))}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach((e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")}))}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){-1===this._heartbeat&&(this._heartbeat=fN.run(Mb,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),fN.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return wR(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});if(this.badCaseDetector.resetMonitor(),null==(e=this._signalChannel)||!e.isConnected)return;let r=this._signalChannel.isConnected?function(e){if(QO.has(e)){let t=QO.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc})));return QO.delete(e),t}return[]}(this.userId):[],n=yR({str_sdk_version:ZR,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:vA[this._networkType]},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i);qP.emit(XP.HEARTBEAT_REPORT,{room:this,report:n}),this._signalChannel.send(oL,n);let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(o-this._lastHeartBeatTime)),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map((e=>{let{userId:t,srcTinyId:i,flag:r}=e,n=this.remotePublishedUserMap.get(t);return n&&this._changeBigSmallRecords.has(t)&&this.checkSubscribeBigSmallVideo(n),{userId:t,tinyId:i,flag:r}}));qP.emit(XP.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=null),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r}=e,n=new(this.singlePC?oV:BL)({userId:t,tinyId:i,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:r});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,t),this.emit("remote-published",n)}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("sei-message",(e=>{this.emit("sei-message",e)})),e.on("error",(e=>{let i=e.getCode();i!==aD.ICE_TRANSPORT_ERROR&&(i===aD.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",ER(yR({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=fN.run(Mb,this.syncUserList.bind(this)))}stopSyncUserListInterval(){fN.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:TL,responseCommand:tL.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 Xw({key:xw,data:{signalResponse:tL.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.isOnline||!NL)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(){this.singlePC||this.getAllConnections().forEach((e=>{if(e instanceof OL&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===ob&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return wR(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),TN.uploadEvent({log:"stat-fallback",userId:this.userId}),this._enableSPC=!1,null==(e=this.singlePC)||e.close(),this.singlePC=null,yield this.reJoin(),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new qL({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),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}))}this.remotePublishedUserMap.forEach((e=>{let t=new BL({userId:e.userId,tinyId:e.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:e.flag,remoteAudioTrack:e.remoteAudioTrack,remoteVideoTrack:e.remoteVideoTrack,remoteAuxiliaryTrack:e.remoteAuxiliaryTrack});this.installDownlinkEvents(t,e.userId),this.remotePublishedUserMap.set(e.userId,t),e.isMainStreamSubscribed&&t.subscribe(e.subscribeState,"main"),e.isAuxStreamSubscribed&&t.subscribe(e.subscribeState,"auxiliary")}))}))}destroy(){this._isDestroyed||(super.destroy(),this._joinReject&&(this._joinReject(new cD({code:aD.INVALID_OPERATION,message:Xw({key:Rw,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return wR(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:SL,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey},responseCommand:tL.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 cD({code:aD.SWITCH_ROLE_FAILED,message:Xw({key:Tw,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof cD&&e.getCode()===aD.API_CALL_TIMEOUT&&(e=new cD({code:aD.SWITCH_ROLE_FAILED,message:Xw({key:vw})})),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 wR(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role)return;qP.emit(XP.PUBLISH_START,{room:this});let e={},i={};this._isPublishing=!0,t.forEach((t=>{!t.mediaTrack||(t instanceof CO&&(t instanceof kO?(i.audio=t,this.audioManager.addScreenAudioTrack(t)):(e.audio=t,this.audioManager.addAudioTrack(t))),t instanceof RO&&(t instanceof bO&&2===t.mediaType?i.video=t:e.video=t),t.setPublishStarting(this))}));try{let r=uV(e),n=uV(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new rV({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new qL({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",(e=>{this.emit("media-connection-state-changed",ER(yR({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==aD.ICE_TRANSPORT_ERROR&&(t===aD.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")),this._isPublishing=!1,t.forEach((e=>{!e.mediaTrack||(this.localTracks.add(e),e.publish(this))}))}catch(r){throw t.forEach((e=>{let t="error";r.message.includes("timeout")?t="timeout":r.code===aD.API_CALL_ABORTED&&(t="api-call"),e.setPublishStopped(t,"error"===t?r:void 0)})),this._isPublishing=!1,r}}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return wR(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 instanceof CO&&(t instanceof kO?i.audio=t:e.audio=t),t instanceof RO&&(t instanceof bO&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");uV(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),uV(i)||(this._log.info("unpublish() => aux ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(r){}t.forEach((e=>{!e.mediaTrack||(e.unpublish(),this.localTracks.delete(e))})),0===this.localTracks.size&&!this.audioManager.isMixed&&this.closeUplink("you unpublished")}))}addTrack(e){return this.uplinkConnection&&e.mediaTrack?(e.setPublishStarting(this),this.uplinkConnection.addTrack(e).then((t=>(e.publish(this),t)))):Promise.resolve()}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?this.uplinkConnection.replaceTrack(e).then((t=>{qP.emit(XP.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return wR(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return wR(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";try{let n=yR({},i.subscribeState);t.forEach((e=>{switch(e.mediaType){case 1:n.audio=!0;break;case 4:n.video=!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),qP.emit(XP.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(VL(n),"] prev: [").concat(VL(i.subscribeState),"]")),yield i.subscribe(n,r),i.remoteVideoTrack.setMediaType(n.smallVideo?8:4),t.forEach((e=>e.subscribe())),qP.emit(XP.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(tA){let i=tA instanceof cD?tA.getCode():aD.UNKNOWN,n=tA;throw tA instanceof cD?i===aD.REMOTE_STREAM_NOT_EXIST&&(n=new cD({code:aD.API_CALL_ABORTED,message:Xw({key:Jw,data:{message:tA.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new cD({code:i,message:Xw({key:gw,data:{message:tA.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 wR(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(tA){this._log.warn("unsubscribe() => failed ".concat(tA))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),qP.emit(XP.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,fN.clearTask(this._audioVolumeIntervalId),void(this._audioVolumeIntervalId=null);e=Math.floor(Math.max(e,100)),qP.emit(XP.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&(fN.clearTask(this._audioVolumeIntervalId),this._audioVolumeIntervalId=null),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=fN.run(Lb,(()=>{var e,t;let i=[];if(null!=(e=this.uplinkConnection)&&e.localMainAudioTrack){let e=Math.floor(100*this.uplinkConnection.localMainAudioTrack.getAudioLevel());i.push({userId:"",volume:e})}null==(t=this.remotePublishedUserMap)||t.forEach((e=>{if(e.muteState.hasAudio){let t=Math.floor(100*e.remoteAudioTrack.getAudioLevel());i.push({userId:e.userId,volume:t})}})),this.emit("audio-volume",i)}),{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return wR(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t.audio.bytesSent,packetsSent:t.audio.packetsSent}}return e}))}getLocalVideoStats(){return wR(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:t,packetsSent:i,framesEncoded:r,framesSent:n,frameWidth:o,frameHeight:a}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:i,framesEncoded:r,framesSent:n,frameWidth:o,frameHeight:a}}return e}))}getTransportStats(){return wR(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 wR(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 wR(this,null,(function*(){let e={};for(let[t,i]of this.remotePublishedUserMap)i.muteState.hasAudio&&(e[t]=i.remoteAudioTrack.stat);return e}))}setProxyServer(e){if(aV(e)){if(!e.startsWith("wss://"))throw new cD({code:aD.INVALID_PARAMETER,message:"invalid websocket url"});this.proxy_ws=e}else if(sV(e)){let{websocketProxy:t,loggerProxy:i}=e;t&&(this.proxy_ws=t),i&&oA(i)}}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(Bb.getTurnServer(e)))):Bb.isPlainObject(e)&&i.push(Bb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:gL,data:e,timeout:5e3,responseCommand:tL.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:vL,data:e,timeout:5e3,responseCommand:tL.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?pL:_L,data:e,timeout:5e3,responseCommand:t?tL.START_PUBLISH_TENCENT_CDN_RES:tL.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?mL:fL,data:e,timeout:5e3,responseCommand:t?tL.STOP_PUBLISH_TENCENT_CDN_RES:tL.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}getIceServers(){return 0===this._turnServers.length&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=Bb.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):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())||{}}reset(){this.mixTranscodeManager.reset(),this.publishCDNManager.reset(),this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this._signalChannel&&(this._log.info("destroying SignalChannel"),this._signalChannel.close()),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null)}checkSubscribeBigSmallVideo(e){return wR(this,null,(function*(){let t=null==e?void 0:e.muteState.hasSmall,i=null==e?void 0:e.muteState.hasVideo;if(!t&&!i||!e.isBigStreamSubscribed&&!e.isSmallStreamSubscribed)return;let r=e.getUserId(),n=this._changeBigSmallRecords.get(r)||{},{subscribeState:o}=e,{options:a,isSubscribing:s,reSubscribeCount:c}=n;if(a.video&&o.video||a.smallVideo&&o.smallVideo&&t||s)return;let l={audio:o.audio,auxiliary:o.auxiliary,video:a.video,smallVideo:a.smallVideo};if(t&&e.isBigStreamSubscribed||e.isSmallStreamSubscribed)try{a&&!s&&c>=1&&(n.isSubscribing=!0,n.reSubscribeCount=c-1,!t&&e.isSmallStreamSubscribed&&(l.video=!0,l.smallVideo=!1),yield null==e?void 0:e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info("change [".concat(r,"] to ").concat(l.smallVideo?"small":"big"," video successfully. count ").concat(10-n.reSubscribeCount,".")),n.isSubscribing=!1,n.reSubscribeCount=10)}catch(d){this._log.info("change [".concat(r,"] to ").concat(l.smallVideo?"small":"big"," video failed. count ").concat(10-n.reSubscribeCount,".")),n.isSubscribing=!1,0===c&&this._changeBigSmallRecords.delete(r)}}))}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:10};this._changeBigSmallRecords.set(t.userId,i),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big"))}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(aV(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!cV(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new cD({code:aD.INVALID_PARAMETER,message:Xw({key:cw})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!cV(e.streamId)){if(!(aV(e.streamId)&&String(e.streamId)&&String(e.streamId).length<=64))throw new cD({code:aD.INVALID_PARAMETER,message:Xw({key:lw})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_streamid_main=e.streamId}if(!cV(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new cD({code:aD.INVALID_PARAMETER,message:Xw({key:dw})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!cV(e.userDefinePushArgs)){if(!(aV(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new cD({code:aD.INVALID_PARAMETER,message:Xw({key:uw})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}uV(t)||(this._businessInfo=JSON.stringify(t))}startPlugin(e,t){return wR(this,null,(function*(){var i,r;"AudioMixer"===e&&(yield this.audioManager.addMusicSource(t),this.isJoined&&(null==(i=this.uplinkConnection)?void 0:i.localMainAudioTrack)&&(yield this.replaceTrack(null==(r=this.uplinkConnection)?void 0:r.localMainAudioTrack)))}))}updatePlugin(e,t){return wR(this,null,(function*(){"AudioMixer"===e&&(yield this.audioManager.updateMusicSource(t))}))}stopPlugin(e,t){return wR(this,null,(function*(){"AudioMixer"===e&&(yield this.audioManager.removeMusicSource(t))}))}sendSEI(e,t){var i;null==(i=this.uplinkConnection)||i.sendSEI(e,t)}};return AR([Nx(["left",Ux.INIT],"joined"),yO((e=>{let t=new class{constructor(){this._set=new Set,qP.on(XP.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))}};return function(i,r,n){return wR(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 cD({code:aD.INVALID_OPERATION,message:Xw({key:hw})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new cD({code:aD.INVALID_OPERATION,message:Xw({key:Cw,data:this.userId})});t.add({room:this,roomId:o}),this._log.info("Join() => joining room: ".concat(o," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),this.role=21===i.role?"audience":"anchor",qP.emit(XP.JOIN_START,{room:this,roomId:o}),this.checkSystemResult=yield rD.checkSystemRequirementsInternal(),this.checkDestroy();let a=Bb.getEnv();a||(a=mA,this.proxy_ws&&(this.proxy_ws.startsWith(YA)?a=_A:this.proxy_ws.startsWith(XA)&&(a=fA))),TN.setConfig({env:a,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),GM.call(this);let{isH264EncodeSupported:s,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!rD.isWebRTCSupported()||!s&&!c)throw new cD({code:aD.NOT_SUPPORTED,message:Xw({key:Dw})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Bb.getEnv()&&(yield this.schedule(o,n,eA));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=Bb.performanceNow(),qP.emit(XP.JOIN_SUCCESS,{room:this}),TN.uploadEvent({log:"stat-conv-".concat(Number(Xk),"-").concat(location.hostname),userId:this.userId}),t}catch(l){throw t.delete({room:this,roomId:o}),qP.emit(XP.JOIN_FAILED,{room:this,error:l}),l}}))}}))],hV.prototype,"join",1),AR([Nx("joined","left",{ignoreError:!0}),yO((e=>function(){return wR(this,null,(function*(){qP.emit(XP.LEAVE_START,{room:this}),yield e.call(this),qP.emit(XP.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),function(e){return function(t,i,r){let n=r.value;return r.value=function(){var t,i;let r=[];for(var o=arguments.length,a=new Array(o),s=0;s<o;s++)a[s]=arguments[s];return null==(t=Sx.get(this))||t.forEach((e=>r.push(e))),null==(i=yx.get(this))||i.forEach((e=>e.forEach((e=>r.push(e))))),r.forEach((t=>{t.reject(new cD({code:aD.API_CALL_ABORTED,message:e}))})),Sx.delete(this),yx.delete(this),n.apply(this,a)},r}}("leave room"),ex({fnName:"publish",validateArgs:!1}),ex({fnName:"unsubscribe",validateArgs:!1})],hV.prototype,"leave",1),AR([Ex(),ZL({settings:{retries:db,timeout:e=>_P(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))}})],hV.prototype,"publish",1),AR([ex({fnName:"publish",callback(){for(var e,t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];0===this.localTracks.size&&(null==(e=this.uplinkConnection)||e.close("you unpublished"),this.uplinkConnection=null,i.forEach((e=>e.setPublishStopped("api-call"))))}}),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=Sx.get(this);if(o){let t=o.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 cD({code:aD.API_CALL_ABORTED,message:e})),!1)}));Sx.set(this,t)}return n.apply(this,i)},r}}("api-call"),Ex()],hV.prototype,"unpublish",1),AR([Ix((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),ZL({settings:{retries:db,timeout:e=>_P(e)},onError(e,t,i){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),i(e))}})],hV.prototype,"subscribe",1),AR([ex({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")}))}}),Ix((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],hV.prototype,"unsubscribe",1),HM.create=HM._create.bind(HM,hV),HM}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TRTC=t()}(this,(function(){var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},t=function(e){try{return!!e()}catch(t){return!0}},i=!t((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),r=i,n=Function.prototype,o=n.call,a=r&&n.bind.bind(o,o),s=r?a:function(e){return function(){return o.apply(e,arguments)}},c=s,l=c({}.toString),d=c("".slice),u=function(e){return d(l(e),8,-1)},h=t,p=u,m=Object,_=s("".split),f=h((function(){return!m("z").propertyIsEnumerable(0)}))?function(e){return"String"==p(e)?_(e,""):m(e)}:m,g=function(e){return null==e},T=g,S=TypeError,v=function(e){if(T(e))throw S("Can't call method on "+e);return e},E=f,y=v,I=function(e){return E(y(e))},C=function(e){return e&&e.Math==Math&&e},A=C("object"==typeof globalThis&&globalThis)||C("object"==typeof window&&window)||C("object"==typeof self&&self)||C("object"==typeof e&&e)||function(){return this}()||Function("return this")(),R={},b={get exports(){return R},set exports(e){R=e}},k=A,D=Object.defineProperty,O=function(e,t){try{D(k,e,{value:t,configurable:!0,writable:!0})}catch(i){k[e]=t}return t},N=O,P="__core-js_shared__",w=A[P]||N(P,{}),M=w;(b.exports=function(e,t){return M[e]||(M[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.30.0",mode:"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.30.0/LICENSE",source:"https://github.com/zloirock/core-js"});var L,V,U=v,x=Object,F=function(e){return x(U(e))},B=F,j=s({}.hasOwnProperty),H=Object.hasOwn||function(e,t){return j(B(e),t)},G=s,W=0,J=Math.random(),K=G(1..toString),z=function(e){return"Symbol("+(void 0===e?"":e)+")_"+K(++W+J,36)},Y="undefined"!=typeof navigator&&String(navigator.userAgent)||"",q=A,Q=Y,X=q.process,$=q.Deno,Z=X&&X.versions||$&&$.version,ee=Z&&Z.v8;ee&&(V=(L=ee.split("."))[0]>0&&L[0]<4?1:+(L[0]+L[1])),!V&&Q&&(!(L=Q.match(/Edge\/(\d+)/))||L[1]>=74)&&(L=Q.match(/Chrome\/(\d+)/))&&(V=+L[1]);var te=V,ie=te,re=t,ne=!!Object.getOwnPropertySymbols&&!re((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ie&&ie<41})),oe=ne&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ae=R,se=H,ce=z,le=ne,de=oe,ue=A.Symbol,he=ae("wks"),pe=de?ue.for||ue:ue&&ue.withoutSetter||ce,me=function(e){return se(he,e)||(he[e]=le&&se(ue,e)?ue[e]:pe("Symbol."+e)),he[e]},_e="object"==typeof document&&document.all,fe={all:_e,IS_HTMLDDA:void 0===_e&&void 0!==_e},ge=fe.all,Te=fe.IS_HTMLDDA?function(e){return"function"==typeof e||e===ge}:function(e){return"function"==typeof e},Se=Te,ve=fe.all,Ee=fe.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:Se(e)||e===ve}:function(e){return"object"==typeof e?null!==e:Se(e)},ye=Ee,Ie=String,Ce=TypeError,Ae=function(e){if(ye(e))return e;throw Ce(Ie(e)+" is not an object")},Re={},be=!t((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),ke=be&&t((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),De={},Oe=Ee,Ne=A.document,Pe=Oe(Ne)&&Oe(Ne.createElement),we=function(e){return Pe?Ne.createElement(e):{}},Me=we,Le=!be&&!t((function(){return 7!=Object.defineProperty(Me("div"),"a",{get:function(){return 7}}).a})),Ve=i,Ue=Function.prototype.call,xe=Ve?Ue.bind(Ue):function(){return Ue.apply(Ue,arguments)},Fe=A,Be=Te,je=function(e){return Be(e)?e:void 0},He=function(e,t){return arguments.length<2?je(Fe[e]):Fe[e]&&Fe[e][t]},Ge=s({}.isPrototypeOf),We=He,Je=Te,Ke=Ge,ze=Object,Ye=oe?function(e){return"symbol"==typeof e}:function(e){var t=We("Symbol");return Je(t)&&Ke(t.prototype,ze(e))},qe=String,Qe=function(e){try{return qe(e)}catch(t){return"Object"}},Xe=Te,$e=Qe,Ze=TypeError,et=function(e){if(Xe(e))return e;throw Ze($e(e)+" is not a function")},tt=et,it=g,rt=function(e,t){var i=e[t];return it(i)?void 0:tt(i)},nt=xe,ot=Te,at=Ee,st=TypeError,ct=xe,lt=Ee,dt=Ye,ut=rt,ht=function(e,t){var i,r;if("string"===t&&ot(i=e.toString)&&!at(r=nt(i,e)))return r;if(ot(i=e.valueOf)&&!at(r=nt(i,e)))return r;if("string"!==t&&ot(i=e.toString)&&!at(r=nt(i,e)))return r;throw st("Can't convert object to primitive value")},pt=TypeError,mt=me("toPrimitive"),_t=function(e,t){if(!lt(e)||dt(e))return e;var i,r=ut(e,mt);if(r){if(void 0===t&&(t="default"),i=ct(r,e,t),!lt(i)||dt(i))return i;throw pt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ht(e,t)},ft=_t,gt=Ye,Tt=function(e){var t=ft(e,"string");return gt(t)?t:t+""},St=be,vt=Le,Et=ke,yt=Ae,It=Tt,Ct=TypeError,At=Object.defineProperty,Rt=Object.getOwnPropertyDescriptor,bt="enumerable",kt="configurable",Dt="writable";De.f=St?Et?function(e,t,i){if(yt(e),t=It(t),yt(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Dt in i&&!i.writable){var r=Rt(e,t);r&&r.writable&&(e[t]=i.value,i={configurable:kt in i?i.configurable:r.configurable,enumerable:bt in i?i.enumerable:r.enumerable,writable:!1})}return At(e,t,i)}:At:function(e,t,i){if(yt(e),t=It(t),yt(i),vt)try{return At(e,t,i)}catch(r){}if("get"in i||"set"in i)throw Ct("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Ot=Math.ceil,Nt=Math.floor,Pt=Math.trunc||function(e){var t=+e;return(t>0?Nt:Ot)(t)},wt=Pt,Mt=function(e){var t=+e;return t!=t||0===t?0:wt(t)},Lt=Mt,Vt=Math.max,Ut=Math.min,xt=function(e,t){var i=Lt(e);return i<0?Vt(i+t,0):Ut(i,t)},Ft=Mt,Bt=Math.min,jt=function(e){return e>0?Bt(Ft(e),9007199254740991):0},Ht=jt,Gt=function(e){return Ht(e.length)},Wt=I,Jt=xt,Kt=Gt,zt=function(e){return function(t,i,r){var n,o=Wt(t),a=Kt(o),s=Jt(r,a);if(e&&i!=i){for(;a>s;)if((n=o[s++])!=n)return!0}else for(;a>s;s++)if((e||s in o)&&o[s]===i)return e||s||0;return!e&&-1}},Yt={includes:zt(!0),indexOf:zt(!1)},qt={},Qt=H,Xt=I,$t=Yt.indexOf,Zt=qt,ei=s([].push),ti=function(e,t){var i,r=Xt(e),n=0,o=[];for(i in r)!Qt(Zt,i)&&Qt(r,i)&&ei(o,i);for(;t.length>n;)Qt(r,i=t[n++])&&(~$t(o,i)||ei(o,i));return o},ii=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ri=ti,ni=ii,oi=Object.keys||function(e){return ri(e,ni)},ai=be,si=ke,ci=De,li=Ae,di=I,ui=oi;Re.f=ai&&!si?Object.defineProperties:function(e,t){li(e);for(var i,r=di(t),n=ui(t),o=n.length,a=0;o>a;)ci.f(e,i=n[a++],r[i]);return e};var hi,pi=He("document","documentElement"),mi=z,_i=R("keys"),fi=function(e){return _i[e]||(_i[e]=mi(e))},gi=Ae,Ti=Re,Si=ii,vi=qt,Ei=pi,yi=we,Ii=fi("IE_PROTO"),Ci=function(){},Ai=function(e){return"<script>"+e+"</"+"script>"},Ri=function(e){e.write(Ai("")),e.close();var t=e.parentWindow.Object;return e=null,t},bi=function(){try{hi=new ActiveXObject("htmlfile")}catch(r){}var e,t;bi="undefined"!=typeof document?document.domain&&hi?Ri(hi):((t=yi("iframe")).style.display="none",Ei.appendChild(t),t.src=String("javascript:"),(e=t.contentWindow.document).open(),e.write(Ai("document.F=Object")),e.close(),e.F):Ri(hi);for(var i=Si.length;i--;)delete bi.prototype[Si[i]];return bi()};vi[Ii]=!0;var ki=Object.create||function(e,t){var i;return null!==e?(Ci.prototype=gi(e),i=new Ci,Ci.prototype=null,i[Ii]=e):i=bi(),void 0===t?i:Ti.f(i,t)},Di=me,Oi=ki,Ni=De.f,Pi=Di("unscopables"),wi=Array.prototype;null==wi[Pi]&&Ni(wi,Pi,{configurable:!0,value:Oi(null)});var Mi,Li,Vi,Ui=function(e){wi[Pi][e]=!0},xi={},Fi=Te,Bi=A.WeakMap,ji=Fi(Bi)&&/native code/.test(String(Bi)),Hi=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},Gi=De,Wi=Hi,Ji=be?function(e,t,i){return Gi.f(e,t,Wi(1,i))}:function(e,t,i){return e[t]=i,e},Ki=ji,zi=A,Yi=Ee,qi=Ji,Qi=H,Xi=w,$i=fi,Zi=qt,er="Object already initialized",tr=zi.TypeError,ir=zi.WeakMap;if(Ki||Xi.state){var rr=Xi.state||(Xi.state=new ir);rr.get=rr.get,rr.has=rr.has,rr.set=rr.set,Mi=function(e,t){if(rr.has(e))throw tr(er);return t.facade=e,rr.set(e,t),t},Li=function(e){return rr.get(e)||{}},Vi=function(e){return rr.has(e)}}else{var nr=$i("state");Zi[nr]=!0,Mi=function(e,t){if(Qi(e,nr))throw tr(er);return t.facade=e,qi(e,nr,t),t},Li=function(e){return Qi(e,nr)?e[nr]:{}},Vi=function(e){return Qi(e,nr)}}var or={set:Mi,get:Li,has:Vi,enforce:function(e){return Vi(e)?Li(e):Mi(e,{})},getterFor:function(e){return function(t){var i;if(!Yi(t)||(i=Li(t)).type!==e)throw tr("Incompatible receiver, "+e+" required");return i}}},ar={},sr={},cr={}.propertyIsEnumerable,lr=Object.getOwnPropertyDescriptor,dr=lr&&!cr.call({1:2},1);sr.f=dr?function(e){var t=lr(this,e);return!!t&&t.enumerable}:cr;var ur=be,hr=xe,pr=sr,mr=Hi,_r=I,fr=Tt,gr=H,Tr=Le,Sr=Object.getOwnPropertyDescriptor;ar.f=ur?Sr:function(e,t){if(e=_r(e),t=fr(t),Tr)try{return Sr(e,t)}catch(i){}if(gr(e,t))return mr(!hr(pr.f,e,t),e[t])};var vr={},Er={get exports(){return vr},set exports(e){vr=e}},yr=be,Ir=H,Cr=Function.prototype,Ar=yr&&Object.getOwnPropertyDescriptor,Rr=Ir(Cr,"name"),br={EXISTS:Rr,PROPER:Rr&&"something"===function(){}.name,CONFIGURABLE:Rr&&(!yr||yr&&Ar(Cr,"name").configurable)},kr=Te,Dr=w,Or=s(Function.toString);kr(Dr.inspectSource)||(Dr.inspectSource=function(e){return Or(e)});var Nr=Dr.inspectSource,Pr=s,wr=t,Mr=Te,Lr=H,Vr=be,Ur=br.CONFIGURABLE,xr=Nr,Fr=or.enforce,Br=or.get,jr=String,Hr=Object.defineProperty,Gr=Pr("".slice),Wr=Pr("".replace),Jr=Pr([].join),Kr=Vr&&!wr((function(){return 8!==Hr((function(){}),"length",{value:8}).length})),zr=String(String).split("String"),Yr=Er.exports=function(e,t,i){"Symbol("===Gr(jr(t),0,7)&&(t="["+Wr(jr(t),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Lr(e,"name")||Ur&&e.name!==t)&&(Vr?Hr(e,"name",{value:t,configurable:!0}):e.name=t),Kr&&i&&Lr(i,"arity")&&e.length!==i.arity&&Hr(e,"length",{value:i.arity});try{i&&Lr(i,"constructor")&&i.constructor?Vr&&Hr(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var r=Fr(e);return Lr(r,"source")||(r.source=Jr(zr,"string"==typeof t?t:"")),e};Function.prototype.toString=Yr((function(){return Mr(this)&&Br(this).source||xr(this)}),"toString");var qr=Te,Qr=De,Xr=vr,$r=O,Zr=function(e,t,i,r){r||(r={});var n=r.enumerable,o=void 0!==r.name?r.name:t;if(qr(i)&&Xr(i,o,r),r.global)n?e[t]=i:$r(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch(a){}n?e[t]=i:Qr.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},en={},tn=ti,rn=ii.concat("length","prototype");en.f=Object.getOwnPropertyNames||function(e){return tn(e,rn)};var nn={};nn.f=Object.getOwnPropertySymbols;var on,an,sn,cn=He,ln=en,dn=nn,un=Ae,hn=s([].concat),pn=cn("Reflect","ownKeys")||function(e){var t=ln.f(un(e)),i=dn.f;return i?hn(t,i(e)):t},mn=H,_n=pn,fn=ar,gn=De,Tn=function(e,t,i){for(var r=_n(t),n=gn.f,o=fn.f,a=0;a<r.length;a++){var s=r[a];mn(e,s)||i&&mn(i,s)||n(e,s,o(t,s))}},Sn=t,vn=Te,En=/#|\.prototype\./,yn=function(e,t){var i=Cn[In(e)];return i==Rn||i!=An&&(vn(t)?Sn(t):!!t)},In=yn.normalize=function(e){return String(e).replace(En,".").toLowerCase()},Cn=yn.data={},An=yn.NATIVE="N",Rn=yn.POLYFILL="P",bn=yn,kn=A,Dn=ar.f,On=Ji,Nn=Zr,Pn=O,wn=Tn,Mn=bn,Ln=function(e,t){var i,r,n,o,a,s=e.target,c=e.global,l=e.stat;if(i=c?kn:l?kn[s]||Pn(s,{}):(kn[s]||{}).prototype)for(r in t){if(o=t[r],n=e.dontCallGetSet?(a=Dn(i,r))&&a.value:i[r],!Mn(c?r:s+(l?".":"#")+r,e.forced)&&void 0!==n){if(typeof o==typeof n)continue;wn(o,n)}(e.sham||n&&n.sham)&&On(o,"sham",!0),Nn(i,r,o,e)}},Vn=!t((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Un=H,xn=Te,Fn=F,Bn=Vn,jn=fi("IE_PROTO"),Hn=Object,Gn=Hn.prototype,Wn=Bn?Hn.getPrototypeOf:function(e){var t=Fn(e);if(Un(t,jn))return t[jn];var i=t.constructor;return xn(i)&&t instanceof i?i.prototype:t instanceof Hn?Gn:null},Jn=t,Kn=Te,zn=Ee,Yn=Wn,qn=Zr,Qn=me("iterator"),Xn=!1;[].keys&&("next"in(sn=[].keys())?(an=Yn(Yn(sn)))!==Object.prototype&&(on=an):Xn=!0);var $n=!zn(on)||Jn((function(){var e={};return on[Qn].call(e)!==e}));$n&&(on={}),Kn(on[Qn])||qn(on,Qn,(function(){return this}));var Zn={IteratorPrototype:on,BUGGY_SAFARI_ITERATORS:Xn},eo=De.f,to=H,io=me("toStringTag"),ro=function(e,t,i){e&&!i&&(e=e.prototype),e&&!to(e,io)&&eo(e,io,{configurable:!0,value:t})},no=Zn.IteratorPrototype,oo=ki,ao=Hi,so=ro,co=xi,lo=function(){return this},uo=function(e,t,i,r){var n=t+" Iterator";return e.prototype=oo(no,{next:ao(+!r,i)}),so(e,n,!1),co[n]=lo,e},ho=s,po=et,mo=Te,_o=String,fo=TypeError,go=function(e,t,i){try{return ho(po(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},To=Ae,So=function(e){if("object"==typeof e||mo(e))return e;throw fo("Can't set "+_o(e)+" as a prototype")},vo=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=go(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return To(i),So(r),t?e(i,r):i.__proto__=r,i}}():void 0),Eo=Ln,yo=xe,Io=Te,Co=uo,Ao=Wn,Ro=vo,bo=ro,ko=Ji,Do=Zr,Oo=xi,No=br.PROPER,Po=br.CONFIGURABLE,wo=Zn.IteratorPrototype,Mo=Zn.BUGGY_SAFARI_ITERATORS,Lo=me("iterator"),Vo="keys",Uo="values",xo="entries",Fo=function(){return this},Bo=function(e,t,i,r,n,o,a){Co(i,t,r);var s,c,l,d=function(e){if(e===n&&_)return _;if(!Mo&&e in p)return p[e];switch(e){case Vo:case Uo:case xo:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[Lo]||p["@@iterator"]||n&&p[n],_=!Mo&&m||d(n),f="Array"==t&&p.entries||m;if(f&&(s=Ao(f.call(new e)))!==Object.prototype&&s.next&&(Ao(s)!==wo&&(Ro?Ro(s,wo):Io(s[Lo])||Do(s,Lo,Fo)),bo(s,u,!0)),No&&n==Uo&&m&&m.name!==Uo&&(Po?ko(p,"name",Uo):(h=!0,_=function(){return yo(m,this)})),n)if(c={values:d(Uo),keys:o?_:d(Vo),entries:d(xo)},a)for(l in c)(Mo||h||!(l in p))&&Do(p,l,c[l]);else Eo({target:t,proto:!0,forced:Mo||h},c);return p[Lo]!==_&&Do(p,Lo,_,{name:n}),Oo[t]=_,c},jo=function(e,t){return{value:e,done:t}},Ho=I,Go=Ui,Wo=xi,Jo=or,Ko=De.f,zo=Bo,Yo=jo,qo=be,Qo="Array Iterator",Xo=Jo.set,$o=Jo.getterFor(Qo),Zo=zo(Array,"Array",(function(e,t){Xo(this,{type:Qo,target:Ho(e),index:0,kind:t})}),(function(){var e=$o(this),t=e.target,i=e.kind,r=e.index++;return!t||r>=t.length?(e.target=void 0,Yo(void 0,!0)):Yo("keys"==i?r:"values"==i?t[r]:[r,t[r]],!1)}),"values"),ea=Wo.Arguments=Wo.Array;if(Go("keys"),Go("values"),Go("entries"),qo&&"values"!==ea.name)try{Ko(ea,"name",{value:"values"})}catch(NU){}var ta={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},ia=we("span").classList,ra=ia&&ia.constructor&&ia.constructor.prototype,na=ra===Object.prototype?void 0:ra,oa=A,aa=ta,sa=na,ca=Zo,la=Ji,da=me,ua=da("iterator"),ha=da("toStringTag"),pa=ca.values,ma=function(e,t){if(e){if(e[ua]!==pa)try{la(e,ua,pa)}catch(NU){e[ua]=pa}if(e[ha]||la(e,ha,t),aa[t])for(var i in ca)if(e[i]!==ca[i])try{la(e,i,ca[i])}catch(NU){e[i]=ca[i]}}};for(var _a in aa)ma(oa[_a]&&oa[_a].prototype,_a);ma(sa,"DOMTokenList");var fa="undefined"!=typeof process&&"process"==u(process),ga=vr,Ta=De,Sa=function(e,t,i){return i.get&&ga(i.get,t,{getter:!0}),i.set&&ga(i.set,t,{setter:!0}),Ta.f(e,t,i)},va=He,Ea=Sa,ya=be,Ia=me("species"),Ca=function(e){var t=va(e);ya&&t&&!t[Ia]&&Ea(t,Ia,{configurable:!0,get:function(){return this}})},Aa=Ge,Ra=TypeError,ba=function(e,t){if(Aa(t,e))return e;throw Ra("Incorrect invocation")},ka={};ka[me("toStringTag")]="z";var Da="[object z]"===String(ka),Oa=Te,Na=u,Pa=me("toStringTag"),wa=Object,Ma="Arguments"==Na(function(){return arguments}()),La=Da?Na: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(NU){}}(t=wa(e),Pa))?i:Ma?Na(t):"Object"==(r=Na(t))&&Oa(t.callee)?"Arguments":r},Va=s,Ua=t,xa=Te,Fa=La,Ba=Nr,ja=function(){},Ha=[],Ga=He("Reflect","construct"),Wa=/^\s*(?:class|function)\b/,Ja=Va(Wa.exec),Ka=!Wa.exec(ja),za=function(e){if(!xa(e))return!1;try{return Ga(ja,Ha,e),!0}catch(NU){return!1}},Ya=function(e){if(!xa(e))return!1;switch(Fa(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ka||!!Ja(Wa,Ba(e))}catch(NU){return!0}};Ya.sham=!0;var qa,Qa,Xa,$a,Za=!Ga||Ua((function(){var e;return za(za.call)||!za(Object)||!za((function(){e=!0}))||e}))?Ya:za,es=Za,ts=Qe,is=TypeError,rs=function(e){if(es(e))return e;throw is(ts(e)+" is not a constructor")},ns=Ae,os=rs,as=g,ss=me("species"),cs=function(e,t){var i,r=ns(e).constructor;return void 0===r||as(i=ns(r)[ss])?t:os(i)},ls=i,ds=Function.prototype,us=ds.apply,hs=ds.call,ps="object"==typeof Reflect&&Reflect.apply||(ls?hs.bind(us):function(){return hs.apply(us,arguments)}),ms=u,_s=s,fs=function(e){if("Function"===ms(e))return _s(e)},gs=et,Ts=i,Ss=fs(fs.bind),vs=function(e,t){return gs(e),void 0===t?e:Ts?Ss(e,t):function(){return e.apply(t,arguments)}},Es=s([].slice),ys=TypeError,Is=function(e,t){if(e<t)throw ys("Not enough arguments");return e},Cs=/(?:ipad|iphone|ipod).*applewebkit/i.test(Y),As=A,Rs=ps,bs=vs,ks=Te,Ds=H,Os=t,Ns=pi,Ps=Es,ws=we,Ms=Is,Ls=Cs,Vs=fa,Us=As.setImmediate,xs=As.clearImmediate,Fs=As.process,Bs=As.Dispatch,js=As.Function,Hs=As.MessageChannel,Gs=As.String,Ws=0,Js={},Ks="onreadystatechange";Os((function(){qa=As.location}));var zs=function(e){if(Ds(Js,e)){var t=Js[e];delete Js[e],t()}},Ys=function(e){return function(){zs(e)}},qs=function(e){zs(e.data)},Qs=function(e){As.postMessage(Gs(e),qa.protocol+"//"+qa.host)};Us&&xs||(Us=function(e){Ms(arguments.length,1);var t=ks(e)?e:js(e),i=Ps(arguments,1);return Js[++Ws]=function(){Rs(t,void 0,i)},Qa(Ws),Ws},xs=function(e){delete Js[e]},Vs?Qa=function(e){Fs.nextTick(Ys(e))}:Bs&&Bs.now?Qa=function(e){Bs.now(Ys(e))}:Hs&&!Ls?($a=(Xa=new Hs).port2,Xa.port1.onmessage=qs,Qa=bs($a.postMessage,$a)):As.addEventListener&&ks(As.postMessage)&&!As.importScripts&&qa&&"file:"!==qa.protocol&&!Os(Qs)?(Qa=Qs,As.addEventListener("message",qs,!1)):Qa=Ks in ws("script")?function(e){Ns.appendChild(ws("script")).onreadystatechange=function(){Ns.removeChild(this),zs(e)}}:function(e){setTimeout(Ys(e),0)});var Xs={set:Us,clear:xs},$s=function(){this.head=null,this.tail=null};$s.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 Zs,ec,tc,ic,rc,nc=$s,oc=/ipad|iphone|ipod/i.test(Y)&&"undefined"!=typeof Pebble,ac=/web0s(?!.*chrome)/i.test(Y),sc=A,cc=vs,lc=ar.f,dc=Xs.set,uc=nc,hc=Cs,pc=oc,mc=ac,_c=fa,fc=sc.MutationObserver||sc.WebKitMutationObserver,gc=sc.document,Tc=sc.process,Sc=sc.Promise,vc=lc(sc,"queueMicrotask"),Ec=vc&&vc.value;if(!Ec){var yc=new uc,Ic=function(){var e,t;for(_c&&(e=Tc.domain)&&e.exit();t=yc.get();)try{t()}catch(NU){throw yc.head&&Zs(),NU}e&&e.enter()};hc||_c||mc||!fc||!gc?!pc&&Sc&&Sc.resolve?((ic=Sc.resolve(void 0)).constructor=Sc,rc=cc(ic.then,ic),Zs=function(){rc(Ic)}):_c?Zs=function(){Tc.nextTick(Ic)}:(dc=cc(dc,sc),Zs=function(){dc(Ic)}):(ec=!0,tc=gc.createTextNode(""),new fc(Ic).observe(tc,{characterData:!0}),Zs=function(){tc.data=ec=!ec}),Ec=function(e){yc.head||Zs(),yc.add(e)}}var Cc=Ec,Ac=function(e){try{return{error:!1,value:e()}}catch(NU){return{error:!0,value:NU}}},Rc=A.Promise,bc="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,kc=!bc&&!fa&&"object"==typeof window&&"object"==typeof document,Dc=A,Oc=Rc,Nc=Te,Pc=bn,wc=Nr,Mc=me,Lc=kc,Vc=bc,Uc=te;Oc&&Oc.prototype;var xc=Mc("species"),Fc=!1,Bc=Nc(Dc.PromiseRejectionEvent),jc=Pc("Promise",(function(){var e=wc(Oc),t=e!==String(Oc);if(!t&&66===Uc)return!0;if(!Uc||Uc<51||!/native code/.test(e)){var i=new Oc((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((i.constructor={})[xc]=r,!(Fc=i.then((function(){}))instanceof r))return!0}return!t&&(Lc||Vc)&&!Bc})),Hc={CONSTRUCTOR:jc,REJECTION_EVENT:Bc,SUBCLASSING:Fc},Gc={},Wc=et,Jc=TypeError,Kc=function(e){var t,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw Jc("Bad Promise constructor");t=e,i=r})),this.resolve=Wc(t),this.reject=Wc(i)};Gc.f=function(e){return new Kc(e)};var zc,Yc,qc,Qc=Ln,Xc=fa,$c=A,Zc=xe,el=Zr,tl=vo,il=ro,rl=Ca,nl=et,ol=Te,al=Ee,sl=ba,cl=cs,ll=Xs.set,dl=Cc,ul=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(NU){}},hl=Ac,pl=nc,ml=or,_l=Rc,fl=Gc,gl="Promise",Tl=Hc.CONSTRUCTOR,Sl=Hc.REJECTION_EVENT,vl=Hc.SUBCLASSING,El=ml.getterFor(gl),yl=ml.set,Il=_l&&_l.prototype,Cl=_l,Al=Il,Rl=$c.TypeError,bl=$c.document,kl=$c.process,Dl=fl.f,Ol=Dl,Nl=!!(bl&&bl.createEvent&&$c.dispatchEvent),Pl="unhandledrejection",wl=function(e){var t;return!(!al(e)||!ol(t=e.then))&&t},Ml=function(e,t){var i,r,n,o=t.value,a=1==t.state,s=a?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{s?(a||(2===t.rejection&&Fl(t),t.rejection=1),!0===s?i=o:(d&&d.enter(),i=s(o),d&&(d.exit(),n=!0)),i===e.promise?l(Rl("Promise-chain cycle")):(r=wl(i))?Zc(r,i,c,l):c(i)):l(o)}catch(NU){d&&!n&&d.exit(),l(NU)}},Ll=function(e,t){e.notified||(e.notified=!0,dl((function(){for(var i,r=e.reactions;i=r.get();)Ml(i,e);e.notified=!1,t&&!e.rejection&&Ul(e)})))},Vl=function(e,t,i){var r,n;Nl?((r=bl.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),$c.dispatchEvent(r)):r={promise:t,reason:i},!Sl&&(n=$c["on"+e])?n(r):e===Pl&&ul("Unhandled promise rejection",i)},Ul=function(e){Zc(ll,$c,(function(){var t,i=e.facade,r=e.value;if(xl(e)&&(t=hl((function(){Xc?kl.emit("unhandledRejection",r,i):Vl(Pl,i,r)})),e.rejection=Xc||xl(e)?2:1,t.error))throw t.value}))},xl=function(e){return 1!==e.rejection&&!e.parent},Fl=function(e){Zc(ll,$c,(function(){var t=e.facade;Xc?kl.emit("rejectionHandled",t):Vl("rejectionhandled",t,e.value)}))},Bl=function(e,t,i){return function(r){e(t,r,i)}},jl=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Ll(e,!0))},Hl=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw Rl("Promise can't be resolved itself");var r=wl(t);r?dl((function(){var i={done:!1};try{Zc(r,t,Bl(Hl,i,e),Bl(jl,i,e))}catch(NU){jl(i,NU,e)}})):(e.value=t,e.state=1,Ll(e,!1))}catch(NU){jl({done:!1},NU,e)}}};if(Tl&&(Al=(Cl=function(e){sl(this,Al),nl(e),Zc(zc,this);var t=El(this);try{e(Bl(Hl,t),Bl(jl,t))}catch(NU){jl(t,NU)}}).prototype,(zc=function(e){yl(this,{type:gl,done:!1,notified:!1,parent:!1,reactions:new pl,rejection:!1,state:0,value:void 0})}).prototype=el(Al,"then",(function(e,t){var i=El(this),r=Dl(cl(this,Cl));return i.parent=!0,r.ok=!ol(e)||e,r.fail=ol(t)&&t,r.domain=Xc?kl.domain:void 0,0==i.state?i.reactions.add(r):dl((function(){Ml(r,i)})),r.promise})),Yc=function(){var e=new zc,t=El(e);this.promise=e,this.resolve=Bl(Hl,t),this.reject=Bl(jl,t)},fl.f=Dl=function(e){return e===Cl||undefined===e?new Yc(e):Ol(e)},ol(_l)&&Il!==Object.prototype)){qc=Il.then,vl||el(Il,"then",(function(e,t){var i=this;return new Cl((function(e,t){Zc(qc,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete Il.constructor}catch(NU){}tl&&tl(Il,Al)}Qc({global:!0,constructor:!0,wrap:!0,forced:Tl},{Promise:Cl}),il(Cl,gl,!1),rl(gl);var Gl=xi,Wl=me("iterator"),Jl=Array.prototype,Kl=function(e){return void 0!==e&&(Gl.Array===e||Jl[Wl]===e)},zl=La,Yl=rt,ql=g,Ql=xi,Xl=me("iterator"),$l=function(e){if(!ql(e))return Yl(e,Xl)||Yl(e,"@@iterator")||Ql[zl(e)]},Zl=xe,ed=et,td=Ae,id=Qe,rd=$l,nd=TypeError,od=function(e,t){var i=arguments.length<2?rd(e):t;if(ed(i))return td(Zl(i,e));throw nd(id(e)+" is not iterable")},ad=xe,sd=Ae,cd=rt,ld=function(e,t,i){var r,n;sd(e);try{if(!(r=cd(e,"return"))){if("throw"===t)throw i;return i}r=ad(r,e)}catch(NU){n=!0,r=NU}if("throw"===t)throw i;if(n)throw r;return sd(r),i},dd=vs,ud=xe,hd=Ae,pd=Qe,md=Kl,_d=Gt,fd=Ge,gd=od,Td=$l,Sd=ld,vd=TypeError,Ed=function(e,t){this.stopped=e,this.result=t},yd=Ed.prototype,Id=function(e,t,i){var r,n,o,a,s,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),_=dd(t,d),f=function(e){return r&&Sd(r,"normal",e),new Ed(!0,e)},g=function(e){return u?(hd(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=Td(e)))throw vd(pd(e)+" is not iterable");if(md(n)){for(o=0,a=_d(e);a>o;o++)if((s=g(e[o]))&&fd(yd,s))return s;return new Ed(!1)}r=gd(e,n)}for(c=h?e.next:r.next;!(l=ud(c,r)).done;){try{s=g(l.value)}catch(NU){Sd(r,"throw",NU)}if("object"==typeof s&&s&&fd(yd,s))return s}return new Ed(!1)},Cd=me("iterator"),Ad=!1;try{var Rd=0,bd={next:function(){return{done:!!Rd++}},return:function(){Ad=!0}};bd[Cd]=function(){return this},Array.from(bd,(function(){throw 2}))}catch(NU){}var kd=function(e,t){if(!t&&!Ad)return!1;var i=!1;try{var r={};r[Cd]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(NU){}return i},Dd=Rc,Od=Hc.CONSTRUCTOR||!kd((function(e){Dd.all(e).then(void 0,(function(){}))})),Nd=xe,Pd=et,wd=Gc,Md=Ac,Ld=Id;Ln({target:"Promise",stat:!0,forced:Od},{all:function(e){var t=this,i=wd.f(t),r=i.resolve,n=i.reject,o=Md((function(){var i=Pd(t.resolve),o=[],a=0,s=1;Ld(e,(function(e){var c=a++,l=!1;s++,Nd(i,t,e).then((function(e){l||(l=!0,o[c]=e,--s||r(o))}),n)})),--s||r(o)}));return o.error&&n(o.value),i.promise}});var Vd=Ln,Ud=Hc.CONSTRUCTOR,xd=Rc,Fd=He,Bd=Te,jd=Zr,Hd=xd&&xd.prototype;if(Vd({target:"Promise",proto:!0,forced:Ud,real:!0},{catch:function(e){return this.then(void 0,e)}}),Bd(xd)){var Gd=Fd("Promise").prototype.catch;Hd.catch!==Gd&&jd(Hd,"catch",Gd,{unsafe:!0})}var Wd=xe,Jd=et,Kd=Gc,zd=Ac,Yd=Id;Ln({target:"Promise",stat:!0,forced:Od},{race:function(e){var t=this,i=Kd.f(t),r=i.reject,n=zd((function(){var n=Jd(t.resolve);Yd(e,(function(e){Wd(n,t,e).then(i.resolve,r)}))}));return n.error&&r(n.value),i.promise}});var qd=xe,Qd=Gc;Ln({target:"Promise",stat:!0,forced:Hc.CONSTRUCTOR},{reject:function(e){var t=Qd.f(this);return qd(t.reject,void 0,e),t.promise}});var Xd=Ae,$d=Ee,Zd=Gc,eu=function(e,t){if(Xd(e),$d(t)&&t.constructor===e)return t;var i=Zd.f(e);return(0,i.resolve)(t),i.promise},tu=Ln,iu=Hc.CONSTRUCTOR,ru=eu;He("Promise"),tu({target:"Promise",stat:!0,forced:iu},{resolve:function(e){return ru(this,e)}});var nu=La,ou=String,au=function(e){if("Symbol"===nu(e))throw TypeError("Cannot convert a Symbol value to a string");return ou(e)},su=Ln,cu=be,lu=s,du=H,uu=Te,hu=Ge,pu=au,mu=Sa,_u=Tn,fu=A.Symbol,gu=fu&&fu.prototype;if(cu&&uu(fu)&&(!("description"in gu)||void 0!==fu().description)){var Tu={},Su=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:pu(arguments[0]),t=hu(gu,this)?new fu(e):void 0===e?fu():fu(e);return""===e&&(Tu[t]=!0),t};_u(Su,fu),Su.prototype=gu,gu.constructor=Su;var vu="Symbol(test)"==String(fu("test")),Eu=lu(gu.valueOf),yu=lu(gu.toString),Iu=/^Symbol\((.*)\)[^)]+$/,Cu=lu("".replace),Au=lu("".slice);mu(gu,"description",{configurable:!0,get:function(){var e=Eu(this);if(du(Tu,e))return"";var t=yu(e),i=vu?Au(t,7,-1):Cu(t,Iu,"$1");return""===i?void 0:i}}),su({global:!0,constructor:!0,forced:!0},{Symbol:Su})}var Ru=Ae,bu=function(){var e=Ru(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},ku=t,Du=A.RegExp,Ou=ku((function(){var e=Du("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),Nu=Ou||ku((function(){return!Du("a","y").sticky})),Pu=Ou||ku((function(){var e=Du("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),wu={BROKEN_CARET:Pu,MISSED_STICKY:Nu,UNSUPPORTED_Y:Ou},Mu=t,Lu=A.RegExp,Vu=Mu((function(){var e=Lu(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),Uu=t,xu=A.RegExp,Fu=Uu((function(){var e=xu("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Bu=xe,ju=s,Hu=au,Gu=bu,Wu=wu,Ju=ki,Ku=or.get,zu=Vu,Yu=Fu,qu=R("native-string-replace",String.prototype.replace),Qu=RegExp.prototype.exec,Xu=Qu,$u=ju("".charAt),Zu=ju("".indexOf),eh=ju("".replace),th=ju("".slice),ih=function(){var e=/a/,t=/b*/g;return Bu(Qu,e,"a"),Bu(Qu,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),rh=Wu.BROKEN_CARET,nh=void 0!==/()??/.exec("")[1];(ih||nh||rh||zu||Yu)&&(Xu=function(e){var t,i,r,n,o,a,s,c=this,l=Ku(c),d=Hu(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=Bu(Xu,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=rh&&c.sticky,m=Bu(Gu,c),_=c.source,f=0,g=d;if(p&&(m=eh(m,"y",""),-1===Zu(m,"g")&&(m+="g"),g=th(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==$u(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),nh&&(i=new RegExp("^"+_+"$(?!\\s)",m)),ih&&(r=c.lastIndex),n=Bu(Qu,p?i:c,g),p?n?(n.input=th(n.input,f),n[0]=th(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:ih&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),nh&&n&&n.length>1&&Bu(qu,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=a=Ju(null),o=0;o<h.length;o++)a[(s=h[o])[0]]=n[s[1]];return n});var oh=Xu;Ln({target:"RegExp",proto:!0,forced:/./.exec!==oh},{exec:oh});var ah=et,sh=F,ch=f,lh=Gt,dh=TypeError,uh=function(e){return function(t,i,r,n){ah(i);var o=sh(t),a=ch(o),s=lh(o),c=e?s-1:0,l=e?-1:1;if(r<2)for(;;){if(c in a){n=a[c],c+=l;break}if(c+=l,e?c<0:s<=c)throw dh("Reduce of empty array with no initial value")}for(;e?c>=0:s>c;c+=l)c in a&&(n=i(n,a[c],c,o));return n}},hh={left:uh(!1),right:uh(!0)},ph=t,mh=function(e,t){var i=[][e];return!!i&&ph((function(){i.call(null,t||function(){return 1},1)}))},_h=hh.left;Ln({target:"Array",proto:!0,forced:!fa&&te>79&&te<83||!mh("reduce")},{reduce:function(e){var t=arguments.length;return _h(this,e,t,t>1?arguments[1]:void 0)}});var fh=u,gh=Array.isArray||function(e){return"Array"==fh(e)},Th=gh,Sh=Za,vh=Ee,Eh=me("species"),yh=Array,Ih=function(e){var t;return Th(e)&&(t=e.constructor,(Sh(t)&&(t===yh||Th(t.prototype))||vh(t)&&null===(t=t[Eh]))&&(t=void 0)),void 0===t?yh:t},Ch=vs,Ah=f,Rh=F,bh=Gt,kh=function(e,t){return new(Ih(e))(0===t?0:t)},Dh=s([].push),Oh=function(e){var t=1==e,i=2==e,r=3==e,n=4==e,o=6==e,a=7==e,s=5==e||o;return function(c,l,d,u){for(var h,p,m=Rh(c),_=Ah(m),f=Ch(l,d),g=bh(_),T=0,S=u||kh,v=t?S(c,g):i||a?S(c,0):void 0;g>T;T++)if((s||T in _)&&(p=f(h=_[T],T,m),e))if(t)v[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:Dh(v,h)}else switch(e){case 4:return!1;case 7:Dh(v,h)}return o?-1:r||n?n:v}},Nh={forEach:Oh(0),map:Oh(1),filter:Oh(2),some:Oh(3),every:Oh(4),find:Oh(5),findIndex:Oh(6),filterReject:Oh(7)},Ph=Nh.forEach,wh=mh("forEach")?[].forEach:function(e){return Ph(this,e,arguments.length>1?arguments[1]:void 0)},Mh=A,Lh=ta,Vh=na,Uh=wh,xh=Ji,Fh=function(e){if(e&&e.forEach!==Uh)try{xh(e,"forEach",Uh)}catch(NU){e.forEach=Uh}};for(var Bh in Lh)Lh[Bh]&&Fh(Mh[Bh]&&Mh[Bh].prototype);Fh(Vh);var jh=Yt.includes,Hh=Ui;Ln({target:"Array",proto:!0,forced:t((function(){return!Array(1).includes()}))},{includes:function(e){return jh(this,e,arguments.length>1?arguments[1]:void 0)}}),Hh("includes");var Gh=fs,Wh=Zr,Jh=oh,Kh=t,zh=me,Yh=Ji,qh=zh("species"),Qh=RegExp.prototype,Xh=s,$h=Mt,Zh=au,ep=v,tp=Xh("".charAt),ip=Xh("".charCodeAt),rp=Xh("".slice),np=function(e){return function(t,i){var r,n,o=Zh(ep(t)),a=$h(i),s=o.length;return a<0||a>=s?e?"":void 0:(r=ip(o,a))<55296||r>56319||a+1===s||(n=ip(o,a+1))<56320||n>57343?e?tp(o,a):r:e?rp(o,a,a+2):n-56320+(r-55296<<10)+65536}},op={codeAt:np(!1),charAt:np(!0)},ap=op.charAt,sp=s,cp=F,lp=Math.floor,dp=sp("".charAt),up=sp("".replace),hp=sp("".slice),pp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,mp=/\$([$&'`]|\d{1,2})/g,_p=xe,fp=Ae,gp=Te,Tp=u,Sp=oh,vp=TypeError,Ep=ps,yp=xe,Ip=s,Cp=function(e,t,i,r){var n=zh(e),o=!Kh((function(){var t={};return t[n]=function(){return 7},7!=""[e](t)})),a=o&&!Kh((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[qh]=function(){return i},i.flags="",i[n]=/./[n]),i.exec=function(){return t=!0,null},i[n](""),!t}));if(!o||!a||i){var s=Gh(/./[n]),c=t(n,""[e],(function(e,t,i,r,n){var a=Gh(e),c=t.exec;return c===Jh||c===Qh.exec?o&&!n?{done:!0,value:s(t,i,r)}:{done:!0,value:a(i,t,r)}:{done:!1}}));Wh(String.prototype,e,c[0]),Wh(Qh,n,c[1])}r&&Yh(Qh[n],"sham",!0)},Ap=t,Rp=Ae,bp=Te,kp=g,Dp=Mt,Op=jt,Np=au,Pp=v,wp=function(e,t,i){return t+(i?ap(e,t).length:1)},Mp=rt,Lp=function(e,t,i,r,n,o){var a=i+e.length,s=r.length,c=mp;return void 0!==n&&(n=cp(n),c=pp),up(o,c,(function(o,c){var l;switch(dp(c,0)){case"$":return"$";case"&":return e;case"`":return hp(t,0,i);case"'":return hp(t,a);case"<":l=n[hp(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>s){var u=lp(d/10);return 0===u?o:u<=s?void 0===r[u-1]?dp(c,1):r[u-1]+dp(c,1):o}l=r[d-1]}return void 0===l?"":l}))},Vp=function(e,t){var i=e.exec;if(gp(i)){var r=_p(i,e,t);return null!==r&&fp(r),r}if("RegExp"===Tp(e))return _p(Sp,e,t);throw vp("RegExp#exec called on incompatible receiver")},Up=me("replace"),xp=Math.max,Fp=Math.min,Bp=Ip([].concat),jp=Ip([].push),Hp=Ip("".indexOf),Gp=Ip("".slice),Wp="$0"==="a".replace(/./,"$0"),Jp=!!/./[Up]&&""===/./[Up]("a","$0"),Kp=!Ap((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));Cp("replace",(function(e,t,i){var r=Jp?"$":"$0";return[function(e,i){var r=Pp(this),n=kp(e)?void 0:Mp(e,Up);return n?yp(n,e,r,i):yp(t,Np(r),e,i)},function(e,n){var o=Rp(this),a=Np(e);if("string"==typeof n&&-1===Hp(n,r)&&-1===Hp(n,"$<")){var s=i(t,o,a,n);if(s.done)return s.value}var c=bp(n);c||(n=Np(n));var l=o.global;if(l){var d=o.unicode;o.lastIndex=0}for(var u=[];;){var h=Vp(o,a);if(null===h)break;if(jp(u,h),!l)break;""===Np(h[0])&&(o.lastIndex=wp(a,Op(o.lastIndex),d))}for(var p,m="",_=0,f=0;f<u.length;f++){for(var g=Np((h=u[f])[0]),T=xp(Fp(Dp(h.index),a.length),0),S=[],v=1;v<h.length;v++)jp(S,void 0===(p=h[v])?p:String(p));var E=h.groups;if(c){var y=Bp([g],S,T,a);void 0!==E&&jp(y,E);var I=Np(Ep(n,void 0,y))}else I=Lp(g,a,T,S,E,n);T>=_&&(m+=Gp(a,_,T)+I,_=T+g.length)}return m+Gp(a,_)}]}),!Kp||!Wp||Jp);var zp=Te,Yp=Ee,qp=vo,Qp=function(e,t,i){var r,n;return qp&&zp(r=t.constructor)&&r!==i&&Yp(n=r.prototype)&&n!==i.prototype&&qp(e,n),e},Xp=Ee,$p=u,Zp=me("match"),em=xe,tm=H,im=Ge,rm=bu,nm=RegExp.prototype,om=De.f,am=be,sm=A,cm=s,lm=bn,dm=Qp,um=Ji,hm=en.f,pm=Ge,mm=function(e){var t;return Xp(e)&&(void 0!==(t=e[Zp])?!!t:"RegExp"==$p(e))},_m=au,fm=function(e){var t=e.flags;return void 0!==t||"flags"in nm||tm(e,"flags")||!im(nm,e)?t:em(rm,e)},gm=wu,Tm=function(e,t,i){i in e||om(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Sm=Zr,vm=t,Em=H,ym=or.enforce,Im=Ca,Cm=Vu,Am=Fu,Rm=me("match"),bm=sm.RegExp,km=bm.prototype,Dm=sm.SyntaxError,Om=cm(km.exec),Nm=cm("".charAt),Pm=cm("".replace),wm=cm("".indexOf),Mm=cm("".slice),Lm=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,Vm=/a/g,Um=/a/g,xm=new bm(Vm)!==Vm,Fm=gm.MISSED_STICKY,Bm=gm.UNSUPPORTED_Y,jm=am&&(!xm||Fm||Cm||Am||vm((function(){return Um[Rm]=!1,bm(Vm)!=Vm||bm(Um)==Um||"/a/i"!=bm(Vm,"i")})));if(lm("RegExp",jm)){for(var Hm=function(e,t){var i,r,n,o,a,s,c=pm(km,this),l=mm(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Hm)return e;if((l||pm(km,e))&&(e=e.source,d&&(t=fm(h))),e=void 0===e?"":_m(e),t=void 0===t?"":_m(t),h=e,Cm&&"dotAll"in Vm&&(r=!!t&&wm(t,"s")>-1)&&(t=Pm(t,/s/g,"")),i=t,Fm&&"sticky"in Vm&&(n=!!t&&wm(t,"y")>-1)&&Bm&&(t=Pm(t,/y/g,"")),Am&&(o=function(e){for(var t,i=e.length,r=0,n="",o=[],a={},s=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=Nm(e,r)))t+=Nm(e,++r);else if("]"===t)s=!1;else if(!s)switch(!0){case"["===t:s=!0;break;case"("===t:Om(Lm,Mm(e,r+1))&&(r+=2,c=!0),n+=t,l++;continue;case">"===t&&c:if(""===d||Em(a,d))throw new Dm("Invalid capture group name");a[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]),a=dm(bm(e,t),c?this:km,Hm),(r||n||u.length)&&(s=ym(a),r&&(s.dotAll=!0,s.raw=Hm(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=Nm(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+Nm(e,++r);return n}(e),i)),n&&(s.sticky=!0),u.length&&(s.groups=u)),e!==h)try{um(a,"source",""===h?"(?:)":h)}catch(NU){}return a},Gm=hm(bm),Wm=0;Gm.length>Wm;)Tm(Hm,bm,Gm[Wm++]);km.constructor=Hm,Hm.prototype=km,Sm(sm,"RegExp",Hm,{constructor:!0})}Im("RegExp");var Jm="\t\n\v\f\r \u2028\u2029\ufeff",Km=v,zm=au,Ym=Jm,qm=s("".replace),Qm=RegExp("^["+Ym+"]+"),Xm=RegExp("(^|[^"+Ym+"])["+Ym+"]+$"),$m=function(e){return function(t){var i=zm(Km(t));return 1&e&&(i=qm(i,Qm,"")),2&e&&(i=qm(i,Xm,"$1")),i}},Zm={start:$m(1),end:$m(2),trim:$m(3)},e_=br.PROPER,t_=t,i_=Jm,r_=Zm.trim;Ln({target:"String",proto:!0,forced:function(e){return t_((function(){return!!i_[e]()||"
"!=="
"[e]()||e_&&i_[e].name!==e}))}("trim")},{trim:function(){return r_(this)}});var n_=xe;Ln({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return n_(URL.prototype.toString,this)}});var o_=Ln,a_=Rc,s_=t,c_=He,l_=Te,d_=cs,u_=eu,h_=Zr,p_=a_&&a_.prototype;if(o_({target:"Promise",proto:!0,real:!0,forced:!!a_&&s_((function(){p_.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=d_(this,c_("Promise")),i=l_(e);return this.then(i?function(i){return u_(t,e()).then((function(){return i}))}:e,i?function(i){return u_(t,e()).then((function(){throw i}))}:e)}}),l_(a_)){var m_=c_("Promise").prototype.finally;p_.finally!==m_&&h_(p_,"finally",m_,{unsafe:!0})}var __=Mt,f_=au,g_=v,T_=RangeError,S_=s,v_=jt,E_=au,y_=function(e){var t=f_(g_(this)),i="",r=__(e);if(r<0||Infinity==r)throw T_("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},I_=v,C_=S_(y_),A_=S_("".slice),R_=Math.ceil,b_=function(e){return function(t,i,r){var n,o,a=E_(I_(t)),s=v_(i),c=a.length,l=void 0===r?" ":E_(r);return s<=c||""==l?a:((o=C_(l,R_((n=s-c)/l.length))).length>n&&(o=A_(o,0,n)),e?a+o:o+a)}},k_={start:b_(!1),end:b_(!0)},D_=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Y),O_=k_.start;Ln({target:"String",proto:!0,forced:D_},{padStart:function(e){return O_(this,e,arguments.length>1?arguments[1]:void 0)}});var N_=t,P_=be,w_=me("iterator"),M_=!N_((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i="";return e.pathname="c%20d",t.forEach((function(e,r){t.delete("b"),i+=r+e})),!t.size&&!P_||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[w_]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==i||"x"!==new URL("http://x",void 0).host})),L_=Zr,V_=function(e,t,i){for(var r in t)L_(e,r,t[r],i);return e},U_=Tt,x_=De,F_=Hi,B_=function(e,t,i){var r=U_(t);r in e?x_.f(e,r,F_(0,i)):e[r]=i},j_=xt,H_=Gt,G_=B_,W_=Array,J_=Math.max,K_=function(e,t,i){for(var r=H_(e),n=j_(t,r),o=j_(void 0===i?r:i,r),a=W_(J_(o-n,0)),s=0;n<o;n++,s++)G_(a,s,e[n]);return a.length=s,a},z_=K_,Y_=Math.floor,q_=function(e,t){var i=e.length,r=Y_(i/2);return i<8?Q_(e,t):X_(e,q_(z_(e,0,r),t),q_(z_(e,r),t),t)},Q_=function(e,t){for(var i,r,n=e.length,o=1;o<n;){for(r=o,i=e[o];r&&t(e[r-1],i)>0;)e[r]=e[--r];r!==o++&&(e[r]=i)}return e},X_=function(e,t,i,r){for(var n=t.length,o=i.length,a=0,s=0;a<n||s<o;)e[a+s]=a<n&&s<o?r(t[a],i[s])<=0?t[a++]:i[s++]:a<n?t[a++]:i[s++];return e},$_=q_,Z_=Ln,ef=A,tf=xe,rf=s,nf=be,of=M_,af=Zr,sf=Sa,cf=V_,lf=ro,df=uo,uf=or,hf=ba,pf=Te,mf=H,_f=vs,ff=La,gf=Ae,Tf=Ee,Sf=au,vf=ki,Ef=Hi,yf=od,If=$l,Cf=Is,Af=$_,Rf=me("iterator"),bf="URLSearchParams",kf="URLSearchParamsIterator",Df=uf.set,Of=uf.getterFor(bf),Nf=uf.getterFor(kf),Pf=Object.getOwnPropertyDescriptor,wf=function(e){if(!nf)return ef[e];var t=Pf(ef,e);return t&&t.value},Mf=wf("fetch"),Lf=wf("Request"),Vf=wf("Headers"),Uf=Lf&&Lf.prototype,xf=Vf&&Vf.prototype,Ff=ef.RegExp,Bf=ef.TypeError,jf=ef.decodeURIComponent,Hf=ef.encodeURIComponent,Gf=rf("".charAt),Wf=rf([].join),Jf=rf([].push),Kf=rf("".replace),zf=rf([].shift),Yf=rf([].splice),qf=rf("".split),Qf=rf("".slice),Xf=/\+/g,$f=Array(4),Zf=function(e){return $f[e-1]||($f[e-1]=Ff("((?:%[\\da-f]{2}){"+e+"})","gi"))},eg=function(e){try{return jf(e)}catch(NU){return e}},tg=function(e){var t=Kf(e,Xf," "),i=4;try{return jf(t)}catch(NU){for(;i;)t=Kf(t,Zf(i--),eg);return t}},ig=/[!'()~]|%20/g,rg={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},ng=function(e){return rg[e]},og=function(e){return Kf(Hf(e),ig,ng)},ag=df((function(e,t){Df(this,{type:kf,iterator:yf(Of(e).entries),kind:t})}),"Iterator",(function(){var e=Nf(this),t=e.kind,i=e.iterator.next(),r=i.value;return i.done||(i.value="keys"===t?r.key:"values"===t?r.value:[r.key,r.value]),i}),!0),sg=function(e){this.entries=[],this.url=null,void 0!==e&&(Tf(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===Gf(e,0)?Qf(e,1):e:Sf(e)))};sg.prototype={type:bf,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,a,s,c=If(e);if(c)for(i=(t=yf(e,c)).next;!(r=tf(i,t)).done;){if(o=(n=yf(gf(r.value))).next,(a=tf(o,n)).done||(s=tf(o,n)).done||!tf(o,n).done)throw Bf("Expected sequence with length 2");Jf(this.entries,{key:Sf(a.value),value:Sf(s.value)})}else for(var l in e)mf(e,l)&&Jf(this.entries,{key:l,value:Sf(e[l])})},parseQuery:function(e){if(e)for(var t,i,r=qf(e,"&"),n=0;n<r.length;)(t=r[n++]).length&&(i=qf(t,"="),Jf(this.entries,{key:tg(zf(i)),value:tg(Wf(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],Jf(i,og(e.key)+"="+og(e.value));return Wf(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var cg=function(){hf(this,lg);var e=arguments.length>0?arguments[0]:void 0,t=Df(this,new sg(e));nf||(this.length=t.entries.length)},lg=cg.prototype;if(cf(lg,{append:function(e,t){Cf(arguments.length,2);var i=Of(this);Jf(i.entries,{key:Sf(e),value:Sf(t)}),nf||this.length++,i.updateURL()},delete:function(e){Cf(arguments.length,1);for(var t=Of(this),i=t.entries,r=Sf(e),n=0;n<i.length;)i[n].key===r?Yf(i,n,1):n++;nf||(this.length=i.length),t.updateURL()},get:function(e){Cf(arguments.length,1);for(var t=Of(this).entries,i=Sf(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){Cf(arguments.length,1);for(var t=Of(this).entries,i=Sf(e),r=[],n=0;n<t.length;n++)t[n].key===i&&Jf(r,t[n].value);return r},has:function(e){Cf(arguments.length,1);for(var t=Of(this).entries,i=Sf(e),r=0;r<t.length;)if(t[r++].key===i)return!0;return!1},set:function(e,t){Cf(arguments.length,1);for(var i,r=Of(this),n=r.entries,o=!1,a=Sf(e),s=Sf(t),c=0;c<n.length;c++)(i=n[c]).key===a&&(o?Yf(n,c--,1):(o=!0,i.value=s));o||Jf(n,{key:a,value:s}),nf||(this.length=n.length),r.updateURL()},sort:function(){var e=Of(this);Af(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=Of(this).entries,r=_f(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 ag(this,"keys")},values:function(){return new ag(this,"values")},entries:function(){return new ag(this,"entries")}},{enumerable:!0}),af(lg,Rf,lg.entries,{name:"entries"}),af(lg,"toString",(function(){return Of(this).serialize()}),{enumerable:!0}),nf&&sf(lg,"size",{get:function(){return Of(this).entries.length},configurable:!0,enumerable:!0}),lf(cg,bf),Z_({global:!0,constructor:!0,forced:!of},{URLSearchParams:cg}),!of&&pf(Vf)){var dg=rf(xf.has),ug=rf(xf.set),hg=function(e){if(Tf(e)){var t,i=e.body;if(ff(i)===bf)return t=e.headers?new Vf(e.headers):new Vf,dg(t,"content-type")||ug(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),vf(e,{body:Ef(0,Sf(i)),headers:Ef(0,t)})}return e};if(pf(Mf)&&Z_({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return Mf(e,arguments.length>1?hg(arguments[1]):{})}}),pf(Lf)){var pg=function(e){return hf(this,Uf),new Lf(e,arguments.length>1?hg(arguments[1]):{})};Uf.constructor=pg,pg.prototype=Uf,Z_({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:pg})}}var mg={URLSearchParams:cg,getState:Of},_g=op.charAt,fg=au,gg=or,Tg=Bo,Sg=jo,vg="String Iterator",Eg=gg.set,yg=gg.getterFor(vg);Tg(String,"String",(function(e){Eg(this,{type:vg,string:fg(e),index:0})}),(function(){var e,t=yg(this),i=t.string,r=t.index;return r>=i.length?Sg(void 0,!0):(e=_g(i,r),t.index+=e.length,Sg(e,!1))}));var Ig,Cg=be,Ag=s,Rg=xe,bg=t,kg=oi,Dg=nn,Og=sr,Ng=F,Pg=f,wg=Object.assign,Mg=Object.defineProperty,Lg=Ag([].concat),Vg=!wg||bg((function(){if(Cg&&1!==wg({b:1},wg(Mg({},"a",{enumerable:!0,get:function(){Mg(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol(),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach((function(e){t[e]=e})),7!=wg({},e)[i]||kg(wg({},t)).join("")!=r}))?function(e,t){for(var i=Ng(e),r=arguments.length,n=1,o=Dg.f,a=Og.f;r>n;)for(var s,c=Pg(arguments[n++]),l=o?Lg(kg(c),o(c)):kg(c),d=l.length,u=0;d>u;)s=l[u++],Cg&&!Rg(a,c,s)||(i[s]=c[s]);return i}:wg,Ug=Ae,xg=ld,Fg=vs,Bg=xe,jg=F,Hg=function(e,t,i,r){try{return r?t(Ug(i)[0],i[1]):t(i)}catch(NU){xg(e,"throw",NU)}},Gg=Kl,Wg=Za,Jg=Gt,Kg=B_,zg=od,Yg=$l,qg=Array,Qg=s,Xg=2147483647,$g=/[^\0-\u007E]/,Zg=/[.\u3002\uFF0E\uFF61]/g,eT="Overflow: input needs wider integers to process",tT=RangeError,iT=Qg(Zg.exec),rT=Math.floor,nT=String.fromCharCode,oT=Qg("".charCodeAt),aT=Qg([].join),sT=Qg([].push),cT=Qg("".replace),lT=Qg("".split),dT=Qg("".toLowerCase),uT=function(e){return e+22+75*(e<26)},hT=function(e,t,i){var r=0;for(e=i?rT(e/700):e>>1,e+=rT(e/t);e>455;)e=rT(e/35),r+=36;return rT(r+36*e/(e+38))},pT=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=oT(e,i++);if(n>=55296&&n<=56319&&i<r){var o=oT(e,i++);56320==(64512&o)?sT(t,((1023&n)<<10)+(1023&o)+65536):(sT(t,n),i--)}else sT(t,n)}return t}(e);var i,r,n=e.length,o=128,a=0,s=72;for(i=0;i<e.length;i++)(r=e[i])<128&&sT(t,nT(r));var c=t.length,l=c;for(c&&sT(t,"-");l<n;){var d=Xg;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>rT((Xg-a)/u))throw tT(eT);for(a+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++a>Xg)throw tT(eT);if(r==o){for(var h=a,p=36;;){var m=p<=s?1:p>=s+26?26:p-s;if(h<m)break;var _=h-m,f=36-m;sT(t,nT(uT(m+_%f))),h=rT(_/f),p+=36}sT(t,nT(uT(h))),s=hT(a,u,l==c),a=0,l++}}a++,o++}return aT(t,"")},mT=Ln,_T=be,fT=M_,gT=A,TT=vs,ST=s,vT=Zr,ET=Sa,yT=ba,IT=H,CT=Vg,AT=function(e){var t=jg(e),i=Wg(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=Fg(n,r>2?arguments[2]:void 0));var a,s,c,l,d,u,h=Yg(t),p=0;if(!h||this===qg&&Gg(h))for(a=Jg(t),s=i?new this(a):qg(a);a>p;p++)u=o?n(t[p],p):t[p],Kg(s,p,u);else for(d=(l=zg(t,h)).next,s=i?new this:[];!(c=Bg(d,l)).done;p++)u=o?Hg(l,n,[c.value,p],!0):c.value,Kg(s,p,u);return s.length=p,s},RT=K_,bT=op.codeAt,kT=function(e){var t,i,r=[],n=lT(cT(dT(e),Zg,"."),".");for(t=0;t<n.length;t++)i=n[t],sT(r,iT($g,i)?"xn--"+pT(i):i);return aT(r,".")},DT=au,OT=ro,NT=Is,PT=mg,wT=or,MT=wT.set,LT=wT.getterFor("URL"),VT=PT.URLSearchParams,UT=PT.getState,xT=gT.URL,FT=gT.TypeError,BT=gT.parseInt,jT=Math.floor,HT=Math.pow,GT=ST("".charAt),WT=ST(/./.exec),JT=ST([].join),KT=ST(1..toString),zT=ST([].pop),YT=ST([].push),qT=ST("".replace),QT=ST([].shift),XT=ST("".split),$T=ST("".slice),ZT=ST("".toLowerCase),eS=ST([].unshift),tS="Invalid scheme",iS="Invalid host",rS="Invalid port",nS=/[a-z]/i,oS=/[\d+-.a-z]/i,aS=/\d/,sS=/^0x/i,cS=/^[0-7]+$/,lS=/^\d+$/,dS=/^[\da-f]+$/i,uS=/[\0\t\n\r #%/:<>?@[\\\]^|]/,hS=/[\0\t\n\r #/:<>?@[\\\]^|]/,pS=/^[\u0000-\u0020]+/,mS=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,_S=/[\t\n\r]/g,fS=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)eS(t,e%256),e=jT(e/256);return JT(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&&(t=r,i=n),t}(e),i=0;i<8;i++)n&&0===e[i]||(n&&(n=!1),r===i?(t+=i?":":"::",n=!0):(t+=KT(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},gS={},TS=CT({},gS,{" ":1,'"':1,"<":1,">":1,"`":1}),SS=CT({},TS,{"#":1,"?":1,"{":1,"}":1}),vS=CT({},SS,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),ES=function(e,t){var i=bT(e,0);return i>32&&i<127&&!IT(t,e)?e:encodeURIComponent(e)},yS={ftp:21,file:null,http:80,https:443,ws:80,wss:443},IS=function(e,t){var i;return 2==e.length&&WT(nS,GT(e,0))&&(":"==(i=GT(e,1))||!t&&"|"==i)},CS=function(e){var t;return e.length>1&&IS($T(e,0,2))&&(2==e.length||"/"===(t=GT(e,2))||"\\"===t||"?"===t||"#"===t)},AS=function(e){return"."===e||"%2e"===ZT(e)},RS={},bS={},kS={},DS={},OS={},NS={},PS={},wS={},MS={},LS={},VS={},US={},xS={},FS={},BS={},jS={},HS={},GS={},WS={},JS={},KS={},zS=function(e,t,i){var r,n,o,a=DT(e);if(t){if(n=this.parse(a))throw FT(n);this.searchParams=null}else{if(void 0!==i&&(r=new zS(i,!0)),n=this.parse(a,null,r))throw FT(n);(o=UT(new VT)).bindURL(this),this.searchParams=o}};zS.prototype={type:"URL",parse:function(e,t,i){var r,n,o,a,s,c=this,l=t||RS,d=0,u="",h=!1,p=!1,m=!1;for(e=DT(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=qT(e,pS,""),e=qT(e,mS,"$1")),e=qT(e,_S,""),r=AT(e);d<=r.length;){switch(n=r[d],l){case RS:if(!n||!WT(nS,n)){if(t)return tS;l=kS;continue}u+=ZT(n),l=bS;break;case bS:if(n&&(WT(oS,n)||"+"==n||"-"==n||"."==n))u+=ZT(n);else{if(":"!=n){if(t)return tS;u="",l=kS,d=0;continue}if(t&&(c.isSpecial()!=IT(yS,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&yS[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?l=FS:c.isSpecial()&&i&&i.scheme==c.scheme?l=DS:c.isSpecial()?l=wS:"/"==r[d+1]?(l=OS,d++):(c.cannotBeABaseURL=!0,YT(c.path,""),l=WS)}break;case kS:if(!i||i.cannotBeABaseURL&&"#"!=n)return tS;if(i.cannotBeABaseURL&&"#"==n){c.scheme=i.scheme,c.path=RT(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=KS;break}l="file"==i.scheme?FS:NS;continue;case DS:if("/"!=n||"/"!=r[d+1]){l=NS;continue}l=MS,d++;break;case OS:if("/"==n){l=LS;break}l=GS;continue;case NS:if(c.scheme=i.scheme,n==Ig)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=RT(i.path),c.query=i.query;else if("/"==n||"\\"==n&&c.isSpecial())l=PS;else if("?"==n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=RT(i.path),c.query="",l=JS;else{if("#"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=RT(i.path),c.path.length--,l=GS;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=RT(i.path),c.query=i.query,c.fragment="",l=KS}break;case PS:if(!c.isSpecial()||"/"!=n&&"\\"!=n){if("/"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=GS;continue}l=LS}else l=MS;break;case wS:if(l=MS,"/"!=n||"/"!=GT(u,d+1))continue;d++;break;case MS:if("/"!=n&&"\\"!=n){l=LS;continue}break;case LS:if("@"==n){h&&(u="%40"+u),h=!0,o=AT(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!=f||m){var g=ES(f,vS);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n==Ig||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(h&&""==u)return"Invalid authority";d-=AT(u).length+1,u="",l=VS}else u+=n;break;case VS:case US:if(t&&"file"==c.scheme){l=jS;continue}if(":"!=n||p){if(n==Ig||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(c.isSpecial()&&""==u)return iS;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(a=c.parseHost(u))return a;if(u="",l=HS,t)return;continue}"["==n?p=!0:"]"==n&&(p=!1),u+=n}else{if(""==u)return iS;if(a=c.parseHost(u))return a;if(u="",l=xS,t==US)return}break;case xS:if(!WT(aS,n)){if(n==Ig||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()||t){if(""!=u){var T=BT(u,10);if(T>65535)return rS;c.port=c.isSpecial()&&T===yS[c.scheme]?null:T,u=""}if(t)return;l=HS;continue}return rS}u+=n;break;case FS:if(c.scheme="file","/"==n||"\\"==n)l=BS;else{if(!i||"file"!=i.scheme){l=GS;continue}if(n==Ig)c.host=i.host,c.path=RT(i.path),c.query=i.query;else if("?"==n)c.host=i.host,c.path=RT(i.path),c.query="",l=JS;else{if("#"!=n){CS(JT(RT(r,d),""))||(c.host=i.host,c.path=RT(i.path),c.shortenPath()),l=GS;continue}c.host=i.host,c.path=RT(i.path),c.query=i.query,c.fragment="",l=KS}}break;case BS:if("/"==n||"\\"==n){l=jS;break}i&&"file"==i.scheme&&!CS(JT(RT(r,d),""))&&(IS(i.path[0],!0)?YT(c.path,i.path[0]):c.host=i.host),l=GS;continue;case jS:if(n==Ig||"/"==n||"\\"==n||"?"==n||"#"==n){if(!t&&IS(u))l=GS;else if(""==u){if(c.host="",t)return;l=HS}else{if(a=c.parseHost(u))return a;if("localhost"==c.host&&(c.host=""),t)return;u="",l=HS}continue}u+=n;break;case HS:if(c.isSpecial()){if(l=GS,"/"!=n&&"\\"!=n)continue}else if(t||"?"!=n)if(t||"#"!=n){if(n!=Ig&&(l=GS,"/"!=n))continue}else c.fragment="",l=KS;else c.query="",l=JS;break;case GS:if(n==Ig||"/"==n||"\\"==n&&c.isSpecial()||!t&&("?"==n||"#"==n)){if(".."===(s=ZT(s=u))||"%2e."===s||".%2e"===s||"%2e%2e"===s?(c.shortenPath(),"/"==n||"\\"==n&&c.isSpecial()||YT(c.path,"")):AS(u)?"/"==n||"\\"==n&&c.isSpecial()||YT(c.path,""):("file"==c.scheme&&!c.path.length&&IS(u)&&(c.host&&(c.host=""),u=GT(u,0)+":"),YT(c.path,u)),u="","file"==c.scheme&&(n==Ig||"?"==n||"#"==n))for(;c.path.length>1&&""===c.path[0];)QT(c.path);"?"==n?(c.query="",l=JS):"#"==n&&(c.fragment="",l=KS)}else u+=ES(n,SS);break;case WS:"?"==n?(c.query="",l=JS):"#"==n?(c.fragment="",l=KS):n!=Ig&&(c.path[0]+=ES(n,gS));break;case JS:t||"#"!=n?n!=Ig&&("'"==n&&c.isSpecial()?c.query+="%27":c.query+="#"==n?"%23":ES(n,gS)):(c.fragment="",l=KS);break;case KS:n!=Ig&&(c.fragment+=ES(n,TS))}d++}},parseHost:function(e){var t,i,r;if("["==GT(e,0)){if("]"!=GT(e,e.length-1))return iS;if(t=function(e){var t,i,r,n,o,a,s,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return GT(e,u)};if(":"==h()){if(":"!=GT(e,1))return;u+=2,d=++l}for(;h();){if(8==l)return;if(":"!=h()){for(t=i=0;i<4&&WT(dS,h());)t=16*t+BT(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(!WT(aS,h()))return;for(;WT(aS,h());){if(o=BT(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(a=l-d,l=7;0!=l&&a>0;)s=c[l],c[l--]=c[d+a-1],c[d+--a]=s;else if(8!=l)return;return c}($T(e,1,-1)),!t)return iS;this.host=t}else if(this.isSpecial()){if(e=kT(e),WT(uS,e))return iS;if(t=function(e){var t,i,r,n,o,a,s,c=XT(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"==GT(n,0)&&(o=WT(sS,n)?16:8,n=$T(n,8==o?1:2)),""===n)a=0;else{if(!WT(10==o?lS:8==o?cS:dS,n))return e;a=BT(n,o)}YT(i,a)}for(r=0;r<t;r++)if(a=i[r],r==t-1){if(a>=HT(256,5-t))return null}else if(a>255)return null;for(s=zT(i),r=0;r<i.length;r++)s+=i[r]*HT(256,3-r);return s}(e),null===t)return iS;this.host=t}else{if(WT(hS,e))return iS;for(t="",i=AT(e),r=0;r<i.length;r++)t+=ES(i[r],gS);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return IT(yS,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&IS(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,a=e.path,s=e.query,c=e.fragment,l=t+":";return null!==n?(l+="//",e.includesCredentials()&&(l+=i+(r?":"+r:"")+"@"),l+=fS(n),null!==o&&(l+=":"+o)):"file"==t&&(l+="//"),l+=e.cannotBeABaseURL?a[0]:a.length?"/"+JT(a,"/"):"",null!==s&&(l+="?"+s),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw FT(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new YS(e.path[0]).origin}catch(NU){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+fS(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(DT(e)+":",RS)},getUsername:function(){return this.username},setUsername:function(e){var t=AT(DT(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=ES(t[i],vS)}},getPassword:function(){return this.password},setPassword:function(e){var t=AT(DT(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=ES(t[i],vS)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?fS(e):fS(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,VS)},getHostname:function(){var e=this.host;return null===e?"":fS(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,US)},getPort:function(){var e=this.port;return null===e?"":DT(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=DT(e))?this.port=null:this.parse(e,xS))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+JT(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,HS))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=DT(e))?this.query=null:("?"==GT(e,0)&&(e=$T(e,1)),this.query="",this.parse(e,JS)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=DT(e))?("#"==GT(e,0)&&(e=$T(e,1)),this.fragment="",this.parse(e,KS)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var YS=function(e){var t=yT(this,qS),i=NT(arguments.length,1)>1?arguments[1]:void 0,r=MT(t,new zS(e,!1,i));_T||(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())},qS=YS.prototype,QS=function(e,t){return{get:function(){return LT(this)[e]()},set:t&&function(e){return LT(this)[t](e)},configurable:!0,enumerable:!0}};if(_T&&(ET(qS,"href",QS("serialize","setHref")),ET(qS,"origin",QS("getOrigin")),ET(qS,"protocol",QS("getProtocol","setProtocol")),ET(qS,"username",QS("getUsername","setUsername")),ET(qS,"password",QS("getPassword","setPassword")),ET(qS,"host",QS("getHost","setHost")),ET(qS,"hostname",QS("getHostname","setHostname")),ET(qS,"port",QS("getPort","setPort")),ET(qS,"pathname",QS("getPathname","setPathname")),ET(qS,"search",QS("getSearch","setSearch")),ET(qS,"searchParams",QS("getSearchParams")),ET(qS,"hash",QS("getHash","setHash"))),vT(qS,"toJSON",(function(){return LT(this).serialize()}),{enumerable:!0}),vT(qS,"toString",(function(){return LT(this).serialize()}),{enumerable:!0}),xT){var XS=xT.createObjectURL,$S=xT.revokeObjectURL;XS&&vT(YS,"createObjectURL",TT(XS,xT)),$S&&vT(YS,"revokeObjectURL",TT($S,xT))}OT(YS,"URL"),mT({global:!0,constructor:!0,forced:!fT,sham:!_T},{URL:YS});var ZS="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,ev=Mt,tv=jt,iv=RangeError,rv=function(e){if(void 0===e)return 0;var t=ev(e),i=tv(t);if(t!==i)throw iv("Wrong length or index");return i},nv=Array,ov=Math.abs,av=Math.pow,sv=Math.floor,cv=Math.log,lv=Math.LN2,dv={pack:function(e,t,i){var r,n,o,a=nv(i),s=8*i-t-1,c=(1<<s)-1,l=c>>1,d=23===t?av(2,-24)-av(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=ov(e))!=e||Infinity===e?(n=e!=e?1:0,r=c):(r=sv(cv(e)/lv),e*(o=av(2,-r))<1&&(r--,o*=2),(e+=r+l>=1?d/o:d*av(2,1-l))*o>=2&&(r++,o/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*o-1)*av(2,t),r+=l):(n=e*av(2,l-1)*av(2,t),r=0));t>=8;)a[h++]=255&n,n/=256,t-=8;for(r=r<<t|n,s+=t;s>0;)a[h++]=255&r,r/=256,s-=8;return a[--h]|=128*u,a},unpack:function(e,t){var i,r=e.length,n=8*r-t-1,o=(1<<n)-1,a=o>>1,s=n-7,c=r-1,l=e[c--],d=127&l;for(l>>=7;s>0;)d=256*d+e[c--],s-=8;for(i=d&(1<<-s)-1,d>>=-s,s+=t;s>0;)i=256*i+e[c--],s-=8;if(0===d)d=1-a;else{if(d===o)return i?NaN:l?-Infinity:Infinity;i+=av(2,t),d-=a}return(l?-1:1)*i*av(2,d-t)}},uv=F,hv=xt,pv=Gt,mv=function(e){for(var t=uv(this),i=pv(t),r=arguments.length,n=hv(r>1?arguments[1]:void 0,i),o=r>2?arguments[2]:void 0,a=void 0===o?i:hv(o,i);a>n;)t[n++]=e;return t},_v=A,fv=s,gv=be,Tv=ZS,Sv=br,vv=Ji,Ev=Sa,yv=V_,Iv=t,Cv=ba,Av=Mt,Rv=jt,bv=rv,kv=dv,Dv=Wn,Ov=vo,Nv=en.f,Pv=mv,wv=K_,Mv=ro,Lv=or,Vv=Sv.PROPER,Uv=Sv.CONFIGURABLE,xv="ArrayBuffer",Fv="DataView",Bv="Wrong index",jv=Lv.getterFor(xv),Hv=Lv.getterFor(Fv),Gv=Lv.set,Wv=_v.ArrayBuffer,Jv=Wv,Kv=Jv&&Jv.prototype,zv=_v.DataView,Yv=zv&&zv.prototype,qv=Object.prototype,Qv=_v.Array,Xv=_v.RangeError,$v=fv(Pv),Zv=fv([].reverse),eE=kv.pack,tE=kv.unpack,iE=function(e){return[255&e]},rE=function(e){return[255&e,e>>8&255]},nE=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},oE=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},aE=function(e){return eE(e,23,4)},sE=function(e){return eE(e,52,8)},cE=function(e,t,i){Ev(e.prototype,t,{configurable:!0,get:function(){return i(this)[t]}})},lE=function(e,t,i,r){var n=bv(i),o=Hv(e);if(n+t>o.byteLength)throw Xv(Bv);var a=o.bytes,s=n+o.byteOffset,c=wv(a,s,s+t);return r?c:Zv(c)},dE=function(e,t,i,r,n,o){var a=bv(i),s=Hv(e);if(a+t>s.byteLength)throw Xv(Bv);for(var c=s.bytes,l=a+s.byteOffset,d=r(+n),u=0;u<t;u++)c[l+u]=d[o?u:t-u-1]};if(Tv){var uE=Vv&&Wv.name!==xv;if(Iv((function(){Wv(1)}))&&Iv((function(){new Wv(-1)}))&&!Iv((function(){return new Wv,new Wv(1.5),new Wv(NaN),1!=Wv.length||uE&&!Uv})))uE&&Uv&&vv(Wv,"name",xv);else{(Jv=function(e){return Cv(this,Kv),new Wv(bv(e))}).prototype=Kv;for(var hE,pE=Nv(Wv),mE=0;pE.length>mE;)(hE=pE[mE++])in Jv||vv(Jv,hE,Wv[hE]);Kv.constructor=Jv}Ov&&Dv(Yv)!==qv&&Ov(Yv,qv);var _E=new zv(new Jv(2)),fE=fv(Yv.setInt8);_E.setInt8(0,2147483648),_E.setInt8(1,2147483649),!_E.getInt8(0)&&_E.getInt8(1)||yv(Yv,{setInt8:function(e,t){fE(this,e,t<<24>>24)},setUint8:function(e,t){fE(this,e,t<<24>>24)}},{unsafe:!0})}else Kv=(Jv=function(e){Cv(this,Kv);var t=bv(e);Gv(this,{type:xv,bytes:$v(Qv(t),0),byteLength:t}),gv||(this.byteLength=t,this.detached=!1)}).prototype,Yv=(zv=function(e,t,i){Cv(this,Yv),Cv(e,Kv);var r=jv(e),n=r.byteLength,o=Av(t);if(o<0||o>n)throw Xv("Wrong offset");if(o+(i=void 0===i?n-o:Rv(i))>n)throw Xv("Wrong length");Gv(this,{type:Fv,buffer:e,byteLength:i,byteOffset:o,bytes:r.bytes}),gv||(this.buffer=e,this.byteLength=i,this.byteOffset=o)}).prototype,gv&&(cE(Jv,"byteLength",jv),cE(zv,"buffer",Hv),cE(zv,"byteLength",Hv),cE(zv,"byteOffset",Hv)),yv(Yv,{getInt8:function(e){return lE(this,1,e)[0]<<24>>24},getUint8:function(e){return lE(this,1,e)[0]},getInt16:function(e){var t=lE(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=lE(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return oE(lE(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return oE(lE(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return tE(lE(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return tE(lE(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){dE(this,1,e,iE,t)},setUint8:function(e,t){dE(this,1,e,iE,t)},setInt16:function(e,t){dE(this,2,e,rE,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){dE(this,2,e,rE,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){dE(this,4,e,nE,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){dE(this,4,e,nE,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){dE(this,4,e,aE,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){dE(this,8,e,sE,t,arguments.length>2?arguments[2]:void 0)}});Mv(Jv,xv),Mv(zv,Fv);var gE={ArrayBuffer:Jv,DataView:zv},TE=Ca,SE="ArrayBuffer",vE=gE.ArrayBuffer;Ln({global:!0,constructor:!0,forced:A.ArrayBuffer!==vE},{ArrayBuffer:vE}),TE(SE);var EE=Ln,yE=fs,IE=t,CE=Ae,AE=xt,RE=jt,bE=cs,kE=gE.ArrayBuffer,DE=gE.DataView,OE=DE.prototype,NE=yE(kE.prototype.slice),PE=yE(OE.getUint8),wE=yE(OE.setUint8);EE({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:IE((function(){return!new kE(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(NE&&void 0===t)return NE(CE(this),e);for(var i=CE(this).byteLength,r=AE(e,i),n=AE(void 0===t?i:t,i),o=new(bE(this,kE))(RE(n-r)),a=new DE(this),s=new DE(o),c=0;r<n;)wE(s,c++,PE(a,r++));return o}});var ME=Qe,LE=TypeError,VE=Y.match(/firefox\/(\d+)/i),UE=!!VE&&+VE[1],xE=/MSIE|Trident/.test(Y),FE=Y.match(/AppleWebKit\/(\d+)\./),BE=!!FE&&+FE[1],jE=Ln,HE=s,GE=et,WE=F,JE=Gt,KE=function(e,t){if(!delete e[t])throw LE("Cannot delete property "+ME(t)+" of "+ME(e))},zE=au,YE=t,qE=$_,QE=mh,XE=UE,$E=xE,ZE=te,ey=BE,ty=[],iy=HE(ty.sort),ry=HE(ty.push),ny=YE((function(){ty.sort(void 0)})),oy=YE((function(){ty.sort(null)})),ay=QE("sort"),sy=!YE((function(){if(ZE)return ZE<70;if(!(XE&&XE>3)){if($E)return!0;if(ey)return ey<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++)ty.push({k:t+r,v:i})}for(ty.sort((function(e,t){return t.v-e.v})),r=0;r<ty.length;r++)t=ty[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));jE({target:"Array",proto:!0,forced:ny||!oy||!ay||!sy},{sort:function(e){void 0!==e&&GE(e);var t=WE(this);if(sy)return void 0===e?iy(t):iy(t,e);var i,r,n=[],o=JE(t);for(r=0;r<o;r++)r in t&&ry(n,t[r]);for(qE(n,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:zE(t)>zE(i)?1:-1}}(e)),i=JE(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)KE(t,r++);return t}});var cy,ly,dy,uy={},hy={get exports(){return uy},set exports(e){uy=e}},py=ZS,my=be,_y=A,fy=Te,gy=Ee,Ty=H,Sy=La,vy=Qe,Ey=Ji,yy=Zr,Iy=Sa,Cy=Ge,Ay=Wn,Ry=vo,by=me,ky=z,Dy=or.enforce,Oy=or.get,Ny=_y.Int8Array,Py=Ny&&Ny.prototype,wy=_y.Uint8ClampedArray,My=wy&&wy.prototype,Ly=Ny&&Ay(Ny),Vy=Py&&Ay(Py),Uy=Object.prototype,xy=_y.TypeError,Fy=by("toStringTag"),By=ky("TYPED_ARRAY_TAG"),jy="TypedArrayConstructor",Hy=py&&!!Ry&&"Opera"!==Sy(_y.opera),Gy=!1,Wy={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},Jy={BigInt64Array:8,BigUint64Array:8},Ky=function(e){var t=Ay(e);if(gy(t)){var i=Oy(t);return i&&Ty(i,jy)?i.TypedArrayConstructor:Ky(t)}},zy=function(e){if(!gy(e))return!1;var t=Sy(e);return Ty(Wy,t)||Ty(Jy,t)};for(cy in Wy)(dy=(ly=_y[cy])&&ly.prototype)?Dy(dy).TypedArrayConstructor=ly:Hy=!1;for(cy in Jy)(dy=(ly=_y[cy])&&ly.prototype)&&(Dy(dy).TypedArrayConstructor=ly);if((!Hy||!fy(Ly)||Ly===Function.prototype)&&(Ly=function(){throw xy("Incorrect invocation")},Hy))for(cy in Wy)_y[cy]&&Ry(_y[cy],Ly);if((!Hy||!Vy||Vy===Uy)&&(Vy=Ly.prototype,Hy))for(cy in Wy)_y[cy]&&Ry(_y[cy].prototype,Vy);if(Hy&&Ay(My)!==Vy&&Ry(My,Vy),my&&!Ty(Vy,Fy))for(cy in Gy=!0,Iy(Vy,Fy,{configurable:!0,get:function(){return gy(this)?this[By]:void 0}}),Wy)_y[cy]&&Ey(_y[cy],By,cy);var Yy={NATIVE_ARRAY_BUFFER_VIEWS:Hy,TYPED_ARRAY_TAG:Gy&&By,aTypedArray:function(e){if(zy(e))return e;throw xy("Target is not a typed array")},aTypedArrayConstructor:function(e){if(fy(e)&&(!Ry||Cy(Ly,e)))return e;throw xy(vy(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(my){if(i)for(var n in Wy){var o=_y[n];if(o&&Ty(o.prototype,e))try{delete o.prototype[e]}catch(NU){try{o.prototype[e]=t}catch(a){}}}Vy[e]&&!i||yy(Vy,e,i?t:Hy&&Py[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(my){if(Ry){if(i)for(r in Wy)if((n=_y[r])&&Ty(n,e))try{delete n[e]}catch(NU){}if(Ly[e]&&!i)return;try{return yy(Ly,e,i?t:Hy&&Ly[e]||t)}catch(NU){}}for(r in Wy)!(n=_y[r])||n[e]&&!i||yy(n,e,t)}},getTypedArrayConstructor:Ky,isView:function(e){if(!gy(e))return!1;var t=Sy(e);return"DataView"===t||Ty(Wy,t)||Ty(Jy,t)},isTypedArray:zy,TypedArray:Ly,TypedArrayPrototype:Vy},qy=A,Qy=t,Xy=kd,$y=Yy.NATIVE_ARRAY_BUFFER_VIEWS,Zy=qy.ArrayBuffer,eI=qy.Int8Array,tI=!$y||!Qy((function(){eI(1)}))||!Qy((function(){new eI(-1)}))||!Xy((function(e){new eI,new eI(null),new eI(1.5),new eI(e)}),!0)||Qy((function(){return 1!==new eI(new Zy(2),1,void 0).length})),iI=Ee,rI=Math.floor,nI=Number.isInteger||function(e){return!iI(e)&&isFinite(e)&&rI(e)===e},oI=Mt,aI=RangeError,sI=function(e){var t=oI(e);if(t<0)throw aI("The argument can't be less than 0");return t},cI=RangeError,lI=function(e,t){var i=sI(e);if(i%t)throw cI("Wrong offset");return i},dI=La,uI=_t,hI=TypeError,pI=function(e){var t=uI(e,"number");if("number"==typeof t)throw hI("Can't convert number to bigint");return BigInt(t)},mI=vs,_I=xe,fI=rs,gI=F,TI=Gt,SI=od,vI=$l,EI=Kl,yI=function(e){var t=dI(e);return"BigInt64Array"==t||"BigUint64Array"==t},II=Yy.aTypedArrayConstructor,CI=pI,AI=Ln,RI=A,bI=xe,kI=be,DI=tI,OI=Yy,NI=gE,PI=ba,wI=Hi,MI=Ji,LI=nI,VI=jt,UI=rv,xI=lI,FI=Tt,BI=H,jI=La,HI=Ee,GI=Ye,WI=ki,JI=Ge,KI=vo,zI=en.f,YI=function(e){var t,i,r,n,o,a,s,c,l=fI(this),d=gI(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=vI(d);if(m&&!EI(m))for(c=(s=SI(d,m)).next,d=[];!(a=_I(c,s)).done;)d.push(a.value);for(p&&u>2&&(h=mI(h,arguments[2])),i=TI(d),r=new(II(l))(i),n=yI(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?CI(o):+o;return r},qI=Nh.forEach,QI=Ca,XI=Sa,$I=De,ZI=ar,eC=Qp,tC=or.get,iC=or.set,rC=or.enforce,nC=$I.f,oC=ZI.f,aC=Math.round,sC=RI.RangeError,cC=NI.ArrayBuffer,lC=cC.prototype,dC=NI.DataView,uC=OI.NATIVE_ARRAY_BUFFER_VIEWS,hC=OI.TYPED_ARRAY_TAG,pC=OI.TypedArray,mC=OI.TypedArrayPrototype,_C=OI.aTypedArrayConstructor,fC=OI.isTypedArray,gC="BYTES_PER_ELEMENT",TC="Wrong length",SC=function(e,t){_C(e);for(var i=0,r=t.length,n=new e(r);r>i;)n[i]=t[i++];return n},vC=function(e,t){XI(e,t,{configurable:!0,get:function(){return tC(this)[t]}})},EC=function(e){var t;return JI(lC,e)||"ArrayBuffer"==(t=jI(e))||"SharedArrayBuffer"==t},yC=function(e,t){return fC(e)&&!GI(t)&&t in e&&LI(+t)&&t>=0},IC=function(e,t){return t=FI(t),yC(e,t)?wI(2,e[t]):oC(e,t)},CC=function(e,t,i){return t=FI(t),!(yC(e,t)&&HI(i)&&BI(i,"value"))||BI(i,"get")||BI(i,"set")||i.configurable||BI(i,"writable")&&!i.writable||BI(i,"enumerable")&&!i.enumerable?nC(e,t,i):(e[t]=i.value,e)};kI?(uC||(ZI.f=IC,$I.f=CC,vC(mC,"buffer"),vC(mC,"byteOffset"),vC(mC,"byteLength"),vC(mC,"length")),AI({target:"Object",stat:!0,forced:!uC},{getOwnPropertyDescriptor:IC,defineProperty:CC}),hy.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,a="set"+e,s=RI[n],c=s,l=c&&c.prototype,d={},u=function(e,t){nC(e,t,{get:function(){return function(e,t){var i=tC(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=tC(e);i&&(n=(n=aC(n))<0?0:n>255?255:255&n),o.view[a](t*r+o.byteOffset,n,!0)}(this,t,e)},enumerable:!0})};uC?DI&&(c=t((function(e,t,i,n){return PI(e,l),eC(HI(t)?EC(t)?void 0!==n?new s(t,xI(i,r),n):void 0!==i?new s(t,xI(i,r)):new s(t):fC(t)?SC(c,t):bI(YI,c,t):new s(UI(t)),e,c)})),KI&&KI(c,pC),qI(zI(s),(function(e){e in c||MI(c,e,s[e])})),c.prototype=l):(c=t((function(e,t,i,n){PI(e,l);var o,a,s,d=0,h=0;if(HI(t)){if(!EC(t))return fC(t)?SC(c,t):bI(YI,c,t);o=t,h=xI(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw sC(TC);if((a=p-h)<0)throw sC(TC)}else if((a=VI(n)*r)+h>p)throw sC(TC);s=a/r}else s=UI(t),o=new cC(a=s*r);for(iC(e,{buffer:o,byteOffset:h,byteLength:a,length:s,view:new dC(o)});d<s;)u(e,d++)})),KI&&KI(c,pC),l=c.prototype=WI(mC)),l.constructor!==c&&MI(l,"constructor",c),rC(l).TypedArrayConstructor=c,hC&&MI(l,hC,n);var h=c!=s;d[n]=c,AI({global:!0,constructor:!0,forced:h,sham:!uC},d),gC in c||MI(c,gC,r),gC in l||MI(l,gC,r),QI(n)}):hy.exports=function(){},uy("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var AC=mv,RC=pI,bC=La,kC=xe,DC=t,OC=Yy.aTypedArray,NC=Yy.exportTypedArrayMethod,PC=s("".slice);NC("fill",(function(e){var t=arguments.length;OC(this);var i="Big"===PC(bC(this),0,3)?RC(e):+e;return kC(AC,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),DC((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var wC=A,MC=xe,LC=Yy,VC=Gt,UC=lI,xC=F,FC=t,BC=wC.RangeError,jC=wC.Int8Array,HC=jC&&jC.prototype,GC=HC&&HC.set,WC=LC.aTypedArray,JC=LC.exportTypedArrayMethod,KC=!FC((function(){var e=new Uint8ClampedArray(2);return MC(GC,e,{length:1,0:3},1),3!==e[1]})),zC=KC&&LC.NATIVE_ARRAY_BUFFER_VIEWS&&FC((function(){var e=new jC(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));JC("set",(function(e){WC(this);var t=UC(arguments.length>1?arguments[1]:void 0,1),i=xC(e);if(KC)return MC(GC,this,i,t);var r=this.length,n=VC(i),o=0;if(n+t>r)throw BC("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!KC||zC);var YC=fs,qC=t,QC=et,XC=$_,$C=UE,ZC=xE,eA=te,tA=BE,iA=Yy.aTypedArray,rA=Yy.exportTypedArrayMethod,nA=A.Uint16Array,oA=nA&&YC(nA.prototype.sort),aA=!(!oA||qC((function(){oA(new nA(2),null)}))&&qC((function(){oA(new nA(2),{})}))),sA=!!oA&&!qC((function(){if(eA)return eA<74;if($C)return $C<67;if(ZC)return!0;if(tA)return tA<602;var e,t,i=new nA(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(oA(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));rA("sort",(function(e){return void 0!==e&&QC(e),sA?oA(this,e):XC(iA(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))}),!sA||aA);var cA=Ln,lA=gh,dA=s([].reverse),uA=[1,2];cA({target:"Array",proto:!0,forced:String(uA)===String(uA.reverse())},{reverse:function(){return lA(this)&&(this.length=this.length),dA(this)}});var hA=Object.create,pA=Object.defineProperty,mA=Object.defineProperties,_A=Object.getOwnPropertyDescriptor,fA=Object.getOwnPropertyDescriptors,gA=Object.getOwnPropertyNames,TA=Object.getOwnPropertySymbols,SA=Object.getPrototypeOf,vA=Object.prototype.hasOwnProperty,EA=Object.prototype.propertyIsEnumerable,yA=Reflect.get,IA=Math.pow,CA=(e,t,i)=>t in e?pA(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,AA=(e,t)=>{for(var i in t||(t={}))vA.call(t,i)&&CA(e,i,t[i]);if(TA)for(var i of TA(t))EA.call(t,i)&&CA(e,i,t[i]);return e},RA=(e,t)=>mA(e,fA(t)),bA=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),kA=(e,t)=>{for(var i in t)pA(e,i,{get:t[i],enumerable:!0})},DA=(e,t,i)=>(i=null!=e?hA(SA(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of gA(t))!vA.call(e,n)&&n!==i&&pA(e,n,{get:()=>t[n],enumerable:!(r=_A(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:pA(i,"default",{value:e,enumerable:!0}),e)),OA=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?_A(t,i):t,a=e.length-1;a>=0;a--)(n=e[a])&&(o=(r?n(t,i,o):n(o))||o);return r&&o&&pA(t,i,o),o},NA=(e,t,i)=>(CA(e,"symbol"!=typeof t?t+"":t,i),i),PA=(e,t,i)=>yA(SA(e),i,t),wA=(e,t,i)=>new Promise(((r,n)=>{var o=e=>{try{s(i.next(e))}catch(t){n(t)}},a=e=>{try{s(i.throw(e))}catch(t){n(t)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,a);s((i=i.apply(e,t)).next())})),MA=bA((e=>{DA(QA()),Object.defineProperty(e,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};e.extractVersion=n,e.wrapPeerConnectionEvent=function(e,t,i){if(e.RTCPeerConnection){var r=e.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return n.apply(this,arguments);var o=function(e){var 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])};var 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);var 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:function(){return this["_on"+t]},set:function(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})}},e.disableLog=function(e){return"boolean"!=typeof e?new Error("Argument type: "+(void 0===e?"undefined":t(e))+". Please use a boolean."):(i=e,e?"adapter.js logging disabled":"adapter.js logging enabled")},e.disableWarnings=function(e){return"boolean"!=typeof e?new Error("Argument type: "+(void 0===e?"undefined":t(e))+". Please use a boolean."):(r=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))},e.log=function(){if("object"===("undefined"==typeof window?"undefined":t(window))){if(i)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}},e.deprecated=function(e,t){!r||console.warn(e+" is deprecated, please use "+t+" instead.")},e.detectBrowser=function(e){var t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;var i=e.navigator;if(i.mozGetUserMedia)t.browser="firefox",t.version=n(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=n(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(i.mediaDevices&&i.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=n(i.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=n(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t},e.compactObject=function e(t){return o(t)?Object.keys(t).reduce((function(i,r){var n=o(t[r]),a=n?e(t[r]):t[r],s=n&&!Object.keys(a).length;return void 0===a||s?i:Object.assign(i,function(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}({},r,a))}),{}):t},e.walkStats=a,e.filterStats=function(e,t,i){var r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;var o=[];return e.forEach((function(e){"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((function(t){e.forEach((function(i){i.type===r&&i.trackId===t.id&&a(e,i,n)}))})),n};var i=!0,r=!0;function n(e,t,i){var r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function o(e){return"[object Object]"===Object.prototype.toString.call(e)}function a(e,t,i){!t||i.has(t.id)||(i.set(t.id,t),Object.keys(t).forEach((function(r){r.endsWith("Id")?a(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((function(t){a(e,e.get(t),i)}))})))}})),LA=bA((e=>{DA(QA()),Object.defineProperty(e,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};e.shimGetUserMedia=function(e,r){var n=e&&e.navigator;if(n.mediaDevices){var o=function(e){if("object"!==(void 0===e?"undefined":t(e))||e.mandatory||e.optional)return e;var i={};return Object.keys(e).forEach((function(r){if("require"!==r&&"advanced"!==r&&"mediaSource"!==r){var n="object"===t(e[r])?e[r]:{ideal:e[r]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);var o=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){i.optional=i.optional||[];var a={};"number"==typeof n.ideal?(a[o("min",r)]=n.ideal,i.optional.push(a),(a={})[o("max",r)]=n.ideal,i.optional.push(a)):(a[o("",r)]=n.ideal,i.optional.push(a))}void 0!==n.exact&&"number"!=typeof n.exact?(i.mandatory=i.mandatory||{},i.mandatory[o("",r)]=n.exact):["min","max"].forEach((function(e){void 0!==n[e]&&(i.mandatory=i.mandatory||{},i.mandatory[o(e,r)]=n[e])}))}})),e.advanced&&(i.optional=(i.optional||[]).concat(e.advanced)),i},a=function(e,a){if(r.version>=61)return a(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"===t(e.audio)){var s=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};s((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),s(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=o(e.audio)}if(e&&"object"===t(e.video)){var c=e.video.facingMode;c=c&&("object"===(void 0===c?"undefined":t(c))?c:{ideal:c});var l=r.version<66;if(c&&("user"===c.exact||"environment"===c.exact||"user"===c.ideal||"environment"===c.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||l)){delete e.video.facingMode;var d=void 0;if("environment"===c.exact||"environment"===c.ideal?d=["back","rear"]:("user"===c.exact||"user"===c.ideal)&&(d=["front"]),d)return n.mediaDevices.enumerateDevices().then((function(t){var r=(t=t.filter((function(e){return"videoinput"===e.kind}))).find((function(e){return d.some((function(t){return e.label.toLowerCase().includes(t)}))}));return!r&&t.length&&d.includes("back")&&(r=t[t.length-1]),r&&(e.video.deviceId=c.exact?{exact:r.deviceId}:{ideal:r.deviceId}),e.video=o(e.video),i("chrome: "+JSON.stringify(e)),a(e)}))}e.video=o(e.video)}return i("chrome: "+JSON.stringify(e)),a(e)},s=function(e){return r.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:function(){return this.name+(this.message&&": ")+this.message}}};if(n.getUserMedia=function(e,t,i){a(e,(function(e){n.webkitGetUserMedia(e,t,(function(e){i&&i(s(e))}))}))}.bind(n),n.mediaDevices.getUserMedia){var c=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(e){return a(e,(function(e){return c(e).then((function(t){if(e.audio&&!t.getAudioTracks().length||e.video&&!t.getVideoTracks().length)throw t.getTracks().forEach((function(e){e.stop()})),new DOMException("","NotFoundError");return t}),(function(e){return Promise.reject(s(e))}))}))}}}};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(MA()).log})),VA=bA((e=>{DA(QA()),Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetDisplayMedia=function(e,t){if((!e.navigator.mediaDevices||!("getDisplayMedia"in e.navigator.mediaDevices))&&e.navigator.mediaDevices){if("function"!=typeof t)return void console.error("shimGetDisplayMedia: getSourceId argument is not a function");e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((function(t){var 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)}))}}}})),UA=bA((e=>{DA(QA()),Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetDisplayMedia=e.shimGetUserMedia=void 0;var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=LA();Object.defineProperty(e,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}});var r=VA();Object.defineProperty(e,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}}),e.shimMediaStream=function(e){e.MediaStream=e.MediaStream||e.webkitMediaStream},e.shimOnTrack=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});var i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var t=this;return this._ontrackpoly||(this._ontrackpoly=function(i){i.stream.addEventListener("addtrack",(function(r){var n=void 0;n=e.RTCPeerConnection.prototype.getReceivers?t.getReceivers().find((function(e){return e.track&&e.track.id===r.track.id})):{track:r.track};var o=new Event("track");o.track=r.track,o.receiver=n,o.transceiver={receiver:n},o.streams=[i.stream],t.dispatchEvent(o)})),i.stream.getTracks().forEach((function(r){var n=void 0;n=e.RTCPeerConnection.prototype.getReceivers?t.getReceivers().find((function(e){return e.track&&e.track.id===r.id})):{track:r};var o=new Event("track");o.track=r,o.receiver=n,o.transceiver={receiver:n},o.streams=[i.stream],t.dispatchEvent(o)}))},this.addEventListener("addstream",this._ontrackpoly)),i.apply(this,arguments)}}else n.wrapPeerConnectionEvent(e,"track",(function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e}))},e.shimGetSendersWithDtmf=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){var i=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()};var r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,t){var n=r.apply(this,arguments);return n||(n=i(this,e),this._senders.push(n)),n};var n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);var t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}var o=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var t=this;this._senders=this._senders||[],o.apply(this,[e]),e.getTracks().forEach((function(e){t._senders.push(i(t,e))}))};var a=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._senders=this._senders||[],a.apply(this,[e]),e.getTracks().forEach((function(e){var i=t._senders.find((function(t){return t.track===e}));i&&t._senders.splice(t._senders.indexOf(i),1)}))}}else if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){var s=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){var e=this,t=s.apply(this,[]);return t.forEach((function(t){return t._pc=e})),t},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}},e.shimGetStats=function(e){if(e.RTCPeerConnection){var t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){var e=this,i=Array.prototype.slice.call(arguments),r=i[0],n=i[1],o=i[2];if(arguments.length>0&&"function"==typeof r)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof r))return t.apply(this,[]);var a=function(e){var t={};return e.result().forEach((function(e){var i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((function(t){i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((function(t){return[t,e[t]]})))};if(arguments.length>=2){var c=function(e){n(s(a(e)))};return t.apply(this,[c,r])}return new Promise((function(i,r){t.apply(e,[function(e){i(s(a(e)))},r])})).then(n,o)}}},e.shimSenderReceiverGetStats=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver){if(!("getStats"in e.RTCRtpSender.prototype)){var i=e.RTCPeerConnection.prototype.getSenders;i&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,t=i.apply(this,[]);return t.forEach((function(t){return t._pc=e})),t});var r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){var e=this;return this._pc.getStats().then((function(t){return n.filterStats(t,e.track,!0)}))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){var o=e.RTCPeerConnection.prototype.getReceivers;o&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,t=o.apply(this,[]);return t.forEach((function(t){return t._pc=e})),t}),n.wrapPeerConnectionEvent(e,"track",(function(e){return e.receiver._pc=e.srcElement,e})),e.RTCRtpReceiver.prototype.getStats=function(){var e=this;return this._pc.getStats().then((function(t){return n.filterStats(t,e.track,!1)}))}}if("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype){var a=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){var t=arguments[0],i=void 0,r=void 0,n=void 0;return this.getSenders().forEach((function(e){e.track===t&&(i?n=!0:i=e)})),this.getReceivers().forEach((function(e){return e.track===t&&(r?n=!0:r=e),e.track===t})),n||i&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return a.apply(this,arguments)}}}},e.shimAddTrackRemoveTrackWithNative=a,e.shimAddTrackRemoveTrack=function(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return a(e);var i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this,t=i.apply(this);return this._reverseStreams=this._reverseStreams||{},t.map((function(t){return e._reverseStreams[t.id]}))};var r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){var i=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((function(e){if(i.getSenders().find((function(t){return t.track===e})))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){var n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}r.apply(this,[t])};var n=e.RTCPeerConnection.prototype.removeStream;function s(e,t){var i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((function(t){var 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})}function c(e,t){var i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((function(t){var 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})}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){var r=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((function(e){return e===t})))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");var o=this.getSenders().find((function(e){return e.track===t}));if(o)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var a=this._streams[i.id];if(a)a.addTrack(t),Promise.resolve().then((function(){r.dispatchEvent(new Event("negotiationneeded"))}));else{var s=new e.MediaStream([t]);this._streams[i.id]=s,this._reverseStreams[s.id]=i,this.addStream(s)}return this.getSenders().find((function(e){return e.track===t}))},["createOffer","createAnswer"].forEach((function(t){var i=e.RTCPeerConnection.prototype[t],r=o({},t,(function(){var e=this,t=arguments,r=arguments.length&&"function"==typeof arguments[0];return r?i.apply(this,[function(i){var r=s(e,i);t[0].apply(null,[r])},function(e){t[1]&&t[1].apply(null,e)},arguments[2]]):i.apply(this,arguments).then((function(t){return s(e,t)}))}));e.RTCPeerConnection.prototype[t]=r[t]}));var l=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=c(this,arguments[0]),l.apply(this,arguments)):l.apply(this,arguments)};var d=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get:function(){var e=d.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){var t=this;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");this._streams=this._streams||{};var i=void 0;Object.keys(this._streams).forEach((function(r){var n=t._streams[r].getTracks().find((function(t){return e.track===t}));n&&(i=t._streams[r])})),i&&(1===i.getTracks().length?this.removeStream(this._reverseStreams[i.id]):i.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}},e.shimPeerConnection=function(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){var i=e.RTCPeerConnection.prototype[t],r=o({},t,(function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}));e.RTCPeerConnection.prototype[t]=r[t]}))},e.fixNegotiationNeeded=function(e,t){n.wrapPeerConnectionEvent(e,"negotiationneeded",(function(e){var i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))};var n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(MA());function o(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function a(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((function(t){return e._shimmedLocalStreams[t][0]}))};var t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var 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};var i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var t=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((function(e){if(t.getSenders().find((function(t){return t.track===e})))throw new DOMException("Track already exists.","InvalidAccessError")}));var r=this.getSenders();i.apply(this,arguments);var n=this.getSenders().filter((function(e){return-1===r.indexOf(e)}));this._shimmedLocalStreams[e.id]=[e].concat(n)};var 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)};var n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){var t=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((function(i){var r=t._shimmedLocalStreams[i].indexOf(e);-1!==r&&t._shimmedLocalStreams[i].splice(r,1),1===t._shimmedLocalStreams[i].length&&delete t._shimmedLocalStreams[i]})),n.apply(this,arguments)}}})),xA=bA((e=>{DA(QA()),Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetUserMedia=function(e){var t=e&&e.navigator,i=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(e){return i(e).catch((function(e){return Promise.reject(function(e){return{name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString:function(){return this.name}}}(e))}))}}})),FA=bA((e=>{DA(QA()),Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetDisplayMedia=function(e){"getDisplayMedia"in e.navigator&&(!e.navigator.mediaDevices||e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=e.navigator.getDisplayMedia.bind(e.navigator)))}})),BA=bA((e=>{DA(QA()),Object.defineProperty(e,"__esModule",{value:!0}),e.filterIceServers=function(e,i){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var i=e.urls||e.url;e.url&&!e.urls&&t.deprecated("RTCIceServer.url","RTCIceServer.urls");var n="string"==typeof i;return n&&(i=[i]),i=i.filter((function(e){if(0===e.indexOf("stun:"))return!1;var t=e.startsWith("turn")&&!e.startsWith("turn:[")&&e.includes("transport=udp");return t&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=n?i[0]:i,!!i.length}}))};var t=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(MA())})),jA=bA(((e,t)=>{DA(QA());var i={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};i.localCName=i.generateIdentifier(),i.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},i.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},i.getDescription=function(e){var t=i.splitSections(e);return t&&t[0]},i.getMediaSections=function(e){var t=i.splitSections(e);return t.shift(),t},i.matchPrefix=function(e,t){return i.splitLines(e).filter((function(e){return 0===e.indexOf(t)}))},i.parseCandidate=function(e){for(var t,i={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},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:i[t[r]]=t[r+1]}return i},i.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var i=e.type;return t.push("typ"),t.push(i),"host"!==i&&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(" ")},i.parseIceOptions=function(e){return e.substr(14).split(" ")},i.parseRtpMap=function(e){var t=e.substr(9).split(" "),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},i.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},i.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},i.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},i.parseFmtp=function(e){for(var t,i={},r=e.substr(e.indexOf(" ")+1).split(";"),n=0;n<r.length;n++)i[(t=r[n].trim().split("="))[0].trim()]=t[1];return i},i.writeFmtp=function(e){var t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var r=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+i+" "+r.join(";")+"\r\n"}return t},i.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},i.writeRtcpFb=function(e){var t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},i.parseSsrcMedia=function(e){var t=e.indexOf(" "),i={ssrc:parseInt(e.substr(7,t-7),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substr(t+1,r-t-1),i.value=e.substr(r+1)):i.attribute=e.substr(t+1),i},i.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},i.getMid=function(e){var t=i.matchPrefix(e,"a=mid:")[0];if(t)return t.substr(6)},i.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},i.getDtlsParameters=function(e,t){return{role:"auto",fingerprints:i.matchPrefix(e+t,"a=fingerprint:").map(i.parseFingerprint)}},i.writeDtlsParameters=function(e,t){var i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},i.parseCryptoLine=function(e){var t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},i.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?i.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},i.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;var t=e.substr(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}},i.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},i.getCryptoParameters=function(e,t){return i.matchPrefix(e+t,"a=crypto:").map(i.parseCryptoLine)},i.getIceParameters=function(e,t){var r=i.matchPrefix(e+t,"a=ice-ufrag:")[0],n=i.matchPrefix(e+t,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substr(12),password:n.substr(10)}:null},i.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},i.parseRtpParameters=function(e){for(var t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=i.splitLines(e)[0].split(" "),n=3;n<r.length;n++){var o=r[n],a=i.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(a){var s=i.parseRtpMap(a),c=i.matchPrefix(e,"a=fmtp:"+o+" ");switch(s.parameters=c.length?i.parseFmtp(c[0]):{},s.rtcpFeedback=i.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(i.parseRtcpFb),t.codecs.push(s),s.name.toUpperCase()){case"RED":case"ULPFEC":t.fecMechanisms.push(s.name.toUpperCase())}}}return i.matchPrefix(e,"a=extmap:").forEach((function(e){t.headerExtensions.push(i.parseExtmap(e))})),t},i.writeRtpDescription=function(e,t){var r="";r+="m="+e+" ",r+=t.codecs.length>0?"9":"0",r+=" UDP/TLS/RTP/SAVPF ",r+=t.codecs.map((function(e){return 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",t.codecs.forEach((function(e){r+=i.writeRtpMap(e),r+=i.writeFmtp(e),r+=i.writeRtcpFb(e)}));var n=0;return t.codecs.forEach((function(e){e.maxptime>n&&(n=e.maxptime)})),n>0&&(r+="a=maxptime:"+n+"\r\n"),r+="a=rtcp-mux\r\n",t.headerExtensions&&t.headerExtensions.forEach((function(e){r+=i.writeExtmap(e)})),r},i.parseRtpEncodingParameters=function(e){var t,r=[],n=i.parseRtpParameters(e),o=-1!==n.fecMechanisms.indexOf("RED"),a=-1!==n.fecMechanisms.indexOf("ULPFEC"),s=i.matchPrefix(e,"a=ssrc:").map((function(e){return i.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute})),c=s.length>0&&s[0].ssrc,l=i.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));l.length>0&&l[0].length>1&&l[0][0]===c&&(t=l[0][1]),n.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var i={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&t&&(i.rtx={ssrc:t}),r.push(i),o&&((i=JSON.parse(JSON.stringify(i))).fec={ssrc:c,mechanism:a?"red+ulpfec":"red"},r.push(i))}})),0===r.length&&c&&r.push({ssrc:c});var d=i.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substr(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substr(5),10)*.95-16e3:void 0,r.forEach((function(e){e.maxBitrate=d}))),r},i.parseRtcpParameters=function(e){var t={},r=i.matchPrefix(e,"a=ssrc:").map((function(e){return i.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];r&&(t.cname=r.value,t.ssrc=r.ssrc);var n=i.matchPrefix(e,"a=rtcp-rsize");t.reducedSize=n.length>0,t.compound=0===n.length;var o=i.matchPrefix(e,"a=rtcp-mux");return t.mux=o.length>0,t},i.parseMsid=function(e){var t,r=i.matchPrefix(e,"a=msid:");if(1===r.length)return{stream:(t=r[0].substr(7).split(" "))[0],track:t[1]};var n=i.matchPrefix(e,"a=ssrc:").map((function(e){return i.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return n.length>0?{stream:(t=n[0].value.split(" "))[0],track:t[1]}:void 0},i.parseSctpDescription=function(e){var t,r=i.parseMLine(e),n=i.matchPrefix(e,"a=max-message-size:");n.length>0&&(t=parseInt(n[0].substr(19),10)),isNaN(t)&&(t=65536);var o=i.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substr(12),10),protocol:r.fmt,maxMessageSize:t};if(i.matchPrefix(e,"a=sctpmap:").length>0){var a=i.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(a[0],10),protocol:a[1],maxMessageSize:t}}},i.writeSctpDescription=function(e,t){var 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("")},i.generateSessionId=function(){return Math.random().toString().substr(2,21)},i.writeSessionBoilerplate=function(e,t,r){var n=void 0!==t?t:2;return"v=0\r\no="+(r||"thisisadapterortc")+" "+(e||i.generateSessionId())+" "+n+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},i.writeMediaSection=function(e,t,r,n){var o=i.writeRtpDescription(e.kind,t);if(o+=i.writeIceParameters(e.iceGatherer.getLocalParameters()),o+=i.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":"active"),o+="a=mid:"+e.mid+"\r\n",e.direction?o+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?o+="a=sendrecv\r\n":e.rtpSender?o+="a=sendonly\r\n":e.rtpReceiver?o+="a=recvonly\r\n":o+="a=inactive\r\n",e.rtpSender){var a="msid:"+n.id+" "+e.rtpSender.track.id+"\r\n";o+="a="+a,o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,o+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+"\r\n"),o},i.getDirection=function(e,t){for(var r=i.splitLines(e),n=0;n<r.length;n++)switch(r[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[n].substr(2)}return t?i.getDirection(t):"sendrecv"},i.getKind=function(e){return i.splitLines(e)[0].split(" ")[0].substr(2)},i.isRejected=function(e){return"0"===e.split(" ",2)[1]},i.parseMLine=function(e){var t=i.splitLines(e)[0].substr(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}},i.parseOLine=function(e){var t=i.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:t[0],sessionId:t[1],sessionVersion:parseInt(t[2],10),netType:t[3],addressType:t[4],address:t[5]}},i.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var t=i.splitLines(e),r=0;r<t.length;r++)if(t[r].length<2||"="!==t[r].charAt(1))return!1;return!0},"object"==typeof t&&(t.exports=i)})),HA=bA(((e,t)=>{DA(QA());var i=jA();function r(e,t,r,n,o){var a=i.writeRtpDescription(e.kind,t);if(a+=i.writeIceParameters(e.iceGatherer.getLocalParameters()),a+=i.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":o||"active"),a+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?a+="a=sendrecv\r\n":e.rtpSender?a+="a=sendonly\r\n":e.rtpReceiver?a+="a=recvonly\r\n":a+="a=inactive\r\n",e.rtpSender){var s=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=s;var c="msid:"+(n?n.id:"-")+" "+s+"\r\n";a+="a="+c,a+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+c,e.sendEncodingParameters[0].rtx&&(a+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+c,a+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return a+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(a+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+"\r\n"),a}function n(e,t){var i={codecs:[],headerExtensions:[],fecMechanisms:[]},r=function(e,t){e=parseInt(e,10);for(var i=0;i<t.length;i++)if(t[i].payloadType===e||t[i].preferredPayloadType===e)return t[i]},n=function(e,t,i,n){var o=r(e.parameters.apt,i),a=r(t.parameters.apt,n);return o&&a&&o.name.toLowerCase()===a.name.toLowerCase()};return e.codecs.forEach((function(r){for(var o=0;o<t.codecs.length;o++){var a=t.codecs[o];if(r.name.toLowerCase()===a.name.toLowerCase()&&r.clockRate===a.clockRate){if("rtx"===r.name.toLowerCase()&&r.parameters&&a.parameters.apt&&!n(r,a,e.codecs,t.codecs))continue;(a=JSON.parse(JSON.stringify(a))).numChannels=Math.min(r.numChannels,a.numChannels),i.codecs.push(a),a.rtcpFeedback=a.rtcpFeedback.filter((function(e){for(var t=0;t<r.rtcpFeedback.length;t++)if(r.rtcpFeedback[t].type===e.type&&r.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var r=0;r<t.headerExtensions.length;r++){var n=t.headerExtensions[r];if(e.uri===n.uri){i.headerExtensions.push(n);break}}})),i}function o(e,t,i){return-1!=={offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[t][e].indexOf(i)}function a(e,t){var i=e.getRemoteCandidates().find((function(e){return t.foundation===e.foundation&&t.ip===e.ip&&t.port===e.port&&t.priority===e.priority&&t.protocol===e.protocol&&t.type===e.type}));return i||e.addRemoteCandidate(t),!i}function s(e,t){var i=new Error(t);return i.name=e,i.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[e],i}t.exports=function(e,t){function c(t,i){i.addTrack(t),i.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function l(t,i,r,n){var o=new Event("track");o.track=i,o.receiver=r,o.transceiver={receiver:r},o.streams=n,e.setTimeout((function(){t._dispatchEvent("track",o)}))}var d=function(r){var n=this,o=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){n[e]=o[e].bind(o)})),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",r=JSON.parse(JSON.stringify(r||{})),this.usingBundle="max-bundle"===r.bundlePolicy,"negotiate"===r.rtcpMuxPolicy)throw s("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var i=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var r=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var n="string"==typeof r;return n&&(r=[r]),r=r.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||i?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(i=!0,!0)})),delete e.url,e.urls=n?r[0]:r,!!r.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var a=r.iceCandidatePoolSize;a>0;a--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=i.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(d.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(d.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),d.prototype.onicecandidate=null,d.prototype.onaddstream=null,d.prototype.ontrack=null,d.prototype.onremovestream=null,d.prototype.onsignalingstatechange=null,d.prototype.oniceconnectionstatechange=null,d.prototype.onconnectionstatechange=null,d.prototype.onicegatheringstatechange=null,d.prototype.onnegotiationneeded=null,d.prototype.ondatachannel=null,d.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},d.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},d.prototype.getConfiguration=function(){return this._config},d.prototype.getLocalStreams=function(){return this.localStreams},d.prototype.getRemoteStreams=function(){return this.remoteStreams},d.prototype._createTransceiver=function(e,t){var i=this.transceivers.length>0,r={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&i)r.iceTransport=this.transceivers[0].iceTransport,r.dtlsTransport=this.transceivers[0].dtlsTransport;else{var n=this._createIceAndDtlsTransports();r.iceTransport=n.iceTransport,r.dtlsTransport=n.dtlsTransport}return t||this.transceivers.push(r),r},d.prototype.addTrack=function(t,i){if(this._isClosed)throw s("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");if(this.transceivers.find((function(e){return e.track===t})))throw s("InvalidAccessError","Track already exists.");for(var r,n=0;n<this.transceivers.length;n++)!this.transceivers[n].track&&this.transceivers[n].kind===t.kind&&(r=this.transceivers[n]);return r||(r=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(i)&&this.localStreams.push(i),r.track=t,r.stream=i,r.rtpSender=new e.RTCRtpSender(t,r.dtlsTransport),r.rtpSender},d.prototype.addStream=function(e){var i=this;if(t>=15025)e.getTracks().forEach((function(t){i.addTrack(t,e)}));else{var r=e.clone();e.getTracks().forEach((function(e,t){var i=r.getTracks()[t];e.addEventListener("enabled",(function(e){i.enabled=e.enabled}))})),r.getTracks().forEach((function(e){i.addTrack(e,r)}))}},d.prototype.removeTrack=function(t){if(this._isClosed)throw s("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(t instanceof e.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var i=this.transceivers.find((function(e){return e.rtpSender===t}));if(!i)throw s("InvalidAccessError","Sender was not created by this connection.");var r=i.stream;i.rtpSender.stop(),i.rtpSender=null,i.track=null,i.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(r)&&this.localStreams.indexOf(r)>-1&&this.localStreams.splice(this.localStreams.indexOf(r),1),this._maybeFireNegotiationNeeded()},d.prototype.removeStream=function(e){var t=this;e.getTracks().forEach((function(e){var i=t.getSenders().find((function(t){return t.track===e}));i&&t.removeTrack(i)}))},d.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},d.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},d.prototype._createIceGatherer=function(t,i){var r=this;if(i&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var n=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(n,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(e){var i=!e.candidate||0===Object.keys(e.candidate).length;n.state=i?"completed":"gathering",null!==r.transceivers[t].bufferedCandidateEvents&&r.transceivers[t].bufferedCandidateEvents.push(e)},n.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),n},d.prototype._gather=function(t,r){var n=this,o=this.transceivers[r].iceGatherer;if(!o.onlocalcandidate){var a=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,o.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),o.onlocalcandidate=function(e){if(!(n.usingBundle&&r>0)){var a=new Event("icecandidate");a.candidate={sdpMid:t,sdpMLineIndex:r};var s=e.candidate,c=!s||0===Object.keys(s).length;if(c)("new"===o.state||"gathering"===o.state)&&(o.state="completed");else{"new"===o.state&&(o.state="gathering"),s.component=1,s.ufrag=o.getLocalParameters().usernameFragment;var l=i.writeCandidate(s);a.candidate=Object.assign(a.candidate,i.parseCandidate(l)),a.candidate.candidate=l,a.candidate.toJSON=function(){return{candidate:a.candidate.candidate,sdpMid:a.candidate.sdpMid,sdpMLineIndex:a.candidate.sdpMLineIndex,usernameFragment:a.candidate.usernameFragment}}}var d=i.getMediaSections(n._localDescription.sdp);d[a.candidate.sdpMLineIndex]+=c?"a=end-of-candidates\r\n":"a="+a.candidate.candidate+"\r\n",n._localDescription.sdp=i.getDescription(n._localDescription.sdp)+d.join("");var u=n.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==n.iceGatheringState&&(n.iceGatheringState="gathering",n._emitGatheringStateChange()),c||n._dispatchEvent("icecandidate",a),u&&(n._dispatchEvent("icecandidate",new Event("icecandidate")),n.iceGatheringState="complete",n._emitGatheringStateChange())}},e.setTimeout((function(){a.forEach((function(e){o.onlocalcandidate(e)}))}),0)}},d.prototype._createIceAndDtlsTransports=function(){var t=this,i=new e.RTCIceTransport(null);i.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var r=new e.RTCDtlsTransport(i);return r.ondtlsstatechange=function(){t._updateConnectionState()},r.onerror=function(){Object.defineProperty(r,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:i,dtlsTransport:r}},d.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var i=this.transceivers[e].iceTransport;i&&(delete i.onicestatechange,delete this.transceivers[e].iceTransport);var r=this.transceivers[e].dtlsTransport;r&&(delete r.ondtlsstatechange,delete r.onerror,delete this.transceivers[e].dtlsTransport)},d.prototype._transceive=function(e,r,o){var a=n(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(a.encodings=e.sendEncodingParameters,a.rtcp={cname:i.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(a.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(a)),o&&e.rtpReceiver&&a.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?a.encodings=e.recvEncodingParameters:a.encodings=[{}],a.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(a.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(a.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(a))},d.prototype.setLocalDescription=function(e){var t,r,a=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(s("TypeError",'Unsupported type "'+e.type+'"'));if(!o("setLocalDescription",e.type,a.signalingState)||a._isClosed)return Promise.reject(s("InvalidStateError","Can not set local "+e.type+" in state "+a.signalingState));if("offer"===e.type)t=i.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=i.parseRtpParameters(e);a.transceivers[t].localCapabilities=r})),a.transceivers.forEach((function(e,t){a._gather(e.mid,t)}));else if("answer"===e.type){t=i.splitSections(a._remoteDescription.sdp),r=t.shift();var c=i.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var o=a.transceivers[t],s=o.iceGatherer,l=o.iceTransport,d=o.dtlsTransport,u=o.localCapabilities,h=o.remoteCapabilities;if(!(i.isRejected(e)&&0===i.matchPrefix(e,"a=bundle-only").length)&&!o.rejected){var p=i.getIceParameters(e,r),m=i.getDtlsParameters(e,r);c&&(m.role="server"),(!a.usingBundle||0===t)&&(a._gather(o.mid,t),"new"===l.state&&l.start(s,p,c?"controlling":"controlled"),"new"===d.state&&d.start(m));var _=n(u,h);a._transceive(o,_.codecs.length>0,!1)}}))}return a._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?a._updateSignalingState("have-local-offer"):a._updateSignalingState("stable"),Promise.resolve()},d.prototype.setRemoteDescription=function(r){var d=this;if(-1===["offer","answer"].indexOf(r.type))return Promise.reject(s("TypeError",'Unsupported type "'+r.type+'"'));if(!o("setRemoteDescription",r.type,d.signalingState)||d._isClosed)return Promise.reject(s("InvalidStateError","Can not set remote "+r.type+" in state "+d.signalingState));var u={};d.remoteStreams.forEach((function(e){u[e.id]=e}));var h=[],p=i.splitSections(r.sdp),m=p.shift(),_=i.matchPrefix(m,"a=ice-lite").length>0,f=i.matchPrefix(m,"a=group:BUNDLE ").length>0;d.usingBundle=f;var g=i.matchPrefix(m,"a=ice-options:")[0];return d.canTrickleIceCandidates=!!g&&g.substr(14).split(" ").indexOf("trickle")>=0,p.forEach((function(o,s){var l=i.splitLines(o),p=i.getKind(o),g=i.isRejected(o)&&0===i.matchPrefix(o,"a=bundle-only").length,T=l[0].substr(2).split(" ")[2],S=i.getDirection(o,m),v=i.parseMsid(o),E=i.getMid(o)||i.generateIdentifier();if(g||"application"===p&&("DTLS/SCTP"===T||"UDP/DTLS/SCTP"===T))d.transceivers[s]={mid:E,kind:p,protocol:T,rejected:!0};else{!g&&d.transceivers[s]&&d.transceivers[s].rejected&&(d.transceivers[s]=d._createTransceiver(p,!0));var y,I,C,A,R,b,k,D,O,N,P,w=i.parseRtpParameters(o);g||(N=i.getIceParameters(o,m),(P=i.getDtlsParameters(o,m)).role="client"),k=i.parseRtpEncodingParameters(o);var M=i.parseRtcpParameters(o),L=i.matchPrefix(o,"a=end-of-candidates",m).length>0,V=i.matchPrefix(o,"a=candidate:").map((function(e){return i.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===r.type||"answer"===r.type)&&!g&&f&&s>0&&d.transceivers[s]&&(d._disposeIceAndDtlsTransports(s),d.transceivers[s].iceGatherer=d.transceivers[0].iceGatherer,d.transceivers[s].iceTransport=d.transceivers[0].iceTransport,d.transceivers[s].dtlsTransport=d.transceivers[0].dtlsTransport,d.transceivers[s].rtpSender&&d.transceivers[s].rtpSender.setTransport(d.transceivers[0].dtlsTransport),d.transceivers[s].rtpReceiver&&d.transceivers[s].rtpReceiver.setTransport(d.transceivers[0].dtlsTransport)),"offer"!==r.type||g){if("answer"===r.type&&!g){I=(y=d.transceivers[s]).iceGatherer,C=y.iceTransport,A=y.dtlsTransport,R=y.rtpReceiver,b=y.sendEncodingParameters,D=y.localCapabilities,d.transceivers[s].recvEncodingParameters=k,d.transceivers[s].remoteCapabilities=w,d.transceivers[s].rtcpParameters=M,V.length&&"new"===C.state&&(!_&&!L||f&&0!==s?V.forEach((function(e){a(y.iceTransport,e)})):C.setRemoteCandidates(V)),(!f||0===s)&&("new"===C.state&&C.start(I,N,"controlling"),"new"===A.state&&A.start(P)),!n(y.localCapabilities,y.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&y.sendEncodingParameters[0].rtx&&delete y.sendEncodingParameters[0].rtx,d._transceive(y,"sendrecv"===S||"recvonly"===S,"sendrecv"===S||"sendonly"===S),!R||"sendrecv"!==S&&"sendonly"!==S?delete y.rtpReceiver:(O=R.track,v?(u[v.stream]||(u[v.stream]=new e.MediaStream),c(O,u[v.stream]),h.push([O,R,u[v.stream]])):(u.default||(u.default=new e.MediaStream),c(O,u.default),h.push([O,R,u.default])))}}else{(y=d.transceivers[s]||d._createTransceiver(p)).mid=E,y.iceGatherer||(y.iceGatherer=d._createIceGatherer(s,f)),V.length&&"new"===y.iceTransport.state&&(!L||f&&0!==s?V.forEach((function(e){a(y.iceTransport,e)})):y.iceTransport.setRemoteCandidates(V)),D=e.RTCRtpReceiver.getCapabilities(p),t<15019&&(D.codecs=D.codecs.filter((function(e){return"rtx"!==e.name}))),b=y.sendEncodingParameters||[{ssrc:1001*(2*s+2)}];var U,x=!1;if("sendrecv"===S||"sendonly"===S){if(x=!y.rtpReceiver,R=y.rtpReceiver||new e.RTCRtpReceiver(y.dtlsTransport,p),x)O=R.track,v&&"-"===v.stream||(v?(u[v.stream]||(u[v.stream]=new e.MediaStream,Object.defineProperty(u[v.stream],"id",{get:function(){return v.stream}})),Object.defineProperty(O,"id",{get:function(){return v.track}}),U=u[v.stream]):(u.default||(u.default=new e.MediaStream),U=u.default)),U&&(c(O,U),y.associatedRemoteMediaStreams.push(U)),h.push([O,R,U])}else y.rtpReceiver&&y.rtpReceiver.track&&(y.associatedRemoteMediaStreams.forEach((function(t){var i=t.getTracks().find((function(e){return e.id===y.rtpReceiver.track.id}));i&&function(t,i){i.removeTrack(t),i.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(i,t)})),y.associatedRemoteMediaStreams=[]);y.localCapabilities=D,y.remoteCapabilities=w,y.rtpReceiver=R,y.rtcpParameters=M,y.sendEncodingParameters=b,y.recvEncodingParameters=k,d._transceive(d.transceivers[s],!1,x)}}})),void 0===d._dtlsRole&&(d._dtlsRole="offer"===r.type?"active":"passive"),d._remoteDescription={type:r.type,sdp:r.sdp},"offer"===r.type?d._updateSignalingState("have-remote-offer"):d._updateSignalingState("stable"),Object.keys(u).forEach((function(t){var i=u[t];if(i.getTracks().length){if(-1===d.remoteStreams.indexOf(i)){d.remoteStreams.push(i);var r=new Event("addstream");r.stream=i,e.setTimeout((function(){d._dispatchEvent("addstream",r)}))}h.forEach((function(e){var t=e[0],r=e[1];i.id===e[2].id&&l(d,t,r,[i])}))}})),h.forEach((function(e){e[2]||l(d,e[0],e[1],[])})),e.setTimeout((function(){!d||!d.transceivers||d.transceivers.forEach((function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},d.prototype.close=function(){this.transceivers.forEach((function(e){e.iceTransport&&e.iceTransport.stop(),e.dtlsTransport&&e.dtlsTransport.stop(),e.rtpSender&&e.rtpSender.stop(),e.rtpReceiver&&e.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},d.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},d.prototype._maybeFireNegotiationNeeded=function(){var t=this;"stable"!==this.signalingState||!0===this.needNegotiation||(this.needNegotiation=!0,e.setTimeout((function(){if(t.needNegotiation){t.needNegotiation=!1;var e=new Event("negotiationneeded");t._dispatchEvent("negotiationneeded",e)}}),0))},d.prototype._updateIceConnectionState=function(){var e,t={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&!e.rejected&&t[e.iceTransport.state]++})),e="new",t.failed>0?e="failed":t.checking>0?e="checking":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0?e="connected":t.completed>0&&(e="completed"),e!==this.iceConnectionState){this.iceConnectionState=e;var i=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",i)}},d.prototype._updateConnectionState=function(){var e,t={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&e.dtlsTransport&&!e.rejected&&(t[e.iceTransport.state]++,t[e.dtlsTransport.state]++)})),t.connected+=t.completed,e="new",t.failed>0?e="failed":t.connecting>0?e="connecting":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0&&(e="connected"),e!==this.connectionState){this.connectionState=e;var i=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",i)}},d.prototype.createOffer=function(){var n=this;if(n._isClosed)return Promise.reject(s("InvalidStateError","Can not call createOffer after close"));var o=n.transceivers.filter((function(e){return"audio"===e.kind})).length,a=n.transceivers.filter((function(e){return"video"===e.kind})).length,c=arguments[0];if(c){if(c.mandatory||c.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==c.offerToReceiveAudio&&(o=!0===c.offerToReceiveAudio?1:!1===c.offerToReceiveAudio?0:c.offerToReceiveAudio),void 0!==c.offerToReceiveVideo&&(a=!0===c.offerToReceiveVideo?1:!1===c.offerToReceiveVideo?0:c.offerToReceiveVideo)}for(n.transceivers.forEach((function(e){"audio"===e.kind?--o<0&&(e.wantReceive=!1):"video"===e.kind&&(--a<0&&(e.wantReceive=!1))}));o>0||a>0;)o>0&&(n._createTransceiver("audio"),o--),a>0&&(n._createTransceiver("video"),a--);var l=i.writeSessionBoilerplate(n._sdpSessionId,n._sdpSessionVersion++);n.transceivers.forEach((function(r,o){var a=r.track,s=r.kind,c=r.mid||i.generateIdentifier();r.mid=c,r.iceGatherer||(r.iceGatherer=n._createIceGatherer(o,n.usingBundle));var l=e.RTCRtpSender.getCapabilities(s);t<15019&&(l.codecs=l.codecs.filter((function(e){return"rtx"!==e.name}))),l.codecs.forEach((function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1"),r.remoteCapabilities&&r.remoteCapabilities.codecs&&r.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),l.headerExtensions.forEach((function(e){(r.remoteCapabilities&&r.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=r.sendEncodingParameters||[{ssrc:1001*(2*o+1)}];a&&t>=15019&&"video"===s&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),r.wantReceive&&(r.rtpReceiver=new e.RTCRtpReceiver(r.dtlsTransport,s)),r.localCapabilities=l,r.sendEncodingParameters=d})),"max-compat"!==n._config.bundlePolicy&&(l+="a=group:BUNDLE "+n.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),l+="a=ice-options:trickle\r\n",n.transceivers.forEach((function(e,t){l+=r(e,e.localCapabilities,"offer",e.stream,n._dtlsRole),l+="a=rtcp-rsize\r\n",e.iceGatherer&&"new"!==n.iceGatheringState&&(0===t||!n.usingBundle)&&(e.iceGatherer.getLocalCandidates().forEach((function(e){e.component=1,l+="a="+i.writeCandidate(e)+"\r\n"})),"completed"===e.iceGatherer.state&&(l+="a=end-of-candidates\r\n"))}));var d=new e.RTCSessionDescription({type:"offer",sdp:l});return Promise.resolve(d)},d.prototype.createAnswer=function(){var o=this;if(o._isClosed)return Promise.reject(s("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==o.signalingState&&"have-local-pranswer"!==o.signalingState)return Promise.reject(s("InvalidStateError","Can not call createAnswer in signalingState "+o.signalingState));var a=i.writeSessionBoilerplate(o._sdpSessionId,o._sdpSessionVersion++);o.usingBundle&&(a+="a=group:BUNDLE "+o.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),a+="a=ice-options:trickle\r\n";var c=i.getMediaSections(o._remoteDescription.sdp).length;o.transceivers.forEach((function(e,i){if(!(i+1>c)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?a+="m=application 0 DTLS/SCTP 5000\r\n":a+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?a+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(a+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(a+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var s;if(e.stream)"audio"===e.kind?s=e.stream.getAudioTracks()[0]:"video"===e.kind&&(s=e.stream.getVideoTracks()[0]),s&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1});var l=n(e.localCapabilities,e.remoteCapabilities);!l.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,a+=r(e,l,"answer",e.stream,o._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(a+="a=rtcp-rsize\r\n")}}));var l=new e.RTCSessionDescription({type:"answer",sdp:a});return Promise.resolve(l)},d.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(n,o){if(!r._remoteDescription)return o(s("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var c=e.sdpMLineIndex;if(e.sdpMid)for(var l=0;l<r.transceivers.length;l++)if(r.transceivers[l].mid===e.sdpMid){c=l;break}var d=r.transceivers[c];if(!d)return o(s("OperationError","Can not add ICE candidate"));if(d.rejected)return n();var u=Object.keys(e.candidate).length>0?i.parseCandidate(e.candidate):{};if("tcp"===u.protocol&&(0===u.port||9===u.port)||u.component&&1!==u.component)return n();if((0===c||c>0&&d.iceTransport!==r.transceivers[0].iceTransport)&&!a(d.iceTransport,u))return o(s("OperationError","Can not add ICE candidate"));var h=e.candidate.trim();0===h.indexOf("a=")&&(h=h.substr(2)),(t=i.getMediaSections(r._remoteDescription.sdp))[c]+="a="+(u.type?h:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=i.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var p=0;p<r.transceivers.length&&(r.transceivers[p].rejected||(r.transceivers[p].iceTransport.addRemoteCandidate({}),(t=i.getMediaSections(r._remoteDescription.sdp))[p]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=i.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));p++);n()}))},d.prototype.getStats=function(t){if(t&&t instanceof e.MediaStreamTrack){var i=null;if(this.transceivers.forEach((function(e){e.rtpSender&&e.rtpSender.track===t?i=e.rtpSender:e.rtpReceiver&&e.rtpReceiver.track===t&&(i=e.rtpReceiver)})),!i)throw s("InvalidAccessError","Invalid selector.");return i.getStats()}var r=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&r.push(e[t].getStats())}))})),Promise.all(r).then((function(e){var t=new Map;return e.forEach((function(e){e.forEach((function(e){t.set(e.id,e)}))})),t}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(t){var i=e[t];if(i&&i.prototype&&i.prototype.getStats){var r=i.prototype.getStats;i.prototype.getStats=function(){return r.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(i){e[i].type=function(e){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type}(e[i]),t.set(i,e[i])})),t}))}}}));var u=["createOffer","createAnswer"];return u.forEach((function(e){var t=d.prototype[e];d.prototype[e]=function(){var e=arguments;return"function"==typeof e[0]||"function"==typeof e[1]?t.apply(this,[arguments[2]]).then((function(t){"function"==typeof e[0]&&e[0].apply(null,[t])}),(function(t){"function"==typeof e[1]&&e[1].apply(null,[t])})):t.apply(this,arguments)}})),(u=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=d.prototype[e];d.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]||"function"==typeof e[2]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)}),(function(t){"function"==typeof e[2]&&e[2].apply(null,[t])})):t.apply(this,arguments)}})),["getStats"].forEach((function(e){var t=d.prototype[e];d.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)})):t.apply(this,arguments)}})),d}})),GA=bA((e=>{DA(QA()),Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetDisplayMedia=e.shimGetUserMedia=void 0;var t=xA();Object.defineProperty(e,"shimGetUserMedia",{enumerable:!0,get:function(){return t.shimGetUserMedia}});var i=FA();Object.defineProperty(e,"shimGetDisplayMedia",{enumerable:!0,get:function(){return i.shimGetDisplayMedia}}),e.shimPeerConnection=function(e,t){if(e.RTCIceGatherer&&(e.RTCIceCandidate||(e.RTCIceCandidate=function(e){return e}),e.RTCSessionDescription||(e.RTCSessionDescription=function(e){return e}),t.version<15025)){var i=Object.getOwnPropertyDescriptor(e.MediaStreamTrack.prototype,"enabled");Object.defineProperty(e.MediaStreamTrack.prototype,"enabled",{set:function(e){i.set.call(this,e);var t=new Event("enabled");t.enabled=e,this.dispatchEvent(t)}})}e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)&&Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new e.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),e.RTCDtmfSender&&!e.RTCDTMFSender&&(e.RTCDTMFSender=e.RTCDtmfSender);var r=(0,s.default)(e,t.version);e.RTCPeerConnection=function(e){return e&&e.iceServers&&(e.iceServers=(0,o.filterIceServers)(e.iceServers,t.version),n.log("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype},e.shimReplaceTrack=function(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)};var r,n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(MA()),o=BA(),a=HA(),s=(r=a)&&r.__esModule?r:{default:r}})),WA=bA((e=>{DA(QA()),Object.defineProperty(e,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};e.shimGetUserMedia=function(e,r){var n=e&&e.navigator,o=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){i.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(e).then(t,r)},!(r.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){var a=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},s=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(e){return"object"===(void 0===e?"undefined":t(e))&&"object"===t(e.audio)&&(e=JSON.parse(JSON.stringify(e)),a(e.audio,"autoGainControl","mozAutoGainControl"),a(e.audio,"noiseSuppression","mozNoiseSuppression")),s(e)},o&&o.prototype.getSettings){var c=o.prototype.getSettings;o.prototype.getSettings=function(){var e=c.apply(this,arguments);return a(e,"mozAutoGainControl","autoGainControl"),a(e,"mozNoiseSuppression","noiseSuppression"),e}}if(o&&o.prototype.applyConstraints){var l=o.prototype.applyConstraints;o.prototype.applyConstraints=function(e){return"audio"===this.kind&&"object"===(void 0===e?"undefined":t(e))&&(e=JSON.parse(JSON.stringify(e)),a(e,"autoGainControl","mozAutoGainControl"),a(e,"noiseSuppression","mozNoiseSuppression")),l.apply(this,[e])}}}};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(MA())})),JA=bA((e=>{DA(QA()),Object.defineProperty(e,"__esModule",{value:!0}),e.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){var r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}})),KA=bA((e=>{DA(QA()),Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetDisplayMedia=e.shimGetUserMedia=void 0;var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=WA();Object.defineProperty(e,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}});var r=JA();Object.defineProperty(e,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}}),e.shimOnTrack=function(e){"object"===(void 0===e?"undefined":t(e))&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},e.shimPeerConnection=function(e,i){if("object"===(void 0===e?"undefined":t(e))&&(e.RTCPeerConnection||e.mozRTCPeerConnection)){!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),i.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){var i=e.RTCPeerConnection.prototype[t],r=function(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}({},t,(function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}));e.RTCPeerConnection.prototype[t]=r[t]}));var r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){var e=Array.prototype.slice.call(arguments),t=e[0],o=e[1],a=e[2];return n.apply(this,[t||null]).then((function(e){if(i.version<53&&!o)try{e.forEach((function(e){e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach((function(t,i){e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(o,a)}}},e.shimSenderGetStats=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&(!e.RTCRtpSender||!("getStats"in e.RTCRtpSender.prototype))){var i=e.RTCPeerConnection.prototype.getSenders;i&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,t=i.apply(this,[]);return t.forEach((function(t){return t._pc=e})),t});var r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=r.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)}}},e.shimReceiverGetStats=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection&&e.RTCRtpSender&&(!e.RTCRtpSender||!("getStats"in e.RTCRtpReceiver.prototype))){var i=e.RTCPeerConnection.prototype.getReceivers;i&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,t=i.apply(this,[]);return t.forEach((function(t){return t._pc=e})),t}),n.wrapPeerConnectionEvent(e,"track",(function(e){return e.receiver._pc=e.srcElement,e})),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}},e.shimRemoveStream=function(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;n.deprecated("removeStream","removeTrack"),this.getSenders().forEach((function(i){i.track&&e.getTracks().includes(i.track)&&t.removeTrack(i)}))})},e.shimRTCDataChannel=function(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)},e.shimAddTransceiver=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection){var i=e.RTCPeerConnection.prototype.addTransceiver;i&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var e=arguments[1],t=e&&"sendEncodings"in e;t&&e.sendEncodings.forEach((function(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")}));var r=i.apply(this,arguments);if(t){var n=r.sender,o=n.getParameters();(!("encodings"in o)||1===o.encodings.length&&0===Object.keys(o.encodings[0]).length)&&(o.encodings=e.sendEncodings,n.sendEncodings=e.sendEncodings,this.setParametersPromises.push(n.setParameters(o).then((function(){delete n.sendEncodings})).catch((function(){delete n.sendEncodings}))))}return r})}},e.shimGetParameters=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCRtpSender){var i=e.RTCRtpSender.prototype.getParameters;i&&(e.RTCRtpSender.prototype.getParameters=function(){var e=i.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}},e.shimCreateOffer=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection){var i=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){var e=this,t=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return i.apply(e,t)})).finally((function(){e.setParametersPromises=[]})):i.apply(this,arguments)}}},e.shimCreateAnswer=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection){var i=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){var e=this,t=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return i.apply(e,t)})).finally((function(){e.setParametersPromises=[]})):i.apply(this,arguments)}}};var n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(MA())})),zA=bA((e=>{DA(QA()),Object.defineProperty(e,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};e.shimLocalStreamsAPI=function(e){if("object"===(void 0===e?"undefined":t(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)){var i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){var t=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((function(r){return i.call(t,r,e)})),e.getVideoTracks().forEach((function(r){return i.call(t,r,e)}))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var t=this,r=arguments.length,n=Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return n&&n.forEach((function(e){t._localStreams?t._localStreams.includes(e)||t._localStreams.push(e):t._localStreams=[e]})),i.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._localStreams||(this._localStreams=[]);var i=this._localStreams.indexOf(e);if(-1!==i){this._localStreams.splice(i,1);var r=e.getTracks();this.getSenders().forEach((function(e){r.includes(e.track)&&t.removeTrack(e)}))}})}},e.shimRemoteStreamsAPI=function(e){if("object"===(void 0===e?"undefined":t(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:function(){return this._onaddstream},set:function(e){var t=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((function(e){if(t._remoteStreams||(t._remoteStreams=[]),!t._remoteStreams.includes(e)){t._remoteStreams.push(e);var i=new Event("addstream");i.stream=e,t.dispatchEvent(i)}}))})}});var i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((function(t){if(e._remoteStreams||(e._remoteStreams=[]),!(e._remoteStreams.indexOf(t)>=0)){e._remoteStreams.push(t);var i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}}))}),i.apply(e,arguments)}}},e.shimCallbacksAPI=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.RTCPeerConnection){var i=e.RTCPeerConnection.prototype,r=i.createOffer,n=i.createAnswer,o=i.setLocalDescription,a=i.setRemoteDescription,s=i.addIceCandidate;i.createOffer=function(e,t){var i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},i.createAnswer=function(e,t){var i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};var c=function(e,t,i){var r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r};i.setLocalDescription=c,c=function(e,t,i){var r=a.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},i.setRemoteDescription=c,c=function(e,t,i){var r=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},i.addIceCandidate=c}},e.shimGetUserMedia=function(e){var t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){var i=t.mediaDevices,n=i.getUserMedia.bind(i);t.mediaDevices.getUserMedia=function(e){return n(r(e))}}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))},e.shimConstraints=r,e.shimRTCIceServerUrls=function(e){if(e.RTCPeerConnection){var t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){for(var n=[],o=0;o<e.iceServers.length;o++){var a=e.iceServers[o];!a.hasOwnProperty("urls")&&a.hasOwnProperty("url")?(i.deprecated("RTCIceServer.url","RTCIceServer.urls"),(a=JSON.parse(JSON.stringify(a))).urls=a.url,delete a.url,n.push(a)):n.push(e.iceServers[o])}e.iceServers=n}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:function(){return t.generateCertificate}})}},e.shimTrackEventTransceiver=function(e){"object"===(void 0===e?"undefined":t(e))&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})},e.shimCreateOfferLegacy=function(e){var t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);var i=this.getTransceivers().find((function(e){return"audio"===e.receiver.track.kind}));!1===e.offerToReceiveAudio&&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.offerToReceiveAudio&&!i&&this.addTransceiver("audio"),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);var r=this.getTransceivers().find((function(e){return"video"===e.receiver.track.kind}));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0===e.offerToReceiveVideo&&!r&&this.addTransceiver("video")}return t.apply(this,arguments)}},e.shimAudioContext=function(e){"object"!==(void 0===e?"undefined":t(e))||e.AudioContext||(e.AudioContext=e.webkitAudioContext)};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(MA());function r(e){return e&&void 0!==e.video?Object.assign({},e,{video:i.compactObject(e.video)}):e}})),YA=bA((e=>{DA(QA()),Object.defineProperty(e,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};e.shimRTCIceCandidate=function(e){if(!(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)){var i=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"===(void 0===e?"undefined":t(e))&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){var r=new i(e),o=n.default.parseCandidate(e.candidate),a=Object.assign(r,o);return a.toJSON=function(){return{candidate:a.candidate,sdpMid:a.sdpMid,sdpMLineIndex:a.sdpMLineIndex,usernameFragment:a.usernameFragment}},a}return new i(e)},e.RTCIceCandidate.prototype=i.prototype,o.wrapPeerConnectionEvent(e,"icecandidate",(function(t){return t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t}))}},e.shimMaxMessageSize=function(e,t){if(e.RTCPeerConnection){"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp}});var i=function(e){if(!e||!e.sdp)return!1;var t=n.default.splitSections(e.sdp);return t.shift(),t.some((function(e){var t=n.default.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},r=function(e){var t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;var i=parseInt(t[1],10);return i!=i?-1:i},o=function(e){var i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i},a=function(e,i){var r=65536;"firefox"===t.browser&&57===t.version&&(r=65535);var o=n.default.matchPrefix(e.sdp,"a=max-message-size:");return o.length>0?r=parseInt(o[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(r=2147483637),r},s=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){var e=this.getConfiguration(),n=e.sdpSemantics;"plan-b"===n&&Object.defineProperty(this,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){var c=r(arguments[0]),l=o(c),d=a(arguments[0],c),u=void 0;u=0===l&&0===d?Number.POSITIVE_INFINITY:0===l||0===d?Math.max(l,d):Math.min(l,d);var h={};Object.defineProperty(h,"maxMessageSize",{get:function(){return u}}),this._sctp=h}return s.apply(this,arguments)}}},e.shimSendThrowTypeError=function(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){var i=e.send;e.send=function(){var 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)}}var i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){var e=i.apply(this,arguments);return t(e,this),e},o.wrapPeerConnectionEvent(e,"datachannel",(function(e){return t(e.channel,e.target),e}))},e.shimConnectionState=function(e){if(e.RTCPeerConnection&&!("connectionState"in e.RTCPeerConnection.prototype)){var t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(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((function(e){var i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;var i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}},e.removeExtmapAllowMixed=function(e,t){if(e.RTCPeerConnection&&!("chrome"===t.browser&&t.version>=71)&&!("safari"===t.browser&&t.version>=605)){var i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){var r=t.sdp.split("\n").filter((function(e){return"a=extmap-allow-mixed"!==e.trim()})).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return i.apply(this,arguments)}}},e.shimAddIceCandidateNullOrEmpty=function(e,t){if(e.RTCPeerConnection&&e.RTCPeerConnection.prototype){var 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())})}};var i,r=jA(),n=(i=r)&&i.__esModule?i:{default:i},o=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(MA())})),qA=bA((e=>{DA(QA()),Object.defineProperty(e,"__esModule",{value:!0}),e.adapterFactory=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=e.window,c=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},l=t.log,d=t.detectBrowser(s),u={browserDetails:d,commonShim:a,extractVersion:t.extractVersion,disableLog:t.disableLog,disableWarnings:t.disableWarnings};switch(d.browser){case"chrome":if(!i||!i.shimPeerConnection||!c.shimChrome)return l("Chrome shim is not included in this adapter release."),u;if(null===d.version)return l("Chrome shim can not determine version, not shimming."),u;l("adapter.js shimming chrome."),u.browserShim=i,a.shimAddIceCandidateNullOrEmpty(s,d),i.shimGetUserMedia(s,d),i.shimMediaStream(s,d),i.shimPeerConnection(s,d),i.shimOnTrack(s,d),i.shimAddTrackRemoveTrack(s,d),i.shimGetSendersWithDtmf(s,d),i.shimGetStats(s,d),i.shimSenderReceiverGetStats(s,d),i.fixNegotiationNeeded(s,d),a.shimRTCIceCandidate(s,d),a.shimConnectionState(s,d),a.shimMaxMessageSize(s,d),a.shimSendThrowTypeError(s,d),a.removeExtmapAllowMixed(s,d);break;case"firefox":if(!n||!n.shimPeerConnection||!c.shimFirefox)return l("Firefox shim is not included in this adapter release."),u;l("adapter.js shimming firefox."),u.browserShim=n,a.shimAddIceCandidateNullOrEmpty(s,d),n.shimGetUserMedia(s,d),n.shimPeerConnection(s,d),n.shimOnTrack(s,d),n.shimRemoveStream(s,d),n.shimSenderGetStats(s,d),n.shimReceiverGetStats(s,d),n.shimRTCDataChannel(s,d),n.shimAddTransceiver(s,d),n.shimGetParameters(s,d),n.shimCreateOffer(s,d),n.shimCreateAnswer(s,d),a.shimRTCIceCandidate(s,d),a.shimConnectionState(s,d),a.shimMaxMessageSize(s,d),a.shimSendThrowTypeError(s,d);break;case"edge":if(!r||!r.shimPeerConnection||!c.shimEdge)return l("MS edge shim is not included in this adapter release."),u;l("adapter.js shimming edge."),u.browserShim=r,r.shimGetUserMedia(s,d),r.shimGetDisplayMedia(s,d),r.shimPeerConnection(s,d),r.shimReplaceTrack(s,d),a.shimMaxMessageSize(s,d),a.shimSendThrowTypeError(s,d);break;case"safari":if(!o||!c.shimSafari)return l("Safari shim is not included in this adapter release."),u;l("adapter.js shimming safari."),u.browserShim=o,a.shimAddIceCandidateNullOrEmpty(s,d),o.shimRTCIceServerUrls(s,d),o.shimCreateOfferLegacy(s,d),o.shimCallbacksAPI(s,d),o.shimLocalStreamsAPI(s,d),o.shimRemoteStreamsAPI(s,d),o.shimTrackEventTransceiver(s,d),o.shimGetUserMedia(s,d),o.shimAudioContext(s,d),a.shimRTCIceCandidate(s,d),a.shimMaxMessageSize(s,d),a.shimSendThrowTypeError(s,d),a.removeExtmapAllowMixed(s,d);break;default:l("Unsupported browser!")}return u};var t=s(MA()),i=s(UA()),r=s(GA()),n=s(KA()),o=s(zA()),a=s(YA());function s(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}})),QA=bA((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=(0,qA().adapterFactory)({window:"undefined"==typeof window?void 0:window});e.default=t})),XA=bA(((e,t)=>{DA(QA());var i=Object.prototype.hasOwnProperty,r="~";function n(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var s=new o(i,n||e,a),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(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,a=new Array(o);n<o;n++)a[n]=i[n].fn;return a},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,a){var s=r?r+e:e;if(!this._events[s])return!1;var c,l,d=this._events[s],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,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,a),!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 a(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return a(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 s(this,o),this;var a=this._events[o];if(a.fn)a.fn===t&&(!n||a.once)&&(!i||a.context===i)&&s(this,o);else{for(var c=0,l=[],d=a.length;c<d;c++)(a[c].fn!==t||n&&!a[c].once||i&&a[c].context!==i)&&l.push(a[c]);l.length?this._events[o]=1===l.length?l[0]:l:s(this,o)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(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)})),$A=bA(((e,t)=>{DA(QA());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")}))}))})),ZA=bA((e=>{DA(QA());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=$A(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],a=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:[]}),a=o[o.length-1]);for(var s=0;s<(r[t]||[]).length;s+=1){var c=r[t][s];if(c.reg.test(n))return i(c,a,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}}))}))}})),eR=bA(((e,t)=>{DA(QA());var i=$A(),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 a=t.names[o];t.name?r.push(i[t.name][a]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||a,n=t.innerOrder||s,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"}})),tR=bA((e=>{DA(QA());var t=ZA(),i=eR();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})),iR=bA(((e,t)=>{DA(QA()),function(e){function i(e,t){var i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function r(e,t,r,n,o,a){return i(function(e,t){return e<<t|e>>>32-t}(i(i(t,e),i(n,a)),o),r)}function n(e,t,i,n,o,a,s){return r(t&i|~t&n,e,t,o,a,s)}function o(e,t,i,n,o,a,s){return r(t&n|i&~n,e,t,o,a,s)}function a(e,t,i,n,o,a,s){return r(t^i^n,e,t,o,a,s)}function s(e,t,i,n,o,a,s){return r(i^(t|~n),e,t,o,a,s)}function c(e,t){e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var r,c,l,d,u,h=1732584193,p=-271733879,m=-1732584194,_=271733878;for(r=0;r<e.length;r+=16)c=h,l=p,d=m,u=_,h=n(h,p,m,_,e[r],7,-680876936),_=n(_,h,p,m,e[r+1],12,-389564586),m=n(m,_,h,p,e[r+2],17,606105819),p=n(p,m,_,h,e[r+3],22,-1044525330),h=n(h,p,m,_,e[r+4],7,-176418897),_=n(_,h,p,m,e[r+5],12,1200080426),m=n(m,_,h,p,e[r+6],17,-1473231341),p=n(p,m,_,h,e[r+7],22,-45705983),h=n(h,p,m,_,e[r+8],7,1770035416),_=n(_,h,p,m,e[r+9],12,-1958414417),m=n(m,_,h,p,e[r+10],17,-42063),p=n(p,m,_,h,e[r+11],22,-1990404162),h=n(h,p,m,_,e[r+12],7,1804603682),_=n(_,h,p,m,e[r+13],12,-40341101),m=n(m,_,h,p,e[r+14],17,-1502002290),h=o(h,p=n(p,m,_,h,e[r+15],22,1236535329),m,_,e[r+1],5,-165796510),_=o(_,h,p,m,e[r+6],9,-1069501632),m=o(m,_,h,p,e[r+11],14,643717713),p=o(p,m,_,h,e[r],20,-373897302),h=o(h,p,m,_,e[r+5],5,-701558691),_=o(_,h,p,m,e[r+10],9,38016083),m=o(m,_,h,p,e[r+15],14,-660478335),p=o(p,m,_,h,e[r+4],20,-405537848),h=o(h,p,m,_,e[r+9],5,568446438),_=o(_,h,p,m,e[r+14],9,-1019803690),m=o(m,_,h,p,e[r+3],14,-187363961),p=o(p,m,_,h,e[r+8],20,1163531501),h=o(h,p,m,_,e[r+13],5,-1444681467),_=o(_,h,p,m,e[r+2],9,-51403784),m=o(m,_,h,p,e[r+7],14,1735328473),h=a(h,p=o(p,m,_,h,e[r+12],20,-1926607734),m,_,e[r+5],4,-378558),_=a(_,h,p,m,e[r+8],11,-2022574463),m=a(m,_,h,p,e[r+11],16,1839030562),p=a(p,m,_,h,e[r+14],23,-35309556),h=a(h,p,m,_,e[r+1],4,-1530992060),_=a(_,h,p,m,e[r+4],11,1272893353),m=a(m,_,h,p,e[r+7],16,-155497632),p=a(p,m,_,h,e[r+10],23,-1094730640),h=a(h,p,m,_,e[r+13],4,681279174),_=a(_,h,p,m,e[r],11,-358537222),m=a(m,_,h,p,e[r+3],16,-722521979),p=a(p,m,_,h,e[r+6],23,76029189),h=a(h,p,m,_,e[r+9],4,-640364487),_=a(_,h,p,m,e[r+12],11,-421815835),m=a(m,_,h,p,e[r+15],16,530742520),h=s(h,p=a(p,m,_,h,e[r+2],23,-995338651),m,_,e[r],6,-198630844),_=s(_,h,p,m,e[r+7],10,1126891415),m=s(m,_,h,p,e[r+14],15,-1416354905),p=s(p,m,_,h,e[r+5],21,-57434055),h=s(h,p,m,_,e[r+12],6,1700485571),_=s(_,h,p,m,e[r+3],10,-1894986606),m=s(m,_,h,p,e[r+10],15,-1051523),p=s(p,m,_,h,e[r+1],21,-2054922799),h=s(h,p,m,_,e[r+8],6,1873313359),_=s(_,h,p,m,e[r+15],10,-30611744),m=s(m,_,h,p,e[r+6],15,-1560198380),p=s(p,m,_,h,e[r+13],21,1309151649),h=s(h,p,m,_,e[r+4],6,-145523070),_=s(_,h,p,m,e[r+11],10,-1120210379),m=s(m,_,h,p,e[r+2],15,718787259),p=s(p,m,_,h,e[r+9],21,-343485551),h=i(h,c),p=i(p,l),m=i(m,d),_=i(_,u);return[h,p,m,_]}function l(e){var t,i="",r=32*e.length;for(t=0;t<r;t+=8)i+=String.fromCharCode(e[t>>5]>>>t%32&255);return i}function d(e){var t,i=[];for(i[(e.length>>2)-1]=void 0,t=0;t<i.length;t+=1)i[t]=0;var r=8*e.length;for(t=0;t<r;t+=8)i[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return i}function u(e){var t,i,r="0123456789abcdef",n="";for(i=0;i<e.length;i+=1)t=e.charCodeAt(i),n+=r.charAt(t>>>4&15)+r.charAt(15&t);return n}function h(e){return unescape(encodeURIComponent(e))}function p(e){return function(e){return l(c(d(e),8*e.length))}(h(e))}function m(e,t){return function(e,t){var i,r,n=d(e),o=[],a=[];for(o[15]=a[15]=void 0,n.length>16&&(n=c(n,8*e.length)),i=0;i<16;i+=1)o[i]=909522486^n[i],a[i]=1549556828^n[i];return r=c(o.concat(d(t)),512+8*t.length),l(c(a.concat(r),640))}(h(e),h(t))}function _(e,t,i){return t?i?m(t,e):function(e,t){return u(m(e,t))}(t,e):i?p(e):function(e){return u(p(e))}(e)}"function"==typeof define&&define.amd?define((function(){return _})):"object"==typeof t&&t.exports?t.exports=_:e.md5=_}(e)}));DA(QA()),DA(QA());var rR=DA(XA());DA(QA(),1),DA(QA(),1),DA(QA(),1);var nR,oR=((nR=oR||{})[nR.INVALID_PARAMETER=4096]="INVALID_PARAMETER",nR[nR.INVALID_OPERATION=4097]="INVALID_OPERATION",nR[nR.NOT_SUPPORTED=4098]="NOT_SUPPORTED",nR[nR.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",nR[nR.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",nR[nR.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",nR[nR.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",nR[nR.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",nR[nR.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",nR[nR.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",nR[nR.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",nR[nR.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",nR[nR.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",nR[nR.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",nR[nR.CLIENT_BANNED=16448]="CLIENT_BANNED",nR[nR.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",nR[nR.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",nR[nR.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",nR[nR.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",nR[nR.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",nR[nR.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",nR[nR.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",nR[nR.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",nR[nR.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",nR[nR.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",nR[nR.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",nR[nR.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",nR[nR.API_CALL_ABORTED=16461]="API_CALL_ABORTED",nR[nR.UNKNOWN=65535]="UNKNOWN",nR),aR=oR,sR=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=aR.UNKNOWN,extraCode:n=0,constraint:o}=e,a="<".concat(function(e){for(let t in aR)if(aR[t]===e)return t;return"UNKNOWN"}(r)," 0x").concat(r.toString(16),">"),s="".concat(i).concat(o?" constraint: ".concat(o):"").concat(null!=i&&i.includes(a)?"":" ".concat(a));super(s),NA(this,"code"),NA(this,"extraCode"),NA(this,"message"),NA(this,"originMessage"),NA(this,"name"),NA(this,"constraint"),this.code=r,this.extraCode=n,this.name=t,this.message=s,this.constraint=o,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},cR=sR;DA(QA(),1),DA(QA(),1);(new Date).getTime();var lR=0,dR=function(){return(new Date).getTime()+lR},uR=function(){let e=new Date;return e.setTime(dR()),e.toLocaleString()},hR={};kA(hR,{bytes2ms:()=>PD,copyProperties:()=>ND,deepMerge:()=>hO,fibonacci:()=>FD,formatedTime:()=>_O,getConstructorName:()=>ZD,getContainerFromElement:()=>pO,getEnv:()=>CD,getInternalVersion:()=>nO,getLoggerUrl:()=>RD,getMuteStateFromFlag:()=>sO,getNetworkQuality:()=>cO,getNetworkType:()=>DD,getOSType:()=>kD,getReconnectionTimeout:()=>BD,getSysInfo:()=>OD,getTerminalType:()=>bD,getTurnServer:()=>lO,getValueType:()=>jD,glog:()=>VD,ipv4ToUint32:()=>dO,isArray:()=>YD,isArrayOrObject:()=>uO,isAudioWorkletSupported:()=>eO,isBoolean:()=>KD,isConstructor:()=>$D,isEmpty:()=>aO,isFunction:()=>HD,isLangChinese:()=>UD,isMediaStreamTrack:()=>qD,isNumber:()=>JD,isObject:()=>zD,isOverseaSdkAppId:()=>AD,isPlainObject:()=>xD,isPromise:()=>XD,isRemoteTrack:()=>QD,isString:()=>WD,isUndefined:()=>GD,ms2bytes:()=>MD,ms2samples:()=>LD,performanceNow:()=>iO,promiseAny:()=>tO,samples2ms:()=>wD,stringify:()=>fO}),DA(QA(),1);var pR={};kA(pR,{ANDROID_VERSION:()=>RR,CHROME_MAJOR_VERSION:()=>Rb,CHROME_VERSION:()=>bb,EDGE_VERSION:()=>wR,EDG_MAJOR_VERSION:()=>VR,EDG_VERSION:()=>LR,FIREFOX_MAJOR_VERSION:()=>NR,FIREFOX_VERSION:()=>OR,HUAWEI_VERSION:()=>_b,IE_VERSION:()=>zR,IOS_VERSION:()=>Pb,IPADQQB_VERSION:()=>nb,IS_ANDROID:()=>AR,IS_ANDROID_WEBVIEW:()=>Nb,IS_ANY_SAFARI:()=>Db,IS_CHROME:()=>Cb,IS_CHROME_ONLY:()=>Ib,IS_EDG:()=>MR,IS_EDGE:()=>PR,IS_ELECTRON:()=>db,IS_FIREFOX:()=>DR,IS_HEADLESS_CHROME:()=>Ab,IS_HUAWEI:()=>mb,IS_HUAWEIBROWSER:()=>pb,IS_IE:()=>KR,IS_IE8:()=>JR,IS_IOS:()=>CR,IS_IOS_13_OR_14:()=>Lb,IS_IOS_15_1:()=>Mb,IS_IPAD:()=>vR,IS_IPADQQB:()=>rb,IS_IPAD_PRO:()=>ER,IS_IPHONE:()=>yR,IS_IPOD:()=>IR,IS_LINUX:()=>sb,IS_LOCAL:()=>Vb,IS_MAC:()=>ab,IS_MACQQB:()=>tb,IS_MIBROWSER:()=>ub,IS_MQQB:()=>XR,IS_NATIVE_ANDROID:()=>kR,IS_OLD_ANDROID:()=>bR,IS_OPPOBROWSER:()=>Tb,IS_SAFARI:()=>kb,IS_SAFARI_15_1:()=>wb,IS_SAMSUNGBROWSER:()=>fb,IS_SOGOU:()=>FR,IS_SOGOUM:()=>UR,IS_TBS:()=>jR,IS_UCBROWSER:()=>lb,IS_VIVOBROWSER:()=>vb,IS_WECHAT:()=>YR,IS_WIN:()=>ob,IS_WQQB:()=>ZR,IS_WX:()=>cb,IS_X5MQQB:()=>QR,IS_XWEB:()=>GR,MACQQB_VERSION:()=>ib,MI_VERSION:()=>hb,MQQB_VERSION:()=>$R,OPPO_VERSION:()=>Sb,SAFARI_VERSION:()=>Ob,SAMSUNG_VERSION:()=>gb,SOGOUM_VERSION:()=>xR,SOGOU_VERSION:()=>BR,TBS_VERSION:()=>HR,USER_AGENT:()=>mR,VIVO_VERSION:()=>Eb,WECHAT_VERSION:()=>qR,WQQB_VERSION:()=>eb,XWEB_VERSION:()=>WR,browserInfo:()=>xb,getBrowserInfo:()=>Fb,getChromeMajorVersion:()=>yb,isLocalStorageEnabled:()=>Ub}),DA(QA(),1);var mR="undefined"==typeof navigator?"":navigator.userAgent,_R=e=>new RegExp(e,"i").test(mR),fR=e=>{if(_R(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=mR.match(t);if(i&&i[1])return i[1]}return""},gR=e=>{if(_R(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=mR.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},TR=/AppleWebKit\/([\d.]+)/i.exec(mR),SR=TR?parseFloat(TR[1]):NaN,vR=_R("iPad"),ER="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&_R("Macintosh"),yR=_R("iPhone")&&!vR,IR=_R("iPod"),CR=yR||vR||IR||ER,AR=_R("Android"),RR=function(){if(AR){let e=mR.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}(),bR=AR&&_R("webkit")&&RR<2.3,kR=AR&&RR<5&&SR<537,DR=_R("Firefox"),OR=fR("Firefox"),NR=gR("Firefox"),PR=_R("Edge"),wR=fR("Edge"),MR=_R("Edg"),LR=fR("Edg"),VR=gR("Edg"),UR=_R("SogouMobileBrowser"),xR=fR("SogouMobileBrowser"),FR=_R("MetaSr\\s"),BR=fR("MetaSr\\s"),jR=_R("TBS"),HR=fR("TBS"),GR=_R("XWEB"),WR=fR("XWEB"),JR=_R("MSIE\\s8\\.0"),KR=_R("MSIE\\/\\d+"),zR=function(){if(KR){let e=/MSIE\s(\d+)\.\d/.exec(mR),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(mR)&&/rv:11.0/.test(mR)&&(t=11),t}return NaN}(),YR=_R("(micromessenger|webbrowser)"),qR=fR("MicroMessenger"),QR=!jR&&_R("MQQBrowser")&&_R("COVC"),XR=!jR&&_R("MQQBrowser")&&!_R("COVC"),$R=XR||QR?fR("MQQBrowser"):"",ZR=!jR&&_R(" QQBrowser"),eb=fR(" QQBrowser"),tb=!jR&&_R("QQBrowserLite"),ib=fR("QQBrowserLite"),rb=!jR&&_R("MQBHD"),nb=fR("MQBHD"),ob=_R("Windows"),ab=!CR&&_R("MAC OS X"),sb=!AR&&_R("Linux"),cb=_R("MicroMessenger"),lb=_R("UCBrowser"),db=_R("Electron"),ub=_R("MiuiBrowser"),hb=fR("MiuiBrowser"),pb=_R("HuaweiBrowser"),mb=_R("Huawei"),_b=fR("HuaweiBrowser"),fb=_R("SamsungBrowser"),gb=fR("SamsungBrowser"),Tb=_R("HeyTapBrowser"),Sb=fR("HeyTapBrowser"),vb=_R("VivoBrowser"),Eb=fR("VivoBrowser"),yb=()=>gR("Chrome"),Ib=_R("Chrome"),Cb=!PR&&!FR&&!UR&&!jR&&!GR&&!MR&&!ZR&&!ub&&!pb&&!fb&&!Tb&&!vb&&Ib,Ab=_R("HeadlessChrome"),Rb=yb(),bb=fR("Chrome"),kb=!Ib&&!XR&&!QR&&!tb&&!rb&&_R("Safari"),Db=kb||CR,Ob=fR("Safari"),Nb=/Android.*(wv|.0.0.0)/.test(mR),Pb=(()=>{if(ER)return Ob;if(CR){let e=mR.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),wb="15.1"===Ob,Mb="15.1"===Pb,Lb=(()=>{let e=Number(Pb.split(".")[0]);return 14===e||13===e})(),Vb="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),Ub=(()=>{let e;return()=>{if(GD(e))try{e=!!window.localStorage}catch(cM){e=!1}return e}})(),xb=Fb();function Fb(){let e=new Map([[DR,["Firefox",OR]],[MR,["Edg",LR]],[Cb,["Chrome",bb]],[kb,["Safari",Ob]],[jR,["TBS",HR]],[GR,["XWEB",WR]],[YR&&yR,["WeChat",qR]],[ZR,["QQ(Win)",eb]],[XR,["QQ(Mobile)",$R]],[QR,["QQ(Mobile X5)",$R]],[tb,["QQ(Mac)",ib]],[rb,["QQ(iPad)",nb]],[ub,["MI",hb]],[pb,["HW",_b]],[fb,["Samsung",gb]],[Tb,["OPPO",Sb]],[vb,["VIVO",Eb]],[PR,["EDGE",wR]],[UR,["SogouMobile",xR]],[FR,["Sogou",BR]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var Bb={};kA(Bb,{AUDIO_MUTE_BIT:()=>bk,AUDIO_STAT_BIT:()=>Rk,AUX_STAT_BIT:()=>Ak,AUX_STREAM_MSID:()=>Ok,BACKEND_ENV:()=>Ek,BASE_DOC_URL:()=>ik,BASE_HOST:()=>$b,CAPABILITIES_KEYS:()=>yD,CLASS_NAME:()=>lD,CLOUD_CONSOLE_URL:()=>tk,DATA_FREEZE_TIMING:()=>iD,DOC_URL:()=>rk,DTLS_STATE_UNKNOWN:()=>Bk,ENV_NAME:()=>ck,EXCHANGE_SDP_TIMEOUT:()=>Qk,INTERVAL:()=>vD,IS_WORKER:()=>zb,IS_WORKLET:()=>Yb,KIBANA_EVENT:()=>zk,LOCAL_STREAM_PUBLISH_STATE:()=>tD,LOGGER_CMD_TYPE:()=>sk,LOGGER_DOMAIN:()=>nk,LOGGER_DOMAIN_OVERSEA:()=>ok,LOG_LEVEL:()=>lk,LOG_LEVEL_NAME:()=>mD,MAIN_STREAM_MSID:()=>Dk,MICROPHONE_COMMUNICATIONS:()=>pD,MICROPHONE_DEFAULT:()=>uD,MIX_TRANCODE:()=>hk,MIX_TRANSCODE:()=>Zk,NAME:()=>Sk,NETWORK_TYPE:()=>pk,NOT_SUPPORTED_H264:()=>eD,PAUSED_RETRY_COUNT:()=>dD,PEERCONNECTION_CONNECTING_TIMEOUT:()=>aD,PEER_CONNECTION_STATE:()=>jk,PEER_LEAVE_REASON:()=>_D,RAF:()=>SD,RECOVER_CAPTURE_INTERVAL:()=>gD,REMOTE_STREAM_TYPE_AUX:()=>Pk,REMOTE_STREAM_TYPE_MAIN:()=>Nk,RENDER_FREEZE_TIMING:()=>rD,RIC:()=>TD,SCHEDULE_DOMAIN:()=>sD,SCHEDULE_TIMEOUT:()=>cD,SDP_SEMANTICS_PLAN_B:()=>$k,SDP_SEMANTICS_UNIFIED_PLAN:()=>Xk,SECOND_HOST:()=>Zb,SIGNAL_PING_PONG_INTERVAL:()=>uk,SIGNAL_PING_TIMEOUT:()=>dk,SIGNAL_RECONNECTION_COUNT:()=>Kk,SMALL_STAT_BIT:()=>Ck,SPEAKER_DEFAULT:()=>hD,STORAGE_EXPIRES_TIME:()=>mk,STREAM_TYPE_BIG:()=>nD,STREAM_TYPE_SMALL:()=>oD,SUBSCRIBE_SMALL_RETRY_COUNT:()=>fD,SYNC_USER_LIST_INTERVAL:()=>Yk,Scene:()=>yk,Switch:()=>_k,THIRD_HOST:()=>ek,TIMEOUT:()=>ED,TRANSPORT_DIRECTION:()=>vk,TRTC_ERROR_ASSISTANCE:()=>ak,TRTC_QUALITY_BAD:()=>Uk,TRTC_QUALITY_DISCONNECTED:()=>Fk,TRTC_QUALITY_EXCELLENT:()=>Mk,TRTC_QUALITY_GOOD:()=>Lk,TRTC_QUALITY_POOR:()=>Vk,TRTC_QUALITY_UNKNOWN:()=>wk,TRTC_QUALITY_VERY_BAD:()=>xk,UPDATE_OFFER_TIMEOUT:()=>qk,VIDEO_MUTE_BIT:()=>kk,VIDEO_STAT_BIT:()=>Ik,audioProfileMap:()=>fk,getRetryCount:()=>Wk,getScriptDir:()=>qb,innerVersion:()=>jb,loggerProxy:()=>Qb,screenProfileMap:()=>Tk,setLoggerProxy:()=>Xb,setRetryCount:()=>Gk,setVersion:()=>Gb,version:()=>Hb,videoProfileMap:()=>gk}),DA(QA(),1);var jb="4.15.00.1600",Hb="5.0.0";function Gb(e){Hb=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 Wb,Jb,Kb,zb="undefined"!=typeof importScripts,Yb="undefined"!=typeof registerProcessor,qb=()=>{let e=zb?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Qb="",Xb=e=>Qb=e,$b="web.sdk.qcloud.com",Zb="web.sdk.tencent.cn",ek="web.sdk.cloud.tencent.cn",tk="https://console.cloud.tencent.com/trtc",ik="https://".concat($b,"/trtc/webrtc/v5/doc"),rk="".concat(ik,"/zh-cn/"),nk="https://yun.tim.qq.com",ok="https://videoapi-sgp.im.qcloud.com",ak="trtc_error_assistance",sk={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport"},ck={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},lk=((Kb=lk||{})[Kb.TRACE=0]="TRACE",Kb[Kb.DEBUG=1]="DEBUG",Kb[Kb.INFO=2]="INFO",Kb[Kb.WARN=3]="WARN",Kb[Kb.ERROR=4]="ERROR",Kb[Kb.NONE=5]="NONE",Kb),dk=18e3,uk=2e3,hk={MODE:{MANUAL:"manual",PRESET_LAYOUT:"preset-layout"},PLACE_HOLDER:{REMOTE:"$PLACE_HOLDER_REMOTE$"},STREAM_TYPE:{IT_AUDIO_VIDEO:0,IT_PICTURE:2,IT_CANVAS:3,IT_PURE_AUDIO:4,IT_PURE_VIDEO:5}},pk={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5},mk=6048e5,_k=((Jb=_k||{}).USEAINS="useAINS",Jb.ENABLEDEBUG="enableDebug",Jb.USEV2="useV2",Jb.USEWT="useWt",Jb),fk={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:192},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},gk={"120p":{width:160,height:120,frameRate:15,bitrate:200},"180p":{width:320,height:180,frameRate:15,bitrate:350},"240p":{width:320,height:240,frameRate:15,bitrate:400},"360p":{width:640,height:360,frameRate:15,bitrate:800},"480p":{width:640,height:480,frameRate:15,bitrate:900},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},Tk={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},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",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"},vk={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Ek={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},yk=((Wb=yk||{}).LIVE="live",Wb.RTC="rtc",Wb),Ik=1,Ck=2,Ak=4,Rk=8,bk=64,kk=16,Dk="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Ok="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Nk=Sk.MAIN,Pk=Sk.AUXILIARY,wk=0,Mk=1,Lk=2,Vk=3,Uk=4,xk=5,Fk=6,Bk="unknown",jk={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Hk=1/0;function Gk(e){Hk=e}function Wk(){return Hk}var Jk,Kk=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"},Yk=1e4,qk=1e4,Qk=1e4,Xk="unified-plan",$k="plan-b",Zk={MODE:{MANUAL:"manual",PRESET_LAYOUT:"preset-layout"},PLACE_HOLDER:{REMOTE:"$PLACE_HOLDER_REMOTE$"},STREAM_TYPE:{IT_AUDIO_VIDEO:0,IT_PICTURE:2,IT_CANVAS:3,IT_PURE_AUDIO:4,IT_PURE_VIDEO:5}},eD=1028,tD=((Jk=tD||{})[Jk.UNPUBLISH=-1]="UNPUBLISH",Jk[Jk.PUBLISHING=0]="PUBLISHING",Jk[Jk.PUBLISHED=1]="PUBLISHED",Jk),iD=500,rD=1e3,nD=Sk.BIG,oD=Sk.SMALL,aD=1e4,sD={MAIN:"schedule.rtc.qq.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA:"schedule-ecdn.rtc.tencentcloud.com"},cD=2e3,lD={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},dD=5,uD="default",hD=uD,pD="communications",mD=Object.keys(lk),_D=["normal leave","timeout leave","kick","role change"],fD=10,gD=2e3,TD="ric",SD="raf",vD="interval",ED="timeout",yD=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId"];DA(QA(),1);var ID=1e8,CD=function(){return new URLSearchParams(location.search).get("trtc_env")||""},AD=e=>Number(e)<14e8,RD=function(e,t){let i;i=Qb||(AD(e)?ok:nk);let r=Math.floor(Math.random()*IA(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)};function bD(){return AR?4:yR?2:vR?3:ab?12:ob?5:sb?13:1}function kD(){return AR?"Android":yR?"iPhone":vR?"iPad":ab?"Mac":ob?"Windows":sb?"Linux":"unknown"}function DD(){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();"slow-2"===n&&(n="2g");let o=i||"unknown";if(r)switch(r){case"cellular":case"wimax":o=n||"unknown";break;case"wifi":o="wifi";break;case"ethernet":o="wired";break;default:o="unknown"}return o}var OD=function(e){return{AbilityOption:{AVLimit:e,GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:String(navigator.platform),uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:bD(),uint32_device_type:0,str_os_verion:kD(),uint32_link_type:1,str_client_version:jb,uint32_net_type:pk[DD()],ua:navigator.userAgent,version:""}}}};function ND(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){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3;return wD(e/4,t)}function wD(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3;return 1e3*e/t}function MD(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3;return 4*LD(e,t)}function LD(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3;return e*t/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},xD=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 FD(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?i:FD(e-1,i,t+i)}function BD(e){return e>8?3e4:1e3*FD(e)}function jD(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var HD=e=>"function"==typeof e,GD=e=>void 0===e,WD=e=>"string"==typeof e,JD=e=>"number"==typeof e,KD=e=>"boolean"==typeof e,zD=e=>"object"===jD(e),YD=e=>"array"===jD(e),qD=e=>jD(e)==="MediaStreamTrack".toLowerCase(),QD=e=>e.isRemote,XD=e=>"promise"===jD(e),$D=e=>HD(e)&&e.prototype.constructor===e,ZD=e=>$D(e)?e.prototype.constructor.name:"",eO="undefined"!=typeof AudioWorkletNode;function tO(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 iO(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var rO=e=>+e<10?"0".concat(e):e,nO=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=rO(i[1])+rO(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},oO=Object.prototype.hasOwnProperty;function aO(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(xD(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(oO.call(e,t))return!1;return!0}return!1}function sO(e,t){return{userId:t,hasAudio:!!(e&Rk),hasVideo:!!(e&Ik),hasAuxiliary:!!(e&Ak),hasSmall:!!(e&Ck),audioMuted:!!(e&bk),videoMuted:!!(e&kk),audioAvailable:!(!(e&Rk)||e&bk),videoAvailable:!(!(e&Ik)||e&kk)}}function cO(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}function lO(e){let t={urls:"turn:".concat(e.url)};return!GD(e.username)&&!GD(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",GD(e.credentialType)||(t.credentialType=e.credentialType)),t}function dO(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!WD(e))return 0;let i=e.split(".");return t?(Number(i[0])<<24|Number(i[1])<<16|Number(i[2])<<8|Number(i[3]))>>>0:(Number(i[3])<<24|Number(i[2])<<16|Number(i[1])<<8|Number(i[0]))>>>0}var uO=function(e){return YD(e)||zD(e)},hO=function(e,t,i,r){if(!uO(e)||!uO(t))return 0;let n,o=0,a=Object.keys(t);for(let s=0,c=a.length;s<c;s++)if(n=a[s],!(GD(t[n])||i&&i.includes(n)))if(uO(e[n])&&uO(t[n]))o+=hO(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=t[n],o+=1)}return o},pO=e=>WD(e)?document.getElementById(e):e,mO=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),_O=()=>mO.format(new Date);function fO(e,t){try{if(YD(e))return"[".concat(e.map((e=>fO(e,t))).join(","),"]");if(!xD(e)||!YD(t))return JSON.stringify(e);let i={},r=new Set(t);return Object.keys(e).forEach((t=>{r.has(t)&&(i[t]=e[t])})),JSON.stringify(i)}catch(Wb){return"{}"}}function gO(e){let{url:t,body:i,method:r,timeout:n}=e,o=new XMLHttpRequest;return new Promise(((e,a)=>{o.onreadystatechange=()=>{if(4===o.readyState)if(o.status>=200&&o.status<300)try{let t=JSON.parse(o.response);e({data:t})}catch(cU){e({data:o.response})}else a({status:o.status,statusText:o.statusText||"request failed!"})},o.timeout=n||5e3,o.open(r||"POST",t,!0),o.send(i)}))}DA(QA(),1),DA(QA(),1);var TO=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:n,onRetryFailed:o,context:a}=e;return function(){for(var e=arguments.length,s=new Array(e),c=0;c<e;c++)s[c]=arguments[c];let{retries:l=5,timeout:d=1e3}=i,u=0,h=-1,p=0,m=(e,i)=>wA(this,null,(function*(){let c=a||this;try{let i=yield t.apply(c,s);u=0,e(i)}catch(cA){let a=()=>{clearTimeout(h),u=0,p=2,i(cA)},_=()=>{2!==p&&u<(HD(l)?l():l)?(u++,p=1,HD(n)&&n.call(this,u,a),h=window.setTimeout((()=>{h=-1,m(e,i)}),HD(d)?d(u):d)):(a(),HD(o)&&o.call(this,cA))};HD(r)?r.call(c,cA,_,i,s):_()}}));return new Promise(m)}};DA(QA(),1);DA(QA(),1);var SO=new(DA(XA(),1).default);DA(QA(),1),DA(QA(),1);var vO,EO=((vO=EO||{}).ROOM_DESTROY="1",vO.JOIN_START="21",vO.JOIN_SCHEDULE_SUCCESS="22",vO.JOIN_SIGNAL_CONNECTION_START="23",vO.JOIN_SIGNAL_CONNECTION_END="24",vO.JOIN_SEND_CMD="25",vO.JOIN_RECEIVED_CMD_RES="26",vO.JOIN_SUCCESS="27",vO.JOIN_FAILED="28",vO.LEAVE_START="51",vO.LEAVE_SEND_CMD="52",vO.LEAVE_SUCCESS="53",vO.PUBLISH_START="61",vO.SEND_FIRST_VIDEO_FRAME="62",vO.SUBSCRIBE_START="81",vO.SUBSCRIBE_SUCCESS="82",vO.UNSUBSCRIBE_SUCCESS="83",vO.LOCAL_TRACK_CAPTURE_START="101",vO.LOCAL_TRACK_CAPTURE_SUCCESS="102",vO.LOCAL_TRACK_CAPTURE_FAILED="103",vO.LOCAL_TRACK_PUBLISHED="104",vO.LOCAL_TRACK_UNPUBLISHED="105",vO.LOCAL_TRACK_REPLACED="106",vO.SWITCH_DEVICE_SUCCESS="107",vO.TRACK_MUTED="108",vO.TRACK_UNMUTED="109",vO.REMOTE_TRACK_SUBSCRIBED="110",vO.REMOTE_TRACK_UNSUBSCRIBED="111",vO.PLAY_TRACK_START="151",vO.PLAYER_STATE_CHANGED="152",vO.VIDEO_LOADED_DATA="153",vO.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",vO.WORKLET_LOADED_SUCCESS="155",vO.WORKLET_LOADED_FAILED="156",vO.SIGNAL_CONNECTION_STATE_CHANGED="201",vO.PEER_CONNECTION_STATE_CHANGED="202",vO.HEARTBEAT_REPORT="251",vO.RECEIVED_PUBLISHED_USER_LIST="252",vO.REMOTE_PUBLISH_STATE_CHANGED="253",vO.AUDIO_LEVEL_INTERVAL="260",vO.NETWORK_QUALITY="261",vO.API_SUCCESS_RATE="262",vO),yO=EO,IO=!(CR||AR||Ab),CO=new class{constructor(){NA(this,"_isEnableUploadLog",!0),NA(this,"_localJoinedUser",new Map),NA(this,"_queue",[]),NA(this,"_timeoutId",-1),NA(this,"_logLevel",1),NA(this,"_logLevelToUpload",2),!zb&&!Yb&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){SO.on(yO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&lk[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),SO.on(yO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),SO.once(yO.JOIN_FAILED,(()=>{this.startUpload()})),SO.on(yO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.deleteJoinedUser(t.userId)}))}startUpload(){-1===this._timeoutId&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch((()=>{})),this._timeoutId=window.setTimeout((()=>this.uploadInterval()),2e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&0===this._localJoinedUser.size)return e;let t=0;for(;t<this._queue.length&&50!==t;t++){let i=this._queue[t];if(i.forAllJoinedClients)this._localJoinedUser.forEach((t=>{let{userId:r,sdkAppId:n}=t;e.map.has(r)?e.map.get(r).logs.push(i):e.map.set(r,{userId:r,sdkAppId:n,logs:[i]})}));else if(WD(i.userId)&&JD(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 wA(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:uR(),sdkAppId:String(r),userId:i,version:Hb,log:n.map((e=>e.log)).join("\n")}),r),n.forEach((e=>e.uploaded=!0))}}catch(Jb){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return TO({retryFunction:()=>gO({url:RD(t,sk.LOG),body:e,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:(e,t)=>{t()}})()}getPrefix(e){let t=new Date;t.setTime(dR());let i=String(t.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),"[".concat(t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(i,"] <").concat(lk[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){GD(lk[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(WD(e))return e;try{return JSON.stringify(e)}catch(Wb){return""}}log(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;var o;if(t.unshift(this.getPrefix(e)),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push({log:t.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:e,userId:r,sdkAppId:n,forAllJoinedClients:i}),e<this._logLevel)return;let a=(null==(o=lk[e])?void 0:o.toLowerCase())||"info";IO?console[a]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...t):console[a](...t)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}createLogger(e){return new class{constructor(e){NA(this,"userId"),NA(this,"remoteUserId"),NA(this,"id"),NA(this,"sdkAppId"),NA(this,"type"),NA(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!KD(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):"","]")),CO.log(e,t,GD(this.userId)||aO(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)}}(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;lk[t]&&(this._logLevelToUpload=t)}};DA(QA(),1);var AO=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)}))};DA(QA(),1);var RO=new class{constructor(){NA(this,"_prefix","TRTC"),NA(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){Ub()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix)){let t=JSON.parse(localStorage.getItem(e));if(t&&t.expiresIn<Date.now())return!0}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(Ub())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(cM){CO.warn(cM)}}getItem(e){if(!Ub())return null;try{let t=JSON.parse(localStorage.getItem(this.getRealKey(e)));return t&&t.expiresIn>=Date.now()?t.value:null}catch(Wb){CO.warn(Wb)}}setItem(e,t){if(Ub())try{let i={expiresIn:Date.now()+mk,value:t};this._queue.set(this.getRealKey(e),i)}catch(Jk){CO.warn(Jk)}}deleteItem(e){if(!Ub())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(Wb){return CO.warn(Wb),!1}}clear(){if(Ub())try{localStorage.clear()}catch(cM){CO.warn(cM)}}};DA(QA(),1);var bO={};kA(bO,{HTTPS_API:()=>FN,IS_GET_CAPABILITIES_SUPPORTED:()=>nP,IS_GET_SETTINGS_SUPPORTED:()=>rP,IS_SEI_SUPPORTED:()=>oP,IS_SPC_SUPPORTED:()=>ZN,basis:()=>dP,checkSystemRequirementsInternal:()=>VN,decodeSupportStatus:()=>LN,encodeSupportStatus:()=>MN,getBrowserInfo:()=>bN,getDisplayResolution:()=>GN,getOSName:()=>HN,isAddTransceiverSupported:()=>$N,isBrowserSupported:()=>kN,isGetReceiversSupported:()=>qN,isGetSendersSupported:()=>QN,isGetTransceiversSupported:()=>XN,isGetUserMediaSupported:()=>WN,isMediaDevicesSupported:()=>ON,isMediaSessionSupported:()=>cP,isMediaStreamTrackProcessorSupported:()=>wN,isReplaceTrackSupported:()=>tP,isScreenCaptureApiAvailable:()=>xN,isSelectedCandidatePair:()=>BN,isSetParametersSupported:()=>iP,isSmallStreamAPISupported:()=>KN,isSmallStreamSupported:()=>zN,isStopTransceiverSupported:()=>eP,isTRTCSupported:()=>UN,isUnifiedPlanDefault:()=>YN,isUsedInHttpProtocol:()=>PN,isWebAudioSupported:()=>JN,isWebCodecSupported:()=>sP,isWebCodecsSupported:()=>DN,isWebRTCSupported:()=>aP,isWebTransportSupported:()=>lP}),DA(QA(),1),DA(QA(),1);var kO="API_CALL_TIMEOUT",DO="SIGNAL_CHANNEL_RECONNECTION_FAILED",OO="SIGNAL_CHANNEL_SETUP_FAILED",NO="ERROR_MESSAGE",PO="DOWNLINK_RECONNECTION_FAILED",wO="EXCHANGE_SDP_FAILED",MO="UPLINK_RECONNECTION_FAILED",LO="INVALID_PURE_AUDIO",VO="INVALID_STREAMID",UO="INVALID_USER_DEFINE_RECORDID",xO="INVALID_USER_DEFINE_PUSH_ARGS",FO="INVALID_JOIN",BO="JOIN_ROOM_TIMEOUT",jO="JOIN_ROOM_FAILED",HO="REJOIN_ROOM_FAILED",GO="INVALID_DESTROY",WO="SUBSCRIBE_FAILED",JO="SWITCH_ROLE_TIMEOUT",KO="SWITCH_ROLE_FAILED",zO="INVALID_OPERATION_START_PUBLISH_CDN",YO="INVALID_OPERATION_STOP_PUBLISH_CDN",qO="START_PUBLISH_CDN_FAILED",QO="STOP_PUBLISH_CDN_FAILED",XO="REPEAT_JOIN",$O="CLIENT_DESTROYED",ZO="START_MIX_TRANSCODE_FAILED",eN="STOP_MIX_TRANSCODE_FAILED",tN="MIX_TRANSCODE_NOT_STARTED",iN="PLAY_FAILED",rN="NOT_SUPPORTED_HTTP",nN="NOT_SUPPORTED_WEBRTC",oN="NOT_SUPPORTED_H264ENCODE",aN="NOT_SUPPORTED_H264DECODE",sN="MICROPHONE_NOT_FOUND",cN="CAMERA_NOT_FOUND",lN="SIGNAL_RESPONSE_FAILED",dN="CATCH_HANDLER_ERROR",uN="CONNECTION_CLOSED",hN="SEI_DISABLED",pN="SEI_EMPTY",mN="SEI_OVERSIZE",_N="SEI_BEFORE_PUBLISH",fN="CALL_FREQUENCY_LIMIT",gN="CONNECTION_ABORTED",TN="API_CALL_ABORTED",SN={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),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(a," when calling ").concat(r,"(), received type: ").concat(jD(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),a="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(a," when calling ").concat(r,"(), received type: ").concat(jD(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:r,value:n}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(n,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,fnName:r,value:n}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(n,".")},API_CALL_TIMEOUT:e=>"".concat(e.commandDesc||e.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," })."),ERROR_MESSAGE(e){let t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>"exchange sdp failed ".concat(e.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>"'".concat(e,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:e=>"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(e){let{error:t,code:i}=e;return"Failed to join room - ".concat(t," code: ").concat(i)},REJOIN_ROOM_FAILED:e=>"reJoin room: ".concat(e.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:"no permission to publish() under live/".concat("audience",', please call switchRole("',"anchor",'") firstly before publish().'),INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>"duplicate ".concat(e," stream publishing, please unpublish your prev ").concat(e," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(e){let{message:t,userId:i,streamType:r}=e;return"failed to subscribe ".concat(i," ").concat(r," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as ".concat("anchor"," or ","audience","."),INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,"."),CLIENT_BANNED:e=>"client was banned because of ".concat(e.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>"startPublishCDNStream failed, errMsg: ".concat(e.message,"."),STOP_PUBLISH_CDN_FAILED:e=>"stopPublishCDNStream failed, errMsg: ".concat(e.message,"."),INVALID_STREAM_ID:e=>"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>"cannot replace ".concat(e.kind," track because stream has not ").concat(e.kind," track"),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 and publish streams, please use the https protocol.",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 and the configuration on TRTC.createStream.",CAMERA_NOT_FOUND:"no camera detected, please check your camera and the configuration on TRTC.createStream.",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 on ".concat(t,".on('").concat(i,"', handler), please check your code on 'handler'.")},API_NOT_EXIST(e){let{name:t}=e;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:e=>"[".concat(e,"] is calling client.join api or has already joined room, 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, to enable SEI: TRTC.createClient({ enableSEI: true })",SEI_EMPTY:"buffer cannot be empty",SEI_OVERSIZE:e=>"buffer size(".concat(e,") is over 1000 Bytes"),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,"()")};function vN(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}DA(QA(),1),DA(QA());var EN={AVOID_REPEATED_CALL:e=>"前一个 ".concat(e.name,"() 调用正在进行中, 请避免重复调用。"),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"调用 ".concat(r,"() 方法的时候 '").concat(t||i.name,"' 是必须的参数, 收到的值为: ").concat(n,"。")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"调用 ".concat(r,"() 方法的时候 '").concat(o,"' 必须是 ").concat(a," 类型, 收到的类型是: ").concat(vN(n),"。")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"调用 ".concat(r,"() 的时候 '").concat(t||i.name,"' 不能是 '").concat(n,"'。")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),a="".concat(i.instanceOf.name||i.instanceOf);return"调用 ".concat(r,"() 的时候 '").concat(o,"' 原型必须是 ").concat(a," , 收到的是: ").concat(vN(n),"。")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"调用 ".concat(r,"() 的时候 '").concat(t||i.name,"' 必须是 ").concat(i.values.join("|")," 的其中一种, 收到的是: ").concat(n,"。")},API_CALL_TIMEOUT:e=>"".concat(e.commandDesc||e.command," 超时。"),SIGNAL_CHANNEL_RECONNECTION_FAILED:"信令通道重连失败,请检查你的网络。",SIGNAL_CHANNEL_SETUP_FAILED:e=>"信令通道建立失败: (错误码: ".concat(e.errorCode,", 错误信息: ").concat(e.errorMsg," })。"),ERROR_MESSAGE(e){let t="".concat(e.type," 失败。");return e.message&&(t="".concat(t,": ").concat(e.message,"。")),t},SUBSCRIPTION_TIMEOUT:"远程服务器不响应订阅行为。",EXCHANGE_SDP_TIMEOUT:"交换 sdp 超时,请刷新网络重试。",DOWNLINK_RECONNECTION_FAILED:"下行重连失败,请检查您的网络并重新加入房间。",EXCHANGE_SDP_FAILED:e=>"交换 SDP 失败,原因 ".concat(e.errMsg,"。"),REPLACE_TRACK_INVALID:"LocalStream 发布之后才可以调用 replaceTrack。",UPDATE_OFFER_TIMEOUT:"更新 offer 超时,请刷新网络重试。",UPLINK_RECONNECTION_FAILED:"上行重连失败,请检查您的网络并重新推流。",INVALID_RECORDID:"recordId 必须是数字。",INVALID_PURE_AUDIO:"pureAudioPushMode 必须是数字1或2。",INVALID_STREAMID:"streamId 必须是 64 字节以内的字符串,并且不能为空。",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId 必须是包含 (a-zA-Z)、(0-9)、下划线和连字符的字符串字面量,64 个字节以内,且不为空。",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs 必须是 256 字节以内的字符串文字,并且不能为空。",INVALID_PROXY:"代理服务器 url 必须以“wss://”开头。",INVALID_JOIN:"join() 方法不能被重复调用。",INVALID_ROOMID_STRING:e=>"当 useStringRoomId 为 true 时,'".concat(e,"' 必须是合法字符串。"),INVALID_ROOMID_INTEGER:e=>"当 useStringRoomId 为 false 时,'".concat(e,"' 必须是合法整数在区间[1, 4294967294]。"),INVALID_SIGNAL_CHANNEL:"SignalChannel 还未初始化好。",JOIN_ROOM_TIMEOUT:"进房超时。",JOIN_ROOM_FAILED:e=>"进房失败,原因:".concat(e.error,"。"),REJOIN_ROOM_FAILED:e=>"重进房: ".concat(e.roomId," 失败,请检查网络状况。"),INVALID_LEAVE:"请在调用 destroy() 方法之前调用 leave()。",INVALID_PUBLISH:"请在调用 publish() 方法之前调用 join()。",INVALID_UNPUBLISH:"还没有被 publish。",INVALID_AUDIENCE:"在观众模式下不允许调用 publish(),请先切换成主播模式。",INVALID_INITIALIZE:"无法发布 stream,原因:localStream 未初始化、正在切换设备、已经调用 localStream.close() 关闭采集",INVALID_DUPLICATE_PUBLISHING:"重复发布,请先 unpublish 之后,再重新 publish。",INVALID_SUBSCRIBE_UNDEFINED:"stream 参数是 undefined 或者 null。",INVALID_SUBSCRIBE_LOCAL:"stream 参数不能为本地流。",INVALID_REMOTE_STREAM:"remoteStream 不存在,已被远端 client 取消发布。",SUBSCRIBE_FAILED(e){let t="订阅流失败,原因: ";return e.message.includes("REMOTE_STREAM_NOT_EXIST")?t+="远端用户已取消推流,无法订阅该远端流。":t+="".concat(e.message,"。"),t},INVALID_ROLE:"只有直播模式才可以进行角色切换。",INVALID_PARAMETER_SWITCH_ROLE:"role 只能设置为 anchor 或者 audience。",INVALID_OPERATION_SWITCH_ROLE:"请在使用 switchRole() 方法前先进房。",SWITCH_ROLE_TIMEOUT:"切换角色超时。",SWITCH_ROLE_FAILED:e=>"切换角色失败。错误码: ".concat(e.code," 错误信息: ").concat(e.message,"。"),CLIENT_BANNED:e=>"您被动退房了,原因为:".concat(e.reason,"。"),INVALID_OPERATION_START_PUBLISH_CDN:"请在进房前或者进房并成功发布本地流后调用 startPublishCDNStream() 方法。",INVALID_OPERATION_STOP_PUBLISH_CDN:"在调用 stopPublishCDNStream() 方法前需要先 startPublishCDNStream()。",INVALID_STREAM_ID:e=>"'".concat(e,"' 只能由大小写字母(a-zA-z), 数字(0-9), 连字符和下划线组成"),START_PUBLISH_CDN_FAILED:e=>"startPublishCDNStream 调用失败,错误信息: ".concat(e.message,"。"),STOP_PUBLISH_CDN_FAILED:e=>"stopPublishCDNStream 调用失败,错误信息: ".concat(e.message,"。"),START_MIX_TRANSCODE:"调用 startMixTranscode() 方法前需要先调用 join()。",STOP_MIX_TRANSCODE:"调用 stopMixTranscode 之前需要调用 startMixTranscode。",INVALID_AUDIO_VOLUME:"interval 必须是数字。",ENABLE_SMALL_STREAM_PUBLISHED:"发布 localStream 之后不允许开启小流。",DISABLE_SMALL_STREAM_PUBLISHED:"发布 localStream 之后不允许关闭小流。",NOT_SUPPORTED_SMALL_STREAM:"您的浏览器不支持开启小流。",INVALID_SMALL_STREAM_PROFILE:"小流参数不合法。",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream 不合法。",REMOTE_NOT_PUBLISH_SMALL_STREAM:"远端用户没有发布小流。",INVALID_SWITCH_DEVICE:"当前的流不可以调用 switchDevice。",INVALID_SWITCH_DEVICE_PUBLISHING:"发布本地流时不能切换设备。",INVALID_REPLACE_TRACK:"client.publish 接口尚未调用完成,请等其调用完成后再调用 replaceTrack 接口。",INVALID_INITIALIZE_LOCAL_STREAM:"本地流还没有初始化。",INVALID_ADD_TRACK_REPETITIVE:"前一个 addTrack 正在进行,请避免重复调用。",INVALID_ADD_TRACK_REMOVING:"track 在移动的时候不能添加新的 track。",INVALID_ADD_TRACK_PUBLISHING:"在发布本地流的时候不能添加新的 track。",INVALID_STREAM_INITIALIZED:"您的本地流还没有初始化。",INVALID_ADD_TRACK_NUMBER:"一条流最多有一个音频轨道和一个视频轨道。",INVALID_REMOVE_AUDIO_TRACK:"remove audio track 是不允许的。",INVALID_REMOVE_AUDIO_ADDING:"当一个 track 被 addTrack 的时候不能对流进行 removeTrack 操作。",INVALID_REMOVE_AUDIO_ON:"前一次调用的 removeTrack 正在进行中,请避免重复操作。",INVALID_REMOVE_TRACK_PUBLISHING:"发布流的过程中不能进行 removeTrack 操作。",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"被 remove 的 track 没有被发布。",INVALID_REMOVE_TRACK_NUMBER:"不支持移除唯一的视频轨道,请使用 replaceTrack 或者 muteVideo 方法。",INVALID_REPLACE_TRACK_NO_TRACK:e=>"LocalStream 没有 ".concat(e.kind," track,无法进行替换。"),START_MIX_TRANSCODE_FAILED:e=>"startMixTranscode 调用失败,错误信息: ".concat(e.message,"。"),STOP_MIX_TRANSCODE_FAILED:e=>"stopMixTranscode 调用失败,错误信息: ".concat(e.message,"。"),MIX_TRANSCODE_NOT_STARTED:"还没有开始 mixTranscode。",CANNOT_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r}=e;return"'当调用 ".concat(r,"() 函数时,要求参数 ").concat(t||i.name,"' 必须大于等于0")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' 应该是 (0, 30] 区间内的整数。",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' 应该是 [1, 8] 区间内的整数。",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' 应该是 [32, 192] 区间内的整数。",MIX_PARAMS_USER_Z_ORDER:e=>"'".concat(e,"' 是必传的,且要求为 [1 ,15] 之间的整数。"),MIX_PARAMS_NOT_SELF:"'config.mixUsers' 必须包含发起混流的用户信息。",MIX_PARAMS_USER_STREAM:"输出流的 'config.videoWidth' 和 'config.videoHeight' 应该容纳所有混入流。",INVALID_PLAY:"play() 被重复调用,请先 stop(),然后再重新调用 play。",INVALID_ELEMENT_ID:e=>{let{key:t,fnName:i}=e;return"在调用 ".concat(i,"() 时,document 对象中找不到 ").concat(t," 对应的元素,请检查。")},INVALID_ELEMENT_ID_TYPE:e=>{let{key:t,type:i,fnName:r}=e;return"在调用 ".concat(r,"() 方法时,").concat(t," 参数对应的 HTML 标签元素必须是 HTMLElement 实例,您传入的是:").concat(i,"。")},PLAY_FAILED:e=>"".concat(e.media," 播放被中断,浏览器异常原因:").concat(e.error.toString()),INVALID_USERID:"userId 不能为空格。",INVALID_CREATE_STREAM_SOURCE:"createStream() 生成 LocalStream 可以使用 audio & video 或 audioSource & videoSource 创建,但不能混合使用。",INVALID_CREATE_STREAM_SCREEN:"screen 和 video 不能同时为 true。",INVALID_CREATE_STREAM_AUDIO:"audio 和 screenAudio 不能同时为 true。",INVALID_CREATE_STREAM_SCREEN_AUDIO:"screen 为 true 时,不能设置 screenAudio。",NOT_SUPPORTED_HTTP:"由于浏览器安全策略限制,不支持在 http 协议下使用采集、推流等能力,请使用 https 协议。",NOT_SUPPORTED_WEBRTC:"当前浏览器或环境不完全支持 WebRTC 能力,请检查浏览器版本和页面访问协议是否满足条件。",NOT_SUPPORTED_PROFILE:"您的浏览器不支持 setVideoProfile 方法。请检查浏览器版本是否满足条件。",NOT_SUPPORTED_MEDIA:"当前浏览器或环境不支持 navigator.mediaDevices,请检查浏览器版本和页面访问协议是否满足条件。",NOT_SUPPORTED_H264ENCODE:"当前的设备或环境不支持 H264 编码,不支持 H264 格式进行推流。",NOT_SUPPORTED_H264DECODE:"当前的设备或环境不支持 H264 解码,不支持 H264 格式进行拉流。",NOT_SUPPORTED_TRACK:e=>"您的浏览器不支持 ".concat(e,"Track 方法。"),NOT_SUPPORTED_REPLACE_TRACK:"您的浏览器不支持 replaceTrack 方法,请使用 switchDevice 或者 addTrack。",NOT_SUPPORTED_CAPTURE:"您当前的浏览器不支持屏幕分享,请检查浏览器版本和页面访问协议是否满足条件。",NOT_SUPPORTED_AUX:"您当前的浏览器不支持推辅流,请检查浏览器版本是否满足条件(Chrome 69+, Safari 11+, Firefox 59+)。",MICROPHONE_NOT_FOUND:"未检测到麦克风,请检查您的麦克风和 TRTC.createStream 上的配置。",CAMERA_NOT_FOUND:"未检测到摄像头,请检查您的摄像头和 TRTC.createStream 上的配置。",CATCH_HANDLER_ERROR:e=>{let{name:t,event:i}=e;return" 在 ".concat(t,".on('").concat(i,"', handler) 事件中捕获到业务侧错误,请根据下述错误信息,检查您在 handler 中的业务代码。")},REPEAT_JOIN:e=>"用户 [".concat(e,"] 正在调用进房接口或者已经在房间内,请勿重复创建相同 userId 的 client 进入同一个房间。"),CLIENT_DESTROYED:e=>{let{funName:t}=e;return"client 已经被销毁,调用 ".concat(t,"() 方法失败。")},API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?"中断订阅用户 ".concat(e.userId," 的 ").concat(e.streamType," stream, 原因: 在您订阅过程中,远端用户 ").concat(e.userId," 取消了推流,您可以在下次远端推流时再进行订阅。"):"中断接口调用, 原因: ".concat(e.message,"。"),t},SEI_BEFORE_PUBLISH:"当前 client 没有推 localStream(主流,非屏幕分享流),无法调用 client.sendSEIMessage() 接口。"},yN={INVALID_USER_DEFINE_RECORDID:"TRTC.html#createClient",INVALID_PROXY:"Client.html#setProxyServer",INVALID_JOIN:"Client.html#join",INVALID_ROOMID_STRING:"Client.html#join",INVALID_ROOMID_INTEGER:"Client.html#join",INVALID_PUBLISH:"Client.html#publish",INVALID_UNPUBLISH:"Client.html#unpublish",INVALID_AUDIENCE:"Client.html#switchRole",INVALID_INITIALIZE:"Client.html#publish",INVALID_DUPLICATE_PUBLISHING:"Client.html#publish",INVALID_SUBSCRIBE_UNDEFINED:"Client.html#subscribe",INVALID_SUBSCRIBE_LOCAL:"Client.html#subscribe",INVALID_REMOTE_STREAM:"Client.html#subscribe",INVALID_ROLE:"Client.html#switchRole",INVALID_PARAMETER_SWITCH_ROLE:"Client.html#switchRole",INVALID_OPERATION_SWITCH_ROLE:"Client.html#switchRole",CLIENT_BANNED:"module-ClientEvent.html#.CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"Client.html#startPublishCDNStream",INVALID_OPERATION_STOP_PUBLISH_CDN:"Client.html#stopPublishCDNStream",START_MIX_TRANSCODE:"Client.html#startMixTranscode",STOP_MIX_TRANSCODE:"Client.html#stopMixTranscode",INVALID_AUDIO_VOLUME:"Client.html#enableAudioVolumeEvaluation",ENABLE_SMALL_STREAM_PUBLISHED:"Client.html#enableSmallStream",DISABLE_SMALL_STREAM_PUBLISHED:"Client.html#disableSmallStream",NOT_SUPPORTED_SMALL_STREAM:"tutorial-27-advanced-small-stream.html#h2-4",INVALID_SMALL_STREAM_PROFILE:"Client.html#setSmallStreamProfile",REMOTE_NOT_PUBLISH_SMALL_STREAM:"Client.html#setRemoteVideoStreamType",INVALID_SWITCH_DEVICE:"LocalStream.html#switchDevice",INVALID_SWITCH_DEVICE_PUBLISHING:"LocalStream.html#switchDevice",INVALID_REPLACE_TRACK:"LocalStream.html#replaceTrack",INVALID_INITIALIZE_LOCAL_STREAM:"LocalStream.html#replaceTrack",INVALID_ADD_TRACK_REPETITIVE:"LocalStream.html#addTrack",INVALID_ADD_TRACK_REMOVING:"LocalStream.html#addTrack",INVALID_ADD_TRACK_PUBLISHING:"LocalStream.html#addTrack",INVALID_STREAM_INITIALIZED:"LocalStream.html#addTrack",INVALID_ADD_TRACK_NUMBER:"LocalStream.html#addTrack",INVALID_REMOVE_AUDIO_TRACK:"LocalStream.html#removeTrack",INVALID_REMOVE_AUDIO_ADDING:"LocalStream.html#removeTrack",INVALID_REMOVE_AUDIO_ON:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_PUBLISHING:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NUMBER:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NOT_PUBLISHED:"LocalStream.html#removeTrack",START_MIX_TRANSCODE_TIMEOUT:"Client.html#startMixTranscode",START_MIX_TRANSCODE_FAILED:"Client.html#startMixTranscode",STOP_MIX_TRANSCODE_FAILED:"Client.html#stopMixTranscode",MIX_TRANSCODE_NOT_STARTED:"Client.html#startMixTranscode",MIX_PARAMS_VIDEO_FRAMERATE:"Client.html#startMixTranscode",MIX_PARAMS_VIDEO_GOP:"Client.html#startMixTranscode",MIX_PARAMS_AUDIO_BITRATE:"Client.html#startMixTranscode",MIX_PARAMS_USER_Z_ORDER:"Client.html#startMixTranscode",MIX_PARAMS_NOT_SELF:"Client.html#startMixTranscode",MIX_PARAMS_USER_STREAM:"Client.html#startMixTranscode",INVALID_PLAY:"Stream.html#play",PLAY_FAILED:"Stream.html#play",INVALID_USERID:"TRTC.html#createClient",INVALID_CREATE_STREAM_SOURCE:"TRTC.html#createStream",INVALID_CREATE_STREAM_SCREEN:"TRTC.html#createStream",INVALID_CREATE_STREAM_AUDIO:"TRTC.html#createStream",INVALID_CREATE_STREAM_SCREEN_AUDIO:"TRTC.html#createStream",NOT_SUPPORTED_HTTP:"tutorial-05-info-browser.html#h2-2",NOT_SUPPORTED_WEBRTC:"tutorial-05-info-browser.html",NOT_SUPPORTED_TRTC:"tutorial-05-info-browser.html",NOT_SUPPORTED_PROFILE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_MEDIA:"tutorial-05-info-browser.html",NOT_SUPPORTED_H264ENCODE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_H264DECODE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_TRACK:"LocalStream.html#addTrack",NOT_SUPPORTED_REPLACE_TRACK:"LocalStream.html#replaceTrack",NOT_SUPPORTED_CAPTURE:"tutorial-05-info-browser.html",MICROPHONE_NOT_FOUND:"TRTC.html#createStream",CAMERA_NOT_FOUND:"TRTC.html#createStream",SUBSCRIBE_FAILED:"Client.html#subscribe",API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?"Client.html#subscribe":"module-ErrorCode.html#.API_CALL_ABORTED",t}};"undefined"!=typeof window&&(window.TRTC_ERROR_INFO=EN,window.TRTC_ERROR_LINK=yN);var IN=(e,t)=>t?"".concat(ik,"/").concat(e,"/").concat(t):"".concat(ik,"/").concat(e,"/index.html");function CN(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",a="",s="";HD(SN[t])?o=SN[t](i):WD(SN[t])&&(o=SN[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=(()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let e=localStorage.getItem(ak);if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let i=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:r}}return{}})();r?s="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(HD(l[t])?s=l[t](i):WD(l[t])&&(s=l[t]));let d=o;return UD()&&(c&&c[t]&&(HD(c[t])?a=c[t](i):WD(c[t])&&(a=c[t])),a&&(d=n?"".concat(a,"\n请查看文档: ").concat(IN("zh-cn",s),"\n\n"):"".concat(a,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(IN("en",s),"\n")),d}var AN={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},RN=new Map([[DR,["Firefox",OR]],[MR,["Edg",LR]],[Cb,["Chrome",bb]],[kb,["Safari",Ob]],[jR,["TBS",HR]],[GR,["XWEB",WR]],[YR&&yR,["WeChat",qR]],[ZR,["QQ(Win)",eb]],[XR,["QQ(Mobile)",$R]],[QR,["QQ(Mobile X5)",$R]],[tb,["QQ(Mac)",ib]],[rb,["QQ(iPad)",nb]],[ub,["MI",hb]],[pb,["HW",_b]],[fb,["Samsung",gb]],[Tb,["OPPO",Sb]],[vb,["VIVO",Eb]],[PR,["EDGE",wR]],[UR,["SogouMobile",xR]],[FR,["Sogou",BR]]]);function bN(){let e=RN.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var kN=function(){return!(lb||PR||MR&&VR<80||DR&&NR<56)},DN=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},ON=function(){if(!navigator.mediaDevices)return CO.error(SN.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},NN=!1;function PN(){return"http:"===location.protocol&&!Vb&&!NN&&(NN=!0,CO.warn(CN({key:rN})),!0)}var wN=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},MN=function(){return wA(this,null,(function*(){if(AN.detail.isH264EncodeSupported||AN.detail.isVp8EncodeSupported)return{isH264EncodeSupported:AN.detail.isH264EncodeSupported,isVp8EncodeSupported:AN.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(),AN.detail.isH264EncodeSupported=t,AN.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:AN.detail.isH264EncodeSupported,isVp8EncodeSupported:AN.detail.isVp8EncodeSupported}}catch(Jk){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},LN=function(){return wA(this,null,(function*(){if(AN.detail.isH264DecodeSupported&&AN.detail.isVp8DecodeSupported)return{isH264DecodeSupported:AN.detail.isH264DecodeSupported,isVp8DecodeSupported:AN.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(Jk){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},VN=function(){return wA(this,null,(function*(){if(AN.result)return AN;let e=kN(),t=aP(),i=DN(),r=ON(),{isH264EncodeSupported:n,isVp8EncodeSupported:o}=yield MN(),{isH264DecodeSupported:a,isVp8DecodeSupported:s}=yield LN();return AN.result=e&&t&&r&&(n||o)&&(a||s),AN.detail.isBrowserSupported=e,AN.detail.isWebRTCSupported=t,AN.detail.isWebCodecsSupported=i,AN.detail.isMediaDevicesSupported=r,AN.detail.isScreenShareSupported=xN(),AN.detail.isSmallStreamSupported=zN(),AN.detail.isH264EncodeSupported=n,AN.detail.isVp8EncodeSupported=o,AN.detail.isH264DecodeSupported=a,AN.detail.isVp8DecodeSupported=s,AN.result||CO.error("".concat(navigator.userAgent," isBrowserSupported: ").concat(e,"isWebCodecsSupported: ").concat(i," isMediaSupported: ").concat(r," isH264EncodeSupported: ").concat(n," isVp8EncodeSupported: ").concat(o," isH264DecodeSupported: ").concat(a," isVp8DecodeSupported: ").concat(s," ")),AN}))},UN=function(){return AN.result},xN=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},FN=(e,t,i)=>{"http:"===location.protocol&&!Vb&&(e[t]=()=>{throw new cR({code:aR.INVALID_OPERATION,message:SN.NOT_SUPPORTED_HTTP})})},BN=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(KD(e.selected)&&!e.selected)},jN=new Map([[AR,"Android"],[CR,"iOS"],[ob,"Windows"],[ab,"MacOS"],[sb,"Linux"]]),HN=function(){return jN.get(!0)?jN.get(!0):"unknown"};function GN(){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 WN(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function JN(){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 KN(){return"captureStream"in HTMLCanvasElement.prototype}function zN(){return!(YR||CR||Rb&&Rb<63)&&!(!kN()||!KN())}var YN=function(){if(GD(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:Xk}),e.addTransceiver(Sk.AUDIO),t=!0}catch(Wb){}return null==e||e.close(),t};function qN(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function QN(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function XN(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function $N(){return"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var ZN=$N();function eP(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function tP(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function iP(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&QN()}var rP=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,nP=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,oP="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&yb()>=86,aP=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function sP(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return GD(window.AudioDecoder)||(e.AudioDecoder=!0),GD(window.AudioEncoder)||(e.AudioEncoder=!0),GD(window.VideoDecoder)||(e.VideoDecoder=!0),GD(window.VideoEncoder)||(e.VideoEncoder=!0),GD(window.ImageDecoder)||(e.ImageDecoder=!0),e}function cP(){return"mediaSession"in navigator&&!GD(navigator.mediaSession.setActionHandler)}function lP(){return!GD(window.WebTransport)}function dP(){let e={browser:"".concat(xb.name,"/").concat(xb.version),os:HN(),displayResolution:GN(),isScreenShareSupported:xN(),isWebRTCSupported:aP(),isGetUserMediaSupported:WN(),isWebAudioSupported:JN(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:sP(),isMediaSessionSupported:cP(),isWebTransportSupported:lP()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}DA(QA(),1);var uP=DA(XA(),1),hP=Symbol("instance"),pP=Symbol("abortCtrl"),mP=Symbol("cacheResult"),_P=class{constructor(e,t,i){NA(this,"oldState"),NA(this,"newState"),NA(this,"action"),NA(this,"error"),this.oldState=e,this.newState=t,this.action=i}toString(){return"".concat(this.action,"ing")}},fP=class extends Error{constructor(e,t,i){super(t),NA(this,"state"),NA(this,"message"),NA(this,"cause"),this.state=e,this.message=t,this.cause=i}},gP=new Map,TP=Object.getPrototypeOf(wA(void 0,null,(function*(){}))).constructor;function SP(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,n,o)=>{let a=i.action||n;if(!i.context){let i=gP.get(r)||[];gP.has(r)||gP.set(r,i),i.push({from:e,to:t,action:a})}let s=o.value;o.value=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return wA(this,null,(function*(){var r;let o=this;if(i.context&&(o=AP.get("function"==typeof i.context?i.context.call(this,...n):i.context)),o.state===t)return o[mP];let c=null;if(Array.isArray(e)?0==e.length?o[pP]&&(o[pP].aborted=!0):("string"!=typeof o.state||!e.includes(o.state))&&(c=new fP(o._state,"".concat(o.name," ").concat(a," to ").concat(t," failed: current state ").concat(o._state," not in from config"))):e!==o.state&&(c=new fP(o._state,"".concat(o.name," ").concat(a," to ").concat(t," failed: current state ").concat(o._state," not from ").concat(e))),c){if(!i.fail){if(i.ignoreError)return c;throw c}i.fail.call(this,c)}let l=o.state;EP.call(o,new _P(l,t,a));let d={aborted:!1};o[pP]=d;try{let e=s.apply(this,n);return o[mP]=e instanceof TP?yield e:e,d.aborted||(o[pP]=void 0,EP.call(o,t),null==(r=i.success)||r.call(this,o[mP])),o[mP]}catch(u){let e=u instanceof Error?u.message:String(u);if(EP.call(o,l,e),!i.fail){if(i.ignoreError)return u;throw u}i.fail.call(this,new fP(o._state,"action '".concat(a,"' failed :").concat(e),u instanceof Error?u:new Error(e)))}}))}}}var vP="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 EP(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(AP.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t})}var yP,IP,CP=class extends uP.default{constructor(e,t,i){super(),NA(this,"name"),NA(this,"groupName"),NA(this,"_state",CP.INIT),NA(this,yP),NA(this,IP),this.name=e,this.groupName=t,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let r=i[hP];r?this.name=r.name+"-"+r.count++:i[hP]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=gP.get(e)||[],i=new Set,r=[],n=[],o=new Set,a=Object.getPrototypeOf(e);gP.has(a)&&(a.stateDiagram.forEach((e=>i.add(e))),a.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 s=[...i];return Object.defineProperties(e,{stateDiagram:{value:s},allStates:{value:o}}),s}static get(e){let t;return"string"==typeof e?(t=CP.instances.get(e),t||CP.instances.set(e,t=new CP(e,void 0,Object.create(CP.prototype)))):(t=CP.instances2.get(e),t||CP.instances2.set(e,t=new CP(e.constructor.name,void 0,Object.create(CP.prototype)))),t}static getState(e){var t;return null==(t=CP.get(e))?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};vP(CP.UPDATEAFSM,AA({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){EP.call(this,e)}},AP=CP;yP=mP,IP=pP,NA(AP,"STATECHANGED","stateChanged"),NA(AP,"UPDATEAFSM","updateAFSM"),NA(AP,"INIT","[*]"),NA(AP,"ON","on"),NA(AP,"OFF","off"),NA(AP,"instances",new Map),NA(AP,"instances2",new WeakMap),DA(QA(),1),DA(QA(),1),DA(QA(),1),DA(QA(),1),DA(QA(),1);var RP=(null==window?void 0:window.requestIdleCallback)||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},bP=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},kP=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),DP=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ED,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=AA(e===vD?{delay:2e3,count:0,backgroundTask:!0}:e===TD?{delay:1e4,count:0}:e===SD?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),zD(t)&&(i=AA(AA({},i),t)),HD(e)&&(t=e,e=ED);let r=AA({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i);return this.taskMap.set(r.taskID,r),this[e](r),r.taskID}static interval(e){return e.intervalID=setInterval((()=>{e.callback(),e.loopCount+=1,this.isBreakLoop(e)}),e.delay)}static timeout(e){let t=()=>{if(e.callback(),e.loopCount+=1,!this.isBreakLoop(e))return e.timeoutID=setTimeout(t,e.delay)};return e.timeoutID=setTimeout(t,e.delay)}static ric(e){let t,i=iO(),r=()=>{if(t=iO()-i,t>=e.delay&&(i=iO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=RP(r,{timeout:e.delay})};return e.ricID=RP(r,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=iO(),r=()=>document.hidden&&e.backgroundTask?(t=iO()-i,i=iO(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(r,e.delay-Math.floor(t%e.delay))):(t=iO()-i,t>=e.delay&&(i=iO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),this.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(r));if(e.rafID=requestAnimationFrame(r),e.backgroundTask){let t=()=>{if(document.hidden){let t=iO()-i;t>=e.delay?r():e.timeoutID=setTimeout(r,e.delay-t)}};document.addEventListener("visibilitychange",t),e.onVisibilitychange=t,document.hidden&&t()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:t,timeoutID:i,rafID:r,ricID:n,onVisibilitychange:o}=this.taskMap.get(e);return t&&clearInterval(t),i&&clearTimeout(i),r&&kP(r),n&&bP(n),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.taskMap.has(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};DP.taskMap=new Map,DP.currentTaskID=1;var OP=DP;DA(QA(),1);var NP="connection-state-changed";Sk.SEI_MESSAGE;Sk.SEI_MESSAGE;var PP={LOADED_DATA:Sk.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed"};DA(QA(),1),DA(QA(),1);var wP=new class{constructor(){this._roomIdMap=new Map,"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:Hb,env:ck.QCLOUD,browserVersion:xb.name+xb.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){Vb||!CO.isAbleToUpload||this._configs.env===ck.QCLOUD&&this.uploadEventToKibana(RA(AA({},e),{result:"success"}))}logFailedEvent(e){if(Vb||!CO.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)||aR.UNKNOWN};this._configs.env===ck.QCLOUD&&this.uploadEventToKibana(RA(AA({},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:uR(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:Hb,log:t};r&&(n.errorInfo=r.message),this.sendRequest(RD(this._configs.sdkAppId,sk.LOG),n)}sendRequest(e,t){CO.isAbleToUpload?gO({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},MP="trtc_autoplay",LP="".concat(MP,"_mask"),VP="".concat(MP,"_wrapper"),UP="".concat(MP,"_header"),xP="".concat(MP,"_content"),FP="".concat(MP,"_action_wrapper"),BP="".concat(MP,"_question"),jP="".concat(MP,"_collapse"),HP="".concat(MP,"_action_confirm"),GP="".concat(MP,"_detail"),WP="#2473E8",JP="dialog",KP="".concat(JP,"-show"),zP="".concat(JP,"-1"),YP="".concat(JP,"-2"),qP=!1,QP=()=>!!document.querySelector(".".concat(VP)),XP="".concat(ik,"/").concat(UD()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),$P="<br><a href='".concat(XP,"' target='_blank'>").concat(UD()?"其他方案?":"Any other solution?","</a>"),ZP="".concat(UD()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat($P):"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($P)),ew=class{constructor(){if(NA(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),NA(this,"_dialogNode",null),NA(this,"_bodyPosition",""),NA(this,"_showDetail",!1),NA(this,"_isCollapseClicked",!1),NA(this,"_isQuestionClicked",!1),UD()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!qP){let e=document.createElement("style");e.innerHTML=".".concat(LP,"{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(LP," div:not(.").concat(FP,"){display:block !important;}.").concat(VP,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(VP," a{color:").concat(WP,";}.").concat(UP,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(xP,"{margin:8px 0;}.").concat(FP,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(jP,"{margin-right:auto;cursor:pointer}.").concat(BP,"{height:100%;line-height:16px;cursor:pointer;}.").concat(HP,"{margin-left:8px;color:#fff;background:").concat(WP,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(HP,":hover{opacity:0.9;}.").concat(jP,",.").concat(HP,",.").concat(xP,",.").concat(BP,"{font-size:14px;}@media screen and (max-width:750px){.").concat(VP,"{width:80vw;}}"),document.head.appendChild(e),qP=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(LP,"\"><div class='").concat(VP,"'><div class='").concat(UP,"'>").concat(location.host,"</div><div class='").concat(xP,"'>").concat(this.content,"</div><div class='").concat(GP,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(ZP,"</div><div class='").concat(FP,"'></div></div></div>").trim();let t=document.createElement("button");t.className=HP,t.innerText=UD()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=BP,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=jP,r.innerText="".concat(UD()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(FP));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){QP()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(VP)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",CO.info("show autoplay dialog"),wP.uploadEvent({log:KP}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){CO.warn("confirm clicked, try resume stream"),SO.emit(yO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(GP));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||wP.uploadEvent({log:zP}),this._isCollapseClicked=!0}onQuestionClick(){window.open(XP,"_blank"),this._isQuestionClicked||wP.uploadEvent({log:YP}),this._isQuestionClicked=!0}},tw={};kA(tw,{create:()=>rw,remove:()=>nw}),DA(QA(),1);var iw=new WeakMap;function rw(e,t){iw.has(e)||iw.set(e,[]);let i=iw.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 nw(e){let t=iw.get(e);t&&(t.forEach((e=>e())),iw.delete(e))}var ow=class extends AP{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,NA(this,"id"),NA(this,"element",null),NA(this,"container",null),NA(this,"mediaStream",new MediaStream),NA(this,"track"),NA(this,"url"),NA(this,"attr"),NA(this,"muted"),NA(this,"_log"),NA(this,"_pausedRetryCount"),NA(this,"_isElementPlayingFired",!1),NA(this,"_interval"),this.id=e.id,this._log=e.log,this.track=e.track,this.container=e.container,this.muted=e.muted,this._pausedRetryCount=dD,this._state="STOPPED",this.bindTrackEvents()}get isPlaying(){return"PLAYING"===this._state}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setTrack(e){if(e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(PP.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element))){let t=new MediaStream;t.addTrack(e),this.element.srcObject=t}}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))}setContainer(e){this.container=e,this.track&&this.element&&this.container&&this.container.appendChild(this.element)}play(){return wA(this,null,(function*(){if(this.element&&this.element.parentElement!==this.container&&this.container&&this.container.append(this.element),!this.isPlaying)try{this.bindAutoPlayEvent(),yield this.element.play()}catch(Wb){let t=CN({key:iN,data:{media:this.kind,error:Wb}});if(this.track&&!this.track.muted&&this._log.warn(Wb),t.includes("NotAllowedError"))throw new cR({code:aR.PLAY_NOT_ALLOWED,message:t})}}))}stop(){this.unbindEvents(),this._isElementPlayingFired=!1,this.element&&(this.container&&this.container.removeChild(this.element),this.element.srcObject=null,this.element=null),this.handleStopped(Sk.ENDED),this._interval>0&&OP.clearTask(this._interval)}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this.isPlaying?Promise.resolve():Mb?this.replay():this.play().catch((()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}setRect(e,t){this.element&&(this.element.style.width="".concat(e,"px"),this.element.style.height="".concat(t,"px"))}replay(){return this.stop(),this.play().catch((()=>{}))}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);rw(this.element,this.element).add(Sk.PLAYING,e).add(Sk.ENDED,e).add(Sk.PAUSE,e).add(Sk.ERROR,e).add(Sk.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==tw||tw.create(this.track,this.track).add(Sk.ENDED,e).add(Sk.MUTE,e).add(Sk.UNMUTE,e),this.track.readyState===Sk.ENDED&&this.handleTrackEvent({type:Sk.ENDED}),this.track.muted&&this.handleTrackEvent({type:Sk.MUTE})}}bindAutoPlayEvent(){SO.on(yO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&nw(this.track)}unbindEvents(){this.element&&nw(this.element),this.unbindTrackEvents(),SO.off(yO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){var t;switch(e.type){case Sk.PLAYING:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(Sk.PLAYING),this._interval&&(OP.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);let e=this.container&&document.getElementById(this.container.id);e||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id));let i=yb();this._pausedRetryCount>0&&(this.kind===Sk.VIDEO&&!QP()||this.kind===Sk.AUDIO&&(JD(i)&&i<=70||!e))&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--),CR&&(this._interval=OP.run(ED,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case Sk.ERROR:if(this.element&&this.element.error){let{code:e,message:t}=this.element.error;this._log.error("".concat(this.kind," player error observed. code: ").concat(e," message: ").concat(t," userAgent: ").concat(navigator.userAgent)),wP.uploadEvent({log:"stat-".concat(this.kind,"-").concat(zk.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error})}break;case Sk.LOADEDDATA:this.kind===Sk.VIDEO&&this.emit(PP.LOADED_DATA)}}handleTrackEvent(e){switch(e.type){case Sk.ENDED:this._log.info("".concat(this.kind," track is ended")),this.handleStopped(Sk.ENDED);break;case Sk.MUTE:this._log.info("".concat(this.kind," track is unable to provide media output")),this.handlePaused(Sk.MUTE);break;case Sk.UNMUTE:this._log.info("".concat(this.kind," track is able to provide media output")),this._isElementPlayingFired&&this.handlePlaying(Sk.UNMUTE)}}handlePlaying(e){this.emit(PP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(PP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(PP.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};OA([SP([],"PLAYING")],ow.prototype,"handlePlaying",1),OA([SP("PLAYING","PAUSED",{ignoreError:!0})],ow.prototype,"handlePaused",1),OA([SP([],"STOPPED")],ow.prototype,"handleStopped",1);var aw=class extends ow{constructor(e){super(e,Sk.VIDEO),NA(this,"mirror"),NA(this,"objectFit"),GD(e.mirror)||(this.mirror=e.mirror),GD(e.objectFit)||(this.objectFit=e.objectFit)}initializeElement(){var e;let t=document.createElement(Sk.VIDEO);if(this.track){let e=new MediaStream;e.addTrack(this.track),t.srcObject=e}t.muted=!0;let i="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");this.mirror&&(i+="transform: scaleX(-1);"),t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",i),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),null==(e=this.container)||e.appendChild(t),this.element=t,this.bindElementEvents()}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)}setMirror(e){this.element&&(this.element.style.transform=e?"scaleX(-1)":""),this.mirror=e}setObjectFit(e){this.element&&(this.element.style.objectFit="".concat(e)),this.objectFit=e}play(){return this.element||this.initializeElement(),super.play()}getVideoFrame(){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}};DA(QA(),1),DA(QA(),1),DA(QA(),1);var sw=!1,cw=class{constructor(e){NA(this,"context_"),NA(this,"blob_"),this.context_=e.context,this.blob_=new Blob(["class VolumeMeter extends AudioWorkletProcessor{constructor(){super();this.volume=0;this.intervalTime=200;this.tick=this.intervalTime;this.isStop=false;this.port.onmessage=event=>{const{data}=event;switch(data.name){case'setIntervalTime':this.intervalTime=data.intervalTime;break;case'stop':this.isStop=true;break}}}process(inputs){const input=inputs[0];if(this.isStop){return false}if(input.length>0){const firstChannel=input[0];let sum=0;let rms;for(let i=0;i<firstChannel.length;++i){sum+=firstChannel[i]*firstChannel[i]}rms=Math.sqrt(sum/firstChannel.length);this.volume=Math.max(rms,this.volume*0.95);this.tick-=firstChannel.length;if(this.tick<0){this.tick+=(this.intervalTime/1000)*sampleRate;this.port.postMessage({volume:this.volume})}}return true}}registerProcessor('volume-meter',VolumeMeter);"],{type:"application/javascript"}),this.addModuleToContext()}addModuleToContext(){return wA(this,null,(function*(){try{yield this.context_.audioWorklet.addModule(URL.createObjectURL(this.blob_)),CO.info("worklet addModule success"),SO.emit(yO.WORKLET_LOADED_SUCCESS),sw=!0}catch(cM){CO.info("worklet addModule catch error. ".concat(cM.message)),SO.emit(yO.WORKLET_LOADED_FAILED)}}))}get initWorkletSuccess(){return sw}};DA(QA(),1),"undefined"!=typeof window&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var lw,dw,uw=()=>{let e=new window.AudioContext,t=()=>{"suspended"===e.state?(e.resume(),document.addEventListener("click",t)):"interrupted"===e.state?e.resume():document.removeEventListener("click",t)};return document.addEventListener("click",t),e.onstatechange=()=>{CO.info("audioSource context state: ".concat(e.state)),t()},e},hw=0,pw=class{constructor(e){NA(this,"_volume"),NA(this,"_log"),NA(this,"_track"),NA(this,"_stream"),NA(this,"_audioCtx"),NA(this,"_destination"),NA(this,"_streamSource"),NA(this,"_scriptProcessorNode"),NA(this,"_audioWorkletNode"),NA(this,"_interval");let{track:t,log:i}=e;this._volume=0,this._log=i,this._track=t,lw||(lw=uw()),this._audioCtx=lw,this._destination=this._audioCtx.destination;let r=new MediaStream;r.addTrack(this._track),this._streamSource=this._audioCtx.createMediaStreamSource(r),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._interval=200,SO.on(yO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),eO?(SO.on(yO.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),SO.on(yO.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),this.preload()):this.initScriptProcessor(),hw+=1}preload(){dw?dw.initWorkletSuccess&&this.initAudioWorklet():dw=new cw({context:lw})}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(this._audioCtx,"volume-meter"),this._audioWorkletNode.port.onmessage=e=>{this._volume=e.data.volume||0},this._streamSource.connect(this._audioWorkletNode).connect(this._destination),this.handleAudioLevelInterval({interval:this._interval})}catch(cM){wP.logFailedEvent({userId:this._log.userId,eventType:zk.LOAD_WORKLET,error:cM}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=this._audioCtx.createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{let t=e.inputBuffer.getChannelData(0),i=0;for(let r=0;r<t.length;++r)i+=t[r]*t[r];this._volume=Math.sqrt(i/t.length)||0},this._streamSource.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._destination)}catch(cM){this._log.error("volumeMeter init script processor error: ".concat(cM))}}destroy(){this._streamSource&&this._streamSource.disconnect(),this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null,this._scriptProcessorNode.disconnect()),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null,this._audioWorkletNode.disconnect()),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._audioCtx=null,SO.off(yO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),SO.off(yO.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),SO.off(yO.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),hw>0&&(hw-=1),0===hw&&(null==lw||lw.close(),lw=null,dw=null)}resume(){null==lw||lw.resume()}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(e){var t;let{interval:i}=e;this._interval=i,null==(t=this._audioWorkletNode)||t.port.postMessage({name:"setIntervalTime",intervalTime:i})}},mw=class extends ow{constructor(e){super(e,Sk.AUDIO),NA(this,"_volumeMeter"),NA(this,"gainedTrack"),NA(this,"_outputDeviceId"),NA(this,"_volume",1),NA(this,"_loop",!1),e.gainedTrack&&(this.gainedTrack=e.gainedTrack),this._outputDeviceId=e.outputDeviceId,this.track&&this.initVolumeMeter(this.track)}setTrack(e){this.track!==e&&(this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),null!==e&&this.initVolumeMeter(e)),super.setTrack(e)}initVolumeMeter(e){this._volumeMeter=new pw({track:this.gainedTrack||e,log:this._log})}initializeElement(){if(("15.2"===Pb||"15.3"===Pb||"15.4"===Pb)&&this.muted)return void this._log.info("audioElement is muted.");let e=document.createElement(Sk.AUDIO);if(this.gainedTrack||this.track){let t=new MediaStream;t.addTrack(this.gainedTrack||this.track),e.srcObject=t}e.muted=this.muted,e.setAttribute("id","audio_".concat(this.id)),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,this.bindElementEvents()}play(){return wA(this,null,(function*(){this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),!this._volumeMeter&&this.track&&this.initVolumeMeter(this.track),this.setVolume(this._volume),yield PA(mw.prototype,this,"play").call(this)}))}stop(){this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),super.stop()}resume(){return wA(this,null,(function*(){yield PA(mw.prototype,this,"resume").call(this),this._volumeMeter&&this._volumeMeter.resume()}))}setSinkId(e){return wA(this,null,(function*(){this._outputDeviceId!==e&&(this.element&&(yield this.element.setSinkId(e)),this._outputDeviceId=e)}))}setVolume(e){!this.element||(this.element.volume=e,this._volume=e)}setLoop(e){!this.element||(this.element.loop=e,this._loop=e)}getAudioLevel(){var e;return(null==(e=this._volumeMeter)?void 0:e.getCalculatedVolume())||0}getInternalAudioLevel(){var e;return null==(e=this._volumeMeter)?void 0:e.getInternalAudioLevel()}},_w=class extends AP{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n}=e;var o;super(),NA(this,"id",AO()),NA(this,"userId"),NA(this,"isRemote"),NA(this,"mediaType"),NA(this,"room"),NA(this,"user"),NA(this,"_log"),NA(this,"isPlayCalled"),NA(this,"mediaTrack",null),NA(this,"mediaStream"),NA(this,"container",null),NA(this,"subVideoPlayerMap"),NA(this,"playerMuted",!1),NA(this,"abortCtrl"),NA(this,"audioOutputDeviceId"),NA(this,"audioVolume"),NA(this,"objectFit","cover"),NA(this,"mirror",!1),NA(this,"gain"),NA(this,"isScreen",!1),GD(t)||(this.userId=t),this.mediaType=r,this._log=CO.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(o=n||this.room)?void 0:o.userId,remoteUserId:this instanceof Uw?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof Uw}),this.initPlayer()}get log(){return this._log||CO}get kind(){return 1===this.mediaType?Sk.AUDIO:Sk.VIDEO}get muted(){return!(!this.mediaTrack||this.mediaTrack.enabled)}get strMediaType(){return 4===this.mediaType?Sk.VIDEO:2===this.mediaType?Sk.SCREEN:Sk.AUDIO}uninstallEvents(){}play(e,t){return wA(this,null,(function*(){let i=YD(e)?e[0]:e;if(this.isPlayCalled)return t&&!GD(t.muted)&&this.setPlayerMute(t.muted),t&&!GD(t.objectFit)&&(this.objectFit=t.objectFit),this.isScreen?this.mirror=!1:t&&!GD(t.mirror)&&(this.mirror=t.mirror),void(this.kind===Sk.VIDEO&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),YD(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if((!this.isRemote||this.kind===Sk.VIDEO)&&this.setPlayerMute(!0),t&&!GD(t.muted)&&this.setPlayerMute(t.muted),t&&!GD(t.objectFit)&&(this.objectFit=t.objectFit),this.isRemote||(this.mirror=!0),this.isScreen?this.mirror=!1:t&&!GD(t.mirror)&&(this.mirror=t.mirror),this.kind===Sk.VIDEO&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror)),this.isPlayCalled=!0,i&&(this.container=i,this.player.setContainer(i)),SO.emit(yO.PLAY_TRACK_START,{track:this}),this.mediaTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{yield this.player.play(),YD(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(r){throw this.handleAutoPlayFailed(),this.emit("error",r),r}}}))}playSubContainer(e,t){return wA(this,null,(function*(){if(!this.mediaTrack||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(),t.setContainer(null),null==(r=this.subVideoPlayerMap)||r.delete(i))}));for(let[r,n]of e.entries()){let e=this.subVideoPlayerMap.get(n);e?t&&(GD(t.mirror)||e.setMirror(t.mirror),GD(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new aw({id:this.userId||this.id,track:this.mediaTrack,container:n,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log.createChild({id:"vp-sub".concat(r+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let e of i)yield e.play()}))}initPlayer(){var e;this.log.info("create ".concat(this.kind,"Player")),this.kind===Sk.AUDIO?this.player=new mw({id:this.userId||this.id,track:this.mediaTrack,gainedTrack:null==(e=this.gain)?void 0:e.audioTrack,container:this.container||null,muted:this.playerMuted,outputDeviceId:this.audioOutputDeviceId,log:this.log}):(this.player=new aw({id:this.userId||this.id,track:this.mediaTrack,container:this.container||null,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log}),this.player.on(PP.LOADED_DATA,(()=>{SO.emit(yO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(PP.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))}))),this.player.on(PP.PLAYER_STATE_CHANGED,(e=>{SO.emit(yO.PLAYER_STATE_CHANGED,AA({track:this},e)),this.emit("player-state-changed",e)}))}setAudioOutput(e){return wA(this,null,(function*(){var t;this.audioOutputDeviceId=e,yield null==(t=this.player)?void 0:t.setSinkId(e)}))}setAudioVolume(e){var t;this.audioVolume=e,this.log.info("setAudioVolume to ".concat(e)),null==(t=this.player)||t.setVolume(e)}getAudioLevel(){var e;return(null==(e=this.player)?void 0:e.getAudioLevel())||0}getInternalAudioLevel(){var e;return(null==(e=this.player)?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(),this.player.setContainer(null)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop(),e.setContainer(null)})),this.container=null)}resume(){return wA(this,null,(function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume())}))}close(){var e;this.log.info("close"),this.isPlayCalled&&this.stop(),!this.isRemote&&(null==(e=this.mediaTrack)||e.stop(),this.mediaTrack=null,this.uninstallEvents())}setMute(e){return!!this.mediaTrack&&(this.mediaTrack.enabled=!e,this.emit(e?"mute":"unmute",this),SO.emit(e?yO.TRACK_MUTED:yO.TRACK_UNMUTED,{track:this}),!0)}setPlayerMute(e){this.playerMuted=e,this.player.setMuted(e)}setMediaStream(e){e!==this.mediaStream&&(this.mediaStream=e)}setMediaStreamTrack(e){this.mediaStream||(this.mediaStream=new MediaStream),this.mediaTrack&&this.mediaStream.removeTrack(this.mediaTrack);let t=this.mediaTrack;this.mediaTrack=e,this.mediaTrack&&(this.mediaTrack.enabled=!this.muted,this.mediaStream.addTrack(this.mediaTrack),this.isRemote||this.player.setTrack(this.mediaTrack)),this.updatePlayingState(!!e),this.emit("media-track-changed",this.mediaTrack,t)}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(!(!this.isPlayCalled||e&&!this.player.isStopped||!e&&this.player.isStopped)&&this.isPlayCalled&&this.player.isStopped===e){if(this.log.info("playing state updated, ".concat(e?"play":"stop"," ").concat(this.kind)),e&&this.player.isStopped){if(this instanceof Kw&&(!this.isSubscribed||!this.hasFlag))return;this.player.play().catch((()=>this.handleAutoPlayFailed()))}!e&&!this.player.isStopped&&this.player.stop()}}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new ew;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0),document.removeEventListener("touchstart",e,!0)}))};document.addEventListener("click",e,!0),document.addEventListener("touchstart",e,!0)}}};OA([SP([],AP.INIT)],_w.prototype,"close",1),DA(QA(),1),DA(QA(),1);var fw=Object.prototype.hasOwnProperty;var gw=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(xD(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(fw.call(e,t))return!1;return!0}return!1};DA(QA(),1);var Tw=DA(XA(),1),Sw=e=>t=>t.deviceId===e,vw=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";NA(this,"kind"),NA(this,"type"),NA(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())));t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(Sw(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");CO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(Sw(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");CO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},Ew=class extends Tw.EventEmitter{constructor(){super(),NA(this,"audioInputs",new vw(Sk.AUDIO)),NA(this,"videoInputs",new vw(Sk.VIDEO)),NA(this,"audioOutputs",new vw(Sk.AUDIO,"Output")),this.init(),navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",this.update.bind(this))}init(){Iw().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return wA(this,null,(function*(){let e=yield Iw();return this.audioInputs.update(e,this),this.videoInputs.update(e,this),this.audioOutputs.update(e,this),this}))}},yw=Yb||zb?null:new Ew;function Iw(){return wA(this,null,(function*(){return PN()||!ON()?[]:(yield navigator.mediaDevices.enumerateDevices()).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&&bw.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}))}function Cw(){return yw.update().then((e=>e.audioInputs.devices))}function Aw(){return yw.update().then((e=>e.videoInputs.devices))}function Rw(){return wA(this,null,(function*(){return yw.update().then((e=>e.audioOutputs.devices))}))}var bw=new Set;function kw(e,t){return wA(this,null,(function*(){let i=(yield Cw()).find((e=>e.deviceId===uD));return(null==i?void 0:i.groupId)===e&&i.label===t}))}var Dw=TO({retryFunction:function(e){return wA(this,null,(function*(){let t=function(e){return{audio:Nw(e),video:Pw(e)}}(e);CO.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[];t.audio&&(i=yield Cw(),CO.info("microphones: ".concat(fO(i,["label","deviceId"])))),t.video&&(r=yield Aw(),CO.info("cameras: ".concat(fO(r,["label","deviceId"]))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return nP&&e.getTracks().forEach((e=>{CO.info("".concat(e.kind," capabilities: ").concat(fO(e.getCapabilities(),yD)))})),e}catch(Jb){if("NotFoundError"===Jb.name){if(r&&0===r.length)throw new cR({code:aR.DEVICE_NOT_FOUND,message:CN({key:cN})});if(i&&0===i.length)throw new cR({code:aR.DEVICE_NOT_FOUND,message:CN({key:sN})})}throw new cR({code:aR.INITIALIZE_FAILED,name:Jb.name,message:Jb.message,constraint:Jb.constraint})}}))},settings:{retries:3,timeout:500},onError:(e,t,i,r)=>{"NotReadableError"===e.name?(r[0].video&&(r[0].maxResolution=!1,r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)),t()):i(e),r[0].microphoneId&&Ow(r[0].microphoneId,!1),r[0].cameraId&&Ow(r[0].cameraId,!0)},onRetrying:e=>{CO.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))}});function Ow(e,t){return wA(this,null,(function*(){let i=(t?yield Aw():yield Cw()).find((t=>t.deviceId===e));i&&HD(i.getCapabilities)&&CO.warn(fO(i.getCapabilities(),yD))}))}function Nw(e){if(!e.audio)return!1;let t={};return gw(e.microphoneId)||(t.deviceId=e.useExact?{exact:e.microphoneId}:e.microphoneId),JD(e.channelCount)&&e.channelCount>1&&(t.channelCount=e.channelCount),KD(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),KD(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),KD(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!gw(t)||t}function Pw(e){if(!e.video)return!1;let{maxResolution:t=!0}=e,i={};return e.cameraId?i.deviceId=e.useExact?{exact:e.cameraId}:e.cameraId:e.facingMode&&(i.facingMode=e.facingMode),e.width&&(i.width={ideal:e.width},t&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&(i.height.max=e.height)),DR&&ab&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!gw(i)||i}var ww=Dw;function Mw(e){return Vw(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return wA(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function Lw(e){return Vw(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return wA(this,null,(function*(){return e.call(this,t.apply(this,r))}))}))}function Vw(e){return function(t,i,r){return r.value=e(r.value,i),r}}DA(QA(),1);var Uw=class extends _w{constructor(e){super({mediaType:e}),NA(this,"isRemote",!1),NA(this,"deviceId"),NA(this,"groupId",""),NA(this,"label",""),NA(this,"_isRecapturing",!1),NA(this,"_lastRecaptureTime",0),NA(this,"_onMuteTimeoutId",-1),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}installTrackEvent(e){e.addEventListener(Sk.MUTE,this.onTrackMuted),e.addEventListener(Sk.UNMUTE,this.onTrackUnmuted),e.addEventListener(Sk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Sk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(Sk.MUTE,this.onTrackMuted),e.removeEventListener(Sk.UNMUTE,this.onTrackUnmuted),e.removeEventListener(Sk.ENDED,this.onTrackEnded)}setStateToCapture(){}capture(e){return wA(this,null,(function*(){try{let t;SO.emit(yO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(t=new MediaStream,t.addTrack(e.customSource)):t=yield ww(e);let i=t.getTracks()[0];return this.setMediaStream(t),this.setMediaStreamTrack(i),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),SO.emit(yO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this}),t}catch(Jk){throw SO.emit(yO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:Jk}),this.log.error("getUserMedia error observed ".concat(Jk)),Jk}}))}setMediaStreamTrack(e){this.state===AP.INIT&&this.setStateToCapture(),this.mediaTrack&&this.uninstallTrackEvent(this.mediaTrack),super.setMediaStreamTrack(e),e&&this.installTrackEvent(e)}setPublishStarting(e){this.room=e}setPublishStarted(){}setPublishStopped(e,t){}publish(e){this.room=e,this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),SO.emit(yO.LOCAL_TRACK_PUBLISHED,{track:this}),this.setPublishStarted()}unpublish(){this.room=void 0,2===this.mediaType&&(this.mediaType=4),SO.emit(yO.LOCAL_TRACK_UNPUBLISHED,{track:this}),this.setPublishStopped("api-call")}get isPublishing(){return"publish"===this.state}updateDeviceIdInUse(){return wA(this,null,(function*(){if(this.mediaTrack&&rP){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return wA(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!==uD||(yield kw(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),Iw().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!!bw.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!!bw.has(i)}(this.mediaTrack)||this._isRecapturing||e&&ab&&kb)}onTrackMuted(){if(this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<gD)return void setTimeout((()=>this.onTrackMuted()),gD);this._onMuteTimeoutId=setTimeout((()=>wA(this,null,(function*(){var e;(null==(e=this.mediaTrack)?void 0:e.muted)&&"visible"===document.visibilityState&&this.recapture(yield this.getRecoverCaptureDeviceId())}))),5e3)}}onTrackUnmuted(){this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return wA(this,null,(function*(){if(this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<gD)return void setTimeout((()=>this.onTrackEnded()),gD);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return wA(this,null,(function*(){var t;if(this._isRecapturing||!this.mediaTrack)return;let i;return this.log.warn("recapture trying"),null==(t=this.mediaTrack)||t.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now(),("audio"===this.kind?yield Cw():yield Aw()).find((t=>t.deviceId===e))&&(i=e),this.capture({deviceId:i,useExact:!0}).then((()=>{var e;return null==(e=this.room)?void 0:e.replaceTrack(this)})).then((()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e)}))}))}getRecoverCaptureDeviceId(){return wA(this,null,(function*(){let{deviceId:e}=this;if(e){let t=(xw.get(e)||0)+1;if(xw.set(e,t),t>=3){let i="video"===this.kind?(yield Aw()).find((e=>!xw.has(e.deviceId))):(yield Cw()).find((e=>!xw.has(e.deviceId)));i&&(this.log.warn("".concat(e," capture fail ").concat(t," times, change new ").concat(i.deviceId)),e=i.deviceId)}}return e}))}};OA([SP(AP.INIT,"capture")],Uw.prototype,"setStateToCapture",1),OA([SP("capture","publish_starting",{success(){this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"})}})],Uw.prototype,"setPublishStarting",1),OA([SP("publish_starting","publish",{success(){this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})}})],Uw.prototype,"setPublishStarted",1),OA([Vw((e=>function(t,i){let r=this.state.oldState||this.state;e.call(this,t,i),"capture"!==r&&this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"publish_starting"===this.state.oldState?"starting":"started",reason:t,error:i})})),SP(["publish","publish_starting"],"capture",{ignoreError:!0})],Uw.prototype,"setPublishStopped",1);var xw=new Map;SO.on(yO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&xw.delete(e.track.deviceId)})),DA(QA(),1);var Fw=class extends Uw{constructor(){super(1),NA(this,"mediaType",1),NA(this,"volume",0),NA(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),NA(this,"playerMuted",!0)}getAudioLevel(){return this.volume||super.getAudioLevel()}capture(){let{deviceId:e,useExact:t=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExact:t})}switchDevice(e){return wA(this,null,(function*(){if(this.mediaStream&&this.mediaTrack){if(this.deviceId===e){if(e!==uD)return;if(yield kw(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExact:!0}),this.room&&(yield this.room.replaceTrack(this)),SO.emit(yO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(Jk){throw this.log.error("switch microphone failed ".concat(Jk)),this.deviceId&&this.recapture(this.deviceId),Jk}}}))}listenDeviceChange(){yw&&!yw.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&yw.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return wA(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e)));let t=yield Cw();t[0]?this.recapture(t[0].deviceId):yw.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){return wA(this,null,(function*(){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}close(){yw.off("audioInputAdded",this.handleMicrophoneAdded,this),yw.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}};DA(QA(),1);var Bw=class extends Uw{constructor(){super(4),NA(this,"mediaType",4),NA(this,"profile",{width:640,height:480,frameRate:15,bitrate:900}),NA(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0}),NA(this,"small"),NA(this,"facingMode"),NA(this,"_canvas"),NA(this,"_canvasInterval"),NA(this,"canvasTrack")}capture(){let{deviceId:e,facingMode:t,useExact:i=!1,customSource:r}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExact:i,customSource:r})}genCanvasTrack(){if(this.canvasTrack||!this.mediaTrack)return;this.log.info("gen canvas track");let{width:e,height:t,frameRate:i}=this.mediaTrack.getSettings();this._canvas=document.createElement("canvas");let r=this._canvas.getContext("2d");e&&t&&(this._canvas.width=e,this._canvas.height=t),this._canvasInterval=OP.run(SD,(()=>{if(!this._canvas)return;if(this.mediaTrack){let e=this.mediaTrack.getSettings();(e.width!==this._canvas.width||e.height!==this._canvas.height)&&(this._canvas.width=e.width,this._canvas.height=e.height)}let e=this.player.getElement();e&&(null==r||r.drawImage(e,0,0,this._canvas.width,this._canvas.height))}),{fps:Math.max(15,i||0)});let n=this._canvas.captureStream();this.canvasTrack=n.getVideoTracks()[0]}destoryCanvasTrack(){this._canvasInterval&&(OP.clearTask(this._canvasInterval),this._canvasInterval=void 0,this._canvas=void 0,this.canvasTrack=void 0)}setPublishStarting(e){super.setPublishStarting(e),this.isNeedToResetVideoProfile(this.profile)&&this.setProfile(this.profile)}setMediaStreamTrack(e){super.setMediaStreamTrack(e),this.isNeedToResetVideoProfile(this.profile)&&this.setProfile(this.profile)}setProfile(e){var t;if(!e)return;let i=e.bitrate&&e.bitrate!==this.profile.bitrate;return this.isNeedToResetVideoProfile(e)&&(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),e.width=1920,e.height=1080),super.setProfile(e),null==(t=this.mediaTrack)?void 0:t.applyConstraints({width:e.width,height:e.height,frameRate:e.frameRate}).then((()=>{if(i&&this.room&&this.room.setBandWidth)return this.room.setBandWidth({bandwidth:e.bitrate,type:Sk.VIDEO,videoType:Sk.BIG})}))}isNeedToResetVideoProfile(e){return!!(this.room&&this.room.scheduleResult&&1!==(this.room.scheduleResult.trtcAutoConf||{})["2k4k"]&&!this.isScreen&&e.height*e.width>=3686400)}switchDevice(e){return wA(this,null,(function*(){try{if(!this.mediaStream||this.deviceId===e||this.facingMode===e)return;(e===Sk.FACING_MODE_USER||e===Sk.FACING_MODE_ENVIRONMENT)&&(this.facingMode=e,e=void 0),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExact:!0}),this.room&&(yield this.room.replaceTrack(this)),SO.emit(yO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(Jk){throw this.log.error("switch camera failed ".concat(Jk)),this.deviceId&&this.recapture(this.deviceId),Jk}}))}listenDeviceChange(){yw&&!yw.listeners("audioInputRemoved").includes(this.handleCameraRemoved)&&yw.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return wA(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e)));let t=yield Aw();t[0]?this.recapture(t[0].deviceId):yw.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return wA(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}close(){yw.off("videoInputAdded",this.handleCameraAdded,this),yw.off("videoInputRemoved",this.handleCameraRemoved,this),this.destoryCanvasTrack(),super.close()}};DA(QA(),1),DA(QA(),1);var jw=function(e){return wA(this,null,(function*(){let t=null,i=function(e){let t={systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:kb?{max:e.width}:{ideal:e.width,max:e.width},height:kb?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:"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);CO.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);if(e.systemAudio&&0===r.getAudioTracks().length&&(Cb&&Rb<74||kb||DR)&&CO.warn("Your browser not support capture system audio"),e.frameRate&&r.getVideoTracks()[0]&&r.getVideoTracks()[0].applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate}}).catch((e=>{CO.warn("screen applyConstraints failed: ".concat(e))})),e.audio){let i=function(e){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return GD(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);CO.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},Hw=class extends Bw{constructor(){super(),NA(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),NA(this,"objectFit","contain"),NA(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(){return wA(this,arguments,(function(){var e=this;let{systemAudio:t=!1,autoGainControl:i,echoCancellation:r,noiseSuppression:n,audioTrack:o,videoTrack:a}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){try{let s;return a||o?(s=new MediaStream,a&&s.addTrack(a),o&&s.addTrack(o)):s=yield jw({audio:!1,systemAudio:t,width:e.profile.width,height:e.profile.height,frameRate:e.profile.frameRate,autoGainControl:i,echoCancellation:r,noiseSuppression:n}),e.setMediaStream(s),e.setMediaStreamTrack(s.getVideoTracks()[0]),s}catch(s){throw e.log.error("getDisplayMedia error observed ".concat(s)),s instanceof cR?s:new cR({code:aR.INITIALIZE_FAILED,name:s.name,message:s.message})}}()}))}switchDevice(e){return wA(this,null,(function*(){throw new Error("Method not implemented.")}))}};DA(QA(),1);var Gw=class extends Fw{constructor(){super(),this._log.id="s-".concat(this._log.id)}setScreenAudioTrack(e,t){this.setMediaStream(t),this.setMediaStreamTrack(e)}};DA(QA(),1),DA(QA(),1);var Ww=class extends Uw{constructor(e){super(1),NA(this,"musicId"),NA(this,"mediaType",1),NA(this,"volume",0),NA(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),NA(this,"playerMuted",!1),NA(this,"_audioContext"),NA(this,"_destination"),NA(this,"_source",null),this.initAudioContext(),this._destination=this._audioContext.createMediaStreamDestination(),this._destination.channelCount=1,this.setPlayerMute(!1),this.player.initializeElement(),this.player.setUrl(e.url),KD(e.loop)&&this.player.setLoop(e.loop),JD(e.volume)&&this.player.setVolume(e.volume),e.id&&(this.musicId=e.id),this._source=this._audioContext.createMediaElementSource(this.player.getElement()),this._source.connect(this._destination),this.setMediaStream(this._destination.stream)}initAudioContext(){this._audioContext=uw(),"running"!==this._audioContext.state&&this._log.warn("local music ".concat(this.musicId," context state: ").concat(this._audioContext.state))}destroy(){var e,t;null==(e=this._source)||e.disconnect(),null==(t=this._destination)||t.disconnect(),this.player.stop(),this._audioContext.close().then((()=>{this._source=null,this._destination=null,this._audioContext=null}))}getStream(){var e;return(null==(e=this._destination)?void 0:e.stream)||null}setPosition(e){e<0&&e>this.duration()?CO.warn("Time beyond song duration."):this.player&&this.player.getElement()&&(this.player.getElement().currentTime=e)}getPosition(){var e;if(this.player)return(null==(e=this.player.getElement())?void 0:e.currentTime)||0}setVolume(e){e>1&&e<0?this.log.warn("volume is out of range"):this.player.setVolume(e)}getVolume(){let e=this.player.getElement();return(null==e?void 0:e.volume)||0}setPlayBackRate(e){if(e>8&&e<0)return void this.log.warn("rate is out of range");let t=this.player.getElement();t&&(t.playbackRate=e)}getPlayBackRate(){let e=this.player.getElement();return(null==e?void 0:e.playbackRate)||0}duration(){let e=this.player.getElement();return(null==e?void 0:e.duration)||0}loop(e){let t=this.player.getElement();return t&&KD(e)&&(t.loop=e),(null==t?void 0:t.loop)||!1}setOperation(e){"pause"===e&&this.player.pause(),"resume"===e&&this.player.resume(),"stop"===e&&this.player.stop()}listenDeviceChange(){}};DA(QA(),1),DA(QA(),1);var Jw=class extends _w{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,NA(this,"userId"),NA(this,"tinyId"),NA(this,"isRemote",!0),this.tinyId=t.tinyId,this.userId=t.userId}play(e,t){return this.hasFlag?super.play(e,t):(this.isPlayCalled=!0,this.container=e,e&&this.player.setContainer(e),Promise.resolve())}setMute(e){return this.hasFlag&&super.setMute(e)}setMediaStreamTrack(e){super.setMediaStreamTrack(e),this.mediaTrack&&this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.mediaTrack)}get isSubscribed(){return this.state===Jw.STATE_SUBSCRIBE}get streamType(){return 0==(2&this.mediaType)?"main":"auxiliary"}subscribe(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.mediaTrack&&this.hasFlag&&this.player.setTrack(this.mediaTrack),e&&SO.emit(yO.REMOTE_TRACK_SUBSCRIBED,{track:this})}unsubscribe(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.player.setTrack(null),e&&SO.emit(yO.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}onFlagChanged(){this.updatePlayingState(this.hasFlag),this.mediaTrack&&this.hasFlag&&this.player.setTrack(this.mediaTrack)}},Kw=Jw;NA(Kw,"STATE_SUBSCRIBE","subscribe"),OA([SP(AP.INIT,Kw.STATE_SUBSCRIBE,{success(){this.updatePlayingState(!0)}})],Kw.prototype,"subscribe",1),OA([SP(Kw.STATE_SUBSCRIBE,AP.INIT,{success(){this.updatePlayingState(!1)}})],Kw.prototype,"unsubscribe",1);var zw=class extends Kw{constructor(e,t){super(e,t,1),NA(this,"volume",0),NA(this,"mediaType",1),NA(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0})}getAudioLevel(){return this.volume||super.getAudioLevel()}get hasFlag(){return this.user.muteState.hasAudio&&!this.user.muteState.audioMuted}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}};DA(QA(),1);var Yw=class extends Kw{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),NA(this,"mediaType",4),NA(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0})}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}},qw=class extends Yw{constructor(e,t){super(e,t,2),NA(this,"mediaType",2),NA(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function Qw(){}DA(QA(),1),DA(QA()),DA(QA());var Xw=e=>e(),$w=1,Zw=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new nM(e,this,this.streamId++);return oM.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},eM=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=Qw,this.error=Qw,this.next=Qw,this.dispose=Qw,this.subscribe=Qw,this.doDefer()}subscribe(e){return e instanceof Zw?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(Xw),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}},tM=class extends eM{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)}};function iM(e,t,i){if("undefined"!=typeof __FASTRX_DEVTOOLS__){let r=Object.defineProperties(Object.setPrototypeOf(e,Zw.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}});oM.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof Zw&&oM.addSource(r,t)}return r}return e}function rM(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var nM=class extends tM{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{oM.defer(this.source,this.id)}))}next(e){oM.next(this.source,this.id,e),this.sink.next(e)}complete(){oM.complete(this.source,this.id),this.sink.complete()}error(e){oM.complete(this.source,this.id,e),this.sink.error(e)}},oM={addSource(e,t){rM("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){rM("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;rM("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){rM("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){rM("defer",{id:e.id,streamId:t})},pipe(e){rM("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){rM("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=$w++),rM("create",{name:e.toString(),id:e.id})}};DA(QA()),DA(QA());var aM=class extends eM{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()}};DA(QA()),DA(QA()),DA(QA());var sM,cM,lM=(sM=class extends tM{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},cM="map",function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>{if(e instanceof Zw){let i=iM((r=>{let n=new sM(r,...t);n.sourceId=i.id,n.subscribe(e)}),cM,arguments);return i.source=e,oM.pipe(i),i}return i=>e(new sM(i,...t))}});DA(QA()),function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];i.reduce(((e,t)=>t(e)),e)}(function(e){return iM((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}(250),lM((()=>performance.now())),function(){return e=>{let t=new aM(e);if(e instanceof Zw){let i=iM((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,oM.pipe(i),i}return iM(t.add.bind(t),"share",arguments)}}()),DA(QA(),1);var dM=new Map;function uM(e,t){let i=RA(AA({},t),{timestamp:dR()});dM.has(e)?dM.get(e).push(i):dM.set(e,[i])}SO.on(yO.JOIN_SUCCESS,(e=>{let{room:t}=e;uM(t.userId,{eventId:32788,eventDesc:"join room"})})),SO.on(yO.LEAVE_START,(e=>{let{room:t}=e;uM(t.userId,{eventId:32789,eventDesc:"leave room"})})),SO.on(yO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;t.room&&uM(t.room.userId,{eventId:t.kind===Sk.AUDIO?32769:32768,eventDesc:"publish ".concat(t.kind)})})),SO.on(yO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;t.room&&uM(t.room.userId,{eventId:t.kind===Sk.AUDIO?32771:32770,eventDesc:"unpublish ".concat(t.kind)})})),SO.on(yO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Sk.AUDIO?uM(t.room.userId,{eventId:t.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:t.isRemote?t.userId:void 0}):uM(t.room.userId,{eventId:t.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:t.isRemote?t.userId:void 0}))})),SO.on(yO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Sk.AUDIO?uM(t.room.userId,{eventId:t.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:t.isRemote?t.userId:void 0}):uM(t.room.userId,{eventId:t.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:t.isRemote?t.userId:void 0}))})),SO.on(yO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;1===t.mediaType&&uM(t.room.userId,{eventId:32777,eventDesc:"".concat(Sk.SUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&uM(t.room.userId,{eventId:32776,eventDesc:"".concat(Sk.SUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&uM(t.room.userId,{eventId:32803,eventDesc:"".concat(Sk.SUBSCRIBE," ").concat(Sk.SMALL_VIDEO),remoteUserId:t.userId})})),SO.on(yO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;1===t.mediaType&&uM(t.room.userId,{eventId:32779,eventDesc:"".concat(Sk.UNSUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&uM(t.room.userId,{eventId:32778,eventDesc:"".concat(Sk.UNSUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&uM(t.room.userId,{eventId:32804,eventDesc:"".concat(Sk.UNSUBSCRIBE," ").concat(Sk.SMALL_VIDEO),remoteUserId:t.userId})})),SO.on(yO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&uM(t.room.userId,{eventId:t.kind===Sk.VIDEO?32780:32781,eventDesc:"switch ".concat(t.kind===Sk.VIDEO?"camera":"microphone")})})),SO.on(yO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&uM(t.room.userId,{eventId:t.kind===Sk.VIDEO?32782:32783,eventDesc:"replace ".concat(t.kind)})})),SO.on(yO.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:r,prevState:n,state:o}=e;switch(o){case"CONNECTED":"RECONNECTING"===n?(t=32795,i="signal reconnected"):(t=32791,i="signal connected");break;case"DISCONNECTED":"RECONNECTING"===n?(t=32796,i="signal reconnect fail"):(t=32790,i="signal disconnected");break;case"RECONNECTING":t=32794,i="signal reconnecting"}t&&i&&uM(r.userId,{eventId:t,eventDesc:i})})),SO.on(yO.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:r,prevState:n,state:o,remoteUserId:a}=e,s=!!a,c=s?"downlink":"uplink";switch(o){case"CONNECTED":"RECONNECTING"===n?(t=s?32801:32798,i="".concat(c," reconnected")):(t=s?32793:32792,i="".concat(c," connected"));break;case"DISCONNECTED":"RECONNECTING"===n&&(t=s?32802:32799,i="".concat(c," reconnect fail"));break;case"RECONNECTING":t=s?32800:32797,i="".concat(c," reconnecting")}t&&i&&uM(r.userId,{eventId:t,eventDesc:i,remoteUserId:a})})),DA(QA(),1),DA(QA(),1);var hM=DA(XA(),1),pM=class extends hM.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,NA(this,"userMap",new Map),NA(this,"remotePublishedUserMap",new Map)}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,"]");GD(t)||(r+=":".concat(_D[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,a=sO(r,n),s=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(s){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:s,muteState:a,flag:r}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(a))),this.addUser({userId:n,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:sO(0,n),muteState:a,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};DA(QA(),1),DA(QA(),1);var mM=!0;DA(QA()),DA(QA());var _M={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"};DA(QA()),DA(QA());var fM,gM={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},TM=((fM=TM||{})[fM.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",fM[fM.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",fM[fM.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",fM[fM.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",fM[fM.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",fM[fM.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",fM[fM.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",fM[fM.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",fM[fM.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",fM[fM.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",fM[fM.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",fM[fM.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",fM[fM.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",fM[fM.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",fM[fM.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",fM[fM.MIX_PARAMS_USER_Z_ORDER=5015]="MIX_PARAMS_USER_Z_ORDER",fM[fM.MIX_PARAMS_VIDEO_FRAMERATE=5016]="MIX_PARAMS_VIDEO_FRAMERATE",fM[fM.MIX_PARAMS_VIDEO_GOP=5017]="MIX_PARAMS_VIDEO_GOP",fM[fM.MIX_PARAMS_AUDIO_BITRATE=5018]="MIX_PARAMS_AUDIO_BITRATE",fM[fM.MIX_PARAMS_NOT_SELF=5019]="MIX_PARAMS_NOT_SELF",fM[fM.MIX_PARAMS_USER_STREAM=5020]="MIX_PARAMS_USER_STREAM",fM[fM.INVALID_OPERATION=5100]="INVALID_OPERATION",fM[fM.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",fM[fM.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",fM[fM.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",fM[fM.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",fM[fM.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",fM[fM.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",fM[fM.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",fM[fM.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",fM[fM.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",fM[fM.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",fM[fM.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",fM[fM.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",fM[fM.DEVICE_ERROR=5300]="DEVICE_ERROR",fM[fM.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",fM[fM.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",fM[fM.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",fM[fM.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",fM[fM.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",fM[fM.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",fM[fM.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",fM[fM.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",fM[fM.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",fM[fM.SERVER_ERROR=5400]="SERVER_ERROR",fM[fM.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",fM[fM.OPERATION_FAILED=5500]="OPERATION_FAILED",fM[fM.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",fM[fM.REJOIN_FAILED=5502]="REJOIN_FAILED",fM[fM.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",fM[fM.OPERATION_ABORT=5998]="OPERATION_ABORT",fM[fM.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",fM);DA(QA());var SM={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),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(a," when calling ").concat(r,"(), received type: ").concat(jD(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),a="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(a," when calling ").concat(r,"(), received type: ").concat(jD(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 validate string when useStringRoomId is true.")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return"'".concat(t,"' must be an integer between [1, 4294967294] when useStringRoomId is false.")},INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},MIX_PARAMS_USER_Z_ORDER(e){let{key:t}=e;return"'".concat(t,"' is required and must be between 1 and 15.")},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_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_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,"'.")},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_HTTP:"http protocol does not support the ability to capture and publish streams, please use the https protocol.",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.",DEVICE_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got server exception").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:i=vM(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=vM(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=vM(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=vM(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=vM(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=vM(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=vM(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'.")},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.")},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 vM(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var EM=class extends Error{constructor(e){let t,{code:i,extraCode:r,message:n="",messageParams:o,fnName:a="",originError:s}=e;t=n||function(e){let t,{code:i,params:r,enableDocLink:n=!1}=e,o="",s=TM[i];try{t=SM[s]}catch(a){t=SM.UNKNOWN_ERROR}return HD(t)?o=t(r):WD(t)&&(o=t),n&&(o+=" doc:"),o}({code:r||i,params:AA({fnName:a,error:s},o)}),super(t),NA(this,"name","RtcError"),NA(this,"code"),NA(this,"extraCode"),NA(this,"functionName"),NA(this,"message"),NA(this,"originError"),this.name=TM[i],this.code=i,this.extraCode=r,this.functionName=a,this.originError=s,this.message=t}static convertFrom(e,t,i){let r=e;if(e instanceof cR){let{stack:n}=e,o={code:gM.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case aR.INVALID_PARAMETER:o.code=gM.INVALID_PARAMETER;break;case aR.INVALID_OPERATION:o.code=gM.INVALID_OPERATION;break;case aR.NOT_SUPPORTED:case aR.NOT_SUPPORTED_H264:o.code=gM.ENV_NOT_SUPPORTED,e.getCode()===aR.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(SN.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case aR.DEVICE_NOT_FOUND:case aR.DEVICE_AUTO_RECOVER_FAILED:o.code=gM.DEVICE_ERROR;break;case aR.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case aR.SERVER_TIMEOUT:case aR.SWITCH_ROLE_FAILED:o.code=gM.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case aR.API_CALL_ABORTED:o.code=gM.OPERATION_ABORT;break;case aR.INITIALIZE_FAILED:o.code=5300,o.extraCode=function(e){let t;switch(e){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}(e.name);break;case aR.UNKNOWN:break;default:o.code=gM.OPERATION_FAILED}r=new EM(o),n&&(r.stack+=n.substr(n.indexOf("\n")))}else r=new EM({code:gM.UNKNOWN_ERROR,fnName:t,originError:e});return r}};var yM=EM,IM={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},CM={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}}},AM={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(WD(e)){let r=document.getElementById(e);if(!r)throw new yM({code:gM.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}});if(!(r instanceof HTMLElement))throw new yM({code:gM.INVALID_PARAMETER,extraCode:5010,fnName:i,messageParams:{key:t,type:jD(r)}})}}},RM={name:"userId",required:!0,type:"string"},bM={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0,max:100},earMonitorVolume:{type:"number",min:0,max:100},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function kM(e,t,i,r){if(!/^[A-Za-z\d_-]*$/.test(e))throw new yM({code:gM.INVALID_PARAMETER,extraCode:5011,fnName:i,messageParams:{key:t}})}function DM(e,t,i,r){if(WD(e)){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new yM({code:gM.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}})}else if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new yM({code:gM.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}function OM(e,t){if(!e)throw new yM({code:gM.INVALID_OPERATION,extraCode:5101,fnName:t})}function NM(e,t,i){if(!e)throw new yM({code:gM.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var PM={type:"number",notLessThanZero:!0},wM={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 yM({code:gM.INVALID_OPERATION,extraCode:5104,fnName:i})},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:{required:!0,type:["string","number"],validate:DM},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"},streamId:{type:"string"},userDefineRecordId:{type:"string"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:AM,publish:{type:"boolean"},option:IM}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:RA(AA({},AM),{required:!1}),publish:{type:"boolean"},mute:{type:"boolean"},option:IM}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:bM}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:bM}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:AM,publish:{type:"boolean"},option:CM}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:AM,publish:{type:"boolean"},option:CM}},muteRemoteAudio:[RM,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[RM,{name:"volume",required:!0,type:"number",min:0,max:100}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:AM,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){OM(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(NM(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new yM({code:gM.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:RA(AA({},AM),{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){OM(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(NM(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new yM({code:gM.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&&GD(e.streamType))throw new yM({code:gM.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){OM(this._room.isJoined,i)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],startMixTranscode:{name:"config",required:!0,type:"object",properties:{mode:{type:"string",values:["preset-layout","manual"]},streamId:{type:"string",validate:kM},videoWidth:PM,videoHeight:PM,videoBitrate:RA(AA({},PM),{allowEmpty:!1}),videoFramerate:{type:"number",validate(e,t,i,r){if(e<=0||e>30)throw new yM({code:gM.INVALID_PARAMETER,extraCode:5016,fnName:i})}},videoGop:{type:"number",validate(e,t,i,r){if(e<1||e>8)throw new yM({code:gM.INVALID_PARAMETER,extraCode:5017,fnName:i})}},audioSampleRate:PM,audioBitrate:{type:"number",validate(e,t,i,r){if(e<32||e>192)throw new yM({code:gM.INVALID_PARAMETER,extraCode:5018,fnName:i})}},audioChannels:{type:"number",values:[1,2]},backgroundColor:{type:"number"},backgroundImage:{type:"string"},mixUsers:{required:!0,type:"array",arrayItem:{require:!0,type:"object",properties:{userId:{required:!0,type:"string"},roomId:{type:["string","number"],validate:DM},pureAudio:{type:"boolean"},width:PM,height:PM,locationX:PM,locationY:PM,zOrder:{type:"number"},streamType:{values:["main","sub"]},renderMode:{type:"number",values:[0,1,2,4]}}}}},validate(e,t,i,r){let n=0,o=0,{mixUsers:a}=e,s=[];if(a.forEach(((e,t)=>{if(s.push(e.userId),!e.pureAudio){if(!e.zOrder||e.zOrder<1||e>15)throw new yM({code:gM.INVALID_PARAMETER,extraCode:5015,fnName:i,messageParams:{key:"config.mixUsers[".concat(t,"].zOrder")}});e.width+e.locationX>n&&(n=e.width+e.locationX),e.height+e.locationY>o&&(o=e.height+e.locationY)}})),s.indexOf(this._room.userId)<0)throw new yM({code:gM.INVALID_PARAMETER,extraCode:5019,fnName:i});if(e.videoWidth<n||e.videoHeight<o)throw new yM({code:gM.INVALID_PARAMETER,extraCode:5020,fnName:i})}},startPublishCDNStream:{name:"options",required:!1,properties:{streamId:{type:"string",validate:kM},streamType:{values:["main","sub"]},appId:{type:"number",allowEmpty:!1},bizId:{type:"number",allowEmpty:!1},url:{type:"string",allowEmpty:!1}}},sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(e,t,i,r){if(!oP)throw new yM({code:gM.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new yM({code:gM.INVALID_OPERATION,messageParams:{key:hN}});if(e.byteLength>1e3)throw new yM({code:gM.INVALID_PARAMETER,messageParams:{key:mN,data:e.byteLength}});if(0===e.byteLength)throw new yM({code:gM.INVALID_PARAMETER,messageParams:{key:pN}});if(OM(this._room.isJoined,i),!this._room.isMainStreamPublished)throw new yM({code:gM.INVALID_PARAMETER,messageParams:{key:_N}})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}]},MM={TRTC:wM};DA(QA()),DA(QA(),1);var LM=class extends Error{};function VM(e,t){let i=[];return hO(i,e),hO(i,t),i}function UM(e){this._resolve=Promise.resolve(e)}function xM(e){this._reject=Promise.reject(e)}var FM=class{constructor(e,t){this.instance=e,this.group=t,NA(this,"started",!1),NA(this,"ops",[]),NA(this,"startSame",(()=>!0)),NA(this,"mergeUpdate",VM);let i=FM.instances.get(e);i?i.set(t,this):FM.instances.set(e,new Map([[t,this]]))}static get(e,t){let i=FM.instances.get(e);return i&&i.get(t)||new FM(e,t)}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 LM("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:UM,reject:xM};try{switch(this.state){case 1:if(0===e)throw new LM("already started");break;case 4:if(2===e)throw new LM("not started");break;default:return this.cacheOp(o)}}catch(cU){return Promise.reject(cU)}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 LM("already start");break;case 3:switch(e.type){case 2:throw new LM("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new LM("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new LM("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 LM("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new LM("start not allowed after update");case 0:throw new LM("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new LM("keep start")),new LM("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}},BM=FM;NA(BM,"instances",new WeakMap);var jM=(e,t)=>{if(t instanceof LM){let{stack:i}=t;t=new yM({code:gM.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function HM(e,t){return Vw(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),a=0;a<n;a++)o[a]=arguments[a];let s=BM.get(this,"string"==typeof e?e:e.call(this,...o));return t&&(s.startSame=t.bind(this)),s.action(0,i.bind(this),o).catch(jM.bind(null,r))}))}function GM(e,t){return Vw(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),a=0;a<n;a++)o[a]=arguments[a];let s=BM.get(this,"string"==typeof e?e:e.call(this,...o));return t&&(s.mergeUpdate=t.bind(this)),s.action(2,i.bind(this),o).catch(jM.bind(null,r))}))}function WM(e){return Vw(((t,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return BM.get(this,"string"==typeof e?e:e.call(this,...n)).action(3,t.bind(this),n).catch(jM.bind(null,i))}))}DA(QA());var JM={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",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",SEI_MESSAGE:"sei-message"};function KM(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function zM(e){return e===_M.QOS_PREFERENCE_CLEAR?"detail":e===_M.QOS_PREFERENCE_SMOOTH?"motion":""}DA(QA()),DA(QA(),1),DA(QA(),1);DA(QA(),1);var YM=new WeakMap;function qM(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Vw(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{XM.call(this,t,n,i,this._name)}catch(Jb){return Promise.reject(Jb)}return e.apply(this,n)}))}function QM(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Vw(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{XM.call(this,t,n,i,this._name)}catch(Jb){throw Jb}return e.apply(this,n)}))}function XM(e,t,i,r){if(YD(e))for(let n=0;n<e.length;n++)$M.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else $M.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function $M(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function a(e){return{code:gM.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(GD(i)){if(t.required)throw new yM(a(5001));if(GD(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),HD(t.type[r])&&i instanceof t.type[r]&&(e=!0),WD(t.type[r])&&jD(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new yM({code:gM.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>$D(e)?ZD(e):WD(e)?e:jD(e)))},value:i}})}else if(!GD(t.type)&&jD(i)!==t.type)throw new yM(a(5002));if(!1===t.allowEmpty){let e=JD(i)&&(0===i||Number.isNaN(i)),t=WD(i)&&""===i.trim();if(e||t)throw new yM(a(5003))}if(t.notLessThanZero&&JD(i)&&i<0)throw new yM(a(5006));if(!GD(t.min)&&JD(i)&&i<t.min)throw new yM(a(5007));if(!GD(t.max)&&JD(i)&&i>t.max)throw new yM(a(5008));if(WD(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new yM(a(5004))}else if(HD(t.instanceOf)&&!(i instanceof t.instanceOf))throw new yM(a(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new yM(a(5005));let{properties:s}=t;xD(s)&&zD(i)&&Object.keys(s).forEach((e=>{$M.call(this,{rule:s[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;xD(c)&&YD(i)&&i.forEach(((e,t)=>{$M.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 ZM(){return Vw(((e,t)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];let o=this._log||loggerManager;r.length>0?o.info("".concat(t,"() ").concat(JSON.stringify(r,((e,t)=>{if(t===r||e in r)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(jD(t)):(JSON.stringify(t),t)}catch(Kb){return"type:".concat(jD(t))}})))):o.info("".concat(t,"()"));try{let i=e.apply(this,r),n=iO();return XD(i)?i.then((e=>(o.info("".concat(t,"() success")),SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:t,cost:iO()-n}),e))).catch((e=>{throw e=yM.convertFrom.call(this,e,t,1===r.length?r[0]:r),o.error("".concat(t,"() failed ").concat(e)),SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:t,error:e}),e})):(SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:t,cost:iO()-n}),i)}catch(Jb){throw Jb=yM.convertFrom.call(this,Jb,t),o.error("".concat(t,"() failed ").concat(Jb)),SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:t,error:Jb}),Jb}}))}DA(QA()),DA(QA()),DA(QA());var eL=e=>Vw(((t,i)=>function(r,n){return wA(this,null,(function*(){let o=this._plugins.get(r);if(o)return XM.call(this,o.getValidateRule(e),[n],i,"TRTC"),t.call(this,o,n);this._log.warn("plugin ".concat(r," is not found"))}))})),tL=0,iL=new Set,rL=null;Gb("5.0.3");var nL=class extends rR.EventEmitter{constructor(e,t){super(),NA(this,"_room"),NA(this,"_eventListened",new Set),NA(this,"_localVideoTrack",null),NA(this,"_localAudioTrack",null),NA(this,"_localScreenTrack",null),NA(this,"_localScreenAudioTrack",null),NA(this,"_localVideoConfig",null),NA(this,"_localScreenConfig",null),NA(this,"_localAudioConfig",null),NA(this,"_remoteVideoConfigMap",new Map),NA(this,"_remoteAudioConfigMap",new Map),NA(this,"_remoteAudioMuteMap",new Map),NA(this,"_log",CO.createLogger({id:"t".concat(++tL)})),NA(this,"_plugins",new Map),this._room=new e(AA({logger:this._log,frameWorkType:nL.frameWorkType},t)),t.plugins&&t.plugins.forEach((e=>{let t=new e(function(e){return{room:e,innerEmitter:SO,constants:Bb,environment:pR,utils:hR,eventLogger:wP,log:e.getLogger(),clearStarted(t,i){let r=t.getAlias(),n=BM.instances.get(e);if(n)if(i){let e=n.get(r+i);if(!e)return;e.started=!1}else n.forEach(((e,t)=>{t.startsWith(r)&&(e.started=!1)}))}}}(this._room));this._plugins.set(t.getName(),t)})),this._room.on("audio-volume",(e=>{!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*this._localAudioTrack.getAudioLevel())}),this.emit(JM.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this.on(JM.REMOTE_AUDIO_UNAVAILABLE,(e=>{let{userId:t}=e;this._stopRemoteAudio({userId:t},!1).catch((()=>{}))})),this.on(JM.REMOTE_VIDEO_UNAVAILABLE,(e=>{let{userId:t,streamType:i}=e;this._stopRemoteVideo({userId:t,streamType:i},!1).catch((()=>{}))})),rw(yw,yw).add("audioInputAdded",(e=>{this.emit(JM.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(JM.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(JM.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(JM.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>wA(this,null,(function*(){if(this.emit(JM.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),rL&&rL.deviceId===hD){let e=(yield Rw()).find((e=>e.deviceId===hD));e&&rL.groupId!==e.groupId&&(rL=e,this.emit(JM.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>wA(this,null,(function*(){this.emit(JM.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Rw())[0];t&&rL&&(rL.deviceId===e.deviceId||rL.deviceId===hD&&rL.groupId!==t.groupId)&&(rL=t,this.emit(JM.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})))),((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(Jb){let i=CN({key:dN,data:{name:t,event:n[0]},addDocLink:!1});return CO.warn("".concat(i,"\n\n").concat(Jb.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,t){tL+=1,function(){var e;mM&&(mM=!1,5!==CO.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(rk,"index.html")),console.info("* Changelog: https://cloud.tencent.com/document/product/647/38958"),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),CO.info("TRTC Web SDK Version:",Hb),CO.info("UA:",navigator.userAgent),CO.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")))}();let i=new nL(e,t||{});return iL.add(i),rL?i.emit(JM.DEVICE_CHANGED,{type:"speaker",action:"active",device:rL}):Rw().then((e=>{e[0]&&(rL=e[0],i.emit(JM.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]}))})),i}enterRoom(e){return wA(this,null,(function*(){var t,i;let{scene:r="rtc",enableAutoPlayDialog:n=!0,autoReceiveAudio:o=!0,autoReceiveVideo:a=!0}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!WD(e.proxy)&&e.proxy.turnServer&&(null==(i=(t=this._room).setTurnServer)||i.call(t,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=n,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=a;let s={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,role:"audience"===e.role?21:20,roomId:0,strRoomId:"",businessInfo:e.businessInfo||null,streamId:e.streamId||null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};WD(e.roomId)?(s.strRoomId=e.roomId,this._room.useStringRoomId=!0):s.roomId=e.roomId,rw(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(JM.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(JM.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(JM.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(JM.ERROR,yM.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(JM.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this.emit(JM.NETWORK_QUALITY,e)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{rw(t,t).add("player-state-changed",(i=>{let r=RA(AA({},i),{userId:e.userId});t.kind===Sk.VIDEO&&(r.streamType=KM(t.streamType)),this.emit(t.kind===Sk.AUDIO?JM.AUDIO_PLAY_STATE_CHANGED:JM.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===aR.PLAY_NOT_ALLOWED&&this.emit(JM.AUTOPLAY_FAILED)}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{nw(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:r}=i;this._room.remotePublishedUserMap.get(r);let n=t.audioAvailable,o=t.videoAvailable,{audioAvailable:a,videoAvailable:s}=i;a||this._remoteAudioConfigMap.delete(r),s||this._remoteVideoConfigMap.delete("".concat(r,"_","main")),i.hasAuxiliary||this._remoteVideoConfigMap.delete("".concat(r,"_","sub")),n!==a&&this.emit(a?JM.REMOTE_AUDIO_AVAILABLE:JM.REMOTE_AUDIO_UNAVAILABLE,{userId:r}),o!==s&&this.emit(s?JM.REMOTE_VIDEO_AVAILABLE:JM.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"}),t.hasAuxiliary!==i.hasAuxiliary&&this.emit(i.hasAuxiliary?JM.REMOTE_VIDEO_AVAILABLE:JM.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"})})).add("firewall-restriction",(()=>{this.emit(JM.ERROR,new yM({code:gM.OPERATION_FAILED,extraCode:5501}))})).add("sei-message",(e=>{this.emit(JM.SEI_MESSAGE,e)})),this._handleReceiveMode(),yield this._room.join(s,r,nL.frameWorkType),this._checkTrackToPublish()}))}exitRoom(){return wA(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e){return wA(this,null,(function*(){yield this._room.switchRole(e),"anchor"===e&&this._checkTrackToPublish()}))}destroy(){nw(yw),this.removeAllListeners(),this._room.destroy(),iL.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare()}startLocalAudio(){return wA(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,option:r}=t,n=new Fw,o={},a={muted:!0};r&&(GD(r.microphoneId)?GD(r.audioTrack)||(o.customSource=r.audioTrack):o.deviceId=r.microphoneId,GD(r.captureVolume),GD(r.profile)||(WD(r.profile)?fk[r.profile]&&n.setProfile(fk[r.profile]):n.setProfile(r.profile)),JD(r.earMonitorVolume)&&(a.muted=!(r.earMonitorVolume>0),a.volume=r.earMonitorVolume),GD(r.echoCancellation)||(n.profile.echoCancellation=r.echoCancellation),GD(r.noiseSuppression)||(n.profile.noiseSuppression=r.noiseSuppression),GD(r.autoGainControl)||(n.profile.autoGainControl=r.autoGainControl)),n.on("5",(t=>{e.emit(JM.ERROR,new yM({code:gM.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),n.on("2",(t=>{e.emit(JM.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),n.on("4",(t=>{let i;t.error&&(i=yM.convertFrom(t.error)),e.emit(JM.PUBLISH_STATE_CHANGED,RA(AA({},t),{error:i}))})),yield n.capture(o),rw(n,n).add("player-state-changed",(t=>{e.emit(JM.AUDIO_PLAY_STATE_CHANGED,RA(AA({},t),{userId:""}))})),yield e._updateAudioPlayOption({playOption:a,track:n}),i&&e._room.isJoined&&e._room.publish(n).catch((()=>{})),e._localAudioTrack=n,e._localAudioConfig=RA(AA({},t),{publish:i})}()}))}updateLocalAudio(e){return wA(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):GD(r.audioTrack)||(this._localAudioTrack.setMediaStreamTrack(r.audioTrack),yield this._room.replaceTrack(this._localAudioTrack)),GD(r.captureVolume),GD(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume)),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),this._room.isJoined&&!GD(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),GD(i)||this._localAudioTrack.setMute(i),hO(this._localAudioConfig,e)}))}stopLocalAudio(){return wA(this,null,(function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),this._localAudioTrack.stop(),this._localAudioTrack.close(),nw(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return wA(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,option:n}=t,o=new Bw,a={},s={};if(n&&(n.cameraId?a.deviceId=n.cameraId:GD(n.useFrontCamera)?GD(n.videoTrack)||(a.customSource=n.videoTrack):a.facingMode=n.useFrontCamera?Sk.FACING_MODE_USER:Sk.FACING_MODE_ENVIRONMENT,GD(n.profile)||(WD(n.profile)?gk[n.profile]&&o.setProfile(gk[n.profile]):o.setProfile(n.profile)),GD(n.fillMode)||(s.objectFit=n.fillMode),GD(n.mirror)||(s.mirror=n.mirror),GD(n.small)||(zN()?WD(n.small)?o.small=gk[n.small]:o.small=n.small:e._log.warn("small stream is not supported"))),o.on("5",(t=>{e.emit(JM.ERROR,new yM({code:gM.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(JM.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=yM.convertFrom(t.error)),e.emit(JM.PUBLISH_STATE_CHANGED,RA(AA({},t),{error:i}))})),yield o.capture(a),(null==n?void 0:n.qosPreference)&&o.mediaTrack){let e=zM(n.qosPreference);o.mediaTrack.contentHint=e}rw(o,o).add("player-state-changed",(t=>{e.emit(JM.VIDEO_PLAY_STATE_CHANGED,RA(AA({},t),{userId:"",streamType:"main"}))})),yield e._updateVideoPlayOption({view:i,playOption:s,track:o}),r&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localVideoTrack=o,e._localVideoConfig=RA(AA({},t),{view:i,publish:r})}()}))}updateLocalVideo(e){return wA(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:r,option:n}=e,o={};if(n&&(n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):GD(n.useFrontCamera)?GD(n.videoTrack)||(this._localVideoTrack.setMediaStreamTrack(n.videoTrack),yield this._room.replaceTrack(this._localVideoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?Sk.FACING_MODE_USER:Sk.FACING_MODE_ENVIRONMENT),GD(n.profile)||(WD(n.profile)?gk[n.profile]&&this._localVideoTrack.setProfile(gk[n.profile]):this._localVideoTrack.setProfile(n.profile)),GD(n.fillMode)||(o.objectFit=n.fillMode),GD(n.mirror)||(o.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack)){let e=zM(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e}yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),this._room.isJoined&&!GD(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),GD(r)||this._localVideoTrack.setMute(r),hO(this._localVideoConfig,e)}))}stopLocalVideo(){return wA(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),nw(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return wA(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 Hw;o.on("4",(t=>{let i;t.error&&(i=yM.convertFrom(t.error)),e.emit(JM.PUBLISH_STATE_CHANGED,RA(AA({},t),{error:i}))}));let a=null;o.setMediaType(2);let s={},c={};n&&(GD(n.profile)||(WD(n.profile)?Tk[n.profile]&&o.setProfile(Tk[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(s.systemAudio=!0,s.echoCancellation=n.echoCancellation,s.noiseSuppression=n.noiseSuppression,s.autoGainControl=n.autoGainControl),GD(n.fillMode)||(c.objectFit=n.fillMode),n.videoTrack&&(s.videoTrack=n.videoTrack),n.audioTrack&&(s.audioTrack=n.audioTrack));let l=yield o.capture(s);if(null!=n&&n.qosPreference){let e=zM(n.qosPreference);o.mediaTrack.contentHint=e}if(o.mediaTrack.addEventListener(Sk.ENDED,(()=>{e._stopScreenShare(),e.emit(JM.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(a=new Gw,a.setScreenAudioTrack(l.getAudioTracks()[0],l)),rw(o,o).add("player-state-changed",(t=>{e.emit(JM.VIDEO_PLAY_STATE_CHANGED,RA(AA({},t),{userId:"",streamType:"sub"}))})),yield e._updateVideoPlayOption({view:i,playOption:c,track:o}),r&&e._room.isJoined){let t=[o];a&&t.push(a),e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=o,e._localScreenAudioTrack=a,e._localScreenConfig=RA(AA({},t),{view:i,publish:r})}()}))}updateScreenShare(e){return wA(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(GD(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let e=zM(r.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),this._room.isJoined&&!GD(i)&&(i&&!this._localScreenConfig.publish&&this._room.publish(this._localScreenTrack).catch((()=>{})),this._localScreenConfig.publish&&!i&&this._room.unpublish(this._localScreenTrack).catch((()=>{}))),hO(this._localScreenConfig,e)}))}stopScreenShare(){return wA(this,null,(function*(){return yield this._stopScreenShare()}))}startPlugin(e,t){return wA(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return wA(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return wA(this,null,(function*(){return e.stop(t)}))}startRemoteVideo(e){return wA(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 a=this._room.remotePublishedUserMap.get(i);if(!a)return;let s={},c="main"===r?a.remoteVideoTrack:a.remoteAuxiliaryTrack;n&&(GD(n.fillMode)||(s.objectFit=n.fillMode),GD(n.mirror)||(s.mirror=n.mirror),"main"===r&&!GD(n.small)&&this._room.changeType(n.small,c.user)),yield this._room.subscribe(c),yield this._updateVideoPlayOption({view:t,playOption:s,track:c}),this._remoteVideoConfigMap.set(o,e)}))}updateRemoteVideo(e){return wA(this,null,(function*(){let{view:t,userId:i,streamType:r,option:n}=e,o="".concat(i,"_").concat(r);if(!this._remoteVideoConfigMap.has(o)||!this._room.remotePublishedUserMap.has(i))return;let a={};n&&(GD(n.fillMode)||(a.objectFit=n.fillMode),GD(n.mirror)||(a.mirror=n.mirror));let s=null,c=this._room.remotePublishedUserMap.get(i);"main"===r&&(null==c?void 0:c.muteState.hasVideo)&&(s=c.remoteVideoTrack),"sub"===r&&(null==c?void 0:c.muteState.hasAuxiliary)&&(s=c.remoteAuxiliaryTrack);let l=this._remoteVideoConfigMap.get(o);s&&("main"===r&&n&&!GD(n.small)&&this._room.changeType(n.small,s.user),yield this._updateVideoPlayOption({view:t,playOption:a,track:s,prevConfig:l})),hO(l,e)}))}stopRemoteVideo(e){return wA(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return wA(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._remoteVideoConfigMap.delete("".concat(e.userId,"_").concat(e.streamType))}))}muteRemoteAudio(e,t){return wA(this,null,(function*(){if("*"===e)if(t)yield this._stopRemoteAudio({userId:e});else{let e=[...this._room.remotePublishedUserMap.values()];for(let t of e)t.muteState.hasAudio&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):yield this._startRemoteAudio({userId:e});this._remoteAudioMuteMap.set(e,t)}))}setRemoteAudioVolume(e,t){if("*"===e){let e=[...this._room.remotePublishedUserMap.values()];for(let i of e)this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);i&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}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)}startMixTranscode(e){let t=AA({},e);return t.mixUsers=e.mixUsers.map((e=>{let t=AA({},e);return GD(e.streamType)||(t.streamType=KM(e.streamType)),t})),this._room.startMixTranscode(t)}stopMixTranscode(){return this._room.stopMixTranscode()}startPublishCDNStream(e){let t=AA({},e);return GD(e.streamType)||(t.streamType=KM(e.streamType)),this._room.startPublishCDNStream(t)}stopPublishCDNStream(){return this._room.stopPublishCDNStream()}on(e,t,i){return super.on(e,t,i),this._eventListened.add(e),this}off(e,t,i){return"*"===e?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,i),this}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main"}=e;if(""===t){if("main"===i&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let e=this._room.remotePublishedUserMap.get(t);if(e)return"main"===i?e.remoteVideoTrack.mediaTrack:e.remoteAuxiliaryTrack.mediaTrack}return null}getAudioTrack(e){if(e){let t=this._room.remotePublishedUserMap.get(e);if(t)return t.remoteAudioTrack.mediaTrack}else if(this._localAudioTrack)return this._localAudioTrack.mediaTrack;return null}setCurrentSpeaker(e){var t;null==(t=this._localAudioTrack)||t.setAudioOutput(e),this._room.remotePublishedUserMap.forEach((t=>t.remoteAudioTrack.setAudioOutput(e)))}_startRemoteAudio(e){return wA(this,null,(function*(){let{userId:t,option:i}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let n={};i&&(GD(i.volume)||(n.volume=i.volume));let o=r.remoteAudioTrack;yield this._room.subscribe(o),yield this._updateAudioPlayOption({playOption:n,track:o}),this._remoteAudioConfigMap.set(t,e)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return wA(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._remoteAudioConfigMap.delete("".concat(e.userId))}))}_updateVideoPlayOption(e){return wA(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(GD(t)&&n&&n.view&&!aO(i)){let e;e=YD(n.view)?n.view:pO(n.view),e&&(yield r.play(e,i))}if(!GD(t)){let e;e=YD(t)?t:pO(t),e?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return wA(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:r}=e;return function*(){i.isPlayCalled||(yield i.play(null,t)),GD(t.muted)||i.setPlayerMute(t.muted),GD(t.volume)||i.setAudioVolume(t.volume/100)}()}))}_checkTrackToPublish(){var e,t,i;let r=[];if((null==(e=this._localAudioConfig)?void 0:e.publish)&&this._localAudioTrack&&r.push(this._localAudioTrack),(null==(t=this._localVideoConfig)?void 0:t.publish)&&this._localVideoTrack&&r.push(this._localVideoTrack),null!=(i=this._localScreenConfig)&&i.publish&&(this._localScreenTrack&&r.push(this._localScreenTrack),this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack)),0!==r.length)return this._room.publish(...r).catch((()=>{}))}_handleReceiveMode(){this._room.autoReceiveAudio&&rw(this,this).add(JM.REMOTE_AUDIO_AVAILABLE,(e=>wA(this,[e],(function(e){var t=this;let{userId:i}=e;return function*(){if(t._remoteAudioMuteMap.get("*")||t._remoteAudioMuteMap.get(i))return;let e=t._room.remotePublishedUserMap.get(i);e&&(yield t._room.subscribe(e.remoteAudioTrack).catch((()=>{})),yield t._updateAudioPlayOption({track:e.remoteAudioTrack}).catch((()=>{})),t._remoteAudioConfigMap.set(i,{userId:i}))}()})))),this._room.autoReceiveVideo&&rw(this,this).add(JM.REMOTE_VIDEO_AVAILABLE,(e=>{let{userId:t,streamType:i}=e,r=this._room.remotePublishedUserMap.get(t);r&&("main"===i?this._room.subscribe(r.remoteVideoTrack).catch((()=>{})):"sub"===i&&this._room.subscribe(r.remoteAuxiliaryTrack).catch((()=>{})))}))}_exitRoom(){return wA(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),[...this._remoteAudioConfigMap.keys()].forEach((e=>{this._stopRemoteAudio({userId:e}).catch()})),[...this._remoteVideoConfigMap.keys()].forEach((e=>{let t=e.includes("main")?"main":"sub",i=e.split("_".concat(t))[0];i&&this._stopRemoteVideo({userId:i,streamType:t}).catch()})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach((e=>{nw(e.remoteAudioTrack),nw(e.remoteVideoTrack),nw(e.remoteAuxiliaryTrack)})),nw(this)}))}_stopScreenShare(){return wA(this,null,(function*(){var e,t,i;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(),null==(t=this._localScreenAudioTrack)||t.stop(),null==(i=this._localScreenAudioTrack)||i.close(),nw(this._localScreenTrack),this._localScreenTrack=null,this._localScreenAudioTrack=null,this._localScreenConfig=null}}))}sendSEIMessage(e,t){this._room.sendSEI(e,t||{seiPayloadType:243})}static setLogLevel(e,t){CO.setLogLevel(e),GD(t)||(t?CO.enableUploadLog():CO.disableUploadLog())}static isSupported(){return VN()}static getCameraList(){return Aw()}static getMicrophoneList(){return Cw()}static getSpeakerList(){return Rw()}static setCurrentSpeaker(e){return wA(this,null,(function*(){(yield Rw()).forEach((t=>{t.deviceId===e&&(iL.forEach((i=>{i.setCurrentSpeaker(e),i.emit(JM.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),rL=t)}))}))}},oL=nL;NA(oL,"_loggerManager",CO),NA(oL,"EVENT",JM),NA(oL,"ERROR_CODE",gM),NA(oL,"TYPE",_M),NA(oL,"frameWorkType",30),OA([qM(MM.TRTC.enterRoom),HM("room",((e,t)=>{let[i]=e,[r]=t;return i.roomId===r.roomId&&i.userId===r.userId&&i.sdkAppId===r.sdkAppId})),Vw((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t).catch((e=>{throw nw(this),e}))})),ZM()],oL.prototype,"enterRoom",1),OA([ZM()],oL.prototype,"exitRoom",1),OA([qM(MM.TRTC.switchRole),GM("room",((e,t)=>t)),ZM()],oL.prototype,"switchRole",1),OA([ZM()],oL.prototype,"destroy",1),OA([qM(MM.TRTC.startLocalAudio),HM("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)})),ZM()],oL.prototype,"startLocalAudio",1),OA([qM(MM.TRTC.updateLocalAudio),GM("audio"),ZM()],oL.prototype,"updateLocalAudio",1),OA([WM("audio"),ZM()],oL.prototype,"stopLocalAudio",1),OA([qM(MM.TRTC.startLocalVideo),HM("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)})),ZM()],oL.prototype,"startLocalVideo",1),OA([qM(MM.TRTC.updateLocalVideo),GM("video"),ZM()],oL.prototype,"updateLocalVideo",1),OA([WM("video"),ZM()],oL.prototype,"stopLocalVideo",1),OA([qM(MM.TRTC.startScreenShare),HM("screen",(()=>!0)),ZM()],oL.prototype,"startScreenShare",1),OA([qM(MM.TRTC.updateScreenShare),GM("screen"),ZM()],oL.prototype,"updateScreenShare",1),OA([ZM()],oL.prototype,"stopScreenShare",1),OA([eL("start"),HM(((e,t)=>e.getAlias()+e.getGroup(t)))],oL.prototype,"startPlugin",1),OA([eL("update"),GM(((e,t)=>e.getAlias()+e.getGroup(t)))],oL.prototype,"updatePlugin",1),OA([eL("stop"),WM(((e,t)=>e.getAlias()+e.getGroup(t)))],oL.prototype,"stopPlugin",1),OA([qM(MM.TRTC.startRemoteVideo),HM((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),ZM()],oL.prototype,"startRemoteVideo",1),OA([qM(MM.TRTC.updateRemoteVideo),GM((e=>"v".concat(e.userId).concat(e.streamType))),ZM()],oL.prototype,"updateRemoteVideo",1),OA([qM(MM.TRTC.stopRemoteVideo),Vw((e=>function(t){return wA(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)}))})),ZM()],oL.prototype,"stopRemoteVideo",1),OA([WM((e=>"v".concat(e.userId).concat(e.streamType)))],oL.prototype,"_stopRemoteVideo",1),OA([qM(...MM.TRTC.muteRemoteAudio),ZM()],oL.prototype,"muteRemoteAudio",1),OA([QM(...MM.TRTC.setRemoteAudioVolume),function(e,t){return Vw(((i,r)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];var a,s;let c=null==(a=YM.get(this))?void 0:a.get(t(...n));c&&c>0&&clearTimeout(c);let l=window.setTimeout((()=>{i.apply(this,n)}),e);YM.has(this)?null==(s=YM.get(this))||s.set(t(...n),l):YM.set(this,new Map([[t(...n),l]]))}))}(200,(e=>e)),ZM()],oL.prototype,"setRemoteAudioVolume",1),OA([QM(...MM.TRTC.enableAudioVolumeEvaluation)],oL.prototype,"enableAudioVolumeEvaluation",1),OA([qM(MM.TRTC.startMixTranscode)],oL.prototype,"startMixTranscode",1),OA([HM((e=>"a".concat(e.userId)),(()=>!0))],oL.prototype,"_startRemoteAudio",1),OA([Vw((e=>function(t){return wA(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(RA(AA({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),WM((e=>"a".concat(e.userId)))],oL.prototype,"_stopRemoteAudio",1),OA([WM("room")],oL.prototype,"_exitRoom",1),OA([WM("screen")],oL.prototype,"_stopScreenShare",1),OA([qM(MM.TRTC.sendSEIMessage),function(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return Vw(((e,n)=>{let o=new Map;return SO.on(yO.ROOM_DESTROY,(e=>{let{room:t}=e;return o.delete(t)})),function(){let a=o.get(this);for(var s=arguments.length,c=new Array(s),l=0;l<s;l++)c[l]=arguments[l];if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),0===a.timestamp?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),r&&(a.totalSizeInSecond+=r(...c)),0!==a.timestamp&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=t||a.totalSizeInSecond>i))throw new cR({code:aR.INVALID_OPERATION,message:CN({key:fN,data:{isTimes:a.callCountInSecond>=t,isSize:a.totalSizeInSecond>i,name:n,timesInSecond:t,maxSizeInSecond:i}})});a.callCountInSecond++,e.call(this,...c)}}))}({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}})],oL.prototype,"sendSEIMessage",1),OA([qM(MM.TRTC.create)],oL,"_create",1);var aL=oL;DA(QA()),DA(QA(),1);function sL(){return wA(this,null,(function*(){let e,t;try{let t=yield Cw();e=t&&t.length}catch(u){}try{let e=yield Aw();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:a}=this.checkSystemResult.detail,s=bO.basis(),c={webRTC:s.isWebRTCSupported,getUserMedia:s.isGetUserMediaSupported,webSocket:s.isWebSocketsSupported,screenShare:s.isScreenShareSupported,webAudio:s.isWebAudioSupported,h264Encode:r,h264Decode:o,vp8Encode:n,vp8Decode:a},l={browser:s.browser,os:s.os,trtc:c,devices:i},d={isWebCodecSupported:s.isWebCodecSupported,isMediaSessionSupported:s.isMediaSessionSupported,isWebTransportSupported:s.isWebTransportSupported};wP.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),wP.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}DA(QA(),1);DA(QA());var cL=DA(XA());DA(QA());var lL="1",dL="5",uL="2",hL="3",pL="4",mL="DISCONNECTED",_L="CONNECTING",fL="CONNECTED",gL={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,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},TL=[gL.UPDATE_REMOTE_MUTE_STAT,gL.UPLINK_NETWORK_STATS,gL.USER_LIST_RES,gL.MUTE_RESULT],SL={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",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"},vL="publish_change",EL="join",yL="leave",IL="quality_report",CL="mute_uplink",AL="publish",RL="publish_state_change",bL="unpublish",kL="subscribe",DL="unsubscribe",OL="subscribe_change",NL="start_publishing",PL="stop_publishing",wL="start_push_user_cdn",ML="stop_push_user_cdn",LL="start_mcu_mix",VL="stop_mcu_mix",UL="get_user_list",xL="change_role",FL="update_constraint_config",BL="rebuild_pc",jL="join/v2",HL="publish/v2",GL="subscribe/v3";DA(QA()),DA(QA());var WL=DA(XA());DA(QA()),DA(QA(),1);var JL=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}},KL=class{constructor(e,t,i){this._connection=e,this._log=t,this._isUplink=i,NA(this,"_seiMessageList",[]),NA(this,"_seiPayloadType",243),NA(this,"_mainVideoSenderOrReceiver",null),NA(this,"_mainVideoAbortController",null),NA(this,"_abortMap",new Map),NA(this,"onSEIMessage")}get isRunning(){return!!this._mainVideoAbortController}start(e){this._mainVideoSenderOrReceiver=e;let t=e.createEncodedStreams(),i=t.readable,r=t.writable,n=new TransformStream({transform:this._isUplink?this.encodeVideoFrame.bind(this):this.decodeVideoFrame.bind(this)});this._mainVideoAbortController=new AbortController,i.pipeThrough(n).pipeTo(r,this._mainVideoAbortController).catch((()=>{}))}restart(e){this.stop(),this.start(e)}stop(){var e;null==(e=this._mainVideoAbortController)||e.abort(),this._mainVideoAbortController=null}destroy(){this.stop(),this._abortMap.forEach((e=>e.abort())),this._abortMap.clear(),this._log=null,this.onSEIMessage=null,this._mainVideoSenderOrReceiver=null,this._connection=null}handleEncodedStreams(){try{let e=this._connection.getPeerConnection();this.clearUnusedSenderOrReceiver(e),this._isUplink?e.getSenders().forEach(((e,t)=>{if(1===t){if(e===this._mainVideoSenderOrReceiver)return;this.isRunning?this.restart(e):this.start(e)}else{if(this._abortMap.has(e))return;this.pipeSenderOrReceiver(e)}})):e.getReceivers().forEach(((e,t)=>{var i;this._abortMap.has(e)||e===this._mainVideoSenderOrReceiver||(1===t&&(null==(i=e.track)?void 0:i.kind)===Sk.VIDEO?this.isRunning?this.restart(e):this.start(e):this.pipeSenderOrReceiver(e))}))}catch(cM){this._log.warn(cM)}}pipeSenderOrReceiver(e){let{readable:t,writable:i}=e.createEncodedStreams(),r=new AbortController;this._abortMap.set(e,r),t.pipeTo(i,r).catch((()=>{}))}clearUnusedSenderOrReceiver(e){this._abortMap.forEach(((t,i)=>{(this._isUplink?e.getSenders():e.getReceivers()).find((e=>e===i))||(t.abort(),this._abortMap.delete(i))}))}push(e,t){t&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e)}hasSEI(e){let t=new DataView(e);return 1===t.getInt32(0)&&6===t.getInt8(4)}isEmptyFrame(e){return"empty"===e.type||0===e.data.byteLength}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}encodeVideoFrame(e,t){try{if(this._connection.isH264&&this._seiMessageList.length>0&&!this.isEmptyFrame(e)){let t=9-this.getNaluCount(e.data);if(t<=0)return;let i=this._seiMessageList.splice(0,t).reverse().map(this.encodeSEINalu.bind(this)),r=i.reduce(((e,t)=>e+t.dataView.byteLength),0),n=new ArrayBuffer(r+e.data.byteLength),o=new DataView(n),a=new DataView(e.data),s=0;for(let e=0;e<i.length;e++)for(let t=0;t<i[e].dataView.byteLength;t++)o.setInt8(s++,i[e].dataView.getInt8(t));for(let c=0;c<e.data.byteLength;c++)o.setInt8(s++,a.getInt8(c));e.data=n,this._log.debug("".concat(i.length," sei sent"))}}catch(Jk){this._log.warn(Jk)}t.enqueue(e)}decodeVideoFrame(e,t){try{if(this._connection.isH264&&!this.isEmptyFrame(e)&&this.hasSEI(e.data)){let t=[],i=new DataView(e.data),r=0,n=-1,o=-1;for(let a=0;a<e.data.byteLength;a++){let s=i.getUint8(a);if(0===s)r++;else if(1===s){if(2===r||3===r){let s=a-r;if(-1===n?n=s:-1===o&&(o=s,t.push(new JL(new DataView(i.buffer.slice(n,o)))),n=s,o=-1),6!==i.getUint8(a+1)){e.data=new DataView(i.buffer.slice(s)).buffer;break}}r=0}else r=0}this._log.debug("".concat(t.length," sei received")),HD(this.onSEIMessage)&&t.reverse().forEach((e=>{this.onSEIMessage({seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer})}))}}catch(Jk){this._log.warn(Jk)}t.enqueue(e)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(t/255),r=t%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<i;a++)n.push(255);n.push(r);let o=new DataView(e);return n.push(...new Uint8Array(o.buffer)),n.push(128),new JL(new DataView(new Uint8Array(n).buffer),!0)}},zL=0,YL=!1,qL=new Set,QL=!1,XL=class{constructor(e){NA(this,"userId"),NA(this,"tinyId"),NA(this,"_sdpSemantics"),NA(this,"_isUplink"),NA(this,"_room"),NA(this,"_log"),NA(this,"_signalChannel"),NA(this,"_isErrorObserved",!1),NA(this,"_waitForPeerConnectionConnectedPromise"),NA(this,"_waitForPeerConnectionConnectedPromiseReject",null),NA(this,"_peerConnection",null),NA(this,"_emitter",new WL.default),NA(this,"_currentState","DISCONNECTED"),NA(this,"_isReconnecting",!1),NA(this,"_reconnectionCount",0),NA(this,"_reconnectionTimer",-1),NA(this,"_isFirstConnection",!0),NA(this,"_prevTime",-1),NA(this,"_enableSEI"),NA(this,"_sei"),NA(this,"_localAddress"),NA(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=CO.createLogger({id:"n",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&oP&&(this._sei=new KL(this,this._log,this._isUplink))}beforeConnect(){this._prevTime<0&&(this._prevTime=iO())}afterConnect(e){return wA(this,null,(function*(){try{yield e,this._isFirstConnection?(this._isFirstConnection=!1,SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",cost:Math.min(iO()-this._prevTime,3e4)})):this._isReconnecting&&SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",cost:iO()-this._prevTime}),this._prevTime=-1}catch(Wb){throw this._isFirstConnection?(this._isFirstConnection=!1,SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",error:Wb})):this._isReconnecting&&this._reconnectionCount>=3&&SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",error:Wb}),Wb}}))}initialize(){let e={encodedInsertableStreams:this._enableSEI&&oP,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(),this._sei&&(this._sei.destroy(),this._sei=null),qL.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 cR({code:aR.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Bk;let e=null;if(this._isUplink){if(!QN()||0===this._peerConnection.getSenders().length)return Bk;e=this._peerConnection.getSenders()[0].transport}else{if(!qN()||0===this._peerConnection.getReceivers().length)return Bk;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:Bk}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===jk.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===jk.FAILED||e.target.connectionState===jk.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new cR({message:r,code:aR.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===jk.CONNECTED||e.target.connectionState===jk.COMPLETED)&&(this.logSelectedCandidate(),wP.logSuccessEvent({userId:this._room.userId,eventType:zk.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(zL=0,YL=!1,QL=!0,qL.add(this)):qL.delete(this),SO.emit(yO.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 wA(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(BN(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 cR({code:aR.API_CALL_ABORTED,message:CN({key:gN,data:"leave room"})})))},n=()=>{SO.off(yO.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new cR({code:aR.API_CALL_TIMEOUT,message:"connection timeout"});zL+=1,(e=>zL>2&&!YL&&0===qL.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),YL=!0,this._emitter.emit("firewall-restriction")),t(e)}),aD);SO.on(yO.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(hL,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Wk()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new cR({code:this._isUplink?aR.UPLINK_RECONNECTION_FAILED:aR.DOWNLINK_RECONNECTION_FAILED,message:CN({key:this._isUplink?MO:PO})});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(hL,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"))}};DA(QA());var $L=DA(tR()),ZL=function(e){return $L.default.parse(e)},eV=function(e){return $L.default.write(e)};function tV(e){return Object.keys(e).filter((t=>e[t]))}DA(QA());var iV=class extends XL{constructor(e){super(RA(AA({},e),{isUplink:!1})),NA(this,"_flag",0),NA(this,"role","anchor"),NA(this,"remoteAudioTrack"),NA(this,"remoteVideoTrack"),NA(this,"remoteAuxiliaryTrack"),NA(this,"ssrc",{audio:0,video:0,auxiliary:0}),NA(this,"_isSDPExchanging",!1),this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new zw(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Yw(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new qw(this._room,this)}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 sO(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===Dk?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.setMediaStream(t),o.setMediaStreamTrack(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=ZL(e);return t.media.forEach((e=>{e.type===Sk.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),eV(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=ZL(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),eV(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return wA(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===jk.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===jk.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(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(Kb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Kb.message," ").concat(JSON.stringify(this.muteState))),new cR({code:aR.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Kb}}))}unsubscribe(e){return wA(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=AA({},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(tV(e),"]")),yield t.sendSubscription(n,e),"unsubscribe"===n&&(t.remoteAudioTrack.setMediaStreamTrack(null),t.remoteVideoTrack.setMediaStreamTrack(null),t.remoteAuxiliaryTrack.setMediaStreamTrack(null),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=DL,n=SL.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=OL,n=SL.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 cR({code:i.code,message:CN({key:NO,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return wA(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(Jk){throw e.closePeerConnection(!0),Jk}}()}))}exchangeSDP(e){return wA(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:kL,commandDesc:"exchange sdp",data:r,responseCommand:SL.SUBSCRIBE_RESULT,timeout:Qk});if(!this._peerConnection){let e=new cR({code:aR.INVALID_OPERATION,message:CN({key:uN})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(Jk){throw this._isSDPExchanging=!1,Jk}}))}createOffer(){return wA(this,null,(function*(){let e={voiceActivityDetection:!1};$N()&&this._sdpSemantics===Xk?(this._peerConnection.addTransceiver(Sk.AUDIO,{direction:vk.RECVONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:vk.RECVONLY}),this._peerConnection.addTransceiver(Sk.VIDEO,{direction:vk.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield LN();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=ZL(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(" ")}})),eV(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=ZL(e);return t.media.forEach((e=>{e.type===Sk.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),eV(t)}(t.sdp),this._sdpSemantics===Xk&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)}))}onSubscribeResult(e){return wA(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===eD)throw new cR({code:aR.NOT_SUPPORTED_H264,message:CN({key:aN})});try{if(0!==t)throw new cR({code:t,message:CN({key:wO,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(n)),yield this._peerConnection.setRemoteDescription({type:r,sdp:n}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=e=>{this._emitter.emit("sei-message",RA(AA({},e),{userId:this.userId}))}),this.updateSSRC(n)}catch(cU){throw this._log.error(cU),cU}}))}updateSSRC(e){try{ZL(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(Dk)}));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(Dk)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Ok)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(Jk){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return wA(this,null,(function*(){if(!(PA(iV.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(Jk){let t=BD(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}},rV=iV;OA([Vw((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 cR({code:aR.API_CALL_ABORTED,message:CN({key:gN,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],rV.prototype,"subscribe",1),OA([Lw(XL.prototype.afterConnect),Mw(XL.prototype.beforeConnect)],rV.prototype,"connect",1);var nV=rV;DA(QA()),DA(QA()),DA(QA());var oV=new Blob(["let width,height,offscreen,ctx;onmessage=function(e){const{action,data}=e.data;switch(action){case'render':offscreen=data.canvas;width=offscreen.width;height=offscreen.height;ctx=offscreen.getContext('2d');draw(data.readable,data.writable);break}};function draw(readable,writable){const transformer=new TransformStream({async transform(cameraFrame,controller){ctx.drawImage(cameraFrame,0,0,width,height);const frame=new VideoFrame(offscreen,{timestamp:cameraFrame.timestamp});cameraFrame.close();controller.enqueue(frame)}});readable.pipeThrough(transformer).pipeTo(writable)}"],{type:"application/javascript"}),aV=class{constructor(e){NA(this,"width"),NA(this,"height"),NA(this,"canvas"),NA(this,"offscreen"),NA(this,"smallGenerator"),NA(this,"smallWritable"),NA(this,"bigProcessor"),NA(this,"bigReadable"),NA(this,"worker");let{videoTrack:t}=e;this.width=void 0,this.height=void 0,this.canvas=null,this.offscreen=null,this.smallGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.smallWritable=this.smallGenerator.writable,this.bigProcessor=new MediaStreamTrackProcessor({track:t}),this.bigReadable=this.bigProcessor.readable,this.initWorker()}initWorker(){try{this.worker=new Worker(URL.createObjectURL(oV)),CO.info("init worker processor success")}catch(cM){CO.warn("init worker processor failed. ".concat(cM.error))}}setCanvasRect(e,t){this.width=e,this.height=t,this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t,this.offscreen=this.canvas.transferControlToOffscreen(),this.worker.postMessage({action:"render",data:{canvas:this.offscreen,readable:this.bigReadable,writable:this.smallWritable}},[this.offscreen,this.bigReadable,this.smallWritable])}generateVideoTrack(){let e=new MediaStream([this.smallGenerator]);return null==e?void 0:e.getTracks()[0]}destroy(){this.worker.terminate()}};DA(QA());var sV=class{constructor(e){NA(this,"_player"),NA(this,"_canvas"),NA(this,"_canvasCtx"),this._player=e,this._canvas=document.createElement("canvas"),this._canvasCtx=this._canvas.getContext("2d")}setCanvasRect(e,t){!this._canvas||(this._canvas.width=e,this._canvas.height=t)}drawVideoToCanvas(){let e=this._player.getElement();this._canvas&&this._canvasCtx&&e&&this._canvasCtx.drawImage(e,0,0,this._canvas.width,this._canvas.height)}generateVideoTrack(e){return this._canvas.captureStream(e).getVideoTracks()[0]}generateStreamFromTrack(e){let t=new MediaStream;return t.addTrack(e),t}destroy(){var e;null==(e=this._player)||e.stop(),this._canvas&&(this._canvas.width=0,this._canvas.height=0,this._canvas=null,this._canvasCtx=null)}get canvas(){return this._canvas}get canvasCtx(){return this._canvasCtx}get canDrawVideoToCanvas(){if(this._player){let e=this._player.getElement();if(e)return e.readyState===e.HAVE_ENOUGH_DATA}return!1}},cV=class{constructor(e){NA(this,"_player"),NA(this,"_processor"),NA(this,"_initOffscreenSuccess"),NA(this,"_localVideoTrack"),NA(this,"_interval"),this._localVideoTrack=e,this._player=e.player,this._processor=null,this._initOffscreenSuccess=!1}initialize(){return wA(this,null,(function*(){if(wN()&&(null==navigator?void 0:navigator.hardwareConcurrency)>=6)try{yield this.initOffscreen(),this._initOffscreenSuccess=!0,CO.info("Initialize VideoGenerator successfully!")}catch(cM){this.initCanvas()}else this.initCanvas()}))}generateSmallVideoTrack(e){let t,i=this.getSmallVideoProfile(e);return this._initOffscreenSuccess?(this._processor.setCanvasRect(i.width,i.height),t=this._processor.generateVideoTrack(i.frameRate)):(this._processor.setCanvasRect(i.width,i.height),this._player.setRect(i.width,i.height),t=this._processor.generateVideoTrack(i.frameRate),this._interval=OP.run(SD,this.render.bind(this),{fps:i.frameRate})),t}render(){this._processor instanceof sV&&this._processor.drawVideoToCanvas()}destroy(){OP.clearTask(this._interval),this._processor&&this._processor.destroy()}initOffscreen(){this._processor=new aV({videoTrack:this._localVideoTrack.mediaTrack})}initCanvas(){this._player=new aw({track:this._localVideoTrack.mediaTrack,muted:!0,objectFit:"cover",mirror:!1,container:null,id:"video-player",log:this._localVideoTrack.log}),this._player.play().then((()=>{CO.info("VideoGenerator: play local video success")})).catch((()=>{CO.error("VideoGenerator: Failed to play local video")})),this._processor=new sV(this._player)}getSmallVideoProfile(e){let t=this._localVideoTrack.mediaTrack,i=this._localVideoTrack.profile;if(rP){let e=t.getSettings();e&&e.width&&e.height&&(i.width=e.width,i.height=e.height)}let r,n=i.width*i.height,o=e.width*e.height;return CO.info("big res: ".concat(i.width,"*").concat(i.height," small res: ").concat(e.width,"*").concat(e.height," ")),n>o?r=n/o:(CO.warn("Small stream resolution is larger than big stream, which is invalid. big: ".concat(i.width," * ").concat(i.height," small: ").concat(e.width," * ").concat(e.height)),r=n/19200),{width:i.width/Math.sqrt(r),height:i.height/Math.sqrt(r),frameRate:e.frameRate}}},lV={voiceActivityDetection:!1},dV=class extends XL{constructor(e){super(RA(AA({},e),{isUplink:!0})),NA(this,"localMainAudioTrack",null),NA(this,"localMainVideoTrack",null),NA(this,"localAuxAudioTrack",null),NA(this,"localAuxVideoTrack",null),NA(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),NA(this,"_isPublishingAux",!1),NA(this,"_publishingLocalAudioTrack"),NA(this,"_publishingLocalVideoTrack"),NA(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}),NA(this,"_smallGenerator"),NA(this,"_audioManager"),this._audioManager=e.audioManager,this._smallGenerator=null}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&&(XN()?(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._smallGenerator&&(n.smallVideo=!0)))})))}return n}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents(),this.localMainVideoTrack&&this.localMainVideoTrack.canvasTrack&&this.localMainVideoTrack.destoryCanvasTrack()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null)}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,a=super.emitConnectionStateChangedEvent(e);return a&&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}))),a}publish(e){return wA(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e;let o;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),r&&(t._publishingLocalVideoTrack=r),t._isPublishingAux=n,r&&!n&&r.small&&(t._smallGenerator=new cV(r),yield t._smallGenerator.initialize(),o=t._smallGenerator.generateSmallVideoTrack(r.small)),t.sendMediaSettings(),$N()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:o,isAuxiliary:n}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:r,smallTrack:o}),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)),null==(e=t._sei)||e.handleEncodedStreams(),t.installTrackMuteEvents(i,r),t.sendMutedFlag()}()}))}publishByTransceiver(e){return wA(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;r&&Mb&&wb&&r.genCanvasTrack();let a=(null==r?void 0:r.canvasTrack)||(null==r?void 0:r.mediaTrack),s=t._audioManager.mediaStreamTrack;s&&e.addTrack(s),a&&e.addTrack(a);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(s||Sk.AUDIO,{direction:vk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?Sk.VIDEO:a||Sk.VIDEO,{direction:vk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||Sk.VIDEO,{direction:vk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&a||Sk.VIDEO,{direction:vk.SENDONLY,streams:[e]}),yield t.connect();else{let e=[];if(s&&(c[0].sender.track||e.push(0),yield c[0].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:(null==i?void 0:i.profile.bitrate)||40,type:Sk.AUDIO})),a){let i=o?3:1;yield c[i].sender.replaceTrack(a),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(vk.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 wA(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.mediaTrack,o=null!=i&&i.mediaTrack?t._audioManager.mediaStreamTrack:null;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return o&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(r)));let a=new MediaStream;if(o&&a.addTrack(o),e&&a.addTrack(e),o&&t._peerConnection.addTrack(o,a),e&&(t._peerConnection.addTrack(e,a),n)){let e=new MediaStream;e.addTrack(n),t._peerConnection.addTrack(n,e)}yield t.connect()}()}))}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 wA(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!XN())return i&&i.mediaTrack&&!r&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):r&&r.mediaTrack&&!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==i?void 0:i.mediaTrack,o=null==r?void 0:r.mediaTrack,a=t._peerConnection.getSenders(),s=[];n&&(t._audioManager.removeAudioTrack(i),t._audioManager.isMixed||(yield a[0].replaceTrack(null),s.push(0),t.localMainAudioTrack=null)),o&&(e?(yield a[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=RA(AA({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=RA(AA({},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(vk.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 wA(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:RL,data:t,responseCommand:SL.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:bL,commandDesc:"unpublish",responseCommand:SL.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===aR.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),rP){if(i&&i.mediaTrack){let e=i.mediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(r&&r.mediaTrack){let e=r.mediaTrack.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.mediaTrack){let e=n.mediaTrack.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.mediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),r&&r.mediaTrack&&(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:FL,data:this._mediaSettings,responseCommand:SL.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return wA(this,null,(function*(){var t;if(!this._peerConnection)return;let i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(i?Sk.AUXILIARY:Sk.MAIN," stream")),null==(t=this._sei)||t.handleEncodedStreams(),XN()?yield this.addTrackByTransceiver(e,i):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return wA(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers(),n=e.mediaTrack;if(e.kind===Sk.AUDIO)this._audioManager.addAudioTrack(e),n=this._audioManager.mediaStreamTrack,yield r[0].sender.replaceTrack(n);else{let e=t?3:1;if(yield r[e].sender.replaceTrack(n),1===e&&(null==(i=this.localMainVideoTrack)?void 0:i.small)){this._smallGenerator=new cV(this.localMainVideoTrack),yield this._smallGenerator.initialize();let e=this._smallGenerator.generateSmallVideoTrack(this.localMainVideoTrack.small);yield r[2].sender.replaceTrack(e)}r[e].direction===vk.INACTIVE&&(yield this.setTransceiverDirection(vk.SENDONLY,[e]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return wA(this,null,(function*(){if(!e.mediaTrack)return;let t=e.mediaTrack;XN()&&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)}let{mediaStream:r}=e;if(this._peerConnection.addTrack(t,r),t.kind===Sk.VIDEO&&e instanceof Bw&&e.small){this._smallGenerator=new cV(e),yield this._smallGenerator.initialize();let t=this._smallGenerator.generateSmallVideoTrack(e.small),i=new MediaStream;i.addTrack(t),this._peerConnection.addTrack(t,i)}yield this.updateOffer("add",t)}))}isNeedToResetOfferOrder(){if(this._sdpSemantics===$k||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=ZL(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;XN()&&(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 wA(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")),XN()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return wA(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Sk.AUDIO)this._audioManager.removeAudioTrack(e),this._audioManager.isMixed||(yield i[0].sender.replaceTrack(null));else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(vk.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return wA(this,null,(function*(){if(!DR)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._peerConnection.setLocalDescription(e)}let o=-1,a=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(vk.INACTIVE,"|").concat(vk.RECVONLY,"|").concat(vk.SENDONLY,")")))&&o++,t.includes(o)){if(e===vk.INACTIVE&&i.includes("a=".concat(vk.RECVONLY)))return r=!0,"a=".concat(e);if(e===vk.SENDONLY&&i.includes("a=".concat(vk.INACTIVE)))return r=!0,"a=".concat(vk.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:a}))}))}removeTrackBySender(e){return wA(this,null,(function*(){var t,i;if(!e.mediaTrack)return;if(e.kind===Sk.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),null==(i=null==(t=this.localMainVideoTrack)?void 0:t.mediaStream)||i.removeTrack(e.mediaTrack),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let r=this._peerConnection.getSenders().find((t=>t.track===e.mediaTrack));r&&(this.removeSender(r),e.kind===Sk.VIDEO&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===Sk.VIDEO&&this.removeSender(e)})))),yield this.updateOffer("remove",e.mediaTrack)}))}replaceTrack(e){return wA(this,null,(function*(){var t,i;let r=null==(t=this._peerConnection)?void 0:t.getSenders();if(!r||0===r.length||!e.mediaTrack)return;let n=e.mediaTrack,o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;if(this._log.info("is replacing ".concat(n.kind," track on ").concat(o?Sk.AUXILIARY:Sk.MAIN," stream")),n.kind===Sk.AUDIO&&r[0])this._audioManager.addAudioTrack(e),this._audioManager.isMixed&&(n=this._audioManager.mediaStreamTrack),yield r[0].replaceTrack(n);else if(n.kind===Sk.VIDEO){if(!o&&r[1]&&(yield r[1].replaceTrack(n),this._smallGenerator&&r[2])){this._log.info("replacing smallVideo"),this._smallGenerator.destroy(),this._smallGenerator=new cV(this.localMainVideoTrack),yield this._smallGenerator.initialize();let e=this._smallGenerator.generateSmallVideoTrack((null==(i=this.localMainVideoTrack)?void 0:i.small)||this._room.smallStreamConfig);yield r[2].replaceTrack(e)}o&&r[3]&&(yield r[3].replaceTrack(n))}}))}updateOffer(e,t){return wA(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(lV);DR&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(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:vL,data:n,responseCommand:SL.UPDATE_OFFER_RESULT,timeout:qk,commandDesc:"update offer"}),{code:a,message:s}=o.data;0!==a&&this.checkPublishResultCode(a,s),yield this.acceptAnswer(o.data.data),i.sdp&&this.updateSSRC(i.sdp)}catch(Jb){throw this._log.error(Jb),Jb}}))}setBandwidth(e){return wA(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!iP())return o?r===Sk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e=0;r===Sk.VIDEO&&(e=n===Sk.SMALL?2:n===Sk.AUXILIARY?3:1);let a=t._peerConnection.getSenders()[e];if(a){let e=a.getParameters();(!e.encodings||0===e.encodings.length)&&(e.encodings=[{}]),e.encodings[0].maxBitrate=1e3*i;try{return yield a.setParameters(e),t._log.info("".concat(n||"").concat(r," bandwidth ").concat(i," kbps")),o}catch(s){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(s)),o)return r===Sk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";DR&&(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 DR&&(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 wA(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(Wb){throw this.closePeerConnection(!0),this.uninstallEvents(),Wb}}))}exchangeSDP(){return wA(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(Wb){throw Wb}}))}createOffer(){return wA(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(lV);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(Wb){throw Wb}}))}doExchangeSDP(){let e={command:AL,responseCommand:SL.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof Hw||this.localAuxVideoTrack instanceof Hw,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=ZL(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),eV(r)}acceptAnswer(e){return wA(this,null,(function*(){var t,i,r,n,o;try{let a;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;a=yield this.setBandwidth({bandwidth:e,type:Sk.VIDEO,sdp:a,videoType:t})}o&&(a=yield this.setBandwidth({bandwidth:o,type:Sk.AUDIO,sdp:a}))}if(a=this.removeVideoOrientation(e.sdp),null!=(o=this._publishingLocalVideoTrack)&&o.small){let{smallStreamConfig:e}=this._room;a=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:Sk.VIDEO,videoType:Sk.SMALL,sdp:a})}let s={type:e.type,sdp:a};yield this._peerConnection.setRemoteDescription(s),this._log.debug("accepted answer: ".concat(a))}catch(a){throw this._log.error("failed to accept remote answer ".concat(a)),a}}))}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(CL,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return wA(this,null,(function*(){if(!(PA(dV.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:bL,responseCommand:SL.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(Jk){let t=BD(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)&&SO.emit(yO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{ZL(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===$k&&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(Jk){}}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===eD?(this._log.error(SN.NOT_SUPPORTED_H264ENCODE),new cR({code:aR.NOT_SUPPORTED_H264,message:CN({key:oN})})):new cR({code:aR.UNKNOWN,message:CN({key:lN,data:{signalResponse:SL.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}},uV=dV;OA([Vw((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 cR({code:aR.API_CALL_ABORTED,message:CN({key:gN,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],uV.prototype,"publish",1),OA([Lw(XL.prototype.afterConnect),Mw(XL.prototype.beforeConnect)],uV.prototype,"connect",1);var hV=uV;DA(QA());DA(QA());var pV=DA(XA()),mV=class extends pV.default{constructor(e){let{signalChannel:t,room:i}=e;super(),NA(this,"_room"),NA(this,"_signalChannel"),NA(this,"_log"),NA(this,"_uplinkRTT",0),NA(this,"_uplinkLoss",0),NA(this,"_downlinkRTT",0),NA(this,"_downlinkLoss",0),NA(this,"_downlinkPrevStatMap",new Map),NA(this,"_downlinkLossAndRTTMap",new Map),NA(this,"_interval",-1),NA(this,"_uplinkNetworkQuality",0),NA(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=CO.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 network quality change ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this._uplinkRTT,", loss: ").concat(this._uplinkLoss)),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 network quality change ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(t,", loss: ").concat(i))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(SL.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(uL,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.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,a=r.recvAudPkg+r.recvVidPkg,s=o-a;0===o&&0===a||(this._uplinkLoss=s<=0?0:Math.round(s/o*100),this._uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return wA(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)===jk.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 a=0,s=this._downlinkPrevStatMap.get(e),c=r-s.totalPacketsLost,l=o-s.totalPacketsReceived;a=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:a,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;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 wA(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!qN())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&&JD(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 t}catch(r){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state===mL?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state===fL&&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!==jk.DISCONNECTED&&e.connectionState!==jk.FAILED&&e.connectionState!==jk.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on(NP,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=OP.run(TD,(()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];SO.emit(yO.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(mV.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss,downlinkInfo:e})}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.info("stop network quality calculating"),-1!==this._interval&&(OP.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})}}))}},_V=mV;NA(_V,"EVENT_NETWORK_QUALITY","0"),DA(QA(),1),DA(QA(),1),DA(QA(),1);var fV=new WeakMap;function gV(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,a){let s=TO({retryFunction:a.value,settings:t,onError(t,r,n){i&&i.call(this,t,(()=>{var i;null!=(i=fV.get(e))&&i.has(o)?r():n(t)}),n)},onRetrying:(t,i)=>{var n;HD(r)&&r(t,i),null!=(n=fV.get(e))&&n.has(o)&&(fV.get(e).get(o).stopRetry=i)},onRetryFailed:n});return a.value=function(){let t=fV.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}):fV.set(e,new Map([[o,{args:r}]])),s.apply(this,r).finally((()=>{var t;return null==(t=fV.get(e))?void 0:t.delete(o)}))},a}}function TV(e){let{fnName:t,callback:i,validateArgs:r=!0}=e;return function(e,n,o){let a=o.value;return o.value=function(){for(var n,o,s=arguments.length,c=new Array(s),l=0;l<s;l++)c[l]=arguments[l];if(null!=(n=fV.get(e))&&n.has(t)){let{stopRetry:n,args:a}=fV.get(e).get(t),s=!0;if(r)for(let e of a)if(!c.find((t=>t===e))){s=!1;break}s&&(i&&i.apply(this,c),n&&n(),null==(o=fV.get(e))||o.delete(t))}return a.apply(this,c)},o}}var SV=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._apiSuccessRateMap=new Map,this._eventMap=new Map,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=CO.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||this,r);return XD(o)?o.catch((e=>CO.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(Jk){CO.error("".concat(t.name,"() error observed ").concat(Jk))}}}({fn:this[e],context:this}))})),this.initData(),this.installEvents(),this._intervalId=OP.run(TD,this.setStorage.bind(this),{delay:2e4})}get _storageKey(){return"".concat(this._keyPrefix,"_").concat(this._room.userId)}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Hb,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:pk[DD()],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_init_audio_start_time:0,uint64_init_audio_end_time:0,uint64_init_camera_start_time:0,uint64_init_camera_end_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_init_audio_ret:0,int32_init_camera_ret: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,this._apiSuccessRateMap.clear()}addEvent(e,t){return this._eventMap.set(e,t),SO.on(e,t),this}installEvents(){this._room.once("banned",(()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId}))),this.addEvent(yO.JOIN_START,this.handleJoinStart).addEvent(yO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(yO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(yO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(yO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(yO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(yO.JOIN_FAILED,this.handleJoinFailed).addEvent(yO.LEAVE_START,this.handleLeaveStart).addEvent(yO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(yO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(yO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(yO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(yO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(yO.PUBLISH_START,this.handlePublishStart).addEvent(yO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(yO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(yO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(yO.PLAY_TRACK_START,this.handlePlayStart).addEvent(yO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(yO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!QD(t)||!this.hitTest(t.room)||"PLAYING"===i&&(r===Sk.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(yO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(yO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(yO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(yO.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,a=r.hasAudio||r.hasVideo||r.hasSmall,s=r.hasAuxiliary;!n&&a&&this.handleRemoteStreamAdded(r.userId,"main"),!o&&s&&this.handleRemoteStreamAdded(r.userId,"auxiliary")})).addEvent(yO.API_SUCCESS_RATE,this.handleAPISuccessRate)}uninstallEvents(){this._eventMap.forEach(((e,t)=>SO.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),OP.clearTask(this._intervalId)}handleJoinStart(e){this.hitTest(e.room)&&(0===this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage()),e.params&&(GD(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),GD(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),GD(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}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 cR?Number(i.getExtraCode()||i.getCode()):aR.UNKNOWN,this._pathJoinRoom.int32_end_ret=2))}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=3))}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}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=3),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:RA(AA({},yV),{msg_user_info:new IV({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:a,role:s}=i,c=new IV({userId:o,tinyId:a,role:"anchor"===s?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(!QD(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._remoteStreamStatMap.get(i);0===(null==r?void 0:r.playStreamTime)&&(r.playStreamTime=Date.now())}handleVideoLoadedData(e){let{track:t}=e;if(!QD(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._pathMainVideoMap.get(i);r&&0===r.statsToReport.uint64_combine_first_frame_time&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=Date.now(),r=this._pathMainVideoMap.get(t),n=this._remoteStreamStatMap.get(t);if(r&&(0===r.statsToReport.uint64_render_first_frame_time&&(r.statsToReport.uint64_render_first_frame_time=i),n)){let{statsToReport:e,playStreamTime:t,subscribedTime:o}=n;0===e.uint32_video_render_first&&t-o<=100&&(e.uint32_video_render_first=i-r.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(t);if(o&&n){let{statsToReport:e,playStreamTime:t,subscribedTime:r}=n;0===e.uint32_video_render_first&&t-r<=100&&(e.uint32_video_render_first=i-o.sendSubscribeCMDTime)}}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=this._pathMainAudioMap.get(t);i&&0===i.statsToReport.uint64_play_first_frame_time&&(i.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(e){this.hitTest(e.room)&&(this._networkQuality.totalUplinkLoss+=e.uplink.loss,this._networkQuality.totalUplinkRTT+=e.uplink.rtt,this._networkQuality.count++,e.downlinks.forEach((e=>{let{rtt:t,loss:i,userId:r,videoDelay:n,audioDelay:o}=e,a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=t,a.totalLoss+=i,n&&(a.totalVideoDelay=(a.totalVideoDelay||0)+n,a.videoDelayCount=(a.videoDelayCount||0)+1),o&&(a.totalAudioDelay=(a.totalAudioDelay||0)+o,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let e,a,s,c;n&&(a=n,s=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:a,audioDelayCount:c,videoDelayCount:s})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_up_stream_info:t,msg_down_stream_info:i}=e.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:i,uint32_video_width:r,uint32_video_height:n}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=i,this._localStreamStat.totalVideoWidth+=r,this._localStreamStat.totalVideoHeight+=n,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:e}=t.msg_audio_status;Math.floor(e/ID*100)>0&&(this._localStreamStat.totalAudioLevel+=e/ID,this._localStreamStat.audioLevelCount++)}i.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"),a=this._remoteStreamStatMap.get(r);if(a&&(t&&(null==o?void 0:o.remoteVideoTrack.isSubscribed)||i&&(null==o?void 0:o.remoteAuxiliaryTrack))){a.totalVideoFPS+=e.uint32_video_receive_fps,a.totalVideoBitrate+=e.uint32_video_codec_bitrate,a.videoCount++,0===a.statsToReport.uint32_video_width&&(a.statsToReport.uint32_video_width=e.uint32_video_width),0===a.statsToReport.uint32_video_height&&(a.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(a.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(a.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*IA(10,6)))}})),i){let e="".concat(n,"_","main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&(null==o?void 0:o.remoteAudioTrack.isSubscribed)&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,o.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=o.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/ID*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/ID,t.audioLevelCount++))}}))}}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&&0===this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&0===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&&0===this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&0===this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,r=i instanceof cR?i.getExtraCode()||i.getCode():{NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5}[i.name]||aR.UNKNOWN;1===t.mediaType&&0===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&&0===this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleAPISuccessRate(e){let{room:t,apiName:i,error:r,cost:n}=e;if(!this.hitTest(t))return;let o=CV[i],a={uint32_function_request_type:o,uint32_avg_value:0,uint32_max_value:0,uint32_request_count:1,uint32_success_count:0,msg_error_code:[]};if(r){let e=aR.UNKNOWN;r instanceof cR&&(e=r.extraCode||r.code),wP.uploadEvent({log:"stat-".concat(i,"-failed-").concat(e),userId:this._room.userId,error:r});let t={int32_error_code:e,error_count:1};a.msg_error_code.push(t)}else JD(n)&&(a.uint32_avg_value=n,a.uint32_max_value=n,a.uint32_success_count=1);let s=this._apiSuccessRateMap.get(o);s?(s.uint32_success_count+a.uint32_success_count>0&&(s.uint32_avg_value=(s.uint32_avg_value*s.uint32_success_count+a.uint32_avg_value)/(s.uint32_success_count+a.uint32_success_count)),s.uint32_max_value=Math.max(s.uint32_max_value,a.uint32_max_value),s.uint32_request_count+=1,s.uint32_success_count=s.uint32_success_count+a.uint32_success_count,a.msg_error_code.forEach((e=>{let t=s.msg_error_code.find((t=>t.int32_error_code===e.int32_error_code));t?t.error_count+=1:s.msg_error_code.push(e)}))):this._apiSuccessRateMap.set(o,a)}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Ik))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Rk))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Ak))>=0}hitTest(e){return e===this._room}checkStorage(){return wA(this,null,(function*(){try{let e=RO.getItem(this._storageKey);e&&(yield this.upload(e),RO.deleteItem(this._storageKey))}catch(cM){this._log.warn(cM)}}))}setStorage(){this.prepareReport();let e=this.getReportData();0!==e.msg_path_enter_room.uint64_start_time&&RO.setItem(this._storageKey,e)}prepareReport(){if(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:a,totalVideoDelay:s}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),n&&a&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(a/n),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&s&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(s/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=Math.min(e.statsToReport.uint32_video_render_first,EV);let{badCaseDetector:o}=this._room,{dataFreeze:a,count:s}=o.getDataFreezeDuration(t),{renderFreeze:c}=o.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=s,e.statsToReport.uint32_video_block_time=Math.min(a,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),o.isBlackStream(t)&&0===e.statsToReport.uint32_video_avg_fps?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0,(0===e.subscribeStartTime||e.subscribeStartTime-e.streamAddedTime>100||0===e.playStreamTime)&&(this._pathMainAudioMap.delete(t),this._pathMainVideoMap.delete(t),e.statsToReport.uint32_video_render_first=0)})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>EV&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+EV):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>EV&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+EV):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>EV&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+EV)}getReportData(){return{uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new IV({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:dO(this._signalInfo.relayIp),uint32_client_ip:dO(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(2147483648*Math.random()),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:dO(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,msg_function_request_stats:[...this._apiSuccessRateMap.values()]}}report(){return wA(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),RO.deleteItem(this._storageKey),this.initData()}catch(cM){this._log.warn(cM)}}))}upload(e){return wA(this,null,(function*(){if(Vb||0===e.msg_path_enter_room.uint64_start_time||[$b,Zb,ek].findIndex((e=>e===location.host))>=0)return;let t=Number(this._room.sdkAppId),i=RD(t,sk.KEY_POINT),r=yield gO({url:i,body:JSON.stringify(e)});if("ok"!==r.data)throw"key point upload failed: ".concat(r.data)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}};OA([gV({settings:{timeout:500,retries:3}})],SV.prototype,"upload",1);var vV,EV=5e3,yV={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},IV=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},CV=((vV=CV||{})[vV.enterRoom=50001]="enterRoom",vV[vV.exitRoom=50002]="exitRoom",vV[vV.switchRole=50003]="switchRole",vV[vV.destroy=50004]="destroy",vV[vV.startLocalAudio=50005]="startLocalAudio",vV[vV.updateLocalAudio=50006]="updateLocalAudio",vV[vV.stopLocalAudio=50007]="stopLocalAudio",vV[vV.startLocalVideo=50008]="startLocalVideo",vV[vV.updateLocalVideo=50009]="updateLocalVideo",vV[vV.stopLocalVideo=50010]="stopLocalVideo",vV[vV.startScreenShare=50011]="startScreenShare",vV[vV.updateScreenShare=50012]="updateScreenShare",vV[vV.stopScreenShare=50013]="stopScreenShare",vV[vV.enableAudioVolumeEvaluation=50014]="enableAudioVolumeEvaluation",vV[vV.startRemoteVideo=50015]="startRemoteVideo",vV[vV.updateRemoteVideo=50016]="updateRemoteVideo",vV[vV.stopRemoteVideo=50017]="stopRemoteVideo",vV[vV.muteRemoteAudio=50018]="muteRemoteAudio",vV[vV.setRemoteAudioVolume=50019]="setRemoteAudioVolume",vV[vV.startMixTranscode=50020]="startMixTranscode",vV[vV.stopMixTranscode=50021]="stopMixTranscode",vV[vV.startPublishCDNStream=50022]="startPublishCDNStream",vV[vV.stopPublishCDNStream=50023]="stopPublishCDNStream",vV[vV.PeerConnectionConnect=50024]="PeerConnectionConnect",vV[vV.PeerConnectionReconnect=50025]="PeerConnectionReconnect",vV[vV.WebsocketConnect=50026]="WebsocketConnect",vV[vV.WebsocketReconnect=50027]="WebsocketReconnect",vV[vV.schedule=50028]="schedule",vV[vV.SPCConnect=50029]="SPCConnect",vV[vV.SPCReconnect=50030]="SPCReconnect",vV),AV=SV;DA(QA(),1),DA(QA(),1);var RV=class{constructor(){NA(this,"_startTime"),NA(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=iO())}stop(){0===this._endTime&&(this._endTime=iO())}getDuration(){return 0===this._endTime?iO()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},bV=class{constructor(e){NA(this,"_room",null),NA(this,"_durationMap"),NA(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(yO.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(yO.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(yO.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 a=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);!a||(!i.hasAudio&&r.hasAudio&&a.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,Sk.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&a.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,Sk.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&a.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,Sk.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>SO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>SO.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);if(r.muteState.hasAudio&&"main"===i)if(r.remoteAudioTrack.isSubscribed){let e=new RV,t=this._durationMap.get(o);t?this.isRecording(t.audio)||t.audio.push(e):this._durationMap.set(o,{userId:n,type:i,audio:[e],video:[]})}else this.stopDurationItem(o,Sk.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let e=new RV,t=this._durationMap.get(o);t?this.isRecording(t.video)||t.video.push(e):this._durationMap.set(o,{userId:n,type:i,audio:[],video:[e]})}else this.stopDurationItem(o,Sk.VIDEO)}handleStreamStopped(e){let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);this.stopDurationItem(o,Sk.AUDIO),this.stopDurationItem(o,Sk.VIDEO)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new RV,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()}};DA(QA(),1);var kV=class{constructor(e){NA(this,"_room"),NA(this,"_renderFreezeMap",new Map),NA(this,"_isVideoPlayingEventFiredMap",new Map),NA(this,"_dataFreezeMap",new Map),NA(this,"_monitorFreezeData",new Map),NA(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(yO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(yO.PLAY_TRACK_START,this.onPlayTrackStart).set(yO.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(yO.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(yO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(QD(t)&&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(yO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>SO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>SO.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 RV;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 a=o.getDuration();a>iD?this._monitorFreezeData.set(t,{userId:i,type:r,duration:a}):n.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return wA(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=iO();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=iO();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!QD(t)||!this.hitTest(t.room)||t.kind!==Sk.VIDEO||t.hasFlag)return;let i="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(i)||this._isVideoPlayingEventFiredMap.set(i,!1)}getDataFreezeDuration(e){let t={dataFreeze:0,count:0},i=this._dataFreezeMap.get(e);if(i){if(i.isFreezing()){let e=i.durationItemList[i.durationItemList.length-1];e.stop(),e.getDuration()<iD&&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=iO()-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()}};DA(QA(),1);var DV=DA(iR(),1),OV=class{constructor(e){NA(this,"_room"),NA(this,"_log"),NA(this,"_config",null),NA(this,"_data"),NA(this,"_remoteVideoTrackMap",new Map),this._room=e,this._log=CO.createLogger({id:"mix",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.installEvents()}get isPresetLayoutMode(){return this._config&&this._config.mode===Zk.MODE.PRESET_LAYOUT}get isMixing(){return!!this._data}installEvents(){SO.on(yO.REMOTE_TRACK_SUBSCRIBED,this.onSubscribed,this),SO.on(yO.REMOTE_TRACK_UNSUBSCRIBED,this.onUnSubscribed,this),SO.on(yO.REMOTE_PUBLISH_STATE_CHANGED,this.onRemotePublishedChanged,this)}uninstallEvents(){SO.off(yO.REMOTE_TRACK_SUBSCRIBED,this.onSubscribed,this),SO.off(yO.REMOTE_TRACK_UNSUBSCRIBED,this.onUnSubscribed,this),SO.off(yO.REMOTE_PUBLISH_STATE_CHANGED,this.onRemotePublishedChanged,this)}reset(){this.uninstallEvents(),this._config=null}onSubscribed(e){let{track:t}=e;t.room!==this._room||t.kind!==Sk.VIDEO||(this._remoteVideoTrackMap.set("".concat(t.userId,"_").concat(t.streamType),!1),this.isMixing&&this.hasAvailablePlaceHolder()&&this._config&&this.startMixTranscode(this._config))}onUnSubscribed(e){let{track:t}=e;t.room!==this._room||t.kind!==Sk.VIDEO||this.handleRemoteTrackUnavailable("".concat(t.userId,"_").concat(t.streamType))}onRemotePublishedChanged(e){let{room:t,prevMuteState:i,muteState:r}=e;t===this._room&&(i.hasVideo&&!r.hasVideo&&this.handleRemoteTrackUnavailable("".concat(r.userId,"_","main")),i.hasAuxiliary&&!r.hasAuxiliary&&this.handleRemoteTrackUnavailable("".concat(r.userId,"_","auxiliary")))}handleRemoteTrackUnavailable(e){if(this._remoteVideoTrackMap.has(e)){let t=this._remoteVideoTrackMap.get(e);this._remoteVideoTrackMap.delete(e),this.isMixing&&this.isPresetLayoutMode&&t&&this._config&&this.startMixTranscode(this._config)}}startMixTranscode(e){return wA(this,null,(function*(){try{this.resetIsUsedFlag(),this._config=e;let t=this.getInputParam(e),i=this.getOutputParam(e),r=this.getOutputSessionId({config:e,roomId:this._room.roomId,userId:this._room.userId});this.isMixing&&this._data&&r!==this._data.outputSessionId&&(this._log.info("startMixTranscode() streamId changed, stop mixing before start"),yield this.doStopMixTranscode()),yield this.doStartMixTranscode({outputSessionId:r,inputParam:t,outputParam:i})}catch(Wb){throw this.resetIsUsedFlag(),Wb}}))}doStartMixTranscode(e){return wA(this,arguments,(function(e){var t=this;let{outputSessionId:i,inputParam:r,outputParam:n}=e;return function*(){let e={roomId:String(t._room.roomId),mcuRequestTime:Date.now(),outputSessionId:i,inputParam:r,outputParam:n};t._log.info("startMixTranscode: ".concat(JSON.stringify(e)));let o=yield t._room.sendStartMixTranscode(e),{code:a}=o.data,{message:s}=o.data;if(0!==a)throw-102083===a&&(s="Please enable relayed-push in ".concat(tk," and try later, refer to ").concat(rk,"tutorial-26-advanced-publish-cdn-stream.html")),t._log.error("startMixTranscode failed, errCode: ".concat(a," errMsg: ").concat(s)),new cR({code:aR.START_MIX_TRANSCODE_FAILED,message:CN({key:ZO,data:{message:s},link:{className:"Client",fnName:"startMixTranscode"}})});t._data=e}()}))}reStartMixTranscode(){!this.isMixing||this._config&&this.startMixTranscode(this._config)}stopMixTranscode(){return wA(this,null,(function*(){if(!this.isMixing)throw new cR({code:aR.INVALID_OPERATION,message:CN({key:tN})});yield this.doStopMixTranscode(),this.resetIsUsedFlag()}))}doStopMixTranscode(){return wA(this,null,(function*(){let e={mcuRequestTime:Date.now(),outputSessionId:this._data.outputSessionId,streamType:this._data.outputParam.streamType};this._log.info("stopMixTranscode: ".concat(JSON.stringify(e)));let t=yield this._room.sendStopMixTranscode(e),{code:i,message:r}=t.data;if(0!==i)throw this._log.error("stopMixTranscode failed, errCode: ".concat(i," errMsg: ").concat(r)),new cR({code:aR.STOP_MIX_TRANSCODE_FAILED,message:CN({key:eN,data:{message:r},link:{className:"Client",fnName:"stopMixTranscode"}})});this._data=void 0}))}getOutputSessionId(e){let{config:t,userId:i,roomId:r}=e;return WD(t.streamId)&&t.streamId.length>0?t.streamId:(0,DV.default)("".concat(r,"_").concat(i,"_main"))}getInputParam(e){let t=e.mixUsers.map((e=>({userId:e.userId,roomId:String(e.roomId||this._room.roomId),width:e.width||0,height:e.height||0,locationX:e.locationX||0,locationY:e.locationY||0,zOrder:e.zOrder,streamType:GD(e.streamType)||e.streamType!==Pk?0:1,inputType:e.pureAudio?Zk.STREAM_TYPE.IT_PURE_AUDIO:Zk.STREAM_TYPE.IT_AUDIO_VIDEO,renderMode:e.renderMode||0})));return e.mode===Zk.MODE.PRESET_LAYOUT&&(t.forEach((e=>{if(e.userId===Zk.PLACE_HOLDER.REMOTE){let t=[...this._remoteVideoTrackMap.entries()].find((e=>{let[,t]=e;return!t}));if(t){let[i]=t,r=i.split("_");e.userId=r.slice(0,r.length-1).join("_"),e.streamType="auxiliary"===r.splice(-1)[0]?1:0,this._remoteVideoTrackMap.set(i,!0)}}})),t=t.filter((e=>e.userId!==Zk.PLACE_HOLDER.REMOTE))),t}getOutputParam(e){let t=e.streamId||"";return{streamId:t,streamType:t.length>0?1:0,width:GD(e.videoWidth)?640:e.videoWidth,height:GD(e.videoHeight)?480:e.videoHeight,videoBps:e.videoBitrate||0,fps:e.videoFramerate||15,gop:e.videoGOP||2,audioSampleRate:e.audioSampleRate||48e3,audioBps:e.audioBitrate||64,audioChannels:e.audioChannels||1,backgroundColor:e.backgroundColor||0,backgroundImg:e.backgroundImage||"",extraInfo:"",videoCodec:2,audioCodec:0}}hasAvailablePlaceHolder(){var e,t;return!(!this.isPresetLayoutMode||(null==(e=this._data)?void 0:e.inputParam.length)===(null==(t=this._config)?void 0:t.mixUsers.length))}resetIsUsedFlag(){this._remoteVideoTrackMap.forEach(((e,t)=>{this._remoteVideoTrackMap.set(t,!1)}))}};DA(QA(),1);var NV=DA(iR(),1);function PV(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Sk.MAIN;return t=AD(e)?i===Sk.MAIN?sD.MAIN_OVERSEA:sD.BACKUP_OVERSEA:i===Sk.MAIN?sD.MAIN:sD.BACKUP,"https://".concat(t,"/api/v1/config")}function wV(e,t,i){return new Promise(((r,n)=>{gO({url:e,body:t,timeout:i.timeout}).then((e=>{0===e.data.code?r(e.data.data):n({code:e.data.code,message:e.data.msg})})).catch(n)}))}DA(QA(),1);var MV=(e,t)=>TO({retryFunction:wV,settings:{retries:3,timeout:0},onError:t,onRetrying:e});function LV(e,t,i){return new Promise(((r,n)=>{let o=null;tO([MV((e=>t.count[0]=e+1),((e,i)=>{t.msg[0]=e.message,o||i()}))(PV(i,Sk.MAIN),e,{get timeout(){return 1e3*FD(2+t.count[0])}}),MV((e=>t.count[1]=e+1),((e,i)=>{t.msg[1]=e.message,o||i()}))(PV(i,Sk.BACKUP),e,{get timeout(){return 1e3*FD(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}var VV=0,UV=class extends AP{constructor(e){super("room"),this.seq=++VV,this.role="anchor",this.localTracks=new Set,this.enableAutoPlayDialog=!0,this.autoReceiveAudio=!0,this.autoReceiveVideo=!0,this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this._log=CO.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this._isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,KD(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),KD(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),KD(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this.keyPointManager=new AV({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new bV({room:this}),this.badCaseDetector=new kV({room:this}),this.mixTranscodeManager=new OV(this),this.publishCDNManager=new class{constructor(e){NA(this,"_room"),NA(this,"_publishTencentMainStreamObj",{params:null,streamId:void 0,isPublishing:!1}),NA(this,"_publishTencentAuxStreamObj",{params:null,streamId:void 0,isPublishing:!1}),NA(this,"_publishGivenCDNData",null),NA(this,"_isPublishingGivenCDN",!1),this._room=e}get _isPublishingTencentCDN(){return this._publishTencentMainStreamObj.isPublishing||this._publishTencentAuxStreamObj.isPublishing}generatePublishCDNStreamId(e,t){if(!e){let e="".concat(this._room.roomId,"_").concat(this._room.userId,"_").concat(this.convertStreamType(t));return/^[A-Za-z\d_-]*$/.test(e)||(e=(0,NV.default)(e)),"".concat(this._room.sdkAppId,"_").concat(e)}return e}convertStreamType(e){return"main"===e?e:"aux"}generatePublishCDNSessionId(e){return(0,NV.default)("".concat(this._room.roomId,"_").concat(this._room.userId,"_").concat(this.convertStreamType(e)))}startPublishCDN(e){return wA(this,null,(function*(){let{streamId:t="",streamType:i="main",appId:r,bizId:n,url:o}=e;yield this.startPublishTencentCDN({streamId:t,streamType:i}),r&&n&&o&&(yield this.startPublishGivenCDN({streamType:i,appId:r,bizId:n,url:o}))}))}stopPublishCDN(){return wA(this,null,(function*(){if(!this._isPublishingTencentCDN)throw new cR({code:aR.INVALID_OPERATION,message:CN({key:YO})});yield this.stopPublishTencentCDN(),this._isPublishingGivenCDN&&(yield this.stopPublishGivenCDN())}))}startPublishTencentCDN(e){return wA(this,null,(function*(){if("auxiliary"===e.streamType?(this._publishTencentAuxStreamObj.params=e,this._publishTencentAuxStreamObj.isPublishing=!0):(this._publishTencentMainStreamObj.params=e,this._publishTencentMainStreamObj.isPublishing=!0),!this._room.isJoined)return;let t=this.generatePublishCDNStreamId(e.streamId,e.streamType),i=this.generatePublishCDNSessionId(e.streamType),r="auxiliary"===e.streamType?1:0,n={requestTime:Date.now(),sessionId:i,streamId:t,streamType:r};yield this.doStartPublishTencentCDN(n,e.streamType)}))}doStartPublishTencentCDN(e,t){return wA(this,null,(function*(){try{CO.info("startPublishTencentCDN: ".concat(JSON.stringify(e)));let i=yield this._room.sendStartPublishCDN(e,!0),{code:r}=i.data,{message:n}=i.data;if(0!==r)throw"auxiliary"===t?this._publishTencentAuxStreamObj.isPublishing=!1:this._publishTencentMainStreamObj.isPublishing=!1,-102083===r&&(n="Please enable relayed-push in ".concat(tk," and try later, refer to ").concat(rk,"tutorial-26-advanced-publish-cdn-stream.html")),CO.error("startPublishTencentCDN failed, errCode: ".concat(r,", errMsg: ").concat(n)),new cR({code:aR.START_PUBLISH_CDN_FAILED,message:CN({key:qO,data:{message:n},link:{className:"Client",fnName:"startPublishCDNStream"}})});"auxiliary"===t?this._publishTencentAuxStreamObj.streamId=e.streamId:this._publishTencentMainStreamObj.streamId=e.streamId}catch(Jk){throw"auxiliary"===t?this._publishTencentAuxStreamObj.isPublishing=!1:this._publishTencentMainStreamObj.isPublishing=!1,Jk}}))}resetPublishTencentParam(e){"main"===e&&(this._publishTencentMainStreamObj={params:null,streamId:void 0,isPublishing:!1}),"auxiliary"===e&&(this._publishTencentAuxStreamObj={params:null,streamId:void 0,isPublishing:!1})}stopPublishTencentCDN(){return wA(this,null,(function*(){if(!this._room.isJoined)return this.resetPublishTencentParam("main"),void this.resetPublishTencentParam("auxiliary");this._publishTencentMainStreamObj.isPublishing&&(yield this.doStopPublishTencentCDN("main")),this._publishTencentAuxStreamObj.isPublishing&&(yield this.doStopPublishTencentCDN("auxiliary"))}))}doStopPublishTencentCDN(e){return wA(this,null,(function*(){let t={requestTime:Date.now(),sessionId:(0,NV.default)("".concat(this._room.roomId,"_").concat(this._room.userId,"_").concat(this.convertStreamType(e)))};CO.info("stopPublishTencentCDN: ".concat(JSON.stringify(t)));let i=yield this._room.sendStopPublishCDN(t,!0),{code:r,message:n}=i.data;if(0===r)this.resetPublishTencentParam(e);else{if(-102069!==r)throw CO.error("stopPublishTencentCDN failed, errCode: ".concat(r," errMsg: ").concat(n)),new cR({code:aR.STOP_PUBLISH_CDN_FAILED,message:CN({key:QO,data:{message:n},link:{className:"Client",fnName:"stopPublishCDNStream"}})});CO.warn("stopPublishTencentCDN failed, can not stopPublishTencentCDN in auto relayed-push mode"),this.resetPublishTencentParam(e)}}))}startPublishGivenCDN(e){return wA(this,null,(function*(){let t="main"===e.streamType?this._publishTencentMainStreamObj.streamId:this._publishTencentAuxStreamObj.streamId,i={pushRequestTime:Date.now(),pushAppId:e.appId,pushBizId:e.bizId,pushCdnUrl:e.url,pushStreamType:this.convertStreamType(e.streamType),pushStreamId:t};if(CO.info("startPublishGivenCDN: ".concat(JSON.stringify(i))),this._publishGivenCDNData=i,this._isPublishingGivenCDN=!0,this._room.isJoined)try{let e=yield this._room.sendStartPublishCDN(i,!1),{code:t,message:r}=e.data;if(0!==t)throw CO.error("startPublishGivenCDN failed, errCode: ".concat(t,", errMsg: ").concat(r)),this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1,new cR({code:aR.START_PUBLISH_CDN_FAILED,message:CN({key:qO,data:{message:r},link:{className:"Client",fnName:"startPublishCDNStream"}})})}catch(Jb){throw this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1,Jb}}))}stopPublishGivenCDN(){return wA(this,null,(function*(){if(!this._room.isJoined||!this._publishGivenCDNData)return this._publishGivenCDNData=null,void(this._isPublishingGivenCDN=!1);let{pushAppId:e,pushBizId:t,pushCdnUrl:i,pushStreamType:r}=this._publishGivenCDNData,n={pushRequestTime:Date.now(),pushAppId:e,pushBizId:t,pushCdnUrl:i,pushStreamType:r};CO.info("stopPublishGivenCDN: ".concat(JSON.stringify(n)));let o=yield this._room.sendStopPublishCDN(n,!1),{code:a,message:s}=o.data;if(0!==a)throw CO.error("stopPublishGivenCDN failed, errCode: ".concat(a," errMsg: ").concat(s)),new cR({code:aR.STOP_PUBLISH_CDN_FAILED,message:CN({key:QO,data:{message:s},link:{className:"Client",fnName:"stopPublishCDNStream"}})});this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1}))}handleCDNConfigForJoinData(e){let t,i=e;if(this._publishTencentMainStreamObj.isPublishing||this._publishTencentAuxStreamObj.isPublishing){let e={};WD(i)&&(e=JSON.parse(i)),e.Str_uc_params||(e.Str_uc_params={}),this._publishTencentMainStreamObj.isPublishing&&(this._publishTencentMainStreamObj.streamId?e.Str_uc_params.userdefine_streamid_main=this._publishTencentMainStreamObj.streamId:this._publishTencentMainStreamObj.params&&(e.Str_uc_params.userdefine_streamid_main=this.generatePublishCDNStreamId(this._publishTencentMainStreamObj.params.streamId,"main"))),this._publishTencentAuxStreamObj.isPublishing&&(this._publishTencentAuxStreamObj.streamId?e.Str_uc_params.userdefine_streamid_aux=this._publishTencentAuxStreamObj.streamId:this._publishTencentAuxStreamObj.params&&(e.Str_uc_params.userdefine_streamid_aux=this.generatePublishCDNStreamId(this._publishTencentAuxStreamObj.params.streamId,"auxiliary"))),i=JSON.stringify(e)}if(this._isPublishingGivenCDN&&this._publishGivenCDNData){let{pushAppId:e,pushBizId:i,pushCdnUrl:r,pushStreamType:n,pushStreamId:o}=this._publishGivenCDNData;t={pushRequestTime:Date.now(),pushAppId:e,pushBizId:i,pushCdnUrl:r,pushStreamType:n,pushStreamId:o}}return{bussinessInfo:i,pushUserCdnInfo:t}}reset(){this.resetPublishTencentParam("main"),this.resetPublishTencentParam("auxiliary"),this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1}}(this),this.audioManager=new class{constructor(e){let{room:t}=e;NA(this,"audioContext",null),NA(this,"_destination",null),NA(this,"_localAudioTrack",null),NA(this,"_localScreenAudioTrack",null),NA(this,"_localMediaStreamAudioTrack",null),NA(this,"_audioTrackStreamSource",null),NA(this,"_screenAudioTrackStreamSource",null),NA(this,"_mixedMusicSet",new Set),NA(this,"hasMusic",!1),NA(this,"mixedMusicMap",new Map),NA(this,"cacheMusicMap",new Map),NA(this,"_log"),NA(this,"_originTrack",null),this._log=CO.createLogger({id:"am",userId:t.userId,sdkAppId:t.sdkAppId}),this.initAudioContext()}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}get isMixed(){return(this.hasMusic?1:0)+(this._localAudioTrack?1:0)+(this._localScreenAudioTrack?1:0)>=1}get mediaStreamTrack(){return this._destination.stream.getAudioTracks()[0]}addMusicSource(e){return wA(this,null,(function*(){this._log.info("add music source, id: ".concat(e.id," url: ").concat(e.url)),this.initAudioContext();let t,{id:i,url:r,loop:n,volume:o}=e;if(this.mixedMusicMap.has(i))return;t=this.cacheMusicMap.has(i)?this.cacheMusicMap.get(i).localMusicTrack:new Ww(e);let{stream:a}=t._destination,s=document.createElement("audio");s.srcObject=a,t.play(),yield s.play(),this._log.info("start mix audio ".concat(i," success."));let c=this.audioContext.createMediaStreamSource(a),l=this.audioContext.createGain();return c.connect(l),l.connect(this._destination),this._mixedMusicSet.add(i),this.mixedMusicMap.set(i,{localMusicTrack:t,streamSource:c,gainNode:l,audioPlayer:s}),this.cacheMusicMap.set(i,{localMusicTrack:t}),this.hasMusic=!0,t}))}updateMusicSource(e){return wA(this,null,(function*(){let{id:t,volume:i,loop:r,operation:n}=e;if(this._log.info("update music source, id: ".concat(e.id," operation: ").concat(n)),this.mixedMusicMap.has(t)){let{localMusicTrack:e}=this.mixedMusicMap.get(t);GD(i)||e.setVolume(i),GD(r)||e.loop(r),GD(n)||e.setOperation(n)}}))}addAudioTrack(e){return wA(this,null,(function*(){var t;if(this._log.info("start add audioTrack, userId: ".concat(e.userId)),this.initAudioContext(),null==e||!e.mediaStream)return;if(this._localMediaStreamAudioTrack===e.mediaTrack)return void this._log.info("addAudioTrack duplicate.");let i=yield null==(t=e.mediaTrack)?void 0:t.getSettings();this._destination.channelCount=(null==i?void 0:i.channelCount)||1,this._localAudioTrack=e,this._localMediaStreamAudioTrack=e.mediaTrack,this._audioTrackStreamSource=this.audioContext.createMediaStreamSource(e.mediaStream),this._audioTrackStreamSource.connect(this._destination)}))}removeAudioTrack(e){var t,i,r,n;this._localAudioTrack===e&&(this._log.info("start remove audioTrack, userId: ".concat(e.userId)),null==(t=this._audioTrackStreamSource)||t.disconnect(),null==(i=this._localMediaStreamAudioTrack)||i.stop(),this._localMediaStreamAudioTrack=null,null==(r=this._localAudioTrack)||r.stop(),this._localAudioTrack=null),this._localScreenAudioTrack===e&&(this._log.info("start remove screenTrack, userId: ".concat(e.userId)),null==(n=this._screenAudioTrackStreamSource)||n.disconnect(),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack=null)}addScreenAudioTrack(e){this._log.info("start add screenAudioTrack, userId: ".concat(e.userId)),this.initAudioContext(),null!=e&&e.mediaStream&&this._localScreenAudioTrack!==e&&(this._localScreenAudioTrack=e,this._screenAudioTrackStreamSource=this.audioContext.createMediaStreamSource(e.mediaStream),this._screenAudioTrackStreamSource.connect(this._destination))}removeAudioTrackSource(e){var t,i;this._log.info("remove audio track source, type: ".concat(e)),"main"===e&&(null==(t=this._audioTrackStreamSource)||t.disconnect(),this._audioTrackStreamSource=null,this._localAudioTrack=null),"screen"===e&&(null==(i=this._screenAudioTrackStreamSource)||i.disconnect(),this._screenAudioTrackStreamSource=null,this._localScreenAudioTrack=null)}removeMusicSource(e){let{id:t}=e;if(this.mixedMusicMap.has(t)){this._log.info("start remove music source, music id: ".concat(t));let{localMusicTrack:e,streamSource:i,gainNode:r,audioPlayer:n}=this.mixedMusicMap.get(t);i.disconnect(),r.disconnect(),n.pause(),n.srcObject=null,e.stop(),this.mixedMusicMap.delete(t),this._mixedMusicSet.delete(t),0===this._mixedMusicSet.size&&(this.hasMusic=!1)}"*"===t&&this.destroyAllMusic()}destroyAllMusic(){this._log.info("destroy all music source."),this._mixedMusicSet.forEach((e=>{this.removeMusicSource({id:e})}))}destroyAllCache(){this._log.info("destroy all music cache."),this.cacheMusicMap.forEach((e=>{e.localMusicTrack.stop()}))}initAudioContext(){this.audioContext||(this.audioContext=uw(),"running"!==this.audioContext.state&&this._log.warn("context state: ".concat(this.audioContext.state)),this._destination=this.audioContext.createMediaStreamDestination(),this._destination.channelCount=1)}initDenoiser(e){return wA(this,arguments,(function(e){return function*(){}()}))}enableDenoiser(e){return wA(this,null,(function*(){}))}disableDenoiser(){return wA(this,null,(function*(){}))}destroy(){this.removeAudioTrackSource("main"),this.removeAudioTrackSource("aux"),this.audioContext.close(),this.destroyAllMusic(),this.destroyAllCache()}}({room:this})}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}getLogger(){return this._log}get isJoined(){return"joined"===this.state}addTrack(e){return wA(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return wA(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return wA(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}getRemoteAudioStats(){return wA(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return wA(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 wA(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 cR({code:aR.INVALID_OPERATION,message:CN({key:$O,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(SN.INVALID_DESTROY),new cR({code:aR.INVALID_OPERATION,message:CN({key:GO})});this._log.info("destroy room"),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this._isDestroyed=!0,SO.emit(yO.ROOM_DESTROY,{room:this})}startMixTranscode(e){return this.mixTranscodeManager.startMixTranscode(e)}stopMixTranscode(){return this.mixTranscodeManager.stopMixTranscode()}startPublishCDNStream(){return wA(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){if(e._log.info("startPublishCDNStream with params: ".concat(JSON.stringify(t),"; isJoined: ").concat(e.isJoined,"; hasMainStream: ").concat(e.isMainStreamPublished,"; hasAuxStream: ").concat(!!e.isAuxStreamPublished,";")),e.isJoined){if("main"===t.streamType&&!e.isMainStreamPublished)throw new cR({code:aR.INVALID_OPERATION,message:CN({key:zO})});if("auxiliary"===t.streamType&&!e.isAuxStreamPublished)throw new cR({code:aR.INVALID_OPERATION,message:CN({key:zO})})}yield e.publishCDNManager.startPublishCDN(t)}()}))}stopPublishCDNStream(){return this.publishCDNManager.stopPublishCDN()}schedule(e,t,i){return wA(this,null,(function*(){var r,n;let o=iO();try{let a=yield function(e){return wA(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:n,userSig:o,version:a,frameWorkType:s}=e;return function*(){let e={delta:0,count:[1,1],msg:[]};try{let c=new FormData;c.append("userId",String(t)),c.append("sdkAppId",String(i)),c.append("isStrGroupId",String(r)),c.append("groupId",String(n)),c.append("sdkVersion",a),c.append("userSig",String(o)),c.append("frameWorkType",String(s));let l=iO(),d=yield LV(c,e,i);return e.delta=iO()-l,d}catch(c){let e=YD(c)?c[0]:c,t=JD(e.code)?e.code:0,i="get websocket url failed: ".concat(e.message.includes("timeout")?"timeout":e.message),r=new cR({code:aR.SCHEDULE_FAILED,extraCode:t,message:CN({key:jO,data:{error:i,code:t}})});throw CO.error(r),r}}()}))}({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:i,userSig:this.userSig,frameWorkType:t});this._log.info("schedule: ".concat(JSON.stringify(a))),this.scheduleResult=AA(AA({},this.scheduleResult),a),JD(null==(r=a.config)?void 0:r.retryCount)&&Gk(a.config.retryCount),WD(null==(n=a.config)?void 0:n.loggerDomain)&&Xb(a.config.loggerDomain),SO.emit(yO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult}),SO.emit(yO.API_SUCCESS_RATE,{room:this,apiName:"schedule",cost:iO()-o})}catch(a){throw SO.emit(yO.API_SUCCESS_RATE,{room:this,apiName:"schedule",error:a}),a}}))}};DA(QA(),1);var xV=new WeakMap,FV=new WeakMap;function BV(){return function(e,t,i){let r=i.value,n=e=>{let{fn:t,args:i,context:r,resolve:n,reject:o}=e;t.apply(r,i).then(n,o)};return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return new Promise(((e,i)=>{if(xV.has(this)){let o=xV.get(this),{length:a}=o;o.push({fn:r,args:t,context:this,resolve:e,reject:i}),0===a&&n({fn:r,args:t,context:this,resolve:e,reject:i})}else xV.set(this,[{fn:r,args:t,context:this,resolve:e,reject:i}]),n({fn:r,args:t,context:this,resolve:e,reject:i})})).finally((()=>{let e=xV.get(this);e&&(e.shift(),e[0]&&n(AA({},e[0])))}))},i}}function jV(e){return function(t,i,r){let n=r.value,o=t=>JD(e)?t[e]:e(...t),a=e=>{let{fn:t,args:i,context:r,resolve:n,reject:s}=e;t.apply(r,i).then(n,s).finally((()=>{if(FV.has(r)&&FV.get(r).has(o(i))){let e=FV.get(r).get(o(i));e&&(e.shift(),e[0]&&a(AA({},e[0])))}}))};return r.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return new Promise(((e,i)=>{if(FV.has(this))if(FV.get(this).has(o(t))){let r=FV.get(this).get(o(t));if(r){let{length:o}=r;r.push({fn:n,args:t,context:this,resolve:e,reject:i}),0===o&&a({fn:n,args:t,context:this,resolve:e,reject:i})}}else FV.get(this).set(o(t),[{fn:n,args:t,context:this,resolve:e,reject:i}]),a({fn:n,args:t,context:this,resolve:e,reject:i});else{let r=new Map;r.set(o(t),[{fn:n,args:t,context:this,resolve:e,reject:i}]),FV.set(this,r),a({fn:n,args:t,context:this,resolve:e,reject:i})}}))},r}}DA(QA(),1);var HV=DA(XA(),1),GV=Symbol("instance"),WV=Symbol("abortCtrl"),JV=Symbol("cacheResult"),KV=class{constructor(e,t,i){NA(this,"oldState"),NA(this,"newState"),NA(this,"action"),NA(this,"error"),this.oldState=e,this.newState=t,this.action=i}toString(){return"".concat(this.action,"ing")}},zV=class extends Error{constructor(e,t,i){super(t),NA(this,"state"),NA(this,"message"),NA(this,"cause"),this.state=e,this.message=t,this.cause=i}},YV=new Map,qV=Object.getPrototypeOf(wA(void 0,null,(function*(){}))).constructor;function QV(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,n,o)=>{let a=i.action||n;if(!i.context){let i=YV.get(r)||[];YV.has(r)||YV.set(r,i),i.push({from:e,to:t,action:a})}let s=o.value;o.value=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return wA(this,null,(function*(){var r;let o=this;if(i.context&&(o=iU.get("function"==typeof i.context?i.context.call(this,...n):i.context)),o.state===t)return o[JV];let c=null;if(Array.isArray(e)?0==e.length?o[WV]&&(o[WV].aborted=!0):("string"!=typeof o.state||!e.includes(o.state))&&(c=new zV(o._state,"".concat(o.name," ").concat(a," to ").concat(t," failed: current state ").concat(o._state," not in from config"))):e!==o.state&&(c=new zV(o._state,"".concat(o.name," ").concat(a," to ").concat(t," failed: current state ").concat(o._state," not from ").concat(e))),c){if(!i.fail){if(i.ignoreError)return c;throw c}i.fail.call(this,c)}let l=o.state;$V.call(o,new KV(l,t,a));let d={aborted:!1};o[WV]=d;try{let e=s.apply(this,n);return o[JV]=e instanceof qV?yield e:e,d.aborted||(o[WV]=void 0,$V.call(o,t),null==(r=i.success)||r.call(this,o[JV])),o[JV]}catch(u){let e=u instanceof Error?u.message:String(u);if($V.call(o,l,e),!i.fail){if(i.ignoreError)return u;throw u}i.fail.call(this,new zV(o._state,"action '".concat(a,"' failed :").concat(e),u instanceof Error?u:new Error(e)))}}))}}}var XV="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 $V(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(iU.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t})}var ZV,eU,tU=class extends HV.default{constructor(e,t,i){super(),NA(this,"name"),NA(this,"groupName"),NA(this,"_state",tU.INIT),NA(this,ZV),NA(this,eU),this.name=e,this.groupName=t,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let r=i[GV];r?this.name=r.name+"-"+r.count++:i[GV]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=YV.get(e)||[],i=new Set,r=[],n=[],o=new Set,a=Object.getPrototypeOf(e);YV.has(a)&&(a.stateDiagram.forEach((e=>i.add(e))),a.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 s=[...i];return Object.defineProperty(this,"stateDiagram",{value:s}),s}static get(e){let t;return"string"==typeof e?(t=tU.instances.get(e),t||tU.instances.set(e,t=new tU(e,void 0,Object.create(tU.prototype)))):(t=tU.instances2.get(e),t||tU.instances2.set(e,t=new tU(e.constructor.name,void 0,Object.create(tU.prototype)))),t}static getState(e){var t;return null==(t=tU.get(e))?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};XV(tU.UPDATEAFSM,AA({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){$V.call(this,e)}},iU=tU;ZV=JV,eU=WV,NA(iU,"STATECHANGED","stateChanged"),NA(iU,"UPDATEAFSM","updateAFSM"),NA(iU,"INIT","[*]"),NA(iU,"ON","on"),NA(iU,"OFF","off"),NA(iU,"instances",new Map),NA(iU,"instances2",new WeakMap),DA(QA());var rU=DA(XA());DA(QA());var nU=DA(tR()),oU=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,o=ZL(r),a={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},s={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 a.media.push(s),[1,2,3].forEach((e=>{a.media.push(aU({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),n&&a.media.push(o.media.find((e=>"dc"===e.mid))),eV(a)},aU=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,useAllCodec:o=!1}=e,a={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction: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(i.video.codecs.length>0)if(o)for(let s=0;s<i.video.codecs.length;s++)sU(a,i.video.codecs[s]);else{let e=i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264")));sU(a,i.video.codecs[e])}else if(o)for(let s=0;s<r.video.codecs.length;s++)sU(a,r.video.codecs[s]);else sU(a,r.video.codecs[0]);return a.payloads=a.payloads.trim(),a},sU=(e,t)=>{e.payloads="".concat(e.payloads," ").concat(t.payload),e.fmtp.push({payload:t.payload,config:t.fmtp}),e.rtcpFb=[...e.rtcpFb||[],...(t.rtcpfb||t.rtcpFb).map((e=>({payload:t.payload,type:e.id,subtype:e.params[0]})))],e.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(e.payloads="".concat(e.payloads," ").concat(t.rtx),e.fmtp.push({payload:t.rtx,config:"apt=".concat(t.payload)}),e.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))};var cU,lU=e=>{let t=nU.default.parse(e);return t.media.forEach((e=>{var i;(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)),(null==(i=e.payloads)?void 0:i.includes("datachannel"))&&t.groups&&e.mid&&(t.groups[0].mids=t.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),nU.default.write(t)},dU=((cU=dU||{}).TRACK="track",cU.DATA_CHANNEL_MESSAGE="data_channel_msg",cU[cU.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",cU[cU.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",cU.RECONNECTED="spc-reconnected",cU.RECONNECT_FAILED="spc-reconnect-failed",cU.ERROR="error",cU),uU=0,hU=!1,pU=new Set,mU=class extends rU.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),NA(this,"currentState","DISCONNECTED"),NA(this,"_room"),NA(this,"_signalChannel"),NA(this,"_peerConnection",null),NA(this,"_datachannel",null),NA(this,"_enableCustomMessage"),NA(this,"_log"),NA(this,"_downlinkMIDMap",new Map),NA(this,"_reconnectionTimer",-1),NA(this,"reconnectionCount",0),NA(this,"_clientAbility",null),NA(this,"_serverAbility",null),NA(this,"addDownlinkQueue",new Set),NA(this,"removeDownlinkQueue",new Set),NA(this,"_parsedAnswer",null),NA(this,"_updateSDPPromise",null),NA(this,"_waitForPCConnectedPromise"),NA(this,"_waitForPCConnectedPromiseReject",null),NA(this,"_isSDPLogged",!1),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=CO.createLogger({id:"spc",userId:this._room.userId,sdkAppId:this._room.sdkAppId})}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}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.useVp8),e}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=ZL(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&&!GD(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}}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0}initialize(){return wA(this,null,(function*(){try{this._peerConnection=new RTCPeerConnection({offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.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 fU(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});let e=yield this._peerConnection.createOffer();return yield this.setOffer(e),this._clientAbility=((e,t)=>{var i,r;let n=ZL(e),o={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:t};o.ice.ufrag=String(n.media[0].iceUfrag),o.ice.password=n.media[0].icePwd||"",n.fingerprint&&(o.dtls.hash=n.fingerprint.type,o.dtls.fingerprint=n.fingerprint.hash,o.dtls.setup=n.setup||""),n.media[0].fingerprint&&(o.dtls.hash=n.media[0].fingerprint.type,o.dtls.fingerprint=n.media[0].fingerprint.hash),o.dtls.setup=n.media[0].setup||"";let a=n.media[0],s=n.media[1];a.ext&&(o.audio.extensions=a.ext.map((e=>({id:e.value,uri:e.uri})))),s.ext&&(o.video.extensions=s.ext.map((e=>({id:e.value,uri:e.uri}))));let c={codec:a.rtp[0].codec,fmtp:a.fmtp[0].config,payload:a.fmtp[0].payload,rate:a.rtp[0].rate,channel:a.rtp[0].encoding,rtcpFb:[],rtx:0};null==(i=a.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:r}=e;if(t===c.payload){let e={id:i,params:[]};r&&e.params.push(r),c.rtcpFb.push(e)}})),o.audio.codecs.push(c);for(let l=0;l<s.rtp.length;l++){if(["rtx","red","ulpfec"].includes(s.rtp[l].codec))continue;let e=s.fmtp.filter((e=>e.payload===s.rtp[l].payload))[0];o.video.codecs.push({payload:s.rtp[l].payload,codec:s.rtp[l].codec,fmtp:e?e.config:"",rate:s.rtp[l].rate,rtx:"rtx"===(null==(r=s.rtp[l+1])?void 0:r.codec)?s.rtp[l+1].payload:0,rtcpFb:((null==s?void 0:s.rtcpFb)||[]).filter((e=>e.payload===s.rtp[l].payload)).map((e=>{let{type:t,subtype:i}=e;return{id:t,params:i?[i]:[]}}))})}return o})(e.sdp,this._enableCustomMessage),this._clientAbility}catch(Wb){throw this._log.error("initialize failed ".concat(Wb)),Wb}}))}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return wA(this,null,(function*(){try{if("CONNECTED"===this.currentState)return;let i=iO(),r={type:"answer",sdp:oU({serverAbility:e,clientAbility:this._clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(r),yield this.waitForPeerConnectionConnected(),t||SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:"SPCConnect",cost:Math.min(iO()-i,3e4)})}catch(Jb){let i=Jb instanceof cR&&Jb.code===aR.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(Jb," ").concat(e)),this.reset(),!i&&!this.isReconnecting&&(SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:"SPCConnect",error:Jb}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),Jb}}))}reconnect(){return wA(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(hL,this.reconnect,this);try{this.reconnectionCount++,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:BL,responseCommand:SL.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});yield this.connect(t.data.data.ability,!0),this._log.warn("reconnect() successfully"),this.stopReconnection(),this.emit("spc-reconnected")}catch(Wb){if(Wb)if(Wb.message.includes("timeout")){let e=BD(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),this._reconnectionTimer=window.setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),e)}else this._log.error("reconnect() failed ".concat(Wb)),SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:"SPCReconnect",error:Wb}),this.reconnectionCount>=Wk()&&this._log.warn("SDK has tried reconnect for ".concat(Wk()," 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 wA(this,null,(function*(){this._log.warn("start reconnect"),this.emitConnectionStateChangedEvent("RECONNECTING");let e=iO();yield this.reconnect(),SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:"SPCReconnect",cost:Math.min(iO()-e,3e4)})}))}stopReconnection(){-1!==this._reconnectionTimer&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(hL,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===jk.CLOSED&&this.startReconnection()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}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===jk.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===jk.FAILED||e.target.connectionState===jk.CLOSED){let r="ICE/DTLS Transport connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i);new cR({message:r,code:aR.ICE_TRANSPORT_ERROR}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()}(e.target.connectionState===jk.CONNECTED||e.target.connectionState===jk.COMPLETED)&&(this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return Bk;let e=null;return QN()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,qN()&&0!==this._peerConnection.getReceivers().length&&e?e.state:Bk):Bk}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(dU.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return wA(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(BN(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):"")),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();this._waitForPCConnectedPromiseReject=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 cR({code:aR.API_CALL_ABORTED,message:CN({key:gN,data:"leave room"})})))},n=()=>{SO.off(yO.LEAVE_SUCCESS,r,this),this.off(dU.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{n();let e=new cR({code:aR.API_CALL_TIMEOUT,message:"connection timeout"});uU+=1,(e=>uU>2&&!hU&&0===pU.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),hU=!0,this.emit(dU.FIREWALL_RESTRICTION)),t(e)}),aD);SO.on(yO.LEAVE_SUCCESS,r,this),this.on(dU.CONNECTION_STATE_CHANGED,i,this)})),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally((()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null}))),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise(((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)})):Promise.resolve()}addDownlink(e){return wA(this,null,(function*(){if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this.updateLocalAndRemoteSDPConfig(e),0===this.addDownlinkQueue.size)try{yield this.updateSDP({isNeedToCreateOffer:!0}),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(Jk){this._log.info("addDownlink(".concat(e.userId,") failed")),yield this.startReconnection()}}))}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,tinyId:i}=e;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(JSON.stringify(t)," ").concat(i));let r,n,o,a=this._peerConnection.getTransceivers().filter((e=>"inactive"===e.direction)).slice(0,3).map((e=>(e.direction=Sk.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));if(0===a.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})),this._parsedAnswer||(this._parsedAnswer=ZL(this._peerConnection.remoteDescription.sdp)),3===a.length)r=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[0]))),n=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[1]))),o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[2])));else{r=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=aU({mid:1,serverAbility:this._serverAbility,clientAbility:this._clientAbility,parsedOffer:ZL(this._peerConnection.localDescription.sdp),useAllCodec:!0});n=JSON.parse(JSON.stringify(e)),o=JSON.parse(JSON.stringify(e)),r.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(r),n.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(n),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o)}r.direction=Sk.TRANSCEIVER_DIRECTION_SENDONLY,r.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(i)},{id:t.audio,attribute:"msid",value:"".concat(i,"-").concat(Sk.MAIN," ").concat(i,"-audio")}],n.direction=Sk.TRANSCEIVER_DIRECTION_SENDONLY,n.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(i)},{id:t.video,attribute:"msid",value:"".concat(i,"-").concat(Sk.MAIN," ").concat(i,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(i)},{id:t.videoRtx,attribute:"msid",value:"".concat(i,"-").concat(Sk.MAIN," ").concat(i,"-bigvideo")}],n.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],o.direction=Sk.TRANSCEIVER_DIRECTION_SENDONLY;let s="".concat(i,"-aux");o.ssrcs=[{id:t.auxiliary,attribute:"cname",value:s},{id:t.auxiliary,attribute:"msid",value:"".concat(s," ").concat(i,"-aux").concat(Sk.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(s," ").concat(i,"-aux").concat(Sk.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(s," ").concat(i,"-aux").concat(Sk.VIDEO)}],o.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,[r.mid,n.mid,o.mid])}removeDownlink(e,t){return wA(this,null,(function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(t,") trying")),this.isReconnecting&&(yield this.waitForReconnected());let i=this._downlinkMIDMap.get(e),r=!1;this._peerConnection.getTransceivers().forEach((e=>{null!=i&&i.includes(Number(e.mid))&&(r=!0,e.direction="inactive")})),this._parsedAnswer||(this._parsedAnswer=ZL(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((e=>{null!=i&&i.includes(Number(e.mid))&&(r=!0,e.direction="inactive",e.ssrcs=[],e.ssrcGroups=[])})),0===this.removeDownlinkQueue.size&&r&&(yield this.updateSDP({isNeedToCreateOffer:!0,tinyIdRemoving:e})),this._downlinkMIDMap.delete(e),this._log.info("removeDownlink(".concat(t,") done"))}))}getDownlinkMids(e){return this._downlinkMIDMap.get(e)}setBandwidth(e){return wA(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(iP()){let e=this._peerConnection.getSenders().slice(0,4);for(let o=0;o<e.length;o++){let a,s=e[o];0===o&&t?a=t:1===o&&i?a=i:2===o&&r?a=r:3===o&&n&&(a=n),a&&(yield this.setSenderMaxBitrate(s,a))}}else yield this.setBandwidthBySDP(e);Object.keys(e).forEach((t=>{e[t]&&this._log.info("".concat(t," bandwidth was set to ").concat(e[t]," kbps"))}))}catch(cU){this._log.error("failed to set bandwidth".concat(cU))}}))}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=ZL(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=ZL(this._peerConnection.remoteDescription.sdp));let a=DR?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:a,limit:DR?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:DR?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:a,limit:DR?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:DR?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:a,limit:DR?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:DR?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:a,limit:DR?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:DR?1e3*n:n}]);let s={type:"offer",sdp:eV(o)};return this.updateSDP({localDescription:s})}updateSDP(e){let{isNeedToCreateOffer:t=!1,localDescription:i,tinyIdRemoving:r}=e;if(!this._parsedAnswer)return;let n=eV(this._parsedAnswer);return this._updateSDPPromise=new Promise(((e,r)=>wA(this,null,(function*(){var o,a;try{t&&this._peerConnection&&(this._log.info("creating offer"),i=yield this._peerConnection.createOffer()),i&&(yield this.setOffer(i)),yield this.setAnswer({type:"answer",sdp:n}),this._updateSDPPromise=null,e()}catch(s){this._log.error(s),!this._isSDPLogged&&this._peerConnection&&(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._log.warn("local sdp: ".concat(null==i?void 0:i.sdp)||(null==(o=this._peerConnection.localDescription)?void 0:o.sdp)),this._log.warn("remote sdp: ".concat(n)||(null==(a=this._peerConnection.remoteDescription)?void 0:a.sdp)),this._isSDPLogged=!0),this._updateSDPPromise=null,r(s)}})))),this._updateSDPPromise}setOffer(e){return this._log.info("setting offer"),this._peerConnection.setLocalDescription({type:"offer",sdp:lU(e.sdp)})}setAnswer(e){return this._log.info("setting answer"),this._peerConnection.setRemoteDescription(e)}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;null==(e=this._peerConnection)||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}};OA([BV()],mU.prototype,"updateSDP",1);var _U=class{constructor(e){NA(this,"tag"),NA(this,"len"),NA(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}},fU=class{constructor(e){NA(this,"tinyId"),NA(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new _U(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)}))}},gU=new Set;function TU(){let e=Math.floor(4294967296*Math.random());return gU.has(e)?TU():(gU.add(e),e)}DA(QA()),DA(QA());var SU=DA(XA()),vU=class extends SU.default{constructor(e){super(),NA(this,"userId"),NA(this,"tinyId"),NA(this,"_sdpSemantics"),NA(this,"_isUplink"),NA(this,"_room"),NA(this,"_log"),NA(this,"_signalChannel"),NA(this,"_currentState","DISCONNECTED"),NA(this,"_prevTime",-1),NA(this,"_enableSEI"),NA(this,"_sei"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=CO.createLogger({id:"n",userId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&oP&&(this._sei=new KL(this,this._log,this._isUplink))}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}close(e){this._log.info("close connection"),this.emit("closed",e),this._sei&&(this._sei.destroy(),this._sei=null)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(SO.emit(yO.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"))}},EU=class extends vU{constructor(e){super(RA(AA({},e),{isUplink:!0})),NA(this,"localMainAudioTrack",null),NA(this,"localMainVideoTrack",null),NA(this,"localAuxAudioTrack",null),NA(this,"localAuxVideoTrack",null),NA(this,"_isPublishingAux",!1),NA(this,"_publishingLocalAudioTrack"),NA(this,"_publishingLocalVideoTrack"),NA(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}),NA(this,"_smallGenerator"),NA(this,"_audioManager"),this._audioManager=e.audioManager,this._smallGenerator=null,this.initialize()}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:a}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:o||0,auxiliaryRtx:a||0}}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&&(XN()?(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._smallGenerator&&(n.smallVideo=!0)))})))}return n}initialize(){this.installEvents()}reset(){this.uninstallEvents(),this.localMainVideoTrack&&this.localMainVideoTrack.canvasTrack&&this.localMainVideoTrack.destoryCanvasTrack()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null)}installEvents(){var e;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(e=this.singlePC)||e.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,a=super.emitConnectionStateChangedEvent(e);return a&&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}))),a}publish(e){return wA(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e,o,a,s,c,l;if(!t.singlePC)return;if(yield t.singlePC.waitForPeerConnectionConnected(),i&&(t._publishingLocalAudioTrack=i),r){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new cR({code:aR.NOT_SUPPORTED_H264,message:CN({key:oN})});t._publishingLocalVideoTrack=r}let d;t._isPublishingAux=n,r&&!n&&r.small&&(t._smallGenerator=new cV(r),yield t._smallGenerator.initialize(),d=t._smallGenerator.generateSmallVideoTrack(r.small)),$N()&&(yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:d,isAuxiliary:n})),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)),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==(a=t.localMainVideoTrack)?void 0:a.profile.bitrate,smallVideo:null==(c=null==(s=t.localMainVideoTrack)?void 0:s.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),yield t._signalChannel.sendWaitForResponse({command:HL,responseCommand:SL.SPC_PUBLISH_RESULT,data:RA(AA({},t.singlePC.uplinkSSRC),{state:t.publishState})}),t.sendMediaSettings(),t.installTrackMuteEvents(i,r),t.sendMutedFlag()}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;this._log.info("publish by transceiver");let o=new MediaStream;i&&Mb&&wb&&i.genCanvasTrack();let a=(null==i?void 0:i.canvasTrack)||(null==i?void 0:i.mediaTrack),s=this._audioManager.mediaStreamTrack,c=this._peerConnection.getTransceivers(),l=[];if(s){o.addTrack(s);let e=c[0].sender.replaceTrack(s);l.push(e)}if(a)if(o.addTrack(a),n){let e=c[3].sender.replaceTrack(a);l.push(e)}else{let e=c[1].sender.replaceTrack(a);l.push(e)}if(r){let e=c[2].sender.replaceTrack(r);l.push(e)}return Promise.all(l)}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 wA(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){let e=r&&r===t.localAuxVideoTrack,n=null==i?void 0:i.mediaTrack,o=null==r?void 0:r.mediaTrack,a=t._peerConnection.getSenders(),s=[];n&&(t._audioManager.removeAudioTrack(i),t._audioManager.isMixed||(yield a[0].replaceTrack(null),s.push(0),t.localMainAudioTrack=null)),o&&(e?(yield a[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=RA(AA({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=RA(AA({},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(vk.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 wA(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:RL,data:t,responseCommand:SL.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:bL,commandDesc:"unpublish",responseCommand:SL.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===aR.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),rP){if(i&&i.mediaTrack){let e=i.mediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(r&&r.mediaTrack){let e=r.mediaTrack.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.mediaTrack){let e=n.mediaTrack.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.mediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),r&&r.mediaTrack&&(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:FL,data:this._mediaSettings,responseCommand:SL.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return wA(this,null,(function*(){var t;if(!this._peerConnection)return;let i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(i?Sk.AUXILIARY:Sk.MAIN," stream")),null==(t=this._sei)||t.handleEncodedStreams(),XN()&&(yield this.addTrackByTransceiver(e,i))}))}addTrackByTransceiver(e,t){return wA(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers(),n=e.mediaTrack;if(e.kind===Sk.AUDIO)this._audioManager.addAudioTrack(e),n=this._audioManager.mediaStreamTrack,yield r[0].sender.replaceTrack(n);else{let e=t?3:1;if(yield r[e].sender.replaceTrack(n),1===e&&(null==(i=this.localMainVideoTrack)?void 0:i.small)){this._smallGenerator=new cV(this.localMainVideoTrack),yield this._smallGenerator.initialize();let e=this._smallGenerator.generateSmallVideoTrack(this.localMainVideoTrack.small);yield r[2].sender.replaceTrack(e)}r[e].direction===vk.INACTIVE&&(yield this.setTransceiverDirection(vk.SENDONLY,[e]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return wA(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")),XN()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return wA(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Sk.AUDIO)this._audioManager.removeAudioTrack(e),this._audioManager.isMixed||(yield i[0].sender.replaceTrack(null));else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(vk.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return wA(this,null,(function*(){if(!DR)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._peerConnection.setLocalDescription(e)}let o=-1,a=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(vk.INACTIVE,"|").concat(vk.RECVONLY,"|").concat(vk.SENDONLY,")")))&&o++,t.includes(o)){if(e===vk.INACTIVE&&i.includes("a=".concat(vk.RECVONLY)))return r=!0,"a=".concat(e);if(e===vk.SENDONLY&&i.includes("a=".concat(vk.INACTIVE)))return r=!0,"a=".concat(vk.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:a}))}))}replaceTrack(e){return wA(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders();if(!i||0===i.length||!e.mediaTrack)return;let r=e.mediaTrack,n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;if(this._log.info("is replacing ".concat(r.kind," track on ").concat(n?Sk.AUXILIARY:Sk.MAIN," stream")),r.kind===Sk.AUDIO&&i[0]&&(this._audioManager.addAudioTrack(e),this._audioManager.isMixed&&(r=this._audioManager.mediaStreamTrack),yield i[0].replaceTrack(r)),r.kind===Sk.VIDEO){if(!n&&i[1]&&(yield i[1].replaceTrack(r),this._smallGenerator&&i[2])){this._log.info("replacing smallVideo"),this._smallGenerator.destroy(),this._smallGenerator=new cV(this.localMainVideoTrack),yield this._smallGenerator.initialize();let e=this._smallGenerator.generateSmallVideoTrack(this._room.smallStreamConfig);yield i[2].replaceTrack(e)}n&&i[3]&&(yield i[3].replaceTrack(r))}}))}setBandwidth(e){return wA(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){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(CL,n)}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&SO.emit(yO.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===eD?(this._log.error(SN.NOT_SUPPORTED_H264ENCODE),new cR({code:aR.NOT_SUPPORTED_H264,message:CN({key:oN})})):new cR({code:aR.UNKNOWN,message:CN({key:lN,data:{signalResponse:SL.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}onSinglePCReconnected(){return wA(this,null,(function*(){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}))}))}};DA(QA());var yU=class extends vU{constructor(e){super(RA(AA({},e),{isUplink:!1})),NA(this,"_flag",0),NA(this,"role","anchor"),NA(this,"remoteAudioTrack"),NA(this,"remoteVideoTrack"),NA(this,"remoteAuxiliaryTrack"),NA(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),this.flag=e.flag,this.remoteAudioTrack=new zw(this._room,this),this.remoteVideoTrack=new Yw(this._room,this),this.remoteAuxiliaryTrack=new qw(this._room,this),this.initialize()}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 sO(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){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){let t=e.streams[0],{track:i}=e;if(t.id.split("-")[0]!==this.tinyId)return;let r=t.id.includes("aux")?"auxiliary":"main";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.setMediaStream(t),o.setMediaStreamTrack(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return wA(this,null,(function*(){try{if(this.isSubscriptionStateNotChanged(e))return;if(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)}catch(Jb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Jb.message," ").concat(JSON.stringify(this.muteState))),new cR({code:aR.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Jb}}))}unsubscribe(e){return wA(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=AA({},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(function(e){return Object.keys(e).filter((t=>e[t]))}(n),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,n),"unsubscribe"===o&&(t.remoteAudioTrack.setMediaStreamTrack(null),t.remoteVideoTrack.setMediaStreamTrack(null),t.remoteAuxiliaryTrack.setMediaStreamTrack(null),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=DL,n=SL.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=OL,n=SL.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 cR({code:i.code,message:CN({key:NO,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&this.doSubscribe(this.subscribeState,!1)}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return wA(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){if(e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected(),i||!e.hasSSRC){let i={audioSsrc:TU(),bigVideoSsrc:TU(),bigVideoRtxSsrc:TU(),auxVideoSsrc:TU(),auxVideoRtxSsrc:TU()},{audioSsrc:r,bigVideoSsrc:n,bigVideoRtxSsrc:o,auxVideoSsrc:a,auxVideoRtxSsrc:s}=i;e.ssrc={audio:r,video:n,videoRtx:o,auxiliary:a,auxiliaryRtx:s},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});let c=yield e._signalChannel.sendWaitForResponse({command:GL,responseCommand:SL.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!0,ssrc:i}});if(0!==c.data.code)throw yield e.removeDownlink(),new cR({code:c.data.code,message:c.data.message});return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}}()}))}removeDownlink(){return wA(this,null,(function*(){!this.singlePC||(this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),yield this.singlePC.removeDownlink(this.tinyId,this.userId))}))}};OA([Vw((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 cR({code:aR.API_CALL_ABORTED,message:CN({key:gN,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],yU.prototype,"subscribe",1);var IU=yU,{isString:CU,isPlainObject:AU,isUndefined:RU,getNetworkType:bU,getTerminalType:kU,isEmpty:DU}=hR,OU=class extends UV{constructor(e){super(e),this.privateMapKey="",this._heartbeat=-1,this._lastHeartBeatTime=-1,this._joinTimeout=-1,this._firstPublishedList=null,this._joinReject=null,this._isPublishing=!1,this._isRelayChanged=!1,this.uplinkConnection=null,this.singlePC=null,this._enableSPC=!0,this._changeBigSmallRecords=new Map,this._networkQuality=null,this._networkType=bU(),this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=null,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this._stats=new class{constructor(e,t){this.room=e,NA(this,"_log"),NA(this,"_prevReportTime"),NA(this,"_prevReport",{}),NA(this,"_prevEncoderImplementation"),NA(this,"_prevQualityLimitationReason"),NA(this,"_prevAuxQualityLimitationReason"),NA(this,"_prevDecoderImplementationMap",new Map),NA(this,"_spcStats",null),this._log=t,this._prevReportTime=0,this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevAuxQualityLimitationReason=""}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return wA(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{(this._spcStats||(yield r.getStats())).forEach((t=>{if("outbound-rtp"===t.type)if(t.mediaType===Sk.VIDEO){let e;if(t.ssrc===n.video?e=Sk.VIDEO:t.ssrc===n.small?e=Sk.SMALL:t.ssrc===n.auxiliary&&(e=Sk.AUXILIARY),!e)return;i[e].bytesSent=t.bytesSent,i[e].packetsSent=t.packetsSent,i[e].framesEncoded=t.framesEncoded,t.ssrc===n.video?(!GD(t.encoderImplementation)&&this._prevEncoderImplementation!==t.encoderImplementation&&(this._log.info("encoderImplementation change to ".concat(t.encoderImplementation)),this._prevEncoderImplementation=t.encoderImplementation),!GD(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),this._prevQualityLimitationReason=t.qualityLimitationReason)):t.ssrc===n.auxiliary&&!GD(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),this._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else t.mediaType===Sk.AUDIO&&(i.audio.bytesSent=t.bytesSent,i.audio.packetsSent=t.packetsSent);else"candidate-pair"===t.type?BN(t)&&JD(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.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(GD(t.audioLevel)||(i.audio.audioLevel=t.audioLevel||0),!GD(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}})),0===i.audio.audioLevel&&(i.audio.audioLevel=(null==(t=e.localMainAudioTrack)?void 0:t.getInternalAudioLevel())||0)}catch(Kb){this._log.warn("failed to getStats on sender connection ".concat(Kb))}return i}))}getReceiverStats(e){return wA(this,null,(function*(){let t={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,jitter: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},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0}},i=e.getPeerConnection();if(i)try{let{ssrc:r}=e,{muteState:n}=e;(this._spcStats||(yield i.getStats())).forEach((i=>{if("inbound-rtp"===i.type){if(i.mediaType===Sk.AUDIO&&i.ssrc===r.audio&&n.hasAudio){t.audio.packetsReceived=i.packetsReceived,t.audio.bytesReceived=i.bytesReceived,t.audio.packetsLost=i.packetsLost,i.insertedSamplesForDeceleration&&(t.audio.insertedSamplesForDeceleration=i.insertedSamplesForDeceleration),i.removedSamplesForAcceleration&&(t.audio.removedSamplesForAcceleration=i.removedSamplesForAcceleration);let{remoteAudioTrack:r}=e;r.stat.packetsReceived=i.packetsReceived,r.stat.bytesReceived=i.bytesReceived,r.stat.packetsLost=i.packetsLost,i.jitterBufferDelay&&(r.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)),t.hasAudio=!0}else if(i.mediaType===Sk.VIDEO){if(DR&&0===i.bytesReceived)return;let o;i.ssrc===r.video&&n.hasVideo&&(t.video.packetsReceived=i.packetsReceived,t.video.bytesReceived=i.bytesReceived,t.video.packetsLost=i.packetsLost,t.video.framesReceived=i.framesReceived,t.video.framesDecoded=i.framesDecoded,t.video.fpsDecoded=i.framesPerSecond,t.hasVideo=!0,o=e.remoteVideoTrack,i.decoderImplementation&&(!this._prevDecoderImplementationMap.has(t.userId)||this._prevDecoderImplementationMap.get(t.userId)!==i.decoderImplementation)&&(this._log.info("".concat(t.userId," decoderImplementation change to ").concat(i.decoderImplementation)),this._prevDecoderImplementationMap.set(t.userId,i.decoderImplementation))),i.ssrc===r.auxiliary&&n.hasAuxiliary&&(t.auxiliary.packetsReceived=i.packetsReceived,t.auxiliary.bytesReceived=i.bytesReceived,t.auxiliary.packetsLost=i.packetsLost,t.auxiliary.framesReceived=i.framesReceived,t.auxiliary.framesDecoded=i.framesDecoded,t.auxiliary.fpsDecoded=i.framesPerSecond,o=e.remoteAuxiliaryTrack,t.hasAuxiliary=!0),o&&(o.stat.packetsReceived=i.packetsReceived,o.stat.bytesReceived=i.bytesReceived,o.stat.packetsLost=i.packetsLost,o.stat.framesReceived=i.framesReceived,o.stat.framesDecoded=i.framesDecoded,i.jitterBufferDelay&&(o.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)))}}else"candidate-pair"===i.type&&BN(i)&&JD(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime));GD(i.frameWidth)||((i.trackIdentifier===e.getMainStreamVideoTrackId()||i.ssrc===r.video)&&(t.video.frameWidth=i.frameWidth,t.video.frameHeight=i.frameHeight,e.remoteVideoTrack.stat.frameWidth=i.frameWidth,e.remoteVideoTrack.stat.frameHeight=i.frameHeight),(i.trackIdentifier===e.getAuxStreamVideoTrackId()||i.ssrc===r.auxiliary)&&(t.auxiliary.frameWidth=i.frameWidth,t.auxiliary.frameHeight=i.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=i.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=i.frameHeight)),GD(i.audioLevel)||(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0)})),0===t.audio.audioLevel&&(t.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0)}catch(Jb){this._log.warn("failed to getStats on receiver connection ".concat(Jb))}return t}))}getStats(e,t){return wA(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=yield e.getStats(),n=[],o=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);t.forEach((e=>o.has(e.type)&&n.push(e))),this._spcStats=n}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(gw(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r}=e;if(!gw(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*ID,uint32_audio_energy:1e6*t.senderStats.audio.totalAudioEnergy,uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent},r=[],n={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};if(r.push(n),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};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};r.push(e)}let o={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:o}}let{statInterval:n}=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_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(Nk)),n=i?i.duration:0,o={uint32_video_stream_type: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};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=r.get("".concat(e.userId,"_").concat(Pk)),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};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let o=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(i)),i.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let e=o.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status,r=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*r/n),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}let a=o.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=a.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,o=0,s=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(r=t.uint32_video_codec_bitrate,o=t.uint32_video_enc_fps,s=t.uint32_video_codec_fps);let c=this.getDifferenceValue(r,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*c/n),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_enc_fps)/n),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(s,e.uint32_video_codec_fps)/n)}));let s=i.msg_down_stream_info,c=o.msg_down_stream_info;return s.forEach((e=>{let t=c.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(t){if(gw(e.msg_audio_status)||gw(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,r=t.msg_audio_status;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 o=this.getDifferenceValue(r.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*o/n),i.uint32_audio_total_bitrate=Math.round(8*o/n)}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,o=t.uint32_video_origin_lost,a=t.uint32_video_codec_bitrate,s=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(o,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(a,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/n);let d=this.getDifferenceValue(s,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/n),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/n)}))}}})),i}getStatsReport(e){return wA(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:r,freezeMap:n}=e;return function*(){let e={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:0,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:[{uint32_video_stream_type:0,uint32_video_codec_fps:0,uint32_video_capture_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_final_lost:0,uint32_video_enc_fps:0}],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_format:0,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_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}}(this,this._log),this.userManager=new pM(this.userId,this._log),this._version=Hb,this.sdpSemantics=$k,RU(e.sdpSemantics)?bO.isUnifiedPlanDefault()&&(this.sdpSemantics=Xk):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(this._networkType)),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!RU(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!RU(e.enableSPC)&&ZN&&(this._enableSPC=e.enableSPC),this._initBusinessInfo(e)}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.remotePublishedUserMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,i){return wA(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)vA.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&TA)for(var r of TA(e))t.indexOf(r)<0&&EA.call(e,r)&&(i[r]=e[r]);return i})(e,[]);SO.emit(yO.REMOTE_PUBLISH_STATE_CHANGED,AA({room:this},t)),this.emit("remote-publish-state-changed",AA({},t))})),String(e.roomId||e.strRoomId),this._joinOptions=e,new Promise(((t,i)=>wA(this,null,(function*(){this._joinReject=i;try{this.checkDestroy(),yield this.initialize(),yield this.doJoin(e),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(r){this.reset(),i(r)}this._joinReject=null}))))}))}doJoin(e){return new Promise(((t,i)=>wA(this,null,(function*(){var r,n,o;let a;if(RU(e.role)||(this.role=20===e.role?"anchor":"audience"),RU(e.privateMapKey)||(this.privateMapKey=e.privateMapKey),this._signalChannel.once(dL,(e=>{this.clearJoinTimeout(),SO.emit(yO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),i(e)})),KD(null==(n=null==(r=this.scheduleResult)?void 0:r.config)?void 0:n.singlePC)&&ZN&&(this._enableSPC=this.scheduleResult.config.singlePC),this._enableSPC&&!this.singlePC){this.singlePC=new mU({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.once("error",(()=>this.fallbackToMPC()));try{a=yield this.singlePC.initialize()}catch(u){this.fallbackToMPC()}}this.keyPointManager.setConnectionType(this.singlePC?1:2);let s={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,trtcRole:"anchor"===this.role?20:21,trtcScene:"live"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:kU(),netType:pk[this._networkType],bussinessInfo:this._businessInfo,ability:a},{bussinessInfo:c,pushUserCdnInfo:l}=this.publishCDNManager.handleCDNConfigForJoinData(this._businessInfo);Object.assign(s,{bussinessInfo:c,pushUserCdnInfo:l}),this._log.debug("join room signal data: ".concat(JSON.stringify(s)));let d=5e3;(null==(o=this.scheduleResult.config)?void 0:o.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(d=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{this._log.error("join room timeout observed"),i(new cR({code:aR.JOIN_ROOM_FAILED,message:CN({key:BO})}))}),d),SO.emit(yO.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?jL:EL,s),this._signalChannel.once(SL.JOIN_ROOM_RESULT,(e=>{this.clearJoinTimeout();let{code:r,message:n,data:o}=e.data;SO.emit(yO.JOIN_RECEIVED_CMD_RES,{room:this,code:r}),0===r?(this._log.info("Join room success, start heartbeat"),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=o.publishers,this.singlePC&&this.singlePC.connect(o.ability).catch((()=>{})),t()):(this._log.error("Join room failed result: ".concat(r," error: ").concat(n)),i(new cR({code:aR.JOIN_ROOM_FAILED,extraCode:r,message:CN({key:jO,data:{error:n,code:r}})})))}))}))))}reJoin(){return wA(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this._joinOptions.roomId)),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this._signalChannel.close(),yield this._signalChannel.connect(),yield this.doJoin(RA(AA({},this._joinOptions),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey})),this._log.warn("reJoin success"),wP.logSuccessEvent({userId:this.userId,eventType:zk.REJOIN}),this.singlePC?(yield this.singlePC.waitForPeerConnectionConnected(),this.uplinkConnection instanceof EU&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.doSubscribe()}))):(this.checkConnectionsToReconnect(),this.uplinkConnection instanceof hV&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()),this.mixTranscodeManager.reStartMixTranscode()}catch(Wb){this._log.warn("reJoin fail ".concat(Wb)),this.reset(),wP.logFailedEvent({userId:this.userId,eventType:zk.REJOIN,error:Wb}),this.emit("error",new cR({code:aR.JOIN_ROOM_FAILED,message:CN({key:HO,data:{roomId:this._joinOptions.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){this._log.info("setup signal channel");let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl();return this._signalChannel=new class{constructor(e){NA(this,"_room"),NA(this,"_sdkAppId"),NA(this,"_userId"),NA(this,"_userSig"),NA(this,"_url"),NA(this,"_backupUrl"),NA(this,"_urlWithParam"),NA(this,"_backupUrlWithParam"),NA(this,"_socketInUse"),NA(this,"_socket"),NA(this,"_backupSocket"),NA(this,"_backupTimer",-1),NA(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),NA(this,"_currentState",mL),NA(this,"_reconnectionCount",0),NA(this,"_reconnectionTimer",-1),NA(this,"_seq",0),NA(this,"_log"),NA(this,"_emitter"),NA(this,"_lastMessageTime",-1),NA(this,"_prevTime",-1),this._room=e.room,this._sdkAppId=e.sdkAppId,this._userId=e.userId,this._userSig=e.userSig,this._url=e.url,this._backupUrl=e.backupUrl;let t="?sdkAppId=".concat(encodeURIComponent(this._sdkAppId),"&userId=").concat(encodeURIComponent(this._userId),"&userSig=").concat(encodeURIComponent(this._userSig));this._urlWithParam="".concat(this._url).concat(t),this._backupUrlWithParam="".concat(this._backupUrl).concat(t),this._seq=0,this._log=CO.createLogger({id:"ws",userId:this._userId,sdkAppId:this._sdkAppId}),this._emitter=new cL.default}get isConnected(){return this._currentState===fL}get isConnecting(){return this._currentState===_L}get isOnline(){return this._currentState===fL&&Date.now()-this._lastMessageTime<12e3}connect(){return new Promise(((e,t)=>{this._prevTime<0&&(this._prevTime=iO()),this._log.info("connect to ".concat(this._url)),this.emitConnectionStateChanged(_L),this._socket=new WebSocket(this._urlWithParam),this.bindSocket(this._socket),this._backupTimer=setTimeout((()=>{this.isConnected||(this._log.info("trying to connect to backupUrl"),this.tryConnectBackup())}),5e3),this.once(hL,e),this.once(pL,t)}))}tryConnectBackup(){this._backupSocket||(this.unbindAndCloseSocket(Sk.MAIN),this._log.debug("try to connect to url: ".concat(this._backupUrlWithParam)),this._backupSocket=new WebSocket(this._backupUrlWithParam),this.bindSocket(this._backupSocket))}bindSocket(e){e.onopen=this.onopen.bind(this),e.onclose=this.onclose.bind(this),e.onerror=this.onerror.bind(this),e.onmessage=this.onmessage.bind(this)}unbindSocket(e){this.clearBackupTimer(),e.onopen=()=>{},e.onclose=()=>{},e.onerror=()=>{},e.onmessage=()=>{}}unbindAndCloseSocket(t){if(t===Sk.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(e){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(e){}this._backupSocket=null}}clearBackupTimer(){-1!==this._backupTimer&&(clearTimeout(this._backupTimer),this._backupTimer=-1)}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onopen(e){this.isConnected||(this.isReconnecting&&!this._signalInfo.tinyId&&this.stopReconnection(),this.clearBackupTimer(),e.target===this._socket?(this.unbindAndCloseSocket(Sk.BACKUP),this._socketInUse=this._socket):(this.unbindAndCloseSocket(Sk.MAIN),this._socketInUse=this._backupSocket),this.emitConnectionStateChanged(fL),this._emitter.emit(hL))}onclose(e){let{url:t}=e.target,i=e.target===this._socketInUse;if(this._log.info("websocket[".concat(t," InUse: ").concat(i,"] is closed with code: ").concat(e.code)),i&&(this.emitConnectionStateChanged(mL),!e.wasClean||1e3!==e.code)){this._log.warn("onclose code:".concat(e.code," reason:").concat(e.reason)),this._log.warn("close current websocket and schedule a reconnect timeout"),this._socketInUse.onclose=()=>{},this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this._socket=null,this._backupSocket=null,this._socketInUse=null,this.reconnect(t?Sk.BACKUP:Sk.MAIN)}}onerror(e){let{url:t}=e.target;if(this._log.error("websocket[".concat(t,"] error observed")),this.isConnected){if(e.target===this._socketInUse){this.unbindAndCloseSocket(Sk.MAIN),this.unbindAndCloseSocket(Sk.BACKUP);let e=this._socketInUse===this._socket;this._socketInUse=null,this.reconnect(e?Sk.BACKUP:Sk.MAIN)}}else this.isReconnecting||SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",error:new Error("ws onerror")}),e.target==this._socket?(this.unbindAndCloseSocket(Sk.MAIN),this.reconnect(Sk.BACKUP)):(this.unbindAndCloseSocket(Sk.BACKUP),this.reconnect(Sk.MAIN))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now();let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values(gL),o=Object.keys(gL)[n.indexOf(i)],a=SL[o];switch(TL.includes(i)||(this._log.debug("received msg: ".concat(e.data)),this._log.info("Received event: [ ".concat(a||"unknown cmd: ".concat(i)," ]"))),i){case gL.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,this._signalInfo.tinyId=t.tinyId,r.svrTime&&function(e){lR=e-(new Date).getTime();let t=new Date;t.setTime(e),CO.info("baseTime from server: ".concat(t," offset: ").concat(lR))}(r.svrTime),this._log.info("ChannelSetup Success"),SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",cost:iO()-this._prevTime}),this._prevTime=-1,this._emitter.emit(lL,{signalInfo:this._signalInfo});else{let e=new cR({code:aR.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:CN({key:OO,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",error:e}),this._emitter.emit(dL,e)}break;case gL.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=r.relayOuterIp,this._signalInfo.relayInnerIp=r.relayInnerIp,this._signalInfo.relayPort=r.relayPort,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this._emitter.emit(a,{data:t});break;case gL.CHANNEL_RECONNECT_RESULT:0===t.code?(this._log.warn("reconnect success"),this.stopReconnection(),SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketReconnect",cost:iO()-this._prevTime}),this._prevTime=-1,this._room.syncUserList(),this._room.checkConnectionsToReconnect()):(this._log.warn("reconnect failed, ".concat(t.code," ").concat(t.message)),this._room.reJoin());break;default:this._emitter.emit(a,{data:t})}}reconnect(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Sk.MAIN;if(this.isReconnecting)return;if(this._reconnectionCount>=Kk){this._log.warn("SDK has tried reconnect signal channel for ".concat(Kk," times, but all failed. please check your network"));let e=new cR({code:aR.SIGNAL_CHANNEL_RECONNECTION_FAILED,message:CN({key:DO})});return SO.emit(yO.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketReconnect",error:e}),void this._emitter.emit(pL,e)}this._reconnectionCount++,this._log.warn("reconnect ".concat(e," [").concat(this._reconnectionCount,"/").concat(Kk,"]"));let t=this.getReconnectionUrl(e);this.emitConnectionStateChanged(_L),this._prevTime<0&&(this._prevTime=iO()),e===Sk.MAIN?(this._socket=new WebSocket(t),this.bindSocket(this._socket)):(this._backupSocket=new WebSocket(t),this.bindSocket(this._backupSocket));let i=BD(this._reconnectionCount);this._reconnectionTimer=setTimeout((()=>{this._log.warn("reconnect ".concat(e," timeout(").concat(i/1e3,"s), try again")),this.clearReconnectionTimer(),this.unbindAndCloseSocket(Sk.MAIN),this.unbindAndCloseSocket(Sk.BACKUP),this.reconnect(e===Sk.MAIN?Sk.BACKUP:Sk.MAIN)}),i)}get isReconnecting(){return-1!==this._reconnectionTimer}getReconnectionUrl(e){let t=e===Sk.MAIN?this._urlWithParam:this._backupUrlWithParam;if(this._signalInfo.tinyId&&-1===t.indexOf("&rc=1")){let{roomId:e,useStringRoomId:i}=this._room;t+="&rc=1&relayInnerIp=".concat(this._signalInfo.relayInnerIp,"&relayOuterIp=").concat(this._signalInfo.relayIp,"&relayPort=").concat(this._signalInfo.relayPort,"&roomId=").concat(e,"&useStringRoomId=").concat(i)}return t}send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected){let i={cmd:e,data:t,userId:this._userId,tinyId:this._signalInfo.tinyId,seq:++this._seq};return this._socketInUse.send(JSON.stringify(i)),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:o,enableLog:a=!0}=e;return new Promise(((e,s)=>{let c=setTimeout((()=>{this.off(n,l);let e=new cR({code:aR.API_CALL_TIMEOUT,message:CN({key:kO,data:{commandDesc:o,command:t}})});a&&this._log.warn(e),s(e)}),r),l=t=>{t.data.seq===d&&(clearTimeout(c),this.off(n,l),e(t))};this.on(n,l);let d=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:r=0,retryTimeout:n=0}=e;return TO({retryFunction:this.sendWaitForResponse,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&&(this._reconnectionCount=0,this.clearReconnectionTimer())}close(){this._log.info("close SignalChannel"),this.clearBackupTimer(),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.unbindAndCloseSocket(Sk.MAIN),this.unbindAndCloseSocket(Sk.BACKUP),this.emitConnectionStateChanged(mL)}on(e,t,i){this._emitter.on(e,t,i)}removeListener(e,t,i){this._emitter.removeListener(e,t,i)}once(e,t,i){this._emitter.once(e,t,i)}off(e,t,i){this._emitter.off(e,t,i)}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this._emitter.emit(uL,{prevState:this._currentState,state:e}),this._currentState=e)}}({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this}),this._networkQuality||(this._networkQuality=new _V({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(_V.EVENT_NETWORK_QUALITY,(e=>{this.emit("network-quality",e)}))),this._signalChannel.on(uL,(e=>{SO.emit(yO.SIGNAL_CONNECTION_STATE_CHANGED,AA({room:this},e)),this.emit("signal-connection-state-changed",e)})),this._signalChannel.on(pL,(e=>{this.reset(),this.emit("error",e)})),this._signalChannel.once(lL,(e=>{this.tinyId=e.signalInfo.tinyId,SO.emit(yO.JOIN_SIGNAL_CONNECTION_END,{room:this})})),this._signalChannel.on(SL.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})),this._signalChannel.on(SL.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})),this._signalChannel.on(SL.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})),this._signalChannel.on(SL.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(wP.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})})),SO.emit(yO.JOIN_SIGNAL_CONNECTION_START,{room:this}),this._signalChannel.connect()}leave(){return wA(this,null,(function*(){try{yield this.doHeartbeat()}catch(Wb){}SO.emit(yO.LEAVE_SEND_CMD,{room:this}),this._log.info("leave() => leaving room"),this._signalChannel.send(yL),this.reset()}))}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach((e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")}))}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){-1===this._heartbeat&&(this._heartbeat=OP.run(TD,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),OP.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return wA(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});if(this.badCaseDetector.resetMonitor(),null==(e=this._signalChannel)||!e.isConnected)return;let r=this._signalChannel.isConnected?function(e){if(dM.has(e)){let t=dM.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc})));return dM.delete(e),t}return[]}(this.userId):[],n=AA({str_sdk_version:jb,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:pk[this._networkType]},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i);SO.emit(yO.HEARTBEAT_REPORT,{room:this,report:n}),this._signalChannel.send(IL,n);let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(o-this._lastHeartBeatTime)),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map((e=>{let{userId:t,srcTinyId:i,flag:r}=e,n=this.remotePublishedUserMap.get(t);return n&&this._changeBigSmallRecords.has(t)&&this.checkSubscribeBigSmallVideo(n),{userId:t,tinyId:i,flag:r}}));SO.emit(yO.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=null),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r}=e,n=new(this.singlePC?IU:nV)({userId:t,tinyId:i,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:r});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,t),this.emit("remote-published",n)}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("sei-message",(e=>{this.emit("sei-message",e)})),e.on("error",(e=>{let i=e.getCode();i!==aR.ICE_TRANSPORT_ERROR&&(i===aR.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",RA(AA({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=OP.run(TD,this.syncUserList.bind(this)))}stopSyncUserListInterval(){OP.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:UL,responseCommand:SL.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 CN({key:lN,data:{signalResponse:SL.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.isOnline||!QL)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(){this.singlePC||this.getAllConnections().forEach((e=>{if(e instanceof XL&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===jk.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return wA(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),wP.uploadEvent({log:"stat-fallback",userId:this.userId}),this._enableSPC=!1,null==(e=this.singlePC)||e.close(),this.singlePC=null,yield this.reJoin(),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new hV({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),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}))}this.remotePublishedUserMap.forEach((e=>{let t=new nV({userId:e.userId,tinyId:e.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:e.flag,remoteAudioTrack:e.remoteAudioTrack,remoteVideoTrack:e.remoteVideoTrack,remoteAuxiliaryTrack:e.remoteAuxiliaryTrack});this.installDownlinkEvents(t,e.userId),this.remotePublishedUserMap.set(e.userId,t),e.isMainStreamSubscribed&&t.subscribe(e.subscribeState,"main"),e.isAuxStreamSubscribed&&t.subscribe(e.subscribeState,"auxiliary")}))}))}destroy(){this._isDestroyed||(super.destroy(),this._joinReject&&(this._joinReject(new cR({code:aR.INVALID_OPERATION,message:CN({key:$O,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return wA(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:xL,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey},responseCommand:SL.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 cR({code:aR.SWITCH_ROLE_FAILED,message:CN({key:KO,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof cR&&e.getCode()===aR.API_CALL_TIMEOUT&&(e=new cR({code:aR.SWITCH_ROLE_FAILED,message:CN({key:JO})})),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 wA(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role)return;SO.emit(yO.PUBLISH_START,{room:this});let e={},i={};this._isPublishing=!0,t.forEach((t=>{!t.mediaTrack||(t instanceof Fw&&(t instanceof Gw?(i.audio=t,this.audioManager.addScreenAudioTrack(t)):(e.audio=t,this.audioManager.addAudioTrack(t))),t instanceof Bw&&(t instanceof Hw&&2===t.mediaType?i.video=t:e.video=t),t.setPublishStarting(this))}));try{let r=DU(e),n=DU(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new EU({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new hV({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",(e=>{this.emit("media-connection-state-changed",RA(AA({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==aR.ICE_TRANSPORT_ERROR&&(t===aR.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")),this._isPublishing=!1,t.forEach((e=>{!e.mediaTrack||(this.localTracks.add(e),e.publish(this))}))}catch(r){throw t.forEach((e=>{let t="error";r.message.includes("timeout")?t="timeout":r.code===aR.API_CALL_ABORTED&&(t="api-call"),e.setPublishStopped(t,"error"===t?r:void 0)})),this._isPublishing=!1,r}}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return wA(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 instanceof Fw&&(t instanceof Gw?i.audio=t:e.audio=t),t instanceof Bw&&(t instanceof Hw&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");DU(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),DU(i)||(this._log.info("unpublish() => aux ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(r){}t.forEach((e=>{!e.mediaTrack||(e.unpublish(),this.localTracks.delete(e))})),0===this.localTracks.size&&!this.audioManager.isMixed&&this.closeUplink("you unpublished")}))}addTrack(e){return this.uplinkConnection&&e.mediaTrack?(e.setPublishStarting(this),this.uplinkConnection.addTrack(e).then((t=>(e.publish(this),t)))):Promise.resolve()}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?this.uplinkConnection.replaceTrack(e).then((t=>{SO.emit(yO.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return wA(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return wA(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";try{let n=AA({},i.subscribeState);t.forEach((e=>{switch(e.mediaType){case 1:n.audio=!0;break;case 4:n.video=!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),SO.emit(yO.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(tV(n),"] prev: [").concat(tV(i.subscribeState),"]")),yield i.subscribe(n,r),i.remoteVideoTrack.setMediaType(n.smallVideo?8:4),t.forEach((e=>e.subscribe())),SO.emit(yO.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(Kb){let i=Kb instanceof cR?Kb.getCode():aR.UNKNOWN,n=Kb;throw Kb instanceof cR?i===aR.REMOTE_STREAM_NOT_EXIST&&(n=new cR({code:aR.API_CALL_ABORTED,message:CN({key:TN,data:{message:Kb.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new cR({code:i,message:CN({key:WO,data:{message:Kb.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 wA(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(Kb){this._log.warn("unsubscribe() => failed ".concat(Kb))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),SO.emit(yO.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,OP.clearTask(this._audioVolumeIntervalId),void(this._audioVolumeIntervalId=null);e=Math.floor(Math.max(e,100)),SO.emit(yO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&(OP.clearTask(this._audioVolumeIntervalId),this._audioVolumeIntervalId=null),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=OP.run(SD,(()=>{var e,t;let i=[];if(null!=(e=this.uplinkConnection)&&e.localMainAudioTrack){let e=Math.floor(100*this.uplinkConnection.localMainAudioTrack.getAudioLevel());i.push({userId:"",volume:e})}null==(t=this.remotePublishedUserMap)||t.forEach((e=>{if(e.muteState.hasAudio){let t=Math.floor(100*e.remoteAudioTrack.getAudioLevel());i.push({userId:e.userId,volume:t})}})),this.emit("audio-volume",i)}),{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return wA(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t.audio.bytesSent,packetsSent:t.audio.packetsSent}}return e}))}getLocalVideoStats(){return wA(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:t,packetsSent:i,framesEncoded:r,framesSent:n,frameWidth:o,frameHeight:a}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:i,framesEncoded:r,framesSent:n,frameWidth:o,frameHeight:a}}return e}))}getTransportStats(){return wA(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 wA(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 wA(this,null,(function*(){let e={};for(let[t,i]of this.remotePublishedUserMap)i.muteState.hasAudio&&(e[t]=i.remoteAudioTrack.stat);return e}))}setProxyServer(e){if(CU(e)){if(!e.startsWith("wss://"))throw new cR({code:aR.INVALID_PARAMETER,message:"invalid websocket url"});this.proxy_ws=e}else if(AU(e)){let{websocketProxy:t,loggerProxy:i}=e;t&&(this.proxy_ws=t),i&&Xb(i)}}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(hR.getTurnServer(e)))):hR.isPlainObject(e)&&i.push(hR.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:LL,data:e,timeout:5e3,responseCommand:SL.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:VL,data:e,timeout:5e3,responseCommand:SL.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?NL:wL,data:e,timeout:5e3,responseCommand:t?SL.START_PUBLISH_TENCENT_CDN_RES:SL.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?PL:ML,data:e,timeout:5e3,responseCommand:t?SL.STOP_PUBLISH_TENCENT_CDN_RES:SL.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}getIceServers(){return 0===this._turnServers.length&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=hR.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):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())||{}}reset(){this.mixTranscodeManager.reset(),this.publishCDNManager.reset(),this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this._signalChannel&&(this._log.info("destroying SignalChannel"),this._signalChannel.close()),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null)}checkSubscribeBigSmallVideo(e){return wA(this,null,(function*(){let t=null==e?void 0:e.muteState.hasSmall,i=null==e?void 0:e.muteState.hasVideo;if(!t&&!i||!e.isBigStreamSubscribed&&!e.isSmallStreamSubscribed)return;let r=e.getUserId(),n=this._changeBigSmallRecords.get(r)||{},{subscribeState:o}=e,{options:a,isSubscribing:s,reSubscribeCount:c}=n;if(a.video&&o.video||a.smallVideo&&o.smallVideo&&t||s)return;let l={audio:o.audio,auxiliary:o.auxiliary,video:a.video,smallVideo:a.smallVideo};if(t&&e.isBigStreamSubscribed||e.isSmallStreamSubscribed)try{a&&!s&&c>=1&&(n.isSubscribing=!0,n.reSubscribeCount=c-1,!t&&e.isSmallStreamSubscribed&&(l.video=!0,l.smallVideo=!1),yield null==e?void 0:e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info("change [".concat(r,"] to ").concat(l.smallVideo?"small":"big"," video successfully. count ").concat(fD-n.reSubscribeCount,".")),n.isSubscribing=!1,n.reSubscribeCount=fD)}catch(d){this._log.info("change [".concat(r,"] to ").concat(l.smallVideo?"small":"big"," video failed. count ").concat(fD-n.reSubscribeCount,".")),n.isSubscribing=!1,0===c&&this._changeBigSmallRecords.delete(r)}}))}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:fD};this._changeBigSmallRecords.set(t.userId,i),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big"))}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(CU(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!RU(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new cR({code:aR.INVALID_PARAMETER,message:CN({key:LO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!RU(e.streamId)){if(!(CU(e.streamId)&&String(e.streamId)&&String(e.streamId).length<=64))throw new cR({code:aR.INVALID_PARAMETER,message:CN({key:VO})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_streamid_main=e.streamId}if(!RU(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new cR({code:aR.INVALID_PARAMETER,message:CN({key:UO})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!RU(e.userDefinePushArgs)){if(!(CU(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new cR({code:aR.INVALID_PARAMETER,message:CN({key:xO})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}DU(t)||(this._businessInfo=JSON.stringify(t))}startPlugin(e,t){return wA(this,null,(function*(){var i,r;"AudioMixer"===e&&(yield this.audioManager.addMusicSource(t),this.isJoined&&(null==(i=this.uplinkConnection)?void 0:i.localMainAudioTrack)&&(yield this.replaceTrack(null==(r=this.uplinkConnection)?void 0:r.localMainAudioTrack)))}))}updatePlugin(e,t){return wA(this,null,(function*(){"AudioMixer"===e&&(yield this.audioManager.updateMusicSource(t))}))}stopPlugin(e,t){return wA(this,null,(function*(){"AudioMixer"===e&&(yield this.audioManager.removeMusicSource(t))}))}sendSEI(e,t){var i;null==(i=this.uplinkConnection)||i.sendSEI(e,t)}};return OA([QV(["left",iU.INIT],"joined"),Vw((e=>{let t=new class{constructor(){this._set=new Set,SO.on(yO.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))}};return function(i,r,n){return wA(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 cR({code:aR.INVALID_OPERATION,message:CN({key:FO})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new cR({code:aR.INVALID_OPERATION,message:CN({key:XO,data:this.userId})});t.add({room:this,roomId:o}),this._log.info("Join() => joining room: ".concat(o," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),this.role=21===i.role?"audience":"anchor",SO.emit(yO.JOIN_START,{room:this,roomId:o,params:i}),this.checkSystemResult=yield bO.checkSystemRequirementsInternal(),this.checkDestroy();let a=hR.getEnv();a||(a=ck.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Ek.OLD_CLOUD_LADDER)?a=ck.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Ek.WEBRTC)&&(a=ck.WEBRTC))),wP.setConfig({env:a,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),sL.call(this);let{isH264EncodeSupported:s,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!bO.isWebRTCSupported()||!s&&!c)throw new cR({code:aR.NOT_SUPPORTED,message:CN({key:nN})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!hR.getEnv()&&(yield this.schedule(o,n,Hb));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=hR.performanceNow(),SO.emit(yO.JOIN_SUCCESS,{room:this}),wP.uploadEvent({log:"stat-conv-".concat(Number(Vb),"-").concat(location.hostname),userId:this.userId}),t}catch(l){throw t.delete({room:this,roomId:o}),SO.emit(yO.JOIN_FAILED,{room:this,error:l}),l}}))}}))],OU.prototype,"join",1),OA([QV("joined","left",{ignoreError:!0}),Vw((e=>function(){return wA(this,null,(function*(){SO.emit(yO.LEAVE_START,{room:this}),yield e.call(this),SO.emit(yO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),function(e){return function(t,i,r){let n=r.value;return r.value=function(){var t,i;let r=[];for(var o=arguments.length,a=new Array(o),s=0;s<o;s++)a[s]=arguments[s];return null==(t=xV.get(this))||t.forEach((e=>r.push(e))),null==(i=FV.get(this))||i.forEach((e=>e.forEach((e=>r.push(e))))),r.forEach((t=>{t.reject(new cR({code:aR.API_CALL_ABORTED,message:e}))})),xV.delete(this),FV.delete(this),n.apply(this,a)},r}}("leave room"),TV({fnName:"publish",validateArgs:!1}),TV({fnName:"unsubscribe",validateArgs:!1})],OU.prototype,"leave",1),OA([BV(),gV({settings:{retries:Wk,timeout:e=>BD(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))}})],OU.prototype,"publish",1),OA([TV({fnName:"publish",callback(){for(var e,t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];0===this.localTracks.size&&(null==(e=this.uplinkConnection)||e.close("you unpublished"),this.uplinkConnection=null,i.forEach((e=>e.setPublishStopped("api-call"))))}}),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=xV.get(this);if(o){let t=o.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 cR({code:aR.API_CALL_ABORTED,message:e})),!1)}));xV.set(this,t)}return n.apply(this,i)},r}}("api-call"),BV()],OU.prototype,"unpublish",1),OA([jV((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),gV({settings:{retries:Wk,timeout:e=>BD(e)},onError(e,t,i){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),i(e))}})],OU.prototype,"subscribe",1),OA([TV({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")}))}}),jV((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],OU.prototype,"unsubscribe",1),aL.create=aL._create.bind(aL,OU),aL}));
|