trtc-sdk-v5 5.0.2-beta.2 → 5.0.2
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 -24
- package/package.json +1 -1
- package/trtc.esm.js +38 -35
- 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))},R=function(e){return e&&e.Math==Math&&e},A=R("object"==typeof globalThis&&globalThis)||R("object"==typeof window&&window)||R("object"==typeof self&&self)||R("object"==typeof e&&e)||function(){return this}()||Function("return this")(),C={},b={get exports(){return C},set exports(e){C=e}},k=A,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,O="__core-js_shared__",N=A[O]||D(O,{}),M=N;(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))},j=F,B=s({}.hasOwnProperty),H=Object.hasOwn||function(e,t){return B(j(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=A,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=C,se=H,ce=K,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,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,Re=TypeError,Ae=function(e){if(Ee(e))return e;throw Re(Ie(e)+" is not an object")},Ce={},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=A.document,Oe=Pe(De)&&Pe(De.createElement),Ne=function(e){return Oe?De.createElement(e):{}},Me=Ne,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=A,je=ve,Be=function(e){return je(e)?e:void 0},He=function(e,t){return arguments.length<2?Be(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=Ae,It=vt,Rt=TypeError,At=Object.defineProperty,Ct=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=Ct(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(Et(e),t=It(t),Et(i),St)try{return At(e,t,i)}catch(r){}if("get"in i||"set"in i)throw Rt("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Pt=Math.ceil,Dt=Math.floor,Ot=Math.trunc||function(e){var t=+e;return(t>0?Dt:Pt)(t)},Nt=function(e){var t=+e;return t!=t||0===t?0:Ot(t)},Mt=Nt,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=Nt,Ft=Math.min,jt=function(e){return e>0?Ft(Ut(e),9007199254740991):0},Bt=jt,Ht=function(e){return Bt(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=Ae,li=I,di=ni;Ce.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=C("keys"),_i=function(e){return mi[e]||(mi[e]=pi(e))},fi=Ae,gi=Ce,vi=ti,Ti=qt,Si=hi,yi=Ne,Ei=_i("IE_PROTO"),Ii=function(){},Ri=function(e){return"<script>"+e+"</"+"script>"},Ai=function(e){e.write(Ri("")),e.close();var t=e.parentWindow.Object;return e=null,t},Ci=function(){try{ui=new ActiveXObject("htmlfile")}catch(r){}var e,t;Ci="undefined"!=typeof document?document.domain&&ui?Ai(ui):((t=yi("iframe")).style.display="none",Si.appendChild(t),t.src=String("javascript:"),(e=t.contentWindow.document).open(),e.write(Ri("document.F=Object")),e.close(),e.F):Ai(ui);for(var i=vi.length;i--;)delete Ci.prototype[vi[i]];return Ci()};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=Ci(),void 0===t?i:gi.f(i,t)},ki=me,wi=bi,Pi=we.f,Di=ki("unscopables"),Oi=Array.prototype;null==Oi[Di]&&Pi(Oi,Di,{configurable:!0,value:wi(null)});var Ni,Mi,Li,xi=function(e){Oi[Di][e]=!0},Vi={},Ui=ve,Fi=A.WeakMap,ji=Ui(Fi)&&/native code/.test(String(Fi)),Bi=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},Hi=we,Gi=Bi,Wi=be?function(e,t,i){return Hi.f(e,t,Gi(1,i))}:function(e,t,i){return e[t]=i,e},Ji=ji,zi=A,Ki=ye,qi=Wi,Qi=H,Yi=N,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,Ni=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,Ni=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:Ni,get:Mi,has:Li,enforce:function(e){return Li(e)?Mi(e):Ni(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=Bi,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,Rr=yr&&Object.getOwnPropertyDescriptor,Ar=Er(Ir,"name"),Cr={EXISTS:Ar,PROPER:Ar&&"something"===function(){}.name,CONFIGURABLE:Ar&&(!yr||yr&&Rr(Ir,"name").configurable)},br=ve,kr=N,wr=s(Function.toString);br(kr.inspectSource)||(kr.inspectSource=function(e){return wr(e)});var Pr=kr.inspectSource,Dr=s,Or=t,Nr=ve,Mr=H,Lr=be,xr=Cr.CONFIGURABLE,Vr=Pr,Ur=nr.enforce,Fr=nr.get,jr=String,Br=Object.defineProperty,Hr=Dr("".slice),Gr=Dr("".replace),Wr=Dr([].join),Jr=Lr&&!Or((function(){return 8!==Br((function(){}),"length",{value:8}).length})),zr=String(String).split("String"),Kr=Sr.exports=function(e,t,i){"Symbol("===Hr(jr(t),0,7)&&(t="["+Gr(jr(t),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Mr(e,"name")||xr&&e.name!==t)&&(Lr?Br(e,"name",{value:t,configurable:!0}):e.name=t),Jr&&i&&Mr(i,"arity")&&e.length!==i.arity&&Br(e,"length",{value:i.arity});try{i&&Mr(i,"constructor")&&i.constructor?Lr&&Br(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 Nr(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=Ae,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==An||i!=Rn&&(Tn(t)?vn(t):!!t)},En=yn.normalize=function(e){return String(e).replace(Sn,".").toLowerCase()},In=yn.data={},Rn=yn.NATIVE="N",An=yn.POLYFILL="P",Cn=yn,bn=A,kn=or.f,wn=Wi,Pn=$r,Dn=P,On=gn,Nn=Cn,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],!Nn(c?r:s+(l?".":"#")+r,e.forced)&&void 0!==n){if(typeof o==typeof n)continue;On(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,jn=_i("IE_PROTO"),Bn=Object,Hn=Bn.prototype,Gn=Fn?Bn.getPrototypeOf:function(e){var t=Un(e);if(xn(t,jn))return t[jn];var i=t.constructor;return Vn(i)&&t instanceof i?i.prototype:t instanceof Bn?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=Bi,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=Ae,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,Ro=Gn,Ao=To,Co=io,bo=Wi,ko=$r,wo=Vi,Po=Cr.PROPER,Do=Cr.CONFIGURABLE,Oo=$n.IteratorPrototype,No=$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(!No&&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],_=!No&&m||d(n),f="Array"==t&&p.entries||m;if(f&&(s=Ro(f.call(new e)))!==Object.prototype&&s.next&&(Ro(s)!==Oo&&(Ao?Ao(s,Oo):Eo(s[Mo])||ko(s,Mo,Uo)),Co(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)(No||h||!(l in p))&&ko(p,l,c[l]);else So({target:t,proto:!0,forced:No||h},c);return p[Mo]!==_&&ko(p,Mo,_,{name:n}),wo[t]=_,c},jo=function(e,t){return{value:e,done:t}},Bo=I,Ho=xi,Go=Vi,Wo=nr,Jo=we.f,zo=Fo,Ko=jo,qo=be,Qo="Array Iterator",Yo=Wo.set,Xo=Wo.getterFor(Qo),$o=zo(Array,"Array",(function(e,t){Yo(this,{type:Qo,target:Bo(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(Mx){}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=Ne("span").classList,ia=ta&&ta.constructor&&ta.constructor.prototype,ra=ia===Object.prototype?void 0:ia,na=A,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(Mx){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(Mx){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}})},Ra=Ge,Aa=TypeError,Ca=function(e,t){if(Ra(t,e))return e;throw Aa("Incorrect invocation")},ba={};ba[me("toStringTag")]="z";var ka="[object z]"===String(ba),wa=ve,Pa=u,Da=me("toStringTag"),Oa=Object,Na="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(Mx){}}(t=Oa(e),Da))?i:Na?Pa(t):"Object"==(r=Pa(t))&&wa(t.callee)?"Arguments":r},La=s,xa=t,Va=ve,Ua=Ma,Fa=Pr,ja=function(){},Ba=[],Ha=He("Reflect","construct"),Ga=/^\s*(?:class|function)\b/,Wa=La(Ga.exec),Ja=!Ga.exec(ja),za=function(e){if(!Va(e))return!1;try{return Ha(ja,Ba,e),!0}catch(Mx){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(Mx){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=Ae,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),Rs=A,As=hs,Cs=Ts,bs=ve,ks=H,ws=t,Ps=hi,Ds=Ss,Os=Ne,Ns=Es,Ms=Is,Ls=_a,xs=Rs.setImmediate,Vs=Rs.clearImmediate,Us=Rs.process,Fs=Rs.Dispatch,js=Rs.Function,Bs=Rs.MessageChannel,Hs=Rs.String,Gs=0,Ws={},Js="onreadystatechange";ws((function(){qa=Rs.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){Rs.postMessage(Hs(e),qa.protocol+"//"+qa.host)};xs&&Vs||(xs=function(e){Ns(arguments.length,1);var t=bs(e)?e:js(e),i=Ds(arguments,1);return Ws[++Gs]=function(){As(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))}:Bs&&!Ms?(Xa=(Ya=new Bs).port2,Ya.port1.onmessage=qs,Qa=Cs(Xa.postMessage,Xa)):Rs.addEventListener&&bs(Rs.postMessage)&&!Rs.importScripts&&qa&&"file:"!==qa.protocol&&!ws(Qs)?(Qa=Qs,Rs.addEventListener("message",qs,!1)):Qa=Js in Os("script")?function(e){Ps.appendChild(Os("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=A,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(Mx){throw yc.head&&$s(),Mx}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,Rc=function(e){try{return{error:!1,value:e()}}catch(Mx){return{error:!0,value:Mx}}},Ac=A.Promise,Cc="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,bc=!Cc&&!_a&&"object"==typeof window&&"object"==typeof document,kc=A,wc=Ac,Pc=ve,Dc=Cn,Oc=Pr,Nc=me,Mc=bc,Lc=Cc,xc=te;wc&&wc.prototype;var Vc=Nc("species"),Uc=!1,Fc=Pc(kc.PromiseRejectionEvent),jc=Dc("Promise",(function(){var e=Oc(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})),Bc={CONSTRUCTOR:jc,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=A,$c=Ue,Zc=$r,el=To,tl=io,il=Ia,rl=et,nl=ve,ol=ye,al=Ca,sl=ss,cl=Ys.set,ll=Ic,dl=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(Mx){}},ul=Rc,hl=rc,pl=nr,ml=Ac,_l=Hc,fl="Promise",gl=Bc.CONSTRUCTOR,vl=Bc.REJECTION_EVENT,Tl=Bc.SUBCLASSING,Sl=pl.getterFor(fl),yl=pl.set,El=ml&&ml.prototype,Il=ml,Rl=El,Al=Xc.TypeError,Cl=Xc.document,bl=Xc.process,kl=_l.f,wl=kl,Pl=!!(Cl&&Cl.createEvent&&Xc.dispatchEvent),Dl="unhandledrejection",Ol=function(e){var t;return!(!ol(e)||!nl(t=e.then))&&t},Nl=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(Al("Promise-chain cycle")):(r=Ol(i))?$c(r,i,c,l):c(i)):l(o)}catch(Mx){d&&!n&&d.exit(),l(Mx)}},Ml=function(e,t){e.notified||(e.notified=!0,ll((function(){for(var i,r=e.reactions;i=r.get();)Nl(i,e);e.notified=!1,t&&!e.rejection&&xl(e)})))},Ll=function(e,t,i){var r,n;Pl?((r=Cl.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)}},jl=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Ml(e,!0))},Bl=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw Al("Promise can't be resolved itself");var r=Ol(t);r?ll((function(){var i={done:!1};try{$c(r,t,Fl(Bl,i,e),Fl(jl,i,e))}catch(Mx){jl(i,Mx,e)}})):(e.value=t,e.state=1,Ml(e,!1))}catch(Mx){jl({done:!1},Mx,e)}}};if(gl&&(Rl=(Il=function(e){al(this,Rl),rl(e),$c(zc,this);var t=Sl(this);try{e(Fl(Bl,t),Fl(jl,t))}catch(Mx){jl(t,Mx)}}).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(Rl,"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(){Nl(r,i)})),r.promise})),Kc=function(){var e=new zc,t=Sl(e);this.promise=e,this.resolve=Fl(Bl,t),this.reject=Fl(jl,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(Mx){}el&&el(El,Rl)}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=Ae,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=Ae,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(Mx){n=!0,r=Mx}if("throw"===t)throw i;if(n)throw r;return ad(r),i},ld=Ts,dd=Ue,ud=Ae,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(Mx){vd(r,"throw",Mx)}if("object"==typeof s&&s&&_d(yd,s))return s}return new Sd(!1)},Id=me("iterator"),Rd=!1;try{var Ad=0,Cd={next:function(){return{done:!!Ad++}},return:function(){Rd=!0}};Cd[Id]=function(){return this},Array.from(Cd,(function(){throw 2}))}catch(Mx){}var bd=function(e,t){if(!t&&!Rd)return!1;var i=!1;try{var r={};r[Id]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(Mx){}return i},kd=Ac,wd=Bc.CONSTRUCTOR||!bd((function(e){kd.all(e).then(void 0,(function(){}))})),Pd=Ue,Dd=et,Od=Hc,Nd=Rc,Md=Ed;Mn({target:"Promise",stat:!0,forced:wd},{all:function(e){var t=this,i=Od.f(t),r=i.resolve,n=i.reject,o=Nd((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=Bc.CONSTRUCTOR,Vd=Ac,Ud=He,Fd=ve,jd=$r,Bd=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;Bd.catch!==Hd&&jd(Bd,"catch",Hd,{unsafe:!0})}var Gd=Ue,Wd=et,Jd=Hc,zd=Rc,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:Bc.CONSTRUCTOR},{reject:function(e){var t=Qd.f(this);return qd(t.reject,void 0,e),t.promise}});var Yd=Ae,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=Bc.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=A.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),Ru=cu("".slice);pu(fu,"description",{configurable:!0,get:function(){var e=Su(this);if(lu(gu,e))return"";var t=yu(e),i=Tu?Ru(t,7,-1):Iu(t,Eu,"$1");return""===i?void 0:i}}),au({global:!0,constructor:!0,forced:!0},{Symbol:vu})}var Au=Ae,Cu=function(){var e=Au(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=A.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=wu||bu((function(){var e=ku("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),Ou={BROKEN_CARET:Du,MISSED_STICKY:Pu,UNSUPPORTED_Y:wu},Nu=t,Mu=A.RegExp,Lu=Nu((function(){var e=Mu(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),xu=t,Vu=A.RegExp,Uu=xu((function(){var e=Vu("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Fu=Ue,ju=s,Bu=ou,Hu=Cu,Gu=Ou,Wu=bi,Ju=nr.get,zu=Lu,Ku=Uu,qu=C("native-string-replace",String.prototype.replace),Qu=RegExp.prototype.exec,Yu=Qu,Xu=ju("".charAt),$u=ju("".indexOf),Zu=ju("".replace),eh=ju("".slice),th=function(){var e=/a/,t=/b*/g;return Fu(Qu,e,"a"),Fu(Qu,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),ih=Gu.BROKEN_CARET,rh=void 0!==/()??/.exec("")[1];(th||rh||ih||zu||Ku)&&(Yu=function(e){var t,i,r,n,o,a,s,c=this,l=Ju(c),d=Bu(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=Fu(Yu,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=ih&&c.sticky,m=Fu(Hu,c),_=c.source,f=0,g=d;if(p&&(m=Zu(m,"y",""),-1===$u(m,"g")&&(m+="g"),g=eh(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Xu(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),rh&&(i=new RegExp("^"+_+"$(?!\\s)",m)),th&&(r=c.lastIndex),n=Fu(Qu,p?i:c,g),p?n?(n.input=eh(n.input,f),n[0]=eh(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:th&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),rh&&n&&n.length>1&&Fu(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=Wu(null),o=0;o<h.length;o++)a[(s=h[o])[0]]=n[s[1]];return n});var nh=Yu;Mn({target:"RegExp",proto:!0,forced:/./.exec!==nh},{exec:nh});var oh=et,ah=F,sh=f,ch=Ht,lh=TypeError,dh=function(e){return function(t,i,r,n){oh(i);var o=ah(t),a=sh(o),s=ch(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 lh("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}},uh={left:dh(!1),right:dh(!0)},hh=t,ph=function(e,t){var i=[][e];return!!i&&hh((function(){i.call(null,t||function(){return 1},1)}))},mh=uh.left;Mn({target:"Array",proto:!0,forced:!_a&&te>79&&te<83||!ph("reduce")},{reduce:function(e){var t=arguments.length;return mh(this,e,t,t>1?arguments[1]:void 0)}});var _h=u,fh=Array.isArray||function(e){return"Array"==_h(e)},gh=fh,vh=$a,Th=ye,Sh=me("species"),yh=Array,Eh=function(e){var t;return gh(e)&&(t=e.constructor,(vh(t)&&(t===yh||gh(t.prototype))||Th(t)&&null===(t=t[Sh]))&&(t=void 0)),void 0===t?yh:t},Ih=Ts,Rh=f,Ah=F,Ch=Ht,bh=function(e,t){return new(Eh(e))(0===t?0:t)},kh=s([].push),wh=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=Ah(c),_=Rh(m),f=Ih(l,d),g=Ch(_),v=0,T=u||bh,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:kh(S,h)}else switch(e){case 4:return!1;case 7:kh(S,h)}return o?-1:r||n?n:S}},Ph={forEach:wh(0),map:wh(1),filter:wh(2),some:wh(3),every:wh(4),find:wh(5),findIndex:wh(6),filterReject:wh(7)},Dh=Ph.forEach,Oh=ph("forEach")?[].forEach:function(e){return Dh(this,e,arguments.length>1?arguments[1]:void 0)},Nh=A,Mh=ea,Lh=ra,xh=Oh,Vh=Wi,Uh=function(e){if(e&&e.forEach!==xh)try{Vh(e,"forEach",xh)}catch(Mx){e.forEach=xh}};for(var Fh in Mh)Mh[Fh]&&Uh(Nh[Fh]&&Nh[Fh].prototype);Uh(Lh);var jh=Kt.includes,Bh=xi;Mn({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)}}),Bh("includes");var Hh=_s,Gh=$r,Wh=nh,Jh=t,zh=me,Kh=Wi,qh=zh("species"),Qh=RegExp.prototype,Yh=s,Xh=Nt,$h=ou,Zh=S,ep=Yh("".charAt),tp=Yh("".charCodeAt),ip=Yh("".slice),rp=function(e){return function(t,i){var r,n,o=$h(Zh(t)),a=Xh(i),s=o.length;return a<0||a>=s?e?"":void 0:(r=tp(o,a))<55296||r>56319||a+1===s||(n=tp(o,a+1))<56320||n>57343?e?ep(o,a):r:e?ip(o,a,a+2):n-56320+(r-55296<<10)+65536}},np={codeAt:rp(!1),charAt:rp(!0)},op=np.charAt,ap=s,sp=F,cp=Math.floor,lp=ap("".charAt),dp=ap("".replace),up=ap("".slice),hp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,pp=/\$([$&'`]|\d{1,2})/g,mp=Ue,_p=Ae,fp=ve,gp=u,vp=nh,Tp=TypeError,Sp=hs,yp=Ue,Ep=s,Ip=function(e,t,i,r){var n=zh(e),o=!Jh((function(){var t={};return t[n]=function(){return 7},7!=""[e](t)})),a=o&&!Jh((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=Hh(/./[n]),c=t(n,""[e],(function(e,t,i,r,n){var a=Hh(e),c=t.exec;return c===Wh||c===Qh.exec?o&&!n?{done:!0,value:s(t,i,r)}:{done:!0,value:a(i,t,r)}:{done:!1}}));Gh(String.prototype,e,c[0]),Gh(Qh,n,c[1])}r&&Kh(Qh[n],"sham",!0)},Rp=t,Ap=Ae,Cp=ve,bp=g,kp=Nt,wp=jt,Pp=ou,Dp=S,Op=function(e,t,i){return t+(i?op(e,t).length:1)},Np=rt,Mp=function(e,t,i,r,n,o){var a=i+e.length,s=r.length,c=pp;return void 0!==n&&(n=sp(n),c=hp),dp(o,c,(function(o,c){var l;switch(lp(c,0)){case"$":return"$";case"&":return e;case"`":return up(t,0,i);case"'":return up(t,a);case"<":l=n[up(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>s){var u=cp(d/10);return 0===u?o:u<=s?void 0===r[u-1]?lp(c,1):r[u-1]+lp(c,1):o}l=r[d-1]}return void 0===l?"":l}))},Lp=function(e,t){var i=e.exec;if(fp(i)){var r=mp(i,e,t);return null!==r&&_p(r),r}if("RegExp"===gp(e))return mp(vp,e,t);throw Tp("RegExp#exec called on incompatible receiver")},xp=me("replace"),Vp=Math.max,Up=Math.min,Fp=Ep([].concat),jp=Ep([].push),Bp=Ep("".indexOf),Hp=Ep("".slice),Gp="$0"==="a".replace(/./,"$0"),Wp=!!/./[xp]&&""===/./[xp]("a","$0"),Jp=!Rp((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));Ip("replace",(function(e,t,i){var r=Wp?"$":"$0";return[function(e,i){var r=Dp(this),n=bp(e)?void 0:Np(e,xp);return n?yp(n,e,r,i):yp(t,Pp(r),e,i)},function(e,n){var o=Ap(this),a=Pp(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=Cp(n);c||(n=Pp(n));var l=o.global;if(l){var d=o.unicode;o.lastIndex=0}for(var u=[];;){var h=Lp(o,a);if(null===h)break;if(jp(u,h),!l)break;""===Pp(h[0])&&(o.lastIndex=Op(a,wp(o.lastIndex),d))}for(var p,m="",_=0,f=0;f<u.length;f++){for(var g=Pp((h=u[f])[0]),v=Vp(Up(kp(h.index),a.length),0),T=[],S=1;S<h.length;S++)jp(T,void 0===(p=h[S])?p:String(p));var y=h.groups;if(c){var E=Fp([g],T,v,a);void 0!==y&&jp(E,y);var I=Pp(Sp(n,void 0,E))}else I=Mp(g,a,v,T,y,n);v>=_&&(m+=Hp(a,_,v)+I,_=v+g.length)}return m+Hp(a,_)}]}),!Jp||!Gp||Wp);var zp=ve,Kp=ye,qp=To,Qp=function(e,t,i){var r,n;return qp&&zp(r=t.constructor)&&r!==i&&Kp(n=r.prototype)&&n!==i.prototype&&qp(e,n),e},Yp=ye,Xp=u,$p=me("match"),Zp=Ue,em=H,tm=Ge,im=Cu,rm=RegExp.prototype,nm=we.f,om=be,am=A,sm=s,cm=Cn,lm=Qp,dm=Wi,um=Zr.f,hm=Ge,pm=function(e){var t;return Yp(e)&&(void 0!==(t=e[$p])?!!t:"RegExp"==Xp(e))},mm=ou,_m=function(e){var t=e.flags;return void 0!==t||"flags"in rm||em(e,"flags")||!tm(rm,e)?t:Zp(im,e)},fm=Ou,gm=function(e,t,i){i in e||nm(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},vm=$r,Tm=t,Sm=H,ym=nr.enforce,Em=Ia,Im=Lu,Rm=Uu,Am=me("match"),Cm=am.RegExp,bm=Cm.prototype,km=am.SyntaxError,wm=sm(bm.exec),Pm=sm("".charAt),Dm=sm("".replace),Om=sm("".indexOf),Nm=sm("".slice),Mm=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,Lm=/a/g,xm=/a/g,Vm=new Cm(Lm)!==Lm,Um=fm.MISSED_STICKY,Fm=fm.UNSUPPORTED_Y,jm=om&&(!Vm||Um||Im||Rm||Tm((function(){return xm[Am]=!1,Cm(Lm)!=Lm||Cm(xm)==xm||"/a/i"!=Cm(Lm,"i")})));if(cm("RegExp",jm)){for(var Bm=function(e,t){var i,r,n,o,a,s,c=hm(bm,this),l=pm(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Bm)return e;if((l||hm(bm,e))&&(e=e.source,d&&(t=_m(h))),e=void 0===e?"":mm(e),t=void 0===t?"":mm(t),h=e,Im&&"dotAll"in Lm&&(r=!!t&&Om(t,"s")>-1)&&(t=Dm(t,/s/g,"")),i=t,Um&&"sticky"in Lm&&(n=!!t&&Om(t,"y")>-1)&&Fm&&(t=Dm(t,/y/g,"")),Rm&&(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=Pm(e,r)))t+=Pm(e,++r);else if("]"===t)s=!1;else if(!s)switch(!0){case"["===t:s=!0;break;case"("===t:wm(Mm,Nm(e,r+1))&&(r+=2,c=!0),n+=t,l++;continue;case">"===t&&c:if(""===d||Sm(a,d))throw new km("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=lm(Cm(e,t),c?this:bm,Bm),(r||n||u.length)&&(s=ym(a),r&&(s.dotAll=!0,s.raw=Bm(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=Pm(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+Pm(e,++r);return n}(e),i)),n&&(s.sticky=!0),u.length&&(s.groups=u)),e!==h)try{dm(a,"source",""===h?"(?:)":h)}catch(Mx){}return a},Hm=um(Cm),Gm=0;Hm.length>Gm;)gm(Bm,Cm,Hm[Gm++]);bm.constructor=Bm,Bm.prototype=bm,vm(am,"RegExp",Bm,{constructor:!0})}Em("RegExp");var Wm="\t\n\v\f\r \u2028\u2029\ufeff",Jm=S,zm=ou,Km=Wm,qm=s("".replace),Qm=RegExp("^["+Km+"]+"),Ym=RegExp("(^|[^"+Km+"])["+Km+"]+$"),Xm=function(e){return function(t){var i=zm(Jm(t));return 1&e&&(i=qm(i,Qm,"")),2&e&&(i=qm(i,Ym,"$1")),i}},$m={start:Xm(1),end:Xm(2),trim:Xm(3)},Zm=Cr.PROPER,e_=t,t_=Wm,i_=$m.trim;Mn({target:"String",proto:!0,forced:function(e){return e_((function(){return!!t_[e]()||"
"!=="
"[e]()||Zm&&t_[e].name!==e}))}("trim")},{trim:function(){return i_(this)}});var r_=Ue;Mn({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return r_(URL.prototype.toString,this)}});var n_=Mn,o_=Ac,a_=t,s_=He,c_=ve,l_=ss,d_=Zd,u_=$r,h_=o_&&o_.prototype;if(n_({target:"Promise",proto:!0,real:!0,forced:!!o_&&a_((function(){h_.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=l_(this,s_("Promise")),i=c_(e);return this.then(i?function(i){return d_(t,e()).then((function(){return i}))}:e,i?function(i){return d_(t,e()).then((function(){throw i}))}:e)}}),c_(o_)){var p_=s_("Promise").prototype.finally;h_.finally!==p_&&u_(h_,"finally",p_,{unsafe:!0})}var m_=Nt,__=ou,f_=S,g_=RangeError,v_=s,T_=jt,S_=ou,y_=S,E_=v_((function(e){var t=__(f_(this)),i="",r=m_(e);if(r<0||Infinity==r)throw g_("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i})),I_=v_("".slice),R_=Math.ceil,A_=function(e){return function(t,i,r){var n,o,a=S_(y_(t)),s=T_(i),c=a.length,l=void 0===r?" ":S_(r);return s<=c||""==l?a:((o=E_(l,R_((n=s-c)/l.length))).length>n&&(o=I_(o,0,n)),e?a+o:o+a)}},C_={start:A_(!1),end:A_(!0)},b_=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(q),k_=C_.start;Mn({target:"String",proto:!0,forced:b_},{padStart:function(e){return k_(this,e,arguments.length>1?arguments[1]:void 0)}});var w_=t,P_=be,D_=me("iterator"),O_=!w_((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[D_]||"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})),N_=$r,M_=function(e,t,i){for(var r in t)N_(e,r,t[r],i);return e},L_=vt,x_=we,V_=Bi,U_=function(e,t,i){var r=L_(t);r in e?x_.f(e,r,V_(0,i)):e[r]=i},F_=Vt,j_=Ht,B_=U_,H_=Array,G_=Math.max,W_=function(e,t,i){for(var r=j_(e),n=F_(t,r),o=F_(void 0===i?r:i,r),a=H_(G_(o-n,0)),s=0;n<o;n++,s++)B_(a,s,e[n]);return a.length=s,a},J_=W_,z_=Math.floor,K_=function(e,t){var i=e.length,r=z_(i/2);return i<8?q_(e,t):Q_(e,K_(J_(e,0,r),t),K_(J_(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},Q_=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},Y_=K_,X_=Mn,$_=A,Z_=Ue,ef=s,tf=be,rf=O_,nf=$r,of=va,af=M_,sf=io,cf=lo,lf=nr,df=Ca,uf=ve,hf=H,pf=Ts,mf=Ma,_f=Ae,ff=ye,gf=ou,vf=bi,Tf=Bi,Sf=nd,yf=Xl,Ef=Es,If=Y_,Rf=me("iterator"),Af="URLSearchParams",Cf="URLSearchParamsIterator",bf=lf.set,kf=lf.getterFor(Af),wf=lf.getterFor(Cf),Pf=Object.getOwnPropertyDescriptor,Df=function(e){if(!tf)return $_[e];var t=Pf($_,e);return t&&t.value},Of=Df("fetch"),Nf=Df("Request"),Mf=Df("Headers"),Lf=Nf&&Nf.prototype,xf=Mf&&Mf.prototype,Vf=$_.RegExp,Uf=$_.TypeError,Ff=$_.decodeURIComponent,jf=$_.encodeURIComponent,Bf=ef("".charAt),Hf=ef([].join),Gf=ef([].push),Wf=ef("".replace),Jf=ef([].shift),zf=ef([].splice),Kf=ef("".split),qf=ef("".slice),Qf=/\+/g,Yf=Array(4),Xf=function(e){return Yf[e-1]||(Yf[e-1]=Vf("((?:%[\\da-f]{2}){"+e+"})","gi"))},$f=function(e){try{return Ff(e)}catch(Mx){return e}},Zf=function(e){var t=Wf(e,Qf," "),i=4;try{return Ff(t)}catch(Mx){for(;i;)t=Wf(t,Xf(i--),$f);return t}},eg=/[!'()~]|%20/g,tg={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},ig=function(e){return tg[e]},rg=function(e){return Wf(jf(e),eg,ig)},ng=cf((function(e,t){bf(this,{type:Cf,iterator:Sf(kf(e).entries),kind:t})}),"Iterator",(function(){var e=wf(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),og=function(e){this.entries=[],this.url=null,void 0!==e&&(ff(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===Bf(e,0)?qf(e,1):e:gf(e)))};og.prototype={type:Af,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,a,s,c=yf(e);if(c)for(i=(t=Sf(e,c)).next;!(r=Z_(i,t)).done;){if(o=(n=Sf(_f(r.value))).next,(a=Z_(o,n)).done||(s=Z_(o,n)).done||!Z_(o,n).done)throw Uf("Expected sequence with length 2");Gf(this.entries,{key:gf(a.value),value:gf(s.value)})}else for(var l in e)hf(e,l)&&Gf(this.entries,{key:l,value:gf(e[l])})},parseQuery:function(e){if(e)for(var t,i,r=Kf(e,"&"),n=0;n<r.length;)(t=r[n++]).length&&(i=Kf(t,"="),Gf(this.entries,{key:Zf(Jf(i)),value:Zf(Hf(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],Gf(i,rg(e.key)+"="+rg(e.value));return Hf(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var ag=function(){df(this,sg);var e=arguments.length>0?arguments[0]:void 0,t=bf(this,new og(e));tf||(this.length=t.entries.length)},sg=ag.prototype;if(af(sg,{append:function(e,t){Ef(arguments.length,2);var i=kf(this);Gf(i.entries,{key:gf(e),value:gf(t)}),tf||this.length++,i.updateURL()},delete:function(e){Ef(arguments.length,1);for(var t=kf(this),i=t.entries,r=gf(e),n=0;n<i.length;)i[n].key===r?zf(i,n,1):n++;tf||(this.length=i.length),t.updateURL()},get:function(e){Ef(arguments.length,1);for(var t=kf(this).entries,i=gf(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){Ef(arguments.length,1);for(var t=kf(this).entries,i=gf(e),r=[],n=0;n<t.length;n++)t[n].key===i&&Gf(r,t[n].value);return r},has:function(e){Ef(arguments.length,1);for(var t=kf(this).entries,i=gf(e),r=0;r<t.length;)if(t[r++].key===i)return!0;return!1},set:function(e,t){Ef(arguments.length,1);for(var i,r=kf(this),n=r.entries,o=!1,a=gf(e),s=gf(t),c=0;c<n.length;c++)(i=n[c]).key===a&&(o?zf(n,c--,1):(o=!0,i.value=s));o||Gf(n,{key:a,value:s}),tf||(this.length=n.length),r.updateURL()},sort:function(){var e=kf(this);If(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=kf(this).entries,r=pf(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 ng(this,"keys")},values:function(){return new ng(this,"values")},entries:function(){return new ng(this,"entries")}},{enumerable:!0}),nf(sg,Rf,sg.entries,{name:"entries"}),nf(sg,"toString",(function(){return kf(this).serialize()}),{enumerable:!0}),tf&&of(sg,"size",{get:function(){return kf(this).entries.length},configurable:!0,enumerable:!0}),sf(ag,Af),X_({global:!0,constructor:!0,forced:!rf},{URLSearchParams:ag}),!rf&&uf(Mf)){var cg=ef(xf.has),lg=ef(xf.set),dg=function(e){if(ff(e)){var t,i=e.body;if(mf(i)===Af)return t=e.headers?new Mf(e.headers):new Mf,cg(t,"content-type")||lg(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),vf(e,{body:Tf(0,gf(i)),headers:Tf(0,t)})}return e};if(uf(Of)&&X_({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return Of(e,arguments.length>1?dg(arguments[1]):{})}}),uf(Nf)){var ug=function(e){return df(this,Lf),new Nf(e,arguments.length>1?dg(arguments[1]):{})};Lf.constructor=ug,ug.prototype=Lf,X_({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:ug})}}var hg={URLSearchParams:ag,getState:kf},pg=np.charAt,mg=ou,_g=nr,fg=Fo,gg=jo,vg="String Iterator",Tg=_g.set,Sg=_g.getterFor(vg);fg(String,"String",(function(e){Tg(this,{type:vg,string:mg(e),index:0})}),(function(){var e,t=Sg(this),i=t.string,r=t.index;return r>=i.length?gg(void 0,!0):(e=pg(i,r),t.index+=e.length,gg(e,!1))}));var yg,Eg=be,Ig=s,Rg=Ue,Ag=t,Cg=ni,bg=rn,kg=ar,wg=F,Pg=f,Dg=Object.assign,Og=Object.defineProperty,Ng=Ig([].concat),Mg=!Dg||Ag((function(){if(Eg&&1!==Dg({b:1},Dg(Og({},"a",{enumerable:!0,get:function(){Og(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!=Dg({},e)[i]||Cg(Dg({},t)).join("")!=r}))?function(e,t){for(var i=wg(e),r=arguments.length,n=1,o=bg.f,a=kg.f;r>n;)for(var s,c=Pg(arguments[n++]),l=o?Ng(Cg(c),o(c)):Cg(c),d=l.length,u=0;d>u;)s=l[u++],Eg&&!Rg(a,c,s)||(i[s]=c[s]);return i}:Dg,Lg=Ae,xg=cd,Vg=Ts,Ug=Ue,Fg=F,jg=function(e,t,i,r){try{return r?t(Lg(i)[0],i[1]):t(i)}catch(Mx){xg(e,"throw",Mx)}},Bg=Jl,Hg=$a,Gg=Ht,Wg=U_,Jg=nd,zg=Xl,Kg=Array,qg=s,Qg=2147483647,Yg=/[^\0-\u007E]/,Xg=/[.\u3002\uFF0E\uFF61]/g,$g="Overflow: input needs wider integers to process",Zg=RangeError,ev=qg(Xg.exec),tv=Math.floor,iv=String.fromCharCode,rv=qg("".charCodeAt),nv=qg([].join),ov=qg([].push),av=qg("".replace),sv=qg("".split),cv=qg("".toLowerCase),lv=function(e){return e+22+75*(e<26)},dv=function(e,t,i){var r=0;for(e=i?tv(e/700):e>>1,e+=tv(e/t);e>455;)e=tv(e/35),r+=36;return tv(r+36*e/(e+38))},uv=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=rv(e,i++);if(n>=55296&&n<=56319&&i<r){var o=rv(e,i++);56320==(64512&o)?ov(t,((1023&n)<<10)+(1023&o)+65536):(ov(t,n),i--)}else ov(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&&ov(t,iv(r));var c=t.length,l=c;for(c&&ov(t,"-");l<n;){var d=Qg;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>tv((Qg-a)/u))throw Zg($g);for(a+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++a>Qg)throw Zg($g);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;ov(t,iv(lv(m+_%f))),h=tv(_/f),p+=36}ov(t,iv(lv(h))),s=dv(a,u,l==c),a=0,l++}}a++,o++}return nv(t,"")},hv=Mn,pv=be,mv=O_,_v=A,fv=Ts,gv=s,vv=$r,Tv=va,Sv=Ca,yv=H,Ev=Mg,Iv=function(e){var t=Fg(e),i=Hg(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=Vg(n,r>2?arguments[2]:void 0));var a,s,c,l,d,u,h=zg(t),p=0;if(!h||this===Kg&&Bg(h))for(a=Gg(t),s=i?new this(a):Kg(a);a>p;p++)u=o?n(t[p],p):t[p],Wg(s,p,u);else for(d=(l=Jg(t,h)).next,s=i?new this:[];!(c=Ug(d,l)).done;p++)u=o?jg(l,n,[c.value,p],!0):c.value,Wg(s,p,u);return s.length=p,s},Rv=W_,Av=np.codeAt,Cv=function(e){var t,i,r=[],n=sv(av(cv(e),Xg,"."),".");for(t=0;t<n.length;t++)i=n[t],ov(r,ev(Yg,i)?"xn--"+uv(i):i);return nv(r,".")},bv=ou,kv=io,wv=Es,Pv=hg,Dv=nr,Ov=Dv.set,Nv=Dv.getterFor("URL"),Mv=Pv.URLSearchParams,Lv=Pv.getState,xv=_v.URL,Vv=_v.TypeError,Uv=_v.parseInt,Fv=Math.floor,jv=Math.pow,Bv=gv("".charAt),Hv=gv(/./.exec),Gv=gv([].join),Wv=gv(1..toString),Jv=gv([].pop),zv=gv([].push),Kv=gv("".replace),qv=gv([].shift),Qv=gv("".split),Yv=gv("".slice),Xv=gv("".toLowerCase),$v=gv([].unshift),Zv="Invalid scheme",eT="Invalid host",tT="Invalid port",iT=/[a-z]/i,rT=/[\d+-.a-z]/i,nT=/\d/,oT=/^0x/i,aT=/^[0-7]+$/,sT=/^\d+$/,cT=/^[\da-f]+$/i,lT=/[\0\t\n\r #%/:<>?@[\\\]^|]/,dT=/[\0\t\n\r #/:<>?@[\\\]^|]/,uT=/^[\u0000-\u0020]+/,hT=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,pT=/[\t\n\r]/g,mT=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)$v(t,e%256),e=Fv(e/256);return Gv(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+=Wv(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},_T={},fT=Ev({},_T,{" ":1,'"':1,"<":1,">":1,"`":1}),gT=Ev({},fT,{"#":1,"?":1,"{":1,"}":1}),vT=Ev({},gT,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),TT=function(e,t){var i=Av(e,0);return i>32&&i<127&&!yv(t,e)?e:encodeURIComponent(e)},ST={ftp:21,file:null,http:80,https:443,ws:80,wss:443},yT=function(e,t){var i;return 2==e.length&&Hv(iT,Bv(e,0))&&(":"==(i=Bv(e,1))||!t&&"|"==i)},ET=function(e){var t;return e.length>1&&yT(Yv(e,0,2))&&(2==e.length||"/"===(t=Bv(e,2))||"\\"===t||"?"===t||"#"===t)},IT=function(e){return"."===e||"%2e"===Xv(e)},RT={},AT={},CT={},bT={},kT={},wT={},PT={},DT={},OT={},NT={},MT={},LT={},xT={},VT={},UT={},FT={},jT={},BT={},HT={},GT={},WT={},JT=function(e,t,i){var r,n,o,a=bv(e);if(t){if(n=this.parse(a))throw Vv(n);this.searchParams=null}else{if(void 0!==i&&(r=new JT(i,!0)),n=this.parse(a,null,r))throw Vv(n);(o=Lv(new Mv)).bindURL(this),this.searchParams=o}};JT.prototype={type:"URL",parse:function(e,t,i){var r,n,o,a,s,c=this,l=t||RT,d=0,u="",h=!1,p=!1,m=!1;for(e=bv(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=Kv(e,uT,""),e=Kv(e,hT,"$1")),e=Kv(e,pT,""),r=Iv(e);d<=r.length;){switch(n=r[d],l){case RT:if(!n||!Hv(iT,n)){if(t)return Zv;l=CT;continue}u+=Xv(n),l=AT;break;case AT:if(n&&(Hv(rT,n)||"+"==n||"-"==n||"."==n))u+=Xv(n);else{if(":"!=n){if(t)return Zv;u="",l=CT,d=0;continue}if(t&&(c.isSpecial()!=yv(ST,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&ST[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?l=VT:c.isSpecial()&&i&&i.scheme==c.scheme?l=bT:c.isSpecial()?l=DT:"/"==r[d+1]?(l=kT,d++):(c.cannotBeABaseURL=!0,zv(c.path,""),l=HT)}break;case CT:if(!i||i.cannotBeABaseURL&&"#"!=n)return Zv;if(i.cannotBeABaseURL&&"#"==n){c.scheme=i.scheme,c.path=Rv(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=WT;break}l="file"==i.scheme?VT:wT;continue;case bT:if("/"!=n||"/"!=r[d+1]){l=wT;continue}l=OT,d++;break;case kT:if("/"==n){l=NT;break}l=BT;continue;case wT:if(c.scheme=i.scheme,n==yg)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Rv(i.path),c.query=i.query;else if("/"==n||"\\"==n&&c.isSpecial())l=PT;else if("?"==n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Rv(i.path),c.query="",l=GT;else{if("#"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Rv(i.path),c.path.length--,l=BT;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Rv(i.path),c.query=i.query,c.fragment="",l=WT}break;case PT:if(!c.isSpecial()||"/"!=n&&"\\"!=n){if("/"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=BT;continue}l=NT}else l=OT;break;case DT:if(l=OT,"/"!=n||"/"!=Bv(u,d+1))continue;d++;break;case OT:if("/"!=n&&"\\"!=n){l=NT;continue}break;case NT:if("@"==n){h&&(u="%40"+u),h=!0,o=Iv(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!=f||m){var g=TT(f,vT);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n==yg||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(h&&""==u)return"Invalid authority";d-=Iv(u).length+1,u="",l=MT}else u+=n;break;case MT:case LT:if(t&&"file"==c.scheme){l=FT;continue}if(":"!=n||p){if(n==yg||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(c.isSpecial()&&""==u)return eT;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(a=c.parseHost(u))return a;if(u="",l=jT,t)return;continue}"["==n?p=!0:"]"==n&&(p=!1),u+=n}else{if(""==u)return eT;if(a=c.parseHost(u))return a;if(u="",l=xT,t==LT)return}break;case xT:if(!Hv(nT,n)){if(n==yg||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()||t){if(""!=u){var v=Uv(u,10);if(v>65535)return tT;c.port=c.isSpecial()&&v===ST[c.scheme]?null:v,u=""}if(t)return;l=jT;continue}return tT}u+=n;break;case VT:if(c.scheme="file","/"==n||"\\"==n)l=UT;else{if(!i||"file"!=i.scheme){l=BT;continue}if(n==yg)c.host=i.host,c.path=Rv(i.path),c.query=i.query;else if("?"==n)c.host=i.host,c.path=Rv(i.path),c.query="",l=GT;else{if("#"!=n){ET(Gv(Rv(r,d),""))||(c.host=i.host,c.path=Rv(i.path),c.shortenPath()),l=BT;continue}c.host=i.host,c.path=Rv(i.path),c.query=i.query,c.fragment="",l=WT}}break;case UT:if("/"==n||"\\"==n){l=FT;break}i&&"file"==i.scheme&&!ET(Gv(Rv(r,d),""))&&(yT(i.path[0],!0)?zv(c.path,i.path[0]):c.host=i.host),l=BT;continue;case FT:if(n==yg||"/"==n||"\\"==n||"?"==n||"#"==n){if(!t&&yT(u))l=BT;else if(""==u){if(c.host="",t)return;l=jT}else{if(a=c.parseHost(u))return a;if("localhost"==c.host&&(c.host=""),t)return;u="",l=jT}continue}u+=n;break;case jT:if(c.isSpecial()){if(l=BT,"/"!=n&&"\\"!=n)continue}else if(t||"?"!=n)if(t||"#"!=n){if(n!=yg&&(l=BT,"/"!=n))continue}else c.fragment="",l=WT;else c.query="",l=GT;break;case BT:if(n==yg||"/"==n||"\\"==n&&c.isSpecial()||!t&&("?"==n||"#"==n)){if(".."===(s=Xv(s=u))||"%2e."===s||".%2e"===s||"%2e%2e"===s?(c.shortenPath(),"/"==n||"\\"==n&&c.isSpecial()||zv(c.path,"")):IT(u)?"/"==n||"\\"==n&&c.isSpecial()||zv(c.path,""):("file"==c.scheme&&!c.path.length&&yT(u)&&(c.host&&(c.host=""),u=Bv(u,0)+":"),zv(c.path,u)),u="","file"==c.scheme&&(n==yg||"?"==n||"#"==n))for(;c.path.length>1&&""===c.path[0];)qv(c.path);"?"==n?(c.query="",l=GT):"#"==n&&(c.fragment="",l=WT)}else u+=TT(n,gT);break;case HT:"?"==n?(c.query="",l=GT):"#"==n?(c.fragment="",l=WT):n!=yg&&(c.path[0]+=TT(n,_T));break;case GT:t||"#"!=n?n!=yg&&("'"==n&&c.isSpecial()?c.query+="%27":c.query+="#"==n?"%23":TT(n,_T)):(c.fragment="",l=WT);break;case WT:n!=yg&&(c.fragment+=TT(n,fT))}d++}},parseHost:function(e){var t,i,r;if("["==Bv(e,0)){if("]"!=Bv(e,e.length-1))return eT;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 Bv(e,u)};if(":"==h()){if(":"!=Bv(e,1))return;u+=2,d=++l}for(;h();){if(8==l)return;if(":"!=h()){for(t=i=0;i<4&&Hv(cT,h());)t=16*t+Uv(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(!Hv(nT,h()))return;for(;Hv(nT,h());){if(o=Uv(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}(Yv(e,1,-1)),!t)return eT;this.host=t}else if(this.isSpecial()){if(e=Cv(e),Hv(lT,e))return eT;if(t=function(e){var t,i,r,n,o,a,s,c=Qv(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"==Bv(n,0)&&(o=Hv(oT,n)?16:8,n=Yv(n,8==o?1:2)),""===n)a=0;else{if(!Hv(10==o?sT:8==o?aT:cT,n))return e;a=Uv(n,o)}zv(i,a)}for(r=0;r<t;r++)if(a=i[r],r==t-1){if(a>=jv(256,5-t))return null}else if(a>255)return null;for(s=Jv(i),r=0;r<i.length;r++)s+=i[r]*jv(256,3-r);return s}(e),null===t)return eT;this.host=t}else{if(Hv(dT,e))return eT;for(t="",i=Iv(e),r=0;r<i.length;r++)t+=TT(i[r],_T);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return yv(ST,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&yT(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+=mT(n),null!==o&&(l+=":"+o)):"file"==t&&(l+="//"),l+=e.cannotBeABaseURL?a[0]:a.length?"/"+Gv(a,"/"):"",null!==s&&(l+="?"+s),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw Vv(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new zT(e.path[0]).origin}catch(Mx){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+mT(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(bv(e)+":",RT)},getUsername:function(){return this.username},setUsername:function(e){var t=Iv(bv(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=TT(t[i],vT)}},getPassword:function(){return this.password},setPassword:function(e){var t=Iv(bv(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=TT(t[i],vT)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?mT(e):mT(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,MT)},getHostname:function(){var e=this.host;return null===e?"":mT(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,LT)},getPort:function(){var e=this.port;return null===e?"":bv(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=bv(e))?this.port=null:this.parse(e,xT))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+Gv(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,jT))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=bv(e))?this.query=null:("?"==Bv(e,0)&&(e=Yv(e,1)),this.query="",this.parse(e,GT)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=bv(e))?("#"==Bv(e,0)&&(e=Yv(e,1)),this.fragment="",this.parse(e,WT)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var zT=function(e){var t=Sv(this,KT),i=wv(arguments.length,1)>1?arguments[1]:void 0,r=Ov(t,new JT(e,!1,i));pv||(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())},KT=zT.prototype,qT=function(e,t){return{get:function(){return Nv(this)[e]()},set:t&&function(e){return Nv(this)[t](e)},configurable:!0,enumerable:!0}};if(pv&&(Tv(KT,"href",qT("serialize","setHref")),Tv(KT,"origin",qT("getOrigin")),Tv(KT,"protocol",qT("getProtocol","setProtocol")),Tv(KT,"username",qT("getUsername","setUsername")),Tv(KT,"password",qT("getPassword","setPassword")),Tv(KT,"host",qT("getHost","setHost")),Tv(KT,"hostname",qT("getHostname","setHostname")),Tv(KT,"port",qT("getPort","setPort")),Tv(KT,"pathname",qT("getPathname","setPathname")),Tv(KT,"search",qT("getSearch","setSearch")),Tv(KT,"searchParams",qT("getSearchParams")),Tv(KT,"hash",qT("getHash","setHash"))),vv(KT,"toJSON",(function(){return Nv(this).serialize()}),{enumerable:!0}),vv(KT,"toString",(function(){return Nv(this).serialize()}),{enumerable:!0}),xv){var QT=xv.createObjectURL,YT=xv.revokeObjectURL;QT&&vv(zT,"createObjectURL",fv(QT,xv)),YT&&vv(zT,"revokeObjectURL",fv(YT,xv))}kv(zT,"URL"),hv({global:!0,constructor:!0,forced:!mv,sham:!pv},{URL:zT});var XT=Ye,$T=TypeError,ZT=q.match(/firefox\/(\d+)/i),eS=!!ZT&&+ZT[1],tS=/MSIE|Trident/.test(q),iS=q.match(/AppleWebKit\/(\d+)\./),rS=!!iS&&+iS[1],nS=Mn,oS=s,aS=et,sS=F,cS=Ht,lS=function(e,t){if(!delete e[t])throw $T("Cannot delete property "+XT(t)+" of "+XT(e))},dS=ou,uS=t,hS=Y_,pS=ph,mS=eS,_S=tS,fS=te,gS=rS,vS=[],TS=oS(vS.sort),SS=oS(vS.push),yS=uS((function(){vS.sort(void 0)})),ES=uS((function(){vS.sort(null)})),IS=pS("sort"),RS=!uS((function(){if(fS)return fS<70;if(!(mS&&mS>3)){if(_S)return!0;if(gS)return gS<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++)vS.push({k:t+r,v:i})}for(vS.sort((function(e,t){return t.v-e.v})),r=0;r<vS.length;r++)t=vS[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));nS({target:"Array",proto:!0,forced:yS||!ES||!IS||!RS},{sort:function(e){void 0!==e&&aS(e);var t=sS(this);if(RS)return void 0===e?TS(t):TS(t,e);var i,r,n=[],o=cS(t);for(r=0;r<o;r++)r in t&&SS(n,t[r]);for(hS(n,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:dS(t)>dS(i)?1:-1}}(e)),i=cS(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)lS(t,r++);return t}});var AS="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,CS=Nt,bS=jt,kS=RangeError,wS=function(e){if(void 0===e)return 0;var t=CS(e),i=bS(t);if(t!==i)throw kS("Wrong length or index");return i},PS=Array,DS=Math.abs,OS=Math.pow,NS=Math.floor,MS=Math.log,LS=Math.LN2,xS={pack:function(e,t,i){var r,n,o,a=PS(i),s=8*i-t-1,c=(1<<s)-1,l=c>>1,d=23===t?OS(2,-24)-OS(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=DS(e))!=e||Infinity===e?(n=e!=e?1:0,r=c):(r=NS(MS(e)/LS),e*(o=OS(2,-r))<1&&(r--,o*=2),(e+=r+l>=1?d/o:d*OS(2,1-l))*o>=2&&(r++,o/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*o-1)*OS(2,t),r+=l):(n=e*OS(2,l-1)*OS(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+=OS(2,t),d-=a}return(l?-1:1)*i*OS(2,d-t)}},VS=F,US=Vt,FS=Ht,jS=function(e){for(var t=VS(this),i=FS(t),r=arguments.length,n=US(r>1?arguments[1]:void 0,i),o=r>2?arguments[2]:void 0,a=void 0===o?i:US(o,i);a>n;)t[n++]=e;return t},BS=A,HS=s,GS=be,WS=AS,JS=Cr,zS=Wi,KS=va,qS=M_,QS=t,YS=Ca,XS=Nt,$S=jt,ZS=wS,ey=xS,ty=Gn,iy=To,ry=Zr.f,ny=jS,oy=W_,ay=io,sy=nr,cy=JS.PROPER,ly=JS.CONFIGURABLE,dy="ArrayBuffer",uy="DataView",hy="Wrong index",py=sy.getterFor(dy),my=sy.getterFor(uy),_y=sy.set,fy=BS.ArrayBuffer,gy=fy,vy=gy&&gy.prototype,Ty=BS.DataView,Sy=Ty&&Ty.prototype,yy=Object.prototype,Ey=BS.Array,Iy=BS.RangeError,Ry=HS(ny),Ay=HS([].reverse),Cy=ey.pack,by=ey.unpack,ky=function(e){return[255&e]},wy=function(e){return[255&e,e>>8&255]},Py=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},Dy=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},Oy=function(e){return Cy(e,23,4)},Ny=function(e){return Cy(e,52,8)},My=function(e,t,i){KS(e.prototype,t,{configurable:!0,get:function(){return i(this)[t]}})},Ly=function(e,t,i,r){var n=ZS(i),o=my(e);if(n+t>o.byteLength)throw Iy(hy);var a=o.bytes,s=n+o.byteOffset,c=oy(a,s,s+t);return r?c:Ay(c)},xy=function(e,t,i,r,n,o){var a=ZS(i),s=my(e);if(a+t>s.byteLength)throw Iy(hy);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(WS){var Vy=cy&&fy.name!==dy;if(QS((function(){fy(1)}))&&QS((function(){new fy(-1)}))&&!QS((function(){return new fy,new fy(1.5),new fy(NaN),1!=fy.length||Vy&&!ly})))Vy&&ly&&zS(fy,"name",dy);else{(gy=function(e){return YS(this,vy),new fy(ZS(e))}).prototype=vy;for(var Uy,Fy=ry(fy),jy=0;Fy.length>jy;)(Uy=Fy[jy++])in gy||zS(gy,Uy,fy[Uy]);vy.constructor=gy}iy&&ty(Sy)!==yy&&iy(Sy,yy);var By=new Ty(new gy(2)),Hy=HS(Sy.setInt8);By.setInt8(0,2147483648),By.setInt8(1,2147483649),!By.getInt8(0)&&By.getInt8(1)||qS(Sy,{setInt8:function(e,t){Hy(this,e,t<<24>>24)},setUint8:function(e,t){Hy(this,e,t<<24>>24)}},{unsafe:!0})}else vy=(gy=function(e){YS(this,vy);var t=ZS(e);_y(this,{type:dy,bytes:Ry(Ey(t),0),byteLength:t}),GS||(this.byteLength=t,this.detached=!1)}).prototype,Sy=(Ty=function(e,t,i){YS(this,Sy),YS(e,vy);var r=py(e),n=r.byteLength,o=XS(t);if(o<0||o>n)throw Iy("Wrong offset");if(o+(i=void 0===i?n-o:$S(i))>n)throw Iy("Wrong length");_y(this,{type:uy,buffer:e,byteLength:i,byteOffset:o,bytes:r.bytes}),GS||(this.buffer=e,this.byteLength=i,this.byteOffset=o)}).prototype,GS&&(My(gy,"byteLength",py),My(Ty,"buffer",my),My(Ty,"byteLength",my),My(Ty,"byteOffset",my)),qS(Sy,{getInt8:function(e){return Ly(this,1,e)[0]<<24>>24},getUint8:function(e){return Ly(this,1,e)[0]},getInt16:function(e){var t=Ly(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=Ly(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return Dy(Ly(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return Dy(Ly(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return by(Ly(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return by(Ly(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){xy(this,1,e,ky,t)},setUint8:function(e,t){xy(this,1,e,ky,t)},setInt16:function(e,t){xy(this,2,e,wy,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){xy(this,2,e,wy,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){xy(this,4,e,Py,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){xy(this,4,e,Py,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){xy(this,4,e,Oy,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){xy(this,8,e,Ny,t,arguments.length>2?arguments[2]:void 0)}});ay(gy,dy),ay(Ty,uy);var Gy={ArrayBuffer:gy,DataView:Ty},Wy=Mn,Jy=_s,zy=t,Ky=Ae,qy=Vt,Qy=jt,Yy=ss,Xy=Gy.ArrayBuffer,$y=Gy.DataView,Zy=$y.prototype,eE=Jy(Xy.prototype.slice),tE=Jy(Zy.getUint8),iE=Jy(Zy.setUint8);Wy({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:zy((function(){return!new Xy(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(eE&&void 0===t)return eE(Ky(this),e);for(var i=Ky(this).byteLength,r=qy(e,i),n=qy(void 0===t?i:t,i),o=new(Yy(this,Xy))(Qy(n-r)),a=new $y(this),s=new $y(o),c=0;r<n;)iE(s,c++,tE(a,r++));return o}});var rE=Mn,nE=fh,oE=s([].reverse),aE=[1,2];rE({target:"Array",proto:!0,forced:String(aE)===String(aE.reverse())},{reverse:function(){return nE(this)&&(this.length=this.length),oE(this)}});var sE=Ia,cE="ArrayBuffer",lE=Gy.ArrayBuffer;Mn({global:!0,constructor:!0,forced:A.ArrayBuffer!==lE},{ArrayBuffer:lE}),sE(cE);var dE,uE,hE,pE={},mE={get exports(){return pE},set exports(e){pE=e}},_E=AS,fE=be,gE=A,vE=ve,TE=ye,SE=H,yE=Ma,EE=Ye,IE=Wi,RE=$r,AE=va,CE=Ge,bE=Gn,kE=To,wE=me,PE=K,DE=nr.enforce,OE=nr.get,NE=gE.Int8Array,ME=NE&&NE.prototype,LE=gE.Uint8ClampedArray,xE=LE&&LE.prototype,VE=NE&&bE(NE),UE=ME&&bE(ME),FE=Object.prototype,jE=gE.TypeError,BE=wE("toStringTag"),HE=PE("TYPED_ARRAY_TAG"),GE="TypedArrayConstructor",WE=_E&&!!kE&&"Opera"!==yE(gE.opera),JE=!1,zE={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},KE={BigInt64Array:8,BigUint64Array:8},qE=function(e){var t=bE(e);if(TE(t)){var i=OE(t);return i&&SE(i,GE)?i.TypedArrayConstructor:qE(t)}},QE=function(e){if(!TE(e))return!1;var t=yE(e);return SE(zE,t)||SE(KE,t)};for(dE in zE)(hE=(uE=gE[dE])&&uE.prototype)?DE(hE).TypedArrayConstructor=uE:WE=!1;for(dE in KE)(hE=(uE=gE[dE])&&uE.prototype)&&(DE(hE).TypedArrayConstructor=uE);if((!WE||!vE(VE)||VE===Function.prototype)&&(VE=function(){throw jE("Incorrect invocation")},WE))for(dE in zE)gE[dE]&&kE(gE[dE],VE);if((!WE||!UE||UE===FE)&&(UE=VE.prototype,WE))for(dE in zE)gE[dE]&&kE(gE[dE].prototype,UE);if(WE&&bE(xE)!==UE&&kE(xE,UE),fE&&!SE(UE,BE))for(dE in JE=!0,AE(UE,BE,{configurable:!0,get:function(){return TE(this)?this[HE]:void 0}}),zE)gE[dE]&&IE(gE[dE],HE,dE);var YE={NATIVE_ARRAY_BUFFER_VIEWS:WE,TYPED_ARRAY_TAG:JE&&HE,aTypedArray:function(e){if(QE(e))return e;throw jE("Target is not a typed array")},aTypedArrayConstructor:function(e){if(vE(e)&&(!kE||CE(VE,e)))return e;throw jE(EE(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(fE){if(i)for(var n in zE){var o=gE[n];if(o&&SE(o.prototype,e))try{delete o.prototype[e]}catch(Mx){try{o.prototype[e]=t}catch(a){}}}UE[e]&&!i||RE(UE,e,i?t:WE&&ME[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(fE){if(kE){if(i)for(r in zE)if((n=gE[r])&&SE(n,e))try{delete n[e]}catch(Mx){}if(VE[e]&&!i)return;try{return RE(VE,e,i?t:WE&&VE[e]||t)}catch(Mx){}}for(r in zE)!(n=gE[r])||n[e]&&!i||RE(n,e,t)}},getTypedArrayConstructor:qE,isView:function(e){if(!TE(e))return!1;var t=yE(e);return"DataView"===t||SE(zE,t)||SE(KE,t)},isTypedArray:QE,TypedArray:VE,TypedArrayPrototype:UE},XE=A,$E=t,ZE=bd,eI=YE.NATIVE_ARRAY_BUFFER_VIEWS,tI=XE.ArrayBuffer,iI=XE.Int8Array,rI=!eI||!$E((function(){iI(1)}))||!$E((function(){new iI(-1)}))||!ZE((function(e){new iI,new iI(null),new iI(1.5),new iI(e)}),!0)||$E((function(){return 1!==new iI(new tI(2),1,void 0).length})),nI=ye,oI=Math.floor,aI=Number.isInteger||function(e){return!nI(e)&&isFinite(e)&&oI(e)===e},sI=Nt,cI=RangeError,lI=function(e){var t=sI(e);if(t<0)throw cI("The argument can't be less than 0");return t},dI=RangeError,uI=function(e,t){var i=lI(e);if(i%t)throw dI("Wrong offset");return i},hI=Ma,pI=_t,mI=TypeError,_I=function(e){var t=pI(e,"number");if("number"==typeof t)throw mI("Can't convert number to bigint");return BigInt(t)},fI=Ts,gI=Ue,vI=is,TI=F,SI=Ht,yI=nd,EI=Xl,II=Jl,RI=function(e){var t=hI(e);return"BigInt64Array"==t||"BigUint64Array"==t},AI=YE.aTypedArrayConstructor,CI=_I,bI=Mn,kI=A,wI=Ue,PI=be,DI=rI,OI=YE,NI=Gy,MI=Ca,LI=Bi,xI=Wi,VI=aI,UI=jt,FI=wS,jI=uI,BI=vt,HI=H,GI=Ma,WI=ye,JI=qe,zI=bi,KI=Ge,qI=To,QI=Zr.f,YI=function(e){var t,i,r,n,o,a,s,c,l=vI(this),d=TI(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=EI(d);if(m&&!II(m))for(c=(s=yI(d,m)).next,d=[];!(a=gI(c,s)).done;)d.push(a.value);for(p&&u>2&&(h=fI(h,arguments[2])),i=SI(d),r=new(AI(l))(i),n=RI(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?CI(o):+o;return r},XI=Ph.forEach,$I=Ia,ZI=va,eR=we,tR=or,iR=Qp,rR=nr.get,nR=nr.set,oR=nr.enforce,aR=eR.f,sR=tR.f,cR=Math.round,lR=kI.RangeError,dR=NI.ArrayBuffer,uR=dR.prototype,hR=NI.DataView,pR=OI.NATIVE_ARRAY_BUFFER_VIEWS,mR=OI.TYPED_ARRAY_TAG,_R=OI.TypedArray,fR=OI.TypedArrayPrototype,gR=OI.aTypedArrayConstructor,vR=OI.isTypedArray,TR="BYTES_PER_ELEMENT",SR="Wrong length",yR=function(e,t){gR(e);for(var i=0,r=t.length,n=new e(r);r>i;)n[i]=t[i++];return n},ER=function(e,t){ZI(e,t,{configurable:!0,get:function(){return rR(this)[t]}})},IR=function(e){var t;return KI(uR,e)||"ArrayBuffer"==(t=GI(e))||"SharedArrayBuffer"==t},RR=function(e,t){return vR(e)&&!JI(t)&&t in e&&VI(+t)&&t>=0},AR=function(e,t){return t=BI(t),RR(e,t)?LI(2,e[t]):sR(e,t)},CR=function(e,t,i){return t=BI(t),!(RR(e,t)&&WI(i)&&HI(i,"value"))||HI(i,"get")||HI(i,"set")||i.configurable||HI(i,"writable")&&!i.writable||HI(i,"enumerable")&&!i.enumerable?aR(e,t,i):(e[t]=i.value,e)};PI?(pR||(tR.f=AR,eR.f=CR,ER(fR,"buffer"),ER(fR,"byteOffset"),ER(fR,"byteLength"),ER(fR,"length")),bI({target:"Object",stat:!0,forced:!pR},{getOwnPropertyDescriptor:AR,defineProperty:CR}),mE.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,a="set"+e,s=kI[n],c=s,l=c&&c.prototype,d={},u=function(e,t){aR(e,t,{get:function(){return function(e,t){var i=rR(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=rR(e);i&&(n=(n=cR(n))<0?0:n>255?255:255&n),o.view[a](t*r+o.byteOffset,n,!0)}(this,t,e)},enumerable:!0})};pR?DI&&(c=t((function(e,t,i,n){return MI(e,l),iR(WI(t)?IR(t)?void 0!==n?new s(t,jI(i,r),n):void 0!==i?new s(t,jI(i,r)):new s(t):vR(t)?yR(c,t):wI(YI,c,t):new s(FI(t)),e,c)})),qI&&qI(c,_R),XI(QI(s),(function(e){e in c||xI(c,e,s[e])})),c.prototype=l):(c=t((function(e,t,i,n){MI(e,l);var o,a,s,d=0,h=0;if(WI(t)){if(!IR(t))return vR(t)?yR(c,t):wI(YI,c,t);o=t,h=jI(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw lR(SR);if((a=p-h)<0)throw lR(SR)}else if((a=UI(n)*r)+h>p)throw lR(SR);s=a/r}else s=FI(t),o=new dR(a=s*r);for(nR(e,{buffer:o,byteOffset:h,byteLength:a,length:s,view:new hR(o)});d<s;)u(e,d++)})),qI&&qI(c,_R),l=c.prototype=zI(fR)),l.constructor!==c&&xI(l,"constructor",c),oR(l).TypedArrayConstructor=c,mR&&xI(l,mR,n);var h=c!=s;d[n]=c,bI({global:!0,constructor:!0,forced:h,sham:!pR},d),TR in c||xI(c,TR,r),TR in l||xI(l,TR,r),$I(n)}):mE.exports=function(){},pE("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var bR=jS,kR=_I,wR=Ma,PR=Ue,DR=t,OR=YE.aTypedArray,NR=YE.exportTypedArrayMethod,MR=s("".slice);NR("fill",(function(e){var t=arguments.length;OR(this);var i="Big"===MR(wR(this),0,3)?kR(e):+e;return PR(bR,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),DR((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var LR=A,xR=Ue,VR=YE,UR=Ht,FR=uI,jR=F,BR=t,HR=LR.RangeError,GR=LR.Int8Array,WR=GR&&GR.prototype,JR=WR&&WR.set,zR=VR.aTypedArray,KR=VR.exportTypedArrayMethod,qR=!BR((function(){var e=new Uint8ClampedArray(2);return xR(JR,e,{length:1,0:3},1),3!==e[1]})),QR=qR&&VR.NATIVE_ARRAY_BUFFER_VIEWS&&BR((function(){var e=new GR(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));KR("set",(function(e){zR(this);var t=FR(arguments.length>1?arguments[1]:void 0,1),i=jR(e);if(qR)return xR(JR,this,i,t);var r=this.length,n=UR(i),o=0;if(n+t>r)throw HR("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!qR||QR);var YR=_s,XR=t,$R=et,ZR=Y_,eA=eS,tA=tS,iA=te,rA=rS,nA=YE.aTypedArray,oA=YE.exportTypedArrayMethod,aA=A.Uint16Array,sA=aA&&YR(aA.prototype.sort),cA=!(!sA||XR((function(){sA(new aA(2),null)}))&&XR((function(){sA(new aA(2),{})}))),lA=!!sA&&!XR((function(){if(iA)return iA<74;if(eA)return eA<67;if(tA)return!0;if(rA)return rA<602;var e,t,i=new aA(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(sA(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));oA("sort",(function(e){return void 0!==e&&$R(e),lA?sA(this,e):ZR(nA(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))}),!lA||cA);var dA=Object.create,uA=Object.defineProperty,hA=Object.defineProperties,pA=Object.getOwnPropertyDescriptor,mA=Object.getOwnPropertyDescriptors,_A=Object.getOwnPropertyNames,fA=Object.getOwnPropertySymbols,gA=Object.getPrototypeOf,vA=Object.prototype.hasOwnProperty,TA=Object.prototype.propertyIsEnumerable,SA=Reflect.get,yA=Math.pow,EA=(e,t,i)=>t in e?uA(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,IA=(e,t)=>{for(var i in t||(t={}))vA.call(t,i)&&EA(e,i,t[i]);if(fA)for(var i of fA(t))TA.call(t,i)&&EA(e,i,t[i]);return e},RA=(e,t)=>hA(e,mA(t)),AA=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),CA=(e,t)=>{for(var i in t)uA(e,i,{get:t[i],enumerable:!0})},bA=(e,t,i)=>(i=null!=e?dA(gA(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of _A(t))!vA.call(e,n)&&n!==i&&uA(e,n,{get:()=>t[n],enumerable:!(r=pA(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:uA(i,"default",{value:e,enumerable:!0}),e)),kA=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?pA(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&&uA(t,i,o),o},wA=(e,t,i)=>(EA(e,"symbol"!=typeof t?t+"":t,i),i),PA=(e,t,i)=>SA(gA(e),i,t),DA=(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())})),OA=AA((e=>{bA(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)}))})))}})),NA=AA((e=>{bA(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}(OA()).log})),MA=AA((e=>{bA(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)}))}}}})),LA=AA((e=>{bA(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=NA();Object.defineProperty(e,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}});var r=MA();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}(OA());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=AA((e=>{bA(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))}))}}})),VA=AA((e=>{bA(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)))}})),UA=AA((e=>{bA(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}(OA())})),FA=AA(((e,t)=>{bA(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)})),jA=AA(((e,t)=>{bA(qA());var i=FA();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,R,A,C,b,k,w,P,D,O,N=i.parseRtpParameters(o);g||(D=i.getIceParameters(o,m),(O=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,R=E.iceTransport,A=E.dtlsTransport,C=E.rtpReceiver,b=E.sendEncodingParameters,w=E.localCapabilities,d.transceivers[s].recvEncodingParameters=k,d.transceivers[s].remoteCapabilities=N,d.transceivers[s].rtcpParameters=M,x.length&&"new"===R.state&&(!_&&!L||f&&0!==s?x.forEach((function(e){a(E.iceTransport,e)})):R.setRemoteCandidates(x)),(!f||0===s)&&("new"===R.state&&R.start(I,D,"controlling"),"new"===A.state&&A.start(O)),!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),!C||"sendrecv"!==T&&"sendonly"!==T?delete E.rtpReceiver:(P=C.track,S?(u[S.stream]||(u[S.stream]=new e.MediaStream),c(P,u[S.stream]),h.push([P,C,u[S.stream]])):(u.default||(u.default=new e.MediaStream),c(P,u.default),h.push([P,C,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,C=E.rtpReceiver||new e.RTCRtpReceiver(E.dtlsTransport,p),U)P=C.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,C,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=N,E.rtpReceiver=C,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}})),BA=AA((e=>{bA(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=VA();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}(OA()),o=UA(),a=jA(),s=(r=a)&&r.__esModule?r:{default:r}})),HA=AA((e=>{bA(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}(OA())})),GA=AA((e=>{bA(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)})}})),WA=AA((e=>{bA(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=HA();Object.defineProperty(e,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}});var r=GA();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}(OA())})),JA=AA((e=>{bA(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}(OA());function r(e){return e&&void 0!==e.video?Object.assign({},e,{video:i.compactObject(e.video)}):e}})),zA=AA((e=>{bA(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=FA(),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}(OA())})),KA=AA((e=>{bA(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(OA()),i=s(LA()),r=s(BA()),n=s(WA()),o=s(JA()),a=s(zA());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=AA((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=(0,KA().adapterFactory)({window:"undefined"==typeof window?void 0:window});e.default=t})),QA=AA(((e,t)=>{bA(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)})),YA=AA(((e,t)=>{bA(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")}))}))})),XA=AA((e=>{bA(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=YA(),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}}))}))}})),$A=AA(((e,t)=>{bA(qA());var i=YA(),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"}})),ZA=AA((e=>{bA(qA());var t=XA(),i=$A();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})),eC=AA(((e,t)=>{bA(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)}));bA(qA()),bA(qA()),bA(qA(),1),bA(qA(),1);var tC="4.15.00.1600",iC="5.0.0";var rC,nC="undefined"!=typeof importScripts,oC="undefined"!=typeof registerProcessor,aC="",sC=e=>aC=e,cC="web.sdk.qcloud.com",lC="web.sdk.tencent.cn",dC="web.sdk.cloud.tencent.cn",uC="https://console.cloud.tencent.com/trtc",hC="https://".concat(cC,"/trtc/webrtc/v5/doc"),pC="".concat(hC,"/zh-cn/"),mC="jssdk_log",_C="jssdk_new_endreport",fC="qcloud",gC="trtc",vC="webrtc",TC=((rC=TC||{})[rC.TRACE=0]="TRACE",rC[rC.DEBUG=1]="DEBUG",rC[rC.INFO=2]="INFO",rC[rC.WARN=3]="WARN",rC[rC.ERROR=4]="ERROR",rC[rC.NONE=5]="NONE",rC),SC={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5},yC={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}},EC={"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}},IC={"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}},RC="canvas",AC="audio",CC="video",bC="screen",kC="small",wC="big",PC="auxiliary",DC="smallVideo",OC="user",NC="environment",MC="mute",LC="unmute",xC="ended",VC="playing",UC="pause",FC="error",jC="loadeddata",BC="audioinput",HC="videoinput",GC="main",WC="backup",JC="subscribe",zC="unsubscribe",KC="inactive",qC="sendonly",QC="recvonly",YC="wss://trtc.rtc.qq.com",XC="wss://webrtc.qq.com",$C="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",ZC=GC,eb=PC,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",Rb="object",Ab="schedule.rtc.qq.com",Cb="schedule.rtc.qcloud.com",bb="schedule.rtc.tencentcloud.com",kb="schedule-ecdn.rtc.tencentcloud.com",wb="default",Pb=wb,Db=["normal leave","timeout leave","kick","role change"],Ob=2e3,Nb="ric",Mb="raf",Lb="timeout";bA(qA(),1),bA(qA(),1);(new Date).getTime();var xb=0,Vb=function(){return(new Date).getTime()+xb},Ub=function(){let e=new Date;return e.setTime(Vb()),e.toLocaleString()},Fb={};CA(Fb,{bytes2ms:()=>tP,catchEmitterError:()=>CP,copyProperties:()=>eP,deepMerge:()=>xP,fibonacci:()=>cP,formatedTime:()=>FP,getConstructorName:()=>EP,getContainerFromElement:()=>VP,getEnv:()=>zw,getInternalVersion:()=>kP,getLoggerUrl:()=>qw,getMuteStateFromFlag:()=>DP,getNetworkQuality:()=>OP,getNetworkType:()=>Xw,getOSType:()=>Yw,getReconnectionTimeout:()=>lP,getSysInfo:()=>$w,getTerminalType:()=>Qw,getTurnServer:()=>NP,getValueType:()=>dP,glog:()=>oP,ipv4ToUint32:()=>MP,isArray:()=>gP,isArrayOrObject:()=>LP,isAudioWorkletSupported:()=>IP,isBoolean:()=>_P,isConstructor:()=>yP,isEmpty:()=>PP,isFunction:()=>uP,isLangChinese:()=>aP,isMediaStreamTrack:()=>vP,isNumber:()=>mP,isObject:()=>fP,isOverseaSdkAppId:()=>Kw,isPlainObject:()=>sP,isPromise:()=>SP,isRemoteTrack:()=>TP,isString:()=>pP,isUndefined:()=>hP,ms2bytes:()=>rP,ms2samples:()=>nP,performanceNow:()=>AP,promiseAny:()=>RP,samples2ms:()=>iP,tryCatchFunction:()=>Zw}),bA(qA(),1),bA(qA(),1);var jb="undefined"==typeof navigator?"":navigator.userAgent,Bb=e=>new RegExp(e,"i").test(jb),Hb=e=>{if(Bb(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=jb.match(t);if(i&&i[1])return i[1]}return""},Gb=e=>{if(Bb(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=jb.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},Wb=/AppleWebKit\/([\d.]+)/i.exec(jb);Wb&&parseFloat(Wb[1]);var Jb=Bb("iPad"),zb="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Bb("Macintosh"),Kb=Bb("iPhone")&&!Jb,qb=Bb("iPod"),Qb=Kb||Jb||qb||zb,Yb=Bb("Android");!function(){if(Yb){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}}}();Yb&&Bb("webkit");var Xb=Bb("Firefox"),$b=Hb("Firefox"),Zb=Gb("Firefox"),ek=Bb("Edge"),tk=Hb("Edge"),ik=Bb("Edg"),rk=Hb("Edg"),nk=Gb("Edg"),ok=Bb("SogouMobileBrowser"),ak=Hb("SogouMobileBrowser"),sk=Bb("MetaSr\\s"),ck=Hb("MetaSr\\s"),lk=Bb("TBS"),dk=Hb("TBS"),uk=Bb("XWEB"),hk=Hb("XWEB");Bb("MSIE\\s8\\.0");var pk=Bb("MSIE\\/\\d+");!function(){if(pk){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 mk=Bb("(micromessenger|webbrowser)"),_k=Hb("MicroMessenger"),fk=!lk&&Bb("MQQBrowser")&&Bb("COVC"),gk=!lk&&Bb("MQQBrowser")&&!Bb("COVC"),vk=gk||fk?Hb("MQQBrowser"):"",Tk=!lk&&Bb(" QQBrowser"),Sk=Hb(" QQBrowser"),yk=!lk&&Bb("QQBrowserLite"),Ek=Hb("QQBrowserLite"),Ik=!lk&&Bb("MQBHD"),Rk=Hb("MQBHD"),Ak=Bb("Windows"),Ck=!Qb&&Bb("MAC OS X"),bk=!Yb&&Bb("Linux");Bb("MicroMessenger");var kk=Bb("UCBrowser");Bb("Electron");var wk=Bb("MiuiBrowser"),Pk=Hb("MiuiBrowser"),Dk=Bb("HuaweiBrowser");Bb("Huawei");var Ok=Hb("HuaweiBrowser"),Nk=Bb("SamsungBrowser"),Mk=Hb("SamsungBrowser"),Lk=Bb("HeyTapBrowser"),xk=Hb("HeyTapBrowser"),Vk=Bb("VivoBrowser"),Uk=Hb("VivoBrowser"),Fk=()=>Gb("Chrome"),jk=Bb("Chrome"),Bk=!ek&&!sk&&!ok&&!lk&&!uk&&!ik&&!Tk&&!wk&&!Dk&&!Nk&&!Lk&&!Vk&&jk,Hk=Bb("HeadlessChrome"),Gk=Fk(),Wk=Hb("Chrome"),Jk=!jk&&!gk&&!fk&&!yk&&!Ik&&Bb("Safari"),zk=Hb("Safari");/Android.*(wv|.0.0.0)/.test(jb);var Kk=(()=>{if(zb)return zk;if(Qb){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"===zk,Qk="15.1"===Kk;(()=>{let e=Number(Kk.split(".")[0])})();var Yk="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),Xk=(()=>{let e;return()=>{if(hP(e))try{e=!!window.localStorage}catch(FN){e=!1}return e}})(),$k=function(){let e=new Map([[Xb,["Firefox",$b]],[ik,["Edg",rk]],[Bk,["Chrome",Wk]],[Jk,["Safari",zk]],[lk,["TBS",dk]],[uk,["XWEB",hk]],[mk&&Kb,["WeChat",_k]],[Tk,["QQ(Win)",Sk]],[gk,["QQ(Mobile)",vk]],[fk,["QQ(Mobile X5)",vk]],[yk,["QQ(Mac)",Ek]],[Ik,["QQ(iPad)",Rk]],[wk,["MI",Pk]],[Dk,["HW",Ok]],[Nk,["Samsung",Mk]],[Lk,["OPPO",xk]],[Vk,["VIVO",Uk]],[ek,["EDGE",tk]],[ok,["SogouMobile",ak]],[sk,["Sogou",ck]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}();bA(qA(),1),bA(qA(),1),bA(qA(),1);var Zk=1e8,ew="API_CALL_TIMEOUT",tw="SIGNAL_CHANNEL_RECONNECTION_FAILED",iw="SIGNAL_CHANNEL_SETUP_FAILED",rw="ERROR_MESSAGE",nw="DOWNLINK_RECONNECTION_FAILED",ow="EXCHANGE_SDP_FAILED",aw="UPLINK_RECONNECTION_FAILED",sw="INVALID_PURE_AUDIO",cw="INVALID_STREAMID",lw="INVALID_USER_DEFINE_RECORDID",dw="INVALID_USER_DEFINE_PUSH_ARGS",uw="INVALID_JOIN",hw="JOIN_ROOM_TIMEOUT",pw="JOIN_ROOM_FAILED",mw="REJOIN_ROOM_FAILED",_w="INVALID_DESTROY",fw="SUBSCRIBE_FAILED",gw="SWITCH_ROLE_TIMEOUT",vw="SWITCH_ROLE_FAILED",Tw="INVALID_OPERATION_START_PUBLISH_CDN",Sw="INVALID_OPERATION_STOP_PUBLISH_CDN",yw="START_PUBLISH_CDN_FAILED",Ew="STOP_PUBLISH_CDN_FAILED",Iw="REPEAT_JOIN",Rw="CLIENT_DESTROYED",Aw="START_MIX_TRANSCODE_FAILED",Cw="STOP_MIX_TRANSCODE_FAILED",bw="MIX_TRANSCODE_NOT_STARTED",kw="PLAY_FAILED",ww="NOT_SUPPORTED_HTTP",Pw="NOT_SUPPORTED_WEBRTC",Dw="NOT_SUPPORTED_H264ENCODE",Ow="NOT_SUPPORTED_H264DECODE",Nw="MICROPHONE_NOT_FOUND",Mw="CAMERA_NOT_FOUND",Lw="SIGNAL_RESPONSE_FAILED",xw="CATCH_HANDLER_ERROR",Vw="CONNECTION_CLOSED",Uw="CONNECTION_ABORTED",Fw="API_CALL_ABORTED",jw={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(dP(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(dP(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 Bw(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}bA(qA());var Hw={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(Bw(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(Bw(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() 接口。"},Gw={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=Hw,window.TRTC_ERROR_LINK=Gw);var Ww=(e,t)=>t?"".concat(hC,"/").concat(e,"/").concat(t):"".concat(hC,"/").concat(e,"/index.html");function Jw(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",a="",s="";uP(jw[t])?o=jw[t](i):pP(jw[t])&&(o=jw[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]&&(uP(l[t])?s=l[t](i):pP(l[t])&&(s=l[t]));let d=o;return aP()&&(c&&c[t]&&(uP(c[t])?a=c[t](i):pP(c[t])&&(a=c[t])),a&&(d=n?"".concat(a,"\n请查看文档: ").concat(Ww("zh-cn",s),"\n\n"):"".concat(a,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(Ww("en",s),"\n")),d}var zw=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Kw=e=>Number(e)<14e8,qw=function(e,t){let i;i=aC||(Kw(e)?"https://videoapi-sgp.im.qcloud.com":"https://yun.tim.qq.com");let r=Math.floor(Math.random()*yA(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)};function Qw(){return Yb?4:Kb?2:Jb?3:Ck?12:Ak?5:bk?13:1}function Yw(){return Yb?"Android":Kb?"iPhone":Jb?"iPad":Ck?"Mac":Ak?"Windows":bk?"Linux":"unknown"}function Xw(){let{userAgent:e,connection:t}=navigator,i=(e.match(/NetType\/\S+/)||[])[0]||"";i=i.toLowerCase().replace("nettype/",""),"3gnet"===i&&(i="3g");let r=t&&t.type&&t.type.toLowerCase(),n=t&&t.effectiveType&&t.effectiveType.toLowerCase();"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 $w=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:Qw(),uint32_device_type:0,str_os_verion:Yw(),uint32_link_type:1,str_client_version:tC,uint32_net_type:SC[Xw()],ua:navigator.userAgent,version:""}}}};function Zw(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 SP(o)?o.catch((e=>KP.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(o){KP.error("".concat(t.name,"() error observed ").concat(o))}}}function eP(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 tP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3;return iP(e/4,t)}function iP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3;return 1e3*e/t}function rP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3;return 4*nP(e,t)}function nP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3;return e*t/1e3}var oP="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},aP=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},sP=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 cP(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:cP(e-1,i,t+i)}function lP(e){return e>8?3e4:1e3*cP(e)}function dP(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var uP=e=>"function"==typeof e,hP=e=>void 0===e,pP=e=>"string"==typeof e,mP=e=>"number"==typeof e,_P=e=>"boolean"==typeof e,fP=e=>"object"===dP(e),gP=e=>"array"===dP(e),vP=e=>dP(e)==="MediaStreamTrack".toLowerCase(),TP=e=>e.isRemote,SP=e=>"promise"===dP(e),yP=e=>uP(e)&&e.prototype.constructor===e,EP=e=>yP(e)?e.prototype.constructor.name:"",IP="undefined"!=typeof AudioWorkletNode;function RP(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 AP(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var CP=(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=Jw({key:xw,data:{name:t,event:n[0]},addDocLink:!1});return KP.warn("".concat(e,"\n\n").concat(a.stack)),!1}},e},bP=e=>+e<10?"0".concat(e):e,kP=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=bP(i[1])+bP(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},wP=Object.prototype.hasOwnProperty;function PP(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(sP(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(wP.call(e,t))return!1;return!0}return!1}function DP(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 OP(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 NP(e){let t={urls:"turn:".concat(e.url)};return!hP(e.username)&&!hP(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",hP(e.credentialType)||(t.credentialType=e.credentialType)),t}function MP(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!pP(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 LP=function(e){return gP(e)||fP(e)},xP=function(e,t,i,r){if(!LP(e)||!LP(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],!(hP(t[n])||i&&i.includes(n)))if(LP(e[n])&&LP(t[n]))o+=xP(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},VP=e=>pP(e)?document.getElementById(e):e,UP=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),FP=()=>UP.format(new Date);function jP(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(t){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)}))}bA(qA(),1),bA(qA(),1);var BP=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)=>DA(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<(uP(l)?l():l)?(u++,p=1,uP(n)&&n.call(this,u,t),h=window.setTimeout((()=>{h=-1,m(e,i)}),uP(d)?d(u):d)):(t(),uP(o)&&o.call(this,_))};uP(r)?r.call(c,_,a,i):a()}}));return new Promise(m)}};bA(qA(),1);bA(qA(),1);var HP=new(bA(QA(),1).default);bA(qA(),1);var GP,WP=((GP=WP||{}).ROOM_DESTROY="1",GP.JOIN_START="21",GP.JOIN_SCHEDULE_SUCCESS="22",GP.JOIN_SIGNAL_CONNECTION_START="23",GP.JOIN_SIGNAL_CONNECTION_END="24",GP.JOIN_SEND_CMD="25",GP.JOIN_RECEIVED_CMD_RES="26",GP.JOIN_SUCCESS="27",GP.JOIN_FAILED="28",GP.LEAVE_START="51",GP.LEAVE_SEND_CMD="52",GP.LEAVE_SUCCESS="53",GP.PUBLISH_START="61",GP.SEND_FIRST_VIDEO_FRAME="62",GP.SUBSCRIBE_START="81",GP.SUBSCRIBE_SUCCESS="82",GP.UNSUBSCRIBE_SUCCESS="83",GP.LOCAL_TRACK_CAPTURE_START="101",GP.LOCAL_TRACK_CAPTURE_SUCCESS="102",GP.LOCAL_TRACK_CAPTURE_FAILED="103",GP.LOCAL_TRACK_PUBLISHED="104",GP.LOCAL_TRACK_UNPUBLISHED="105",GP.LOCAL_TRACK_REPLACED="106",GP.SWITCH_DEVICE_SUCCESS="107",GP.TRACK_MUTED="108",GP.TRACK_UNMUTED="109",GP.REMOTE_TRACK_SUBSCRIBED="110",GP.REMOTE_TRACK_UNSUBSCRIBED="111",GP.PLAY_TRACK_START="151",GP.PLAYER_STATE_CHANGED="152",GP.VIDEO_LOADED_DATA="153",GP.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",GP.WORKLET_LOADED_SUCCESS="155",GP.WORKLET_LOADED_FAILED="156",GP.SIGNAL_CONNECTION_STATE_CHANGED="201",GP.PEER_CONNECTION_STATE_CHANGED="202",GP.HEARTBEAT_REPORT="251",GP.RECEIVED_PUBLISHED_USER_LIST="252",GP.REMOTE_PUBLISH_STATE_CHANGED="253",GP.AUDIO_LEVEL_INTERVAL="260",GP.NETWORK_QUALITY="261",GP.API_SUCCESS_RATE="262",GP),JP=WP,zP=!(Qb||Yb||Hk),KP=new class{constructor(){this._isEnableUploadLog=!0,this._localJoinedUser=new Map,this._queue=[],this._timeoutId=-1,this._logLevel=1,this._logLevelToUpload=2,!nC&&!oC&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){HP.on(JP.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&TC[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),HP.on(JP.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),HP.once(JP.JOIN_FAILED,(()=>{this.startUpload()})),HP.on(JP.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(pP(i.userId)&&mP(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 DA(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:Ub(),sdkAppId:String(r),userId:i,version:iC,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 BP({retryFunction:()=>jP({url:qw(t,mC),body:e,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:(e,t)=>{t()}})()}getPrefix(e){let t=new Date;t.setTime(Vb());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(TC[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){hP(TC[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(pP(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=TC[e])?void 0:o.toLowerCase())||"info";zP?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){wA(this,"userId"),wA(this,"remoteUserId"),wA(this,"id"),wA(this,"sdkAppId"),wA(this,"type"),wA(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!_P(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):"","]")),KP.log(e,t,hP(this.userId)||PP(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;TC[t]&&(this._logLevelToUpload=t)}},qP=!0,QP=bA(QA());bA(qA());var YP={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"},XP={};CA(XP,{HTTPS_API:()=>gD,IS_GET_CAPABILITIES_SUPPORTED:()=>LD,IS_GET_SETTINGS_SUPPORTED:()=>MD,IS_SEI_SUPPORTED:()=>xD,basis:()=>BD,checkSystemRequirementsInternal:()=>mD,decodeSupportStatus:()=>pD,encodeSupportStatus:()=>hD,getBrowserInfo:()=>oD,getDisplayResolution:()=>yD,getOSName:()=>SD,isAddTransceiverSupported:()=>PD,isBrowserSupported:()=>aD,isGetReceiversSupported:()=>bD,isGetSendersSupported:()=>kD,isGetTransceiversSupported:()=>wD,isGetUserMediaSupported:()=>ED,isMediaDevicesSupported:()=>cD,isMediaSessionSupported:()=>FD,isMediaStreamTrackProcessorSupported:()=>uD,isReplaceTrackSupported:()=>OD,isScreenCaptureApiAvailable:()=>fD,isSelectedCandidatePair:()=>vD,isSetParametersSupported:()=>ND,isSmallStreamAPISupported:()=>RD,isSmallStreamSupported:()=>AD,isStopTransceiverSupported:()=>DD,isTRTCSupported:()=>_D,isUnifiedPlanDefault:()=>CD,isUsedInHttpProtocol:()=>dD,isWebAudioSupported:()=>ID,isWebCodecSupported:()=>UD,isWebCodecsSupported:()=>sD,isWebRTCSupported:()=>VD,isWebTransportSupported:()=>jD}),bA(qA(),1),bA(qA(),1),bA(qA(),1);var $P,ZP=(($P=ZP||{})[$P.INVALID_PARAMETER=4096]="INVALID_PARAMETER",$P[$P.INVALID_OPERATION=4097]="INVALID_OPERATION",$P[$P.NOT_SUPPORTED=4098]="NOT_SUPPORTED",$P[$P.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",$P[$P.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",$P[$P.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",$P[$P.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",$P[$P.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",$P[$P.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",$P[$P.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",$P[$P.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",$P[$P.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",$P[$P.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",$P[$P.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",$P[$P.CLIENT_BANNED=16448]="CLIENT_BANNED",$P[$P.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",$P[$P.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",$P[$P.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",$P[$P.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",$P[$P.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",$P[$P.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",$P[$P.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",$P[$P.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",$P[$P.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",$P[$P.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",$P[$P.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",$P[$P.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",$P[$P.API_CALL_ABORTED=16461]="API_CALL_ABORTED",$P[$P.UNKNOWN=65535]="UNKNOWN",$P),eD=ZP,tD=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=eD.UNKNOWN,extraCode:n=0,constraint:o}=e,a="<".concat(function(e){for(let t in eD)if(eD[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),wA(this,"code"),wA(this,"extraCode"),wA(this,"message"),wA(this,"originMessage"),wA(this,"name"),wA(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}},iD=tD,rD={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},nD=new Map([[Xb,["Firefox",$b]],[ik,["Edg",rk]],[Bk,["Chrome",Wk]],[Jk,["Safari",zk]],[lk,["TBS",dk]],[uk,["XWEB",hk]],[mk&&Kb,["WeChat",_k]],[Tk,["QQ(Win)",Sk]],[gk,["QQ(Mobile)",vk]],[fk,["QQ(Mobile X5)",vk]],[yk,["QQ(Mac)",Ek]],[Ik,["QQ(iPad)",Rk]],[wk,["MI",Pk]],[Dk,["HW",Ok]],[Nk,["Samsung",Mk]],[Lk,["OPPO",xk]],[Vk,["VIVO",Uk]],[ek,["EDGE",tk]],[ok,["SogouMobile",ak]],[sk,["Sogou",ck]]]);function oD(){let e=nD.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var aD=function(){return!(kk||ek||ik&&nk<80||Xb&&Zb<56)},sD=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},cD=function(){if(!navigator.mediaDevices)return KP.error(jw.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},lD=!1;function dD(){return"http:"===location.protocol&&!Yk&&!lD&&(lD=!0,KP.warn(Jw({key:ww})),!0)}var uD=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},hD=function(){return DA(this,null,(function*(){if(rD.detail.isH264EncodeSupported||rD.detail.isVp8EncodeSupported)return{isH264EncodeSupported:rD.detail.isH264EncodeSupported,isVp8EncodeSupported:rD.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection,n=document.createElement(RC);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(),rD.detail.isH264EncodeSupported=t,rD.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:rD.detail.isH264EncodeSupported,isVp8EncodeSupported:rD.detail.isVp8EncodeSupported}}catch(r){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},pD=function(){return DA(this,null,(function*(){if(rD.detail.isH264DecodeSupported&&rD.detail.isVp8DecodeSupported)return{isH264DecodeSupported:rD.detail.isH264DecodeSupported,isVp8DecodeSupported:rD.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}}}))},mD=function(){return DA(this,null,(function*(){if(rD.result)return rD;let e=aD(),t=VD(),i=sD(),r=cD(),{isH264EncodeSupported:n,isVp8EncodeSupported:o}=yield hD(),{isH264DecodeSupported:a,isVp8DecodeSupported:s}=yield pD();return rD.result=e&&t&&r&&(n||o)&&(a||s),rD.detail.isBrowserSupported=e,rD.detail.isWebRTCSupported=t,rD.detail.isWebCodecsSupported=i,rD.detail.isMediaDevicesSupported=r,rD.detail.isScreenShareSupported=fD(),rD.detail.isSmallStreamSupported=AD(),rD.detail.isH264EncodeSupported=n,rD.detail.isVp8EncodeSupported=o,rD.detail.isH264DecodeSupported=a,rD.detail.isVp8DecodeSupported=s,rD.result||KP.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," ")),rD}))},_D=function(){return rD.result},fD=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},gD=(e,t,i)=>{"http:"===location.protocol&&!Yk&&(e[t]=()=>{throw new iD({code:eD.INVALID_OPERATION,message:jw.NOT_SUPPORTED_HTTP})})},vD=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(_P(e.selected)&&!e.selected)},TD=new Map([[Yb,"Android"],[Qb,"iOS"],[Ak,"Windows"],[Ck,"MacOS"],[bk,"Linux"]]),SD=function(){return TD.get(!0)?TD.get(!0):"unknown"};function yD(){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 ED(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function ID(){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 RD(){return"captureStream"in HTMLCanvasElement.prototype}function AD(){return!(mk||Qb||Gk&&Gk<63)&&!(!aD()||!RD())}var CD=function(){if(hP(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:_b}),e.addTransceiver(AC),t=!0}catch(i){}return null==e||e.close(),t};function bD(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function kD(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function wD(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function PD(){return"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}function DD(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function OD(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function ND(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&kD()}var MD=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,LD=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,xD="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Fk()>=86,VD=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function UD(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return hP(window.AudioDecoder)||(e.AudioDecoder=!0),hP(window.AudioEncoder)||(e.AudioEncoder=!0),hP(window.VideoDecoder)||(e.VideoDecoder=!0),hP(window.VideoEncoder)||(e.VideoEncoder=!0),hP(window.ImageDecoder)||(e.ImageDecoder=!0),e}function FD(){return"mediaSession"in navigator&&!hP(navigator.mediaSession.setActionHandler)}function jD(){return!hP(window.WebTransport)}function BD(){let e={browser:"".concat($k.name,"/").concat($k.version),os:SD(),displayResolution:yD(),isScreenShareSupported:fD(),isWebRTCSupported:VD(),isGetUserMediaSupported:ED(),isWebAudioSupported:ID(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:UD(),isMediaSessionSupported:FD(),isWebTransportSupported:jD()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}bA(qA(),1),bA(qA(),1);var HD=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)}))};bA(qA(),1);var GD=new class{constructor(){wA(this,"_prefix","TRTC"),wA(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){Xk()&&(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(Xk())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(FN){KP.warn(FN)}}getItem(e){if(!Xk())return null;try{let t=JSON.parse(localStorage.getItem(this.getRealKey(e)));return t&&t.expiresIn>=Date.now()?t.value:null}catch(t){KP.warn(t)}}setItem(e,t){if(Xk())try{let i={expiresIn:Date.now()+6048e5,value:t};this._queue.set(this.getRealKey(e),i)}catch(i){KP.warn(i)}}deleteItem(e){if(!Xk())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(t){return KP.warn(t),!1}}clear(){if(Xk())try{localStorage.clear()}catch(FN){KP.warn(FN)}}};bA(qA(),1),bA(qA(),1);var WD=bA(QA(),1),JD=Symbol("instance"),zD=Symbol("abortCtrl"),KD=Symbol("cacheResult"),qD=class{constructor(e,t,i){wA(this,"oldState"),wA(this,"newState"),wA(this,"action"),wA(this,"error"),this.oldState=e,this.newState=t,this.action=i}toString(){return"".concat(this.action,"ing")}},QD=class extends Error{constructor(e,t,i){super(t),wA(this,"state"),wA(this,"message"),wA(this,"cause"),this.state=e,this.message=t,this.cause=i}},YD=new Map,XD=Object.getPrototypeOf(DA(void 0,null,(function*(){}))).constructor;function $D(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=YD.get(r)||[];YD.has(r)||YD.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 DA(this,null,(function*(){var r;let o=this;if(i.context&&(o=nO.get("function"==typeof i.context?i.context.call(this,...n):i.context)),o.state===t)return o[KD];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 QD(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 QD(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;eO.call(o,new qD(l,t,a));let d={aborted:!1};o[zD]=d;try{let e=s.apply(this,n);return o[KD]=e instanceof XD?yield e:e,d.aborted||(o[zD]=void 0,eO.call(o,t),null==(r=i.success)||r.call(this,o[KD])),o[KD]}catch(u){let e=u instanceof Error?u.message:String(u);if(eO.call(o,l,e),!i.fail){if(i.ignoreError)return u;throw u}i.fail.call(this,new QD(o._state,"action '".concat(a,"' failed :").concat(e),u instanceof Error?u:new Error(e)))}}))}}}var ZD="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 eO(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(nO.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t})}var tO,iO,rO=class extends WD.default{constructor(e,t,i){super(),wA(this,"name"),wA(this,"groupName"),wA(this,"_state",rO.INIT),wA(this,tO),wA(this,iO),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[JD];r?this.name=r.name+"-"+r.count++:i[JD]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=YD.get(e)||[],i=new Set,r=[],n=[],o=new Set,a=Object.getPrototypeOf(e);YD.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=rO.instances.get(e),t||rO.instances.set(e,t=new rO(e,void 0,Object.create(rO.prototype)))):(t=rO.instances2.get(e),t||rO.instances2.set(e,t=new rO(e.constructor.name,void 0,Object.create(rO.prototype)))),t}static getState(e){var t;return null==(t=rO.get(e))?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};ZD(rO.UPDATEAFSM,IA({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){eO.call(this,e)}},nO=rO;tO=KD,iO=zD,wA(nO,"STATECHANGED","stateChanged"),wA(nO,"UPDATEAFSM","updateAFSM"),wA(nO,"INIT","[*]"),wA(nO,"ON","on"),wA(nO,"OFF","off"),wA(nO,"instances",new Map),wA(nO,"instances2",new WeakMap),bA(qA(),1),bA(qA(),1),bA(qA(),1),bA(qA(),1),bA(qA(),1);var oO=(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)},aO=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},sO=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),cO=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Lb,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=IA("interval"===e?{delay:2e3,count:0,backgroundTask:!0}:e===Nb?{delay:1e4,count:0}:e===Mb?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),fP(t)&&(i=IA(IA({},i),t)),uP(e)&&(t=e,e=Lb);let r=IA({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=AP(),r=()=>{if(t=AP()-i,t>=e.delay&&(i=AP()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=oO(r,{timeout:e.delay})};return e.ricID=oO(r,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=AP(),r=()=>document.hidden&&e.backgroundTask?(t=AP()-i,i=AP(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(r,e.delay-Math.floor(t%e.delay))):(t=AP()-i,t>=e.delay&&(i=AP()-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=AP()-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&&sO(r),n&&aO(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)}};cO.taskMap=new Map,cO.currentTaskID=1;var lO=cO;bA(qA(),1);var dO="connection-state-changed",uO={LOADED_DATA:jC,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed"};bA(qA(),1),bA(qA(),1);var hO=new class{constructor(){this._roomIdMap=new Map,"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:iC,env:fC,browserVersion:$k.name+$k.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){Yk||!KP.isAbleToUpload||this._configs.env===fC&&this.uploadEventToKibana(RA(IA({},e),{result:"success"}))}logFailedEvent(e){if(Yk||!KP.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)||eD.UNKNOWN};this._configs.env===fC&&this.uploadEventToKibana(RA(IA({},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:Ub(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:iC,log:t};r&&(n.errorInfo=r.message),this.sendRequest(qw(this._configs.sdkAppId,mC),n)}sendRequest(e,t){KP.isAbleToUpload?jP({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},pO="trtc_autoplay",mO="".concat(pO,"_mask"),_O="".concat(pO,"_wrapper"),fO="".concat(pO,"_header"),gO="".concat(pO,"_content"),vO="".concat(pO,"_action_wrapper"),TO="".concat(pO,"_question"),SO="".concat(pO,"_collapse"),yO="".concat(pO,"_action_confirm"),EO="".concat(pO,"_detail"),IO="#2473E8",RO="dialog",AO="".concat(RO,"-show"),CO="".concat(RO,"-1"),bO="".concat(RO,"-2"),kO=!1,wO=()=>!!document.querySelector(".".concat(_O)),PO="".concat(hC,"/").concat(aP()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),DO="<br><a href='".concat(PO,"' target='_blank'>").concat(aP()?"其他方案?":"Any other solution?","</a>"),OO="".concat(aP()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(DO):"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(DO)),NO=class{constructor(){if(wA(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),wA(this,"_dialogNode",null),wA(this,"_bodyPosition",""),wA(this,"_showDetail",!1),wA(this,"_isCollapseClicked",!1),wA(this,"_isQuestionClicked",!1),aP()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!kO){let e=document.createElement("style");e.innerHTML=".".concat(mO,"{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(mO," div:not(.").concat(vO,"){display:block !important;}.").concat(_O,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(_O," a{color:").concat(IO,";}.").concat(fO,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(gO,"{margin:8px 0;}.").concat(vO,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(SO,"{margin-right:auto;cursor:pointer}.").concat(TO,"{height:100%;line-height:16px;cursor:pointer;}.").concat(yO,"{margin-left:8px;color:#fff;background:").concat(IO,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(yO,":hover{opacity:0.9;}.").concat(SO,",.").concat(yO,",.").concat(gO,",.").concat(TO,"{font-size:14px;}@media screen and (max-width:750px){.").concat(_O,"{width:80vw;}}"),document.head.appendChild(e),kO=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(mO,"\"><div class='").concat(_O,"'><div class='").concat(fO,"'>").concat(location.host,"</div><div class='").concat(gO,"'>").concat(this.content,"</div><div class='").concat(EO,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(OO,"</div><div class='").concat(vO,"'></div></div></div>").trim();let t=document.createElement("button");t.className=yO,t.innerText=aP()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=TO,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=SO,r.innerText="".concat(aP()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(vO));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){wO()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(_O)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",KP.info("show autoplay dialog"),hO.uploadEvent({log:AO}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){KP.warn("confirm clicked, try resume stream"),HP.emit(JP.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(EO));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||hO.uploadEvent({log:CO}),this._isCollapseClicked=!0}onQuestionClick(){window.open(PO,"_blank"),this._isQuestionClicked||hO.uploadEvent({log:bO}),this._isQuestionClicked=!0}},MO={};CA(MO,{create:()=>xO,remove:()=>VO}),bA(qA(),1);var LO=new WeakMap;function xO(e,t){LO.has(e)||LO.set(e,[]);let i=LO.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 VO(e){let t=LO.get(e);t&&(t.forEach((e=>e())),LO.delete(e))}var UO=class extends nO{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,wA(this,"id"),wA(this,"element",null),wA(this,"container",null),wA(this,"mediaStream",new MediaStream),wA(this,"track"),wA(this,"url"),wA(this,"attr"),wA(this,"muted"),wA(this,"_log"),wA(this,"_pausedRetryCount"),wA(this,"_isElementPlayingFired",!1),wA(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(uO.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 DA(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=Jw({key:kw,data:{media:this.kind,error:e}});if(this._log.warn(e),t.includes("NotAllowedError"))throw new iD({code:eD.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(xC),this._interval>0&&lO.clearTask(this._interval)}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this.isPlaying?Promise.resolve():Qk?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);xO(this.element,this.element).add(VC,e).add(xC,e).add(UC,e).add(FC,e).add(jC,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==MO||MO.create(this.track,this.track).add(xC,e).add(MC,e).add(LC,e),this.track.readyState===xC&&this.handleTrackEvent({type:xC}),this.track.muted&&this.handleTrackEvent({type:MC})}}bindAutoPlayEvent(){HP.on(JP.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&VO(this.track)}unbindEvents(){this.element&&VO(this.element),this.unbindTrackEvents(),HP.off(JP.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){var t;switch(e.type){case VC:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(VC),this._interval&&(lO.clearTask(this._interval),this._interval=-1);break;case xC:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(xC);break;case UC:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(UC);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=Fk();this._pausedRetryCount>0&&(this.kind===CC&&!wO()||this.kind===AC&&(mP(i)&&i<=70||!e))&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--),Qb&&(this._interval=lO.run(Lb,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case FC: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)),hO.uploadEvent({log:"stat-".concat(this.kind,"-").concat(pb,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error})}break;case jC:this.kind===CC&&this.emit(uO.LOADED_DATA)}}handleTrackEvent(e){switch(e.type){case xC:this._log.info("".concat(this.kind," track is ended")),this.handleStopped(xC);break;case MC:this._log.info("".concat(this.kind," track is unable to provide media output")),this.handlePaused(MC);break;case LC:this._log.info("".concat(this.kind," track is able to provide media output")),this._isElementPlayingFired&&this.handlePlaying(LC)}}handlePlaying(e){this.emit(uO.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(uO.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}handleStopped(e){this.emit(uO.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};kA([$D([],"PLAYING")],UO.prototype,"handlePlaying",1),kA([$D("PLAYING","STOPPED",{ignoreError:!0})],UO.prototype,"handlePaused",1),kA([$D([],"STOPPED")],UO.prototype,"handleStopped",1);var FO=class extends UO{constructor(e){super(e,CC),wA(this,"mirror"),wA(this,"objectFit"),hP(e.mirror)||(this.mirror=e.mirror),hP(e.objectFit)||(this.objectFit=e.objectFit)}initializeElement(){var e;let t=document.createElement(CC);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}};bA(qA(),1),bA(qA(),1),bA(qA(),1);var jO=!1,BO=class{constructor(e){wA(this,"context_"),wA(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 DA(this,null,(function*(){try{yield this.context_.audioWorklet.addModule(URL.createObjectURL(this.blob_)),KP.info("worklet addModule success"),HP.emit(JP.WORKLET_LOADED_SUCCESS),jO=!0}catch(FN){KP.info("worklet addModule catch error. ".concat(FN.message)),HP.emit(JP.WORKLET_LOADED_FAILED)}}))}get initWorkletSuccess(){return jO}};bA(qA(),1),"undefined"!=typeof window&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var HO,GO,WO=()=>{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=()=>{KP.info("audioSource context state: ".concat(e.state)),t()},e},JO=0,zO=class{constructor(e){wA(this,"_volume"),wA(this,"_log"),wA(this,"_track"),wA(this,"_stream"),wA(this,"_audioCtx"),wA(this,"_destination"),wA(this,"_streamSource"),wA(this,"_scriptProcessorNode"),wA(this,"_audioWorkletNode"),wA(this,"_interval");let{track:t,log:i}=e;this._volume=0,this._log=i,this._track=t,HO||(HO=WO()),this._audioCtx=HO,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,HP.on(JP.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),IP?(HP.on(JP.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),HP.on(JP.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),this.preload()):this.initScriptProcessor(),JO+=1}preload(){GO?GO.initWorkletSuccess&&this.initAudioWorklet():GO=new BO({context:HO})}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(FN){hO.logFailedEvent({userId:this._log.userId,eventType:mb,error:FN}),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(FN){this._log.error("volumeMeter init script processor error: ".concat(FN))}}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,HP.off(JP.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),HP.off(JP.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),HP.off(JP.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),JO>0&&(JO-=1),0===JO&&(null==HO||HO.close(),HO=null,GO=null)}resume(){null==HO||HO.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})}},KO=class extends UO{constructor(e){super(e,AC),wA(this,"_volumeMeter"),wA(this,"gainedTrack"),wA(this,"_outputDeviceId"),wA(this,"_volume",1),wA(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 zO({track:this.gainedTrack||e,log:this._log})}initializeElement(){if(("15.2"===Kk||"15.3"===Kk||"15.4"===Kk)&&this.muted)return void this._log.info("audioElement is muted.");let e=document.createElement(AC);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 DA(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(KO.prototype,this,"play").call(this)}))}stop(){this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),super.stop()}resume(){return DA(this,null,(function*(){yield PA(KO.prototype,this,"resume").call(this),this._volumeMeter&&this._volumeMeter.resume()}))}setSinkId(e){return DA(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()}},qO=class extends nO{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n}=e;var o;super(),wA(this,"id",HD()),wA(this,"userId"),wA(this,"isRemote"),wA(this,"mediaType"),wA(this,"room"),wA(this,"user"),wA(this,"_log"),wA(this,"isPlayCalled"),wA(this,"mediaTrack",null),wA(this,"mediaStream"),wA(this,"container",null),wA(this,"subVideoPlayerMap"),wA(this,"playerMuted",!1),wA(this,"abortCtrl"),wA(this,"audioOutputDeviceId"),wA(this,"audioVolume"),wA(this,"objectFit","cover"),wA(this,"mirror",!1),wA(this,"gain"),wA(this,"isScreen",!1),hP(t)||(this.userId=t),this.mediaType=r,this._log=KP.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(o=n||this.room)?void 0:o.userId,remoteUserId:this instanceof pN?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof pN}),this.initPlayer()}get log(){return this._log||KP}get kind(){return 1===this.mediaType?AC:CC}get muted(){return!(!this.mediaTrack||this.mediaTrack.enabled)}get strMediaType(){return 4===this.mediaType?CC:2===this.mediaType?bC:AC}uninstallEvents(){}play(e,t){return DA(this,null,(function*(){let i=gP(e)?e[0]:e;if(this.isPlayCalled)return t&&!hP(t.muted)&&this.setPlayerMute(t.muted),t&&!hP(t.objectFit)&&(this.objectFit=t.objectFit),this.isScreen?this.mirror=!1:t&&!hP(t.mirror)&&(this.mirror=t.mirror),void(this.kind===CC&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),gP(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if((!this.isRemote||this.kind===CC)&&this.setPlayerMute(!0),t&&!hP(t.muted)&&this.setPlayerMute(t.muted),t&&!hP(t.objectFit)&&(this.objectFit=t.objectFit),this.isRemote||(this.mirror=!0),this.isScreen?this.mirror=!1:t&&!hP(t.mirror)&&(this.mirror=t.mirror),this.kind===CC&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror)),this.isPlayCalled=!0,i&&(this.container=i,this.player.setContainer(i)),HP.emit(JP.PLAY_TRACK_START,{track:this}),this.mediaTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{yield this.player.play(),gP(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 DA(this,null,(function*(){if(!this.mediaTrack||this.kind===AC)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&&(hP(t.mirror)||e.setMirror(t.mirror),hP(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new FO({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===AC?this.player=new KO({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 FO({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(uO.LOADED_DATA,(()=>{HP.emit(JP.VIDEO_LOADED_DATA,{track:this})})),this.player.on(uO.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))}))),this.player.on(uO.PLAYER_STATE_CHANGED,(e=>{HP.emit(JP.PLAYER_STATE_CHANGED,IA({track:this},e)),this.emit("player-state-changed",e)}))}setAudioOutput(e){return DA(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 DA(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),HP.emit(e?JP.TRACK_MUTED:JP.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){!this.isPlayCalled||e&&!this.player.isStopped||!e&&this.player.isStopped||this.isPlayCalled&&this.player.isStopped===e&&(this.log.info("playing state updated, ".concat(e?"play":"stop"," ").concat(this.kind)),e&&this.player.isStopped&&this.player.play().catch((()=>this.handleAutoPlayFailed())),!e&&!this.player.isStopped&&this.player.stop())}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new NO;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)}}};kA([$D([],nO.INIT)],qO.prototype,"close",1),bA(qA(),1),bA(qA(),1);var QO=Object.prototype.hasOwnProperty;var YO=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(sP(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(QO.call(e,t))return!1;return!0}return!1};bA(qA(),1);var XO=bA(QA(),1),$O=e=>t=>t.deviceId===e,ZO=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";wA(this,"kind"),wA(this,"type"),wA(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($O(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");KP.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find($O(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");KP.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},eN=class extends XO.EventEmitter{constructor(){super(),wA(this,"audioInputs",new ZO(AC)),wA(this,"videoInputs",new ZO(CC)),wA(this,"audioOutputs",new ZO(AC,"Output")),this.init(),navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",this.update.bind(this))}init(){iN().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return DA(this,null,(function*(){let e=yield iN();return this.audioInputs.update(e,this),this.videoInputs.update(e,this),this.audioOutputs.update(e,this),this}))}},tN=oC||nC?null:new eN;function iN(){return DA(this,null,(function*(){return dD()||!cD()?[]:(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&&aN.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}))}function rN(){return tN.update().then((e=>e.audioInputs.devices))}function nN(){return tN.update().then((e=>e.videoInputs.devices))}function oN(){return DA(this,null,(function*(){return tN.update().then((e=>e.audioOutputs.devices))}))}var aN=new Set;function sN(e,t){return DA(this,null,(function*(){let i=(yield rN()).find((e=>e.deviceId===wb));return(null==i?void 0:i.groupId)===e&&i.label===t}))}var cN=BP({retryFunction:function(e){return DA(this,null,(function*(){let t,i,r=yield function(e){return DA(this,null,(function*(){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression};if(e.audio)if(YO(e.microphoneId)){t=IA({sampleRate:e.sampleRate,channelCount:e.channelCount},t);let i=(yield rN()).filter((e=>{let{deviceId:t}=e;return t.length>0}));i.length>0&&(t.deviceId={exact:i[0].deviceId})}else t=IA({deviceId:e.useExact?{exact:e.microphoneId}:e.microphoneId,sampleRate:e.sampleRate,channelCount:e.channelCount},t);else t=!1;let i={},r={ideal:e.width,max:e.width},n={ideal:e.height,max:e.height};return Xb&&Ck&&e.width*e.height<101376&&(r=e.width,n=e.height),i=!hP(e.facingMode)&&e.video?{facingMode:e.facingMode,width:r,height:n,frameRate:e.frameRate}:!YO(e.cameraId)&&e.video?{deviceId:e.useExact?{exact:e.cameraId}:e.cameraId,width:r,height:n,frameRate:e.frameRate}:!!e.video&&(!!hP(e.width)||{width:r,height:n,frameRate:e.frameRate}),{audio:t,video:i}}))}(e);KP.info("getUserMedia with constraints: ".concat(JSON.stringify(r))),r.audio&&(t=yield rN(),KP.info("microphones: ".concat(JSON.stringify(t)))),r.video&&(i=yield nN(),KP.info("cameras: ".concat(JSON.stringify(i))));try{return yield navigator.mediaDevices.getUserMedia(r)}catch(n){if("NotFoundError"===n.name){if(i&&0===i.length)throw new iD({code:eD.DEVICE_NOT_FOUND,message:Jw({key:Mw})});if(t&&0===t.length)throw new iD({code:eD.DEVICE_NOT_FOUND,message:Jw({key:Nw})})}throw new iD({code:eD.INITIALIZE_FAILED,name:n.name,message:n.message,constraint:n.constraint})}}))},settings:{retries:3,timeout:500},onError:(e,t,i)=>{"NotReadableError"===e.name?t():i(e)},onRetrying:e=>{KP.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))}});var lN=cN;function dN(e){return hN(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return DA(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function uN(e){return hN(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return DA(this,null,(function*(){return e.call(this,t.apply(this,r))}))}))}function hN(e){return function(t,i,r){return r.value=e(r.value,i),r}}bA(qA(),1);var pN=class extends qO{constructor(e){super({mediaType:e}),wA(this,"isRemote",!1),wA(this,"deviceId"),wA(this,"groupId",""),wA(this,"label",""),wA(this,"_isRecapturing",!1),wA(this,"_lastRecaptureTime",0),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}installTrackEvent(e){e.addEventListener(MC,this.onTrackMuted),e.addEventListener(xC,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===xC&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(MC,this.onTrackMuted),e.removeEventListener(xC,this.onTrackEnded)}setStateToCapture(){}capture(e){return DA(this,null,(function*(){try{let t;HP.emit(JP.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(t=new MediaStream,t.addTrack(e.customSource)):t=yield lN(e);let i=t.getTracks()[0];return this.setMediaStream(t),this.setMediaStreamTrack(i),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),HP.emit(JP.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this}),t}catch(t){throw HP.emit(JP.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:t}),this.log.error("getUserMedia error observed ".concat(t)),t}}))}setMediaStreamTrack(e){this.state===nO.INIT&&this.setStateToCapture(),this.mediaTrack&&this.uninstallTrackEvent(this.mediaTrack),super.setMediaStreamTrack(e),e&&this.installTrackEvent(e)}setPublishStarting(){}setPublishStarted(){}setPublishStopped(e,t){}publish(e){this.room=e,this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),HP.emit(JP.LOCAL_TRACK_PUBLISHED,{track:this}),this.setPublishStarted()}unpublish(){this.room=void 0,2===this.mediaType&&(this.mediaType=4),HP.emit(JP.LOCAL_TRACK_UNPUBLISHED,{track:this}),this.setPublishStopped("api-call")}get isPublishing(){return"publish"===this.state}updateDeviceIdInUse(){return DA(this,null,(function*(){if(this.mediaTrack&&MD){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),i=this.mediaTrack.label;(yield function(e){return DA(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==AC||t!==wb||(yield sN(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),iN().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===AC&&!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(BC);return!!aN.has(i)}(this.mediaTrack)||this.kind===CC&&!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(HC);return!!aN.has(i)}(this.mediaTrack)||this._isRecapturing||e&&Ck&&Jk)}onTrackMuted(){if(this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Ob)return void setTimeout((()=>this.onTrackMuted()),Ob);setTimeout((()=>{var e;(null==(e=this.mediaTrack)?void 0:e.muted)&&"visible"===document.visibilityState&&this.recapture(this.deviceId)}),5e3)}}onTrackEnded(){if(this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Ob)return void setTimeout((()=>this.onTrackEnded()),Ob);this.recapture(this.deviceId)}}recapture(e){return DA(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 rN():yield nN()).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)}))}))}};kA([$D(nO.INIT,"capture")],pN.prototype,"setStateToCapture",1),kA([$D("capture","publish_starting",{success(){this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"})}})],pN.prototype,"setPublishStarting",1),kA([$D("publish_starting","publish",{success(){this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})}})],pN.prototype,"setPublishStarted",1),kA([hN((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})})),$D(["publish","publish_starting"],"capture",{ignoreError:!0})],pN.prototype,"setPublishStopped",1),bA(qA(),1);var mN=class extends pN{constructor(){super(1),wA(this,"mediaType",1),wA(this,"volume",0),wA(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),wA(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 DA(this,null,(function*(){if(this.mediaStream&&this.mediaTrack){if(this.deviceId===e){if(e!==wb)return;if(yield sN(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)),HP.emit(JP.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(){tN&&!tN.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&tN.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return DA(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e)));let t=yield rN();t[0]?this.recapture(t[0].deviceId):tN.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){return DA(this,null,(function*(){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}close(){tN.off("audioInputAdded",this.handleMicrophoneAdded,this),tN.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}};bA(qA(),1);var _N=class extends pN{constructor(){super(4),wA(this,"mediaType",4),wA(this,"profile",{width:640,height:480,frameRate:15,bitrate:900}),wA(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0}),wA(this,"small"),wA(this,"facingMode"),wA(this,"_canvas"),wA(this,"_canvasInterval"),wA(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=lO.run(Mb,(()=>{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&&(lO.clearTask(this._canvasInterval),this._canvasInterval=void 0,this._canvas=void 0,this.canvasTrack=void 0)}setProfile(e){var t;if(!e)return;let i=e.bitrate&&e.bitrate!==this.profile.bitrate;return 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:CC,videoType:wC})}))}switchDevice(e){return DA(this,null,(function*(){try{if(!this.mediaStream||this.deviceId===e||this.facingMode===e)return;(e===OC||e===NC)&&(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)),HP.emit(JP.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(){tN&&!tN.listeners("audioInputRemoved").includes(this.handleCameraRemoved)&&tN.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return DA(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e)));let t=yield nN();t[0]?this.recapture(t[0].deviceId):tN.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return DA(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}close(){tN.off("videoInputAdded",this.handleCameraAdded,this),tN.off("videoInputRemoved",this.handleCameraRemoved,this),this.destoryCanvasTrack(),super.close()}};bA(qA(),1),bA(qA(),1);function fN(e){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return hP(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}function gN(e){let t={systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:Jk?{max:e.width}:{ideal:e.width,max:e.width},height:Jk?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:"monitor"};if(t.video=i,!hP(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}var vN=function(e){return DA(this,null,(function*(){let t=null;if(Bk&&Gk<74||Jk){let i=gN(e);KP.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);if(e.systemAudio)return KP.warn("Your browser not support capture system audio"),r;if(e.audio){let i=fN(e);return KP.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0]),r}return r}if(e.systemAudio){let t=gN(e);return KP.info("getDisplayMedia with constraints: ".concat(JSON.stringify(t))),yield navigator.mediaDevices.getDisplayMedia(t)}let i=gN(e);KP.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);if(e.audio){let i=fN(e);return KP.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0]),r}return r}))},TN=class extends _N{constructor(){super(),wA(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),wA(this,"objectFit","contain"),wA(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(){return DA(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 vN({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 iD?s:new iD({code:eD.INITIALIZE_FAILED,name:s.name,message:s.message})}}()}))}switchDevice(e){return DA(this,null,(function*(){throw new Error("Method not implemented.")}))}};bA(qA(),1);var SN=class extends mN{constructor(){super(),this._log.id="s-".concat(this._log.id)}setScreenAudioTrack(e,t){this.setMediaStream(t),this.setMediaStreamTrack(e)}};bA(qA(),1),bA(qA(),1);var yN=class extends pN{constructor(e){super(1),wA(this,"musicId"),wA(this,"mediaType",1),wA(this,"volume",0),wA(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),wA(this,"playerMuted",!1),wA(this,"_audioContext"),wA(this,"_destination"),wA(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),_P(e.loop)&&this.player.setLoop(e.loop),mP(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=WO(),"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()?KP.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&&_P(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(){}};bA(qA(),1),bA(qA(),1);var EN=class extends qO{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,wA(this,"userId"),wA(this,"tinyId"),wA(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===EN.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),this.updatePlayingState(!0),e&&HP.emit(JP.REMOTE_TRACK_SUBSCRIBED,{track:this})}unsubscribe(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.player.setTrack(null),this.updatePlayingState(!1),e&&HP.emit(JP.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)}},IN=EN;wA(IN,"STATE_SUBSCRIBE","subscribe"),kA([$D(nO.INIT,IN.STATE_SUBSCRIBE)],IN.prototype,"subscribe",1),kA([$D(IN.STATE_SUBSCRIBE,nO.INIT)],IN.prototype,"unsubscribe",1);var RN=class extends IN{constructor(e,t){super(e,t,1),wA(this,"volume",0),wA(this,"mediaType",1),wA(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}};bA(qA(),1);var AN=class extends IN{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),wA(this,"mediaType",4),wA(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}},CN=class extends AN{constructor(e,t){super(e,t,2),wA(this,"mediaType",2),wA(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function bN(){}bA(qA(),1),bA(qA()),bA(qA());var kN=e=>e(),wN=1,PN=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new LN(e,this,this.streamId++);return xN.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},DN=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=bN,this.error=bN,this.next=bN,this.dispose=bN,this.subscribe=bN,this.doDefer()}subscribe(e){return e instanceof PN?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(kN),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}},ON=class extends DN{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 NN(e,t,i){if("undefined"!=typeof __FASTRX_DEVTOOLS__){let r=Object.defineProperties(Object.setPrototypeOf(e,PN.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}});xN.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof PN&&xN.addSource(r,t)}return r}return e}function MN(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var LN=class extends ON{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{xN.defer(this.source,this.id)}))}next(e){xN.next(this.source,this.id,e),this.sink.next(e)}complete(){xN.complete(this.source,this.id),this.sink.complete()}error(e){xN.complete(this.source,this.id,e),this.sink.error(e)}},xN={addSource(e,t){MN("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){MN("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;MN("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){MN("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){MN("defer",{id:e.id,streamId:t})},pipe(e){MN("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){MN("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=wN++),MN("create",{name:e.toString(),id:e.id})}};bA(qA()),bA(qA());var VN=class extends DN{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()}};bA(qA()),bA(qA()),bA(qA());var UN,FN,jN=(UN=class extends ON{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},FN="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 PN){let i=NN((r=>{let n=new UN(r,...t);n.sourceId=i.id,n.subscribe(e)}),FN,arguments);return i.source=e,xN.pipe(i),i}return i=>e(new UN(i,...t))}});bA(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 NN((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}(250),jN((()=>performance.now())),function(){return e=>{let t=new VN(e);if(e instanceof PN){let i=NN((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,xN.pipe(i),i}return NN(t.add.bind(t),"share",arguments)}}()),bA(qA(),1);var BN=new Map;function HN(e,t){let i=RA(IA({},t),{timestamp:Vb()});BN.has(e)?BN.get(e).push(i):BN.set(e,[i])}HP.on(JP.JOIN_SUCCESS,(e=>{let{room:t}=e;HN(t.userId,{eventId:32788,eventDesc:"join room"})})),HP.on(JP.LEAVE_START,(e=>{let{room:t}=e;HN(t.userId,{eventId:32789,eventDesc:"leave room"})})),HP.on(JP.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;t.room&&HN(t.room.userId,{eventId:t.kind===AC?32769:32768,eventDesc:"publish ".concat(t.kind)})})),HP.on(JP.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;t.room&&HN(t.room.userId,{eventId:t.kind===AC?32771:32770,eventDesc:"unpublish ".concat(t.kind)})})),HP.on(JP.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===AC?HN(t.room.userId,{eventId:t.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:t.isRemote?t.userId:void 0}):HN(t.room.userId,{eventId:t.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:t.isRemote?t.userId:void 0}))})),HP.on(JP.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===AC?HN(t.room.userId,{eventId:t.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:t.isRemote?t.userId:void 0}):HN(t.room.userId,{eventId:t.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:t.isRemote?t.userId:void 0}))})),HP.on(JP.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;1===t.mediaType&&HN(t.room.userId,{eventId:32777,eventDesc:"".concat(JC," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&HN(t.room.userId,{eventId:32776,eventDesc:"".concat(JC," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&HN(t.room.userId,{eventId:32803,eventDesc:"".concat(JC," ").concat(DC),remoteUserId:t.userId})})),HP.on(JP.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;1===t.mediaType&&HN(t.room.userId,{eventId:32779,eventDesc:"".concat(zC," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&HN(t.room.userId,{eventId:32778,eventDesc:"".concat(zC," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&HN(t.room.userId,{eventId:32804,eventDesc:"".concat(zC," ").concat(DC),remoteUserId:t.userId})})),HP.on(JP.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&HN(t.room.userId,{eventId:t.kind===CC?32780:32781,eventDesc:"switch ".concat(t.kind===CC?"camera":"microphone")})})),HP.on(JP.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&HN(t.room.userId,{eventId:t.kind===CC?32782:32783,eventDesc:"replace ".concat(t.kind)})})),HP.on(JP.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&&HN(r.userId,{eventId:t,eventDesc:i})})),HP.on(JP.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&&HN(r.userId,{eventId:t,eventDesc:i,remoteUserId:a})})),bA(qA(),1),bA(qA(),1);var GN=bA(QA(),1),WN=class extends GN.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,wA(this,"userMap",new Map),wA(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,"]");hP(t)||(r+=":".concat(Db[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=DP(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:DP(0,n),muteState:a,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};bA(qA());var JN={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"};bA(qA()),bA(qA(),1);var zN=class extends Error{};function KN(e,t){let i=[];return xP(i,e),xP(i,t),i}function qN(e){this._resolve=Promise.resolve(e)}function QN(e){this._reject=Promise.reject(e)}var YN=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=KN;let i=YN.instances.get(e);i?i.set(t,this):YN.instances.set(e,new Map([[t,this]]))}static get(e,t){let i=YN.instances.get(e);return i&&i.get(t)||new YN(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 zN("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:qN,reject:QN};try{switch(this.state){case 1:if(0===e)throw new zN("already started");break;case 4:if(2===e)throw new zN("not started");break;default:return this.cacheOp(o)}}catch(a){return Promise.reject(a)}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 zN("already start");break;case 3:switch(e.type){case 2:throw new zN("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new zN("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new zN("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 zN("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new zN("start not allowed after update");case 0:throw new zN("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new zN("keep start")),new zN("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}},XN=YN;XN.instances=new WeakMap,bA(qA()),bA(qA());var $N,ZN={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},eM=(($N=eM||{})[$N.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",$N[$N.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",$N[$N.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",$N[$N.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",$N[$N.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",$N[$N.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",$N[$N.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",$N[$N.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",$N[$N.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",$N[$N.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",$N[$N.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",$N[$N.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",$N[$N.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",$N[$N.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",$N[$N.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",$N[$N.MIX_PARAMS_USER_Z_ORDER=5015]="MIX_PARAMS_USER_Z_ORDER",$N[$N.MIX_PARAMS_VIDEO_FRAMERATE=5016]="MIX_PARAMS_VIDEO_FRAMERATE",$N[$N.MIX_PARAMS_VIDEO_GOP=5017]="MIX_PARAMS_VIDEO_GOP",$N[$N.MIX_PARAMS_AUDIO_BITRATE=5018]="MIX_PARAMS_AUDIO_BITRATE",$N[$N.MIX_PARAMS_NOT_SELF=5019]="MIX_PARAMS_NOT_SELF",$N[$N.MIX_PARAMS_USER_STREAM=5020]="MIX_PARAMS_USER_STREAM",$N[$N.INVALID_OPERATION=5100]="INVALID_OPERATION",$N[$N.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",$N[$N.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",$N[$N.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",$N[$N.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",$N[$N.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",$N[$N.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",$N[$N.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",$N[$N.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",$N[$N.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",$N[$N.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",$N[$N.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",$N[$N.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",$N[$N.DEVICE_ERROR=5300]="DEVICE_ERROR",$N[$N.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",$N[$N.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",$N[$N.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",$N[$N.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",$N[$N.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",$N[$N.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",$N[$N.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",$N[$N.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",$N[$N.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",$N[$N.SERVER_ERROR=5400]="SERVER_ERROR",$N[$N.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",$N[$N.OPERATION_FAILED=5500]="OPERATION_FAILED",$N[$N.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",$N[$N.REJOIN_FAILED=5502]="REJOIN_FAILED",$N[$N.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",$N[$N.OPERATION_ABORT=5998]="OPERATION_ABORT",$N[$N.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",$N);bA(qA());var tM={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(dP(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(dP(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=iM(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=iM(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=iM(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=iM(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=iM(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=iM(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=iM(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 iM(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var rM=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=eM[i];try{t=tM[s]}catch(a){t=tM.UNKNOWN_ERROR}return uP(t)?o=t(r):pP(t)&&(o=t),n&&(o+=" doc:"),o}({code:r||i,params:IA({fnName:a,error:s},o)}),super(t),wA(this,"name","RtcError"),wA(this,"code"),wA(this,"extraCode"),wA(this,"functionName"),wA(this,"message"),wA(this,"originError"),this.name=eM[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 iD){let{stack:n}=e,o={code:ZN.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case eD.INVALID_PARAMETER:o.code=ZN.INVALID_PARAMETER;break;case eD.INVALID_OPERATION:o.code=ZN.INVALID_OPERATION;break;case eD.NOT_SUPPORTED:case eD.NOT_SUPPORTED_H264:o.code=ZN.ENV_NOT_SUPPORTED,e.getCode()===eD.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(jw.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case eD.DEVICE_NOT_FOUND:case eD.DEVICE_AUTO_RECOVER_FAILED:o.code=ZN.DEVICE_ERROR;break;case eD.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case eD.SERVER_TIMEOUT:case eD.SWITCH_ROLE_FAILED:o.code=ZN.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case eD.API_CALL_ABORTED:o.code=ZN.OPERATION_ABORT;break;case eD.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 eD.UNKNOWN:break;default:o.code=ZN.OPERATION_FAILED}r=new rM(o),n&&(r.stack+=n.substr(n.indexOf("\n")))}else r=new rM({code:ZN.UNKNOWN_ERROR,fnName:t,originError:e});return r}};var nM=rM,oM=(e,t)=>{if(t instanceof zN){let{stack:i}=t;t=new nM({code:ZN.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function aM(e,t){return hN(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),a=0;a<n;a++)o[a]=arguments[a];let s=XN.get(this,"string"==typeof e?e:e(...o));return t&&(s.startSame=t.bind(this)),s.action(0,i.bind(this),o).catch(oM.bind(null,r))}))}function sM(e,t){return hN(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),a=0;a<n;a++)o[a]=arguments[a];let s=XN.get(this,"string"==typeof e?e:e(...o));return t&&(s.mergeUpdate=t.bind(this)),s.action(2,i.bind(this),o).catch(oM.bind(null,r))}))}function cM(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return hN(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),a=0;a<n;a++)o[a]=arguments[a];let s=XN.get(this,"string"==typeof e?e:e(...o));return s.abortStart=t,s.action(3,i.bind(this),o).catch(oM.bind(null,r))}))}bA(qA());var lM={type:Rb,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}}},dM={type:Rb,properties:{systemAudio:{type:Eb},fillMode:{type:Sb,values:["contain","cover","fill"]},profile:{type:[Sb,Rb],properties:{width:{type:yb},height:{type:yb},frameRate:{type:yb},bitrate:{type:yb}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},uM={type:[Sb,HTMLElement,null,Ib],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(pP(e)){let r=document.getElementById(e);if(!r)throw new nM({code:ZN.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}});if(!(r instanceof HTMLElement))throw new nM({code:ZN.INVALID_PARAMETER,extraCode:5010,fnName:i,messageParams:{key:t,type:dP(r)}})}}},hM={name:"userId",required:!0,type:Sb},pM={type:Rb,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 mM(e,t,i,r){if(!/^[A-Za-z\d_-]*$/.test(e))throw new nM({code:ZN.INVALID_PARAMETER,extraCode:5011,fnName:i,messageParams:{key:t}})}function _M(e,t,i,r){if(pP(e)){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new nM({code:ZN.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}})}else if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new nM({code:ZN.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}function fM(e,t){if(!e)throw new nM({code:ZN.INVALID_OPERATION,extraCode:5101,fnName:t})}function gM(e,t,i){if(!e)throw new nM({code:ZN.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var vM={type:yb,notLessThanZero:!0},TM={enterRoom:{name:"EnterRoomConfig",type:Rb,required:!0,validate(e,t,i){if(this._room.isJoined)throw new nM({code:ZN.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:_M},proxy:{type:[Rb,Sb],properties:{websocketProxy:{type:Sb},turnServer:{type:[Rb,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:Rb,properties:{view:uM,publish:{type:Eb},option:lM}},updateLocalVideo:{name:"updateLocalVideoConfig",type:Rb,required:!0,properties:{view:RA(IA({},uM),{required:!1}),publish:{type:Eb},mute:{type:Eb},option:lM}},startLocalAudio:{name:"LocalAudioConfig",type:Rb,properties:{publish:{type:Eb},option:pM}},updateLocalAudio:{name:"updateLocalAudioConfig",type:Rb,required:!0,properties:{publish:{type:Eb},mute:{type:Eb},option:pM}},startScreenShare:{name:"ScreenShareConfig",type:Rb,properties:{view:uM,publish:{type:Eb},option:dM}},updateScreenShare:{name:"updateScreenShareConfig",type:Rb,required:!0,properties:{view:uM,publish:{type:Eb},option:dM}},muteRemoteAudio:[hM,{name:"mute",required:!0,type:Eb}],setRemoteAudioVolume:[hM,{name:"volume",required:!0,type:yb,min:0,max:100}],startRemoteVideo:{name:"startRemoteVideoConfig",type:Rb,required:!0,properties:{view:uM,userId:{type:Sb,required:!0},streamType:{values:["main","sub"],required:!0},option:{type:Rb,properties:{fillMode:{type:Sb,values:["contain","cover","fill"]},mirror:{type:Eb}}}},validate(e,t,i){fM(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(gM(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new nM({code:ZN.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:Rb,required:!0,properties:{view:RA(IA({},uM),{required:!1}),userId:{type:Sb,required:!0},streamType:{values:["main","sub"],required:!0},option:{type:Rb,properties:{fillMode:{type:Sb,values:["contain","cover","fill"]},mirror:{type:Eb}}}},validate(e,t,i){fM(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(gM(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new nM({code:ZN.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:Rb,required:!0,properties:{userId:{type:Sb,required:!0},streamType:{values:["main","sub"]}},validate(e,t,i){if("*"!==e.userId&&hP(e.streamType))throw new nM({code:ZN.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){fM(this._room.isJoined,i)}},enableAudioVolumeEvaluation:[{name:"interval",type:yb},{name:"enableInBackground",type:Eb}],startMixTranscode:{name:"config",required:!0,type:Rb,properties:{mode:{type:Sb,values:["preset-layout","manual"]},streamId:{type:Sb,validate:mM},videoWidth:vM,videoHeight:vM,videoBitrate:RA(IA({},vM),{allowEmpty:!1}),videoFramerate:{type:yb,validate(e,t,i,r){if(e<=0||e>30)throw new nM({code:ZN.INVALID_PARAMETER,extraCode:5016,fnName:i})}},videoGop:{type:yb,validate(e,t,i,r){if(e<1||e>8)throw new nM({code:ZN.INVALID_PARAMETER,extraCode:5017,fnName:i})}},audioSampleRate:vM,audioBitrate:{type:yb,validate(e,t,i,r){if(e<32||e>192)throw new nM({code:ZN.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:Rb,properties:{userId:{required:!0,type:Sb},roomId:{type:[Sb,yb],validate:_M},pureAudio:{type:Eb},width:vM,height:vM,locationX:vM,locationY:vM,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 nM({code:ZN.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 nM({code:ZN.INVALID_PARAMETER,extraCode:5019,fnName:i});if(e.videoWidth<n||e.videoHeight<o)throw new nM({code:ZN.INVALID_PARAMETER,extraCode:5020,fnName:i})}},startPublishCDNStream:{name:"options",required:!1,properties:{streamId:{type:Sb,validate:mM},streamType:{values:["main","sub"]},appId:{type:yb,allowEmpty:!1},bizId:{type:yb,allowEmpty:!1},url:{type:Sb,allowEmpty:!1}}}},SM={TRTC:TM};function yM(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function EM(e){return e===JN.QOS_PREFERENCE_CLEAR?"detail":e===JN.QOS_PREFERENCE_SMOOTH?"motion":""}bA(qA());function IM(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return hN(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{AM.call(this,t,n,i,this._name)}catch(a){return Promise.reject(a)}return e.apply(this,n)}))}function RM(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return hN(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{AM.call(this,t,n,i,this._name)}catch(a){throw a}return e.apply(this,n)}))}function AM(e,t,i,r){if(gP(e))for(let n=0;n<e.length;n++)CM.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else CM.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function CM(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function a(e){return{code:ZN.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(hP(i)){if(t.required)throw new nM(a(5001));if(hP(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),uP(t.type[r])&&i instanceof t.type[r]&&(e=!0),pP(t.type[r])&&dP(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new nM({code:ZN.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>yP(e)?EP(e):pP(e)?e:dP(e)))},value:i}})}else if(!hP(t.type)&&dP(i)!==t.type)throw new nM(a(5002));if(!1===t.allowEmpty){let e=mP(i)&&(0===i||Number.isNaN(i)),t=pP(i)&&""===i.trim();if(e||t)throw new nM(a(5003))}if(t.notLessThanZero&&mP(i)&&i<0)throw new nM(a(5006));if(!hP(t.min)&&mP(i)&&i<t.min)throw new nM(a(5007));if(!hP(t.max)&&mP(i)&&i>t.max)throw new nM(a(5008));if(pP(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new nM(a(5004))}else if(uP(t.instanceOf)&&!(i instanceof t.instanceOf))throw new nM(a(5004));if(t.values&&!t.values.includes(i))throw new nM(a(5005));let{properties:s}=t;sP(s)&&fP(i)&&Object.keys(s).forEach((e=>{CM.call(this,{rule:s[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;sP(c)&&gP(i)&&i.forEach(((e,t)=>{CM.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),uP(t.validate)&&t.validate.call(this,i,r,n,o,this)}function bM(){return hN(((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(dP(t)):(JSON.stringify(t),t)}catch(rC){return"type:".concat(dP(t))}})))):o.info("".concat(t,"()"));try{let i=e.apply(this,r),n=AP();return SP(i)?i.then((e=>(o.info("".concat(t,"() success")),HP.emit(JP.API_SUCCESS_RATE,{room:this._room,apiName:t,cost:AP()-n}),e))).catch((e=>{throw e=nM.convertFrom.call(this,e,t,1===r.length?r[0]:r),o.error("".concat(t,"() failed ").concat(e)),HP.emit(JP.API_SUCCESS_RATE,{room:this._room,apiName:t,error:e}),e})):(HP.emit(JP.API_SUCCESS_RATE,{room:this._room,apiName:t,cost:AP()-n}),i)}catch(a){throw a=nM.convertFrom.call(this,a,t),o.error("".concat(t,"() failed ").concat(a)),HP.emit(JP.API_SUCCESS_RATE,{room:this._room,apiName:t,error:a}),a}}))}bA(qA()),bA(qA()),bA(qA(),1);var kM=new WeakMap;var wM=0,PM=new Set,DM=null;!function(e){iC=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));tC="".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-beta.2");var OM=class extends QP.EventEmitter{constructor(e,t){super(),wA(this,"_room"),wA(this,"_eventListened",new Set),wA(this,"_localVideoTrack",null),wA(this,"_localAudioTrack",null),wA(this,"_localScreenTrack",null),wA(this,"_localScreenAudioTrack",null),wA(this,"_localVideoConfig",null),wA(this,"_localScreenConfig",null),wA(this,"_localAudioConfig",null),wA(this,"_remoteVideoConfigMap",new Map),wA(this,"_remoteAudioConfigMap",new Map),wA(this,"_remoteAudioMuteMap",new Map),wA(this,"_log",KP.createLogger({id:"t".concat(wM)})),this._room=new e(IA({logger:this._log,frameWorkType:OM.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(YP.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this.on(YP.REMOTE_AUDIO_UNAVAILABLE,(e=>{let{userId:t}=e;this._stopRemoteAudio({userId:t},!1).catch((()=>{}))})),this.on(YP.REMOTE_VIDEO_UNAVAILABLE,(e=>{let{userId:t,streamType:i}=e;this._stopRemoteVideo({userId:t,streamType:i},!1).catch((()=>{}))})),xO(tN,tN).add("audioInputAdded",(e=>{this.emit(YP.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(YP.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(YP.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(YP.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>DA(this,null,(function*(){if(this.emit(YP.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),DM&&DM.deviceId===Pb){let e=(yield oN()).find((e=>e.deviceId===Pb));e&&DM.groupId!==e.groupId&&(DM=e,this.emit(YP.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>DA(this,null,(function*(){this.emit(YP.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield oN())[0];t&&DM&&(DM.deviceId===e.deviceId||DM.deviceId===Pb&&DM.groupId!==t.groupId)&&(DM=t,this.emit(YP.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})))),CP(this,"trtc")}static create(){}static _create(e,t){wM+=1,function(){var e;qP&&(qP=!1,5!==KP.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(pC,"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("******************************************************************************")),KP.info("TRTC Web SDK Version:",iC),KP.info("UA:",navigator.userAgent),KP.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")))}();let i=new OM(e,t);return PM.add(i),DM?i.emit(YP.DEVICE_CHANGED,{type:"speaker",action:"active",device:DM}):oN().then((e=>{e[0]&&(DM=e[0],i.emit(YP.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]}))})),i}enterRoom(e){return DA(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),!pP(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};pP(e.roomId)?(s.strRoomId=e.roomId,this._room.useStringRoomId=!0):s.roomId=e.roomId,xO(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(YP.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(YP.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(YP.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(YP.ERROR,nM.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(YP.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this.emit(YP.NETWORK_QUALITY,e)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{xO(t,t).add("player-state-changed",(i=>{let r=RA(IA({},i),{userId:e.userId});t.kind===CC&&(r.streamType=yM(t.streamType)),this.emit(t.kind===AC?YP.AUDIO_PLAY_STATE_CHANGED:YP.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===eD.PLAY_NOT_ALLOWED&&this.emit(YP.AUTOPLAY_FAILED)}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{VO(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?YP.REMOTE_AUDIO_AVAILABLE:YP.REMOTE_AUDIO_UNAVAILABLE,{userId:r}),o!==s&&this.emit(s?YP.REMOTE_VIDEO_AVAILABLE:YP.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"}),t.hasAuxiliary!==i.hasAuxiliary&&this.emit(i.hasAuxiliary?YP.REMOTE_VIDEO_AVAILABLE:YP.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"})})).add("firewall-restriction",(()=>{this.emit(YP.ERROR,new nM({code:ZN.OPERATION_FAILED,extraCode:5501}))})),this._handleReceiveMode(),yield this._room.join(s,r,OM.frameWorkType),this._checkTrackToPublish()}))}exitRoom(){return DA(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e){return DA(this,null,(function*(){yield this._room.switchRole(e),"anchor"===e&&this._checkTrackToPublish()}))}destroy(){VO(tN),this.removeAllListeners(),this._room.destroy(),PM.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare()}startLocalAudio(){return DA(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 mN,o={},a={muted:!0};r&&(hP(r.microphoneId)?hP(r.audioTrack)||(o.customSource=r.audioTrack):o.deviceId=r.microphoneId,hP(r.captureVolume),hP(r.profile)||(pP(r.profile)?yC[r.profile]&&n.setProfile(yC[r.profile]):n.setProfile(r.profile)),mP(r.earMonitorVolume)&&(a.muted=!(r.earMonitorVolume>0),a.volume=r.earMonitorVolume),hP(r.echoCancellation)||(n.profile.echoCancellation=r.echoCancellation),hP(r.noiseSuppression)||(n.profile.noiseSuppression=r.noiseSuppression),hP(r.autoGainControl)||(n.profile.autoGainControl=r.autoGainControl)),n.on("5",(t=>{e.emit(YP.ERROR,new nM({code:ZN.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),n.on("2",(t=>{e.emit(YP.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),n.on("4",(t=>{let i;t.error&&(i=nM.convertFrom(t.error)),e.emit(YP.PUBLISH_STATE_CHANGED,RA(IA({},t),{error:i}))})),yield n.capture(o),xO(n,n).add("player-state-changed",(t=>{e.emit(YP.AUDIO_PLAY_STATE_CHANGED,RA(IA({},t),{userId:""}))})),yield e._updateAudioPlayOption({playOption:a,track:n}),i&&e._room.isJoined&&e._room.publish(n).catch((()=>{})),e._localAudioTrack=n,e._localAudioConfig=RA(IA({},t),{publish:i})}()}))}updateLocalAudio(e){return DA(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):hP(r.audioTrack)||(this._localAudioTrack.setMediaStreamTrack(r.audioTrack),yield this._room.replaceTrack(this._localAudioTrack)),hP(r.captureVolume),hP(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&&!hP(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),hP(i)||this._localAudioTrack.setMute(i),xP(this._localAudioConfig,e)}))}stopLocalAudio(){return DA(this,null,(function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),this._localAudioTrack.stop(),this._localAudioTrack.close(),VO(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return DA(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 _N,a={},s={};if(n&&(n.cameraId?a.deviceId=n.cameraId:hP(n.useFrontCamera)?hP(n.videoTrack)||(a.customSource=n.videoTrack):a.facingMode=n.useFrontCamera?OC:NC,hP(n.profile)||(pP(n.profile)?EC[n.profile]&&o.setProfile(EC[n.profile]):o.setProfile(n.profile)),hP(n.fillMode)||(s.objectFit=n.fillMode),hP(n.mirror)||(s.mirror=n.mirror),hP(n.small)||(AD()?pP(n.small)?o.small=EC[n.small]:o.small=n.small:e._log.warn("small stream is not supported"))),o.on("5",(t=>{e.emit(YP.ERROR,new nM({code:ZN.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(YP.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=nM.convertFrom(t.error)),e.emit(YP.PUBLISH_STATE_CHANGED,RA(IA({},t),{error:i}))})),yield o.capture(a),(null==n?void 0:n.qosPreference)&&o.mediaTrack){let e=EM(n.qosPreference);o.mediaTrack.contentHint=e}xO(o,o).add("player-state-changed",(t=>{e.emit(YP.VIDEO_PLAY_STATE_CHANGED,RA(IA({},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(IA({},t),{view:i,publish:r})}()}))}updateLocalVideo(e){return DA(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):hP(n.useFrontCamera)?hP(n.videoTrack)||(this._localVideoTrack.setMediaStreamTrack(n.videoTrack),yield this._room.replaceTrack(this._localVideoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?OC:NC),hP(n.profile)||(pP(n.profile)?EC[n.profile]&&this._localVideoTrack.setProfile(EC[n.profile]):this._localVideoTrack.setProfile(n.profile)),hP(n.fillMode)||(o.objectFit=n.fillMode),hP(n.mirror)||(o.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack)){let e=EM(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e}yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),this._room.isJoined&&!hP(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),hP(r)||this._localVideoTrack.setMute(r),xP(this._localVideoConfig,e)}))}stopLocalVideo(){return DA(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),VO(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return DA(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 TN;o.on("4",(t=>{let i;t.error&&(i=nM.convertFrom(t.error)),e.emit(YP.PUBLISH_STATE_CHANGED,RA(IA({},t),{error:i}))}));let a=null;o.setMediaType(2);let s={},c={};n&&(hP(n.profile)||(pP(n.profile)?IC[n.profile]&&o.setProfile(IC[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(s.systemAudio=!0,s.echoCancellation=n.echoCancellation,s.noiseSuppression=n.noiseSuppression,s.autoGainControl=n.autoGainControl),hP(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=EM(n.qosPreference);o.mediaTrack.contentHint=e}if(o.mediaTrack.addEventListener(xC,(()=>{e._stopScreenShare(),e.emit(YP.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(a=new SN,a.setScreenAudioTrack(l.getAudioTracks()[0],l)),xO(o,o).add("player-state-changed",(t=>{e.emit(YP.VIDEO_PLAY_STATE_CHANGED,RA(IA({},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(IA({},t),{view:i,publish:r})}()}))}updateScreenShare(e){return DA(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(hP(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let e=EM(r.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),this._room.isJoined&&!hP(i)&&(i&&!this._localScreenConfig.publish&&this._room.publish(this._localScreenTrack).catch((()=>{})),this._localScreenConfig.publish&&!i&&this._room.unpublish(this._localScreenTrack).catch((()=>{}))),xP(this._localScreenConfig,e)}))}stopScreenShare(){return DA(this,null,(function*(){return yield this._stopScreenShare()}))}startPlugin(e,t){return DA(this,null,(function*(){"AudioMixer"===e&&(yield this._room.startPlugin("AudioMixer",t)),"AIDenoiser"===e&&(yield this._room.startPlugin("AIDenoiser",t))}))}updatePlugin(e,t){return DA(this,null,(function*(){"AudioMixer"===e&&(yield this._room.updatePlugin("AudioMixer",t))}))}stopPlugin(e,t){return DA(this,null,(function*(){"AudioMixer"===e&&(yield this._room.stopPlugin("AudioMixer",t)),"AIDenoiser"===e&&(yield this._room.stopPlugin("AIDenoiser",t))}))}startRemoteVideo(e){return DA(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&&(hP(n.fillMode)||(s.objectFit=n.fillMode),hP(n.mirror)||(s.mirror=n.mirror),"main"===r&&!hP(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 DA(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&&(hP(n.fillMode)||(a.objectFit=n.fillMode),hP(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&&!hP(n.small)&&this._room.changeType(n.small,s.user),yield this._updateVideoPlayOption({view:t,playOption:a,track:s,prevConfig:l})),xP(l,e)}))}stopRemoteVideo(e){return DA(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return DA(this,null,(function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:n,remoteAuxiliaryTrack:o}=r;t.hasVideo&&"main"===e.streamType&&i.push(n),t.hasAuxiliary&&"sub"===e.streamType&&i.push(o)}for(let e of i)t&&(yield this._room.unsubscribe(e)),e.stop();this._remoteVideoConfigMap.delete("".concat(e.userId,"_").concat(e.streamType))}))}muteRemoteAudio(e,t){return DA(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=IA({},e);return t.mixUsers=e.mixUsers.map((e=>{let t=IA({},e);return hP(e.streamType)||(t.streamType=yM(e.streamType)),t})),this._room.startMixTranscode(t)}stopMixTranscode(){return this._room.stopMixTranscode()}startPublishCDNStream(e){let t=IA({},e);return hP(e.streamType)||(t.streamType=yM(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 DA(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&&(hP(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 DA(this,null,(function*(){let i=this._room.remotePublishedUserMap.get(e.userId);null!=i&&i.muteState.hasAudio&&(t&&(yield this._room.unsubscribe(i.remoteAudioTrack)),i.remoteAudioTrack.stop()),this._remoteAudioConfigMap.delete("".concat(e.userId))}))}_updateVideoPlayOption(e){return DA(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(hP(t)&&n&&n.view&&!PP(i)){let e;e=gP(n.view)?n.view:VP(n.view),e&&(yield r.play(e,i))}if(!hP(t)){let e;e=gP(t)?t:VP(t),e?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return DA(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:r}=e;return function*(){i.isPlayCalled||(yield i.play(null,t)),hP(t.muted)||i.setPlayerMute(t.muted),hP(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&&xO(this,this).add(YP.REMOTE_AUDIO_AVAILABLE,(e=>DA(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&&xO(this,this).add(YP.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 DA(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=>{VO(e.remoteAudioTrack),VO(e.remoteVideoTrack),VO(e.remoteAuxiliaryTrack)})),VO(this)}))}_stopScreenShare(){return DA(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(),VO(this._localScreenTrack),this._localScreenTrack=null,this._localScreenAudioTrack=null,this._localScreenConfig=null}}))}static setLogLevel(e,t){KP.setLogLevel(e),hP(t)||(t?KP.enableUploadLog():KP.disableUploadLog())}static isSupported(){return mD()}static getCameraList(){return nN()}static getMicrophoneList(){return rN()}static getSpeakerList(){return oN()}static setCurrentSpeaker(e){return DA(this,null,(function*(){(yield oN()).forEach((t=>{t.deviceId===e&&(PM.forEach((i=>{i.setCurrentSpeaker(e),i.emit(YP.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),DM=t)}))}))}},NM=OM;wA(NM,"_loggerManager",KP),wA(NM,"EVENT",YP),wA(NM,"ERROR_CODE",ZN),wA(NM,"TYPE",JN),wA(NM,"frameWorkType",30),kA([IM(SM.TRTC.enterRoom),aM("room",((e,t)=>{let[i]=e,[r]=t;return i.roomId===r.roomId&&i.userId===r.userId&&i.sdkAppId===r.sdkAppId})),hN((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t).catch((e=>{throw VO(this),e}))})),bM()],NM.prototype,"enterRoom",1),kA([bM()],NM.prototype,"exitRoom",1),kA([IM(SM.TRTC.switchRole),sM("room",((e,t)=>t)),bM()],NM.prototype,"switchRole",1),kA([bM()],NM.prototype,"destroy",1),kA([IM(SM.TRTC.startLocalAudio),aM("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)})),bM()],NM.prototype,"startLocalAudio",1),kA([IM(SM.TRTC.updateLocalAudio),sM("audio"),bM()],NM.prototype,"updateLocalAudio",1),kA([cM("audio"),bM()],NM.prototype,"stopLocalAudio",1),kA([IM(SM.TRTC.startLocalVideo),aM("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)})),bM()],NM.prototype,"startLocalVideo",1),kA([IM(SM.TRTC.updateLocalVideo),sM("video"),bM()],NM.prototype,"updateLocalVideo",1),kA([cM("video"),bM()],NM.prototype,"stopLocalVideo",1),kA([IM(SM.TRTC.startScreenShare),aM("screen",(()=>!0)),bM()],NM.prototype,"startScreenShare",1),kA([IM(SM.TRTC.updateScreenShare),sM("screen"),bM()],NM.prototype,"updateScreenShare",1),kA([bM()],NM.prototype,"stopScreenShare",1),kA([IM(SM.TRTC.startRemoteVideo),aM((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),bM()],NM.prototype,"startRemoteVideo",1),kA([IM(SM.TRTC.updateRemoteVideo),sM((e=>"v".concat(e.userId).concat(e.streamType))),bM()],NM.prototype,"updateRemoteVideo",1),kA([IM(SM.TRTC.stopRemoteVideo),hN((e=>function(t){return DA(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)}))})),bM()],NM.prototype,"stopRemoteVideo",1),kA([cM((e=>"v".concat(e.userId).concat(e.streamType)),!0)],NM.prototype,"_stopRemoteVideo",1),kA([IM(...SM.TRTC.muteRemoteAudio),bM()],NM.prototype,"muteRemoteAudio",1),kA([RM(...SM.TRTC.setRemoteAudioVolume),function(e,t){return hN(((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=kM.get(this))?void 0:a.get(t(...n));c&&c>0&&clearTimeout(c);let l=window.setTimeout((()=>{i.apply(this,n)}),e);kM.has(this)?null==(s=kM.get(this))||s.set(t(...n),l):kM.set(this,new Map([[t(...n),l]]))}))}(200,(e=>e)),bM()],NM.prototype,"setRemoteAudioVolume",1),kA([RM(...SM.TRTC.enableAudioVolumeEvaluation)],NM.prototype,"enableAudioVolumeEvaluation",1),kA([IM(SM.TRTC.startMixTranscode)],NM.prototype,"startMixTranscode",1),kA([aM((e=>"a".concat(e.userId)),(()=>!0))],NM.prototype,"_startRemoteAudio",1),kA([hN((e=>function(t){return DA(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(RA(IA({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),cM((e=>"a".concat(e.userId)))],NM.prototype,"_stopRemoteAudio",1),kA([cM("room")],NM.prototype,"_exitRoom",1),kA([cM("screen")],NM.prototype,"_stopScreenShare",1);var MM=NM;bA(qA()),bA(qA(),1);function LM(){return DA(this,null,(function*(){let e,t;try{let t=yield rN();e=t&&t.length}catch(u){}try{let e=yield nN();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:a}=this.checkSystemResult.detail,s=XP.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};hO.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),hO.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}bA(qA(),1);bA(qA());var xM=bA(QA());bA(qA());var VM="1",UM="5",FM="2",jM="3",BM="4",HM="DISCONNECTED",GM="CONNECTING",WM="CONNECTED",JM={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},zM=[JM.UPDATE_REMOTE_MUTE_STAT,JM.UPLINK_NETWORK_STATS,JM.USER_LIST_RES,JM.MUTE_RESULT],KM={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"},qM="publish_change",QM="join",YM="leave",XM="quality_report",$M="mute_uplink",ZM="publish",eL="publish_state_change",tL="unpublish",iL="subscribe",rL="unsubscribe",nL="subscribe_change",oL="start_publishing",aL="stop_publishing",sL="start_push_user_cdn",cL="stop_push_user_cdn",lL="start_mcu_mix",dL="stop_mcu_mix",uL="get_user_list",hL="change_role",pL="update_constraint_config";bA(qA()),bA(qA());var mL=bA(QA());bA(qA());var _L=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:e}=this,t=this.dataView.byteLength-2,i=[],r=0;for(let o=e;o<=t;o++){let e=this.dataView.getInt8(o);switch(e){case 0:case 1:case 2:case 3:2===r&&(i.push(3),r=0),0==e?r++:r=0,i.push(e);break;default:r=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}removePreventionByte(){let{seiPayloadStartIndex:e}=this,t=this.dataView.byteLength-1,i=[],r=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:r++,i.push(this.dataView.getInt8(o));break;case 3:2!==r&&i.push(this.dataView.getInt8(o)),r=0;break;default:i.push(this.dataView.getInt8(o)),r=0}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}get 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}},fL=class{constructor(e,t,i){this._isUplink=i,this._connection=e,this._log=t,this._seiMessageList=[],this._seiPayloadType=243,this._mainVideoSenderOrReceiver=null,this._mainVideoAbortController=null,this._abortMap=new Map,this.onSEIMessage=null}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,{signal:this._mainVideoAbortController.signal}).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)===CC?this.isRunning?this.restart(e):this.start(e):this.pipeSenderOrReceiver(e))}))}catch(FN){this._log.warn(FN)}}pipeSenderOrReceiver(e){let{readable:t,writable:i}=e.createEncodedStreams(),r=new AbortController;this._abortMap.set(e,r),t.pipeTo(i,{signal:r.signal}).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 _L(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")),uP(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 _L(new DataView(new Uint8Array(n).buffer),!0)}},gL=0,vL=!1,TL=new Set,SL=!1,yL=class{constructor(e){wA(this,"userId"),wA(this,"tinyId"),wA(this,"_sdpSemantics"),wA(this,"_isUplink"),wA(this,"_room"),wA(this,"_log"),wA(this,"_signalChannel"),wA(this,"_isErrorObserved",!1),wA(this,"_waitForPeerConnectionConnectedPromise"),wA(this,"_waitForPeerConnectionConnectedPromiseReject",null),wA(this,"_peerConnection",null),wA(this,"_emitter",new mL.default),wA(this,"_currentState","DISCONNECTED"),wA(this,"_isReconnecting",!1),wA(this,"_reconnectionCount",0),wA(this,"_reconnectionTimer",-1),wA(this,"_isFirstConnection",!0),wA(this,"_prevTime",-1),wA(this,"_enableSEI"),wA(this,"_sei"),wA(this,"_localAddress"),wA(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=KP.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&&xD&&(this._sei=new fL(this,this._log,this._isUplink))}beforeConnect(){this._prevTime<0&&(this._prevTime=AP())}afterConnect(e){return DA(this,null,(function*(){try{yield e,this._isFirstConnection?(this._isFirstConnection=!1,HP.emit(JP.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",cost:Math.min(AP()-this._prevTime,3e4)})):this._isReconnecting&&HP.emit(JP.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",cost:AP()-this._prevTime}),this._prevTime=-1}catch(t){throw this._isFirstConnection?(this._isFirstConnection=!1,HP.emit(JP.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",error:t})):this._isReconnecting&&this._reconnectionCount>=3&&HP.emit(JP.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",error:t}),t}}))}initialize(){let e={encodedInsertableStreams:this._enableSEI&&xD,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.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),TL.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 iD({code:eD.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return tb;let e=null;if(this._isUplink){if(!kD()||0===this._peerConnection.getSenders().length)return tb;e=this._peerConnection.getSenders()[0].transport}else{if(!bD()||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 iD({message:r,code:eD.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(),hO.logSuccessEvent({userId:this._room.userId,eventType:hb}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(gL=0,vL=!1,SL=!0,TL.add(this)):TL.delete(this),HP.emit(JP.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 DA(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(vD(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 iD({code:eD.API_CALL_ABORTED,message:Jw({key:Uw,data:"leave room"})})))},n=()=>{HP.off(JP.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new iD({code:eD.API_CALL_TIMEOUT,message:"connection timeout"});gL+=1,(e=>gL>2&&!vL&&0===TL.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),vL=!0,this._emitter.emit("firewall-restriction")),t(e)}),1e4);HP.on(JP.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(jM,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 iD({code:this._isUplink?eD.UPLINK_RECONNECTION_FAILED:eD.DOWNLINK_RECONNECTION_FAILED,message:Jw({key:this._isUplink?aw:nw})});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(jM,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"))}};bA(qA());var EL=bA(ZA()),IL=function(e){return EL.default.parse(e)},RL=function(e){return EL.default.write(e)};function AL(e){return Object.keys(e).filter((t=>e[t]))}bA(qA());var CL=class extends yL{constructor(e){super(RA(IA({},e),{isUplink:!1})),wA(this,"_flag",0),wA(this,"role","anchor"),wA(this,"remoteAudioTrack"),wA(this,"remoteVideoTrack"),wA(this,"remoteAuxiliaryTrack"),wA(this,"ssrc",{audio:0,video:0,auxiliary:0}),wA(this,"_isSDPExchanging",!1),this.flag=e.flag,this.remoteAudioTrack=new RN(this._room,this),this.remoteVideoTrack=new AN(this._room,this),this.remoteAuxiliaryTrack=new CN(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 DP(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===GC?!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===$C?GC:PC;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=AC;i.kind===CC&&(n=r===GC?CC:PC);let o=this.remoteAudioTrack;n===CC?o=this.remoteVideoTrack:n===PC&&(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=IL(e);return t.media.forEach((e=>{e.type===CC&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),RL(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=IL(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),RL(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}isSubscribeSmall(e){return hP(e.smallVideo)&&!this.subscribeState.smallVideo}subscribe(e,t){return DA(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(rC){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(rC.message," ").concat(JSON.stringify(this.muteState))),new iD({code:eD.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):rC}}))}unsubscribe(e){return DA(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=IA({},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(AL(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=rL,n=KM.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=nL,n=KM.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 iD({code:i.code,message:Jw({key:rw,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return DA(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 DA(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:iL,commandDesc:"exchange sdp",data:r,responseCommand:KM.SUBSCRIBE_RESULT,timeout:1e4});if(!this._peerConnection){let e=new iD({code:eD.INVALID_OPERATION,message:Jw({key:Vw})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}}))}createOffer(){return DA(this,null,(function*(){let e={voiceActivityDetection:!1};PD()&&this._sdpSemantics===_b?(this._peerConnection.addTransceiver(AC,{direction:QC}),this._peerConnection.addTransceiver(CC,{direction:QC}),this._peerConnection.addTransceiver(CC,{direction:QC})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield pD();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=IL(e);return t.media.forEach((e=>{var t,i;if(e.type===CC){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(" ")}})),RL(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=IL(e);return t.media.forEach((e=>{e.type===AC&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),RL(t)}(t.sdp),this._sdpSemantics===_b&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)}))}onSubscribeResult(e){return DA(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(1028===t)throw new iD({code:eD.NOT_SUPPORTED_H264,message:Jw({key:Ow})});try{if(0!==t)throw new iD({code:t,message:Jw({key:ow,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(n)),yield this._peerConnection.setRemoteDescription({type:r,sdp:n}),this.updateSSRC(n)}catch(o){throw this._log.error(o),o}}))}updateSSRC(e){try{IL(e).media.forEach((e=>{if(e.ssrcs)if(e.type===AC){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes($C)}));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($C)})),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){}}getSubscribeState(){return this.subscribeState}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return DA(this,null,(function*(){if(!(PA(CL.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=lP(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}},bL=CL;kA([hN((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 iD({code:eD.API_CALL_ABORTED,message:Jw({key:Uw,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],bL.prototype,"subscribe",1),kA([uN(yL.prototype.afterConnect),dN(yL.prototype.beforeConnect)],bL.prototype,"connect",1);var kL=bL;bA(qA()),bA(qA()),bA(qA());var wL=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"}),PL=class{constructor(e){wA(this,"width"),wA(this,"height"),wA(this,"canvas"),wA(this,"offscreen"),wA(this,"smallGenerator"),wA(this,"smallWritable"),wA(this,"bigProcessor"),wA(this,"bigReadable"),wA(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(wL)),KP.info("init worker processor success")}catch(FN){KP.warn("init worker processor failed. ".concat(FN.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()}};bA(qA());var DL=class{constructor(e){wA(this,"_player"),wA(this,"_canvas"),wA(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}},OL=class{constructor(e){wA(this,"_player"),wA(this,"_processor"),wA(this,"_initOffscreenSuccess"),wA(this,"_localVideoTrack"),wA(this,"_interval"),this._localVideoTrack=e,this._player=e.player,this._processor=null,this._initOffscreenSuccess=!1}initialize(){return DA(this,null,(function*(){if(uD()&&(null==navigator?void 0:navigator.hardwareConcurrency)>=6)try{yield this.initOffscreen(),this._initOffscreenSuccess=!0,KP.info("Initialize VideoGenerator successfully!")}catch(FN){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=lO.run(Mb,this.render.bind(this),{fps:i.frameRate})),t}render(){this._processor instanceof DL&&this._processor.drawVideoToCanvas()}destroy(){lO.clearTask(this._interval),this._processor&&this._processor.destroy()}initOffscreen(){this._processor=new PL({videoTrack:this._localVideoTrack.mediaTrack})}initCanvas(){this._player=new FO({track:this._localVideoTrack.mediaTrack,muted:!0,objectFit:"cover",mirror:!1,container:null,id:"video-player",log:this._localVideoTrack.log}),this._player.play().then((()=>{KP.info("VideoGenerator: play local video success")})).catch((()=>{KP.error("VideoGenerator: Failed to play local video")})),this._processor=new DL(this._player)}getSmallVideoProfile(e){let t=this._localVideoTrack.mediaTrack,i=this._localVideoTrack.profile;if(MD){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 KP.info("big res: ".concat(i.width,"*").concat(i.height," small res: ").concat(e.width,"*").concat(e.height," ")),n>o?r=n/o:(KP.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}}},NL={voiceActivityDetection:!1},ML=class extends yL{constructor(e){super(RA(IA({},e),{isUplink:!0})),wA(this,"localMainAudioTrack",null),wA(this,"localMainVideoTrack",null),wA(this,"localAuxAudioTrack",null),wA(this,"localAuxVideoTrack",null),wA(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),wA(this,"_isSDPExchanging",!1),wA(this,"_isPublishingAux",!1),wA(this,"_publishingLocalAudioTrack"),wA(this,"_publishingLocalVideoTrack"),wA(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}),wA(this,"_smallGenerator"),wA(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&&(wD()?(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===AC?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 DA(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e;let o;return t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),r&&(t._publishingLocalVideoTrack=r),t._isPublishingAux=n,r&&!n&&r.small&&(t._smallGenerator=new OL(r),yield t._smallGenerator.initialize(),o=t._smallGenerator.generateSmallVideoTrack(r.small)),t.updateMediaSettings(),PD()?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(),{localAudioTrack:i,localVideoTrack:r}}()}))}publishByTransceiver(e){return DA(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&&Qk&&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||AC,{direction:qC,streams:[e]}),t._peerConnection.addTransceiver(o?CC:a||CC,{direction:qC,streams:[e]}),t._peerConnection.addTransceiver(n||CC,{direction:qC,streams:[e]}),t._peerConnection.addTransceiver(o&&a||CC,{direction:qC,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:AC})),a){let i=o?3:1;yield c[i].sender.replaceTrack(a),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:CC,videoType:o?PC:wC}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:CC,videoType:kC}),e.push(2))}yield t.setTransceiverDirection(qC,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 DA(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 DA(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!wD()){if(i&&i.mediaTrack&&!r&&t.localMainVideoTrack)return yield t.removeTrack(i),void(t.localMainAudioTrack=null);if(r&&r.mediaTrack&&!i&&t.localMainAudioTrack)return yield t.removeTrack(r),void(t.localMainVideoTrack=null);let e=yield t.doUnpublish();return t.uninstallTrackMuteEvents(i,r),t.emitConnectionStateChangedEvent("DISCONNECTED",r),e}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(IA({},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(IA({},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(KC,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 DA(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:eL,data:t,responseCommand:KM.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:tL,commandDesc:"unpublish",responseCommand:KM.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===eD.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),MD){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:pL,data:this._mediaSettings,responseCommand:KM.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch(this._log.warn)}addTrack(e){return DA(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?PC:GC," stream")),null==(t=this._sei)||t.handleEncodedStreams(),wD()?yield this.addTrackByTransceiver(e,i):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return DA(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers(),n=e.mediaTrack;if(e.kind===AC)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 OL(this.localMainVideoTrack),yield this._smallGenerator.initialize();let e=this._smallGenerator.generateSmallVideoTrack(this.localMainVideoTrack.small);yield r[2].sender.replaceTrack(e)}r[e].direction===KC&&(yield this.setTransceiverDirection(qC,[e]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return DA(this,null,(function*(){if(!e.mediaTrack)return;let t=e.mediaTrack;wD()&&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===CC&&e instanceof _N&&e.small){this._smallGenerator=new OL(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=IL(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===CC)return!0;return!1}removeSender(e){let t=null;wD()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&uP(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return DA(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?PC:GC," stream")),wD()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return DA(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===AC)this._audioManager&&!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(KC,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return DA(this,null,(function*(){if(!Xb)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(KC,"|").concat(QC,"|").concat(qC,")")))&&o++,t.includes(o)){if(e===KC&&i.includes("a=".concat(QC)))return r=!0,"a=".concat(e);if(e===qC&&i.includes("a=".concat(KC)))return r=!0,"a=".concat(QC)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:a}))}))}removeTrackBySender(e){return DA(this,null,(function*(){var t,i;if(!e.mediaTrack)return;if(e.kind===CC&&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===CC&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===CC&&this.removeSender(e)})))),yield this.updateOffer("remove",e.mediaTrack)}))}replaceTrack(e){return DA(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?PC:GC," stream")),n.kind===AC&&r[0])this._audioManager.addAudioTrack(e),this._audioManager.isMixed&&(n=this._audioManager.mediaStreamTrack),yield r[0].replaceTrack(n);else if(n.kind===CC){if(!o&&r[1]&&(yield r[1].replaceTrack(n),this._smallGenerator&&r[2])){this._log.info("replacing smallVideo"),this._smallGenerator.destroy(),this._smallGenerator=new OL(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 DA(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(NL);Xb&&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===CC?"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:qM,data:n,responseCommand:KM.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 DA(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!ND())return o?r===CC?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e=0;r===CC&&(e=n===kC?2:n===PC?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===CC?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";Xb&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===kC?n=1:i===PC&&(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 Xb&&(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 DA(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}}))}exchangeSDP(){return DA(this,null,(function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP(),this._isSDPExchanging=!1}catch(e){throw this._isSDPExchanging=!1,e}}))}createOffer(){return DA(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(NL);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}}))}doExchangeSDP(){let e={command:ZM,responseCommand:KM.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof TN||this.localAuxVideoTrack instanceof TN,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=IL(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),RL(r)}acceptAnswer(e){return DA(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?PC:wC;a=yield this.setBandwidth({bandwidth:e,type:CC,sdp:a,videoType:t})}o&&(a=yield this.setBandwidth({bandwidth:o,type:AC,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:CC,videoType:kC,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($M,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return DA(this,null,(function*(){if(!(PA(ML.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:tL,responseCommand:KM.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=lP(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)&&HP.emit(JP.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{IL(e).media.forEach(((e,t)=>{if(e.type===AC){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]:CC;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===PC&&t[3]&&t[3].track)return t[3].track.id;if(e===CC&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===CC){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===PC){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw 1028===e?(this._log.error(jw.NOT_SUPPORTED_H264ENCODE),new iD({code:eD.NOT_SUPPORTED_H264,message:Jw({key:Dw})})):new iD({code:eD.UNKNOWN,message:Jw({key:Lw,data:{signalResponse:KM.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}},LL=ML;kA([hN((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 iD({code:eD.API_CALL_ABORTED,message:Jw({key:Uw,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],LL.prototype,"publish",1),kA([uN(yL.prototype.afterConnect),dN(yL.prototype.beforeConnect)],LL.prototype,"connect",1);var xL=LL;bA(qA());bA(qA());var VL=bA(QA()),UL=class extends VL.default{constructor(e){let{signalChannel:t,room:i}=e;super(),wA(this,"_room"),wA(this,"_signalChannel"),wA(this,"_log"),wA(this,"_uplinkRTT",0),wA(this,"_uplinkLoss",0),wA(this,"_downlinkRTT",0),wA(this,"_downlinkLoss",0),wA(this,"_downlinkPrevStatMap",new Map),wA(this,"_downlinkLossAndRTTMap",new Map),wA(this,"_interval",-1),wA(this,"_uplinkNetworkQuality",0),wA(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=KP.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(KM.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(FM,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 DA(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 DA(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!bD())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&&mP(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===AC||e.mediaType===CC)&&(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===HM?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state===WM&&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(dO,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=lO.run(Nb,(()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];HP.emit(JP.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(UL.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&&(lO.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})}}))}},FL=UL;wA(FL,"EVENT_NETWORK_QUALITY","0"),bA(qA(),1),bA(qA(),1),bA(qA(),1);var jL=new WeakMap;function BL(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,a){let s=BP({retryFunction:a.value,settings:t,onError(t,r,n){i&&i.call(this,t,(()=>{var i;null!=(i=jL.get(e))&&i.has(o)?r():n(t)}),n)},onRetrying:(t,i)=>{var n;uP(r)&&r(t,i),null!=(n=jL.get(e))&&n.has(o)&&(jL.get(e).get(o).stopRetry=i)},onRetryFailed:n});return a.value=function(){let t=jL.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}):jL.set(e,new Map([[o,{args:r}]])),s.apply(this,r).finally((()=>{var t;return null==(t=jL.get(e))?void 0:t.delete(o)}))},a}}function HL(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=jL.get(e))&&n.has(t)){let{stopRetry:n,args:a}=jL.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=jL.get(e))||o.delete(t))}return a.apply(this,c)},o}}var GL=class{constructor(e){wA(this,"_frameWorkType"),wA(this,"_component"),wA(this,"_room"),wA(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),wA(this,"_keyPrefix"),wA(this,"_log"),wA(this,"_intervalId"),wA(this,"_firstPublishedUserList"),wA(this,"_networkQuality"),wA(this,"_basicInfo"),wA(this,"_pathJoinRoom"),wA(this,"_pathLeaveRoom"),wA(this,"_pathMainVideoMap"),wA(this,"_pathMainAudioMap"),wA(this,"_pathAuxiliaryMap"),wA(this,"_remoteStreamStatMap"),wA(this,"_localStreamStat"),wA(this,"_apiSuccessRateMap",new Map),wA(this,"_eventMap",new Map),this._frameWorkType=e.frameWorkType||30,this._component=e.component||0,this._room=e.room,this._keyPrefix="key_point",this._log=KP.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&uP(this[e])&&(this[e]=Zw({fn:this[e],context:this}))})),this.initData(),this.installEvents(),this._intervalId=lO.run(Nb,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:iC,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:SC[Xw()],uint32_framework:this._frameWorkType,uint32_component:this._component},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),HP.on(e,t),this}installEvents(){this._room.once("banned",(()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId}))),this.addEvent(JP.JOIN_START,this.handleJoinStart).addEvent(JP.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(JP.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(JP.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(JP.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(JP.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(JP.JOIN_FAILED,this.handleJoinFailed).addEvent(JP.LEAVE_START,this.handleLeaveStart).addEvent(JP.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(JP.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(JP.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(JP.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(JP.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(JP.PUBLISH_START,this.handlePublishStart).addEvent(JP.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(JP.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(JP.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(JP.PLAY_TRACK_START,this.handlePlayStart).addEvent(JP.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(JP.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!TP(t)||!this.hitTest(t.room)||"PLAYING"===i&&(r===AC?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(JP.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(JP.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(JP.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(JP.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(JP.API_SUCCESS_RATE,this.handleAPISuccessRate)}uninstallEvents(){this._eventMap.forEach(((e,t)=>HP.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),lO.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 iD?Number(i.getExtraCode()||i.getCode()):eD.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(IA({},zL),{msg_user_info:new KL({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 KL({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(!TP(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(!TP(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/Zk*100)>0&&(this._localStreamStat.totalAudioLevel+=e/Zk,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*yA(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/Zk*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/Zk,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 iD?i.getExtraCode()||i.getCode():{NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5}[i.name]||eD.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=qL[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{code:e,extraCode:t}=r;hO.uploadEvent({log:"stat-".concat(i,"-failed-").concat(t||e||eD.UNKNOWN),userId:this._room.userId,error:r});let n={int32_error_code:t||e,error_count:1};a.msg_error_code.push(n)}else mP(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 DA(this,null,(function*(){try{let e=GD.getItem(this._storageKey);e&&(yield this.upload(e),GD.deleteItem(this._storageKey))}catch(FN){this._log.warn(FN)}}))}setStorage(){this.prepareReport();let e=this.getReportData();0!==e.msg_path_enter_room.uint64_start_time&&GD.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,AC),e.statsToReport.uint32_video_play_time=n.getDuration(t,CC)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,JL);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>JL&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+JL):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>JL&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+JL):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>JL&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+JL)}getReportData(){return{uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new KL({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:MP(this._signalInfo.relayIp),uint32_client_ip:MP(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:MP(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,msg_function_request_stats:[...this._apiSuccessRateMap.values()]}}report(){return DA(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),GD.deleteItem(this._storageKey),this.initData()}catch(FN){this._log.warn(FN)}}))}upload(e){return DA(this,null,(function*(){if(Yk||0===e.msg_path_enter_room.uint64_start_time||[cC,lC,dC].findIndex((e=>e===location.host))>=0)return;let t=Number(this._room.sdkAppId),i=qw(t,_C),r=yield jP({url:i,body:JSON.stringify(e)});if("ok"!==r.data)throw"key point upload failed: ".concat(r.data)}))}};kA([BL({settings:{timeout:500,retries:3}})],GL.prototype,"upload",1);var WL,JL=5e3,zL={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},KL=class{constructor(e){wA(this,"str_identifier"),wA(this,"str_tinyid"),wA(this,"uint32_role"),this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},qL=((WL=qL||{})[WL.enterRoom=50001]="enterRoom",WL[WL.exitRoom=50002]="exitRoom",WL[WL.switchRole=50003]="switchRole",WL[WL.destroy=50004]="destroy",WL[WL.startLocalAudio=50005]="startLocalAudio",WL[WL.updateLocalAudio=50006]="updateLocalAudio",WL[WL.stopLocalAudio=50007]="stopLocalAudio",WL[WL.startLocalVideo=50008]="startLocalVideo",WL[WL.updateLocalVideo=50009]="updateLocalVideo",WL[WL.stopLocalVideo=50010]="stopLocalVideo",WL[WL.startScreenShare=50011]="startScreenShare",WL[WL.updateScreenShare=50012]="updateScreenShare",WL[WL.stopScreenShare=50013]="stopScreenShare",WL[WL.enableAudioVolumeEvaluation=50014]="enableAudioVolumeEvaluation",WL[WL.startRemoteVideo=50015]="startRemoteVideo",WL[WL.updateRemoteVideo=50016]="updateRemoteVideo",WL[WL.stopRemoteVideo=50017]="stopRemoteVideo",WL[WL.muteRemoteAudio=50018]="muteRemoteAudio",WL[WL.setRemoteAudioVolume=50019]="setRemoteAudioVolume",WL[WL.startMixTranscode=50020]="startMixTranscode",WL[WL.stopMixTranscode=50021]="stopMixTranscode",WL[WL.startPublishCDNStream=50022]="startPublishCDNStream",WL[WL.stopPublishCDNStream=50023]="stopPublishCDNStream",WL[WL.PeerConnectionConnect=50024]="PeerConnectionConnect",WL[WL.PeerConnectionReconnect=50025]="PeerConnectionReconnect",WL[WL.WebsocketConnect=50026]="WebsocketConnect",WL[WL.WebsocketReconnect=50027]="WebsocketReconnect",WL[WL.schedule=50028]="schedule",WL),QL=GL;bA(qA(),1),bA(qA(),1);var YL=class{constructor(){wA(this,"_startTime"),wA(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=AP())}stop(){0===this._endTime&&(this._endTime=AP())}getDuration(){return 0===this._endTime?AP()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},XL=class{constructor(e){wA(this,"_room",null),wA(this,"_durationMap"),wA(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(JP.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(JP.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(JP.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"),AC),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_","main"),CC),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_","auxiliary"),CC);let a=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);!a||(!i.hasAudio&&r.hasAudio&&a.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,AC,"main"),!i.hasVideo&&r.hasVideo&&a.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,CC,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&a.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,CC,"auxiliary"))})),this._eventMap.forEach(((e,t)=>HP.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>HP.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 YL,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,AC);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let e=new YL,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,CC)}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,AC),this.stopDurationItem(o,CC)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new YL,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===AC?[n]:[],video:t===AC?[]:[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()}};bA(qA(),1);var $L=class{constructor(e){wA(this,"_room"),wA(this,"_renderFreezeMap",new Map),wA(this,"_isVideoPlayingEventFiredMap",new Map),wA(this,"_dataFreezeMap",new Map),wA(this,"_monitorFreezeData",new Map),wA(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(JP.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(JP.PLAY_TRACK_START,this.onPlayTrackStart).set(JP.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(JP.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(JP.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(TP(t)&&this.hitTest(t.room)&&n===CC){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===MC?this.onVideoTrackMuted(t):r===LC&&this.onVideoTrackUnmuted(t)}})).set(JP.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>HP.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>HP.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 YL;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 DA(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=AP();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=AP();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!TP(t)||!this.hitTest(t.room)||t.kind!==CC||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=AP()-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()}};bA(qA(),1);var ZL=bA(eC(),1),ex=class{constructor(e){wA(this,"_room"),wA(this,"_log"),wA(this,"_config",null),wA(this,"_data"),wA(this,"_remoteVideoTrackMap",new Map),this._room=e,this._log=KP.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(){HP.on(JP.REMOTE_TRACK_SUBSCRIBED,this.onSubscribed,this),HP.on(JP.REMOTE_TRACK_UNSUBSCRIBED,this.onUnSubscribed,this),HP.on(JP.REMOTE_PUBLISH_STATE_CHANGED,this.onRemotePublishedChanged,this)}uninstallEvents(){HP.off(JP.REMOTE_TRACK_SUBSCRIBED,this.onSubscribed,this),HP.off(JP.REMOTE_TRACK_UNSUBSCRIBED,this.onUnSubscribed,this),HP.off(JP.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!==CC||(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!==CC||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 DA(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 DA(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(uC," and try later, refer to ").concat(pC,"tutorial-26-advanced-publish-cdn-stream.html")),t._log.error("startMixTranscode failed, errCode: ".concat(a," errMsg: ").concat(s)),new iD({code:eD.START_MIX_TRANSCODE_FAILED,message:Jw({key:Aw,data:{message:s},link:{className:"Client",fnName:"startMixTranscode"}})});t._data=e}()}))}reStartMixTranscode(){!this.isMixing||this._config&&this.startMixTranscode(this._config)}stopMixTranscode(){return DA(this,null,(function*(){if(!this.isMixing)throw new iD({code:eD.INVALID_OPERATION,message:Jw({key:bw})});yield this.doStopMixTranscode(),this.resetIsUsedFlag()}))}doStopMixTranscode(){return DA(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 iD({code:eD.STOP_MIX_TRANSCODE_FAILED,message:Jw({key:Cw,data:{message:r},link:{className:"Client",fnName:"stopMixTranscode"}})});this._data=void 0}))}getOutputSessionId(e){let{config:t,userId:i,roomId:r}=e;return pP(t.streamId)&&t.streamId.length>0?t.streamId:(0,ZL.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:hP(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:hP(e.videoWidth)?640:e.videoWidth,height:hP(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)}))}};bA(qA(),1);var tx=bA(eC(),1);function ix(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:GC;return t=Kw(e)?i===GC?bb:kb:i===GC?Ab:Cb,"https://".concat(t,"/api/v1/config")}function rx(e,t,i){return new Promise(((r,n)=>{jP({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)}))}bA(qA(),1);var nx=(e,t)=>BP({retryFunction:rx,settings:{retries:3,timeout:0},onError:t,onRetrying:e});function ox(e,t,i){return new Promise(((r,n)=>{let o=null;RP([nx((e=>t.count[0]=e+1),((e,i)=>{t.msg[0]=e.message,o||i()}))(ix(i,GC),e,{get timeout(){return 1e3*cP(2+t.count[0])}}),nx((e=>t.count[1]=e+1),((e,i)=>{t.msg[1]=e.message,o||i()}))(ix(i,WC),e,{get timeout(){return 1e3*cP(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}var ax=0,sx=class extends nO{constructor(e){super("room"),this.seq=ax++,this.role="anchor",this.localTracks=new Set,this.enableAutoPlayDialog=!0,this.autoReceiveAudio=!0,this.autoReceiveVideo=!0,this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null},this._log=KP.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this._isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,_P(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),_P(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),_P(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this.keyPointManager=new QL({room:this,frameWorkType:e.frameWorkType,component:e.component}),this.callDurationCalculator=new XL({room:this}),this.badCaseDetector=new $L({room:this}),this.mixTranscodeManager=new ex(this),this.publishCDNManager=new class{constructor(e){wA(this,"_room"),wA(this,"_publishTencentMainStreamObj",{params:null,streamId:void 0,isPublishing:!1}),wA(this,"_publishTencentAuxStreamObj",{params:null,streamId:void 0,isPublishing:!1}),wA(this,"_publishGivenCDNData",null),wA(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,tx.default)(e)),"".concat(this._room.sdkAppId,"_").concat(e)}return e}convertStreamType(e){return"main"===e?e:"aux"}generatePublishCDNSessionId(e){return(0,tx.default)("".concat(this._room.roomId,"_").concat(this._room.userId,"_").concat(this.convertStreamType(e)))}startPublishCDN(e){return DA(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 DA(this,null,(function*(){if(!this._isPublishingTencentCDN)throw new iD({code:eD.INVALID_OPERATION,message:Jw({key:Sw})});yield this.stopPublishTencentCDN(),this._isPublishingGivenCDN&&(yield this.stopPublishGivenCDN())}))}startPublishTencentCDN(e){return DA(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 DA(this,null,(function*(){try{KP.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(uC," and try later, refer to ").concat(pC,"tutorial-26-advanced-publish-cdn-stream.html")),KP.error("startPublishTencentCDN failed, errCode: ".concat(r,", errMsg: ").concat(n)),new iD({code:eD.START_PUBLISH_CDN_FAILED,message:Jw({key:yw,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 DA(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 DA(this,null,(function*(){let t={requestTime:Date.now(),sessionId:(0,tx.default)("".concat(this._room.roomId,"_").concat(this._room.userId,"_").concat(this.convertStreamType(e)))};KP.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 KP.error("stopPublishTencentCDN failed, errCode: ".concat(r," errMsg: ").concat(n)),new iD({code:eD.STOP_PUBLISH_CDN_FAILED,message:Jw({key:Ew,data:{message:n},link:{className:"Client",fnName:"stopPublishCDNStream"}})});KP.warn("stopPublishTencentCDN failed, can not stopPublishTencentCDN in auto relayed-push mode"),this.resetPublishTencentParam(e)}}))}startPublishGivenCDN(e){return DA(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(KP.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 KP.error("startPublishGivenCDN failed, errCode: ".concat(t,", errMsg: ").concat(r)),this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1,new iD({code:eD.START_PUBLISH_CDN_FAILED,message:Jw({key:yw,data:{message:r},link:{className:"Client",fnName:"startPublishCDNStream"}})})}catch(r){throw this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1,r}}))}stopPublishGivenCDN(){return DA(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};KP.info("stopPublishGivenCDN: ".concat(JSON.stringify(n)));let o=yield this._room.sendStopPublishCDN(n,!1),{code:a,message:s}=o.data;if(0!==a)throw KP.error("stopPublishGivenCDN failed, errCode: ".concat(a," errMsg: ").concat(s)),new iD({code:eD.STOP_PUBLISH_CDN_FAILED,message:Jw({key:Ew,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={};pP(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 DA(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return DA(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return DA(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}getRemoteAudioStats(){return DA(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return DA(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 DA(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 iD({code:eD.INVALID_OPERATION,message:Jw({key:Rw,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(jw.INVALID_DESTROY),new iD({code:eD.INVALID_OPERATION,message:Jw({key:_w})});this._log.info("destroy room"),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this._isDestroyed=!0,HP.emit(JP.ROOM_DESTROY,{room:this})}startMixTranscode(e){return this.mixTranscodeManager.startMixTranscode(e)}stopMixTranscode(){return this.mixTranscodeManager.stopMixTranscode()}startPublishCDNStream(){return DA(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 iD({code:eD.INVALID_OPERATION,message:Jw({key:Tw})});if("auxiliary"===t.streamType&&!e.isAuxStreamPublished)throw new iD({code:eD.INVALID_OPERATION,message:Jw({key:Tw})})}yield e.publishCDNManager.startPublishCDN(t)}()}))}stopPublishCDNStream(){return this.publishCDNManager.stopPublishCDN()}schedule(e,t,i){return DA(this,null,(function*(){var r,n;let o=AP();try{let a=yield function(e){return DA(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=AP(),d=yield ox(c,e,i);return e.delta=AP()-l,d}catch(c){let e=gP(c)?c[0]:c,t=mP(e.code)?e.code:0,i="get websocket url failed: ".concat(e.message.includes("timeout")?"timeout":e.message),r=new iD({code:eD.SCHEDULE_FAILED,extraCode:t,message:Jw({key:pw,data:{error:i,code:t}})});throw KP.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=IA(IA({},this.scheduleResult),a),mP(null==(r=a.config)?void 0:r.retryCount)&&function(e){lb=e}(a.config.retryCount),pP(null==(n=a.config)?void 0:n.loggerDomain)&&sC(a.config.loggerDomain),HP.emit(JP.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult}),HP.emit(JP.API_SUCCESS_RATE,{room:this,apiName:"schedule",cost:AP()-o})}catch(a){throw HP.emit(JP.API_SUCCESS_RATE,{room:this,apiName:"schedule",error:a}),a}}))}};bA(qA(),1);var cx=new WeakMap,lx=new WeakMap;function dx(){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(cx.has(this)){let o=cx.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 cx.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=cx.get(this);e&&(e.shift(),e[0]&&n(IA({},e[0])))}))},i}}function ux(e){return function(t,i,r){let n=r.value,o=t=>mP(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(lx.has(r)&&lx.get(r).has(o(i))){let e=lx.get(r).get(o(i));e&&(e.shift(),e[0]&&a(IA({},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(lx.has(this))if(lx.get(this).has(o(t))){let r=lx.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 lx.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}]),lx.set(this,r),a({fn:n,args:t,context:this,resolve:e,reject:i})}}))},r}}bA(qA(),1);var hx=bA(QA(),1),px=Symbol("instance"),mx=Symbol("abortCtrl"),_x=Symbol("cacheResult"),fx=class{constructor(e,t,i){wA(this,"oldState"),wA(this,"newState"),wA(this,"action"),wA(this,"error"),this.oldState=e,this.newState=t,this.action=i}toString(){return"".concat(this.action,"ing")}},gx=class extends Error{constructor(e,t,i){super(t),wA(this,"state"),wA(this,"message"),wA(this,"cause"),this.state=e,this.message=t,this.cause=i}},vx=new Map,Tx=Object.getPrototypeOf(DA(void 0,null,(function*(){}))).constructor;function Sx(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=vx.get(r)||[];vx.has(r)||vx.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 DA(this,null,(function*(){var r;let o=this;if(i.context&&(o=Cx.get("function"==typeof i.context?i.context.call(this,...n):i.context)),o.state===t)return o[_x];let c=null;if(Array.isArray(e)?0==e.length?o[mx]&&(o[mx].aborted=!0):("string"!=typeof o.state||!e.includes(o.state))&&(c=new gx(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 gx(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;Ex.call(o,new fx(l,t,a));let d={aborted:!1};o[mx]=d;try{let e=s.apply(this,n);return o[_x]=e instanceof Tx?yield e:e,d.aborted||(o[mx]=void 0,Ex.call(o,t),null==(r=i.success)||r.call(this,o[_x])),o[_x]}catch(u){let e=u instanceof Error?u.message:String(u);if(Ex.call(o,l,e),!i.fail){if(i.ignoreError)return u;throw u}i.fail.call(this,new gx(o._state,"action '".concat(a,"' failed :").concat(e),u instanceof Error?u:new Error(e)))}}))}}}var yx="undefined"!=typeof window&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:"undefined"!=typeof importScripts?(e,t)=>{postMessage({type:e,payload:t})}:()=>{};function Ex(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(Cx.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t})}var Ix,Rx,Ax=class extends hx.default{constructor(e,t,i){super(),wA(this,"name"),wA(this,"groupName"),wA(this,"_state",Ax.INIT),wA(this,Ix),wA(this,Rx),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[px];r?this.name=r.name+"-"+r.count++:i[px]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=vx.get(e)||[],i=new Set,r=[],n=[],o=new Set,a=Object.getPrototypeOf(e);vx.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=Ax.instances.get(e),t||Ax.instances.set(e,t=new Ax(e,void 0,Object.create(Ax.prototype)))):(t=Ax.instances2.get(e),t||Ax.instances2.set(e,t=new Ax(e.constructor.name,void 0,Object.create(Ax.prototype)))),t}static getState(e){var t;return null==(t=Ax.get(e))?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};yx(Ax.UPDATEAFSM,IA({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){Ex.call(this,e)}},Cx=Ax;Ix=_x,Rx=mx,wA(Cx,"STATECHANGED","stateChanged"),wA(Cx,"UPDATEAFSM","updateAFSM"),wA(Cx,"INIT","[*]"),wA(Cx,"ON","on"),wA(Cx,"OFF","off"),wA(Cx,"instances",new Map),wA(Cx,"instances2",new WeakMap);var{isString:bx,isPlainObject:kx,isUndefined:wx,getNetworkType:Px,getTerminalType:Dx,isEmpty:Ox}=Fb,Nx=class extends sx{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._changeBigSmallRecords=new Map,this._networkQuality=null,this._networkType=Px(),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){wA(this,"_log"),wA(this,"_prevReportTime"),wA(this,"_prevReport",{}),wA(this,"_prevEncoderImplementation"),wA(this,"_prevQualityLimitationReason"),wA(this,"_prevDecoderImplementationMap",new Map),this._log=t,this._prevReportTime=0,this._prevEncoderImplementation="",this._prevQualityLimitationReason=""}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return DA(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{(yield r.getStats()).forEach((t=>{if("outbound-rtp"===t.type)if(t.mediaType===CC){if(!Xb&&hP(t.trackId))return;t.ssrc===n.video&&!hP(t.encoderImplementation)&&this._prevEncoderImplementation!==t.encoderImplementation&&(this._log.info("encoderImplementation change to ".concat(t.encoderImplementation)),this._prevEncoderImplementation=t.encoderImplementation),t.ssrc===n.video&&!hP(t.qualityLimitationReason)&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),this._prevQualityLimitationReason=t.qualityLimitationReason);let e=CC;t.ssrc===n.small?e=kC:t.ssrc===n.auxiliary&&(e=PC),i[e].bytesSent=t.bytesSent,i[e].packetsSent=t.packetsSent,i[e].framesEncoded=t.framesEncoded}else t.mediaType===AC&&(i.audio.bytesSent=t.bytesSent,i.audio.packetsSent=t.packetsSent);else"candidate-pair"===t.type?vD(t)&&mP(t.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*t.currentRoundTripTime)):"media-source"===t.type&&(t.kind===AC?(i.audio.audioLevel=t.audioLevel||0,i.audio.totalAudioEnergy=t.totalAudioEnergy||0):t.kind===CC&&(t.trackIdentifier===e.getVideoTrackId(CC)?i.video.fpsCapture=t.framesPerSecond:t.trackIdentifier===e.getVideoTrackId(PC)?i.auxiliary.fpsCapture=t.framesPerSecond:i.small.fpsCapture=t.framesPerSecond));if(hP(t.audioLevel)||(i.audio.audioLevel=t.audioLevel||0),!hP(t.frameWidth)){let r=kC;t.trackIdentifier===e.getVideoTrackId(CC)||t.ssrc===n.video?r=CC:(t.trackIdentifier===e.getVideoTrackId(PC)||t.ssrc===n.auxiliary)&&(r=PC),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(rC){this._log.warn("failed to getStats on sender connection ".concat(rC))}return i}))}getReceiverStats(e){return DA(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;(yield i.getStats()).forEach((i=>{if("inbound-rtp"===i.type){if(i.mediaType===AC&&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===CC){if(Xb&&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&&vD(i)&&mP(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime));hP(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)),hP(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 DA(this,null,(function*(){let i={};e&&(i=yield this.getSenderStats(e));let r=[];for(let[e,n]of t){let e=yield this.getReceiverStats(n);r.push(e)}return{senderStats:i,receiverStats:r}}))}getDifferenceValue(e,t){if(YO(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r}=e;if(!YO(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*Zk,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(ZC)),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=t.uint32_video_codec_bitrate,o=t.uint32_video_enc_fps,s=t.uint32_video_codec_fps,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(YO(e.msg_audio_status)||YO(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 DA(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 WN(this.userId,this._log),this._version=iC,this.sdpSemantics=fb,wx(e.sdpSemantics)?XP.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;wA(this,"audioContext",null),wA(this,"_destination",null),wA(this,"_localAudioTrack",null),wA(this,"_localScreenAudioTrack",null),wA(this,"_localMediaStreamAudioTrack",null),wA(this,"_audioTrackStreamSource",null),wA(this,"_screenAudioTrackStreamSource",null),wA(this,"_mixedMusicSet",new Set),wA(this,"hasMusic",!1),wA(this,"mixedMusicMap",new Map),wA(this,"cacheMusicMap",new Map),wA(this,"_log"),wA(this,"_originTrack",null),this._log=KP.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 DA(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 yN(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 DA(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);hP(i)||e.setVolume(i),hP(r)||e.loop(r),hP(n)||e.setOperation(n)}}))}addAudioTrack(e){return DA(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=WO(),"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 DA(this,arguments,(function(e){return function*(){}()}))}enableDenoiser(e){return DA(this,null,(function*(){}))}disableDenoiser(){return DA(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=!wx(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI,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 DA(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&&fA)for(var r of fA(e))t.indexOf(r)<0&&TA.call(e,r)&&(i[r]=e[r]);return i})(e,[]);HP.emit(JP.REMOTE_PUBLISH_STATE_CHANGED,IA({room:this},t)),this.emit("remote-publish-state-changed",IA({},t))})),String(e.roomId||e.strRoomId),this._joinOptions=e,new Promise(((t,i)=>DA(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)=>{var r;wx(e.role)||(this.role=20===e.role?"anchor":"audience"),wx(e.privateMapKey)||(this.privateMapKey=e.privateMapKey);let n={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:Dx(),netType:SC[this._networkType],bussinessInfo:this._businessInfo},{bussinessInfo:o,pushUserCdnInfo:a}=this.publishCDNManager.handleCDNConfigForJoinData(this._businessInfo);Object.assign(n,{bussinessInfo:o,pushUserCdnInfo:a}),this._log.debug("join room signal data: ".concat(JSON.stringify(n)));let s=5e3;(null==(r=this.scheduleResult.config)?void 0:r.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(s=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{this._log.error("join room timeout observed"),i(new iD({code:eD.JOIN_ROOM_FAILED,message:Jw({key:hw})}))}),s),HP.emit(JP.JOIN_SEND_CMD,{room:this}),this._signalChannel.once(UM,(e=>{this.clearJoinTimeout(),HP.emit(JP.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),i(e)})),this._signalChannel.send(QM,n),this._signalChannel.once(KM.JOIN_ROOM_RESULT,(e=>{this.clearJoinTimeout();let{code:r,message:n,data:o}=e.data;HP.emit(JP.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,t()):(this._log.error("Join room failed result: ".concat(r," error: ").concat(n)),i(new iD({code:eD.JOIN_ROOM_FAILED,extraCode:r,message:Jw({key:pw,data:{error:n,code:r}})})))}))}))}reJoin(){return DA(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this._joinOptions.roomId)),this._signalChannel.close(),yield this._signalChannel.connect(),yield this.doJoin(RA(IA({},this._joinOptions),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey})),this._log.warn("reJoin success"),hO.logSuccessEvent({userId:this.userId,eventType:ub}),this.checkConnectionsToReconnect(),this.uplinkConnection&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection(),this.mixTranscodeManager.reStartMixTranscode()}catch(e){this._log.warn("reJoin fail ".concat(e)),this.reset(),hO.logFailedEvent({userId:this.userId,eventType:ub,error:e}),this.emit("error",new iD({code:eD.JOIN_ROOM_FAILED,message:Jw({key:mw,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){wA(this,"_room"),wA(this,"_sdkAppId"),wA(this,"_userId"),wA(this,"_userSig"),wA(this,"_url"),wA(this,"_backupUrl"),wA(this,"_urlWithParam"),wA(this,"_backupUrlWithParam"),wA(this,"_socketInUse"),wA(this,"_socket"),wA(this,"_backupSocket"),wA(this,"_backupTimer",-1),wA(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),wA(this,"_currentState",HM),wA(this,"_reconnectionCount",0),wA(this,"_reconnectionTimer",-1),wA(this,"_seq",0),wA(this,"_log"),wA(this,"_emitter"),wA(this,"_lastMessageTime",-1),wA(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=KP.createLogger({id:"ws",userId:this._userId,sdkAppId:this._sdkAppId}),this._emitter=new xM.default}get isConnected(){return this._currentState===WM}get isConnecting(){return this._currentState===GM}get isOnline(){return this._currentState===WM&&Date.now()-this._lastMessageTime<12e3}connect(){return new Promise(((e,t)=>{this._prevTime<0&&(this._prevTime=AP()),this._log.info("connect to ".concat(this._url)),this.emitConnectionStateChanged(GM),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(jM,e),this.once(BM,t)}))}tryConnectBackup(){this._backupSocket||(this.unbindAndCloseSocket(GC),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===GC){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(WC),this._socketInUse=this._socket):(this.unbindAndCloseSocket(GC),this._socketInUse=this._backupSocket),this.emitConnectionStateChanged(WM),this._emitter.emit(jM))}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(HM),(!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(GC)))}onerror(e){let{url:t}=e.target;this._log.error("websocket[".concat(t,"] error observed")),this.isConnected?e.target===this._socketInUse&&(this.unbindAndCloseSocket(GC),this.unbindAndCloseSocket(WC),this._socketInUse=null,this.reconnect(GC)):(this.isReconnecting||HP.emit(JP.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",error:new Error("ws onerror")}),e.target==this._socket?(this.unbindAndCloseSocket(GC),this.reconnect(WC)):(this.unbindAndCloseSocket(WC),this.reconnect(GC)))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now();let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values(JM),o=Object.keys(JM)[n.indexOf(i)],a=KM[o];switch(zM.includes(i)||(this._log.debug("received msg: ".concat(e.data)),this._log.info("Received event: [ ".concat(a||"unknown cmd: ".concat(i)," ]"))),i){case JM.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){xb=e-(new Date).getTime();let t=new Date;t.setTime(e),KP.info("baseTime from server: ".concat(t," offset: ").concat(xb))}(r.svrTime),this._log.info("ChannelSetup Success"),HP.emit(JP.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",cost:AP()-this._prevTime}),this._prevTime=-1,this._emitter.emit(VM,{signalInfo:this._signalInfo});else{let e=new iD({code:eD.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:Jw({key:iw,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),HP.emit(JP.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",error:e}),this._emitter.emit(UM,e)}break;case JM.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 JM.CHANNEL_RECONNECT_RESULT:0===t.code?(this._log.warn("reconnect success"),this.stopReconnection(),HP.emit(JP.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketReconnect",cost:AP()-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]:GC;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 iD({code:eD.SIGNAL_CHANNEL_RECONNECTION_FAILED,message:Jw({key:tw})});return HP.emit(JP.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketReconnect",error:e}),void this._emitter.emit(BM,e)}this._reconnectionCount++,this._log.warn("reconnect ".concat(e," [").concat(this._reconnectionCount,"/").concat(30,"]"));let t=this.getReconnectionUrl(e);this.emitConnectionStateChanged(GM),this._prevTime<0&&(this._prevTime=AP()),e===GC?(this._socket=new WebSocket(t),this.bindSocket(this._socket)):(this._backupSocket=new WebSocket(t),this.bindSocket(this._backupSocket));let i=lP(this._reconnectionCount);this._reconnectionTimer=setTimeout((()=>{this._log.warn("reconnect ".concat(e," timeout(").concat(i/1e3,"s), try again")),this.clearReconnectionTimer(),this.unbindAndCloseSocket(GC),this.unbindAndCloseSocket(WC),this.reconnect(e===GC?WC:GC)}),i)}get isReconnecting(){return-1!==this._reconnectionTimer}getReconnectionUrl(e){let t=e===GC?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 iD({code:eD.API_CALL_TIMEOUT,message:Jw({key:ew,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 BP({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(GC),this.unbindAndCloseSocket(WC),this.emitConnectionStateChanged(HM)}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(FM,{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 FL({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(FL.EVENT_NETWORK_QUALITY,(e=>{this.emit("network-quality",e)}))),this._signalChannel.on(FM,(e=>{HP.emit(JP.SIGNAL_CONNECTION_STATE_CHANGED,IA({room:this},e)),this.emit("signal-connection-state-changed",e)})),this._signalChannel.on(BM,(e=>{this.reset(),this.emit("error",e)})),this._signalChannel.once(VM,(e=>{this.tinyId=e.signalInfo.tinyId,HP.emit(JP.JOIN_SIGNAL_CONNECTION_END,{room:this})})),this._signalChannel.on(KM.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(KM.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})),this._signalChannel.on(KM.UPDATE_REMOTE_MUTE_STAT,(e=>{Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})),this._signalChannel.on(KM.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(hO.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})})),HP.emit(JP.JOIN_SIGNAL_CONNECTION_START,{room:this}),this._signalChannel.connect()}leave(){return DA(this,null,(function*(){try{yield this.doHeartbeat()}catch(e){}HP.emit(JP.LEAVE_SEND_CMD,{room:this}),this._log.info("leave() => leaving room"),this._signalChannel.send(YM),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=lO.run(Nb,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),lO.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return DA(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(BN.has(e)){let t=BN.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc})));return BN.delete(e),t}return[]}(this.userId):[],n=IA({str_sdk_version:tC,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:SC[this._networkType]},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i);HP.emit(JP.HEARTBEAT_REPORT,{room:this,report:n}),this._signalChannel.send(XM,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}}));HP.emit(JP.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 kL({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.getIsReconnecting()&&i.stopReconnection(),i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",(e=>{let i=e.getCode();i!==eD.ICE_TRANSPORT_ERROR&&(i===eD.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",RA(IA({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=lO.run(Nb,this.syncUserList.bind(this)))}stopSyncUserListInterval(){lO.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:KM.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 Jw({key:Lw,data:{signalResponse:KM.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||!SL)return!1;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.getAllConnections().forEach((e=>{if(!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===ob&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}destroy(){this._isDestroyed||(super.destroy(),this._joinReject&&(this._joinReject(new iD({code:eD.INVALID_OPERATION,message:Jw({key:Rw,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return DA(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:hL,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey},responseCommand:KM.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 iD({code:eD.SWITCH_ROLE_FAILED,message:Jw({key:vw,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof iD&&e.getCode()===eD.API_CALL_TIMEOUT&&(e=new iD({code:eD.SWITCH_ROLE_FAILED,message:Jw({key:gw})})),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 DA(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role)return;HP.emit(JP.PUBLISH_START,{room:this});let e={},i={};this._isPublishing=!0,t.forEach((t=>{!t.mediaTrack||(t instanceof mN&&(t instanceof SN?(i.audio=t,this.audioManager.addScreenAudioTrack(t)):(e.audio=t,this.audioManager.addAudioTrack(t))),t instanceof _N&&(t instanceof TN&&2===t.mediaType?i.video=t:e.video=t),t.setPublishStarting())}));try{let r=Ox(e),n=Ox(i);(!r||!n)&&!this.uplinkConnection&&(this.uplinkConnection=new xL({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(IA({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==eD.ICE_TRANSPORT_ERROR&&(t===eD.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===eD.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 DA(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 mN&&(t instanceof SN?i.audio=t:e.audio=t),t instanceof _N&&(t instanceof TN&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");Ox(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),Ox(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.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=>{HP.emit(JP.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return DA(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 DA(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=IA({},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),HP.emit(JP.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(AL(n),"] prev: [").concat(AL(i.subscribeState),"]")),yield i.subscribe(n,r),i.remoteVideoTrack.setMediaType(n.smallVideo?8:4),t.forEach((e=>e.subscribe())),HP.emit(JP.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(rC){let i=rC instanceof iD?rC.getCode():eD.UNKNOWN,n=rC;throw rC instanceof iD?i===eD.REMOTE_STREAM_NOT_EXIST&&(n=new iD({code:eD.API_CALL_ABORTED,message:Jw({key:Fw,data:{message:rC.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new iD({code:i,message:Jw({key:fw,data:{message:rC.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 DA(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)),yield i.unsubscribe({remoteTracks:t,streamType:r}),t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),HP.emit(JP.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,lO.clearTask(this._audioVolumeIntervalId),void(this._audioVolumeIntervalId=null);e=Math.floor(Math.max(e,100)),HP.emit(JP.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&(lO.clearTask(this._audioVolumeIntervalId),this._audioVolumeIntervalId=null),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=lO.run(Mb,(()=>{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 DA(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 DA(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 DA(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 DA(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 DA(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(bx(e)){if(!e.startsWith("wss://"))throw new iD({code:eD.INVALID_PARAMETER,message:"invalid websocket url"});this.proxy_ws=e}else if(kx(e)){let{websocketProxy:t,loggerProxy:i}=e;t&&(this.proxy_ws=t),i&&sC(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(Fb.getTurnServer(e)))):Fb.isPlainObject(e)&&i.push(Fb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:lL,data:e,timeout:5e3,responseCommand:KM.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:dL,data:e,timeout:5e3,responseCommand:KM.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?oL:sL,data:e,timeout:5e3,responseCommand:t?KM.START_PUBLISH_TENCENT_CDN_RES:KM.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?aL:cL,data:e,timeout:5e3,responseCommand:t?KM.STOP_PUBLISH_TENCENT_CDN_RES:KM.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=Fb.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()}checkSubscribeBigSmallVideo(e){return DA(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)||{},o=e.getSubscribeState(),{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(bx(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!wx(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new iD({code:eD.INVALID_PARAMETER,message:Jw({key:sw})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!wx(e.streamId)){if(!(bx(e.streamId)&&String(e.streamId)&&String(e.streamId).length<=64))throw new iD({code:eD.INVALID_PARAMETER,message:Jw({key:cw})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_streamid_main=e.streamId}if(!wx(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new iD({code:eD.INVALID_PARAMETER,message:Jw({key:lw})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!wx(e.userDefinePushArgs)){if(!(bx(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new iD({code:eD.INVALID_PARAMETER,message:Jw({key:dw})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}Ox(t)||(this._businessInfo=JSON.stringify(t))}startPlugin(e,t){return DA(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 DA(this,null,(function*(){"AudioMixer"===e&&(yield this.audioManager.updateMusicSource(t))}))}stopPlugin(e,t){return DA(this,null,(function*(){"AudioMixer"===e&&(yield this.audioManager.removeMusicSource(t))}))}};return kA([Sx(["left",Cx.INIT],"joined"),hN((e=>{let t=new class{constructor(){this._set=new Set,HP.on(JP.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 DA(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 iD({code:eD.INVALID_OPERATION,message:Jw({key:uw})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new iD({code:eD.INVALID_OPERATION,message:Jw({key:Iw,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",HP.emit(JP.JOIN_START,{room:this,roomId:o}),this.checkSystemResult=yield XP.checkSystemRequirementsInternal(),this.checkDestroy();let a=Fb.getEnv();a||(a=fC,this.proxy_ws&&(this.proxy_ws.startsWith(YC)?a=gC:this.proxy_ws.startsWith(XC)&&(a=vC))),hO.setConfig({env:a,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),LM.call(this);let{isH264EncodeSupported:s,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!XP.isWebRTCSupported()||!s&&!c)throw new iD({code:eD.NOT_SUPPORTED,message:Jw({key:Pw})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&(yield this.schedule(o,n,iC));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=Fb.performanceNow(),HP.emit(JP.JOIN_SUCCESS,{room:this}),hO.uploadEvent({log:"stat-conv-".concat(Number(Yk),"-").concat(location.hostname),userId:this.userId}),t}catch(l){throw t.delete({room:this,roomId:o}),HP.emit(JP.JOIN_FAILED,{room:this,error:l}),l}}))}}))],Nx.prototype,"join",1),kA([Sx("joined","left",{ignoreError:!0}),hN((e=>function(){return DA(this,null,(function*(){HP.emit(JP.LEAVE_START,{room:this}),yield e.call(this),HP.emit(JP.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=cx.get(this))||t.forEach((e=>r.push(e))),null==(i=lx.get(this))||i.forEach((e=>e.forEach((e=>r.push(e))))),r.forEach((t=>{t.reject(new iD({code:eD.API_CALL_ABORTED,message:e}))})),cx.delete(this),lx.delete(this),n.apply(this,a)},r}}("leave room"),HL({fnName:"publish",validateArgs:!1}),HL({fnName:"unsubscribe",validateArgs:!1})],Nx.prototype,"leave",1),kA([dx(),BL({settings:{retries:db,timeout:e=>lP(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))}})],Nx.prototype,"publish",1),kA([HL({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=cx.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 iD({code:eD.API_CALL_ABORTED,message:e})),!1)}));cx.set(this,t)}return n.apply(this,i)},r}}("api-call"),dx()],Nx.prototype,"unpublish",1),kA([ux((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),BL({settings:{retries:db,timeout:e=>lP(e)},onError(e,t,i){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),i(e))}})],Nx.prototype,"subscribe",1),kA([HL({fnName:"subscribe",callback(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{let t=this.remotePublishedUserMap.get(e.userId);t&&!t.isMainStreamSubscribed&&!t.isAuxStreamSubscribed&&t.close("you unsubscribed")}))}}),ux((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],Nx.prototype,"unsubscribe",1),MM.create=MM._create.bind(MM,Nx),MM}));
|
|
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}));
|