{"ast":null,"code":"require(\"core-js/modules/es.array.push.js\");require(\"core-js/modules/es.regexp.flags.js\");require(\"core-js/modules/web.url-search-params.delete.js\");require(\"core-js/modules/web.url-search-params.has.js\");require(\"core-js/modules/web.url-search-params.size.js\");require(\"core-js/modules/es.typed-array.to-reversed.js\");require(\"core-js/modules/es.typed-array.to-sorted.js\");require(\"core-js/modules/es.typed-array.with.js\");require(\"core-js/modules/web.dom-exception.stack.js\");!function(e,t){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=t():\"function\"==typeof define&&define.amd?define(t):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).TRTC=t();}(this,function(){function e(e,t){return t.forEach(function(t){t&&\"string\"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(\"default\"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i];}});}});}),Object.freeze(e);}var t=\"undefined\"!=typeof globalThis?globalThis:\"undefined\"!=typeof window?window:\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:{},i=function(e){try{return!!e();}catch(t){return!0;}},n=!i(function(){var e=function(){}.bind();return\"function\"!=typeof e||e.hasOwnProperty(\"prototype\");}),r=n,o=Function.prototype,s=o.call,a=r&&o.bind.bind(s,s),c=r?a:function(e){return function(){return s.apply(e,arguments);};},l=c,d=l({}.toString),u=l(\"\".slice),h=function(e){return u(d(e),8,-1);},p=i,_=h,m=Object,f=c(\"\".split),g=p(function(){return!m(\"z\").propertyIsEnumerable(0);})?function(e){return\"String\"==_(e)?f(e,\"\"):m(e);}:m,T=function(e){return null==e;},E=T,S=TypeError,I=function(e){if(E(e))throw S(\"Can't call method on \"+e);return e;},v=g,y=I,A=function(e){return v(y(e));},R=function(e){return e&&e.Math==Math&&e;},C=R(\"object\"==typeof globalThis&&globalThis)||R(\"object\"==typeof window&&window)||R(\"object\"==typeof self&&self)||R(\"object\"==typeof t&&t)||function(){return this;}()||Function(\"return this\")(),b={},k={get exports(){return b;},set exports(e){b=e;}},N=C,D=Object.defineProperty,O=function(e,t){try{D(N,e,{value:t,configurable:!0,writable:!0});}catch(i){N[e]=t;}return t;},w=O,P=\"__core-js_shared__\",L=C[P]||w(P,{}),M=L;(k.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 V,x,U=I,F=Object,B=function(e){return F(U(e));},H=B,j=c({}.hasOwnProperty),G=Object.hasOwn||function(e,t){return j(H(e),t);},W=c,J=0,K=Math.random(),Y=W(1..toString),z=function(e){return\"Symbol(\"+(void 0===e?\"\":e)+\")_\"+Y(++J+K,36);},q=\"undefined\"!=typeof navigator&&String(navigator.userAgent)||\"\",Q=C,X=q,Z=Q.process,$=Q.Deno,ee=Z&&Z.versions||$&&$.version,te=ee&&ee.v8;te&&(x=(V=te.split(\".\"))[0]>0&&V[0]<4?1:+(V[0]+V[1])),!x&&X&&(!(V=X.match(/Edge\\/(\\d+)/))||V[1]>=74)&&(V=X.match(/Chrome\\/(\\d+)/))&&(x=+V[1]);var ie=x,ne=ie,re=i,oe=!!Object.getOwnPropertySymbols&&!re(function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41;}),se=oe&&!Symbol.sham&&\"symbol\"==typeof Symbol.iterator,ae=b,ce=G,le=z,de=oe,ue=se,he=C.Symbol,pe=ae(\"wks\"),_e=ue?he.for||he:he&&he.withoutSetter||le,me=function(e){return ce(pe,e)||(pe[e]=de&&ce(he,e)?he[e]:_e(\"Symbol.\"+e)),pe[e];},fe=\"object\"==typeof document&&document.all,ge={all:fe,IS_HTMLDDA:void 0===fe&&void 0!==fe},Te=ge.all,Ee=ge.IS_HTMLDDA?function(e){return\"function\"==typeof e||e===Te;}:function(e){return\"function\"==typeof e;},Se=Ee,Ie=ge.all,ve=ge.IS_HTMLDDA?function(e){return\"object\"==typeof e?null!==e:Se(e)||e===Ie;}:function(e){return\"object\"==typeof e?null!==e:Se(e);},ye=ve,Ae=String,Re=TypeError,Ce=function(e){if(ye(e))return e;throw Re(Ae(e)+\" is not an object\");},be={},ke=!i(function(){return 7!=Object.defineProperty({},1,{get:function(){return 7;}})[1];}),Ne=ke&&i(function(){return 42!=Object.defineProperty(function(){},\"prototype\",{value:42,writable:!1}).prototype;}),De={},Oe=ve,we=C.document,Pe=Oe(we)&&Oe(we.createElement),Le=function(e){return Pe?we.createElement(e):{};},Me=Le,Ve=!ke&&!i(function(){return 7!=Object.defineProperty(Me(\"div\"),\"a\",{get:function(){return 7;}}).a;}),xe=n,Ue=Function.prototype.call,Fe=xe?Ue.bind(Ue):function(){return Ue.apply(Ue,arguments);},Be=C,He=Ee,je=function(e,t){return arguments.length<2?(i=Be[e],He(i)?i:void 0):Be[e]&&Be[e][t];var i;},Ge=c({}.isPrototypeOf),We=je,Je=Ee,Ke=Ge,Ye=Object,ze=se?function(e){return\"symbol\"==typeof e;}:function(e){var t=We(\"Symbol\");return Je(t)&&Ke(t.prototype,Ye(e));},qe=String,Qe=function(e){try{return qe(e);}catch(t){return\"Object\";}},Xe=Ee,Ze=Qe,$e=TypeError,et=function(e){if(Xe(e))return e;throw $e(Ze(e)+\" is not a function\");},tt=et,it=T,nt=function(e,t){var i=e[t];return it(i)?void 0:tt(i);},rt=Fe,ot=Ee,st=ve,at=TypeError,ct=Fe,lt=ve,dt=ze,ut=nt,ht=function(e,t){var i,n;if(\"string\"===t&&ot(i=e.toString)&&!st(n=rt(i,e)))return n;if(ot(i=e.valueOf)&&!st(n=rt(i,e)))return n;if(\"string\"!==t&&ot(i=e.toString)&&!st(n=rt(i,e)))return n;throw at(\"Can't convert object to primitive value\");},pt=TypeError,_t=me(\"toPrimitive\"),mt=function(e,t){if(!lt(e)||dt(e))return e;var i,n=ut(e,_t);if(n){if(void 0===t&&(t=\"default\"),i=ct(n,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=mt,gt=ze,Tt=function(e){var t=ft(e,\"string\");return gt(t)?t:t+\"\";},Et=ke,St=Ve,It=Ne,vt=Ce,yt=Tt,At=TypeError,Rt=Object.defineProperty,Ct=Object.getOwnPropertyDescriptor,bt=\"enumerable\",kt=\"configurable\",Nt=\"writable\";De.f=Et?It?function(e,t,i){if(vt(e),t=yt(t),vt(i),\"function\"==typeof e&&\"prototype\"===t&&\"value\"in i&&Nt in i&&!i[Nt]){var n=Ct(e,t);n&&n[Nt]&&(e[t]=i.value,i={configurable:kt in i?i[kt]:n[kt],enumerable:bt in i?i[bt]:n[bt],writable:!1});}return Rt(e,t,i);}:Rt:function(e,t,i){if(vt(e),t=yt(t),vt(i),St)try{return Rt(e,t,i);}catch(n){}if(\"get\"in i||\"set\"in i)throw At(\"Accessors not supported\");return\"value\"in i&&(e[t]=i.value),e;};var Dt=Math.ceil,Ot=Math.floor,wt=Math.trunc||function(e){var t=+e;return(t>0?Ot:Dt)(t);},Pt=wt,Lt=function(e){var t=+e;return t!=t||0===t?0:Pt(t);},Mt=Lt,Vt=Math.max,xt=Math.min,Ut=function(e,t){var i=Mt(e);return i<0?Vt(i+t,0):xt(i,t);},Ft=Lt,Bt=Math.min,Ht=function(e){return e>0?Bt(Ft(e),9007199254740991):0;},jt=Ht,Gt=function(e){return jt(e.length);},Wt=A,Jt=Ut,Kt=Gt,Yt=function(e){return function(t,i,n){var r,o=Wt(t),s=Kt(o),a=Jt(n,s);if(e&&i!=i){for(;s>a;)if((r=o[a++])!=r)return!0;}else for(;s>a;a++)if((e||a in o)&&o[a]===i)return e||a||0;return!e&&-1;};},zt={includes:Yt(!0),indexOf:Yt(!1)},qt={},Qt=G,Xt=A,Zt=zt.indexOf,$t=qt,ei=c([].push),ti=function(e,t){var i,n=Xt(e),r=0,o=[];for(i in n)!Qt($t,i)&&Qt(n,i)&&ei(o,i);for(;t.length>r;)Qt(n,i=t[r++])&&(~Zt(o,i)||ei(o,i));return o;},ii=[\"constructor\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"toLocaleString\",\"toString\",\"valueOf\"],ni=ti,ri=ii,oi=Object.keys||function(e){return ni(e,ri);},si=ke,ai=Ne,ci=De,li=Ce,di=A,ui=oi;be.f=si&&!ai?Object.defineProperties:function(e,t){li(e);for(var i,n=di(t),r=ui(t),o=r.length,s=0;o>s;)ci.f(e,i=r[s++],n[i]);return e;};var hi,pi=je(\"document\",\"documentElement\"),_i=z,mi=b(\"keys\"),fi=function(e){return mi[e]||(mi[e]=_i(e));},gi=Ce,Ti=be,Ei=ii,Si=qt,Ii=pi,vi=Le,yi=\"prototype\",Ai=\"script\",Ri=fi(\"IE_PROTO\"),Ci=function(){},bi=function(e){return\"<\"+Ai+\">\"+e+\"\";},ki=function(e){e.write(bi(\"\")),e.close();var t=e.parentWindow.Object;return e=null,t;},Ni=function(){try{hi=new ActiveXObject(\"htmlfile\");}catch(r){}var e,t,i;Ni=\"undefined\"!=typeof document?document.domain&&hi?ki(hi):(t=vi(\"iframe\"),i=\"java\"+Ai+\":\",t.style.display=\"none\",Ii.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(bi(\"document.F=Object\")),e.close(),e.F):ki(hi);for(var n=Ei.length;n--;)delete Ni[yi][Ei[n]];return Ni();};Si[Ri]=!0;var Di=Object.create||function(e,t){var i;return null!==e?(Ci[yi]=gi(e),i=new Ci(),Ci[yi]=null,i[Ri]=e):i=Ni(),void 0===t?i:Ti.f(i,t);},Oi=me,wi=Di,Pi=De.f,Li=Oi(\"unscopables\"),Mi=Array.prototype;null==Mi[Li]&&Pi(Mi,Li,{configurable:!0,value:wi(null)});var Vi,xi,Ui,Fi=function(e){Mi[Li][e]=!0;},Bi={},Hi=Ee,ji=C.WeakMap,Gi=Hi(ji)&&/native code/.test(String(ji)),Wi=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t};},Ji=De,Ki=Wi,Yi=ke?function(e,t,i){return Ji.f(e,t,Ki(1,i));}:function(e,t,i){return e[t]=i,e;},zi=Gi,qi=C,Qi=ve,Xi=Yi,Zi=G,$i=L,en=fi,tn=qt,nn=\"Object already initialized\",rn=qi.TypeError,on=qi.WeakMap;if(zi||$i.state){var sn=$i.state||($i.state=new on());sn.get=sn.get,sn.has=sn.has,sn.set=sn.set,Vi=function(e,t){if(sn.has(e))throw rn(nn);return t.facade=e,sn.set(e,t),t;},xi=function(e){return sn.get(e)||{};},Ui=function(e){return sn.has(e);};}else{var an=en(\"state\");tn[an]=!0,Vi=function(e,t){if(Zi(e,an))throw rn(nn);return t.facade=e,Xi(e,an,t),t;},xi=function(e){return Zi(e,an)?e[an]:{};},Ui=function(e){return Zi(e,an);};}var cn={set:Vi,get:xi,has:Ui,enforce:function(e){return Ui(e)?xi(e):Vi(e,{});},getterFor:function(e){return function(t){var i;if(!Qi(t)||(i=xi(t)).type!==e)throw rn(\"Incompatible receiver, \"+e+\" required\");return i;};}},ln={},dn={},un={}.propertyIsEnumerable,hn=Object.getOwnPropertyDescriptor,pn=hn&&!un.call({1:2},1);dn.f=pn?function(e){var t=hn(this,e);return!!t&&t.enumerable;}:un;var _n=ke,mn=Fe,fn=dn,gn=Wi,Tn=A,En=Tt,Sn=G,In=Ve,vn=Object.getOwnPropertyDescriptor;ln.f=_n?vn:function(e,t){if(e=Tn(e),t=En(t),In)try{return vn(e,t);}catch(i){}if(Sn(e,t))return gn(!mn(fn.f,e,t),e[t]);};var yn={},An={get exports(){return yn;},set exports(e){yn=e;}},Rn=ke,Cn=G,bn=Function.prototype,kn=Rn&&Object.getOwnPropertyDescriptor,Nn=Cn(bn,\"name\"),Dn={EXISTS:Nn,PROPER:Nn&&\"something\"===function(){}.name,CONFIGURABLE:Nn&&(!Rn||Rn&&kn(bn,\"name\").configurable)},On=Ee,wn=L,Pn=c(Function.toString);On(wn.inspectSource)||(wn.inspectSource=function(e){return Pn(e);});var Ln=wn.inspectSource,Mn=c,Vn=i,xn=Ee,Un=G,Fn=ke,Bn=Dn.CONFIGURABLE,Hn=Ln,jn=cn.enforce,Gn=cn.get,Wn=String,Jn=Object.defineProperty,Kn=Mn(\"\".slice),Yn=Mn(\"\".replace),zn=Mn([].join),qn=Fn&&!Vn(function(){return 8!==Jn(function(){},\"length\",{value:8}).length;}),Qn=String(String).split(\"String\"),Xn=An.exports=function(e,t,i){\"Symbol(\"===Kn(Wn(t),0,7)&&(t=\"[\"+Yn(Wn(t),/^Symbol\\(([^)]*)\\)/,\"$1\")+\"]\"),i&&i.getter&&(t=\"get \"+t),i&&i.setter&&(t=\"set \"+t),(!Un(e,\"name\")||Bn&&e.name!==t)&&(Fn?Jn(e,\"name\",{value:t,configurable:!0}):e.name=t),qn&&i&&Un(i,\"arity\")&&e.length!==i.arity&&Jn(e,\"length\",{value:i.arity});try{i&&Un(i,\"constructor\")&&i.constructor?Fn&&Jn(e,\"prototype\",{writable:!1}):e.prototype&&(e.prototype=void 0);}catch(r){}var n=jn(e);return Un(n,\"source\")||(n.source=zn(Qn,\"string\"==typeof t?t:\"\")),e;};Function.prototype.toString=Xn(function(){return xn(this)&&Gn(this).source||Hn(this);},\"toString\");var Zn=Ee,$n=De,er=yn,tr=O,ir=function(e,t,i,n){n||(n={});var r=n.enumerable,o=void 0!==n.name?n.name:t;if(Zn(i)&&er(i,o,n),n.global)r?e[t]=i:tr(t,i);else{try{n.unsafe?e[t]&&(r=!0):delete e[t];}catch(s){}r?e[t]=i:$n.f(e,t,{value:i,enumerable:!1,configurable:!n.nonConfigurable,writable:!n.nonWritable});}return e;},nr={},rr=ti,or=ii.concat(\"length\",\"prototype\");nr.f=Object.getOwnPropertyNames||function(e){return rr(e,or);};var sr={};sr.f=Object.getOwnPropertySymbols;var ar,cr,lr,dr=je,ur=nr,hr=sr,pr=Ce,_r=c([].concat),mr=dr(\"Reflect\",\"ownKeys\")||function(e){var t=ur.f(pr(e)),i=hr.f;return i?_r(t,i(e)):t;},fr=G,gr=mr,Tr=ln,Er=De,Sr=function(e,t,i){for(var n=gr(t),r=Er.f,o=Tr.f,s=0;s=t.length?(e.target=void 0,Qo(void 0,!0)):Qo(\"keys\"==i?n:\"values\"==i?t[n]:[n,t[n]],!1);},\"values\"),is=Ko.Arguments=Ko.Array;if(Jo(\"keys\"),Jo(\"values\"),Jo(\"entries\"),Xo&&\"values\"!==is.name)try{zo(is,\"name\",{value:\"values\"});}catch(SU){}var ns={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},rs=Le(\"span\").classList,os=rs&&rs.constructor&&rs.constructor.prototype,ss=os===Object.prototype?void 0:os,as=C,cs=ns,ls=ss,ds=ts,us=Yi,hs=me,ps=hs(\"iterator\"),_s=hs(\"toStringTag\"),ms=ds.values,fs=function(e,t){if(e){if(e[ps]!==ms)try{us(e,ps,ms);}catch(SU){e[ps]=ms;}if(e[_s]||us(e,_s,t),cs[t])for(var i in ds)if(e[i]!==ds[i])try{us(e,i,ds[i]);}catch(SU){e[i]=ds[i];}}};for(var gs in cs)fs(as[gs]&&as[gs].prototype,gs);fs(ls,\"DOMTokenList\");var Ts=\"undefined\"!=typeof process&&\"process\"==h(process),Es=yn,Ss=De,Is=function(e,t,i){return i.get&&Es(i.get,t,{getter:!0}),i.set&&Es(i.set,t,{setter:!0}),Ss.f(e,t,i);},vs=je,ys=Is,As=ke,Rs=me(\"species\"),Cs=function(e){var t=vs(e);As&&t&&!t[Rs]&&ys(t,Rs,{configurable:!0,get:function(){return this;}});},bs=Ge,ks=TypeError,Ns=function(e,t){if(bs(t,e))return e;throw ks(\"Incorrect invocation\");},Ds={};Ds[me(\"toStringTag\")]=\"z\";var Os=\"[object z]\"===String(Ds),ws=Ee,Ps=h,Ls=me(\"toStringTag\"),Ms=Object,Vs=\"Arguments\"==Ps(function(){return arguments;}()),xs=Os?Ps:function(e){var t,i,n;return void 0===e?\"Undefined\":null===e?\"Null\":\"string\"==typeof(i=function(e,t){try{return e[t];}catch(SU){}}(t=Ms(e),Ls))?i:Vs?Ps(t):\"Object\"==(n=Ps(t))&&ws(t.callee)?\"Arguments\":n;},Us=c,Fs=i,Bs=Ee,Hs=xs,js=Ln,Gs=function(){},Ws=[],Js=je(\"Reflect\",\"construct\"),Ks=/^\\s*(?:class|function)\\b/,Ys=Us(Ks.exec),zs=!Ks.exec(Gs),qs=function(e){if(!Bs(e))return!1;try{return Js(Gs,Ws,e),!0;}catch(SU){return!1;}},Qs=function(e){if(!Bs(e))return!1;switch(Hs(e)){case\"AsyncFunction\":case\"GeneratorFunction\":case\"AsyncGeneratorFunction\":return!1;}try{return zs||!!Ys(Ks,js(e));}catch(SU){return!0;}};Qs.sham=!0;var Xs,Zs,$s,ea,ta=!Js||Fs(function(){var e;return qs(qs.call)||!qs(Object)||!qs(function(){e=!0;})||e;})?Qs:qs,ia=ta,na=Qe,ra=TypeError,oa=function(e){if(ia(e))return e;throw ra(na(e)+\" is not a constructor\");},sa=Ce,aa=oa,ca=T,la=me(\"species\"),da=function(e,t){var i,n=sa(e).constructor;return void 0===n||ca(i=sa(n)[la])?t:aa(i);},ua=n,ha=Function.prototype,pa=ha.apply,_a=ha.call,ma=\"object\"==typeof Reflect&&Reflect.apply||(ua?_a.bind(pa):function(){return _a.apply(pa,arguments);}),fa=h,ga=c,Ta=function(e){if(\"Function\"===fa(e))return ga(e);},Ea=et,Sa=n,Ia=Ta(Ta.bind),va=function(e,t){return Ea(e),void 0===t?e:Sa?Ia(e,t):function(){return e.apply(t,arguments);};},ya=c([].slice),Aa=TypeError,Ra=function(e,t){if(eo;o++)if((a=g(e[o]))&&Td(Ad,a))return a;return new yd(!1);}n=Ed(e,r);}for(c=h?e.next:n.next;!(l=pd(c,n)).done;){try{a=g(l.value);}catch(SU){Id(n,\"throw\",SU);}if(\"object\"==typeof a&&a&&Td(Ad,a))return a;}return new yd(!1);},Cd=me(\"iterator\"),bd=!1;try{var kd=0,Nd={next:function(){return{done:!!kd++};},return:function(){bd=!0;}};Nd[Cd]=function(){return this;},Array.from(Nd,function(){throw 2;});}catch(SU){}var Dd=function(e,t){if(!t&&!bd)return!1;var i=!1;try{var n={};n[Cd]=function(){return{next:function(){return{done:i=!0};}};},e(n);}catch(SU){}return i;},Od=kc,wd=Wc.CONSTRUCTOR||!Dd(function(e){Od.all(e).then(void 0,function(){});}),Pd=Fe,Ld=et,Md=Jc,Vd=bc,xd=Rd;xr({target:\"Promise\",stat:!0,forced:wd},{all:function(e){var t=this,i=Md.f(t),n=i.resolve,r=i.reject,o=Vd(function(){var i=Ld(t.resolve),o=[],s=0,a=1;xd(e,function(e){var c=s++,l=!1;a++,Pd(i,t,e).then(function(e){l||(l=!0,o[c]=e,--a||n(o));},r);}),--a||n(o);});return o.error&&r(o.value),i.promise;}});var Ud=xr,Fd=Wc.CONSTRUCTOR,Bd=kc,Hd=je,jd=Ee,Gd=ir,Wd=Bd&&Bd.prototype;if(Ud({target:\"Promise\",proto:!0,forced:Fd,real:!0},{catch:function(e){return this.then(void 0,e);}}),jd(Bd)){var Jd=Hd(\"Promise\").prototype.catch;Wd.catch!==Jd&&Gd(Wd,\"catch\",Jd,{unsafe:!0});}var Kd=Fe,Yd=et,zd=Jc,qd=bc,Qd=Rd;xr({target:\"Promise\",stat:!0,forced:wd},{race:function(e){var t=this,i=zd.f(t),n=i.reject,r=qd(function(){var r=Yd(t.resolve);Qd(e,function(e){Kd(r,t,e).then(i.resolve,n);});});return r.error&&n(r.value),i.promise;}});var Xd=Fe,Zd=Jc;xr({target:\"Promise\",stat:!0,forced:Wc.CONSTRUCTOR},{reject:function(e){var t=Zd.f(this);return Xd(t.reject,void 0,e),t.promise;}});var $d=Ce,eu=ve,tu=Jc,iu=function(e,t){if($d(e),eu(t)&&t.constructor===e)return t;var i=tu.f(e);return(0,i.resolve)(t),i.promise;},nu=xr,ru=Wc.CONSTRUCTOR,ou=iu;je(\"Promise\"),nu({target:\"Promise\",stat:!0,forced:ru},{resolve:function(e){return ou(this,e);}});var su=Ee,au=ve,cu=vo,lu=function(e,t,i){var n,r;return cu&&su(n=t.constructor)&&n!==i&&au(r=n.prototype)&&r!==i.prototype&&cu(e,r),e;},du=ve,uu=h,hu=me(\"match\"),pu=function(e){var t;return du(e)&&(void 0!==(t=e[hu])?!!t:\"RegExp\"==uu(e));},_u=xs,mu=String,fu=function(e){if(\"Symbol\"===_u(e))throw TypeError(\"Cannot convert a Symbol value to a string\");return mu(e);},gu=Ce,Tu=function(){var e=gu(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;},Eu=Fe,Su=G,Iu=Ge,vu=Tu,yu=RegExp.prototype,Au=function(e){var t=e.flags;return void 0!==t||\"flags\"in yu||Su(e,\"flags\")||!Iu(yu,e)?t:Eu(vu,e);},Ru=i,Cu=C.RegExp,bu=Ru(function(){var e=Cu(\"a\",\"y\");return e.lastIndex=2,null!=e.exec(\"abcd\");}),ku=bu||Ru(function(){return!Cu(\"a\",\"y\").sticky;}),Nu=bu||Ru(function(){var e=Cu(\"^r\",\"gy\");return e.lastIndex=2,null!=e.exec(\"str\");}),Du={BROKEN_CARET:Nu,MISSED_STICKY:ku,UNSUPPORTED_Y:bu},Ou=De.f,wu=i,Pu=C.RegExp,Lu=wu(function(){var e=Pu(\".\",\"s\");return!(e.dotAll&&e.exec(\"\\n\")&&\"s\"===e.flags);}),Mu=i,Vu=C.RegExp,xu=Mu(function(){var e=Vu(\"(?b)\",\"g\");return\"b\"!==e.exec(\"b\").groups.a||\"bc\"!==\"b\".replace(e,\"$c\");}),Uu=ke,Fu=C,Bu=c,Hu=Nr,ju=lu,Gu=Yi,Wu=nr.f,Ju=Ge,Ku=pu,Yu=fu,zu=Au,qu=Du,Qu=function(e,t,i){i in e||Ou(e,i,{configurable:!0,get:function(){return t[i];},set:function(e){t[i]=e;}});},Xu=ir,Zu=i,$u=G,eh=cn.enforce,th=Cs,ih=Lu,nh=xu,rh=me(\"match\"),oh=Fu.RegExp,sh=oh.prototype,ah=Fu.SyntaxError,ch=Bu(sh.exec),lh=Bu(\"\".charAt),dh=Bu(\"\".replace),uh=Bu(\"\".indexOf),hh=Bu(\"\".slice),ph=/^\\?<[^\\s\\d!#%&*+<=>@^][^\\s!#%&*+<=>@^]*>/,_h=/a/g,mh=/a/g,fh=new oh(_h)!==_h,gh=qu.MISSED_STICKY,Th=qu.UNSUPPORTED_Y,Eh=Uu&&(!fh||gh||ih||nh||Zu(function(){return mh[rh]=!1,oh(_h)!=_h||oh(mh)==mh||\"/a/i\"!=oh(_h,\"i\");}));if(Hu(\"RegExp\",Eh)){for(var Sh=function(e,t){var i,n,r,o,s,a,c=Ju(sh,this),l=Ku(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Sh)return e;if((l||Ju(sh,e))&&(e=e.source,d&&(t=zu(h))),e=void 0===e?\"\":Yu(e),t=void 0===t?\"\":Yu(t),h=e,ih&&(\"dotAll\"in _h)&&(n=!!t&&uh(t,\"s\")>-1)&&(t=dh(t,/s/g,\"\")),i=t,gh&&(\"sticky\"in _h)&&(r=!!t&&uh(t,\"y\")>-1)&&Th&&(t=dh(t,/y/g,\"\")),nh&&(o=function(e){for(var t,i=e.length,n=0,r=\"\",o=[],s={},a=!1,c=!1,l=0,d=\"\";n<=i;n++){if(\"\\\\\"===(t=lh(e,n)))t+=lh(e,++n);else if(\"]\"===t)a=!1;else if(!a)switch(!0){case\"[\"===t:a=!0;break;case\"(\"===t:ch(ph,hh(e,n+1))&&(n+=2,c=!0),r+=t,l++;continue;case\">\"===t&&c:if(\"\"===d||$u(s,d))throw new ah(\"Invalid capture group name\");s[d]=!0,o[o.length]=[d,l],c=!1,d=\"\";continue;}c?d+=t:r+=t;}return[r,o];}(e),e=o[0],u=o[1]),s=ju(oh(e,t),c?this:sh,Sh),(n||r||u.length)&&(a=eh(s),n&&(a.dotAll=!0,a.raw=Sh(function(e){for(var t,i=e.length,n=0,r=\"\",o=!1;n<=i;n++)\"\\\\\"!==(t=lh(e,n))?o||\".\"!==t?(\"[\"===t?o=!0:\"]\"===t&&(o=!1),r+=t):r+=\"[\\\\s\\\\S]\":r+=t+lh(e,++n);return r;}(e),i)),r&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Gu(s,\"source\",\"\"===h?\"(?:)\":h);}catch(SU){}return s;},Ih=Wu(oh),vh=0;Ih.length>vh;)Qu(Sh,oh,Ih[vh++]);sh.constructor=Sh,Sh.prototype=sh,Xu(Fu,\"RegExp\",Sh,{constructor:!0});}th(\"RegExp\");var yh=Fe,Ah=c,Rh=fu,Ch=Tu,bh=Du,kh=Di,Nh=cn.get,Dh=Lu,Oh=xu,wh=b(\"native-string-replace\",String.prototype.replace),Ph=RegExp.prototype.exec,Lh=Ph,Mh=Ah(\"\".charAt),Vh=Ah(\"\".indexOf),xh=Ah(\"\".replace),Uh=Ah(\"\".slice),Fh=function(){var e=/a/,t=/b*/g;return yh(Ph,e,\"a\"),yh(Ph,t,\"a\"),0!==e.lastIndex||0!==t.lastIndex;}(),Bh=bh.BROKEN_CARET,Hh=void 0!==/()??/.exec(\"\")[1];(Fh||Hh||Bh||Dh||Oh)&&(Lh=function(e){var t,i,n,r,o,s,a,c=this,l=Nh(c),d=Rh(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=yh(Lh,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Bh&&c.sticky,_=yh(Ch,c),m=c.source,f=0,g=d;if(p&&(_=xh(_,\"y\",\"\"),-1===Vh(_,\"g\")&&(_+=\"g\"),g=Uh(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&\"\\n\"!==Mh(d,c.lastIndex-1))&&(m=\"(?: \"+m+\")\",g=\" \"+g,f++),i=new RegExp(\"^(?:\"+m+\")\",_)),Hh&&(i=new RegExp(\"^\"+m+\"$(?!\\\\s)\",_)),Fh&&(n=c.lastIndex),r=yh(Ph,p?i:c,g),p?r?(r.input=Uh(r.input,f),r[0]=Uh(r[0],f),r.index=c.lastIndex,c.lastIndex+=r[0].length):c.lastIndex=0:Fh&&r&&(c.lastIndex=c.global?r.index+r[0].length:n),Hh&&r&&r.length>1&&yh(wh,r[0],i,function(){for(o=1;oT;T++)if((a||T in m)&&(p=f(h=m[T],T,_),e))if(t)S[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:ip(S,h);}else switch(e){case 4:return!1;case 7:ip(S,h);}return o?-1:n||r?r:S;};},rp={forEach:np(0),map:np(1),filter:np(2),some:np(3),every:np(4),find:np(5),findIndex:np(6),filterReject:np(7)},op=i,sp=function(e,t){var i=[][e];return!!i&&op(function(){i.call(null,t||function(){return 1;},1);});},ap=rp.forEach,cp=sp(\"forEach\")?[].forEach:function(e){return ap(this,e,arguments.length>1?arguments[1]:void 0);},lp=C,dp=ns,up=ss,hp=cp,pp=Yi,_p=function(e){if(e&&e.forEach!==hp)try{pp(e,\"forEach\",hp);}catch(SU){e.forEach=hp;}};for(var mp in dp)dp[mp]&&_p(lp[mp]&&lp[mp].prototype);_p(up);var fp=et,gp=B,Tp=g,Ep=Gt,Sp=TypeError,Ip=function(e){return function(t,i,n,r){fp(i);var o=gp(t),s=Tp(o),a=Ep(o),c=e?a-1:0,l=e?-1:1;if(n<2)for(;;){if(c in s){r=s[c],c+=l;break;}if(c+=l,e?c<0:a<=c)throw Sp(\"Reduce of empty array with no initial value\");}for(;e?c>=0:a>c;c+=l)c in s&&(r=i(r,s[c],c,o));return r;};},vp={left:Ip(!1),right:Ip(!0)}.left;xr({target:\"Array\",proto:!0,forced:!Ts&&ie>79&&ie<83||!sp(\"reduce\")},{reduce:function(e){var t=arguments.length;return vp(this,e,t,t>1?arguments[1]:void 0);}});var yp=Ta,Ap=ir,Rp=jh,Cp=i,bp=me,kp=Yi,Np=bp(\"species\"),Dp=RegExp.prototype,Op=c,wp=Lt,Pp=fu,Lp=I,Mp=Op(\"\".charAt),Vp=Op(\"\".charCodeAt),xp=Op(\"\".slice),Up=function(e){return function(t,i){var n,r,o=Pp(Lp(t)),s=wp(i),a=o.length;return s<0||s>=a?e?\"\":void 0:(n=Vp(o,s))<55296||n>56319||s+1===a||(r=Vp(o,s+1))<56320||r>57343?e?Mp(o,s):n:e?xp(o,s,s+2):r-56320+(n-55296<<10)+65536;};},Fp={codeAt:Up(!1),charAt:Up(!0)},Bp=Fp.charAt,Hp=c,jp=B,Gp=Math.floor,Wp=Hp(\"\".charAt),Jp=Hp(\"\".replace),Kp=Hp(\"\".slice),Yp=/\\$([$&'`]|\\d{1,2}|<[^>]*>)/g,zp=/\\$([$&'`]|\\d{1,2})/g,qp=function(e,t,i,n,r,o){var s=i+e.length,a=n.length,c=zp;return void 0!==r&&(r=jp(r),c=Yp),Jp(o,c,function(o,c){var l;switch(Wp(c,0)){case\"$\":return\"$\";case\"&\":return e;case\"`\":return Kp(t,0,i);case\"'\":return Kp(t,s);case\"<\":l=r[Kp(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Gp(d/10);return 0===u?o:u<=a?void 0===n[u-1]?Wp(c,1):n[u-1]+Wp(c,1):o;}l=n[d-1];}return void 0===l?\"\":l;});},Qp=Fe,Xp=Ce,Zp=Ee,$p=h,e_=jh,t_=TypeError,i_=ma,n_=Fe,r_=c,o_=function(e,t,i,n){var r=bp(e),o=!Cp(function(){var t={};return t[r]=function(){return 7;},7!=\"\"[e](t);}),s=o&&!Cp(function(){var t=!1,i=/a/;return\"split\"===e&&((i={}).constructor={},i.constructor[Np]=function(){return i;},i.flags=\"\",i[r]=/./[r]),i.exec=function(){return t=!0,null;},i[r](\"\"),!t;});if(!o||!s||i){var a=yp(/./[r]),c=t(r,\"\"[e],function(e,t,i,n,r){var s=yp(e),c=t.exec;return c===Rp||c===Dp.exec?o&&!r?{done:!0,value:a(t,i,n)}:{done:!0,value:s(i,t,n)}:{done:!1};});Ap(String.prototype,e,c[0]),Ap(Dp,r,c[1]);}n&&kp(Dp[r],\"sham\",!0);},s_=i,a_=Ce,c_=Ee,l_=T,d_=Lt,u_=Ht,h_=fu,p_=I,__=function(e,t,i){return t+(i?Bp(e,t).length:1);},m_=nt,f_=qp,g_=function(e,t){var i=e.exec;if(Zp(i)){var n=Qp(i,e,t);return null!==n&&Xp(n),n;}if(\"RegExp\"===$p(e))return Qp(e_,e,t);throw t_(\"RegExp#exec called on incompatible receiver\");},T_=me(\"replace\"),E_=Math.max,S_=Math.min,I_=r_([].concat),v_=r_([].push),y_=r_(\"\".indexOf),A_=r_(\"\".slice),R_=function(e){return void 0===e?e:String(e);},C_=\"$0\"===\"a\".replace(/./,\"$0\"),b_=!!/./[T_]&&\"\"===/./[T_](\"a\",\"$0\"),k_=!s_(function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:\"7\"},e;},\"7\"!==\"\".replace(e,\"$\");});o_(\"replace\",function(e,t,i){var n=b_?\"$\":\"$0\";return[function(e,i){var n=p_(this),r=l_(e)?void 0:m_(e,T_);return r?n_(r,e,n,i):n_(t,h_(n),e,i);},function(e,r){var o=a_(this),s=h_(e);if(\"string\"==typeof r&&-1===y_(r,n)&&-1===y_(r,\"$<\")){var a=i(t,o,s,r);if(a.done)return a.value;}var c=c_(r);c||(r=h_(r));var l=o.global;if(l){var d=o.unicode;o.lastIndex=0;}for(var u=[];;){var h=g_(o,s);if(null===h)break;if(v_(u,h),!l)break;\"\"===h_(h[0])&&(o.lastIndex=__(s,u_(o.lastIndex),d));}for(var p=\"\",_=0,m=0;m=_&&(p+=A_(s,_,g)+v,_=g+f.length);}return p+A_(s,_);}];},!k_||!C_||b_);var N_=zt.includes,D_=Fi;xr({target:\"Array\",proto:!0,forced:i(function(){return!Array(1).includes();})},{includes:function(e){return N_(this,e,arguments.length>1?arguments[1]:void 0);}}),D_(\"includes\");var O_=Lt,w_=fu,P_=I,L_=RangeError,M_=c,V_=Ht,x_=fu,U_=function(e){var t=w_(P_(this)),i=\"\",n=O_(e);if(n<0||Infinity==n)throw L_(\"Wrong number of repetitions\");for(;n>0;(n>>>=1)&&(t+=t))1&n&&(i+=t);return i;},F_=I,B_=M_(U_),H_=M_(\"\".slice),j_=Math.ceil,G_=function(e){return function(t,i,n){var r,o,s=x_(F_(t)),a=V_(i),c=s.length,l=void 0===n?\" \":x_(n);return a<=c||\"\"==l?s:((o=B_(l,j_((r=a-c)/l.length))).length>r&&(o=H_(o,0,r)),e?s+o:o+s);};},W_={start:G_(!1),end:G_(!0)},J_=/Version\\/10(?:\\.\\d+){1,2}(?: [\\w./]+)?(?: Mobile\\/\\w+)? Safari\\//.test(q),K_=W_.start;xr({target:\"String\",proto:!0,forced:J_},{padStart:function(e){return K_(this,e,arguments.length>1?arguments[1]:void 0);}});var Y_=i,z_=ke,q_=me(\"iterator\"),Q_=!Y_(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,n){t.delete(\"b\"),i+=n+e;}),!t.size&&!z_||!t.sort||\"http://a/c%20d?a=1&c=3\"!==e.href||\"3\"!==t.get(\"c\")||\"a=1\"!==String(new URLSearchParams(\"?a=1\"))||!t[q_]||\"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;}),X_=ir,Z_=function(e,t,i){for(var n in t)X_(e,n,t[n],i);return e;},$_=Tt,em=De,tm=Wi,im=function(e,t,i){var n=$_(t);n in e?em.f(e,n,tm(0,i)):e[n]=i;},nm=Ut,rm=Gt,om=im,sm=Array,am=Math.max,cm=function(e,t,i){for(var n=rm(e),r=nm(t,n),o=nm(void 0===i?n:i,n),s=sm(am(o-r,0)),a=0;r0;)e[n]=e[--n];n!==o++&&(e[n]=i);}return e;},pm=function(e,t,i,n){for(var r=t.length,o=i.length,s=0,a=0;s0?arguments[0]:void 0));Em||(this.length=e.entries.length);},Rf=Af.prototype;if(ym(Rf,{append:function(e,t){Fm(arguments.length,2);var i=Jm(this);af(i.entries,{key:Lm(e),value:Lm(t)}),Em||this.length++,i.updateURL();},delete:function(e){Fm(arguments.length,1);for(var t=Jm(this),i=t.entries,n=Lm(e),r=0;rt.key?1:-1;}),e.updateURL();},forEach:function(e){for(var t,i=Jm(this).entries,n=Dm(e,arguments.length>1?arguments[1]:void 0),r=0;r1?kf(arguments[1]):{});}}),km(Qm)){var Nf=function(e){return bm(this,Zm),new Qm(e,arguments.length>1?kf(arguments[1]):{});};Zm.constructor=Nf,Nf.prototype=Zm,mm({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:Nf});}}var Df={URLSearchParams:Af,getState:Jm},Of=\"\\t\\n\\v\\f\\r                 \\u2028\\u2029\\ufeff\",wf=I,Pf=fu,Lf=Of,Mf=c(\"\".replace),Vf=RegExp(\"^[\"+Lf+\"]+\"),xf=RegExp(\"(^|[^\"+Lf+\"])[\"+Lf+\"]+$\"),Uf=function(e){return function(t){var i=Pf(wf(t));return 1&e&&(i=Mf(i,Vf,\"\")),2&e&&(i=Mf(i,xf,\"$1\")),i;};},Ff={start:Uf(1),end:Uf(2),trim:Uf(3)},Bf=Dn.PROPER,Hf=i,jf=Of,Gf=Ff.trim;xr({target:\"String\",proto:!0,forced:function(e){return Hf(function(){return!!jf[e]()||\"​…᠎\"!==\"​…᠎\"[e]()||Bf&&jf[e].name!==e;});}(\"trim\")},{trim:function(){return Gf(this);}});var Wf=xr,Jf=ke,Kf=c,Yf=G,zf=Ee,qf=Ge,Qf=fu,Xf=Is,Zf=Sr,$f=C.Symbol,eg=$f&&$f.prototype;if(Jf&&zf($f)&&(!(\"description\"in eg)||void 0!==$f().description)){var tg={},ig=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:Qf(arguments[0]),t=qf(eg,this)?new $f(e):void 0===e?$f():$f(e);return\"\"===e&&(tg[t]=!0),t;};Zf(ig,$f),ig.prototype=eg,eg.constructor=ig;var ng=\"Symbol(test)\"==String($f(\"test\")),rg=Kf(eg.valueOf),og=Kf(eg.toString),sg=/^Symbol\\((.*)\\)[^)]+$/,ag=Kf(\"\".replace),cg=Kf(\"\".slice);Xf(eg,\"description\",{configurable:!0,get:function(){var e=rg(this);if(Yf(tg,e))return\"\";var t=og(e),i=ng?cg(t,7,-1):ag(t,sg,\"$1\");return\"\"===i?void 0:i;}}),Wf({global:!0,constructor:!0,forced:!0},{Symbol:ig});}var lg=Fp.charAt,dg=fu,ug=cn,hg=jo,pg=Go,_g=\"String Iterator\",mg=ug.set,fg=ug.getterFor(_g);hg(String,\"String\",function(e){mg(this,{type:_g,string:dg(e),index:0});},function(){var e,t=fg(this),i=t.string,n=t.index;return n>=i.length?pg(void 0,!0):(e=lg(i,n),t.index+=e.length,pg(e,!1));});var gg,Tg=ke,Eg=c,Sg=Fe,Ig=i,vg=oi,yg=sr,Ag=dn,Rg=B,Cg=g,bg=Object.assign,kg=Object.defineProperty,Ng=Eg([].concat),Dg=!bg||Ig(function(){if(Tg&&1!==bg({b:1},bg(kg({},\"a\",{enumerable:!0,get:function(){kg(this,\"b\",{value:3,enumerable:!1});}}),{b:2})).b)return!0;var e={},t={},i=Symbol(),n=\"abcdefghijklmnopqrst\";return e[i]=7,n.split(\"\").forEach(function(e){t[e]=e;}),7!=bg({},e)[i]||vg(bg({},t)).join(\"\")!=n;})?function(e,t){for(var i=Rg(e),n=arguments.length,r=1,o=yg.f,s=Ag.f;n>r;)for(var a,c=Cg(arguments[r++]),l=o?Ng(vg(c),o(c)):vg(c),d=l.length,u=0;d>u;)a=l[u++],Tg&&!Sg(s,c,a)||(i[a]=c[a]);return i;}:bg,Og=Ce,wg=ud,Pg=va,Lg=Fe,Mg=B,Vg=function(e,t,i,n){try{return n?t(Og(i)[0],i[1]):t(i);}catch(SU){wg(e,\"throw\",SU);}},xg=zl,Ug=ta,Fg=Gt,Bg=im,Hg=ad,jg=ed,Gg=Array,Wg=c,Jg=2147483647,Kg=/[^\\0-\\u007E]/,Yg=/[.\\u3002\\uFF0E\\uFF61]/g,zg=\"Overflow: input needs wider integers to process\",qg=RangeError,Qg=Wg(Yg.exec),Xg=Math.floor,Zg=String.fromCharCode,$g=Wg(\"\".charCodeAt),eT=Wg([].join),tT=Wg([].push),iT=Wg(\"\".replace),nT=Wg(\"\".split),rT=Wg(\"\".toLowerCase),oT=function(e){return e+22+75*(e<26);},sT=function(e,t,i){var n=0;for(e=i?Xg(e/700):e>>1,e+=Xg(e/t);e>455;)e=Xg(e/35),n+=36;return Xg(n+36*e/(e+38));},aT=function(e){var t=[];e=function(e){for(var t=[],i=0,n=e.length;i=55296&&r<=56319&&i=o&&nXg((Jg-s)/u))throw qg(zg);for(s+=(d-o)*u,o=d,i=0;iJg)throw qg(zg);if(n==o){for(var h=s,p=36;;){var _=p<=a?1:p>=a+26?26:p-a;if(h<_)break;var m=h-_,f=36-_;tT(t,Zg(oT(_+m%f))),h=Xg(m/f),p+=36;}tT(t,Zg(oT(h))),a=sT(s,u,l==c),s=0,l++;}}s++,o++;}return eT(t,\"\");},cT=xr,lT=ke,dT=Q_,uT=C,hT=va,pT=c,_T=ir,mT=Is,fT=Ns,gT=G,TT=Dg,ET=function(e){var t=Mg(e),i=Ug(this),n=arguments.length,r=n>1?arguments[1]:void 0,o=void 0!==r;o&&(r=Pg(r,n>2?arguments[2]:void 0));var s,a,c,l,d,u,h=jg(t),p=0;if(!h||this===Gg&&xg(h))for(s=Fg(t),a=i?new this(s):Gg(s);s>p;p++)u=o?r(t[p],p):t[p],Bg(a,p,u);else for(d=(l=Hg(t,h)).next,a=i?new this():[];!(c=Lg(d,l)).done;p++)u=o?Vg(l,r,[c.value,p],!0):c.value,Bg(a,p,u);return a.length=p,a;},ST=cm,IT=Fp.codeAt,vT=function(e){var t,i,n=[],r=nT(iT(rT(e),Yg,\".\"),\".\");for(t=0;t?@[\\\\\\]^|]/,sE=/[\\0\\t\\n\\r #/:<>?@[\\\\\\]^|]/,aE=/^[\\u0000-\\u0020]+/,cE=/(^|[^\\u0000-\\u0020])[\\u0000-\\u0020]+$/,lE=/[\\t\\n\\r]/g,dE=function(e){var t,i,n,r;if(\"number\"==typeof e){for(t=[],i=0;i<4;i++)zT(t,e%256),e=MT(e/256);return FT(t,\".\");}if(\"object\"==typeof e){for(t=\"\",n=function(e){for(var t=null,i=1,n=null,r=0,o=0;o<8;o++)0!==e[o]?(r>i&&(t=n,i=r),n=null,r=0):(null===n&&(n=o),++r);return r>i&&(t=n,i=r),t;}(e),i=0;i<8;i++)r&&0===e[i]||(r&&(r=!1),n===i?(t+=i?\":\":\"::\",r=!0):(t+=BT(e[i],16),i<7&&(t+=\":\")));return\"[\"+t+\"]\";}return e;},uE={},hE=TT({},uE,{\" \":1,'\"':1,\"<\":1,\">\":1,\"`\":1}),pE=TT({},hE,{\"#\":1,\"?\":1,\"{\":1,\"}\":1}),_E=TT({},pE,{\"/\":1,\":\":1,\";\":1,\"=\":1,\"@\":1,\"[\":1,\"\\\\\":1,\"]\":1,\"^\":1,\"|\":1}),mE=function(e,t){var i=IT(e,0);return i>32&&i<127&&!gT(t,e)?e:encodeURIComponent(e);},fE={ftp:21,file:null,http:80,https:443,ws:80,wss:443},gE=function(e,t){var i;return 2==e.length&&UT(ZT,xT(e,0))&&(\":\"==(i=xT(e,1))||!t&&\"|\"==i);},TE=function(e){var t;return e.length>1&&gE(KT(e,0,2))&&(2==e.length||\"/\"===(t=xT(e,2))||\"\\\\\"===t||\"?\"===t||\"#\"===t);},EE=function(e){return\".\"===e||\"%2e\"===YT(e);},SE={},IE={},vE={},yE={},AE={},RE={},CE={},bE={},kE={},NE={},DE={},OE={},wE={},PE={},LE={},ME={},VE={},xE={},UE={},FE={},BE={},HE=function(e,t,i){var n,r,o,s=yT(e);if(t){if(r=this.parse(s))throw PT(r);this.searchParams=null;}else{if(void 0!==i&&(n=new HE(i,!0)),r=this.parse(s,null,n))throw PT(r);(o=OT(new DT())).bindURL(this),this.searchParams=o;}};HE.prototype={type:\"URL\",parse:function(e,t,i){var n,r,o,s,a,c=this,l=t||SE,d=0,u=\"\",h=!1,p=!1,_=!1;for(e=yT(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=GT(e,aE,\"\"),e=GT(e,cE,\"$1\")),e=GT(e,lE,\"\"),n=ET(e);d<=n.length;){switch(r=n[d],l){case SE:if(!r||!UT(ZT,r)){if(t)return qT;l=vE;continue;}u+=YT(r),l=IE;break;case IE:if(r&&(UT($T,r)||\"+\"==r||\"-\"==r||\".\"==r))u+=YT(r);else{if(\":\"!=r){if(t)return qT;u=\"\",l=vE,d=0;continue;}if(t&&(c.isSpecial()!=gT(fE,u)||\"file\"==u&&(c.includesCredentials()||null!==c.port)||\"file\"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&fE[c.scheme]==c.port&&(c.port=null));u=\"\",\"file\"==c.scheme?l=PE:c.isSpecial()&&i&&i.scheme==c.scheme?l=yE:c.isSpecial()?l=bE:\"/\"==n[d+1]?(l=AE,d++):(c.cannotBeABaseURL=!0,jT(c.path,\"\"),l=UE);}break;case vE:if(!i||i.cannotBeABaseURL&&\"#\"!=r)return qT;if(i.cannotBeABaseURL&&\"#\"==r){c.scheme=i.scheme,c.path=ST(i.path),c.query=i.query,c.fragment=\"\",c.cannotBeABaseURL=!0,l=BE;break;}l=\"file\"==i.scheme?PE:RE;continue;case yE:if(\"/\"!=r||\"/\"!=n[d+1]){l=RE;continue;}l=kE,d++;break;case AE:if(\"/\"==r){l=NE;break;}l=xE;continue;case RE:if(c.scheme=i.scheme,r==gg)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.query=i.query;else if(\"/\"==r||\"\\\\\"==r&&c.isSpecial())l=CE;else if(\"?\"==r)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.query=\"\",l=FE;else{if(\"#\"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.path.length--,l=xE;continue;}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.query=i.query,c.fragment=\"\",l=BE;}break;case CE:if(!c.isSpecial()||\"/\"!=r&&\"\\\\\"!=r){if(\"/\"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=xE;continue;}l=NE;}else l=kE;break;case bE:if(l=kE,\"/\"!=r||\"/\"!=xT(u,d+1))continue;d++;break;case kE:if(\"/\"!=r&&\"\\\\\"!=r){l=NE;continue;}break;case NE:if(\"@\"==r){h&&(u=\"%40\"+u),h=!0,o=ET(u);for(var m=0;m65535)return XT;c.port=c.isSpecial()&&T===fE[c.scheme]?null:T,u=\"\";}if(t)return;l=VE;continue;}return XT;}u+=r;break;case PE:if(c.scheme=\"file\",\"/\"==r||\"\\\\\"==r)l=LE;else{if(!i||\"file\"!=i.scheme){l=xE;continue;}if(r==gg)c.host=i.host,c.path=ST(i.path),c.query=i.query;else if(\"?\"==r)c.host=i.host,c.path=ST(i.path),c.query=\"\",l=FE;else{if(\"#\"!=r){TE(FT(ST(n,d),\"\"))||(c.host=i.host,c.path=ST(i.path),c.shortenPath()),l=xE;continue;}c.host=i.host,c.path=ST(i.path),c.query=i.query,c.fragment=\"\",l=BE;}}break;case LE:if(\"/\"==r||\"\\\\\"==r){l=ME;break;}i&&\"file\"==i.scheme&&!TE(FT(ST(n,d),\"\"))&&(gE(i.path[0],!0)?jT(c.path,i.path[0]):c.host=i.host),l=xE;continue;case ME:if(r==gg||\"/\"==r||\"\\\\\"==r||\"?\"==r||\"#\"==r){if(!t&&gE(u))l=xE;else if(\"\"==u){if(c.host=\"\",t)return;l=VE;}else{if(s=c.parseHost(u))return s;if(\"localhost\"==c.host&&(c.host=\"\"),t)return;u=\"\",l=VE;}continue;}u+=r;break;case VE:if(c.isSpecial()){if(l=xE,\"/\"!=r&&\"\\\\\"!=r)continue;}else if(t||\"?\"!=r){if(t||\"#\"!=r){if(r!=gg&&(l=xE,\"/\"!=r))continue;}else c.fragment=\"\",l=BE;}else c.query=\"\",l=FE;break;case xE:if(r==gg||\"/\"==r||\"\\\\\"==r&&c.isSpecial()||!t&&(\"?\"==r||\"#\"==r)){if(\"..\"===(a=YT(a=u))||\"%2e.\"===a||\".%2e\"===a||\"%2e%2e\"===a?(c.shortenPath(),\"/\"==r||\"\\\\\"==r&&c.isSpecial()||jT(c.path,\"\")):EE(u)?\"/\"==r||\"\\\\\"==r&&c.isSpecial()||jT(c.path,\"\"):(\"file\"==c.scheme&&!c.path.length&&gE(u)&&(c.host&&(c.host=\"\"),u=xT(u,0)+\":\"),jT(c.path,u)),u=\"\",\"file\"==c.scheme&&(r==gg||\"?\"==r||\"#\"==r))for(;c.path.length>1&&\"\"===c.path[0];)WT(c.path);\"?\"==r?(c.query=\"\",l=FE):\"#\"==r&&(c.fragment=\"\",l=BE);}else u+=mE(r,pE);break;case UE:\"?\"==r?(c.query=\"\",l=FE):\"#\"==r?(c.fragment=\"\",l=BE):r!=gg&&(c.path[0]+=mE(r,uE));break;case FE:t||\"#\"!=r?r!=gg&&(\"'\"==r&&c.isSpecial()?c.query+=\"%27\":c.query+=\"#\"==r?\"%23\":mE(r,uE)):(c.fragment=\"\",l=BE);break;case BE:r!=gg&&(c.fragment+=mE(r,hE));}d++;}},parseHost:function(e){var t,i,n;if(\"[\"==xT(e,0)){if(\"]\"!=xT(e,e.length-1))return QT;if(t=function(e){var t,i,n,r,o,s,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return xT(e,u);};if(\":\"==h()){if(\":\"!=xT(e,1))return;u+=2,d=++l;}for(;h();){if(8==l)return;if(\":\"!=h()){for(t=i=0;i<4&&UT(rE,h());)t=16*t+LT(h(),16),u++,i++;if(\".\"==h()){if(0==i)return;if(u-=i,l>6)return;for(n=0;h();){if(r=null,n>0){if(!(\".\"==h()&&n<4))return;u++;}if(!UT(eE,h()))return;for(;UT(eE,h());){if(o=LT(h(),10),null===r)r=o;else{if(0==r)return;r=10*r+o;}if(r>255)return;u++;}c[l]=256*c[l]+r,2!=++n&&4!=n||l++;}if(4!=n)return;break;}if(\":\"==h()){if(u++,!h())return;}else if(h())return;c[l++]=t;}else{if(null!==d)return;u++,d=++l;}}if(null!==d)for(s=l-d,l=7;0!=l&&s>0;)a=c[l],c[l--]=c[d+s-1],c[d+--s]=a;else if(8!=l)return;return c;}(KT(e,1,-1)),!t)return QT;this.host=t;}else if(this.isSpecial()){if(e=vT(e),UT(oE,e))return QT;if(t=function(e){var t,i,n,r,o,s,a,c=JT(e,\".\");if(c.length&&\"\"==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],n=0;n1&&\"0\"==xT(r,0)&&(o=UT(tE,r)?16:8,r=KT(r,8==o?1:2)),\"\"===r)s=0;else{if(!UT(10==o?nE:8==o?iE:rE,r))return e;s=LT(r,o);}jT(i,s);}for(n=0;n=VT(256,5-t))return null;}else if(s>255)return null;for(a=HT(i),n=0;n1?arguments[1]:void 0,n=kT(t,new HE(e,!1,i));lT||(t.href=n.serialize(),t.origin=n.getOrigin(),t.protocol=n.getProtocol(),t.username=n.getUsername(),t.password=n.getPassword(),t.host=n.getHost(),t.hostname=n.getHostname(),t.port=n.getPort(),t.pathname=n.getPathname(),t.search=n.getSearch(),t.searchParams=n.getSearchParams(),t.hash=n.getHash());},GE=jE.prototype,WE=function(e,t){return{get:function(){return NT(this)[e]();},set:t&&function(e){return NT(this)[t](e);},configurable:!0,enumerable:!0};};if(lT&&(mT(GE,\"href\",WE(\"serialize\",\"setHref\")),mT(GE,\"origin\",WE(\"getOrigin\")),mT(GE,\"protocol\",WE(\"getProtocol\",\"setProtocol\")),mT(GE,\"username\",WE(\"getUsername\",\"setUsername\")),mT(GE,\"password\",WE(\"getPassword\",\"setPassword\")),mT(GE,\"host\",WE(\"getHost\",\"setHost\")),mT(GE,\"hostname\",WE(\"getHostname\",\"setHostname\")),mT(GE,\"port\",WE(\"getPort\",\"setPort\")),mT(GE,\"pathname\",WE(\"getPathname\",\"setPathname\")),mT(GE,\"search\",WE(\"getSearch\",\"setSearch\")),mT(GE,\"searchParams\",WE(\"getSearchParams\")),mT(GE,\"hash\",WE(\"getHash\",\"setHash\"))),_T(GE,\"toJSON\",function(){return NT(this).serialize();},{enumerable:!0}),_T(GE,\"toString\",function(){return NT(this).serialize();},{enumerable:!0}),wT){var JE=wT.createObjectURL,KE=wT.revokeObjectURL;JE&&_T(jE,\"createObjectURL\",hT(JE,wT)),KE&&_T(jE,\"revokeObjectURL\",hT(KE,wT));}AT(jE,\"URL\"),cT({global:!0,constructor:!0,forced:!dT,sham:!lT},{URL:jE});var YE=\"undefined\"!=typeof ArrayBuffer&&\"undefined\"!=typeof DataView,zE=Lt,qE=Ht,QE=RangeError,XE=function(e){if(void 0===e)return 0;var t=zE(e),i=qE(t);if(t!==i)throw QE(\"Wrong length or index\");return i;},ZE=Array,$E=Math.abs,eS=Math.pow,tS=Math.floor,iS=Math.log,nS=Math.LN2,rS={pack:function(e,t,i){var n,r,o,s=ZE(i),a=8*i-t-1,c=(1<>1,d=23===t?eS(2,-24)-eS(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=$E(e))!=e||Infinity===e?(r=e!=e?1:0,n=c):(n=tS(iS(e)/nS),e*(o=eS(2,-n))<1&&(n--,o*=2),(e+=n+l>=1?d/o:d*eS(2,1-l))*o>=2&&(n++,o/=2),n+l>=c?(r=0,n=c):n+l>=1?(r=(e*o-1)*eS(2,t),n+=l):(r=e*eS(2,l-1)*eS(2,t),n=0));t>=8;)s[h++]=255&r,r/=256,t-=8;for(n=n<0;)s[h++]=255&n,n/=256,a-=8;return s[--h]|=128*u,s;},unpack:function(e,t){var i,n=e.length,r=8*n-t-1,o=(1<>1,a=r-7,c=n-1,l=e[c--],d=127&l;for(l>>=7;a>0;)d=256*d+e[c--],a-=8;for(i=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)i=256*i+e[c--],a-=8;if(0===d)d=1-s;else{if(d===o)return i?NaN:l?-Infinity:Infinity;i+=eS(2,t),d-=s;}return(l?-1:1)*i*eS(2,d-t);}},oS=B,sS=Ut,aS=Gt,cS=function(e){for(var t=oS(this),i=aS(t),n=arguments.length,r=sS(n>1?arguments[1]:void 0,i),o=n>2?arguments[2]:void 0,s=void 0===o?i:sS(o,i);s>r;)t[r++]=e;return t;},lS=C,dS=c,uS=ke,hS=YE,pS=Dn,_S=Yi,mS=Is,fS=Z_,gS=i,TS=Ns,ES=Lt,SS=Ht,IS=XE,vS=rS,yS=Kr,AS=vo,RS=nr.f,CS=cS,bS=cm,kS=oo,NS=cn,DS=pS.PROPER,OS=pS.CONFIGURABLE,wS=\"ArrayBuffer\",PS=\"DataView\",LS=\"prototype\",MS=\"Wrong index\",VS=NS.getterFor(wS),xS=NS.getterFor(PS),US=NS.set,FS=lS[wS],BS=FS,HS=BS&&BS[LS],jS=lS[PS],GS=jS&&jS[LS],WS=Object.prototype,JS=lS.Array,KS=lS.RangeError,YS=dS(CS),zS=dS([].reverse),qS=vS.pack,QS=vS.unpack,XS=function(e){return[255&e];},ZS=function(e){return[255&e,e>>8&255];},$S=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255];},eI=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0];},tI=function(e){return qS(e,23,4);},iI=function(e){return qS(e,52,8);},nI=function(e,t,i){mS(e[LS],t,{configurable:!0,get:function(){return i(this)[t];}});},rI=function(e,t,i,n){var r=IS(i),o=xS(e);if(r+t>o.byteLength)throw KS(MS);var s=o.bytes,a=r+o.byteOffset,c=bS(s,a,a+t);return n?c:zS(c);},oI=function(e,t,i,n,r,o){var s=IS(i),a=xS(e);if(s+t>a.byteLength)throw KS(MS);for(var c=a.bytes,l=s+a.byteOffset,d=n(+r),u=0;ulI;)(aI=cI[lI++])in BS||_S(BS,aI,FS[aI]);HS.constructor=BS;}AS&&yS(GS)!==WS&&AS(GS,WS);var dI=new jS(new BS(2)),uI=dS(GS.setInt8);dI.setInt8(0,2147483648),dI.setInt8(1,2147483649),!dI.getInt8(0)&&dI.getInt8(1)||fS(GS,{setInt8:function(e,t){uI(this,e,t<<24>>24);},setUint8:function(e,t){uI(this,e,t<<24>>24);}},{unsafe:!0});}else HS=(BS=function(e){TS(this,HS);var t=IS(e);US(this,{type:wS,bytes:YS(JS(t),0),byteLength:t}),uS||(this.byteLength=t,this.detached=!1);})[LS],GS=(jS=function(e,t,i){TS(this,GS),TS(e,HS);var n=VS(e),r=n.byteLength,o=ES(t);if(o<0||o>r)throw KS(\"Wrong offset\");if(o+(i=void 0===i?r-o:SS(i))>r)throw KS(\"Wrong length\");US(this,{type:PS,buffer:e,byteLength:i,byteOffset:o,bytes:n.bytes}),uS||(this.buffer=e,this.byteLength=i,this.byteOffset=o);})[LS],uS&&(nI(BS,\"byteLength\",VS),nI(jS,\"buffer\",xS),nI(jS,\"byteLength\",xS),nI(jS,\"byteOffset\",xS)),fS(GS,{getInt8:function(e){return rI(this,1,e)[0]<<24>>24;},getUint8:function(e){return rI(this,1,e)[0];},getInt16:function(e){var t=rI(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16;},getUint16:function(e){var t=rI(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0];},getInt32:function(e){return eI(rI(this,4,e,arguments.length>1?arguments[1]:void 0));},getUint32:function(e){return eI(rI(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0;},getFloat32:function(e){return QS(rI(this,4,e,arguments.length>1?arguments[1]:void 0),23);},getFloat64:function(e){return QS(rI(this,8,e,arguments.length>1?arguments[1]:void 0),52);},setInt8:function(e,t){oI(this,1,e,XS,t);},setUint8:function(e,t){oI(this,1,e,XS,t);},setInt16:function(e,t){oI(this,2,e,ZS,t,arguments.length>2?arguments[2]:void 0);},setUint16:function(e,t){oI(this,2,e,ZS,t,arguments.length>2?arguments[2]:void 0);},setInt32:function(e,t){oI(this,4,e,$S,t,arguments.length>2?arguments[2]:void 0);},setUint32:function(e,t){oI(this,4,e,$S,t,arguments.length>2?arguments[2]:void 0);},setFloat32:function(e,t){oI(this,4,e,tI,t,arguments.length>2?arguments[2]:void 0);},setFloat64:function(e,t){oI(this,8,e,iI,t,arguments.length>2?arguments[2]:void 0);}});kS(BS,wS),kS(jS,PS);var hI={ArrayBuffer:BS,DataView:jS},pI=Cs,_I=\"ArrayBuffer\",mI=hI[_I];xr({global:!0,constructor:!0,forced:C[_I]!==mI},{ArrayBuffer:mI}),pI(_I);var fI=xr,gI=Ta,TI=i,EI=Ce,SI=Ut,II=Ht,vI=da,yI=hI.ArrayBuffer,AI=hI.DataView,RI=AI.prototype,CI=gI(yI.prototype.slice),bI=gI(RI.getUint8),kI=gI(RI.setUint8);fI({target:\"ArrayBuffer\",proto:!0,unsafe:!0,forced:TI(function(){return!new yI(2).slice(1,void 0).byteLength;})},{slice:function(e,t){if(CI&&void 0===t)return CI(EI(this),e);for(var i=EI(this).byteLength,n=SI(e,i),r=SI(void 0===t?i:t,i),o=new(vI(this,yI))(II(r-n)),s=new AI(this),a=new AI(o),c=0;n1?arguments[1]:void 0,p=void 0!==h,_=Hv(d);if(_&&!jv(_))for(c=(a=Bv(d,_)).next,d=[];!(s=Vv(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=Mv(h,arguments[2])),i=Fv(d),n=new(Wv(l))(i),r=Gv(n),t=0;i>t;t++)o=p?h(d[t],t):d[t],n[t]=r?Jv(o):+o;return n;},fy=rp.forEach,gy=Cs,Ty=Is,Ey=De,Sy=ln,Iy=lu,vy=cn.get,yy=cn.set,Ay=cn.enforce,Ry=Ey.f,Cy=Sy.f,by=Math.round,ky=Yv.RangeError,Ny=Zv.ArrayBuffer,Dy=Ny.prototype,Oy=Zv.DataView,wy=Xv.NATIVE_ARRAY_BUFFER_VIEWS,Py=Xv.TYPED_ARRAY_TAG,Ly=Xv.TypedArray,My=Xv.TypedArrayPrototype,Vy=Xv.aTypedArrayConstructor,xy=Xv.isTypedArray,Uy=\"BYTES_PER_ELEMENT\",Fy=\"Wrong length\",By=function(e,t){Vy(e);for(var i=0,n=t.length,r=new e(n);n>i;)r[i]=t[i++];return r;},Hy=function(e,t){Ty(e,t,{configurable:!0,get:function(){return vy(this)[t];}});},jy=function(e){var t;return hy(Dy,e)||\"ArrayBuffer\"==(t=cy(e))||\"SharedArrayBuffer\"==t;},Gy=function(e,t){return xy(e)&&!dy(t)&&t in e&&iy(+t)&&t>=0;},Wy=function(e,t){return t=sy(t),Gy(e,t)?ey(2,e[t]):Cy(e,t);},Jy=function(e,t,i){return t=sy(t),!(Gy(e,t)&&ly(i)&&ay(i,\"value\"))||ay(i,\"get\")||ay(i,\"set\")||i.configurable||ay(i,\"writable\")&&!i.writable||ay(i,\"enumerable\")&&!i.enumerable?Ry(e,t,i):(e[t]=i.value,e);};qv?(wy||(Sy.f=Wy,Ey.f=Jy,Hy(My,\"buffer\"),Hy(My,\"byteOffset\"),Hy(My,\"byteLength\"),Hy(My,\"length\")),Kv({target:\"Object\",stat:!0,forced:!wy},{getOwnPropertyDescriptor:Wy,defineProperty:Jy}),PI.exports=function(e,t,i){var n=e.match(/\\d+/)[0]/8,r=e+(i?\"Clamped\":\"\")+\"Array\",o=\"get\"+e,s=\"set\"+e,a=Yv[r],c=a,l=c&&c.prototype,d={},u=function(e,t){Ry(e,t,{get:function(){return function(e,t){var i=vy(e);return i.view[o](t*n+i.byteOffset,!0);}(this,t);},set:function(e){return function(e,t,r){var o=vy(e);i&&(r=(r=by(r))<0?0:r>255?255:255&r),o.view[s](t*n+o.byteOffset,r,!0);}(this,t,e);},enumerable:!0});};wy?Qv&&(c=t(function(e,t,i,r){return $v(e,l),Iy(ly(t)?jy(t)?void 0!==r?new a(t,oy(i,n),r):void 0!==i?new a(t,oy(i,n)):new a(t):xy(t)?By(c,t):zv(my,c,t):new a(ry(t)),e,c);}),py&&py(c,Ly),fy(_y(a),function(e){e in c||ty(c,e,a[e]);}),c.prototype=l):(c=t(function(e,t,i,r){$v(e,l);var o,s,a,d=0,h=0;if(ly(t)){if(!jy(t))return xy(t)?By(c,t):zv(my,c,t);o=t,h=oy(i,n);var p=t.byteLength;if(void 0===r){if(p%n)throw ky(Fy);if((s=p-h)<0)throw ky(Fy);}else if((s=ny(r)*n)+h>p)throw ky(Fy);a=s/n;}else a=ry(t),o=new Ny(s=a*n);for(yy(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new Oy(o)});d1?arguments[1]:void 0,t>2?arguments[2]:void 0);},Qy(function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++;}}),1!==e;}));var eA=C,tA=Fe,iA=mv,nA=Gt,rA=Dv,oA=B,sA=i,aA=eA.RangeError,cA=eA.Int8Array,lA=cA&&cA.prototype,dA=lA&&lA.set,uA=iA.aTypedArray,hA=iA.exportTypedArrayMethod,pA=!sA(function(){var e=new Uint8ClampedArray(2);return tA(dA,e,{length:1,0:3},1),3!==e[1];}),_A=pA&&iA.NATIVE_ARRAY_BUFFER_VIEWS&&sA(function(){var e=new cA(2);return e.set(1),e.set(\"2\",1),0!==e[0]||2!==e[1];});hA(\"set\",function(e){uA(this);var t=rA(arguments.length>1?arguments[1]:void 0,1),i=oA(e);if(pA)return tA(dA,this,i,t);var n=this.length,r=nA(i),o=0;if(r+t>n)throw aA(\"Wrong length\");for(;o0&&1/i<0?1:-1:t>i;};}(e));},!PA||wA);var LA=Qe,MA=TypeError,VA=xr,xA=c,UA=et,FA=B,BA=Gt,HA=function(e,t){if(!delete e[t])throw MA(\"Cannot delete property \"+LA(t)+\" of \"+LA(e));},jA=fu,GA=i,WA=_m,JA=sp,KA=fA,YA=gA,zA=ie,qA=EA,QA=[],XA=xA(QA.sort),ZA=xA(QA.push),$A=GA(function(){QA.sort(void 0);}),eR=GA(function(){QA.sort(null);}),tR=JA(\"sort\"),iR=!GA(function(){if(zA)return zA<70;if(!(KA&&KA>3)){if(YA)return!0;if(qA)return qA<603;var e,t,i,n,r=\"\";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(n=0;n<47;n++)QA.push({k:t+n,v:i});}for(QA.sort(function(e,t){return t.v-e.v;}),n=0;njA(i)?1:-1;};}(e)),i=BA(r),n=0;ne.length?-1:\"\"===t?i:DR(e,t,i);};gR({target:\"String\",proto:!0},{replaceAll:function(e,t){var i,n,r,o,s,a,c,l,d=SR(this),u=0,h=0,p=\"\";if(!vR(e)){if(yR(e)&&(i=AR(SR(CR(e))),!~DR(i,\"g\")))throw NR(\"`.replaceAll` does not allow non-global regexes\");if(n=RR(e,kR))return TR(n,e,d,t);}for(r=AR(d),o=AR(e),(s=IR(t))||(t=AR(t)),a=o.length,c=wR(1,a),u=PR(r,o,0);-1!==u;)l=s?AR(t(o,u,r)):bR(o,r,u,[],void 0,t),p+=OR(r,h,u)+l,h=u+a,u=PR(r,o,u+c);return h=i&&parseInt(n[i],10);}function xR(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const o=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t));};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map()),this._eventMap[t].set(n,o),r.apply(this,[e,o]);};const o=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.apply(this,arguments);const n=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,n]);},Object.defineProperty(n,\"on\"+t,{get(){return this[\"_on\"+t];},set(e){this[\"_on\"+t]&&(this.removeEventListener(t,this[\"_on\"+t]),delete this[\"_on\"+t]),e&&this.addEventListener(t,this[\"_on\"+t]=e);},enumerable:!0,configurable:!0});}function UR(e){return\"boolean\"!=typeof e?new Error(\"Argument type: \"+typeof e+\". Please use a boolean.\"):(LR=e,e?\"adapter.js logging disabled\":\"adapter.js logging enabled\");}function FR(e){return\"boolean\"!=typeof e?new Error(\"Argument type: \"+typeof e+\". Please use a boolean.\"):(MR=!e,\"adapter.js deprecation warnings \"+(e?\"disabled\":\"enabled\"));}function BR(){if(\"object\"==typeof window){if(LR)return;\"undefined\"!=typeof console&&\"function\"==typeof console.log&&console.log.apply(console,arguments);}}function HR(e,t){MR&&console.warn(e+\" is deprecated, please use \"+t+\" instead.\");}function jR(e){return\"[object Object]\"===Object.prototype.toString.call(e);}function GR(e){return jR(e)?Object.keys(e).reduce(function(t,i){const n=jR(e[i]),r=n?GR(e[i]):e[i],o=n&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[i]:r});},{}):e;}function WR(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach(n=>{n.endsWith(\"Id\")?WR(e,e.get(t[n]),i):n.endsWith(\"Ids\")&&t[n].forEach(t=>{WR(e,e.get(t),i);});}));}function JR(e,t,i){const n=i?\"outbound-rtp\":\"inbound-rtp\",r=new Map();if(null===t)return r;const o=[];return e.forEach(e=>{\"track\"===e.type&&e.trackIdentifier===t.id&&o.push(e);}),o.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&WR(e,i,r);});}),r;}const KR=BR;function YR(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if(\"object\"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(i=>{if(\"require\"===i||\"advanced\"===i||\"mediaSource\"===i)return;const n=\"object\"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&\"number\"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):\"deviceId\"===t?\"sourceId\":t;};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};\"number\"==typeof n.ideal?(e[r(\"min\",i)]=n.ideal,t.optional.push(e),e={},e[r(\"max\",i)]=n.ideal,t.optional.push(e)):(e[r(\"\",i)]=n.ideal,t.optional.push(e));}void 0!==n.exact&&\"number\"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r(\"\",i)]=n.exact):[\"min\",\"max\"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e]);});}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t;},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&\"object\"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t]);};t((e=JSON.parse(JSON.stringify(e))).audio,\"autoGainControl\",\"googAutoGainControl\"),t(e.audio,\"noiseSuppression\",\"googNoiseSuppression\"),e.audio=n(e.audio);}if(e&&\"object\"==typeof e.video){let o=e.video.facingMode;o=o&&(\"object\"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&(\"user\"===o.exact||\"environment\"===o.exact||\"user\"===o.ideal||\"environment\"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,\"environment\"===o.exact||\"environment\"===o.ideal?t=[\"back\",\"rear\"]:\"user\"!==o.exact&&\"user\"!==o.ideal||(t=[\"front\"]),t)return i.mediaDevices.enumerateDevices().then(i=>{i=i.filter(e=>\"videoinput\"===e.kind);let s=i.find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!s&&i.length&&t.includes(\"back\")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=n(e.video),KR(\"chrome: \"+JSON.stringify(e)),r(e);});}e.video=n(e.video);}return KR(\"chrome: \"+JSON.stringify(e)),r(e);},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:\"NotAllowedError\",PermissionDismissedError:\"NotAllowedError\",InvalidStateError:\"NotAllowedError\",DevicesNotFoundError:\"NotFoundError\",ConstraintNotSatisfiedError:\"OverconstrainedError\",TrackStartError:\"NotReadableError\",MediaDeviceFailedDueToShutdown:\"NotAllowedError\",MediaDeviceKillSwitchOn:\"NotAllowedError\",TabCaptureError:\"AbortError\",ScreenCaptureError:\"AbortError\",DeviceCaptureError:\"AbortError\"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&\": \")+this.message;}};};if(i.getUserMedia=function(e,t,n){r(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(o(e));});});}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop();}),new DOMException(\"\",\"NotFoundError\");return e;},e=>Promise.reject(o(e))));};}}function zR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream;}function qR(e){if(\"object\"==typeof e&&e.RTCPeerConnection&&!(\"ontrack\"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,\"ontrack\",{get(){return this._ontrack;},set(e){this._ontrack&&this.removeEventListener(\"track\",this._ontrack),this.addEventListener(\"track\",this._ontrack=e);},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener(\"addtrack\",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};const r=new Event(\"track\");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r);}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};const r=new Event(\"track\");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r);});},this.addEventListener(\"addstream\",this._ontrackpoly)),t.apply(this,arguments);};}else xR(e,\"track\",e=>(e.transceiver||Object.defineProperty(e,\"transceiver\",{value:{receiver:e.receiver}}),e));}function QR(e){if(\"object\"==typeof e&&e.RTCPeerConnection&&!(\"getSenders\"in e.RTCPeerConnection.prototype)&&\"createDTMFSender\"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&(\"audio\"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf;},_pc:e};};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice();};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r;};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1);};}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e));});};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{const t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1);});};}else if(\"object\"==typeof e&&e.RTCPeerConnection&&\"getSenders\"in e.RTCPeerConnection.prototype&&\"createDTMFSender\"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!(\"dtmf\"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;},Object.defineProperty(e.RTCRtpSender.prototype,\"dtmf\",{get(){return void 0===this._dtmf&&(\"audio\"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf;}});}}function XR(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&\"function\"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||\"function\"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach(e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:\"local-candidate\",remotecandidate:\"remote-candidate\"}[e.type]||e.type};e.names().forEach(t=>{i[t]=e.stat(t);}),t[i.id]=i;}),t;},o=function(e){return new Map(Object.keys(e).map(t=>[t,e[t]]));};if(arguments.length>=2){const n=function(e){i(o(r(e)));};return t.apply(this,[n,e]);}return new Promise((e,i)=>{t.apply(this,[function(t){e(o(r(t)));},i]);}).then(i,n);};}function ZR(e){if(!(\"object\"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!(\"getStats\"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e;}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>JR(t,e.track,!0));};}if(!(\"getStats\"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;}),xR(e,\"track\",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>JR(t,e.track,!1));};}if(!(\"getStats\"in e.RTCRtpSender.prototype)||!(\"getStats\"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach(i=>{i.track===e&&(t?n=!0:t=i);}),this.getReceivers().forEach(t=>(t.track===e&&(i?n=!0:i=t),t.track===e)),n||t&&i?Promise.reject(new DOMException(\"There are more than one sender or receiver for the track.\",\"InvalidAccessError\")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException(\"There is no sender or receiver for the track.\",\"InvalidAccessError\"));}return t.apply(this,arguments);};}function $R(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0]);};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n;};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(\"Track already exists.\",\"InvalidAccessError\");});const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n);};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments);};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t];}),r.apply(this,arguments);};}function eC(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return $R(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id]);};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(\"Track already exists.\",\"InvalidAccessError\");}),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i;}n.apply(this,[t]);};const r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],r=e._streams[n.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||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id];},e.RTCPeerConnection.prototype.addTrack=function(t,i){if(\"closed\"===this.signalingState)throw new DOMException(\"The RTCPeerConnection's signalingState is 'closed'.\",\"InvalidStateError\");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))throw new DOMException(\"The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.\",\"NotSupportedError\");if(this.getSenders().find(e=>e.track===t))throw new DOMException(\"Track already exists.\",\"InvalidAccessError\");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event(\"negotiationneeded\"));});else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n);}return this.getSenders().find(e=>e.track===t);},[\"createOffer\",\"createAnswer\"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&\"function\"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i]);},t=>{e[1]&&e[1].apply(null,t);},arguments[2]]):i.apply(this,arguments).then(e=>o(this,e));}};e.RTCPeerConnection.prototype[t]=n[t];});const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,\"g\"),r.id);}),new RTCSessionDescription({type:t.type,sdp:i});}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments);};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,\"localDescription\");Object.defineProperty(e.RTCPeerConnection.prototype,\"localDescription\",{get(){const e=a.get.apply(this);return\"\"===e.type?e:o(this,e);}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if(\"closed\"===this.signalingState)throw new DOMException(\"The RTCPeerConnection's signalingState is 'closed'.\",\"InvalidStateError\");if(!e._pc)throw new DOMException(\"Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.\",\"TypeError\");if(!(e._pc===this))throw new DOMException(\"Sender was not created by this connection.\",\"InvalidAccessError\");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i]);}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event(\"negotiationneeded\")));};}function tC(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&[\"setLocalDescription\",\"setRemoteDescription\",\"addIceCandidate\"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new(\"addIceCandidate\"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments);}};e.RTCPeerConnection.prototype[t]=n[t];});}function iC(e,t){xR(e,\"negotiationneeded\",e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&\"plan-b\"===i.getConfiguration().sdpSemantics)||\"stable\"===i.signalingState)return e;});}var nC=Object.freeze({__proto__:null,shimMediaStream:zR,shimOnTrack:qR,shimGetSendersWithDtmf:QR,shimGetStats:XR,shimSenderReceiverGetStats:ZR,shimAddTrackRemoveTrackWithNative:$R,shimAddTrackRemoveTrack:eC,shimPeerConnection:tC,fixNegotiationNeeded:iC,shimGetUserMedia:YR,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&\"getDisplayMedia\"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(\"function\"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then(t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:\"desktop\",chromeMediaSourceId:t,maxFrameRate:o||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i);});}:console.error(\"shimGetDisplayMedia: getSourceId argument is not a function\"));}});function rC(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){HR(\"navigator.getUserMedia\",\"navigator.mediaDevices.getUserMedia\"),i.mediaDevices.getUserMedia(e).then(t,n);},!(t.version>55&&\"autoGainControl\"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t]);},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return\"object\"==typeof i&&\"object\"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,\"autoGainControl\",\"mozAutoGainControl\"),e(i.audio,\"noiseSuppression\",\"mozNoiseSuppression\")),t(i);},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,\"mozAutoGainControl\",\"autoGainControl\"),e(i,\"mozNoiseSuppression\",\"noiseSuppression\"),i;};}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return\"audio\"===this.kind&&\"object\"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,\"autoGainControl\",\"mozAutoGainControl\"),e(i,\"noiseSuppression\",\"mozNoiseSuppression\")),t.apply(this,[i]);};}}}function oC(e){\"object\"==typeof e&&e.RTCTrackEvent&&\"receiver\"in e.RTCTrackEvent.prototype&&!(\"transceiver\"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,\"transceiver\",{get(){return{receiver:this.receiver};}});}function sC(e,t){if(\"object\"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&[\"setLocalDescription\",\"setRemoteDescription\",\"addIceCandidate\"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new(\"addIceCandidate\"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments);}};e.RTCPeerConnection.prototype[t]=n[t];});const i={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(){const[e,r,o]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!r)try{e.forEach(e=>{e.type=i[e.type]||e.type;});}catch(sN){if(\"TypeError\"!==sN.name)throw sN;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}));});}return e;}).then(r,o);};}function aC(e){if(\"object\"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&\"getStats\"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e;}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map());};}function cC(e){if(\"object\"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&\"getStats\"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;}),xR(e,\"track\",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track);};}function lC(e){e.RTCPeerConnection&&!(\"removeStream\"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){HR(\"removeStream\",\"removeTrack\"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t);});});}function dC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel);}function uC(e){if(\"object\"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach(e=>{if(\"rid\"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError(\"Invalid RID value provided.\");}if(\"scaleResolutionDownBy\"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError(\"scale_resolution_down_by must be >= 1.0\");if(\"maxFramerate\"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError(\"max_framerate must be >= 0.0\");});const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!(\"encodings\"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings;}).catch(()=>{delete t.sendEncodings;})));}return n;});}function hC(e){if(\"object\"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return\"encodings\"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e;});}function pC(e){if(\"object\"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[];}):t.apply(this,arguments);};}function _C(e){if(\"object\"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[];}):t.apply(this,arguments);};}var mC=Object.freeze({__proto__:null,shimOnTrack:oC,shimPeerConnection:sC,shimSenderGetStats:aC,shimReceiverGetStats:cC,shimRemoveStream:lC,shimRTCDataChannel:dC,shimAddTransceiver:uC,shimGetParameters:hC,shimCreateOffer:pC,shimCreateAnswer:_C,shimGetUserMedia:rC,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&\"getDisplayMedia\"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException(\"getDisplayMedia without video constraints is undefined\");return e.name=\"NotFoundError\",e.code=8,Promise.reject(e);}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i);});}});function fC(e){if(\"object\"==typeof e&&e.RTCPeerConnection){if(\"getLocalStreams\"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams;}),!(\"addStream\"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e));},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e];}),t.apply(this,arguments);};}\"removeStream\"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e);});});}}function gC(e){if(\"object\"==typeof e&&e.RTCPeerConnection&&(\"getRemoteStreams\"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[];}),!(\"onaddstream\"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,\"onaddstream\",{get(){return this._onaddstream;},set(e){this._onaddstream&&(this.removeEventListener(\"addstream\",this._onaddstream),this.removeEventListener(\"track\",this._onaddstreampoly)),this.addEventListener(\"addstream\",this._onaddstream=e),this.addEventListener(\"track\",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event(\"addstream\");t.stream=e,this.dispatchEvent(t);});});}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener(\"track\",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event(\"addstream\");i.stream=t,e.dispatchEvent(i);});}),t.apply(e,arguments);};}}function TC(e){if(\"object\"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r;},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r;};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n;};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n;},t.setRemoteDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n;},t.addIceCandidate=a;}function EC(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(SC(e));}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n);}.bind(t));}function SC(e){return e&&void 0!==e.video?Object.assign({},e,{video:GR(e.video)}):e;}function IC(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;it.generateCertificate});}function vC(e){\"object\"==typeof e&&e.RTCTrackEvent&&\"receiver\"in e.RTCTrackEvent.prototype&&!(\"transceiver\"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,\"transceiver\",{get(){return{receiver:this.receiver};}});}function yC(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find(e=>\"audio\"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?\"sendrecv\"===t.direction?t.setDirection?t.setDirection(\"sendonly\"):t.direction=\"sendonly\":\"recvonly\"===t.direction&&(t.setDirection?t.setDirection(\"inactive\"):t.direction=\"inactive\"):!0!==e.offerToReceiveAudio||t||this.addTransceiver(\"audio\",{direction:\"recvonly\"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find(e=>\"video\"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?\"sendrecv\"===i.direction?i.setDirection?i.setDirection(\"sendonly\"):i.direction=\"sendonly\":\"recvonly\"===i.direction&&(i.setDirection?i.setDirection(\"inactive\"):i.direction=\"inactive\"):!0!==e.offerToReceiveVideo||i||this.addTransceiver(\"video\",{direction:\"recvonly\"});}return t.apply(this,arguments);};}function AC(e){\"object\"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext);}var RC=Object.freeze({__proto__:null,shimLocalStreamsAPI:fC,shimRemoteStreamsAPI:gC,shimCallbacksAPI:TC,shimGetUserMedia:EC,shimConstraints:SC,shimRTCIceServerUrls:IC,shimTrackEventTransceiver:vC,shimCreateOfferLegacy:yC,shimAudioContext:AC}),CC={},bC={get exports(){return CC;},set exports(e){CC=e;}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12);}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split(\"\\n\").map(e=>e.trim());},t.splitSections=function(e){return e.split(\"\\nm=\").map((e,t)=>(t>0?\"m=\"+e:e).trim()+\"\\r\\n\");},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0];},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i;},t.matchPrefix=function(e,i){return t.splitLines(e).filter(e=>0===e.indexOf(i));},t.parseCandidate=function(e){let t;t=0===e.indexOf(\"a=candidate:\")?e.substring(12).split(\" \"):e.substring(10).split(\" \");const i={foundation:t[0],component:{1:\"rtp\",2:\"rtcp\"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let n=8;n0?t[0].split(\"/\")[1]:\"sendrecv\",uri:t[1],attributes:t.slice(2).join(\" \")};},t.writeExtmap=function(e){return\"a=extmap:\"+(e.id||e.preferredId)+(e.direction&&\"sendrecv\"!==e.direction?\"/\"+e.direction:\"\")+\" \"+e.uri+(e.attributes?\" \"+e.attributes:\"\")+\"\\r\\n\";},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(\" \")+1).split(\";\");for(let r=0;r{void 0!==e.parameters[t]?n.push(t+\"=\"+e.parameters[t]):n.push(t);}),t+=\"a=fmtp:\"+i+\" \"+n.join(\";\")+\"\\r\\n\";}return t;},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(\" \")+1).split(\" \");return{type:t.shift(),parameter:t.join(\" \")};},t.writeRtcpFb=function(e){let t=\"\",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+=\"a=rtcp-fb:\"+i+\" \"+e.type+(e.parameter&&e.parameter.length?\" \"+e.parameter:\"\")+\"\\r\\n\";}),t;},t.parseSsrcMedia=function(e){const t=e.indexOf(\" \"),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(\":\",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i;},t.parseSsrcGroup=function(e){const t=e.substring(13).split(\" \");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))};},t.getMid=function(e){const i=t.matchPrefix(e,\"a=mid:\")[0];if(i)return i.substring(6);},t.parseFingerprint=function(e){const t=e.substring(14).split(\" \");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()};},t.getDtlsParameters=function(e,i){return{role:\"auto\",fingerprints:t.matchPrefix(e+i,\"a=fingerprint:\").map(t.parseFingerprint)};},t.writeDtlsParameters=function(e,t){let i=\"a=setup:\"+t+\"\\r\\n\";return e.fingerprints.forEach(e=>{i+=\"a=fingerprint:\"+e.algorithm+\" \"+e.value+\"\\r\\n\";}),i;},t.parseCryptoLine=function(e){const t=e.substring(9).split(\" \");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)};},t.writeCryptoLine=function(e){return\"a=crypto:\"+e.tag+\" \"+e.cryptoSuite+\" \"+(\"object\"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?\" \"+e.sessionParams.join(\" \"):\"\")+\"\\r\\n\";},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf(\"inline:\"))return null;const t=e.substring(7).split(\"|\");return{keyMethod:\"inline\",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(\":\")[0]:void 0,mkiLength:t[2]?t[2].split(\":\")[1]:void 0};},t.writeCryptoKeyParams=function(e){return e.keyMethod+\":\"+e.keySalt+(e.lifeTime?\"|\"+e.lifeTime:\"\")+(e.mkiValue&&e.mkiLength?\"|\"+e.mkiValue+\":\"+e.mkiLength:\"\");},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,\"a=crypto:\").map(t.parseCryptoLine);},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,\"a=ice-ufrag:\")[0],r=t.matchPrefix(e+i,\"a=ice-pwd:\")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null;},t.writeIceParameters=function(e){let t=\"a=ice-ufrag:\"+e.usernameFragment+\"\\r\\na=ice-pwd:\"+e.password+\"\\r\\n\";return e.iceLite&&(t+=\"a=ice-lite\\r\\n\"),t;},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(\" \");i.profile=n[2];for(let o=3;o{i.headerExtensions.push(t.parseExtmap(e));});const r=t.matchPrefix(e,\"a=rtcp-fb:* \").map(t.parseRtcpFb);return i.codecs.forEach(e=>{r.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t);});}),i;},t.writeRtpDescription=function(e,i){let n=\"\";n+=\"m=\"+e+\" \",n+=i.codecs.length>0?\"9\":\"0\",n+=\" \"+(i.profile||\"UDP/TLS/RTP/SAVPF\")+\" \",n+=i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(\" \")+\"\\r\\n\",n+=\"c=IN IP4 0.0.0.0\\r\\n\",n+=\"a=rtcp:9 IN IP4 0.0.0.0\\r\\n\",i.codecs.forEach(e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e);});let r=0;return i.codecs.forEach(e=>{e.maxptime>r&&(r=e.maxptime);}),r>0&&(n+=\"a=maxptime:\"+r+\"\\r\\n\"),i.headerExtensions&&i.headerExtensions.forEach(e=>{n+=t.writeExtmap(e);}),n;},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf(\"RED\"),o=-1!==n.fecMechanisms.indexOf(\"ULPFEC\"),s=t.matchPrefix(e,\"a=ssrc:\").map(e=>t.parseSsrcMedia(e)).filter(e=>\"cname\"===e.attribute),a=s.length>0&&s[0].ssrc;let c;const l=t.matchPrefix(e,\"a=ssrc-group:FID\").map(e=>e.substring(17).split(\" \").map(e=>parseInt(e,10)));l.length>0&&l[0].length>1&&l[0][0]===a&&(c=l[0][1]),n.codecs.forEach(e=>{if(\"RTX\"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?\"red+ulpfec\":\"red\"},i.push(t));}}),0===i.length&&a&&i.push({ssrc:a});let d=t.matchPrefix(e,\"b=\");return d.length&&(d=0===d[0].indexOf(\"b=TIAS:\")?parseInt(d[0].substring(7),10):0===d[0].indexOf(\"b=AS:\")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,i.forEach(e=>{e.maxBitrate=d;})),i;},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,\"a=ssrc:\").map(e=>t.parseSsrcMedia(e)).filter(e=>\"cname\"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,\"a=rtcp-rsize\");i.reducedSize=r.length>0,i.compound=0===r.length;const o=t.matchPrefix(e,\"a=rtcp-mux\");return i.mux=o.length>0,i;},t.writeRtcpParameters=function(e){let t=\"\";return e.reducedSize&&(t+=\"a=rtcp-rsize\\r\\n\"),e.mux&&(t+=\"a=rtcp-mux\\r\\n\"),void 0!==e.ssrc&&e.cname&&(t+=\"a=ssrc:\"+e.ssrc+\" cname:\"+e.cname+\"\\r\\n\"),t;},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,\"a=msid:\");if(1===n.length)return i=n[0].substring(7).split(\" \"),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,\"a=ssrc:\").map(e=>t.parseSsrcMedia(e)).filter(e=>\"msid\"===e.attribute);return r.length>0?(i=r[0].value.split(\" \"),{stream:i[0],track:i[1]}):void 0;},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,\"a=max-message-size:\");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const o=t.matchPrefix(e,\"a=sctp-port:\");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const s=t.matchPrefix(e,\"a=sctpmap:\");if(s.length>0){const e=s[0].substring(10).split(\" \");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r};}},t.writeSctpDescription=function(e,t){let i=[];return i=\"DTLS/SCTP\"!==e.protocol?[\"m=\"+e.kind+\" 9 \"+e.protocol+\" \"+t.protocol+\"\\r\\n\",\"c=IN IP4 0.0.0.0\\r\\n\",\"a=sctp-port:\"+t.port+\"\\r\\n\"]:[\"m=\"+e.kind+\" 9 \"+e.protocol+\" \"+t.port+\"\\r\\n\",\"c=IN IP4 0.0.0.0\\r\\n\",\"a=sctpmap:\"+t.port+\" \"+t.protocol+\" 65535\\r\\n\"],void 0!==t.maxMessageSize&&i.push(\"a=max-message-size:\"+t.maxMessageSize+\"\\r\\n\"),i.join(\"\");},t.generateSessionId=function(){return Math.random().toString().substr(2,22);},t.writeSessionBoilerplate=function(e,i,n){let r;const o=void 0!==i?i:2;r=e||t.generateSessionId();return\"v=0\\r\\no=\"+(n||\"thisisadapterortc\")+\" \"+r+\" \"+o+\" IN IP4 127.0.0.1\\r\\ns=-\\r\\nt=0 0\\r\\n\";},t.getDirection=function(e,i){const n=t.splitLines(e);for(let t=0;t(t.candidate&&Object.defineProperty(t,\"candidate\",{value:new e.RTCIceCandidate(t.candidate),writable:\"false\"}),t));}function OC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&\"relayProtocol\"in e.RTCIceCandidate.prototype||xR(e,\"icecandidate\",e=>{if(e.candidate){const t=kC.parseCandidate(e.candidate.candidate);\"relay\"===t.type&&(e.candidate.relayProtocol={0:\"tls\",1:\"tcp\",2:\"udp\"}[t.priority>>24]);}return e;});}function wC(e,t){if(!e.RTCPeerConnection)return;\"sctp\"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,\"sctp\",{get(){return void 0===this._sctp?null:this._sctp;}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,\"chrome\"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();\"plan-b\"===e&&Object.defineProperty(this,\"sctp\",{get(){return void 0===this._sctp?null:this._sctp;},enumerable:!0,configurable:!0});}if(function(e){if(!e||!e.sdp)return!1;const t=kC.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=kC.parseMLine(e);return t&&\"application\"===t.kind&&-1!==t.protocol.indexOf(\"SCTP\");});}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i;}(arguments[0]),i=function(e){let i=65536;return\"firefox\"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i;}(e),n=function(e,i){let n=65536;\"firefox\"===t.browser&&57===t.version&&(n=65535);const r=kC.matchPrefix(e.sdp,\"a=max-message-size:\");return r.length>0?n=parseInt(r[0].substring(19),10):\"firefox\"===t.browser&&-1!==i&&(n=2147483637),n;}(arguments[0],e);let r;r=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const o={};Object.defineProperty(o,\"maxMessageSize\",{get:()=>r}),this._sctp=o;}return i.apply(this,arguments);};}function PC(e){if(!e.RTCPeerConnection||!(\"createDataChannel\"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if(\"open\"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError(\"Message too large (can send a maximum of \"+t.sctp.maxMessageSize+\" bytes)\");return i.apply(e,arguments);};}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e;},xR(e,\"datachannel\",e=>(t(e.channel,e.target),e));}function LC(e){if(!e.RTCPeerConnection||\"connectionState\"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,\"connectionState\",{get(){return{completed:\"connected\",checking:\"connecting\"}[this.iceConnectionState]||this.iceConnectionState;},enumerable:!0,configurable:!0}),Object.defineProperty(t,\"onconnectionstatechange\",{get(){return this._onconnectionstatechange||null;},set(e){this._onconnectionstatechange&&(this.removeEventListener(\"connectionstatechange\",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener(\"connectionstatechange\",this._onconnectionstatechange=e);},enumerable:!0,configurable:!0}),[\"setLocalDescription\",\"setRemoteDescription\"].forEach(e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event(\"connectionstatechange\",e);t.dispatchEvent(i);}return e;},this.addEventListener(\"iceconnectionstatechange\",this._connectionstatechangepoly)),i.apply(this,arguments);};});}function MC(e,t){if(!e.RTCPeerConnection)return;if(\"chrome\"===t.browser&&t.version>=71)return;if(\"safari\"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf(\"\\na=extmap-allow-mixed\")){const i=t.sdp.split(\"\\n\").filter(e=>\"a=extmap-allow-mixed\"!==e.trim()).join(\"\\n\");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i;}return i.apply(this,arguments);};}function VC(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(\"chrome\"===t.browser&&t.version<78||\"firefox\"===t.browser&&t.version<68||\"safari\"===t.browser)&&arguments[0]&&\"\"===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve());});}function xC(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if(\"object\"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case\"stable\":case\"have-local-offer\":case\"have-remote-pranswer\":e.type=\"offer\";break;default:e.type=\"answer\";}if(e.sdp||\"offer\"!==e.type&&\"answer\"!==e.type)return i.apply(this,[e]);return(\"offer\"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]));});}var UC=Object.freeze({__proto__:null,shimRTCIceCandidate:DC,shimRTCIceCandidateRelayProtocol:OC,shimMaxMessageSize:wC,shimSendThrowTypeError:PC,shimConnectionState:LC,removeExtmapAllowMixed:MC,shimAddIceCandidateNullOrEmpty:VC,shimParameterlessSetLocalDescription:xC});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=BR,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser=\"Not a browser.\",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser=\"firefox\",t.version=VR(i.userAgent,/Firefox\\/(\\d+)\\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser=\"chrome\",t.version=VR(i.userAgent,/Chrom(e|ium)\\/(\\d+)\\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\\/(\\d+)\\./))return t.browser=\"Not a supported browser.\",t;t.browser=\"safari\",t.version=VR(i.userAgent,/AppleWebKit\\/(\\d+)\\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&\"currentDirection\"in e.RTCRtpTransceiver.prototype;}return t;}(e),r={browserDetails:n,commonShim:UC,extractVersion:VR,disableLog:UR,disableWarnings:FR,sdp:NC};switch(n.browser){case\"chrome\":if(!nC||!tC||!t.shimChrome)return i(\"Chrome shim is not included in this adapter release.\"),r;if(null===n.version)return i(\"Chrome shim can not determine version, not shimming.\"),r;i(\"adapter.js shimming chrome.\"),r.browserShim=nC,VC(e,n),xC(e),YR(e,n),zR(e),tC(e,n),qR(e),eC(e,n),QR(e),XR(e),ZR(e),iC(e,n),DC(e),OC(e),LC(e),wC(e,n),PC(e),MC(e,n);break;case\"firefox\":if(!mC||!sC||!t.shimFirefox)return i(\"Firefox shim is not included in this adapter release.\"),r;i(\"adapter.js shimming firefox.\"),r.browserShim=mC,VC(e,n),xC(e),rC(e,n),sC(e,n),oC(e),lC(e),aC(e),cC(e),dC(e),uC(e),hC(e),pC(e),_C(e),DC(e),LC(e),wC(e,n),PC(e);break;case\"safari\":if(!RC||!t.shimSafari)return i(\"Safari shim is not included in this adapter release.\"),r;i(\"adapter.js shimming safari.\"),r.browserShim=RC,VC(e,n),xC(e),IC(e),yC(e),TC(e),fC(e),gC(e),vC(e),EC(e),AC(e),DC(e),OC(e),wC(e,n),PC(e),MC(e,n);break;default:i(\"Unsupported browser!\");}}({window:\"undefined\"==typeof window?void 0:window});var FC,BC=Object.create,HC=Object.defineProperty,jC=Object.defineProperties,GC=Object.getOwnPropertyDescriptor,WC=Object.getOwnPropertyDescriptors,JC=Object.getOwnPropertyNames,KC=Object.getOwnPropertySymbols,YC=Object.getPrototypeOf,zC=Object.prototype.hasOwnProperty,qC=Object.prototype.propertyIsEnumerable,QC=Reflect.get,XC=Math.pow,ZC=(e,t,i)=>t in e?HC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,$C=(e,t)=>{for(var i in t||(t={}))zC.call(t,i)&&ZC(e,i,t[i]);if(KC)for(var i of KC(t))qC.call(t,i)&&ZC(e,i,t[i]);return e;},eb=(e,t)=>jC(e,WC(t)),tb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ib=(e,t)=>{for(var i in t)HC(e,i,{get:t[i],enumerable:!0});},nb=(e,t,i)=>(i=null!=e?BC(YC(e)):{},((e,t,i,n)=>{if(t&&\"object\"==typeof t||\"function\"==typeof t)for(let r of JC(t))!zC.call(e,r)&&r!==i&&HC(e,r,{get:()=>t[r],enumerable:!(n=GC(t,r))||n.enumerable});return e;})(!t&&e&&e.__esModule?i:HC(i,\"default\",{value:e,enumerable:!0}),e)),rb=(e,t,i,n)=>{for(var r,o=n>1?void 0:n?GC(t,i):t,s=e.length-1;s>=0;s--)(r=e[s])&&(o=(n?r(t,i,o):r(o))||o);return n&&o&&HC(t,i,o),o;},ob=(e,t,i)=>(ZC(e,\"symbol\"!=typeof t?t+\"\":t,i),i),sb=(e,t,i)=>QC(YC(e),i,t),ab=(e,t,i)=>new Promise((n,r)=>{var o=e=>{try{a(i.next(e));}catch(t){r(t);}},s=e=>{try{a(i.throw(e));}catch(t){r(t);}},a=e=>e.done?n(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next());}),cb=tb((e,t)=>{var i=Object.prototype.hasOwnProperty,n=\"~\";function r(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1;}function s(e,t,i,r,s){if(\"function\"!=typeof i)throw new TypeError(\"The listener must be a function\");var a=new o(i,r||e,s),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e;}function a(e,t){0==--e._eventsCount?e._events=new r():delete e._events[t];}function c(){this._events=new r(),this._eventsCount=0;}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1)),c.prototype.eventNames=function(){var e,t,r=[];if(0===this._eventsCount)return r;for(t in e=this._events)i.call(e,t)&&r.push(n?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r;},c.prototype.listeners=function(e){var t=n?n+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,o=i.length,s=new Array(o);r{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:%d 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\":\"\");}},{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:\"mid\",reg:/^mid:([^\\s]*)/,format:\"mid:%s\"},{name:\"msid\",reg:/^msid:(.*)/,format:\"msid:%s\"},{name:\"ptime\",reg:/^ptime:(\\d*)/,format:\"ptime:%d\"},{name:\"maxptime\",reg:/^maxptime:(\\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:\"invalid\",names:[\"value\"]}]};Object.keys(i).forEach(function(e){i[e].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format=\"%s\");});});}),db=tb(e=>{var t=function(e){return String(Number(e))===e?Number(e):e;},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:r?i[e.name]:i;(function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var o=0;o1&&(e[n[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=[],n=e.split(\" \").map(t),r=0;r{var i=lb(),n=/%[sdv%]/g,r=function(e){var t=1,i=arguments,r=i.length;return e.replace(n,function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case\"%%\":return\"%\";case\"%s\":return String(n);case\"%d\":return Number(n);case\"%v\":return\"\";}});},o=function(e,t,i){var n=[e+\"=\"+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o{var t=db(),i=ub();e.write=i,e.parse=t.parse,e.parseFmtpConfig=t.parseFmtpConfig,e.parseParams=t.parseParams,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList;}),pb=nb(cb()),_b=((FC=_b||{})[FC.INVALID_PARAMETER=4096]=\"INVALID_PARAMETER\",FC[FC.INVALID_OPERATION=4097]=\"INVALID_OPERATION\",FC[FC.NOT_SUPPORTED=4098]=\"NOT_SUPPORTED\",FC[FC.DEVICE_NOT_FOUND=4099]=\"DEVICE_NOT_FOUND\",FC[FC.INITIALIZE_FAILED=4100]=\"INITIALIZE_FAILED\",FC[FC.SIGNAL_CHANNEL_SETUP_FAILED=16385]=\"SIGNAL_CHANNEL_SETUP_FAILED\",FC[FC.SIGNAL_CHANNEL_ERROR=16386]=\"SIGNAL_CHANNEL_ERROR\",FC[FC.ICE_TRANSPORT_ERROR=16387]=\"ICE_TRANSPORT_ERROR\",FC[FC.JOIN_ROOM_FAILED=16388]=\"JOIN_ROOM_FAILED\",FC[FC.CREATE_OFFER_FAILED=16389]=\"CREATE_OFFER_FAILED\",FC[FC.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]=\"SIGNAL_CHANNEL_RECONNECTION_FAILED\",FC[FC.UPLINK_RECONNECTION_FAILED=16391]=\"UPLINK_RECONNECTION_FAILED\",FC[FC.DOWNLINK_RECONNECTION_FAILED=16392]=\"DOWNLINK_RECONNECTION_FAILED\",FC[FC.REMOTE_STREAM_NOT_EXIST=16400]=\"REMOTE_STREAM_NOT_EXIST\",FC[FC.CLIENT_BANNED=16448]=\"CLIENT_BANNED\",FC[FC.SERVER_TIMEOUT=16449]=\"SERVER_TIMEOUT\",FC[FC.SUBSCRIPTION_TIMEOUT=16450]=\"SUBSCRIPTION_TIMEOUT\",FC[FC.PLAY_NOT_ALLOWED=16451]=\"PLAY_NOT_ALLOWED\",FC[FC.DEVICE_AUTO_RECOVER_FAILED=16452]=\"DEVICE_AUTO_RECOVER_FAILED\",FC[FC.START_PUBLISH_CDN_FAILED=16453]=\"START_PUBLISH_CDN_FAILED\",FC[FC.STOP_PUBLISH_CDN_FAILED=16454]=\"STOP_PUBLISH_CDN_FAILED\",FC[FC.START_MIX_TRANSCODE_FAILED=16455]=\"START_MIX_TRANSCODE_FAILED\",FC[FC.STOP_MIX_TRANSCODE_FAILED=16456]=\"STOP_MIX_TRANSCODE_FAILED\",FC[FC.NOT_SUPPORTED_H264=16457]=\"NOT_SUPPORTED_H264\",FC[FC.SWITCH_ROLE_FAILED=16458]=\"SWITCH_ROLE_FAILED\",FC[FC.API_CALL_TIMEOUT=16459]=\"API_CALL_TIMEOUT\",FC[FC.SCHEDULE_FAILED=16460]=\"SCHEDULE_FAILED\",FC[FC.API_CALL_ABORTED=16461]=\"API_CALL_ABORTED\",FC[FC.UNKNOWN=65535]=\"UNKNOWN\",FC),mb=_b,fb=class extends Error{constructor(e){let{name:t=\"RtcError\",message:i,code:n=mb.UNKNOWN,extraCode:r=0,constraint:o}=e,s=\"<\".concat(function(e){for(let t in mb)if(mb[t]===e)return t;return\"UNKNOWN\";}(n),\" 0x\").concat(n.toString(16),\">\"),a=\"\".concat(i).concat(o?\" constraint: \".concat(o):\"\").concat(null!=i&&i.includes(s)?\"\":\" \".concat(s));super(a),ob(this,\"code\"),ob(this,\"extraCode\"),ob(this,\"message\"),ob(this,\"originMessage\"),ob(this,\"name\"),ob(this,\"constraint\"),this.code=n,this.extraCode=r,this.name=t,this.message=a,this.constraint=o,this.originMessage=i;}getCode(){return this.code;}getExtraCode(){return this.extraCode;}toString(){return this.originMessage;}},gb=fb,Tb=(new Date().getTime(),0),Eb=function(){return new Date().getTime()+Tb;},Sb=function(){let e=new Date();return e.setTime(Eb()),e.toLocaleString();},Ib={};ib(Ib,{bytes2ms:()=>KD,copyProperties:()=>JD,deepMerge:()=>CO,env:()=>vb,fibonacci:()=>$D,formatedTime:()=>NO,getConstructorName:()=>pO,getContainerFromElement:()=>bO,getEnv:()=>UD,getInternalVersion:()=>TO,getLoggerUrl:()=>BD,getMuteStateFromFlag:()=>IO,getNetworkQuality:()=>vO,getNetworkType:()=>GD,getOSType:()=>jD,getReconnectionTimeout:()=>eO,getStringByteLength:()=>wO,getSysInfo:()=>WD,getTerminalType:()=>HD,getTurnServer:()=>yO,getValueType:()=>tO,glog:()=>QD,ipv4ToUint32:()=>AO,isArray:()=>cO,isArrayOrObject:()=>RO,isAudioWorkletSupported:()=>_O,isBoolean:()=>sO,isConstructor:()=>hO,isEmpty:()=>SO,isFunction:()=>iO,isLangChinese:()=>XD,isMediaStreamTrack:()=>lO,isNumber:()=>oO,isObject:()=>aO,isOverseaSdkAppId:()=>FD,isPlainObject:()=>ZD,isPromise:()=>uO,isRemoteTrack:()=>dO,isString:()=>rO,isUndefined:()=>nO,ms2bytes:()=>zD,ms2samples:()=>qD,performanceNow:()=>fO,promiseAny:()=>mO,samples2ms:()=>YD,stringify:()=>DO,stringifyIncludeValue:()=>OO});var vb={};ib(vb,{ANDROID_VERSION:()=>Mb,CHROME_MAJOR_VERSION:()=>Vk,CHROME_VERSION:()=>xk,EDGE_VERSION:()=>jb,EDG_MAJOR_VERSION:()=>Jb,EDG_VERSION:()=>Wb,FIREFOX_MAJOR_VERSION:()=>Bb,FIREFOX_VERSION:()=>Fb,HUAWEI_VERSION:()=>Rk,IE_VERSION:()=>ik,IOS_MAIN_VERSION:()=>Gk,IOS_VERSION:()=>jk,IPADQQB_VERSION:()=>pk,IS_ANDROID:()=>Lb,IS_ANDROID_WEBVIEW:()=>Hk,IS_ANY_SAFARI:()=>Fk,IS_CHROME:()=>Lk,IS_CHROME_OS:()=>gk,IS_CHROMIUM_BASE:()=>Pk,IS_EDG:()=>Gb,IS_EDGE:()=>Hb,IS_ELECTRON:()=>Sk,IS_FIREFOX:()=>Ub,IS_HEADLESS_CHROME:()=>Mk,IS_HUAWEI:()=>Ak,IS_HUAWEIBROWSER:()=>yk,IS_IE:()=>tk,IS_IE8:()=>ek,IS_IOS:()=>Pb,IS_IOS_13_OR_14:()=>Kk,IS_IOS_15_1:()=>Jk,IS_IPAD:()=>Nb,IS_IPADQQB:()=>hk,IS_IPAD_PRO:()=>Db,IS_IPHONE:()=>Ob,IS_IPOD:()=>wb,IS_LINUX:()=>fk,IS_LOCAL:()=>Yk,IS_MAC:()=>mk,IS_MACQQB:()=>dk,IS_MIBROWSER:()=>Ik,IS_MQQB:()=>sk,IS_NATIVE_ANDROID:()=>xb,IS_OLD_ANDROID:()=>Vb,IS_OPPOBROWSER:()=>kk,IS_SAFARI:()=>Uk,IS_SAFARI_15_1:()=>Wk,IS_SAMSUNGBROWSER:()=>Ck,IS_SOGOU:()=>zb,IS_SOGOUM:()=>Kb,IS_TBS:()=>Qb,IS_UCBROWSER:()=>Ek,IS_VIVOBROWSER:()=>Dk,IS_WECHAT:()=>nk,IS_WIN:()=>_k,IS_WQQB:()=>ck,IS_WX:()=>Tk,IS_X5MQQB:()=>ok,IS_XWEB:()=>Zb,MACQQB_VERSION:()=>uk,MI_VERSION:()=>vk,MQQB_VERSION:()=>ak,OPPO_VERSION:()=>Nk,SAFARI_VERSION:()=>Bk,SAMSUNG_VERSION:()=>bk,SOGOUM_VERSION:()=>Yb,SOGOU_VERSION:()=>qb,TBS_VERSION:()=>Xb,USER_AGENT:()=>yb,VIVO_VERSION:()=>Ok,WECHAT_VERSION:()=>rk,WQQB_VERSION:()=>lk,XWEB_VERSION:()=>$b,browserInfo:()=>qk,getBrowserInfo:()=>Qk,getChromeMajorVersion:()=>wk,getOSName:()=>eN,getOSString:()=>tN,getUserAgentData:()=>Zk,isLocalStorageEnabled:()=>zk});var yb=\"undefined\"==typeof navigator?\"\":navigator.userAgent,Ab=e=>new RegExp(e,\"i\").test(yb),Rb=e=>{if(Ab(e)){let t=new RegExp(\"\".concat(e,\"\\\\/([\\\\d.]+)\")),i=yb.match(t);if(i&&i[1])return i[1];}return\"\";},Cb=e=>{if(Ab(e)){let t=new RegExp(\"\".concat(e,\"\\\\/(\\\\d+)\")),i=yb.match(t);if(i&&i[1])return parseFloat(i[1]);}return NaN;},bb=/AppleWebKit\\/([\\d.]+)/i.exec(yb),kb=bb?parseFloat(bb[1]):NaN,Nb=Ab(\"iPad\"),Db=\"undefined\"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Ab(\"Macintosh\"),Ob=Ab(\"iPhone\")&&!Nb,wb=Ab(\"iPod\"),Pb=Ob||Nb||wb||Db,Lb=Ab(\"Android\"),Mb=function(){if(Lb){let e=yb.match(/Android (\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))*/i);if(e){let t=e[1]&&parseFloat(e[1]),i=e[2]&&parseFloat(e[2]);if(t&&i)return parseFloat(\"\".concat(e[1],\".\").concat(e[2]));if(t)return t;}}return NaN;}(),Vb=Lb&&Ab(\"webkit\")&&Mb<2.3,xb=Lb&&Mb<5&&kb<537,Ub=Ab(\"Firefox\"),Fb=Rb(\"Firefox\"),Bb=Cb(\"Firefox\"),Hb=Ab(\"Edge\"),jb=Rb(\"Edge\"),Gb=Ab(\"Edg\"),Wb=Rb(\"Edg\"),Jb=Cb(\"Edg\"),Kb=Ab(\"SogouMobileBrowser\"),Yb=Rb(\"SogouMobileBrowser\"),zb=Ab(\"MetaSr\\\\s\"),qb=Rb(\"MetaSr\\\\s\"),Qb=Ab(\"TBS\"),Xb=Rb(\"TBS\"),Zb=Ab(\"XWEB\"),$b=Rb(\"XWEB\"),ek=Ab(\"MSIE\\\\s8\\\\.0\"),tk=Ab(\"MSIE\\\\/\\\\d+\"),ik=function(){if(tk){let e=/MSIE\\s(\\d+)\\.\\d/.exec(yb),t=e&&parseFloat(e[1]);return!t&&/Trident\\/7.0/i.test(yb)&&/rv:11.0/.test(yb)&&(t=11),t;}return NaN;}(),nk=Ab(\"(micromessenger|webbrowser)\"),rk=Rb(\"MicroMessenger\"),ok=!Qb&&Ab(\"MQQBrowser\")&&Ab(\"COVC\"),sk=!Qb&&Ab(\"MQQBrowser\")&&!Ab(\"COVC\"),ak=sk||ok?Rb(\"MQQBrowser\"):\"\",ck=!Qb&&Ab(\" QQBrowser\"),lk=Rb(\" QQBrowser\"),dk=!Qb&&Ab(\"QQBrowserLite\"),uk=Rb(\"QQBrowserLite\"),hk=!Qb&&Ab(\"MQBHD\"),pk=Rb(\"MQBHD\"),_k=Ab(\"Windows\"),mk=!Pb&&Ab(\"MAC OS X\"),fk=!Lb&&Ab(\"Linux\"),gk=Ab(\"CrOS\"),Tk=Ab(\"MicroMessenger\"),Ek=Ab(\"UCBrowser\"),Sk=Ab(\"Electron\"),Ik=Ab(\"MiuiBrowser\"),vk=Rb(\"MiuiBrowser\"),yk=Ab(\"HuaweiBrowser\"),Ak=Ab(\"Huawei\"),Rk=Rb(\"HuaweiBrowser\"),Ck=Ab(\"SamsungBrowser\"),bk=Rb(\"SamsungBrowser\"),kk=Ab(\"HeyTapBrowser\"),Nk=Rb(\"HeyTapBrowser\"),Dk=Ab(\"VivoBrowser\"),Ok=Rb(\"VivoBrowser\"),wk=()=>Cb(\"Chrome\"),Pk=Ab(\"Chrome\"),Lk=!Hb&&!zb&&!Kb&&!Qb&&!Zb&&!Gb&&!ck&&!Ik&&!yk&&!Ck&&!kk&&!Dk&&Pk,Mk=Ab(\"HeadlessChrome\"),Vk=wk(),xk=Rb(\"Chrome\"),Uk=!Pk&&!sk&&!ok&&!dk&&!hk&&Ab(\"Safari\"),Fk=Uk||Pb,Bk=Rb(\"Version\"),Hk=/Android.*(wv|.0.0.0)/.test(yb),jk=(()=>{if(Db)return Bk;if(Pb){let e=yb.match(/OS (\\d+)_(\\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=\".\".concat(e[2])),t;}}return\"\";})(),Gk=Number(jk.split(\".\")[0]),Wk=\"15.1\"===Bk,Jk=\"15.1\"===jk,Kk=(()=>{let e=Number(jk.split(\".\")[0]);return 14===e||13===e;})(),Yk=\"undefined\"!=typeof location&&(\"file:\"===location.protocol||\"localhost\"===location.hostname||\"127.0.0.1\"===location.hostname),zk=(()=>{let e;return()=>{if(nO(e))try{e=!!window.localStorage;}catch(HL){e=!1;}return e;};})(),qk=Qk();function Qk(){let e=new Map([[Ub,[\"Firefox\",Fb]],[Gb,[\"Edg\",Wb]],[Lk,[\"Chrome\",xk]],[Uk,[\"Safari\",Bk]],[Qb,[\"TBS\",Xb]],[Zb,[\"XWEB\",$b]],[nk&&Ob,[\"WeChat\",rk]],[ck,[\"QQ(Win)\",lk]],[sk,[\"QQ(Mobile)\",ak]],[ok,[\"QQ(Mobile X5)\",ak]],[dk,[\"QQ(Mac)\",uk]],[hk,[\"QQ(iPad)\",pk]],[Ik,[\"MI\",vk]],[yk,[\"HW\",Rk]],[Ck,[\"Samsung\",bk]],[kk,[\"OPPO\",Nk]],[Dk,[\"VIVO\",Ok]],[Hb,[\"EDGE\",jb]],[Kb,[\"SogouMobile\",Yb]],[zb,[\"Sogou\",qb]]]),t=\"unknown\",i=\"unknown\";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i};}var Xk=null;function Zk(){return ab(this,null,function*(){if(Xk)return Xk;if(!navigator.userAgentData||!iO(navigator.userAgentData.getHighEntropyValues))return null;try{return Xk=yield navigator.userAgentData.getHighEntropyValues([\"architecture\",\"bitness\",\"model\",\"platformVersion\",\"fullVersionList\"]);}catch(BL){return null;}});}var $k=new Map([[Lb,\"Android\"],[Pb,\"iOS\"],[_k,\"Windows\"],[mk,\"MacOS\"],[fk,\"Linux\"],[gk,\"ChromeOS\"]]),eN=function(){return $k.get(!0)?$k.get(!0):Xk?Xk.platform:\"unknown\";},tN=()=>{let e=eN();return e+=\"/\".concat(qk.name,\"/\").concat(Uk?qk.version:qk.version.split(\".\")[0]),null!=Xk&&Xk.platformVersion&&(e+=\"/\".concat(Xk.platformVersion)),null!=Xk&&Xk.architecture&&(e+=\"/\".concat(Xk.architecture)),e;},iN={};ib(iN,{AUDIO_MUTE_BIT:()=>jN,AUDIO_STAT_BIT:()=>HN,AUX_STAT_BIT:()=>BN,AUX_STREAM_MSID:()=>JN,BACKEND_ENV:()=>VN,BASE_DOC_URL:()=>TN,BASE_HOST:()=>_N,CAPABILITIES_KEYS:()=>VD,CLASS_NAME:()=>yD,CLOUD_CONSOLE_URL:()=>gN,DATA_FREEZE_TIMING:()=>fD,DOC_URL:()=>EN,DTLS_STATE_UNKNOWN:()=>tD,ENV_NAME:()=>AN,EXCHANGE_SDP_TIMEOUT:()=>uD,INTERVAL:()=>LD,IS_WORKER:()=>lN,IS_WORKLET:()=>dN,KIBANA_EVENT:()=>cD,LOCAL_STREAM_PUBLISH_STATE:()=>mD,LOGGER_CMD_TYPE:()=>yN,LOGGER_DOMAIN:()=>SN,LOGGER_DOMAIN_OVERSEA:()=>IN,LOG_LEVEL:()=>RN,LOG_LEVEL_NAME:()=>kD,MAIN_STREAM_MSID:()=>WN,MICROPHONE_COMMUNICATIONS:()=>bD,MICROPHONE_DEFAULT:()=>RD,NAME:()=>LN,NETWORK_TYPE:()=>kN,NOT_SUPPORTED_H264:()=>_D,PAUSED_RETRY_COUNT:()=>AD,PEERCONNECTION_CONNECTING_TIMEOUT:()=>SD,PEER_CONNECTION_STATE:()=>iD,PEER_LEAVE_REASON:()=>ND,RAF:()=>PD,RECOVER_CAPTURE_INTERVAL:()=>OD,REMOTE_STREAM_TYPE_AUX:()=>YN,REMOTE_STREAM_TYPE_MAIN:()=>KN,RENDER_FREEZE_TIMING:()=>gD,RIC:()=>wD,SCHEDULE_DOMAIN:()=>ID,SCHEDULE_TIMEOUT:()=>vD,SDP_SEMANTICS_PLAN_B:()=>pD,SDP_SEMANTICS_UNIFIED_PLAN:()=>hD,SECOND_HOST:()=>mN,SIGNAL_PING_PONG_INTERVAL:()=>bN,SIGNAL_PING_TIMEOUT:()=>CN,SIGNAL_RECONNECTION_COUNT:()=>aD,SMALL_STAT_BIT:()=>FN,SPEAKER_DEFAULT:()=>CD,STORAGE_EXPIRES_TIME:()=>NN,STREAM_TYPE_BIG:()=>TD,STREAM_TYPE_SMALL:()=>ED,SUBSCRIBE_SMALL_RETRY_COUNT:()=>DD,SYNC_USER_LIST_INTERVAL:()=>lD,Scene:()=>xN,Switch:()=>DN,THIRD_HOST:()=>fN,TIMEOUT:()=>MD,TRANSPORT_DIRECTION:()=>MN,TRTC_ERROR_ASSISTANCE:()=>vN,TRTC_QUALITY_BAD:()=>ZN,TRTC_QUALITY_DISCONNECTED:()=>eD,TRTC_QUALITY_EXCELLENT:()=>qN,TRTC_QUALITY_GOOD:()=>QN,TRTC_QUALITY_POOR:()=>XN,TRTC_QUALITY_UNKNOWN:()=>zN,TRTC_QUALITY_VERY_BAD:()=>$N,UPDATE_OFFER_TIMEOUT:()=>dD,VIDEO_MUTE_BIT:()=>GN,VIDEO_STAT_BIT:()=>UN,audioProfileMap:()=>ON,getRetryCount:()=>oD,getScriptDir:()=>uN,innerVersion:()=>nN,loggerProxy:()=>hN,screenProfileMap:()=>PN,setLoggerProxy:()=>pN,setRetryCount:()=>rD,setVersion:()=>oN,version:()=>rN,videoProfileMap:()=>wN});var nN=\"4.15.00.1600\",rN=\"5.0.0\";function oN(e){rN=e;let[t,i,n]=e.split(\".\").map(e=>parseInt(e,10));nN=\"\".concat(t,\".\").concat(Math.min(15,i),\".\").concat(Math.min(15,n),\".\").concat(i.toString().padStart(2,\"0\")).concat(n.toString().padStart(2,\"0\"));}var sN,aN,cN,lN=\"undefined\"!=typeof importScripts,dN=\"undefined\"!=typeof registerProcessor,uN=()=>{let e=lN?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf(\"/\")+1);},hN=\"\",pN=e=>hN=e,_N=\"web.sdk.qcloud.com\",mN=\"web.sdk.tencent.cn\",fN=\"web.sdk.cloud.tencent.cn\",gN=\"https://console.cloud.tencent.com/trtc\",TN=\"https://\".concat(_N,\"/trtc/webrtc/v5/doc\"),EN=\"\".concat(TN,\"/zh-cn/\"),SN=\"https://yun.tim.qq.com\",IN=\"https://apisgp.my-imcloud.com\",vN=\"trtc_error_assistance\",yN={LOG:\"jssdk_log\",EVENT:\"jssdk_event\",KEY_POINT:\"jssdk_new_endreport\"},AN={QCLOUD:\"qcloud\",OLD_CLOUD_LADDER:\"trtc\",WEBRTC:\"webrtc\"},RN=((cN=RN||{})[cN.TRACE=0]=\"TRACE\",cN[cN.DEBUG=1]=\"DEBUG\",cN[cN.INFO=2]=\"INFO\",cN[cN.WARN=3]=\"WARN\",cN[cN.ERROR=4]=\"ERROR\",cN[cN.NONE=5]=\"NONE\",cN),CN=18e3,bN=2e3,kN={unknown:0,wifi:1,\"3g\":2,\"2g\":3,\"4g\":4,wired:5},NN=6048e5,DN=((aN=DN||{}).USEAINS=\"useAINS\",aN.ENABLEDEBUG=\"enableDebug\",aN.USEV2=\"useV2\",aN.USEWT=\"useWt\",aN),ON={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}},wN={\"120p\":{width:160,height:120,frameRate:15,bitrate:200},\"120p_2\":{width:160,height:120,frameRate:15,bitrate:100},\"180p\":{width:320,height:180,frameRate:15,bitrate:350},\"180p_2\":{width:320,height:180,frameRate:15,bitrate:150},\"240p\":{width:320,height:240,frameRate:15,bitrate:400},\"240p_2\":{width:320,height:240,frameRate:15,bitrate:200},\"360p\":{width:640,height:360,frameRate:15,bitrate:800},\"360p_2\":{width:640,height:360,frameRate:15,bitrate:400},\"480p\":{width:640,height:480,frameRate:15,bitrate:900},\"480p_2\":{width:640,height:480,frameRate:15,bitrate:500},\"720p\":{width:1280,height:720,frameRate:15,bitrate:1500},\"1080p\":{width:1920,height:1080,frameRate:15,bitrate:2e3},\"1440p\":{width:2560,height:1440,frameRate:30,bitrate:4860},\"4K\":{width:3840,height:2160,frameRate:30,bitrate:9e3}},PN={\"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}},LN={CANVAS:\"canvas\",AUDIO:\"audio\",VIDEO:\"video\",SCREEN:\"screen\",SMALL:\"small\",BIG:\"big\",AUXILIARY:\"auxiliary\",SMALL_VIDEO:\"smallVideo\",FACING_MODE_USER:\"user\",FACING_MODE_ENVIRONMENT:\"environment\",MUTE:\"mute\",UNMUTE:\"unmute\",ENDED:\"ended\",PLAYING:\"playing\",PAUSE:\"pause\",ERROR:\"error\",LOADEDDATA:\"loadeddata\",AUDIO_INPUT:\"audioinput\",VIDEO_INPUT:\"videoinput\",DETAIL:\"detail\",TEXT:\"text\",MAIN:\"main\",BACKUP:\"backup\",BANNED:\"banned\",KICK:\"kick\",USER_TIME_OUT:\"user_time_out\",ROOM_DISBAND:\"room_disband\",SEI_MESSAGE:\"sei-message\",ADD:\"add\",REMOVE:\"remove\",REPLACE:\"replace\",TRACK:\"track\",SUBSCRIBE:\"subscribe\",UNSUBSCRIBE:\"unsubscribe\",TRANSCEIVER_DIRECTION_SENDONLY:\"sendonly\",TRANSCEIVER_DIRECTION_RECVONLY:\"recvonly\",ENTER_PICTURE_IN_PICTURE:\"enterpictureinpicture\",LEAVE_PICTURE_IN_PICTURE:\"leavepictureinpicture\"},MN={INACTIVE:\"inactive\",SENDONLY:\"sendonly\",RECVONLY:\"recvonly\"},VN={OLD_CLOUD_LADDER:\"wss://trtc.rtc.qq.com\",WEBRTC:\"wss://webrtc.qq.com\"},xN=((sN=xN||{}).LIVE=\"live\",sN.RTC=\"rtc\",sN),UN=1,FN=2,BN=4,HN=8,jN=64,GN=16,WN=\"5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV\",JN=\"224d130c-7b5c-415b-aaa2-79c2eb5a6df2\",KN=LN.MAIN,YN=LN.AUXILIARY,zN=0,qN=1,QN=2,XN=3,ZN=4,$N=5,eD=6,tD=\"unknown\",iD={NEW:\"new\",CONNECTING:\"connecting\",FAILED:\"failed\",CLOSED:\"closed\",DISCONNECTED:\"disconnected\",CONNECTED:\"connected\",COMPLETED:\"completed\"},nD=1/0;function rD(e){nD=e;}function oD(){return nD;}var sD,aD=30,cD={JOIN:\"join\",DELTA_JOIN:\"delta-join\",REJOIN:\"rejoin\",LEAVE:\"leave\",DELTA_LEAVE:\"delta-leave\",PUBLISH:\"publish\",DELTA_PUBLISH:\"delta-publish\",UNPUBLISH:\"unpublish\",SUBSCRIBE:\"subscribe\",UNSUBSCRIBE:\"unsubscribe\",UPLINK_CONNECTION:\"uplink-connection\",UPLINK_RECONNECTION:\"uplink-reconnection\",DOWNLINK_CONNECTION:\"downlink-connection\",DOWNLINK_RECONNECTION:\"downlink-reconnection\",ON_TRACK:\"ontrack\",ICE_CONNECTION_STATE:\"iceConnectionState\",LOCAL_STREAM_INITIALIZE:\"stream-initialize\",SIGNAL_CONNECTION:\"websocketConnectionState\",SIGNAL_RECONNECTION:\"websocketReconnectionState\",UPDATE_STREAM:\"update-stream\",RECOVER_LOCAL_AUDIO_TRACK:\"recover-local-audio-track\",RECOVER_LOCAL_VIDEO_TRACK:\"recover-local-video-track\",RECOVER_SUBSCRIPTION:\"recover-subscription\",START_MIX_TRANSCODE:\"start-mix-transcode\",STOP_MIX_TRANSCODE:\"stop-mix-transcode\",PLAYER_ERROR:\"player-error\",SCHEDULE:\"schedule\",LOAD_WORKLET:\"load-worklet\",VIDEO_FROZEN_COUNT:\"videoFrozenCount\",GET_USER_MEDIA_RETRY:\"getUserMedia-retry\"},lD=1e4,dD=1e4,uD=1e4,hD=\"unified-plan\",pD=\"plan-b\",_D=1028,mD=((sD=mD||{})[sD.UNPUBLISH=-1]=\"UNPUBLISH\",sD[sD.PUBLISHING=0]=\"PUBLISHING\",sD[sD.PUBLISHED=1]=\"PUBLISHED\",sD),fD=500,gD=1e3,TD=LN.BIG,ED=LN.SMALL,SD=1e4,ID={MAIN:\"schedule.rtc.qq.com\",BACKUP:\"schedule.rtc.qcloud.com\",MAIN_OVERSEA:\"schedule.rtc.tencentcloud.com\",BACKUP_OVERSEA:\"schedule-ecdn.rtc.tencentcloud.com\"},vD=2e3,yD={TRTC:\"TRTC\",CLIENT:\"Client\",LOCAL_STREAM:\"LocalStream\",REMOTE_STREAM:\"RemoteStream\",STREAM:\"Stream\"},AD=5,RD=\"default\",CD=RD,bD=\"communications\",kD=Object.keys(RN),ND=[\"normal leave\",\"timeout leave\",\"kick\",\"role change\"],DD=10,OD=2e3,wD=\"ric\",PD=\"raf\",LD=\"interval\",MD=\"timeout\",VD=[\"width\",\"height\",\"frameRate\",\"facingMode\",\"sampleRate\",\"sampleSize\",\"channelCount\",\"deviceId\"],xD=1e8,UD=function(){return new URLSearchParams(location.search).get(\"trtc_env\")||\"\";},FD=e=>Number(e)<14e8,BD=function(e,t){let i;i=hN||(FD(e)?IN:SN);let n=Math.floor(Math.random()*XC(2,31));return\"\".concat(i,\"/v5/AVQualityReportSvc/C2S?random=\").concat(n,\"&sdkappid=\").concat(e,\"&cmdtype=\").concat(t);};function HD(){return Lb?4:Ob?2:Nb?3:mk?12:_k?5:fk?13:1;}function jD(){return Lb?\"Android\":Ob?\"iPhone\":Nb?\"iPad\":mk?\"Mac\":_k?\"Windows\":fk?\"Linux\":\"unknown\";}function GD(){let{userAgent:e,connection:t}=navigator,i=(e.match(/NetType\\/\\S+/)||[])[0]||\"\";i=i.toLowerCase().replace(\"nettype/\",\"\"),\"3gnet\"===i&&(i=\"3g\");let n=t&&t.type&&t.type.toLowerCase(),r=t&&t.effectiveType&&t.effectiveType.toLowerCase();\"slow-2\"===r&&(r=\"2g\");let o=i||\"unknown\";if(n)switch(n){case\"cellular\":case\"wimax\":o=r||\"unknown\";break;case\"wifi\":o=\"wifi\";break;case\"ethernet\":o=\"wired\";break;default:o=\"unknown\";}return o;}var WD=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:HD(),uint32_device_type:0,str_os_verion:jD(),uint32_link_type:1,str_client_version:nN,uint32_net_type:kN[GD()],ua:navigator.userAgent,version:\"\"}}};};function JD(e,t){for(let i of Reflect.ownKeys(t))if(\"constructor\"!==i&&\"prototype\"!==i&&\"name\"!==i){let n=Object.getOwnPropertyDescriptor(t,i)||\"\";Object.defineProperty(e,i,n);}return e;}function KD(e){return YD(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3);}function YD(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3);}function zD(e){return 4*qD(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3);}function qD(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3;}var QD=\"undefined\"!=typeof window&&\"function\"==typeof window.glog?window.glog:()=>{},XD=()=>{let e=navigator.language;return e=e.substring(0,2),\"zh\"===e;},ZD=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 $D(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:$D(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t);}function eO(e){return e>8?3e4:1e3*$D(e);}function tO(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\\[object\\s(\\w+)\\]$/,\"$1\").toLowerCase();}var iO=e=>\"function\"==typeof e,nO=e=>void 0===e,rO=e=>\"string\"==typeof e,oO=e=>\"number\"==typeof e,sO=e=>\"boolean\"==typeof e,aO=e=>\"object\"===tO(e),cO=e=>\"array\"===tO(e),lO=e=>tO(e)===\"MediaStreamTrack\".toLowerCase(),dO=e=>e.isRemote,uO=e=>\"promise\"===tO(e),hO=e=>iO(e)&&e.prototype.constructor===e,pO=e=>hO(e)?e.prototype.constructor.name:\"\",_O=\"undefined\"!=typeof AudioWorkletNode;function mO(e){return new Promise((t,i)=>{let n=[];e.forEach(r=>{r.then(t).catch(t=>{n.push(t),n.length===e.length&&i(n);});});});}function fO(){return performance&&performance.now?Math.floor(performance.now()):Date.now();}var gO=e=>+e<10?\"0\".concat(e):e,TO=e=>{let t=e.match(/^\\d+\\.\\d+\\.\\d+/)[0];if(!t)return e;let i=t.split(\".\"),n=gO(i[1])+gO(i[2]);return i[1]-15>0&&(i[1]=\"15\"),i[2]-15>0&&(i[2]=\"15\"),\"\".concat(i.join(\".\"),\".\").concat(n);},EO=Object.prototype.hasOwnProperty;function SO(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(ZD(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(EO.call(e,t))return!1;return!0;}return!1;}function IO(e,t){return{userId:t,hasAudio:!!(e&HN),hasVideo:!!(e&UN),hasAuxiliary:!!(e&BN),hasSmall:!!(e&FN),audioMuted:!!(e&jN),videoMuted:!!(e&GN),audioAvailable:!(!(e&HN)||e&jN),videoAvailable:!(!(e&UN)||e&GN)};}function vO(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 yO(e){let t={urls:\"turn:\".concat(e.url)};return!nO(e.username)&&!nO(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType=\"password\",nO(e.credentialType)||(t.credentialType=e.credentialType)),t;}function AO(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!rO(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 RO=function(e){return cO(e)||aO(e);},CO=function(e,t,i,n){if(!RO(e)||!RO(t))return 0;let r,o=0,s=Object.keys(t);for(let a=0,c=s.length;arO(e)?document.getElementById(e):e,kO=new Intl.DateTimeFormat(\"zh-CN\",{dateStyle:\"short\",timeStyle:\"medium\"}),NO=()=>kO.format(new Date());function DO(e,t){let{keysToInclude:i,keysToExclude:n}=t;try{if(cO(e))return\"[\".concat(e.map(e=>DO(e,{keysToInclude:i,keysToExclude:n})).join(\",\"),\"]\");if(!ZD(e)||!cO(i)&&!cO(n))return JSON.stringify(e);let t={},r=new Set(i),o=new Set(n);return Object.keys(e).forEach(s=>{(0===o.size&&r.has(s)||0===r.size&&!o.has(s))&&(t[s]=ZD(e[s])||cO(e[s])?JSON.parse(DO(e[s],{keysToExclude:n,keysToInclude:i})):e[s]);}),JSON.stringify(t);}catch(sD){return\"{}\";}}function OO(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=[];return Object.keys(e).forEach(n=>{t===e[n]&&i.push(n);}),DO(e,{keysToInclude:i});}function wO(e){return e.replace(/[\\u4e00-\\u9fa5]/g,\"aa\").length;}function PO(e){let{url:t,body:i,method:n,timeout:r}=e,o=new XMLHttpRequest();return new Promise((e,s)=>{o.onreadystatechange=()=>{if(4===o.readyState)if(o.status>=200&&o.status<300)try{let t=JSON.parse(o.response);e({data:t});}catch(qx){e({data:o.response});}else s({status:o.status,statusText:o.statusText||\"request failed!\"});},o.timeout=r||5e3,o.open(n||\"POST\",t,!0),o.send(i);});}var LO,MO=function(e){let{retryFunction:t,settings:i,onError:n,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:a}=e;return function(){for(var e=arguments.length,c=new Array(e),l=0;lab(this,null,function*(){let l=a||this;try{let i=yield t.apply(l,c);h>0&&s&&s.call(this,h),h=0,e(i);}catch(f){let t=()=>{clearTimeout(p),h=0,_=2,i(f);},s=()=>{2!==_&&h<(iO(d)?d():d)?(h++,_=1,iO(r)&&r.call(this,h,t),p=window.setTimeout(()=>{p=-1,m(e,i);},iO(u)?u(h):u)):(t(),iO(o)&&o.call(this,f));};iO(n)?n.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retryCount:h}):s();}});return new Promise(m);};},VO=class{constructor(e){ob(this,\"userId\"),ob(this,\"remoteUserId\"),ob(this,\"id\"),ob(this,\"sdkAppId\"),ob(this,\"type\"),ob(this,\"isLocal\"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!sO(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):\"\",\"]\")),HO.log(e,t,nO(this.userId)||SO(this.userId),this.userId,this.sdkAppId);}info(){for(var e=arguments.length,t=new Array(e),i=0;i{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&RN[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload);}),xO.on(FO.JOIN_SUCCESS,e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload();}),xO.once(FO.JOIN_FAILED,()=>{this.startUpload();}),xO.on(FO.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{let{userId:n,sdkAppId:r}=t;e.map.has(n)?e.map.get(n).logs.push(i):e.map.set(n,{userId:n,sdkAppId:r,logs:[i]});});else if(rO(i.userId)&&oO(i.sdkAppId)){let{userId:t,sdkAppId:n}=i;e.map.has(t)?e.map.get(t).logs.push(i):e.map.set(t,{userId:t,sdkAppId:n,logs:[i]});}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e;}upload(){return ab(this,null,function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;ee.log).join(\"\\n\")}),n),r.forEach(e=>e.uploaded=!0);}}catch(aN){}let i=t.filter(e=>!e.uploaded);i.length>0&&(this._queue=i.concat(this._queue));});}uploadLogWithRetry(e,t){return MO({retryFunction:()=>PO({url:BD(t,yN.LOG),body:e,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:e=>{let{retry:t}=e;t();}})();}getPrefix(e){let t=new Date();t.setTime(Eb());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(RN[e],\">\");}getLogLevel(){return this._logLevel;}setLogLevel(e){nO(RN[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(rO(e))return e;try{return JSON.stringify(e);}catch(sN){return\"\";}}log(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,r=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:n,sdkAppId:r,forAllJoinedClients:i}),e{let t=16*Math.random()|0;return(\"x\"==e?t:3&t|8).toString(16);});},GO=new class{constructor(){ob(this,\"_prefix\",\"TRTC\"),ob(this,\"_queue\",new Map()),this.checkStorage();}getRealKey(e){return\"\".concat(this._prefix,\"_\").concat(e);}checkStorage(){zk()&&(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.expiresInlocalStorage.removeItem(e)));}doFlush(){if(zk())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t));}catch(HL){HO.warn(HL);}}getItem(e){if(!zk())return null;try{let t=JSON.parse(localStorage.getItem(this.getRealKey(e)));return t&&t.expiresIn>=Date.now()?t.value:null;}catch(sN){HO.warn(sN);}}setItem(e,t){if(zk())try{let i={expiresIn:Date.now()+NN,value:t};this._queue.set(this.getRealKey(e),i);}catch(sD){HO.warn(sD);}}deleteItem(e){if(!zk())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0;}catch(sN){return HO.warn(sN),!1;}}clear(){if(zk())try{localStorage.clear();}catch(HL){HO.warn(HL);}}}(),WO={};ib(WO,{HTTPS_API:()=>dw,IS_GET_CAPABILITIES_SUPPORTED:()=>bw,IS_GET_SETTINGS_SUPPORTED:()=>Cw,IS_SEI_SUPPORTED:()=>kw,IS_SPC_SUPPORTED:()=>vw,basis:()=>Pw,checkSystemRequirementsInternal:()=>aw,decodeSupportStatus:()=>sw,encodeSupportStatus:()=>ow,getBrowserInfo:()=>ZO,getDisplayResolution:()=>hw,isAddTransceiverSupported:()=>Iw,isBrowserSupported:()=>$O,isGetReceiversSupported:()=>Tw,isGetSendersSupported:()=>Ew,isGetTransceiversSupported:()=>Sw,isGetUserMediaSupported:()=>pw,isMediaDevicesSupported:()=>tw,isMediaSessionSupported:()=>Ow,isMediaStreamTrackProcessorSupported:()=>rw,isReplaceTrackSupported:()=>Aw,isScreenCaptureApiAvailable:()=>lw,isSelectedCandidatePair:()=>uw,isSetParametersSupported:()=>Rw,isSmallStreamAPISupported:()=>mw,isSmallStreamSupported:()=>fw,isStopTransceiverSupported:()=>yw,isTRTCSupported:()=>cw,isUnifiedPlanDefault:()=>gw,isUsedInHttpProtocol:()=>nw,isWebAudioSupported:()=>_w,isWebCodecSupported:()=>Dw,isWebCodecsSupported:()=>ew,isWebRTCSupported:()=>Nw,isWebTransportSupported:()=>ww});var JO={AVOID_REPEATED_CALL:\"AVOID_REPEATED_CALL\",INVALID_PARAMETER_REQUIRED:\"INVALID_PARAMETER_REQUIRED\",INVALID_PARAMETER_TYPE:\"INVALID_PARAMETER_TYPE\",INVALID_PARAMETER_EMPTY:\"INVALID_PARAMETER_EMPTY\",INVALID_PARAMETER_INSTANCE:\"INVALID_PARAMETER_INSTANCE\",INVALID_PARAMETER_RANGE:\"INVALID_PARAMETER_RANGE\",INVALID_PARAMETER_MIN:\"INVALID_PARAMETER_MIN\",INVALID_PARAMETER_MAX:\"INVALID_PARAMETER_MAX\",INVALID_PARAMETER_STREAMTYPE:\"INVALID_PARAMETER_STREAMTYPE\",API_CALL_TIMEOUT:\"API_CALL_TIMEOUT\",SIGNAL_CHANNEL_RECONNECTION_FAILED:\"SIGNAL_CHANNEL_RECONNECTION_FAILED\",SIGNAL_CHANNEL_SETUP_FAILED:\"SIGNAL_CHANNEL_SETUP_FAILED\",ERROR_MESSAGE:\"ERROR_MESSAGE\",EXCHANGE_SDP_TIMEOUT:\"EXCHANGE_SDP_TIMEOUT\",DOWNLINK_RECONNECTION_FAILED:\"DOWNLINK_RECONNECTION_FAILED\",EXCHANGE_SDP_FAILED:\"EXCHANGE_SDP_FAILED\",UPDATE_OFFER_TIMEOUT:\"UPDATE_OFFER_TIMEOUT\",UPLINK_RECONNECTION_FAILED:\"UPLINK_RECONNECTION_FAILED\",INVALID_RECORDID:\"INVALID_RECORDID\",INVALID_PURE_AUDIO:\"INVALID_PURE_AUDIO\",INVALID_STREAMID:\"INVALID_STREAMID\",INVALID_USER_DEFINE_RECORDID:\"INVALID_USER_DEFINE_RECORDID\",INVALID_USER_DEFINE_PUSH_ARGS:\"INVALID_USER_DEFINE_PUSH_ARGS\",INVALID_PROXY:\"INVALID_PROXY\",INVALID_JOIN:\"INVALID_JOIN\",INVALID_ROOMID_STRING:\"INVALID_ROOMID_STRING\",INVALID_ROOMID_INTEGER:\"INVALID_ROOMID_INTEGER\",INVALID_SIGNAL_CHANNEL:\"INVALID_SIGNAL_CHANNEL\",JOIN_ROOM_TIMEOUT:\"JOIN_ROOM_TIMEOUT\",JOIN_ROOM_FAILED:\"JOIN_ROOM_FAILED\",REJOIN_ROOM_FAILED:\"REJOIN_ROOM_FAILED\",INVALID_DESTROY:\"INVALID_DESTROY\",INVALID_PUBLISH:\"INVALID_PUBLISH\",INVALID_UNPUBLISH:\"INVALID_UNPUBLISH\",INVALID_AUDIENCE:\"INVALID_AUDIENCE\",INVALID_INITIALIZE:\"INVALID_INITIALIZE\",INVALID_DUPLICATE_PUBLISHING:\"INVALID_DUPLICATE_PUBLISHING\",INVALID_SUBSCRIBE_UNDEFINED:\"INVALID_SUBSCRIBE_UNDEFINED\",INVALID_SUBSCRIBE_LOCAL:\"INVALID_SUBSCRIBE_LOCAL\",INVALID_REMOTE_STREAM:\"INVALID_REMOTE_STREAM\",SUBSCRIBE_FAILED:\"SUBSCRIBE_FAILED\",INVALID_ROLE:\"INVALID_ROLE\",INVALID_PARAMETER_SWITCH_ROLE:\"INVALID_PARAMETER_SWITCH_ROLE\",INVALID_OPERATION_SWITCH_ROLE:\"INVALID_OPERATION_SWITCH_ROLE\",SWITCH_ROLE_TIMEOUT:\"SWITCH_ROLE_TIMEOUT\",SWITCH_ROLE_FAILED:\"SWITCH_ROLE_FAILED\",CLIENT_BANNED:\"CLIENT_BANNED\",INVALID_OPERATION_START_PUBLISH_CDN:\"INVALID_OPERATION_START_PUBLISH_CDN\",INVALID_OPERATION_STOP_PUBLISH_CDN:\"INVALID_OPERATION_STOP_PUBLISH_CDN\",INVALID_STREAM_ID:\"INVALID_STREAM_ID\",START_PUBLISH_CDN_FAILED:\"START_PUBLISH_CDN_FAILED\",STOP_PUBLISH_CDN_FAILED:\"STOP_PUBLISH_CDN_FAILED\",START_MIX_TRANSCODE:\"START_MIX_TRANSCODE\",STOP_MIX_TRANSCODE:\"STOP_MIX_TRANSCODE\",INVALID_AUDIO_VOLUME:\"INVALID_AUDIO_VOLUME\",ENABLE_SMALL_STREAM_PUBLISHED:\"ENABLE_SMALL_STREAM_PUBLISHED\",DISABLE_SMALL_STREAM_PUBLISHED:\"DISABLE_SMALL_STREAM_PUBLISHED\",NOT_SUPPORTED_SMALL_STREAM:\"NOT_SUPPORTED_SMALL_STREAM\",INVALID_SMALL_STREAM_PROFILE:\"INVALID_SMALL_STREAM_PROFILE\",INVALID_PARAMETER_REMOTE_STREAM:\"INVALID_PARAMETER_REMOTE_STREAM\",INVALID_OPERATION_CHANGE_SMALL:\"INVALID_OPERATION_CHANGE_SMALL\",REMOTE_NOT_PUBLISH_SMALL_STREAM:\"REMOTE_NOT_PUBLISH_SMALL_STREAM\",INVALID_SWITCH_DEVICE:\"INVALID_SWITCH_DEVICE\",INVALID_SWITCH_DEVICE_PUBLISHING:\"INVALID_SWITCH_DEVICE_PUBLISHING\",INVALID_REPLACE_TRACK:\"INVALID_REPLACE_TRACK\",INVALID_INITIALIZE_LOCAL_STREAM:\"INVALID_INITIALIZE_LOCAL_STREAM\",INVALID_ADD_TRACK_REPETITIVE:\"INVALID_ADD_TRACK_REPETITIVE\",INVALID_ADD_TRACK_REMOVING:\"INVALID_ADD_TRACK_REMOVING\",INVALID_ADD_TRACK_PUBLISHING:\"INVALID_ADD_TRACK_PUBLISHING\",INVALID_STREAM_INITIALIZED:\"INVALID_STREAM_INITIALIZED\",INVALID_ADD_TRACK_NUMBER:\"INVALID_ADD_TRACK_NUMBER\",INVALID_REMOVE_AUDIO_TRACK:\"INVALID_REMOVE_AUDIO_TRACK\",INVALID_REMOVE_AUDIO_ADDING:\"INVALID_REMOVE_AUDIO_ADDING\",INVALID_REMOVE_AUDIO_ON:\"INVALID_REMOVE_AUDIO_ON\",INVALID_REMOVE_TRACK_PUBLISHING:\"INVALID_REMOVE_TRACK_PUBLISHING\",INVALID_REMOVE_TRACK_NOT_TRACK:\"INVALID_REMOVE_TRACK_NOT_TRACK\",INVALID_REMOVE_TRACK_NUMBER:\"INVALID_REMOVE_TRACK_NUMBER\",INVALID_REPLACE_TRACK_NO_TRACK:\"INVALID_REPLACE_TRACK_NO_TRACK\",REPEAT_JOIN:\"REPEAT_JOIN\",CLIENT_DESTROYED:\"CLIENT_DESTROYED\",NOT_BUG_PACKAGE:\"NOT_BUG_PACKAGE\",START_MIX_TRANSCODE_FAILED:\"START_MIX_TRANSCODE_FAILED\",STOP_MIX_TRANSCODE_FAILED:\"STOP_MIX_TRANSCODE_FAILED\",MIX_TRANSCODE_NOT_STARTED:\"MIX_TRANSCODE_NOT_STARTED\",CANNOT_LESS_THAN_ZERO:\"CANNOT_LESS_THAN_ZERO\",MIX_PARAMS_VIDEO_FRAMERATE:\"MIX_PARAMS_VIDEO_FRAMERATE\",MIX_PARAMS_VIDEO_GOP:\"MIX_PARAMS_VIDEO_GOP\",MIX_PARAMS_AUDIO_BITRATE:\"MIX_PARAMS_AUDIO_BITRATE\",MIX_PARAMS_USER_Z_ORDER:\"MIX_PARAMS_USER_Z_ORDER\",MIX_PARAMS_NOT_SELF:\"MIX_PARAMS_NOT_SELF\",MIX_PARAMS_USER_STREAM:\"MIX_PARAMS_USER_STREAM\",INVALID_PLAY:\"INVALID_PLAY\",INVALID_ELEMENT_ID:\"INVALID_ELEMENT_ID\",INVALID_ELEMENT_ID_TYPE:\"INVALID_ELEMENT_ID_TYPE\",PLAY_FAILED:\"PLAY_FAILED\",INVALID_USERID:\"INVALID_USERID\",INVALID_CREATE_STREAM_SOURCE:\"INVALID_CREATE_STREAM_SOURCE\",INVALID_CREATE_STREAM_SCREEN:\"INVALID_CREATE_STREAM_SCREEN\",INVALID_CREATE_STREAM_AUDIO:\"INVALID_CREATE_STREAM_AUDIO\",INVALID_CREATE_STREAM_SCREEN_AUDIO:\"INVALID_CREATE_STREAM_SCREEN_AUDIO\",NOT_SUPPORTED_HTTP:\"NOT_SUPPORTED_HTTP\",NOT_SUPPORTED_WEBRTC:\"NOT_SUPPORTED_WEBRTC\",NOT_SUPPORTED_PROFILE:\"NOT_SUPPORTED_PROFILE\",NOT_SUPPORTED_MEDIA:\"NOT_SUPPORTED_MEDIA\",NOT_SUPPORTED_H264ENCODE:\"NOT_SUPPORTED_H264ENCODE\",NOT_SUPPORTED_H264DECODE:\"NOT_SUPPORTED_H264DECODE\",NOT_SUPPORTED_TRACK:\"NOT_SUPPORTED_TRACK\",NOT_SUPPORTED_SWITCH_DEVICE:\"NOT_SUPPORTED_SWITCH_DEVICE\",NOT_SUPPORTED_CAPTURE:\"NOT_SUPPORTED_CAPTURE\",NOT_SUPPORTED_AUX:\"NOT_SUPPORTED_AUX\",MICROPHONE_NOT_FOUND:\"MICROPHONE_NOT_FOUND\",CAMERA_NOT_FOUND:\"CAMERA_NOT_FOUND\",SIGNAL_RESPONSE_FAILED:\"SIGNAL_RESPONSE_FAILED\",CATCH_HANDLER_ERROR:\"CATCH_HANDLER_ERROR\",API_NOT_EXIST:\"API_NOT_EXIST\",CONNECTION_CLOSED:\"CONNECTION_CLOSED\",SUBSCRIBE_ALL_FALSE:\"SUBSCRIBE_ALL_FALSE\",SEI_NOT_SUPPORT:\"SEI_NOT_SUPPORT\",SEI_DISABLED:\"SEI_DISABLED\",SEI_EMPTY:\"SEI_EMPTY\",SEI_OVERSIZE:\"SEI_OVERSIZE\",SEI_BEFORE_PUBLISH:\"SEI_BEFORE_PUBLISH\",SEI_NOT_VIDEO:\"SEI_NOT_VIDEO\",CALL_FREQUENCY_LIMIT:\"CALL_FREQUENCY_LIMIT\",CONNECTION_ABORTED:\"CONNECTION_ABORTED\",API_CALL_ABORTED:\"API_CALL_ABORTED\",DUPLICATE_AUX:\"DUPLICATE_AUX\"},KO={AVOID_REPEATED_CALL:e=>\"previous \".concat(e.name,\"() is ongoing, please avoid repeated calls.\"),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:n,value:r}=e;return\"'\".concat(t||i.name,\"' is a required param when calling \").concat(n,\"(), received: \").concat(r,\".\");},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:n,value:r}=e,o=\"\".concat(t||i.name),s=\"\";return s=Array.isArray(i.type)?i.type.join(\"|\"):i.type,\"'\".concat(o,\"' must be type of \").concat(s,\" when calling \").concat(n,\"(), received type: \").concat(tO(r),\".\");},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:n,value:r}=e;return\"'\".concat(t||i.name,\"' cannot be '\").concat(r,\"' when calling \").concat(n,\"().\");},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:n,value:r}=e,o=\"\".concat(t||i.name),s=\"\".concat(i.instanceOf.name||i.instanceOf);return\"'\".concat(o,\"' must be instanceof \").concat(s,\" when calling \").concat(n,\"(), received type: \").concat(tO(r),\".\");},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:n,value:r}=e;return\"'\".concat(t||i.name,\"' must be one of \").concat(i.values.join(\"|\"),\" when calling \").concat(n,\"(), received: \").concat(r,\".\");},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:n,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,fnName:n,value:r}=e;return\"the max value of \".concat(t||i.name,\" is \").concat(i.max,\", received: \").concat(r,\".\");},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:n}=e;return\"failed to subscribe \".concat(i,\" \").concat(n,\" 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\"),NOT_BUG_PACKAGE:\"You need to buy packages, refer to tencent console.\",START_MIX_TRANSCODE_FAILED:e=>\"startMixTranscode failed, errMsg: \".concat(e.message,\".\"),STOP_MIX_TRANSCODE_FAILED:e=>\"stopMixTranscode failed, errMsg: \".concat(e.message,\".\"),MIX_TRANSCODE_NOT_STARTED:\"mixTranscode has not been started.\",CANNOT_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:n,value:r}=e;return\"'\".concat(t||i.name,\"' cannot be less than 0 when calling \").concat(n,\"().\");},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:n}=e;return\"the element corresponding to '\".concat(t,\"' must be instanceof HTMLElement when calling \").concat(i,\"(), received: \").concat(n,\".\");},PLAY_FAILED:e=>\"\".concat(e.media,\" play failed,browser exception: \").concat(e.error.toString()),INVALID_USERID:\"userId cannot be all spaces.\",INVALID_CREATE_STREAM_SOURCE:\"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.\",INVALID_CREATE_STREAM_SCREEN:\"screen/video cannot be both true.\",INVALID_CREATE_STREAM_AUDIO:\"audio/screenAudio cannot be both true.\",INVALID_CREATE_STREAM_SCREEN_AUDIO:\"when screen is true, screenAudio can be configured.\",NOT_SUPPORTED_HTTP:\"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.\",NOT_SUPPORTED_WEBRTC:\"your browser or environment does not support full WebRTC capabilities.\",NOT_SUPPORTED_PROFILE:\"your browser does not support setVideoProfile.\",NOT_SUPPORTED_MEDIA:\"your browser or environment does not support navigator.mediaDevices.\",NOT_SUPPORTED_H264ENCODE:\"your device does not support H.264 encoding.\",NOT_SUPPORTED_H264DECODE:\"your device does not support H.264 decoding.\",NOT_SUPPORTED_TRACK:e=>\"\".concat(e,\"Track is not supported on your browser.\"),NOT_SUPPORTED_SWITCH_DEVICE:\"switchDevice is not supported on your browser.\",NOT_SUPPORTED_CAPTURE:\"Your browser or environment does not support screen sharing, please check whether the browser version.\",MICROPHONE_NOT_FOUND:\"no microphone detected, please check your microphone.\",CAMERA_NOT_FOUND:\"no camera detected, please check your camera.\",SIGNAL_RESPONSE_FAILED:e=>\"\".concat(e.signalResponse,\" failed, response code is \").concat(e.code,\" , errMsg: \").concat(e.message,\".\"),CATCH_HANDLER_ERROR(e){let{name:t,event:i}=e;return\"an error was caught 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\",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:n,maxSizeInSecond:r}=e;return\"api \".concat(i,\" call \").concat(t?\"size\":\"times\",\" is over \").concat(t?\"\".concat(r,\" bytes\"):n,\" 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,\"()\")},YO=(e,t)=>t?\"\".concat(TN,\"/\").concat(e,\"/\").concat(t):\"\".concat(TN,\"/\").concat(e,\"/index.html\"),zO=()=>{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(vN);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,n=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:n};}return{};};function qO(e){let{key:t,data:i,link:n,addDocLink:r=!0}=e,o=\"\",s=\"\",a=\"\";iO(KO[t])?o=KO[t](i):rO(KO[t])&&(o=KO[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=zO();n?a=\"\".concat(n.className,\".html#\").concat(n.fnName):l&&l[t]&&(iO(l[t])?a=l[t](i):rO(l[t])&&(a=l[t]));let d=o;return XD()&&(c&&c[t]&&(iO(c[t])?s=c[t](i):rO(c[t])&&(s=c[t])),s&&(d=r?\"\".concat(s,\"\\n请查看文档: \").concat(YO(\"zh-cn\",a),\"\\n\\n\"):\"\".concat(s,\"\\n\\n\"),d+=o)),r&&(d+=\" \\nRefer to: \".concat(YO(\"en\",a),\"\\n\")),d;}var QO={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},XO=new Map([[Ub,[\"Firefox\",Fb]],[Gb,[\"Edg\",Wb]],[Lk,[\"Chrome\",xk]],[Uk,[\"Safari\",Bk]],[Qb,[\"TBS\",Xb]],[Zb,[\"XWEB\",$b]],[nk&&Ob,[\"WeChat\",rk]],[ck,[\"QQ(Win)\",lk]],[sk,[\"QQ(Mobile)\",ak]],[ok,[\"QQ(Mobile X5)\",ak]],[dk,[\"QQ(Mac)\",uk]],[hk,[\"QQ(iPad)\",pk]],[Ik,[\"MI\",vk]],[yk,[\"HW\",Rk]],[Ck,[\"Samsung\",bk]],[kk,[\"OPPO\",Nk]],[Dk,[\"VIVO\",Ok]],[Hb,[\"EDGE\",jb]],[Kb,[\"SogouMobile\",Yb]],[zb,[\"Sogou\",qb]]]);function ZO(){let e=XO.get(!0);return{browserName:e?e[0]:\"unknown\",browserVersion:e?e[1]:\"unknown\"};}var $O=function(){return!(Ek||Hb||Gb&&Jb<80||Ub&&Bb<56);},ew=function(){return[\"VideoDecoder\",\"VideoEncoder\",\"AudioEncoder\",\"AudioDecoder\",\"MediaStreamTrackGenerator\"].every(e=>e in window);},tw=function(){if(!navigator.mediaDevices)return nw()||HO.error(KO.NOT_SUPPORTED_MEDIA),!1;let e=[\"getUserMedia\",\"enumerateDevices\"];return e.filter(e=>e in navigator.mediaDevices).length===e.length;},iw=!1;function nw(){return\"http:\"===location.protocol&&!Yk&&(iw||HO.error(qO({key:JO.NOT_SUPPORTED_HTTP})),iw=!0,!0);}var rw=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator);},ow=function(){return ab(this,null,function*(){if(QO.detail.isH264EncodeSupported||QO.detail.isVp8EncodeSupported)return{isH264EncodeSupported:QO.detail.isH264EncodeSupported,isVp8EncodeSupported:QO.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let n=new RTCPeerConnection(),r=document.createElement(LN.CANVAS);r.getContext(\"2d\");let o=r.captureStream(0);return n.addTrack(o.getVideoTracks()[0],o),e=yield n.createOffer(),-1!==e.sdp.toLowerCase().indexOf(\"h264\")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf(\"vp8\")&&(i=!0),n.close(),QO.detail.isH264EncodeSupported=t,QO.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:QO.detail.isH264EncodeSupported,isVp8EncodeSupported:QO.detail.isVp8EncodeSupported};}catch(sD){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1};}});},sw=function(){return ab(this,null,function*(){if(QO.detail.isH264DecodeSupported&&QO.detail.isVp8DecodeSupported)return{isH264DecodeSupported:QO.detail.isH264DecodeSupported,isVp8DecodeSupported:QO.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{let n=new RTCPeerConnection();return e=yield n.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf(\"h264\")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf(\"vp8\")&&(i=!0),n.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i};}catch(sD){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1};}});},aw=function(){return ab(this,null,function*(){if(QO.result)return QO;let e=$O(),t=Nw(),i=ew(),n=tw(),{isH264EncodeSupported:r,isVp8EncodeSupported:o}=yield ow(),{isH264DecodeSupported:s,isVp8DecodeSupported:a}=yield sw();return QO.result=e&&t&&n&&(r||o)&&(s||a),QO.detail.isBrowserSupported=e,QO.detail.isWebRTCSupported=t,QO.detail.isWebCodecsSupported=i,QO.detail.isMediaDevicesSupported=n,QO.detail.isScreenShareSupported=lw(),QO.detail.isSmallStreamSupported=fw(),QO.detail.isH264EncodeSupported=r,QO.detail.isVp8EncodeSupported=o,QO.detail.isH264DecodeSupported=s,QO.detail.isVp8DecodeSupported=a,QO.result||HO.error(\"\".concat(navigator.userAgent,\" \").concat(OO(QO.detail,!1))),QO;});},cw=function(){return QO.result;},lw=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia);},dw=(e,t,i)=>{\"http:\"===location.protocol&&!Yk&&(e[t]=()=>{throw new gb({code:mb.INVALID_OPERATION,message:KO.NOT_SUPPORTED_HTTP});});},uw=function(e){return!(\"candidate-pair\"!==e.type||!e.nominated||\"in-progress\"!==e.state&&\"succeeded\"!==e.state)&&!(sO(e.selected)&&!e.selected);};function hw(){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 pw(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia;}function _w(){let e={isSupported:!1},t=[\"AudioContext\",\"webkitAudioContext\",\"mozAudioContext\",\"msAudioContext\"];for(let i=0;i=86,Nw=function(){return[\"RTCPeerConnection\",\"webkitRTCPeerConnection\",\"RTCIceGatherer\"].filter(e=>e in window).length>0;};function Dw(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return nO(window.AudioDecoder)||(e.AudioDecoder=!0),nO(window.AudioEncoder)||(e.AudioEncoder=!0),nO(window.VideoDecoder)||(e.VideoDecoder=!0),nO(window.VideoEncoder)||(e.VideoEncoder=!0),nO(window.ImageDecoder)||(e.ImageDecoder=!0),e;}function Ow(){return\"mediaSession\"in navigator&&!nO(navigator.mediaSession.setActionHandler);}function ww(){return!nO(window.WebTransport);}function Pw(){let e={browser:\"\".concat(qk.name,\"/\").concat(qk.version),os:eN(),displayResolution:hw(),isScreenShareSupported:lw(),isWebRTCSupported:Nw(),isGetUserMediaSupported:pw(),isWebAudioSupported:_w(),isWebSocketsSupported:\"WebSocket\"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:Dw(),isMediaSessionSupported:Ow(),isWebTransportSupported:ww()};return navigator.userAgent.includes(\"miniProgram\")&&(e.browser=\"mini/\".concat(e.browser)),e;}var Lw=nb(cb(),1),Mw=Symbol(\"instance\"),Vw=Symbol(\"cacheResult\"),xw=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1;}abort(e){this.aborted=!0,jw.call(e,this.oldState,new Error(\"action '\".concat(this.action,\"' aborted\")));}toString(){return\"\".concat(this.action,\"ing\");}},Uw=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i;}};var Fw=new Map();function Bw(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(n,r,o)=>{let s=i.action||r;if(!i.context){let i=Fw.get(n)||[];Fw.has(n)||Fw.set(n,i),i.push({from:e,to:t,action:s});}let a=o.value;o.value=function(){let n=this;for(var r=arguments.length,o=new Array(r),c=0;c{var r;return n[Vw]=e,u.aborted||(jw.call(n,t),null===(r=i.success)||void 0===r||r.call(this,n[Vw])),e;},p=e=>{let t=e instanceof Error?e.message:String(e);if(jw.call(n,d,e),!i.fail){if(i.ignoreError)return e;throw e;}i.fail.call(this,new Uw(n._state,\"action '\".concat(s,\"' failed :\").concat(t),e instanceof Error?e:new Error(t)));};try{let e=a.apply(this,o);return function(e){return\"object\"==typeof e&&e&&\"then\"in e;}(e)?e.then(h).catch(p):h(e);}catch(_){p(_);}};};}var Hw=\"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 jw(e,t){let i=this._state;this._state=e;let n=e.toString();e&&this.emit(n,i),this.emit(Gw.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)});}var Gw=class extends Lw.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=Gw.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let n=i[Mw];n?this.name=n.name+\"-\"+n.count++:i[Mw]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram});}get stateDiagram(){let e=Object.getPrototypeOf(this),t=Fw.get(e)||[],i=new Set(),n=[],r=[],o=new Set(),s=Object.getPrototypeOf(e);Fw.has(s)&&(s.stateDiagram.forEach(e=>i.add(e)),s.allStates.forEach(e=>o.add(e))),t.forEach(e=>{let{from:t,to:i,action:o}=e;\"string\"==typeof t?n.push({from:t,to:i,action:o}):t.length?t.forEach(e=>{n.push({from:e,to:i,action:o});}):r.push({to:i,action:o});}),n.forEach(e=>{let{from:t,to:n,action:r}=e;o.add(t),o.add(n),o.add(r+\"ing\"),i.add(\"\".concat(t,\" --\\x3e \").concat(r,\"ing : \").concat(r)),i.add(\"\".concat(r,\"ing --\\x3e \").concat(n,\" : \").concat(r,\" 🟢\")),i.add(\"\".concat(r,\"ing --\\x3e \").concat(t,\" : \").concat(r,\" 🔴\"));}),r.forEach(e=>{let{to:t,action:n}=e;i.add(\"\".concat(n,\"ing --\\x3e \").concat(t,\" : \").concat(n,\" 🟢\")),o.forEach(e=>{e!==t&&i.add(\"\".concat(e,\" --\\x3e \").concat(n,\"ing : \").concat(n));});});let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a;}static get(e){let t;return\"string\"==typeof e?(t=Gw.instances.get(e),t||Gw.instances.set(e,t=new Gw(e,void 0,Object.create(Gw.prototype)))):(t=Gw.instances2.get(e),t||Gw.instances2.set(e,t=new Gw(e.constructor.name,void 0,Object.create(Gw.prototype)))),t;}static getState(e){var t;return null===(t=Gw.get(e))||void 0===t?void 0:t.state;}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Hw(Gw.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e));}get state(){return this._state;}set state(e){jw.call(this,e);}};Gw.STATECHANGED=\"stateChanged\",Gw.UPDATEAFSM=\"updateAFSM\",Gw.INIT=\"[*]\",Gw.ON=\"on\",Gw.OFF=\"off\",Gw.instances=new Map(),Gw.instances2=new WeakMap();var Ww=(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);},Jw=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e);},Kw=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),Yw=class{static generateTaskID(){return this.currentTaskID++;}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:MD,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=$C(e===LD?{delay:2e3,count:0,backgroundTask:!0}:e===wD?{delay:1e4,count:0}:e===PD?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),aO(t)&&(i=$C($C({},i),t)),iO(e)&&(t=e,e=MD);let n=$C({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i);return this.taskMap.set(n.taskID,n),this[e](n),n.taskID;}static interval(e){return e.intervalID=setInterval(()=>{e.callback(),e.loopCount+=1,this.isBreakLoop(e);},e.delay);}static intervalInWorker(e){e.delay=(1e3/e.fps).toFixed(2);let t=new Worker(URL.createObjectURL(new Blob([\"\\n let timerID = null;\\n self.onmessage = function (e) {\\n if (e.data === 'start') {\\n timerID = setInterval(() => {\\n self.postMessage('tick');\\n }, \".concat(e.delay,\");\\n } else if (e.data === 'stop') {\\n clearInterval(timerID);\\n }\\n };\\n \")])));t.onmessage=i=>{\"tick\"===i.data&&(e.callback(),e.loopCount+=1,this.isBreakLoop(e)&&t.postMessage(\"stop\"));},e.worker=t,t.postMessage(\"start\");}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=fO(),n=()=>{if(t=fO()-i,t>=e.delay&&(i=fO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=Ww(n,{timeout:e.delay});};return e.ricID=Ww(n,{timeout:e.delay});}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=fO(),n=()=>document.hidden&&e.backgroundTask?(t=fO()-i,i=fO(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(n,e.delay-Math.floor(t%e.delay))):(t=fO()-i,t>=e.delay&&(i=fO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),this.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(n));if(e.rafID=requestAnimationFrame(n),e.backgroundTask){let t=()=>{if(document.hidden){let t=fO()-i;t>=e.delay?n():e.timeoutID=setTimeout(n,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:n,ricID:r,onVisibilitychange:o,worker:s}=this.taskMap.get(e);return s&&s.terminate(),t&&clearInterval(t),i&&clearTimeout(i),n&&Kw(n),r&&Jw(r),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);}};Yw.taskMap=new Map(),Yw.currentTaskID=1;var zw=Yw;LN.SEI_MESSAGE;var qw={LOADED_DATA:LN.LOADEDDATA,MEDIA_TRACK_CHANGED:\"media-track-changed\",PLAYER_STATE_CHANGED:\"player-state-changed\"},Qw=new class{constructor(){ob(this,\"_roomIdMap\",new Map()),ob(this,\"_configs\"),\"undefined\"==typeof registerProcessor&&(this._configs={sdkAppId:\"\",userId:\"\",version:rN,env:AN.QCLOUD,browserVersion:qk.name+qk.version,ua:navigator.userAgent});}setConfig(e){let{sdkAppId:t,env:i,userId:n,roomId:r}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=n,this._roomIdMap.set(n,String(r));}logSuccessEvent(e){Yk||!HO.isAbleToUpload||this._configs.env===AN.QCLOUD&&this.uploadEventToKibana(eb($C({},e),{result:\"success\"}));}logFailedEvent(e){if(Yk||!HO.isAbleToUpload)return;let{eventType:t,code:i,error:n,userId:r}=e,o={roomId:this._roomIdMap.get(r||this._configs.userId),userId:r,eventType:t,result:\"failed\",code:i||(null==n?void 0:n.extraCode)||(null==n?void 0:n.code)||mb.UNKNOWN};this._configs.env===AN.QCLOUD&&this.uploadEventToKibana(eb($C({},o),{error:n}));}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:n}=e,r={timestamp:Sb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:rN,log:t};n&&(r.errorInfo=n.message),this.sendRequest(BD(this._configs.sdkAppId,yN.LOG),r);}sendRequest(e,t){HO.isAbleToUpload?PO({url:e,body:JSON.stringify(t)}).catch(()=>{}):setTimeout(()=>{this.sendRequest(e,t);},1e3);}}(),Xw=\"trtc_autoplay\",Zw=\"\".concat(Xw,\"_mask\"),$w=\"\".concat(Xw,\"_wrapper\"),eP=\"\".concat(Xw,\"_header\"),tP=\"\".concat(Xw,\"_content\"),iP=\"\".concat(Xw,\"_action_wrapper\"),nP=\"\".concat(Xw,\"_question\"),rP=\"\".concat(Xw,\"_collapse\"),oP=\"\".concat(Xw,\"_action_confirm\"),sP=\"\".concat(Xw,\"_detail\"),aP=\"#2473E8\",cP=\"dialog\",lP=\"\".concat(cP,\"-show\"),dP=\"\".concat(cP,\"-1\"),uP=\"\".concat(cP,\"-2\"),hP=!1,pP=()=>!!document.querySelector(\".\".concat($w)),_P=\"\".concat(TN,\"/\").concat(XD()?\"zh-cn\":\"en\",\"/tutorial-21-advanced-auto-play-policy.html\"),mP=\"
\").concat(XD()?\"其他方案?\":\"Any other solution?\",\"\"),fP=\"\".concat(XD()?\"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。\".concat(mP):\"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(mP)),gP=class{constructor(){if(ob(this,\"content\",\"音视频播放被浏览器拦截,请点击“恢复播放”。\"),ob(this,\"_dialogNode\",null),ob(this,\"_bodyPosition\",\"\"),ob(this,\"_showDetail\",!1),ob(this,\"_isCollapseClicked\",!1),ob(this,\"_isQuestionClicked\",!1),XD()||(this.content='Media playback failed. Click the \"Resume\" to resume playback.'),!hP){let e=document.createElement(\"style\");e.innerHTML=\".\".concat(Zw,\"{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(Zw,\" div:not(.\").concat(iP,\"){display:block !important;}.\").concat($w,\"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.\").concat($w,\" a{color:\").concat(aP,\";}.\").concat(eP,\"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.\").concat(tP,\"{margin:8px 0;}.\").concat(iP,\"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.\").concat(rP,\"{margin-right:auto;cursor:pointer}.\").concat(nP,\"{height:100%;line-height:16px;cursor:pointer;}.\").concat(oP,\"{margin-left:8px;color:#fff;background:\").concat(aP,\";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.\").concat(oP,\":hover{opacity:0.9;}.\").concat(rP,\",.\").concat(oP,\",.\").concat(tP,\",.\").concat(nP,\"{font-size:14px;}@media screen and (max-width:750px){.\").concat($w,\"{width:80vw;}}\"),document.head.appendChild(e),hP=!0;}this.addDiaLog();}createDiaLog(){let e=document.createElement(\"template\");e.innerHTML='
\").concat(location.host,\"
\").concat(this.content,\"
').concat(fP,\"
\").trim();let t=document.createElement(\"button\");t.className=oP,t.innerText=XD()?\"恢复播放\":\"Resume\",t.onclick=this.onConfirm.bind(this);let i=document.createElement(\"div\");i.className=nP,i.innerHTML='\\n \\n \\n \\n \\n \\n ',i.onclick=this.onQuestionClick.bind(this);let n=document.createElement(\"div\");n.className=rP,n.innerText=\"\".concat(XD()?\"详情 >\":\"Detail >\"),n.onclick=this.onCollapseClick.bind(this);let r=e.content.firstChild,o=r.querySelector(\".\".concat(iP));return o.appendChild(n),o.appendChild(i),o.appendChild(t),r;}addDiaLog(){pP()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(\".\".concat($w)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position=\"fixed\",HO.info(\"show autoplay dialog\"),Qw.uploadEvent({log:lP}));}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null);}onConfirm(){HO.warn(\"confirm clicked, try resume stream\"),xO.emit(FO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog();}onCollapseClick(){let e=this._dialogNode.querySelector(\".\".concat(sP));e.style.visibility=\"\".concat(this._showDetail?\"hidden\":\"visible\"),e.style.height=\"\".concat(this._showDetail?0:\"fit-content\"),this._showDetail=!this._showDetail,this._isCollapseClicked||Qw.uploadEvent({log:dP}),this._isCollapseClicked=!0;}onQuestionClick(){window.open(_P,\"_blank\"),this._isQuestionClicked||Qw.uploadEvent({log:uP}),this._isQuestionClicked=!0;}},TP={};ib(TP,{create:()=>SP,remove:()=>IP});var EP=new WeakMap();function SP(e,t){EP.has(e)||EP.set(e,[]);let i=EP.get(e),n={add:(e,r)=>(\"addEventListener\"in t?(i.push(t.removeEventListener.bind(t,e,r)),t.addEventListener(e,r)):(i.push(t.off.bind(t,e,r)),t.on(e,r)),n)};return n;}function IP(e){let t=EP.get(e);t&&(t.forEach(e=>e()),EP.delete(e));}var vP=class extends Gw{constructor(e,t){super(e.id,\"\".concat(t,\"-player\")),this.kind=t,ob(this,\"id\"),ob(this,\"element\",null),ob(this,\"container\",null),ob(this,\"mediaStream\",new MediaStream()),ob(this,\"track\"),ob(this,\"url\"),ob(this,\"attr\"),ob(this,\"muted\"),ob(this,\"_log\"),ob(this,\"_pausedRetryCount\"),ob(this,\"_isElementPlayingFired\",!1),ob(this,\"_interval\"),this.id=e.id,this._log=e.log,this.track=e.track,this.container=e.container,this.muted=e.muted,this._pausedRetryCount=AD,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(qw.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 ab(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(sN){let t=qO({key:JO.PLAY_FAILED,data:{media:this.kind,error:sN}});if(this.track&&!this.track.muted&&this._log.warn(sN),t.includes(\"NotAllowedError\"))throw new gb({code:mb.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(LN.ENDED),this._interval>0&&zw.clearTask(this._interval);}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause());}resume(){return this.isPlaying?Promise.resolve():Jk?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);return SP(this.element,this.element).add(LN.PLAYING,e).add(LN.ENDED,e).add(LN.PAUSE,e).add(LN.ERROR,e).add(LN.LOADEDDATA,e);}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==TP||TP.create(this.track,this.track).add(LN.ENDED,e).add(LN.MUTE,e).add(LN.UNMUTE,e),this.track.readyState===LN.ENDED&&this.handleTrackEvent({type:LN.ENDED}),this.track.muted&&this.handleTrackEvent({type:LN.MUTE});}}bindAutoPlayEvent(){xO.on(FO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this);}unbindTrackEvents(){this.track&&IP(this.track);}unbindEvents(){this.element&&IP(this.element),this.unbindTrackEvents(),xO.off(FO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this);}handleElementEvent(e){var t;switch(e.type){case LN.PLAYING:this._isElementPlayingFired=!0,this._log.info(\"\".concat(this.kind,\" player is playing\")),this.handlePlaying(LN.PLAYING),this._interval&&(zw.clearTask(this._interval),this._interval=-1);break;case LN.ENDED:this._log.info(\"\".concat(this.kind,\" player is ended\")),this.handleStopped(LN.ENDED);break;case LN.PAUSE:this._log.info(\"\".concat(this.kind,\" player is paused\")),this.handlePaused(LN.PAUSE);let e=this.container&&document.getElementById(this.container.id);e||this._log.warn(\"\".concat(this.kind,\" player has been remove, element ID: \").concat(null==(t=this.container)?void 0:t.id));let i=wk();this._pausedRetryCount>0&&(this.kind===LN.VIDEO&&!pP()||this.kind===LN.AUDIO&&(oO(i)&&i<=70||!e))&&(this._log.info(\"\".concat(this.kind,\" player auto resume when paused\")),this.resume(),this._pausedRetryCount--),Pb&&(this._interval=zw.run(MD,()=>{this.element&&\"PAUSED\"===this._state&&this.resume();},{delay:3e3}));break;case LN.ERROR:if(this.element&&this.element.error){let{code:e,message:t}=this.element.error;this._log.error(\"\".concat(this.kind,\" player error observed. code: \").concat(e,\" message: \").concat(t,\" userAgent: \").concat(navigator.userAgent)),Qw.uploadEvent({log:\"stat-\".concat(this.kind,\"-\").concat(cD.PLAYER_ERROR,\"-\").concat(e,\"-\").concat(navigator.userAgent),error:this.element.error});}break;case LN.LOADEDDATA:this.kind===LN.VIDEO&&this.emit(qw.LOADED_DATA);}}handleTrackEvent(e){switch(e.type){case LN.ENDED:this._log.info(\"\".concat(this.kind,\" track is ended\")),this.handleStopped(LN.ENDED);break;case LN.MUTE:this._log.info(\"\".concat(this.kind,\" track is unable to provide media output\")),this.handlePaused(LN.MUTE);break;case LN.UNMUTE:this._log.info(\"\".concat(this.kind,\" track is able to provide media output\")),this._isElementPlayingFired&&this.handlePlaying(LN.UNMUTE);}}handlePlaying(e){this.emit(qw.PLAYER_STATE_CHANGED,{type:this.kind,state:\"PLAYING\",reason:e});}handlePaused(e){this.emit(qw.PLAYER_STATE_CHANGED,{type:this.kind,state:\"PAUSED\",reason:e});}handleStopped(e){this.emit(qw.PLAYER_STATE_CHANGED,{type:this.kind,state:\"STOPPED\",reason:e});}getElement(){return this.element;}};rb([Bw([],\"PLAYING\")],vP.prototype,\"handlePlaying\",1),rb([Bw(\"PLAYING\",\"PAUSED\",{ignoreError:!0})],vP.prototype,\"handlePaused\",1),rb([Bw([],\"STOPPED\")],vP.prototype,\"handleStopped\",1);var yP=class extends vP{constructor(e){super(e,LN.VIDEO),ob(this,\"mirror\"),ob(this,\"objectFit\"),nO(e.mirror)||(this.mirror=e.mirror),nO(e.objectFit)||(this.objectFit=e.objectFit);}initializeElement(){var e;let t=document.createElement(LN.VIDEO);if(this.track){let e=new MediaStream();e.addTrack(this.track),t.srcObject=e;}t.muted=!0;let i=\"width: 100%; height: 100%; object-fit: \".concat(this.objectFit,\";background-color: black;\");this.mirror&&(i+=\"transform: scaleX(-1);\"),t.setAttribute(\"id\",\"video_\".concat(this.id)),t.setAttribute(\"style\",i),t.setAttribute(\"autoplay\",\"autoplay\"),t.setAttribute(\"playsinline\",\"playsinline\"),null==(e=this.container)||e.appendChild(t),this.element=t,this.bindElementEvents();}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(LN.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(LN.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent);}handleElementEvent(e){super.handleElementEvent(e);let t=e.type;if(this.mirror&&this.element){let e=this.element.style.transform;t===LN.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace(\"scaleX(-1)\",\"\"):t===LN.LEAVE_PICTURE_IN_PICTURE&&!e.includes(\"scaleX\")&&(this.element.style.transform=\"\".concat(e,\" scaleX(-1)\"));}}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;}},AP=!1,RP=class{constructor(e){ob(this,\"context_\"),ob(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=!1,this.port.onmessage=t=>{let{data:e}=t;switch(e.name){case\"setIntervalTime\":this.intervalTime=e.intervalTime;break;case\"stop\":this.isStop=!0}}}process(t){let e=t[0];if(this.isStop)return!1;if(e.length>0){let i=e[0],s=0;for(let l=0;l{let i=new window.AudioContext(t),n=++kP,r=()=>{\"suspended\"===i.state?(i.resume(),document.addEventListener(\"click\",r)):\"interrupted\"===i.state?i.resume():document.removeEventListener(\"click\",r);};return document.addEventListener(\"click\",r),i.onstatechange=()=>{HO.info(\"\".concat(e,\"-\").concat(n,\" context state: \").concat(i.state)),r();},i;},DP=0,OP=class{constructor(e){ob(this,\"_volume\"),ob(this,\"_log\"),ob(this,\"_track\"),ob(this,\"_stream\"),ob(this,\"_audioCtx\"),ob(this,\"_destination\"),ob(this,\"_streamSource\"),ob(this,\"_scriptProcessorNode\"),ob(this,\"_audioWorkletNode\"),ob(this,\"_interval\");let{track:t,log:i}=e;this._volume=0,this._log=i,this._track=t,CP||(CP=NP(\"volume-meter\")),this._audioCtx=CP,this._destination=this._audioCtx.destination;let n=new MediaStream();n.addTrack(this._track),this._streamSource=this._audioCtx.createMediaStreamSource(n),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._interval=200,xO.on(FO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),_O?(xO.on(FO.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),xO.on(FO.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),this.preload()):this.initScriptProcessor(),DP+=1;}preload(){bP?bP.initWorkletSuccess&&this.initAudioWorklet():bP=new RP({context:CP});}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(HL){Qw.logFailedEvent({userId:this._log.userId,eventType:cD.LOAD_WORKLET,error:HL}),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 n=0;n0&&(DP-=1),0===DP&&(null==CP||CP.close(),CP=null,bP=null);}resume(){null==CP||CP.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});}},wP=null,PP=0,LP=class extends vP{constructor(e){super(e,LN.AUDIO),ob(this,\"_volumeMeter\"),ob(this,\"_gainedTrack\",null),ob(this,\"_gainNode\",null),ob(this,\"_destination\",null),ob(this,\"_mediaStreamSource\",null),ob(this,\"_sourceElement\",null),ob(this,\"_outputDeviceId\"),ob(this,\"_volume\",1),ob(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 OP({track:this._gainedTrack||e,log:this._log});}initializeElement(){if((\"15.2\"===jk||\"15.3\"===jk||\"15.4\"===jk)&&this.muted)return void this._log.info(\"audioElement is muted.\");let e=document.createElement(LN.AUDIO);this.track&&(e.srcObject=new MediaStream([this._gainedTrack||this.track])),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 ab(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 sb(LP.prototype,this,\"play\").call(this);});}stop(){this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),this.destroyGain(),super.stop();}resume(){return ab(this,null,function*(){yield sb(LP.prototype,this,\"resume\").call(this),this._volumeMeter&&this._volumeMeter.resume();});}setSinkId(e){return ab(this,null,function*(){this._outputDeviceId!==e&&(this.element&&(yield this.element.setSinkId(e)),this._outputDeviceId=e);});}setVolume(e){this._volume=e,this._gainNode?this._gainNode.gain.value=e:e>1?this.createGain(e):this.element&&(this.element.volume=e);}createGain(e){wP||(wP=NP(\"player\")),this._log.info(\"create gainNode \".concat(e));let t=wP.createMediaStreamSource(new MediaStream([this.track])),i=wP.createGain(),n=wP.createMediaStreamDestination();t.connect(i),i.connect(n),i.gain.value=e,this._gainNode=i,this._destination=n,this._mediaStreamSource=t,this._gainedTrack=n.stream.getAudioTracks()[0],PP+=1,this.element&&(IP(this.element),this._sourceElement=this.element,this.element.muted=!0,this.element=null),this.play();}destroyGain(){var e,t,i;!this._gainNode||(this._log.info(\"destroy gainNode\"),null==(e=this._gainNode)||e.disconnect(),null==(t=this._destination)||t.disconnect(),null==(i=this._mediaStreamSource)||i.disconnect(),this._gainNode=null,this._destination=null,this._mediaStreamSource=null,this._sourceElement&&(this._sourceElement.srcObject=null,this._sourceElement=null),this._gainedTrack=null,0===(PP-=1)&&wP&&(this._log.info(\"destroy gain audioContext\"),wP.close(),wP=null));}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();}},MP=class extends Gw{constructor(e){let{userId:t,sdkAppId:i,mediaType:n,room:r,isInitPlayer:o=!0}=e;var s;super(),ob(this,\"id\",jO()),ob(this,\"userId\"),ob(this,\"isRemote\"),ob(this,\"mediaType\"),ob(this,\"room\"),ob(this,\"user\"),ob(this,\"_log\"),ob(this,\"_inputTrack\"),ob(this,\"_outputTrack\"),ob(this,\"isPlayCalled\"),ob(this,\"container\",null),ob(this,\"player\"),ob(this,\"subVideoPlayerMap\"),ob(this,\"playerMuted\",!1),ob(this,\"abortCtrl\"),ob(this,\"audioOutputDeviceId\"),ob(this,\"audioVolume\"),ob(this,\"objectFit\",\"cover\"),ob(this,\"mirror\",!1),ob(this,\"gain\"),ob(this,\"isScreen\",!1),ob(this,\"manager\"),nO(t)||(this.userId=t),this.mediaType=n,this._log=HO.createLogger({id:\"\".concat(this.kind[0],\"t\"),userId:null==(s=r||this.room)?void 0:s.userId,remoteUserId:this instanceof nL?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?\"auxiliary\":\"main\",isLocal:this instanceof nL}),o&&this.initPlayer();}get log(){return this._log||HO;}get kind(){return 1===this.mediaType?LN.AUDIO:LN.VIDEO;}get muted(){return!(!this.outMediaTrack||this.outMediaTrack.enabled);}get strMediaType(){return 4===this.mediaType?LN.VIDEO:2===this.mediaType?LN.SCREEN:LN.AUDIO;}play(e,t){return ab(this,null,function*(){let i=cO(e)?e[0]:e;if(this.isPlayCalled)return this.log.info(\"play update options: \".concat(JSON.stringify(t))),t&&!nO(t.muted)&&this.setPlayerMute(t.muted),t&&!nO(t.objectFit)&&(this.objectFit=t.objectFit),this.isScreen?this.mirror=!1:t&&!nO(t.mirror)&&(this.mirror=t.mirror),void(this.kind===LN.VIDEO&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),cO(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!nO(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===LN.VIDEO)&&this.setPlayerMute(!0),t&&!nO(t.objectFit)&&(this.objectFit=t.objectFit),this.isRemote||(this.mirror=!0),this.isScreen?this.mirror=!1:t&&!nO(t.mirror)&&(this.mirror=t.mirror),this.kind===LN.VIDEO&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror)),this.isPlayCalled=!0,i&&(this.container=i,this.player.setContainer(i)),xO.emit(FO.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info(\"play with options: \".concat(JSON.stringify(t)));try{this.player.setTrack(this._outputTrack),yield this.player.play(),cO(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t));}catch(n){throw this.handleAutoPlayFailed(),this.emit(\"error\",n),n;}}else this.log.info(\"play has not mediaTrack, abort\");});}playSubContainer(e,t){return ab(this,null,function*(){if(!this._outputTrack||this.kind===LN.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map()),this.subVideoPlayerMap.forEach((t,i)=>{var n;e.find(e=>i===e)||(t.stop(),t.setContainer(null),null==(n=this.subVideoPlayerMap)||n.delete(i));});for(let[n,r]of e.entries()){let e=this.subVideoPlayerMap.get(r);e?t&&(nO(t.mirror)||e.setMirror(t.mirror),nO(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(r,new yP({id:this.userId||this.id,track:this.outMediaTrack,container:r,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log.createChild({id:\"vp-sub\".concat(n+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===LN.AUDIO?this.player=new LP({id:this.userId||this.id,track:this.outMediaTrack,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 yP({id:this.userId||this.id,track:this.outMediaTrack,container:this.container||null,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log}),this.player.on(qw.LOADED_DATA,()=>{xO.emit(FO.VIDEO_LOADED_DATA,{track:this});}),this.player.on(qw.MEDIA_TRACK_CHANGED,e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach(t=>t.setTrack(e));})),this.player.on(qw.PLAYER_STATE_CHANGED,e=>{xO.emit(FO.PLAYER_STATE_CHANGED,$C({track:this},e)),this.emit(\"player-state-changed\",e);});}setAudioOutput(e){return ab(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 ab(this,null,function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume());});}close(){this.log.info(\"close\"),this.isPlayCalled&&this.stop();}setMute(e){return!!this.outMediaTrack&&(this.outMediaTrack.enabled=!e,this.emit(e?\"mute\":\"unmute\",this),xO.emit(e?FO.TRACK_MUTED:FO.TRACK_UNMUTED,{track:this}),!0);}setPlayerMute(e){this.playerMuted=e,this.player.setMuted(e);}get mediaTrack(){return this._inputTrack||null;}get outMediaTrack(){return this._outputTrack||null;}setInputMediaStreamTrack(e){let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.emit(\"input-media-track-changed\",e||null,t||null),this.manager?this.manager.changeInput(this,t):this.setOutputMediaStreamTrack(e);}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug(\"setOutputMediaStreamTrack\",e.label):this.log.info(\"setOutputMediaStreamTrack\",(null==(t=e.getSettings)?void 0:t.call(e).deviceId)||e.label),this._outputTrack=e,e.enabled=!this.muted,this.updatePlayingState(!!e));}setMediaType(e){this.mediaType=e;}updatePlayingState(e){if(this.isPlayCalled)if(e){if(this.player.setTrack(this.outMediaTrack),this.player.isStopped)return this.player.play().catch(()=>this.handleAutoPlayFailed()),void this.log.info(\"playing state updated, play \".concat(this.kind));}else if(!this.player.isStopped)return this.player.stop(),void this.log.info(\"playing state updated, stop \".concat(this.kind));this.log.debug(\"updatePlayingState abort \".concat(this.isPlayCalled,\" \").concat(e,\" \").concat(this.player.isStopped));}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new gP();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);}}};rb([Bw([],Gw.INIT)],MP.prototype,\"close\",1);var VP=Object.prototype.hasOwnProperty;var xP=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(ZD(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(VP.call(e,t))return!1;return!0;}return!1;},UP=nb(cb(),1),FP=e=>t=>t.deviceId===e,BP=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"Input\";ob(this,\"kind\"),ob(this,\"type\"),ob(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(FP(e.deviceId))){let i=\"\".concat(this.kind).concat(this.type,\"Added\");HO.warn(\"\".concat(i,\": \").concat(JSON.stringify(e))),t.emit(i,e);}}),this.devices.forEach(e=>{if(e.deviceId&&!i.find(FP(e.deviceId))){let i=\"\".concat(this.kind).concat(this.type,\"Removed\");HO.warn(\"\".concat(i,\": \").concat(JSON.stringify(e))),t.emit(i,e);}})),this.devices=i;}hasDevice(e){return!!this.devices.find(t=>t.deviceId===e);}},HP=class extends UP.EventEmitter{constructor(){super(),ob(this,\"audioInputs\",new BP(LN.AUDIO)),ob(this,\"videoInputs\",new BP(LN.VIDEO)),ob(this,\"audioOutputs\",new BP(LN.AUDIO,\"Output\")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener(\"devicechange\",this.update.bind(this)),\"ondevicechange\"in navigator.mediaDevices||zw.run(LD,()=>{this.update();},{delay:1e4}));}init(){GP().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e);});}update(){return ab(this,null,function*(){let e=yield GP();return this.audioInputs.update(e,this),this.videoInputs.update(e,this),this.audioOutputs.update(e,this),this;});}},jP=dN||lN?null:new HP();function GP(){return ab(this,null,function*(){return nw()||!tw()?[]:(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&&YP.add(\"\".concat(e.deviceId,\"_\").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i;});});}function WP(){return jP.update().then(e=>e.audioInputs.devices);}function JP(){return jP.update().then(e=>e.videoInputs.devices);}function KP(){return ab(this,null,function*(){return jP.update().then(e=>e.audioOutputs.devices);});}var YP=new Set();function zP(e,t){return ab(this,null,function*(){let i=(yield WP()).find(e=>e.deviceId===RD);return(null==i?void 0:i.groupId)===e&&i.label===t;});}var qP=MO({retryFunction:function(e){return ab(this,null,function*(){let t=function(e){return{audio:XP(e),video:ZP(e)};}(e);HO.info(\"getUserMedia with constraints: \".concat(JSON.stringify(t)));let i=[],n=[],r=[\"label\",\"deviceId\"];t.audio&&(i=yield WP(),HO.info(\"microphones: \".concat(DO(i,{keysToInclude:r})))),t.video&&(n=yield JP(),HO.info(\"cameras: \".concat(DO(n,{keysToInclude:r}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return bw&&e.getTracks().forEach(e=>{HO.info(\"\".concat(e.kind,\" capabilities: \").concat(DO(e.getCapabilities(),{keysToInclude:VD})));}),e;}catch(o){if(\"NotFoundError\"===o.name){if(e.video&&n&&0===n.length)throw new gb({code:mb.DEVICE_NOT_FOUND,message:qO({key:JO.CAMERA_NOT_FOUND})});if(e.audio&&i&&0===i.length)throw new gb({code:mb.DEVICE_NOT_FOUND,message:qO({key:JO.MICROPHONE_NOT_FOUND})});}throw new gb({code:mb.INITIALIZE_FAILED,name:o.name,message:o.message,constraint:o.constraint});}});},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:n,retryFuncArgs:r,retryCount:o}=e;\"NotReadableError\"===t.name?(r[0].video&&(r[0].maxResolution=!1,r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)),2===o&&(r[0].useTrueAsConstraint=!0),i()):n(t),r[0].microphoneId&&QP(r[0].microphoneId,!1),r[0].cameraId&&QP(r[0].cameraId,!0);},onRetrying:e=>{HO.warn(\"getUserMedia NotReadableError observed, retrying [\".concat(e,\"/3]\"));},onRetryFailed:e=>{Qw.logFailedEvent({eventType:cD.GET_USER_MEDIA_RETRY,error:e});},onRetrySuccess:e=>{Qw.logSuccessEvent({eventType:cD.GET_USER_MEDIA_RETRY}),Qw.uploadEvent({log:\"stat-\".concat(cD.GET_USER_MEDIA_RETRY,\"-success-\").concat(e)});}});function QP(e,t){return ab(this,null,function*(){let i=(t?yield JP():yield WP()).find(t=>t.deviceId===e);i&&iO(i.getCapabilities)&&HO.warn(DO(i.getCapabilities(),{keysToInclude:VD}));});}function XP(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};return xP(e.microphoneId)||(t.deviceId=e.useExact?{exact:e.microphoneId}:e.microphoneId),oO(e.channelCount)&&e.channelCount>1&&(t.channelCount=e.channelCount),sO(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),sO(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),sO(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!xP(t)||t;}function ZP(e){if(!e.video)return!1;if(e.useTrueAsConstraint)return!0;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&&!Ub&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!Ub&&(i.height.max=e.height)),Ub&&mk&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!xP(i)||i;}var $P=qP;function eL(e){return iL((t,i)=>function(){for(var i=arguments.length,n=new Array(i),r=0;rfunction(){for(var i=arguments.length,n=new Array(i),r=0;r1&&void 0!==arguments[1])||arguments[1]}),ob(this,\"isRemote\",!1),ob(this,\"deviceId\"),ob(this,\"groupId\",\"\"),ob(this,\"label\",\"\"),ob(this,\"_isRecapturing\",!1),ob(this,\"_lastRecaptureTime\",0),ob(this,\"_onMuteTimeoutId\",-1),ob(this,\"profile\"),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this);}installTrackEvent(e){SP(e,e).add(LN.MUTE,this.onTrackMuted).add(LN.UNMUTE,this.onTrackUnmuted).add(LN.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===LN.ENDED&&this.onTrackEnded();}uninstallTrackEvent(e){IP(e);}setStateToCapture(){}capture(e){return ab(this,null,function*(){try{let t;xO.emit(FO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(t=new MediaStream(),t.addTrack(e.customSource)):t=yield $P(e);let i=t.getTracks()[0];return yield this.setInputMediaStreamTrack(i),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),xO.emit(FO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this}),t;}catch(sD){throw xO.emit(FO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:sD}),this.log.error(\"getUserMedia error observed \".concat(sD)),sD;}});}setInputMediaStreamTrack(e){this.state===Gw.INIT&&this.setStateToCapture(),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack);let t=super.setInputMediaStreamTrack(e);return this.installTrackEvent(e),t;}publish(e,t){return this.room=e,this.emit(\"4\",{mediaType:this.strMediaType,state:\"starting\",prevState:\"stopped\"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),xO.emit(FO.LOCAL_TRACK_PUBLISHED,{track:this}),t;}unpublish(){this.room&&this.room.localTracks.delete(this),xO.emit(FO.LOCAL_TRACK_UNPUBLISHED,{track:this});}updateDeviceIdInUse(){return ab(this,null,function*(){if(this.mediaTrack&&Cw){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return ab(this,arguments,function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:n,oldLabel:r,kind:o}=e;return function*(){return t===i&&(o!==LN.AUDIO||t!==RD||(yield zP(n,r)));}();});}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=i,t&&(this.groupId=t),GP().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===LN.AUDIO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes(\"mic\")||t.includes(\"麦克风\"))return!0;let i=\"\".concat(((null==e?void 0:e.getSettings())||{}).deviceId,\"_\").concat(LN.AUDIO_INPUT);return!!YP.has(i);}(this.mediaTrack)||this.kind===LN.VIDEO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes(\"camera\")||t.includes(\"webcam\"))return!0;let i=\"\".concat(((null==e?void 0:e.getSettings())||{}).deviceId,\"_\").concat(LN.VIDEO_INPUT);return!!YP.has(i);}(this.mediaTrack)||this._isRecapturing||e&&mk&&Uk);}onTrackMuted(){if(this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTimethis.onTrackMuted(),OD);this._onMuteTimeoutId=setTimeout(()=>ab(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 ab(this,null,function*(){if(this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTimethis.onTrackEnded(),OD);this.recapture(yield this.getRecoverCaptureDeviceId());}});}recapture(e){return ab(this,null,function*(){var t;if(this._isRecapturing||!this._inputTrack)return;let i;return this.log.warn(\"recapture trying\"),null==(t=this._inputTrack)||t.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now(),(\"audio\"===this.kind?yield WP():yield JP()).find(t=>t.deviceId===e)&&(i=e),this.capture({deviceId:i,useExact:!0}).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 ab(this,null,function*(){let{deviceId:e}=this;if(e){let t=(rL.get(e)||0)+1;if(rL.set(e,t),t>=3){let i=\"video\"===this.kind?(yield JP()).find(e=>!rL.has(e.deviceId)):(yield WP()).find(e=>!rL.has(e.deviceId));i&&(this.log.warn(\"\".concat(e,\" capture fail \").concat(t,\" times, change new \").concat(i.deviceId)),e=i.deviceId);}}return e;});}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),null==(e=this.manager)||e.removeInput(this);}};rb([Bw(Gw.INIT,\"capture\",{ignoreError:!0})],nL.prototype,\"setStateToCapture\",1),rb([Bw(\"capture\",\"publish\",{ignoreError:!0,success(){this.room.localTracks.add(this),this.emit(\"4\",{mediaType:this.strMediaType,state:\"started\",prevState:\"starting\"});},fail(e){let t=\"error\",i=e.cause;i.message.includes(\"timeout\")?t=\"timeout\":i.code===mb.API_CALL_ABORTED&&(t=\"api-call\"),this.emit(\"4\",{mediaType:this.strMediaType,state:\"stopped\",prevState:\"starting\",reason:t,error:i});}})],nL.prototype,\"publish\",1),rb([iL(e=>function(){return ab(this,null,function*(){let t=\"publish\"===this.state?\"started\":\"starting\";e.call(this),this.emit(\"4\",{mediaType:this.strMediaType,state:\"stopped\",prevState:t,reason:\"api-call\"}),2===this.mediaType&&(this.mediaType=4);});}),Bw([],\"capture\")],nL.prototype,\"unpublish\",1);var rL=new Map();xO.on(FO.SWITCH_DEVICE_SUCCESS,e=>{e.track.deviceId&&rL.delete(e.track.deviceId);});var oL=class extends nL{constructor(e){super(1),ob(this,\"mediaType\",1),ob(this,\"volume\",0),ob(this,\"captureVolume\",1),ob(this,\"profile\",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),ob(this,\"playerMuted\",!0),this.manager=e;}getAudioLevel(){return this.volume||super.getAudioLevel();}capture(){let{deviceId:e,customSource:t,useExact:i=!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:i,customSource:t});}switchDevice(e){return ab(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==RD)return;if(yield zP(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)),xO.emit(FO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info(\"switch microphone success\");}catch(sD){throw this.log.error(\"switch microphone failed \".concat(sD)),this.deviceId&&this.recapture(this.deviceId),sD;}}});}listenDeviceChange(){jP&&!jP.listeners(\"audioInputRemoved\").includes(this.handleMicrophoneRemoved)&&jP.on(\"audioInputRemoved\",this.handleMicrophoneRemoved,this);}handleMicrophoneRemoved(e){return ab(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(\"current microphone is lost: \".concat(JSON.stringify(e)));let t=yield WP();t[0]?this.recapture(t[0].deviceId):jP.on(\"audioInputAdded\",this.handleMicrophoneAdded,this);}});}handleMicrophoneAdded(e){this.log.warn(\"microphone added: \".concat(JSON.stringify(e))),this.recapture(e.deviceId);}update3A(e){return ab(this,arguments,function(e){var t=this;let{echoCancellation:i,noiseSuppression:n,autoGainControl:r}=e;return function*(){let e=!1;!nO(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!nO(n)&&n!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=n,e=!0),!nO(r)&&r!==t.profile.autoGainControl&&(t.profile.autoGainControl=r,e=!0),e&&t.deviceId&&(yield t.recapture(t.deviceId));}();});}setCaptureVolume(e){var t;let i=e/100;i!==this.captureVolume&&(null==(t=this.manager)||t.setCaptureVolume(i),this.captureVolume=i);}close(){jP.off(\"audioInputAdded\",this.handleMicrophoneAdded,this),jP.off(\"audioInputRemoved\",this.handleMicrophoneRemoved,this),super.close();}},sL=class extends nL{constructor(e){super(4),ob(this,\"mediaType\",4),ob(this,\"profile\",{width:640,height:480,frameRate:15,bitrate:500}),ob(this,\"states\",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0}),ob(this,\"small\"),ob(this,\"facingMode\"),ob(this,\"isNeedToSetBandwidth\"),this.manager=e;let t=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&\"publish\"===this.state&&this.room.sendAbilityStatus({\"2k4k\":1}):(this.log.warn(\"Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386\"),this.setProfile(eb($C({},this.profile),{width:1920,height:1080})),this.applyProfile());};this.on(\"input-media-track-changed\",t),this.on(\"publish\",t);}capture(){let{deviceId:e,facingMode:t,useExact:i=!1,customSource:n}=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:n});}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),null==(t=this.room)?void 0:t.replaceTrack(this);}setProfile(e){!e||(e.bitrate&&(this.isNeedToSetBandwidth=e.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(e):(this.log.warn(\"Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386\"),super.setProfile(eb($C({},this.profile),{width:1920,height:1080}))));}applyProfile(){var e;if(!this.mediaTrack)return;let t=this.settings;return t.height!==this.profile.height||t.width!==this.profile.width||t.frameRate!==this.profile.frameRate?null==(e=this.mediaTrack)?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then(()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&\"publish\"===this.state&&this.room.sendAbilityStatus({\"2k4k\":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:LN.VIDEO,videoType:LN.BIG});}):void 0;}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return Cw&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e;}isAllowed2k4k(e){var t;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||1===(null==(t=this.room.scheduleResult.trtcAutoConf)?void 0:t[\"2k4k\"]);}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e);}switchDevice(e){return ab(this,null,function*(){let t=e;try{if(!this.isNeedToSwitchDevice(t))return;(t===LN.FACING_MODE_USER||t===LN.FACING_MODE_ENVIRONMENT)&&(this.facingMode=e,t=void 0),this.mediaTrack.stop(),yield this.capture({deviceId:t,useExact:!0}),xO.emit(FO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info(\"switch camera success\");}catch(aN){throw this.log.error(\"switch camera failed \".concat(aN)),this.deviceId&&this.recapture(this.deviceId),aN;}});}listenDeviceChange(){jP&&!jP.listeners(\"audioInputRemoved\").includes(this.handleCameraRemoved)&&jP.on(\"videoInputRemoved\",this.handleCameraRemoved,this);}handleCameraRemoved(e){return ab(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(\"current camera is lost: \".concat(JSON.stringify(e)));let t=yield JP();t[0]?this.recapture(t[0].deviceId):jP.on(\"videoInputAdded\",this.handleCameraAdded,this);}});}handleCameraAdded(e){return ab(this,null,function*(){this.log.warn(\"camera added: \".concat(JSON.stringify(e))),this.recapture(e.deviceId);});}close(){jP.off(\"videoInputAdded\",this.handleCameraAdded,this),jP.off(\"videoInputRemoved\",this.handleCameraRemoved,this),super.close();}};var aL=function(e){return ab(this,null,function*(){let t=null,i=function(e){let t={systemAudio:\"include\",selfBrowserSurface:\"include\",surfaceSwitching:\"include\"},i={width:Uk?{max:e.width}:{ideal:e.width,max:e.width},height:Uk?{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:n=!1,autoGainControl:r=!1}=e;t.audio={echoCancellation:i,noiseSuppression:n,autoGainControl:r,sampleRate:48e3};}return t;}(e);HO.info(\"getDisplayMedia with constraints: \".concat(JSON.stringify(i)));let n=yield navigator.mediaDevices.getDisplayMedia(i);if(e.systemAudio&&0===n.getAudioTracks().length&&(Lk&&Vk<74||Uk||Ub)&&HO.warn(\"Your browser not support capture system audio\"),e.frameRate&&n.getVideoTracks()[0]&&n.getVideoTracks()[0].applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height}).catch(e=>{HO.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 nO(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1};}(e);HO.info(\"getUserMedia with constraints: \".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),n.addTrack(t.getAudioTracks()[0]);}return n;});},cL=class extends sL{constructor(e){super(e),ob(this,\"profile\",{width:1920,height:1080,frameRate:5,bitrate:1600}),ob(this,\"objectFit\",\"contain\"),ob(this,\"isScreen\",!0),this._log.id=\"s-\".concat(this._log.id);}capture(){return ab(this,arguments,function(){var e=this;let{systemAudio:t=!1,autoGainControl:i,echoCancellation:n,noiseSuppression:r,audioTrack:o,videoTrack:s}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){try{let a;return s||o?(a=new MediaStream(),s&&a.addTrack(s),o&&a.addTrack(o)):a=yield aL({audio:!1,systemAudio:t,width:e.profile.width,height:e.profile.height,frameRate:e.profile.frameRate,autoGainControl:i,echoCancellation:n,noiseSuppression:r}),yield e.setInputMediaStreamTrack(a.getVideoTracks()[0]),a;}catch(a){throw e.log.error(\"getDisplayMedia error observed \".concat(a)),a instanceof gb?a:new gb({code:mb.INITIALIZE_FAILED,name:a.name,message:a.message});}}();});}switchDevice(e){return ab(this,null,function*(){throw new Error(\"Method not implemented.\");});}},lL=class extends oL{constructor(e){super(e),this._log.id=\"s-\".concat(this._log.id);}},dL=class extends oL{constructor(e){super(e),ob(this,\"_inputs\",new Map()),ob(this,\"_destination\"),ob(this,\"audioContext\",NP(\"audio-mixer\")),this._log.id=\"m-\".concat(this._log.id),\"running\"!==this.audioContext.state&&this._log.warn(\"audio mixer context state: \".concat(this.audioContext.state)),this._destination=this.audioContext.createMediaStreamDestination(),this._destination.channelCount=1;}setInputMediaStreamTrack(e){this._inputTrack=e;let t=this.audioContext.createMediaStreamSource(new MediaStream([e]));this._inputs.set(e,{sourceNode:t}),t.connect(this._destination),this._outputTrack||(this._outputTrack=this._destination.stream.getAudioTracks()[0],this.setStateToCapture());}setTrackCaptureVolume(e,t){if(!this._inputs.has(e)||!this._destination)return;let i=this._inputs.get(e),{sourceNode:n}=i;i.gainNode||(this._log.info(\"create GainNode\"),i.gainNode=this.audioContext.createGain()),i.gainNode.gain.value=t,n.disconnect(),n.connect(i.gainNode).connect(this._destination);}publish(e,t){return this.room=e,t;}unpublish(){delete this.room;}replaceTrack(e,t){var i;!this.hasMix||(t&&(null==(i=this._inputs.get(t))||i.sourceNode.disconnect(),this._inputs.delete(t)),this.setInputMediaStreamTrack(e.outMediaTrack));}removeTrack(e){var t;null==(t=this._inputs.get(e))||t.sourceNode.disconnect(),this._inputs.delete(e),0===this._inputs.size&&(delete this._outputTrack,this.unpublish());}close(){this.stop(),this.audioContext.close();}get hasMix(){return!!this._outputTrack;}set channelCount(e){this._destination.channelCount=e;}};rb([Bw(\"capture\",\"publish\",{ignoreError:!0})],dL.prototype,\"publish\",1),rb([Bw([],\"capture\")],dL.prototype,\"unpublish\",1);var uL=class extends nL{constructor(e,t){super(1),ob(this,\"musicId\"),ob(this,\"mediaType\",1),ob(this,\"volume\",0),ob(this,\"profile\",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),ob(this,\"playerMuted\",!1),ob(this,\"audio\"),ob(this,\"_audioContext\"),ob(this,\"_destination\"),ob(this,\"_source\",null),this.manager=e,this.initAudioContext(),this._destination=this._audioContext.createMediaStreamDestination(),this._destination.channelCount=1,this.audio=document.createElement(\"audio\"),this.audio.src=t.url,this.audio.crossOrigin=\"anonymous\",sO(t.loop)&&this.loop(t.loop),oO(t.volume)&&this.setVolume(t.volume),t.id&&(this.musicId=t.id),this._source=this._audioContext.createMediaElementSource(this.audio),this._source.connect(this._destination),this.setInputMediaStreamTrack(this._destination.stream.getAudioTracks()[0]),this.installPlayerEvent();}play(){return ab(this,null,function*(){try{yield this.audio.play(),yield sb(uL.prototype,this,\"play\").call(this,null,{muted:!1}),this._log.info(\"music \".concat(this.musicId,\" play success\"));}catch(sN){this._log.error(\"music \".concat(this.musicId,\" play error\"),sN);}});}installPlayerEvent(){this.audio.addEventListener(\"error\",this.handleAudioError.bind(this));}uninstallPlayerEvent(){this.audio.removeEventListener(\"error\",this.handleAudioError.bind(this));}handleAudioError(e){this._log.warn(\"local music \".concat(this.musicId,\" audio error\"),e);}initAudioContext(){this._audioContext=NP(\"music\"),\"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.uninstallPlayerEvent(),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;}seek(e){e<0&&e>this.duration()?this._log.warn(\"Time beyond song duration.\"):this.audio.currentTime=e;}getPosition(){return this.audio.currentTime||0;}setVolume(e){e>1&&e<0?this.log.warn(\"volume is out of range\"):this.audio.volume=e;}getVolume(){return this.audio.volume||0;}setPlayBackRate(e){e>8&&e<0?this.log.warn(\"rate is out of range\"):this.audio.playbackRate=e;}getPlayBackRate(){return this.audio.playbackRate||0;}duration(){return this.audio.duration||0;}loop(e){return this.audio&&sO(e)&&(this.audio.loop=e),this.audio.loop||!1;}setOperation(e){\"pause\"===e&&this.audio.pause(),\"resume\"===e&&(this.audio.pause(),this.audio.play()),\"stop\"===e&&(this.audio.pause(),this.seek(0));}listenDeviceChange(){}},hL=\"input\",pL=\"output\";var _L=e=>(e=Number(e))>0&&e<14e8;function mL(e){return ab(this,arguments,function(e){let{sdkAppId:t,userId:i,userSig:n,timestamp:r}=e;return function*(){let e=\"https://\".concat(function(e){let t;return t=_L(e)?\"intl-schedule.rtc.qq.com\":\"schedule.rtc.qq.com\",t;}(t),\"/api/v1/audioAiAuth?sdkAppId=\").concat(t,\"&userId=\").concat(i,\"&userSig=\").concat(n,\"×tamp=\").concat(r),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if(\"1\"===l)return{auth:!0,sign:c,status:l,message:a};let d=\"Init RTCAIDenoiser failed.\",u=\"\";switch(s){case 1:u=\"Please check your params.\";break;case 2:u=\"You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247\";break;case 3:u=\"Server is invalid. Please contact our engineer. \";break;case 4:u=\"Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247\";break;case 5:u=\"Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247\";break;case 6:u=\"Your version is not supported.\";}return{auth:!1,status:l,message:a?\"\".concat(d,\" Reason: \").concat(a,\". \").concat(u):\"\".concat(d,\", \").concat(u)};}();});}var fL=nb(cb(),1);function gL(e,t){t=t||{};let i,n=e.numberOfChannels,{sampleRate:r}=e,o=t.float32?3:1,s=3===o?32:16;return i=2===n?function(e,t){let i=e.length+t.length,n=new Float32Array(i),r=0,o=0;for(;r{let{type:t,data:i}=e.data;if(\"ondump\"===t&&this.isDumping_){let{inputPCM:e,outputPCM:t}=i;this.dump_.onDump(e,hL),this.dump_.onDump(t,pL);}\"dumped\"===t&&this.dumped();},this.dump_=new EL(this.audioContext_);}dumped(){this.isDumping_=!1;let e=this.dump_.getBlob(hL),t=this.dump_.getBlob(pL);this.emitter_.emit(\"ondumpend\",{blob:e,name:hL}),this.emitter_.emit(\"ondumpend\",{blob:t,name:pL}),this.dumpedWAV(e,hL),this.dumpedWAV(t,pL),this.dump_.reset();}dumpedWAV(e,t){let i=window.URL.createObjectURL(e),n=document.createElement(\"a\");n.href=i,n.download=\"\".concat(t,\"-\").concat(Date.now(),\".wav\"),n.click(),window.URL.revokeObjectURL(i),n.href=\"\";}process(e){return ab(this,null,function*(){if(this.audioTrack_=e,!this.audioTrack_)throw new Error(\"RTCAIDenoiser: cannot process without audioTrack.\");let t=new MediaStream();t.addTrack(this.audioTrack_),this.source_=this.audioContext_.createMediaStreamSource(t),yield this.source_.connect(this.workletNode_),this.trackConstraint_=this.audioTrack_.getConstraints(),this.trackConstraint_.noiseSuppression=!1,yield this.audioTrack_.applyConstraints(this.trackConstraint_);let i=this.destination_.stream;return this.denoiserTrack_=i.getAudioTracks()[0],this.log_.info(\"RTCAIDenoiser: denoiser process track ID: \".concat(e.id,\" success.\")),this.denoiserTrack_;});}updateTrack(e){return ab(this,null,function*(){var t;let i=new MediaStream();yield i.addTrack(e);let n=this.audioContext_.createMediaStreamSource(i);this.source_.disconnect(),n.connect(this.workletNode_),null==(t=this.audioTrack_)||t.stop(),this.audioTrack_=e,this.source_=n,this.log_.info(\"RTCAIDenoiser: updateTrack success.\");});}disable(){return ab(this,null,function*(){var e,t;return this.enableDenoise_=!1,null==(e=this.workletNode_)||e.port.postMessage({type:\"disable\"}),this.trackConstraint_.noiseSuppression=!0,yield null==(t=this.audioTrack_)?void 0:t.applyConstraints(this.trackConstraint_),this.log_.info(\"RTCAIDenoiser: disable ai denoiser.\"),this.enableDenoise_;});}enable(){return ab(this,null,function*(){var e,t;return this.enableDenoise_=!0,null==(e=this.workletNode_)||e.port.postMessage({type:\"enable\"}),this.trackConstraint_.noiseSuppression=!1,yield null==(t=this.audioTrack_)?void 0:t.applyConstraints(this.trackConstraint_),this.log_.info(\"RTCAIDenoiser: enable ai denoiser.\"),this.enableDenoise_;});}startDump(){return this.isDumping_?(this.log_.info(\"RTCAIDenoiser: data is currently being dumped.\"),!1):(this.workletNode_.port.postMessage({type:\"startDump\"}),this.dump_?this.dump_.reset():this.dump_=new EL(this.audioContext_),this.isDumping_=!0,this.log_.info(\"RTCAIDenoiser: start dump data.\"),!0);}stopDump(){!this.isDumping_||(this.workletNode_.port.postMessage({type:\"stopDump\"}),this.isDumping_=!1,this.log_.info(\"RTCAIDenoiser: stop dump data.\"));}getAudioTrack(){return this.audioTrack_;}getDenoiserTrack(){return this.destination_.stream.getAudioTracks()[0];}get enabled(){return this.enableDenoise_;}destroy(){var e,t,i,n,r,o;this.log_.info(\"RTCAIDenoiser: destroy processor.\"),null==(e=this.audioTrack_)||e.stop(),null==(t=this.workletNode_)||t.port.postMessage({type:\"destroy\"}),this.workletNode_.port.onmessage=null,null==(i=this.source_)||i.disconnect(),null==(n=this.destination_)||n.disconnect(),null==(r=this.workletNode_)||r.disconnect(),null==(o=this.dump_)||o.destroy(),this.emitter_.removeAllListeners();}on(e,t,i){this.emitter_.on(e,t,i);}off(e,t,i){\"*\"===e?this.emitter_.removeAllListeners():this.emitter_.off(e,t,i);}},IL=class{constructor(e){let{assetsPath:t,log:i,audioContext:n}=e;this.isLoaded_=!1,this.audioContext_=n,this.log_=i,this.assetsPath_=t;}createProcessor(e){return ab(this,null,function*(){let t=String(Date.now()).slice(0,-3),{auth:i,sign:n,status:r,message:o}=yield mL(eb($C({},e),{timestamp:t}));if(!i)throw this.log_.info(\"RTCAIDenoiser: \".concat(e.userId,\" auth result: \").concat(i,\". Message: \").concat(o)),new Error(o);try{yield this.load();}catch(c){throw new Error(\"Init wasm failed, please check your assetsPath.\");}let s=yield this.initWorklet(),a=new SL(eb($C({},e),{audioContext:this.audioContext_,timestamp:t,sign:n,status:r,worklet:s,logger:this.log_}));return this.log_.info(\"RTCAIDenoiser: \".concat(e.userId,\" create denoiser processor success.\")),a;});}load(){return ab(this,null,function*(){if(!this.isLoaded_)try{yield this.audioContext_.audioWorklet.addModule(\"\".concat(this.assetsPath_,\"/denoiser-wasm.js\")),this.isLoaded_=!0;}catch(HL){throw this.log_.error(\"Init assets from \".concat(this.assetsPath_,\" failed! Reason: \").concat(HL)),HL;}});}initWorklet(){return ab(this,null,function*(){try{return new AudioWorkletNode(this.audioContext_,\"trtc-denoiser-processor\",{numberOfInputs:1,numberOfOutputs:1});}catch(HL){return yield this.load(),new AudioWorkletNode(this.audioContext_,\"trtc-denoiser-processor\",{numberOfInputs:1,numberOfOutputs:1});}});}destroy(){var e;null==(e=this.audioContext_)||e.close();}isSupported(){return\"AudioWorklet\"in window&&\"WebAssembly\"in window;}},vL=class{constructor(e){let{room:t}=e;ob(this,\"_localAudioTrack\",null),ob(this,\"_localScreenAudioTrack\",null),ob(this,\"localMixAudioTrack\"),ob(this,\"isDenoiserInit\",!1),ob(this,\"isDenoiserEnabled\",!1),ob(this,\"isDenoiserProcessed\",!1),ob(this,\"mixedMusicMap\",new Map()),ob(this,\"cacheMusicMap\",new Map()),ob(this,\"_log\"),ob(this,\"denoiserTrack\",null),ob(this,\"denoiser\",null),ob(this,\"denoiserProcessor\"),ob(this,\"initProcessorOptions\"),ob(this,\"denoiserContext\"),this._log=HO.createLogger({id:\"am\",userId:t.userId,sdkAppId:t.sdkAppId});}get mixedAudioTrack(){return this.localMixAudioTrack?this.localMixAudioTrack.outMediaTrack:null;}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack;}get hasAudioTrack(){return null!==this._localAudioTrack;}changeInput(e,t){var i,n,r;return e instanceof lL?(this._localScreenAudioTrack=e,void(e._outputTrack=e.mediaTrack)):e instanceof uL?(e._outputTrack=e.mediaTrack,void(null==(i=this.localMixAudioTrack)||i.replaceTrack(e,t))):e instanceof oL?(this._localAudioTrack=e,this.isDenoiserProcessed&&(null==(n=this.denoiserProcessor)||n.updateTrack(e.mediaTrack)),e.setOutputMediaStreamTrack(this.isDenoiserProcessed?this.denoiserTrack:e.mediaTrack),void(null==(r=this.localMixAudioTrack)||r.replaceTrack(e,t))):e instanceof RL?e.setOutputMediaStreamTrack(e.mediaTrack):void 0;}removeInput(e){if(e instanceof oL)return this.removeAudioTrack(e);}addMusicSource(e){return ab(this,null,function*(){this._log.info(\"add music source, id: \".concat(e.id,\" url: \").concat(e.url));let t,{id:i,url:n,loop:r,volume:o}=e;if(!this.mixedMusicMap.has(i))return t=this.cacheMusicMap.has(i)?this.cacheMusicMap.get(i):new uL(this,e),t.play(),this._log.info(\"start mix audio \".concat(i,\" success.\")),this.mixedMusicMap.set(i,t),this.cacheMusicMap.set(i,t),t;});}updateMusicSource(e){return ab(this,null,function*(){let{id:t,volume:i,loop:n,operation:r,seekFrom:o}=e;if(this._log.info(\"update music source, \".concat(JSON.stringify(e))),this.mixedMusicMap.has(t)){let e=this.mixedMusicMap.get(t);nO(i)||e.setVolume(i),nO(n)||e.loop(n),nO(r)||e.setOperation(r),nO(o)||e.seek(o);}});}addAudioTrack(e){return ab(this,null,function*(){var t;if(this.localMixAudioTrack||(this.localMixAudioTrack=new dL(this)),this._log.info(\"start add audioTrack, userId: \".concat(e.userId)),e===this._localAudioTrack){if(Cw){let i=yield null==(t=e.mediaTrack)?void 0:t.getSettings();this.localMixAudioTrack.channelCount=(null==i?void 0:i.channelCount)||1;}this.mixedMusicMap.forEach(e=>{var t;null==(t=this.localMixAudioTrack)||t.setInputMediaStreamTrack(e.outMediaTrack);});}this.localMixAudioTrack.setInputMediaStreamTrack(e.outMediaTrack),this._localAudioTrack&&1!==this._localAudioTrack.captureVolume&&this.setCaptureVolume(this._localAudioTrack.captureVolume);});}removeAudioTrack(e){!this.localMixAudioTrack||(e===this._localAudioTrack&&this.mixedMusicMap.forEach(e=>{this.localMixAudioTrack.removeTrack(e.outMediaTrack);}),this.localMixAudioTrack.removeTrack(e.outMediaTrack));}removeMusicSource(e){let{id:t}=e;if(this.localMixAudioTrack){if(this.mixedMusicMap.has(t)){this._log.info(\"remove music source, music id: \".concat(t));let e=this.mixedMusicMap.get(t);e.stop(),this.localMixAudioTrack.removeTrack(e.outMediaTrack),this.mixedMusicMap.delete(t);}\"*\"===t&&this.destroyAllMusic();}}destroyAllMusic(){this._log.info(\"destroy all music source.\"),this.mixedMusicMap.forEach((e,t)=>{this.removeMusicSource({id:t});});}destroyAllCache(){this._log.info(\"destroy all music cache.\"),this.cacheMusicMap.forEach(e=>e.stop());}initDenoiser(e){return ab(this,null,function*(){let{assetsPath:t,sdkAppId:i,userId:n,userSig:r}=e;try{(!this.denoiserContext||\"closed\"===this.denoiserContext.state)&&(this.denoiserContext=NP(\"denoiser\")),this.denoiser||(this.denoiser=new IL({assetsPath:t,log:this._log,audioContext:this.denoiserContext})),this.denoiserProcessor||(this.denoiserProcessor=yield this.denoiser.createProcessor({sdkAppId:i,userId:n,userSig:r})),this.isDenoiserInit=!0,this.initProcessorOptions=e;}catch(cN){throw cN;}});}enableDenoiser(e){return ab(this,null,function*(){var e,t,i;if(this.isDenoiserEnabled=!0,!this.hasAudioTrack){let e=\"enableDenoiser failed, there is no audio\";throw this._log.error(e),new Error(e);}if(this.isDenoiserProcessed)null==(i=this.denoiserProcessor)||i.enable();else{let i=null==(e=this._localAudioTrack)?void 0:e.mediaTrack;if(!i)return;this.denoiserProcessor||(yield this.initDenoiser(this.initProcessorOptions)),this.denoiserTrack=yield this.denoiserProcessor.process(i),this.isDenoiserProcessed=!0,this._localAudioTrack._outputTrack=this.denoiserTrack,null==(t=this.localMixAudioTrack)||t.replaceTrack(this._localAudioTrack,i);}});}disableDenoiser(){return ab(this,null,function*(){var e;this.isDenoiserEnabled&&(null==(e=this.denoiserProcessor)||e.disable(),this.isDenoiserEnabled=!1);});}setCaptureVolume(e){var t;this.localMixAudioTrack&&this._localAudioTrack&&this._localAudioTrack.mediaTrack&&(null==(t=this.localMixAudioTrack)||t.setTrackCaptureVolume(this._localAudioTrack.mediaTrack,e));}destroyDenoiserProcessor(){var e;this.denoiserProcessor&&(this.denoiserProcessor.destroy(),delete this.denoiserProcessor,this.isDenoiserInit=!1,this.isDenoiserEnabled=!1,this.isDenoiserProcessed=!1,null==(e=this.denoiserTrack)||e.stop(),this.denoiserTrack=null),this.denoiserContext&&(this.denoiserContext.close(),delete this.denoiserContext);}destroy(){var e;this.destroyAllMusic(),this.destroyAllCache(),this.destroyDenoiserProcessor(),null==(e=this.denoiser)||e.destroy(),this.localMixAudioTrack&&(this.localMixAudioTrack.close(),delete this.localMixAudioTrack);}},yL=class extends MP{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,ob(this,\"tinyId\"),ob(this,\"isRemote\",!0),this.tinyId=t.tinyId;}setMute(e){return this.hasFlag&&super.setMute(e);}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack);}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once(\"input-media-track-changed\",e);});}get isSubscribing(){return\"subscribeing\"===this.state.toString();}get isSubscribed(){return this.state===yL.STATE_SUBSCRIBE;}get streamType(){return 0==(2&this.mediaType)?\"main\":\"auxiliary\";}subscribe(e){return e;}unsubscribe(){this.player.setTrack(null),\"main\"===this.streamType&&\"video\"===this.kind&&this.room.changeType(!1,this.user);}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack))return void this.log.info(\"abort play, isSubscribed:\".concat(this.isSubscribed,\" hasFlag:\").concat(this.hasFlag,\" hasTrack:\").concat(!!this.outMediaTrack));super.updatePlayingState(e);}}onFlagChanged(){this.updatePlayingState(this.hasFlag);}},AL=yL;ob(AL,\"STATE_SUBSCRIBE\",\"subscribe\"),rb([Bw(Gw.INIT,AL.STATE_SUBSCRIBE,{success(){this.log.info(\"subscribed\"),xO.emit(FO.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0);},ignoreError:!0})],AL.prototype,\"subscribe\",1),rb([Bw(AL.STATE_SUBSCRIBE,Gw.INIT,{success(){this.log.info(\"unsubscribed\"),this.updatePlayingState(!1),xO.emit(FO.REMOTE_TRACK_UNSUBSCRIBED,{track:this});}})],AL.prototype,\"unsubscribe\",1);var RL=class extends AL{constructor(e,t){super(e,t,1),ob(this,\"volume\",0),ob(this,\"mediaType\",1),ob(this,\"stat\",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager;}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;}},CL=class extends AL{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),ob(this,\"mediaType\",4),ob(this,\"stat\",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager;}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;}},bL=class extends CL{constructor(e,t){super(e,t,2),ob(this,\"mediaType\",2),ob(this,\"objectFit\",\"contain\");}get hasFlag(){return this.user.muteState.hasAuxiliary;}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t;}};function kL(){}var NL=e=>e(),DL=()=>\"undefined\"!=typeof __FASTRX_DEVTOOLS__,OL=1,wL=class extends Function{toString(){return\"\".concat(this.name,\"(\").concat(this.args.length?[...this.args].join(\", \"):\"\",\")\");}subscribe(e){let t=new xL(e,this,this.streamId++);return UL.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t;}},PL=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=kL,this.error=kL,this.next=kL,this.dispose=kL,this.subscribe=kL,this.doDefer();}subscribe(e){return e instanceof wL?e.subscribe(this):e(this),this;}get bindSubscribe(){return e=>this.subscribe(e);}doDefer(){this.defers.forEach(NL),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;}},LL=class extends PL{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 ML(e,t,i){if(DL()){let n=Object.defineProperties(Object.setPrototypeOf(e,wL.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}});UL.create(n);for(let e=0;e{UL.defer(this.source,this.id);});}next(e){UL.next(this.source,this.id,e),this.sink.next(e);}complete(){UL.complete(this.source,this.id),this.sink.complete();}error(e){UL.complete(this.source,this.id,e),this.sink.error(e);}},UL={addSource(e,t){VL(\"addSource\",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}});},next(e,t,i){VL(\"next\",{id:e.id,streamId:t,data:i&&i.toString()});},subscribe(e,t){let{id:i,end:n}=e;VL(\"subscribe\",{id:i,end:n,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}});},complete(e,t,i){VL(\"complete\",{id:e.id,streamId:t,err:i?i.toString():null});},defer(e,t){VL(\"defer\",{id:e.id,streamId:t});},pipe(e){VL(\"pipe\",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}});},update(e){VL(\"update\",{id:e.id,name:e.toString()});},create(e){e.id||(e.id=OL++),VL(\"create\",{name:e.toString(),id:e.id});}},FL=class extends PL{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();}};var BL,HL,jL=(BL=class extends LL{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i;}next(e){super.next(this.mapper.call(this.thisArg,e));}},HL=\"map\",function(){for(var e=arguments.length,t=new Array(e),i=0;i{if(e instanceof wL){let i=ML(n=>{let r=new BL(n,...t);r.sourceId=i.id,r.subscribe(e);},HL,arguments);return i.source=e,UL.pipe(i),i;}return i=>e(new BL(i,...t));};});!function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;nt(e),e);}(function(e){return ML(t=>{let i=0,n=setInterval(()=>t.next(i++),e);return t.defer(()=>{clearInterval(n);}),\"interval\";},\"interval\",arguments);}(250),jL(()=>performance.now()),function(){return e=>{let t=new FL(e);if(e instanceof wL){let i=ML(e=>{t.add(e);},\"share\",arguments);return t.sourceId=i.id,i.source=e,UL.pipe(i),i;}return ML(t.add.bind(t),\"share\",arguments);};}());var GL=new Map();function WL(e,t){let i=eb($C({},t),{timestamp:Eb()});GL.has(e)?GL.get(e).push(i):GL.set(e,[i]);}xO.on(FO.JOIN_SUCCESS,e=>{let{room:t}=e;WL(t.userId,{eventId:32788,eventDesc:\"join room\"});}),xO.on(FO.LEAVE_START,e=>{let{room:t}=e;WL(t.userId,{eventId:32789,eventDesc:\"leave room\"});}),xO.on(FO.LOCAL_TRACK_PUBLISHED,e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),WL(t.room.userId,{eventId:e,eventDesc:\"publish \".concat(t.kind)});}}),xO.on(FO.LOCAL_TRACK_UNPUBLISHED,e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),WL(t.room.userId,{eventId:e,eventDesc:\"unpublish \".concat(t.kind)});}}),xO.on(FO.TRACK_MUTED,e=>{let{track:t}=e;t.room&&(t.kind===LN.AUDIO?WL(t.room.userId,{eventId:t.isRemote?32785:32772,eventDesc:\"mute audio\",remoteUserId:t.isRemote?t.userId:void 0}):WL(t.room.userId,{eventId:t.isRemote?32784:32773,eventDesc:\"mute video\",remoteUserId:t.isRemote?t.userId:void 0}));}),xO.on(FO.TRACK_UNMUTED,e=>{let{track:t}=e;t.room&&(t.kind===LN.AUDIO?WL(t.room.userId,{eventId:t.isRemote?32787:32774,eventDesc:\"unmute audio\",remoteUserId:t.isRemote?t.userId:void 0}):WL(t.room.userId,{eventId:t.isRemote?32786:32775,eventDesc:\"unmute video\",remoteUserId:t.isRemote?t.userId:void 0}));}),xO.on(FO.REMOTE_TRACK_SUBSCRIBED,e=>{let{track:t}=e;!t.room||(1===t.mediaType&&WL(t.room.userId,{eventId:32777,eventDesc:\"\".concat(LN.SUBSCRIBE,\" \").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&WL(t.room.userId,{eventId:32776,eventDesc:\"\".concat(LN.SUBSCRIBE,\" \").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&WL(t.room.userId,{eventId:32803,eventDesc:\"\".concat(LN.SUBSCRIBE,\" \").concat(LN.SMALL_VIDEO),remoteUserId:t.userId}));}),xO.on(FO.REMOTE_TRACK_UNSUBSCRIBED,e=>{let{track:t}=e;!t.room||(1===t.mediaType&&WL(t.room.userId,{eventId:32779,eventDesc:\"\".concat(LN.UNSUBSCRIBE,\" \").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&WL(t.room.userId,{eventId:32778,eventDesc:\"\".concat(LN.UNSUBSCRIBE,\" \").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&WL(t.room.userId,{eventId:32804,eventDesc:\"\".concat(LN.UNSUBSCRIBE,\" \").concat(LN.SMALL_VIDEO),remoteUserId:t.userId}));}),xO.on(FO.SWITCH_DEVICE_SUCCESS,e=>{let{track:t}=e;t.room&&WL(t.room.userId,{eventId:t.kind===LN.VIDEO?32780:32781,eventDesc:\"switch \".concat(t.kind===LN.VIDEO?\"camera\":\"microphone\")});}),xO.on(FO.LOCAL_TRACK_REPLACED,e=>{let{track:t}=e;t.room&&WL(t.room.userId,{eventId:t.kind===LN.VIDEO?32782:32783,eventDesc:\"replace \".concat(t.kind)});}),xO.on(FO.SIGNAL_CONNECTION_STATE_CHANGED,e=>{let t,i,{room:n,prevState:r,state:o}=e;switch(o){case\"CONNECTED\":\"RECONNECTING\"===r?(t=32795,i=\"signal reconnected\"):(t=32791,i=\"signal connected\");break;case\"DISCONNECTED\":\"RECONNECTING\"===r?(t=32796,i=\"signal reconnect fail\"):(t=32790,i=\"signal disconnected\");break;case\"RECONNECTING\":t=32794,i=\"signal reconnecting\";}t&&i&&WL(n.userId,{eventId:t,eventDesc:i});}),xO.on(FO.PEER_CONNECTION_STATE_CHANGED,e=>{let t,i,{room:n,prevState:r,state:o,remoteUserId:s}=e,a=!!s,c=a?\"downlink\":\"uplink\";switch(o){case\"CONNECTED\":\"RECONNECTING\"===r?(t=a?32801:32798,i=\"\".concat(c,\" reconnected\")):(t=a?32793:32792,i=\"\".concat(c,\" connected\"));break;case\"DISCONNECTED\":\"RECONNECTING\"===r&&(t=a?32802:32799,i=\"\".concat(c,\" reconnect fail\"));break;case\"RECONNECTING\":t=a?32800:32797,i=\"\".concat(c,\" reconnecting\");}t&&i&&WL(n.userId,{eventId:t,eventDesc:i,remoteUserId:s});});var JL=nb(cb(),1),KL=class extends JL.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,ob(this,\"userMap\",new Map()),ob(this,\"remotePublishedUserMap\",new Map());}getPublishedUser(e){return this.remotePublishedUserMap.get(e);}addUser(e){let t=e[this.key],{userId:i,tinyId:n,role:r}=e;if(this.userMap.has(t))return;let o={userId:i,tinyId:n,role:20===r?\"anchor\":\"audience\"};this.userMap.set(t,o),this.emit(\"1\",o);}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let n=\"peer leave [\".concat(e,\"]\");nO(t)||(n+=\":\".concat(ND[t])),this._log.info(n);let r=this.remotePublishedUserMap.get(e);if(r){let t=r.muteState;r.flag=0,this.emit(\"5\",r.userId),this.deleteRemotePublishedUser(e),this.emit(\"6\",{prevMuteState:t,muteState:r.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:n,userId:r,tinyId:o}=e,s=IO(n,r),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==n&&(e.flag=n,this._log.info(\"remote publish updated: \".concat(JSON.stringify(e.muteState))),this.emit(\"6\",{prevMuteState:a,muteState:s,flag:n}));}else this._log.info(\"remote publish. state: \".concat(JSON.stringify(s))),this.addUser({userId:r,tinyId:o,role:20}),this.emit(\"3\",e),this.emit(\"6\",{prevMuteState:IO(0,r),muteState:s,flag:n});});}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear();}};var YL,zL=!0,qL={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\"},QL={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},XL=((YL=XL||{})[YL.INVALID_PARAMETER=5e3]=\"INVALID_PARAMETER\",YL[YL.INVALID_PARAMETER_REQUIRED=5001]=\"INVALID_PARAMETER_REQUIRED\",YL[YL.INVALID_PARAMETER_TYPE=5002]=\"INVALID_PARAMETER_TYPE\",YL[YL.INVALID_PARAMETER_EMPTY=5003]=\"INVALID_PARAMETER_EMPTY\",YL[YL.INVALID_PARAMETER_INSTANCE=5004]=\"INVALID_PARAMETER_INSTANCE\",YL[YL.INVALID_PARAMETER_RANGE=5005]=\"INVALID_PARAMETER_RANGE\",YL[YL.INVALID_PARAMETER_LESS_THAN_ZERO=5006]=\"INVALID_PARAMETER_LESS_THAN_ZERO\",YL[YL.INVALID_PARAMETER_MIN=5007]=\"INVALID_PARAMETER_MIN\",YL[YL.INVALID_PARAMETER_MAX=5008]=\"INVALID_PARAMETER_MAX\",YL[YL.INVALID_ELEMENT_ID=5009]=\"INVALID_ELEMENT_ID\",YL[YL.INVALID_ELEMENT_ID_TYPE=5010]=\"INVALID_ELEMENT_ID_TYPE\",YL[YL.INVALID_STREAM_ID=5011]=\"INVALID_STREAM_ID\",YL[YL.INVALID_ROOM_ID_STRING=5012]=\"INVALID_ROOM_ID_STRING\",YL[YL.INVALID_ROOM_ID_INTEGER=5013]=\"INVALID_ROOM_ID_INTEGER\",YL[YL.INVALID_STREAM_TYPE=5014]=\"INVALID_STREAM_TYPE\",YL[YL.INVALID_ROOM_ID_REQUIED=5015]=\"INVALID_ROOM_ID_REQUIED\",YL[YL.INVALID_ROOM_ID_INTEGER_STRING=5016]=\"INVALID_ROOM_ID_INTEGER_STRING\",YL[YL.INVALID_OPERATION=5100]=\"INVALID_OPERATION\",YL[YL.INVALID_OPERATION_NOT_JOINED=5101]=\"INVALID_OPERATION_NOT_JOINED\",YL[YL.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]=\"INVALID_OPERATION_REMOTE_USER_NOT_EXIST\",YL[YL.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]=\"INVALID_OPERATION_STREAM_TYPE_NOT_EXIST\",YL[YL.INVALID_OPERATION_REPEAT_CALL=5104]=\"INVALID_OPERATION_REPEAT_CALL\",YL[YL.ENV_NOT_SUPPORTED=5200]=\"ENV_NOT_SUPPORTED\",YL[YL.NOT_SUPPORTED_HTTP=5201]=\"NOT_SUPPORTED_HTTP\",YL[YL.NOT_SUPPORTED_WEBRTC=5202]=\"NOT_SUPPORTED_WEBRTC\",YL[YL.NOT_SUPPORTED_H264_ENCODE=5203]=\"NOT_SUPPORTED_H264_ENCODE\",YL[YL.NOT_SUPPORTED_H264_DECODE=5204]=\"NOT_SUPPORTED_H264_DECODE\",YL[YL.NOT_SUPPORTED_SCREEN_SHARE=5205]=\"NOT_SUPPORTED_SCREEN_SHARE\",YL[YL.NOT_SUPPORTED_SMALL_VIDEO=5206]=\"NOT_SUPPORTED_SMALL_VIDEO\",YL[YL.NOT_SUPPORTED_SEI=5207]=\"NOT_SUPPORTED_SEI\",YL[YL.DEVICE_ERROR=5300]=\"DEVICE_ERROR\",YL[YL.DEVICE_NOT_FOUND_ERROR=5301]=\"DEVICE_NOT_FOUND_ERROR\",YL[YL.DEVICE_NOT_ALLOWED_ERROR=5302]=\"DEVICE_NOT_ALLOWED_ERROR\",YL[YL.DEVICE_NOT_READABLE_ERROR=5303]=\"DEVICE_NOT_READABLE_ERROR\",YL[YL.DEVICE_OVERCONSTRAINED_ERROR=5304]=\"DEVICE_OVERCONSTRAINED_ERROR\",YL[YL.DEVICE_INVALID_STATE_ERROR=5305]=\"DEVICE_INVALID_STATE_ERROR\",YL[YL.DEVICE_SECURITY_ERROR=5306]=\"DEVICE_SECURITY_ERROR\",YL[YL.DEVICE_ABORT_ERROR=5307]=\"DEVICE_ABORT_ERROR\",YL[YL.CAMERA_RECOVER_FAILED=5308]=\"CAMERA_RECOVER_FAILED\",YL[YL.MICROPHONE_RECOVER_FAILED=5309]=\"MICROPHONE_RECOVER_FAILED\",YL[YL.SERVER_ERROR=5400]=\"SERVER_ERROR\",YL[YL.ACCOUNT_NO_MONEY=-100013]=\"ACCOUNT_NO_MONEY\",YL[YL.OPERATION_FAILED=5500]=\"OPERATION_FAILED\",YL[YL.FIREWALL_RESTRICTION=5501]=\"FIREWALL_RESTRICTION\",YL[YL.REJOIN_FAILED=5502]=\"REJOIN_FAILED\",YL[YL.EVENT_HANDLER_ERROR=5503]=\"EVENT_HANDLER_ERROR\",YL[YL.VIDEO_CONTEXT_ERROR=5504]=\"VIDEO_CONTEXT_ERROR\",YL[YL.OPERATION_ABORT=5998]=\"OPERATION_ABORT\",YL[YL.UNKNOWN_ERROR=5999]=\"UNKNOWN_ERROR\",YL);var ZL=eb($C({},KO),{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:n,value:r}=e;return\"'\".concat(t||i.name,\"' is a required param when calling \").concat(n,\"(), received: \").concat(r,\".\");},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:n,value:r}=e,o=\"\".concat(t||i.name),s=\"\";return s=Array.isArray(i.type)?i.type.join(\"|\"):i.type,\"'\".concat(o,\"' must be type of \").concat(s,\" when calling \").concat(n,\"(), received type: \").concat(tO(r),\".\");},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:n,value:r}=e;return\"'\".concat(t||i.name,\"' cannot be '\").concat(r,\"' when calling \").concat(n,\"().\");},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:n,value:r}=e,o=\"\".concat(t||i.name),s=\"\".concat(i.instanceOf.name||i.instanceOf);return\"'\".concat(o,\"' must be instanceof \").concat(s,\" when calling \").concat(n,\"(), received type: \").concat(tO(r),\".\");},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:n,value:r}=e;return\"'\".concat(t||i.name,\"' must be one of \").concat(i.values.join(\"|\"),\" when calling \").concat(n,\"(), received: \").concat(r,\".\");},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:n}=e;return\"'\".concat(t||i.name,\"' cannot be less than 0 when calling \").concat(n,\"().\");},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,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,value:n}=e;return\"the max value of \".concat(t||i.name,\" is \").concat(i.max,\", received: \").concat(n,\".\");},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:n}=e;return\"the element corresponding to '\".concat(t,\"' must be instanceof HTMLElement when calling \").concat(i,\"(), received: \").concat(n,\".\");},INVALID_STREAM_ID(e){let{key:t}=e;return\"'\".concat(t,\"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.\");},INVALID_ROOM_ID_STRING(e){let{key:t}=e;return\"'\".concat(t,\"' must be a valid string.\");},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return\"'\".concat(t,\"' must be an integer between [1, 4294967294].\");},INVALID_ROOM_ID_INTEGER_STRING(e){let{key:t}=e;return\"'\".concat(t,\"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.\");},INVALID_ROOM_ID_REQUIED:()=>\"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.\",INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return\"'streamType' is required when 'userId' is not '*', calling \".concat(t,\"()\");},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_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 device exception\").concat(i?\", error: \".concat(i.toString(),\".\"):\".\");},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:i=$L(t),error:n}=e;return\"NotFoundError, no \".concat(i,\" detected, please check your device and the configuration on '\").concat(t,\"'\").concat(n?\", error: \".concat(n.toString(),\".\"):\".\");},DEVICE_NOT_ALLOWED_ERROR(e){let{fnName:t,deviceType:i=$L(t),error:n}=e;return\"NotAllowedError, you have disabled \".concat(i,\" access, please allow the current application to use the \").concat(i).concat(n?\", error: \".concat(n.toString(),\".\"):\".\");},DEVICE_NOT_READABLE_ERROR(e){let{fnName:t,deviceType:i=$L(t),error:n}=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=$L(t),error:n}=e;return\"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct\".concat(n?\", error: \".concat(n.toString(),\".\"):\".\");},DEVICE_INVALID_STATE_ERROR(e){let{fnName:t,deviceType:i=$L(t),error:n}=e;return\"InvalidStateError, after the user clicks and interacts with the page, turn on the \".concat(i).concat(n?\", error: \".concat(n.toString(),\".\"):\".\");},DEVICE_SECURITY_ERROR(e){let{fnName:t,deviceType:i=$L(t),error:n}=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(n?\", error: \".concat(n.toString(),\".\"):\".\");},DEVICE_ABORT_ERROR(e){let{fnName:t,deviceType:i=$L(t),error:n}=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(n?\" error: \".concat(n.toString(),\".\"):\".\");},CAMERA_RECOVER_FAILED(e){let{error:t}=e;return\"camera recover capture failed \".concat((null==t?void 0:t.name)||\"\",\": \").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message));},MICROPHONE_RECOVER_FAILED(e){let{error:t}=e;return\"microphone recover capture failed \".concat((null==t?void 0:t.name)||\"\",\": \").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message));},OPERATION_FAILED(e){let{fnName:t,error:i}=e;return\"'\".concat(t,\"' failed, reason: \").concat(null==i?void 0:i.toString());},FIREWALL_RESTRICTION:()=>\"media connection failure due to firewall restrictions, please try to change your network.\",EVENT_HANDLER_ERROR(e){let{eventName:t}=e;return\"an error was caught on trtc.on('\".concat(t,\"', handler), please check your code on 'handler'.\");},VIDEO_CONTEXT_ERROR(e){let{reason:t,error:i}=e;return\"video context error \".concat(t,\" \").concat((null==i?void 0:i.name)||\"\",\" \").concat((null==i?void 0:i.message)||\"\");},SERVER_ERROR(e){let{fnName:t,error:i}=e;return\"'\".concat(t,\"' got server error: \").concat(null==i?void 0:i.toString(),\", please check the SDK documentation.\");},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 $L(e){if(!e)return\"camera\";let t=e.toLowerCase();return t.includes(\"screen\")?\"screen share\":t.includes(\"audio\")?\"microphone\":\"camera\";}var eM=class extends Error{constructor(e){let{code:t,extraCode:i,message:n=\"\",messageParams:r,fnName:o=\"\",originError:s}=e;var a;let c;c=n||function(e){let t,{code:i,params:n,enableDocLink:r=!1}=e,s=\"\",a=XL[i];try{t=ZL[a];}catch(o){t=ZL.UNKNOWN_ERROR;}return iO(t)?s=t(n):rO(t)&&(s=t),r&&(s+=\" doc:\"),s;}({code:i||t,params:$C({fnName:o,error:s},r)}),super(c),ob(this,\"name\",\"RtcError\"),ob(this,\"code\"),ob(this,\"extraCode\"),ob(this,\"functionName\"),ob(this,\"message\"),ob(this,\"handler\"),ob(this,\"originError\"),this.name=XL[t],this.code=t,this.extraCode=i,this.functionName=o,this.originError=s,this.message=c,5302===this.extraCode&&(null==(a=this.originError)?void 0:a.message.includes(\"system\"))&&(this.handler=()=>{let e=document.createElement(\"a\");_k?e.href=\"ms-settings:privacy-\".concat({startLocalVideo:\"webcam\",startLocalAudio:\"microphone\"}[this.functionName]):mk&&(e.href=\"x-apple.systempreferences:com.apple.preference.security?Privacy_\".concat({startLocalVideo:\"Camera\",startLocalAudio:\"Microphone\",startScreenShare:\"ScreenCapture\"}[this.functionName])),e.href.length>0&&e.click();});}static convertFrom(e,t,i){let n=e;if(e instanceof gb){let{stack:r}=e,o={code:QL.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case mb.INVALID_PARAMETER:o.code=QL.INVALID_PARAMETER;break;case mb.INVALID_OPERATION:o.code=QL.INVALID_OPERATION;break;case mb.NOT_SUPPORTED:case mb.NOT_SUPPORTED_H264:o.code=QL.ENV_NOT_SUPPORTED,e.getCode()===mb.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(KO.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case mb.DEVICE_NOT_FOUND:case mb.DEVICE_AUTO_RECOVER_FAILED:o.code=QL.DEVICE_ERROR;break;case mb.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case mb.SERVER_TIMEOUT:case mb.SWITCH_ROLE_FAILED:o.code=QL.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case mb.API_CALL_ABORTED:o.code=QL.OPERATION_ABORT;break;case mb.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 mb.UNKNOWN:break;default:o.code=QL.OPERATION_FAILED;}n=new eM(o),r&&(n.stack+=r.substr(r.indexOf(\"\\n\")));}else n=new eM({code:QL.UNKNOWN_ERROR,fnName:t,originError:e});return n;}};var tM=eM,iM={type:\"object\",properties:{cameraId:{type:\"string\"},useFrontCamera:{type:\"boolean\"},fillMode:{type:\"string\",values:[\"contain\",\"cover\",\"fill\"]},mirror:{type:\"boolean\"},small:{properties:{width:{type:\"number\"},height:{type:\"number\"},frameRate:{type:\"number\"},bitrate:{type:\"number\"}}},videoTrack:{instanceOf:MediaStreamTrack}}},nM={type:\"object\",properties:{systemAudio:{type:\"boolean\"},fillMode:{type:\"string\",values:[\"contain\",\"cover\",\"fill\"]},profile:{type:[\"string\",\"object\"],properties:{width:{type:\"number\"},height:{type:\"number\"},frameRate:{type:\"number\"},bitrate:{type:\"number\"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},rM={type:[\"string\",HTMLElement,null,\"array\"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(rO(e)){let n=document.getElementById(e);if(!n)throw new tM({code:QL.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}});if(!(n instanceof HTMLElement))throw new tM({code:QL.INVALID_PARAMETER,extraCode:5010,fnName:i,messageParams:{key:t,type:tO(n)}});}}},oM={name:\"userId\",required:!0,type:\"string\"},sM={type:\"object\",properties:{microphoneId:{type:\"string\"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:\"number\",min:0},earMonitorVolume:{type:\"number\",min:0,max:100},echoCancellation:{type:\"boolean\"},autoGainControl:{type:\"boolean\"},noiseSuppression:{type:\"boolean\"}}};function aM(e,t){if(!e)throw new tM({code:QL.INVALID_OPERATION,extraCode:5101,fnName:t});}function cM(e,t,i){if(!e)throw new tM({code:QL.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}});}var lM={create:[{name:\"RoomConfig\",instanceOf:Function},{name:\"CreateConfig\",type:\"object\",properties:{plugins:{type:\"array\",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:\"EnterRoomConfig\",type:\"object\",required:!0,validate(e,t,i){if(this._room.isJoined)throw new tM({code:QL.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(rO(e.roomId))throw new tM({code:QL.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new tM({code:QL.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}});}else{if(!e.strRoomId)throw new tM({code:QL.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\\d\\s!#$%&()+\\-:;<=.>?@[\\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new tM({code:QL.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}});}},properties:{sdkAppId:{required:!0,type:\"number\",allowEmpty:!1},userId:{required:!0,type:\"string\",allowEmpty:!1},userSig:{required:!0,type:\"string\",allowEmpty:!1},scene:{type:\"string\",values:[\"live\",\"rtc\"]},role:{type:\"string\",values:[\"audience\",\"anchor\"]},roomId:{type:[\"string\",\"number\"]},strRoomId:{type:\"string\"},proxy:{type:[\"object\",\"string\"],properties:{websocketProxy:{type:\"string\"},turnServer:{type:[\"object\",\"array\"],properties:{url:{required:!0,type:\"string\"},username:{type:\"string\"},credential:{type:\"string\"},credentialType:{type:\"string\",values:[\"password\"]}}},loggerProxy:{type:\"string\"},webtransportProxy:{type:\"string\"}}},enableAutoPlayDialog:{type:\"boolean\"},userDefineRecordId:{type:\"string\"}}},startLocalVideo:{name:\"LocalVideoConfig\",type:\"object\",properties:{view:rM,publish:{type:\"boolean\"},option:iM},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&nw())throw new tM({code:QL.ENV_NOT_SUPPORTED,extraCode:5201});}},updateLocalVideo:{name:\"updateLocalVideoConfig\",type:\"object\",required:!0,properties:{view:eb($C({},rM),{required:!1}),publish:{type:\"boolean\"},mute:{type:\"boolean\"},option:iM}},startLocalAudio:{name:\"LocalAudioConfig\",type:\"object\",properties:{publish:{type:\"boolean\"},option:sM},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&nw())throw new tM({code:QL.ENV_NOT_SUPPORTED,extraCode:5201});}},updateLocalAudio:{name:\"updateLocalAudioConfig\",type:\"object\",required:!0,properties:{publish:{type:\"boolean\"},mute:{type:\"boolean\"},option:sM}},startScreenShare:{name:\"ScreenShareConfig\",type:\"object\",properties:{view:rM,publish:{type:\"boolean\"},option:nM},validate(e,t,i,n,r){var o;if((null==(o=null==e?void 0:e.option)||!o.videoTrack)&&nw())throw new tM({code:QL.ENV_NOT_SUPPORTED,extraCode:5201});if(!lw())throw new tM({code:QL.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205});}},updateScreenShare:{name:\"updateScreenShareConfig\",type:\"object\",required:!0,properties:{view:rM,publish:{type:\"boolean\"},option:nM}},muteRemoteAudio:[oM,{name:\"mute\",required:!0,type:\"boolean\"}],setRemoteAudioVolume:[oM,{name:\"volume\",required:!0,type:\"number\",min:0}],startRemoteVideo:{name:\"startRemoteVideoConfig\",type:\"object\",required:!0,properties:{view:rM,userId:{type:\"string\",required:!0},streamType:{values:[\"main\",\"sub\"],required:!0},option:{type:\"object\",properties:{fillMode:{type:\"string\",values:[\"contain\",\"cover\",\"fill\"]},mirror:{type:\"boolean\"}}}},validate(e,t,i){aM(this._room.isJoined,i);let n=this._room.remotePublishedUserMap.get(e.userId);if(cM(!!n,i,e),n&&(\"main\"===e.streamType&&!n.muteState.videoAvailable||\"sub\"===e.streamType&&!n.muteState.hasAuxiliary))throw new tM({code:QL.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}});}},updateRemoteVideo:{name:\"updateRemoteVideoConfig\",type:\"object\",required:!0,properties:{view:eb($C({},rM),{required:!1}),userId:{type:\"string\",required:!0},streamType:{values:[\"main\",\"sub\"],required:!0},option:{type:\"object\",properties:{fillMode:{type:\"string\",values:[\"contain\",\"cover\",\"fill\"]},mirror:{type:\"boolean\"}}}},validate(e,t,i){aM(this._room.isJoined,i);let n=this._room.remotePublishedUserMap.get(e.userId);if(cM(!!n,i,e),n&&(\"main\"===e.streamType&&!n.muteState.videoAvailable||\"sub\"===e.streamType&&!n.muteState.hasAuxiliary))throw new tM({code:QL.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}});}},stopRemoteVideo:{name:\"stopRemoteVideoConfig\",type:\"object\",required:!0,properties:{userId:{type:\"string\",required:!0},streamType:{values:[\"main\",\"sub\"]}},validate(e,t,i){if(\"*\"!==e.userId&&nO(e.streamType))throw new tM({code:QL.INVALID_PARAMETER,extraCode:5014,fnName:i});}},switchRole:{name:\"role\",required:!0,values:[\"anchor\",\"audience\"],validate(e,t,i){aM(this._room.isJoined,i);}},enableAudioVolumeEvaluation:[{name:\"interval\",type:\"number\"},{name:\"enableInBackground\",type:\"boolean\"}],sendSEIMessage:[{name:\"buffer\",required:!0,instanceOf:ArrayBuffer,validate(e,t,i,n){if(!kw)throw new tM({code:QL.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new tM({code:QL.INVALID_OPERATION,messageParams:{key:JO.SEI_DISABLED}});if(e.byteLength>1e3)throw new tM({code:QL.INVALID_PARAMETER,messageParams:{key:JO.SEI_OVERSIZE,data:e.byteLength}});if(0===e.byteLength)throw new tM({code:QL.INVALID_PARAMETER,messageParams:{key:JO.SEI_EMPTY}});if(aM(this._room.isJoined,i),!this._room.isMainStreamPublished)throw new tM({code:QL.INVALID_PARAMETER,messageParams:{key:JO.SEI_BEFORE_PUBLISH}});}},{name:\"options\",type:\"object\",properties:{seiPayloadType:{type:\"number\",values:[5,243]}}}]},dM={TRTC:lM},uM=class extends Error{};function hM(e,t){let i=[];return CO(i,e),CO(i,t),i;}function pM(e){this._resolve=Promise.resolve(e);}function _M(e){this._reject=Promise.reject(e);}var mM=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=hM;let i=mM.instances.get(e);i?i.set(t,this):mM.instances.set(e,new Map([[t,this]]));}static get(e,t){let i=mM.instances.get(e);return i&&i.get(t)||new mM(e,t);}action(e,t,i){let n=t=>{var i;return 0===e?this.started=!0:3===e&&(this.started=!1),this.ops.shift(),null==(i=this.currentOp)||i.action(),t;},r=t=>{var i,n;throw this.ops.shift(),0===e&&2===(null==(i=this.currentOp)?void 0:i.type)&&this.ops.shift().reject(new uM(\"start failed\")),null==(n=this.currentOp)||n.action(),t;},o={type:e,action:()=>t(...o.args).then(n,r),args:i,resolve:pM,reject:_M};try{switch(this.state){case 1:if(0===e)throw new uM(\"already started\");break;case 4:if(2===e)throw new uM(\"not started\");break;default:return this.cacheOp(o);}}catch(qx){return Promise.reject(qx);}return this.ops.push(o),o.promise=t(...o.args).then(n,r);}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new uM(\"already start\");break;case 3:switch(e.type){case 2:throw new uM(\"update not allowed when stopping\");case 3:return this.currentOp.promise;}break;default:throw new uM(\"unknown state\");}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new uM(\"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 uM(\"update not allowed after stop\");}break;case 0:switch(this.lastOpType){case 2:throw new uM(\"start not allowed after update\");case 0:throw new uM(\"duplicate start\");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new uM(\"keep start\")),new uM(\"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;}},fM=mM;fM.instances=new WeakMap();var gM=new WeakMap(),TM=(e,t)=>{if(t instanceof uM){let{stack:i}=t;t=new tM({code:QL.OPERATION_ABORT,message:\"\".concat(e,\" abort: \").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf(\"\\n\")));}throw t;};function EM(e,t){return iL((i,n)=>function(){for(var r=arguments.length,o=new Array(r),s=0;sfunction(){for(var o=arguments.length,s=new Array(o),a=0;a{var a,l;let d=null==(a=gM.get(this))?void 0:a.get(i(...s));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t();}let u=setTimeout(()=>{if(3===c.state||4===c.state)return n();c.action(2,t.bind(this),s).catch(TM.bind(null,r)).then(n,o);},e);gM.has(this)?null==(l=gM.get(this))||l.set(i(...s),{timeoutId:u,resolve:n}):gM.set(this,new Map([[i(...s),{timeoutId:u,resolve:n}]]));});}return c.action(2,t.bind(this),s).catch(TM.bind(null,r));});}function IM(e){return iL((t,i)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o{t.startsWith(n)&&(e.started=!1);});}};}var RM=new WeakMap();function CM(){for(var e=arguments.length,t=new Array(e),i=0;ifunction(){for(var n=arguments.length,r=new Array(n),o=0;ofunction(){for(var n=arguments.length,r=new Array(n),o=0;ohO(e)?pO(e):rO(e)?e:tO(e))},value:i}});}else if(!nO(t.type)&&tO(i)!==t.type)throw new tM(s(5002));if(!1===t.allowEmpty){let e=oO(i)&&(0===i||Number.isNaN(i)),t=rO(i)&&\"\"===i.trim();if(e||t)throw new tM(s(5003));}if(t.notLessThanZero&&oO(i)&&i<0)throw new tM(s(5006));if(!nO(t.min)&&oO(i)&&it.max)throw new tM(s(5008));if(rO(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new tM(s(5004));}else if(iO(t.instanceOf)&&!(i instanceof t.instanceOf))throw new tM(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new tM(s(5005));let{properties:a}=t;ZD(a)&&aO(i)&&Object.keys(a).forEach(e=>{NM.call(this,{rule:a[e],value:i&&i[e],key:\"\".concat(e),fnName:r,className:o});});let{arrayItem:c}=t;ZD(c)&&cO(i)&&i.forEach((e,t)=>{NM.call(this,{rule:c,value:e,key:\"\".concat(n,\"[\").concat(t,\"]\"),fnName:r,className:o});}),iO(t.validate)&&t.validate.call(this,i,n,r,o,this);}function DM(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{namePrefix:t=()=>\"\",getRemoteId:i=()=>\"\"}=e;return iL((e,n)=>function(){for(var r=arguments.length,o=new Array(r),s=0;s0?c.info(\"\".concat(d,\"() \").concat(JSON.stringify(o,(e,t)=>a(e,t,[\"userSig\",\"privateMapKey\"])))):c.info(\"\".concat(d,\"()\"));try{let t=e.apply(this,o),n=fO();return uO(t)?t.then(e=>(c.info(\"\".concat(d,\"() success \").concat(i.call(this,...o))),xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:d,cost:fO()-n}),e)).catch(e=>{throw e=tM.convertFrom.call(this,e,d,1===o.length?o[0]:o),c.error(\"\".concat(d,\"() failed \").concat(i.call(this,...o),\" \").concat(e,\" params: \").concat(JSON.stringify(o,a))),xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:d,error:e}),e;}):(xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:d,cost:fO()-n}),t);}catch(u){throw u=tM.convertFrom.call(this,u,d),c.error(\"\".concat(d,\"() failed \").concat(u,\" params: \").concat(JSON.stringify(o,a))),xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:d,error:u}),u;}});}var OM=e=>iL((t,i)=>function(n,r){return ab(this,null,function*(){let o=this._plugins.get(n);if(o)return kM.call(this,o.getValidateRule(e),[r],i,\"TRTC\"),t.call(this,o,r);this._log.warn(\"plugin \".concat(n,\" is not found\"));});}),wM=0,PM=class{constructor(e){this.core=e,ob(this,\"log\"),wM+=1,this.log=e.log.createChild({id:\"\".concat(this.getAlias()).concat(wM)}),this.log.info(\"[audioMixer] created id=\".concat(this.getAlias()).concat(wM)),this.core=e;}getName(){return\"AudioMixer\";}getAlias(){return\"ax\";}getGroup(e){return null==e?void 0:e.id;}getValidateRule(e){switch(e){case\"start\":return PM.startValidateRule;case\"update\":return PM.updateValidateRule;case\"stop\":return PM.stopValidateRule;}}start(e){return ab(this,null,function*(){let{room:t}=this.core;yield t.audioManager.addMusicSource(e);});}update(e){return ab(this,null,function*(){let{room:t}=this.core;yield t.audioManager.updateMusicSource(e);});}stop(e){return ab(this,null,function*(){let{room:t}=this.core;yield t.audioManager.removeMusicSource(e);});}},LM=PM;ob(LM,\"startValidateRule\",{name:\"options\",required:!0,type:\"object\",properties:{id:{type:\"string\",required:!0},url:{type:\"string\",required:!0},loop:{type:\"boolean\"},volume:{type:\"number\"}},validate(e,t,i){if(\"*\"!==e.url){let t=[\"mp3\",\"ogg\",\"wav\",\"flac\"],n=e.url.split(\".\").pop(),r=t.indexOf(n)>=0,o=e.url.startsWith(\"blob\"),s=e.url.startsWith(\"data\");if(!(r||o||s))throw new tM({code:QL.INVALID_PARAMETER,message:\"start audioMixer plugin: music url is invalid, please check your file format.\",fnName:i});}}}),ob(LM,\"updateValidateRule\",{name:\"options\",required:!0,type:\"object\",properties:{id:{type:\"string\",required:!0},loop:{type:\"boolean\"},volume:{type:\"number\"},seekFrom:{type:\"number\"},operation:{type:\"string\",values:[\"pause\",\"resume\",\"stop\"]}}}),ob(LM,\"stopValidateRule\",{name:\"options\",type:\"object\",required:!0,properties:{id:{type:\"string\",required:!0}}});var MM=0,VM=class{constructor(e){this.core=e,ob(this,\"log\"),MM+=1,this.log=e.log.createChild({id:\"\".concat(this.getAlias()).concat(MM)}),this.log.info(\"[audioDenoiser] created id=\".concat(this.getAlias()).concat(MM));}getName(){return\"AIDenoiser\";}getAlias(){return\"ad\";}getGroup(e){return\"AIDenoiser_\".concat(Date.now());}getValidateRule(e){switch(e){case\"start\":return VM.startValidateRule;case\"update\":return VM.updateValidateRule;case\"stop\":return VM.stopValidateRule;}}start(e){return ab(this,null,function*(){let{room:t}=this.core,{assetsPath:i,sdkAppId:n,userId:r,userSig:o}=e;if(i&&!t.audioManager.isDenoiserInit)try{yield t.audioManager.initDenoiser({assetsPath:i,sdkAppId:n,userId:r,userSig:o});}catch(qx){if(qx.message)throw new gb({code:mb.INVALID_PARAMETER,message:qx.message});}yield t.audioManager.enableDenoiser(e),t.sendAbilityStatus({ai_denoise:1});});}update(e){return ab(this,null,function*(){});}stop(e){return ab(this,null,function*(){let{room:e}=this.core;yield e.audioManager.disableDenoiser();});}},xM=VM;ob(xM,\"startValidateRule\",{name:\"options\",required:!0,type:\"object\",properties:{assetsPath:{type:\"string\",required:!0},sdkAppId:{type:\"number\",required:!0},userId:{type:\"string\",required:!0},userSig:{type:\"string\",required:!0}}}),ob(xM,\"updateValidateRule\",{type:\"object\"}),ob(xM,\"stopValidateRule\",{type:\"object\"});var UM=0,FM=new Set(),BM=null;oN(\"5.2.1\");var HM=class extends pb.EventEmitter{constructor(e,t){super(),ob(this,\"_room\"),ob(this,\"_eventListened\",new Set()),ob(this,\"_localVideoTrack\",null),ob(this,\"_localAudioTrack\",null),ob(this,\"_localScreenTrack\",null),ob(this,\"_localScreenAudioTrack\",null),ob(this,\"_localVideoConfig\",null),ob(this,\"_localScreenConfig\",null),ob(this,\"_localAudioConfig\",null),ob(this,\"_remoteVideoConfigMap\",new Map()),ob(this,\"_remoteAudioConfigMap\",new Map()),ob(this,\"_remoteAudioMuteMap\",new Map()),ob(this,\"_log\",HO.createLogger({id:\"t\".concat(++UM)})),ob(this,\"_plugins\",new Map()),ob(this,\"_networkQuality\",null),this._room=new e($C({logger:this._log,frameWorkType:HM.frameWorkType},t)),t.plugins&&t.plugins.forEach(e=>{let t=new e(AM(this._room));this._plugins.set(t.getName(),t);});let i=new LM(AM(this._room));this._plugins.set(i.getName(),i);let n=new xM(AM(this._room));this._plugins.set(n.getName(),n),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(vM.AUDIO_VOLUME,{result:e.sort((e,t)=>t.volume-e.volume)});}),this._room.videoManager.on(\"error\",e=>{let{reason:t,error:i}=e;this._log.error(new tM({code:QL.OPERATION_FAILED,extraCode:5504,messageParams:{reason:t,error:i}}));}),this.on(vM.REMOTE_AUDIO_UNAVAILABLE,e=>{let{userId:t}=e;this._stopRemoteAudio({userId:t},!1).catch(()=>{});}),this.on(vM.REMOTE_VIDEO_UNAVAILABLE,e=>{let{userId:t,streamType:i}=e;this._stopRemoteVideo({userId:t,streamType:i},!1).catch(()=>{});}),SP(jP,jP).add(\"audioInputAdded\",e=>{this.emit(vM.DEVICE_CHANGED,{type:\"microphone\",action:\"add\",device:e});}).add(\"audioInputRemoved\",e=>{this.emit(vM.DEVICE_CHANGED,{type:\"microphone\",action:\"remove\",device:e});}).add(\"videoInputAdded\",e=>{this.emit(vM.DEVICE_CHANGED,{type:\"camera\",action:\"add\",device:e});}).add(\"videoInputRemoved\",e=>{this.emit(vM.DEVICE_CHANGED,{type:\"camera\",action:\"remove\",device:e});}).add(\"audioOutputAdded\",e=>ab(this,null,function*(){if(this.emit(vM.DEVICE_CHANGED,{type:\"speaker\",action:\"add\",device:e}),BM&&BM.deviceId===CD){let e=(yield KP()).find(e=>e.deviceId===CD);e&&BM.groupId!==e.groupId&&(BM=e,this.emit(vM.DEVICE_CHANGED,{type:\"speaker\",action:\"active\",device:e}));}})).add(\"audioOutputRemoved\",e=>ab(this,null,function*(){this.emit(vM.DEVICE_CHANGED,{type:\"speaker\",action:\"remove\",device:e});let t=(yield KP())[0];t&&BM&&(BM.deviceId===e.deviceId||BM.deviceId===CD&&BM.groupId!==t.groupId)&&(BM=t,this.emit(vM.DEVICE_CHANGED,{type:\"speaker\",action:\"active\",device:t}));})),((e,t)=>{let{emit:n}=e;e.emit=function(){for(var r=arguments.length,o=new Array(r),s=0;s{if(e){let t=\"UAData: \".concat(e.platform,\"/\").concat(e.platformVersion);e.architecture&&e.bitness&&(t+=\" \".concat(e.architecture,\"/\").concat(e.bitness)),e.mobile&&(t+=\" mobile\"),e.model&&(t+=\" model: \".concat(e.model)),e.fullVersionList&&(t+=\" \".concat(e.fullVersionList.filter(e=>\"Not/A)Brand\"!==e.brand).map(e=>\"\".concat(e.brand,\"/\").concat(e.version)).join(\",\"))),HO.info(t);}}));}();let i=new HM(e,t||{});return FM.add(i),BM?i.emit(vM.DEVICE_CHANGED,{type:\"speaker\",action:\"active\",device:BM}):KP().then(e=>{e[0]&&(BM=e[0],i.emit(vM.DEVICE_CHANGED,{type:\"speaker\",action:\"active\",device:e[0]}));}),i;}enterRoom(e){return ab(this,null,function*(){var t,i;let{scene:n=\"rtc\",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:s=!0}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!rO(e.proxy)&&e.proxy.turnServer&&(null==(i=(t=this._room).setTurnServer)||i.call(t,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=s,sO(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,role:\"audience\"===e.role?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||\"\",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};e.strRoomId&&!e.roomId&&(this._room.useStringRoomId=!0),SP(this,this._room).add(\"peer-join\",e=>{let{userId:t}=e;this.emit(vM.REMOTE_USER_ENTER,{userId:t});}).add(\"peer-leave\",e=>{this.emit(vM.REMOTE_USER_EXIT,{userId:e});}).add(\"banned\",e=>{this._exitRoom().then(()=>{this.emit(vM.KICKED_OUT,{reason:e.reason});});}).add(\"error\",e=>{this._exitRoom().then(()=>{this.emit(vM.ERROR,tM.convertFrom(e));});}).add(\"signal-connection-state-changed\",e=>{this.emit(vM.CONNECTION_STATE_CHANGED,e);}).add(\"network-quality\",e=>{this._networkQuality=e,this.emit(vM.NETWORK_QUALITY,e);}).add(\"remote-published\",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(t=>{SP(t,t).add(\"player-state-changed\",i=>{let n=eb($C({},i),{userId:e.userId});t.kind===LN.VIDEO&&(n.streamType=function(e){return\"sub\"===e?\"auxiliary\":\"auxiliary\"===e?\"sub\":\"main\";}(t.streamType)),this.emit(t.kind===LN.AUDIO?vM.AUDIO_PLAY_STATE_CHANGED:vM.VIDEO_PLAY_STATE_CHANGED,n);}).add(\"error\",e=>{e.getCode()===mb.PLAY_NOT_ALLOWED&&this.emit(vM.AUTOPLAY_FAILED,{userId:t.userId});});});}).add(\"remote-unpublished\",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(e=>{IP(e);});}).add(\"remote-publish-state-changed\",e=>{let{prevMuteState:t,muteState:i}=e,{userId:n}=i;this._room.remotePublishedUserMap.get(n);let r=t.audioAvailable,o=t.videoAvailable,{audioAvailable:s,videoAvailable:a}=i;s||this._remoteAudioConfigMap.delete(n),a||this._remoteVideoConfigMap.delete(\"\".concat(n,\"_\",\"main\")),i.hasAuxiliary||this._remoteVideoConfigMap.delete(\"\".concat(n,\"_\",\"sub\")),r!==s&&this.emit(s?vM.REMOTE_AUDIO_AVAILABLE:vM.REMOTE_AUDIO_UNAVAILABLE,{userId:n}),o!==a&&this.emit(a?vM.REMOTE_VIDEO_AVAILABLE:vM.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:\"main\"}),t.hasAuxiliary!==i.hasAuxiliary&&this.emit(i.hasAuxiliary?vM.REMOTE_VIDEO_AVAILABLE:vM.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:\"sub\"});}).add(\"firewall-restriction\",()=>{this.emit(vM.ERROR,new tM({code:QL.OPERATION_FAILED,extraCode:5501}));}).add(\"sei-message\",e=>{this.emit(vM.SEI_MESSAGE,e);}).add(\"heartbeat-report\",e=>{var t,i,n,r,o,s,a;let c={2:\"big\",3:\"small\",7:\"sub\"},l={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(n=this._networkQuality)?void 0:n.downlinkRTT)||0,upLoss:(null==(r=this._networkQuality)?void 0:r.uplinkLoss)||0,downLoss:(null==(o=this._networkQuality)?void 0:o.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/xD},video:e.msg_up_stream_info.msg_video_status.filter(e=>c[e.uint32_video_stream_type]).map(e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_enc_fps,videoType:c[e.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(e=>({userId:e.msg_user_info.str_identifier,audio:{bitrate:(e.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(e.msg_audio_status.uint32_audio_level||0)/xD},video:e.msg_video_status.map(e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_dec_fps,videoType:c[e.uint32_video_stream_type]}))}))};this.emit(vM.STATISTICS,l);}),this._handleReceiveMode(),yield this._room.join(a,n,HM.frameWorkType),this._checkTrackToPublish();});}exitRoom(){return ab(this,null,function*(){return yield this._exitRoom();});}switchRole(e){return ab(this,null,function*(){yield this._room.switchRole(e),\"anchor\"===e&&this._checkTrackToPublish();});}destroy(){IP(jP),this.removeAllListeners(),this._room.destroy(),FM.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare();}startLocalAudio(){return ab(this,arguments,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn(\"local audio is already started\");let{publish:i=!0,option:n}=t,r=new oL(e._room.audioManager),o={},s={muted:!0};n&&(nO(n.microphoneId)?nO(n.audioTrack)||(o.customSource=n.audioTrack):o.deviceId=n.microphoneId,n&&oO(n.captureVolume)&&r.setCaptureVolume(n.captureVolume),nO(n.profile)||(rO(n.profile)?ON[n.profile]&&r.setProfile(ON[n.profile]):r.setProfile(n.profile)),oO(n.earMonitorVolume)&&(s.muted=!(n.earMonitorVolume>0),s.volume=n.earMonitorVolume),nO(n.echoCancellation)||(r.profile.echoCancellation=n.echoCancellation),nO(n.noiseSuppression)||(r.profile.noiseSuppression=n.noiseSuppression),nO(n.autoGainControl)||(r.profile.autoGainControl=n.autoGainControl)),r.on(\"5\",t=>{e.emit(vM.ERROR,new tM({code:QL.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}));}),r.on(\"2\",t=>{e.emit(vM.DEVICE_CHANGED,{type:\"microphone\",action:\"active\",device:t});}),r.on(\"4\",t=>{let i;t.error&&(i=tM.convertFrom(t.error)),e.emit(vM.PUBLISH_STATE_CHANGED,eb($C({},t),{error:i}));}),yield r.capture(o),SP(r,r).add(\"player-state-changed\",t=>{e.emit(vM.AUDIO_PLAY_STATE_CHANGED,eb($C({},t),{userId:\"\"}));}),i&&e._room.isJoined&&e._room.publish(r).catch(()=>{}),yield e._updateAudioPlayOption({playOption:s,track:r}),e._localAudioTrack=r,e._localAudioConfig=eb($C({},t),{publish:i});}();});}updateLocalAudio(e){return ab(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:n}=e,r={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):nO(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),nO(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),nO(n.earMonitorVolume)||(r.muted=!(n.earMonitorVolume>0),r.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!nO(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),nO(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:r,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),CO(this._localAudioConfig,e);});}stopLocalAudio(){return ab(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),IP(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null);});}startLocalVideo(){return ab(this,arguments,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localVideoTrack)return void e._log.warn(\"local video is already started\");let{view:i,publish:n=!0,option:r}=t,o=new sL(e._room.videoManager),s={},a={};if(r&&(r.cameraId?s.deviceId=r.cameraId:nO(r.useFrontCamera)?nO(r.videoTrack)||(s.customSource=r.videoTrack):s.facingMode=r.useFrontCamera?LN.FACING_MODE_USER:LN.FACING_MODE_ENVIRONMENT,nO(r.profile)||(rO(r.profile)?wN[r.profile]&&o.setProfile(wN[r.profile]):o.setProfile(r.profile)),nO(r.fillMode)||(a.objectFit=r.fillMode),nO(r.mirror)||(a.mirror=r.mirror),nO(r.small)||(fw()?rO(r.small)?o.small=wN[r.small]:o.small=r.small:e._log.warn(\"small stream is not supported\"))),o.on(\"5\",t=>{e.emit(vM.ERROR,new tM({code:QL.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}));}),o.on(\"2\",t=>{e.emit(vM.DEVICE_CHANGED,{type:\"camera\",action:\"active\",device:t});}),o.on(\"4\",t=>{let i;t.error&&(i=tM.convertFrom(t.error)),e.emit(vM.PUBLISH_STATE_CHANGED,eb($C({},t),{error:i}));}),yield o.capture(s),(null==r?void 0:r.qosPreference)&&o.mediaTrack){let e=yM(r.qosPreference);o.mediaTrack.contentHint=e;}SP(o,o).add(\"player-state-changed\",t=>{e.emit(vM.VIDEO_PLAY_STATE_CHANGED,eb($C({},t),{userId:\"\",streamType:\"main\"}));}),n&&e._room.isJoined&&e._room.publish(o).catch(()=>{}),yield e._updateVideoPlayOption({view:i,playOption:a,track:o}),e._localVideoTrack=o,e._localVideoConfig=eb($C({},t),{view:i,publish:n});}();});}updateLocalVideo(e){return ab(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:n,option:r}=e,o={};if(r&&(nO(r.profile)||(rO(r.profile)?wN[r.profile]&&this._localVideoTrack.setProfile(wN[r.profile]):this._localVideoTrack.setProfile(r.profile),(!r.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(r.cameraId))&&nO(r.useFrontCamera)&&this._localVideoTrack.applyProfile()),r.cameraId?yield this._localVideoTrack.switchDevice(r.cameraId):nO(r.useFrontCamera)?nO(r.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(r.videoTrack)):yield this._localVideoTrack.switchDevice(r.useFrontCamera?LN.FACING_MODE_USER:LN.FACING_MODE_ENVIRONMENT),nO(r.fillMode)||(o.objectFit=r.fillMode),nO(r.mirror)||(o.mirror=r.mirror),r.qosPreference&&this._localVideoTrack.mediaTrack)){let e=yM(r.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e;}this._room.isJoined&&!nO(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),nO(n)||this._localVideoTrack.setMute(n),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),CO(this._localVideoConfig,e);});}stopLocalVideo(){return ab(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),IP(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null);});}startScreenShare(){return ab(this,arguments,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localScreenTrack)return void e._log.warn(\"screen share is already started\");let{view:i=null,publish:n=!0,option:r}=t,o=new cL(e._room.videoManager);o.on(\"4\",t=>{let i;t.error&&(i=tM.convertFrom(t.error)),e.emit(vM.PUBLISH_STATE_CHANGED,eb($C({},t),{error:i}));});let s=null;o.setMediaType(2);let a={},c={};r&&(nO(r.profile)||(rO(r.profile)?PN[r.profile]&&o.setProfile(PN[r.profile]):o.setProfile(r.profile)),r.systemAudio&&(a.systemAudio=!0,a.echoCancellation=r.echoCancellation,a.noiseSuppression=r.noiseSuppression,a.autoGainControl=r.autoGainControl),nO(r.fillMode)||(c.objectFit=r.fillMode),r.videoTrack&&(a.videoTrack=r.videoTrack),r.audioTrack&&(a.audioTrack=r.audioTrack));let l=yield o.capture(a);if(null!=r&&r.qosPreference){let e=yM(r.qosPreference);o.mediaTrack.contentHint=e;}if(o.mediaTrack.addEventListener(LN.ENDED,()=>{e._stopScreenShare(),e.emit(vM.SCREEN_SHARE_STOPPED);}),l.getAudioTracks()[0]&&(s=new lL(e._room.audioManager),s.setInputMediaStreamTrack(l.getAudioTracks()[0])),SP(o,o).add(\"player-state-changed\",t=>{e.emit(vM.VIDEO_PLAY_STATE_CHANGED,eb($C({},t),{userId:\"\",streamType:\"sub\"}));}),n&&e._room.isJoined){let t=[o];s&&t.push(s),e._room.publish(...t).catch(()=>{});}yield e._updateVideoPlayOption({view:i,playOption:c,track:o}),e._localScreenTrack=o,e._localScreenAudioTrack=s,e._localScreenConfig=eb($C({},t),{view:i,publish:n});}();});}updateScreenShare(e){return ab(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:n}=e,r={};if(n&&(nO(n.fillMode)||(r.objectFit=n.fillMode),n.qosPreference)){let e=yM(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e;}this._room.isJoined&&!nO(i)&&(i&&!this._localScreenConfig.publish&&this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenConfig.publish&&!i&&this._room.unpublish(this._localScreenTrack).catch(()=>{})),yield this._updateVideoPlayOption({view:t,playOption:r,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),CO(this._localScreenConfig,e);});}stopScreenShare(){return ab(this,null,function*(){return yield this._stopScreenShare();});}startRemoteVideo(e){return ab(this,null,function*(){let{view:t,userId:i,streamType:n,option:r}=e,o=\"\".concat(i,\"_\").concat(n);if(this._remoteVideoConfigMap.has(o))return void this._log.warn(\"remote video has already started. userId:\".concat(i,\", streamType:\").concat(n));let s=this._room.remotePublishedUserMap.get(i);if(!s)return;let a={},c=\"main\"===n?s.remoteVideoTrack:s.remoteAuxiliaryTrack;r&&(nO(r.fillMode)||(a.objectFit=r.fillMode),nO(r.mirror)||(a.mirror=r.mirror),\"main\"===n&&!nO(r.small)&&this._room.changeType(r.small,c.user)),yield this._room.subscribe(c),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._remoteVideoConfigMap.set(o,e);});}updateRemoteVideo(e){return ab(this,null,function*(){let{view:t,userId:i,streamType:n,option:r}=e,o=\"\".concat(i,\"_\").concat(n);if(!this._remoteVideoConfigMap.has(o)||!this._room.remotePublishedUserMap.has(i))return;let s={};r&&(nO(r.fillMode)||(s.objectFit=r.fillMode),nO(r.mirror)||(s.mirror=r.mirror));let a=null,c=this._room.remotePublishedUserMap.get(i);\"main\"===n&&(null==c?void 0:c.muteState.hasVideo)&&(a=c.remoteVideoTrack),\"sub\"===n&&(null==c?void 0:c.muteState.hasAuxiliary)&&(a=c.remoteAuxiliaryTrack);let l=this._remoteVideoConfigMap.get(o);a&&(\"main\"===n&&r&&!nO(r.small)&&this._room.changeType(r.small,a.user),yield this._updateVideoPlayOption({view:t,playOption:s,track:a,prevConfig:l})),CO(l,e);});}stopRemoteVideo(e){return ab(this,null,function*(){return this._stopRemoteVideo(e);});}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return ab(this,null,function*(){let i=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:t,remoteVideoTrack:r,remoteAuxiliaryTrack:o}=n;\"main\"===e.streamType&&(r.stop(),t.hasVideo&&i.push(r)),\"sub\"===e.streamType&&(o.stop(),t.hasAuxiliary&&i.push(o));}for(let e of i)t&&(yield this._room.unsubscribe(e));this._remoteVideoConfigMap.delete(\"\".concat(e.userId,\"_\").concat(e.streamType));});}muteRemoteAudio(e,t){return ab(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});}}startPlugin(e,t){return ab(this,null,function*(){return e.start(t);});}updatePlugin(e,t){return ab(this,null,function*(){return e.update(t);});}stopPlugin(e,t){return ab(this,null,function*(){return e.stop(t);});}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t);}on(e,t,i){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 ab(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 n=this._room.remotePublishedUserMap.get(t);if(!n)return;let r={};i&&(nO(i.volume)||(r.volume=i.volume));let o=n.remoteAudioTrack;yield this._room.subscribe(o),yield this._updateAudioPlayOption({playOption:r,track:o}),this._remoteAudioConfigMap.set(t,e);});}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return ab(this,null,function*(){let i=this._room.remotePublishedUserMap.get(e.userId);i&&(i.remoteAudioTrack.stop(),i.muteState.hasAudio&&t&&(yield this._room.unsubscribe(i.remoteAudioTrack))),this._remoteAudioConfigMap.delete(\"\".concat(e.userId));});}_updateVideoPlayOption(e){return ab(this,arguments,function(e){let{view:t,playOption:i,track:n,prevConfig:r}=e;return function*(){if(nO(t)&&r&&r.view&&!SO(i)){let e;e=cO(r.view)?r.view:bO(r.view),e&&(yield n.play(e,i));}if(!nO(t)){let e;e=cO(t)?t:bO(t),e?yield n.play(e,i):n.stop();}}();});}_updateAudioPlayOption(e){return ab(this,arguments,function(e){let{playOption:t={},track:i,prevConfig:n}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t);}catch(cN){}nO(t.muted)||i.setPlayerMute(t.muted),nO(t.volume)||i.setAudioVolume(t.volume/100);}();});}_checkTrackToPublish(){var e,t,i;let n=[];if((null==(e=this._localAudioConfig)?void 0:e.publish)&&this._localAudioTrack&&n.push(this._localAudioTrack),(null==(t=this._localVideoConfig)?void 0:t.publish)&&this._localVideoTrack&&n.push(this._localVideoTrack),null!=(i=this._localScreenConfig)&&i.publish&&(this._localScreenTrack&&n.push(this._localScreenTrack),this._localScreenAudioTrack&&n.push(this._localScreenAudioTrack)),0!==n.length)return this._room.publish(...n).catch(()=>{});}_handleReceiveMode(){this._room.autoReceiveAudio&&SP(this,this).add(vM.REMOTE_AUDIO_AVAILABLE,e=>ab(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&&SP(this,this).add(vM.REMOTE_VIDEO_AVAILABLE,e=>{let{userId:t,streamType:i}=e,n=this._room.remotePublishedUserMap.get(t);n&&(\"main\"===i?this._room.subscribe(n.remoteVideoTrack).catch(()=>{}):\"sub\"===i&&this._room.subscribe(n.remoteAuxiliaryTrack).catch(()=>{}));});}_exitRoom(){return ab(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=>{IP(e.remoteAudioTrack),IP(e.remoteVideoTrack),IP(e.remoteAuxiliaryTrack);}),IP(this);});}_stopScreenShare(){return ab(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(),IP(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){HO.setLogLevel(e),nO(t)||(t?HO.enableUploadLog():HO.disableUploadLog());}static isSupported(){return aw();}static getCameraList(){return JP();}static getMicrophoneList(){return WP();}static getSpeakerList(){return KP();}static setCurrentSpeaker(e){return ab(this,null,function*(){(yield KP()).forEach(t=>{t.deviceId===e&&(FM.forEach(i=>{i.setCurrentSpeaker(e),i.emit(vM.DEVICE_CHANGED,{type:\"speaker\",action:\"active\",device:t});}),BM=t);});});}},jM=HM;ob(jM,\"_loggerManager\",HO),ob(jM,\"EVENT\",vM),ob(jM,\"ERROR_CODE\",QL),ob(jM,\"TYPE\",qL),ob(jM,\"frameWorkType\",30),rb([CM(dM.TRTC.enterRoom),EM(\"room\",(e,t)=>{let[i]=e,[n]=t;return(i.roomId||i.strRoomId)===(n.roomId||n.strRoomId)&&i.userId===n.userId&&i.sdkAppId===n.sdkAppId;}),iL(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t).catch(e=>{throw IP(this),e;});}),DM()],jM.prototype,\"enterRoom\",1),rb([DM()],jM.prototype,\"exitRoom\",1),rb([CM(dM.TRTC.switchRole),SM(\"room\",{merge:(e,t)=>t}),DM()],jM.prototype,\"switchRole\",1),rb([DM()],jM.prototype,\"destroy\",1),rb([CM(dM.TRTC.startLocalAudio),EM(\"audio\",(e,t)=>{let[i]=e,[n]=t;var r,o;return(null==(r=null==i?void 0:i.option)?void 0:r.microphoneId)===(null==(o=null==n?void 0:n.option)?void 0:o.microphoneId);}),DM()],jM.prototype,\"startLocalAudio\",1),rb([CM(dM.TRTC.updateLocalAudio),SM(\"audio\",{debounce:{delay:200,getKey:()=>\"\".concat(UM,\"-localAudio\"),isNeedToDebounce:e=>{var t;return!nO(null==(t=e.option)?void 0:t.captureVolume);}}}),DM()],jM.prototype,\"updateLocalAudio\",1),rb([IM(\"audio\"),DM()],jM.prototype,\"stopLocalAudio\",1),rb([CM(dM.TRTC.startLocalVideo),EM(\"video\",(e,t)=>{let[i]=e,[n]=t;var r,o;return(null==(r=null==i?void 0:i.option)?void 0:r.cameraId)===(null==(o=null==n?void 0:n.option)?void 0:o.cameraId);}),DM()],jM.prototype,\"startLocalVideo\",1),rb([CM(dM.TRTC.updateLocalVideo),SM(\"video\"),DM()],jM.prototype,\"updateLocalVideo\",1),rb([IM(\"video\"),DM()],jM.prototype,\"stopLocalVideo\",1),rb([CM(dM.TRTC.startScreenShare),EM(\"screen\",()=>!0),DM()],jM.prototype,\"startScreenShare\",1),rb([CM(dM.TRTC.updateScreenShare),SM(\"screen\"),DM()],jM.prototype,\"updateScreenShare\",1),rb([DM()],jM.prototype,\"stopScreenShare\",1),rb([CM(dM.TRTC.startRemoteVideo),EM(e=>\"v\".concat(e.userId).concat(e.streamType),()=>!0),DM({getRemoteId:e=>\"\".concat(e.userId,\"_\").concat(e.streamType)})],jM.prototype,\"startRemoteVideo\",1),rb([CM(dM.TRTC.updateRemoteVideo),SM(e=>\"v\".concat(e.userId).concat(e.streamType)),DM({getRemoteId:e=>\"\".concat(e.userId,\"_\").concat(e.streamType)})],jM.prototype,\"updateRemoteVideo\",1),rb([CM(dM.TRTC.stopRemoteVideo),iL(e=>function(t){return ab(this,null,function*(){if(\"*\"===t.userId){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(\"\".concat(t.userId,\"_\",\"main\"))&&e.push(this.stopRemoteVideo({streamType:\"main\",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(\"\".concat(t.userId,\"_\",\"sub\"))&&e.push(this.stopRemoteVideo({streamType:\"sub\",userId:t.userId}).catch(()=>{}));}),Promise.all(e);}return e.call(this,t);});}),DM({getRemoteId:e=>\"\".concat(e.userId,\"_\").concat(e.streamType)})],jM.prototype,\"stopRemoteVideo\",1),rb([IM(e=>\"v\".concat(e.userId).concat(e.streamType))],jM.prototype,\"_stopRemoteVideo\",1),rb([CM(...dM.TRTC.muteRemoteAudio),DM({getRemoteId:e=>e})],jM.prototype,\"muteRemoteAudio\",1),rb([bM(...dM.TRTC.setRemoteAudioVolume),function(e,t){return iL((i,n)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o0&&clearTimeout(c);let l=window.setTimeout(()=>{i.apply(this,r);},e);RM.has(this)?null==(a=RM.get(this))||a.set(t(...r),l):RM.set(this,new Map([[t(...r),l]]));});}(200,e=>e),DM({getRemoteId:e=>e})],jM.prototype,\"setRemoteAudioVolume\",1),rb([OM(\"start\"),EM((e,t)=>e.getAlias()+e.getGroup(t)),DM({namePrefix:e=>e.getName()})],jM.prototype,\"startPlugin\",1),rb([OM(\"update\"),SM((e,t)=>e.getAlias()+e.getGroup(t)),DM({namePrefix:e=>e.getName()})],jM.prototype,\"updatePlugin\",1),rb([OM(\"stop\"),IM((e,t)=>e.getAlias()+e.getGroup(t)),DM({namePrefix:e=>e.getName()})],jM.prototype,\"stopPlugin\",1),rb([bM(...dM.TRTC.enableAudioVolumeEvaluation)],jM.prototype,\"enableAudioVolumeEvaluation\",1),rb([EM(e=>\"a\".concat(e.userId),()=>!0)],jM.prototype,\"_startRemoteAudio\",1),rb([iL(e=>function(t){return ab(this,null,function*(){return\"*\"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(eb($C({},t),{userId:e.userId})).catch(()=>{}))):e.call(this,t);});}),IM(e=>\"a\".concat(e.userId))],jM.prototype,\"_stopRemoteAudio\",1),rb([IM(\"room\")],jM.prototype,\"_exitRoom\",1),rb([IM(\"screen\")],jM.prototype,\"_stopScreenShare\",1),rb([CM(dM.TRTC.sendSEIMessage),function(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:n}=e;return iL((e,r)=>{let o=new Map();return xO.on(FO.ROOM_DESTROY,e=>{let{room:t}=e;return o.delete(t);}),function(){let s=o.get(this);for(var a=arguments.length,c=new Array(a),l=0;l1e3&&(s.timestamp=Date.now(),s.callCountInSecond=0,s.totalSizeInSecond=0),n&&(s.totalSizeInSecond+=n(...c)),0!==s.timestamp&&Date.now()-s.timestamp<1e3&&(s.callCountInSecond>=t||s.totalSizeInSecond>i))throw new gb({code:mb.INVALID_OPERATION,message:qO({key:JO.CALL_FREQUENCY_LIMIT,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>i,name:r,timesInSecond:t,maxSizeInSecond:i}})});s.callCountInSecond++,e.call(this,...c);};});}({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var e=arguments.length,t=new Array(e),i=0;i0&&this.room.enableSPC&&(this.keepAlive=!0,NV.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=HO.createLogger({id:\"ws\",userId:this.userId,sdkAppId:this.sdkAppId});}get urlParam(){return\"?sdkAppId=\".concat(encodeURIComponent(this.sdkAppId),\"&userId=\").concat(encodeURIComponent(this.userId),\"&userSig=\").concat(encodeURIComponent(this.userSig),\"&keepAlive=\").concat(encodeURIComponent(Number(this.keepAlive)));}get _urlWithParam(){return\"\".concat(this.url).concat(this.urlParam);}get _backupUrlWithParam(){return\"\".concat(this.backupUrl).concat(this.urlParam);}get isConnected(){return this._currentState===eV;}get isConnecting(){return this._currentState===$M;}get sdkAppId(){return this.room.sdkAppId;}get userId(){return this.room.userId;}get userSig(){return this.room.userSig;}get isOnline(){return this._currentState===eV&&Date.now()-this._lastMessageTime<12e3;}connect(e){return this.isConnected?Promise.resolve():new Promise((t,i)=>{this._prevTime<0&&(this._prevTime=fO()),this._log.info(\"connect to \".concat(this.url).concat(e?\" timeout: \".concat(e):\"\",\" keepAlive: \").concat(Number(this.keepAlive))),this.emitConnectionStateChanged($M),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);let n=-1;e&&(n=setTimeout(()=>{this.close(),i(new gb({code:mb.JOIN_ROOM_FAILED,message:\"join room timeout\"}));},e)),this.once(QM,()=>{clearTimeout(n),t();}),this.once(XM,e=>{clearTimeout(n),i(e);});});}tryConnectBackup(){this._backupSocket||(this.unbindAndCloseSocket(LN.MAIN),this._log.debug(\"try to connect to url: \".concat(this._backupUrlWithParam)),this._backupSocket=new WebSocket(this._backupUrlWithParam),this.bindSocket(this._backupSocket));}bindSocket(e){e.onopen=this.onopen.bind(this),e.onclose=this.onclose.bind(this),e.onerror=this.onerror.bind(this),e.onmessage=this.onmessage.bind(this);}unbindSocket(e){this.clearBackupTimer(),e.onopen=()=>{},e.onclose=()=>{},e.onerror=()=>{},e.onmessage=()=>{};}unbindAndCloseSocket(e){if(e===LN.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3);}catch(sD){}this._socket=null;}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3);}catch(sD){}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(LN.BACKUP),this._socketInUse=this._socket):(this.unbindAndCloseSocket(LN.MAIN),this._socketInUse=this._backupSocket),this.emitConnectionStateChanged(eV),this.emit(QM));}onclose(e){let{url:t}=e.target,i=e.target===this._socketInUse;if(this._log.info(\"websocket[\".concat(t,\" InUse: \").concat(i,\"] is closed with code: \").concat(e.code)),i&&(this.emitConnectionStateChanged(ZM),!e.wasClean||1e3!==e.code)){this._log.warn(\"onclose code:\".concat(e.code,\" reason:\").concat(e.reason)),this._log.warn(\"close current websocket and schedule a reconnect timeout\"),this._socketInUse.onclose=()=>{},this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this._socket=null,this._backupSocket=null,this._socketInUse=null,this.reconnect(t?LN.BACKUP:LN.MAIN);}}onerror(e){let{url:t}=e.target;if(this._log.error(\"websocket[\".concat(t,\"] error observed\")),this.isConnected){if(e.target===this._socketInUse){this.unbindAndCloseSocket(LN.MAIN),this.unbindAndCloseSocket(LN.BACKUP);let e=this._socketInUse===this._socket;this._socketInUse=null,this.reconnect(e?LN.BACKUP:LN.MAIN);}}else this.isReconnecting||xO.emit(FO.API_SUCCESS_RATE,{room:this.room,apiName:\"WebsocketConnect\",error:new Error(\"ws onerror\")}),e.target==this._socket?(this.unbindAndCloseSocket(LN.MAIN),this.reconnect(LN.BACKUP)):(this.unbindAndCloseSocket(LN.BACKUP),this.reconnect(LN.MAIN));}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=wO(e.data);let t=JSON.parse(e.data),{cmd:i,data:n}=t,r=Object.values(tV),o=Object.keys(tV)[r.indexOf(i)],s=nV[o];switch(iV.includes(i)||(this._log.debug(\"received \".concat(i,\" msg: \").concat(e.data)),s&&this._log.info(\"Received event: [ \".concat(s,\" ]\"))),i){case tV.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,this._signalInfo.tinyId=t.tinyId,n.svrTime&&function(e){Tb=e-new Date().getTime();let t=new Date();t.setTime(e),HO.info(\"baseTime from server: \".concat(t,\" offset: \").concat(Tb));}(n.svrTime),this._log.info(\"ChannelSetup Success\"),xO.emit(FO.API_SUCCESS_RATE,{room:this.room,apiName:\"WebsocketConnect\",cost:fO()-this._prevTime}),this._prevTime=-1,this.emit(YM,{signalInfo:this._signalInfo});else{let e=new gb({code:mb.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:qO({key:JO.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(\"\".concat(t.code,\", \").concat(t.message)),this.close(),xO.emit(FO.API_SUCCESS_RATE,{room:this.room,apiName:\"WebsocketConnect\",error:e}),this.emit(zM,e);}break;case tV.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._log.info(\"signalIp:\".concat(this._signalInfo.signalIp,\" clientIp:\").concat(this._signalInfo.clientIp,\" relayIp: \").concat(this._signalInfo.relayIp))),this.emit(s,{data:t});break;case tV.CHANNEL_RECONNECT_RESULT:0===t.code?(this._log.warn(\"reconnect success\"),this.stopReconnection(),xO.emit(FO.API_SUCCESS_RATE,{room:this.room,apiName:\"WebsocketReconnect\",cost:fO()-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.emit(s,{data:t});}}reconnect(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:LN.MAIN;if(!this.room.isJoined&&this.keepAlive)return void this.close();if(this.isReconnecting)return;if(this._reconnectionCount>=aD){this._log.warn(\"SDK has tried reconnect signal channel for \".concat(aD,\" times, but all failed. please check your network\"));let e=new gb({code:mb.SIGNAL_CHANNEL_RECONNECTION_FAILED,message:qO({key:JO.SIGNAL_CHANNEL_RECONNECTION_FAILED})});return xO.emit(FO.API_SUCCESS_RATE,{room:this.room,apiName:\"WebsocketReconnect\",error:e}),void this.emit(XM,e);}this._reconnectionCount++,this._log.warn(\"reconnect \".concat(e,\" [\").concat(this._reconnectionCount,\"/\").concat(aD,\"]\"));let t=this.getReconnectionUrl(e);this.emitConnectionStateChanged($M),this._prevTime<0&&(this._prevTime=fO()),e===LN.MAIN?(this._socket=new WebSocket(t),this.bindSocket(this._socket)):(this._backupSocket=new WebSocket(t),this.bindSocket(this._backupSocket));let i=eO(this._reconnectionCount);this._reconnectionTimer=setTimeout(()=>{this._log.warn(\"reconnect \".concat(e,\" timeout(\").concat(i/1e3,\"s), try again\")),this.clearReconnectionTimer(),this.unbindAndCloseSocket(LN.MAIN),this.unbindAndCloseSocket(LN.BACKUP),this.reconnect(e===LN.MAIN?LN.BACKUP:LN.MAIN);},i);}get isReconnecting(){return-1!==this._reconnectionTimer;}getReconnectionUrl(e){let t=e===LN.MAIN?this._urlWithParam:this._backupUrlWithParam;if(this._signalInfo.tinyId&&-1===t.indexOf(\"&rc=1\")){let{roomId:e,useStringRoomId:i}=this.room;t+=\"&rc=1&relayInnerIp=\".concat(this._signalInfo.relayInnerIp,\"&relayOuterIp=\").concat(this._signalInfo.relayIp,\"&relayPort=\").concat(this._signalInfo.relayPort,\"&roomId=\").concat(e,\"&useStringRoomId=\").concat(i);}return t;}send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let i={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},n=JSON.stringify(i);return this._socketInUse.send(n),this.bytesSent+=wO(n),i.seq;}}sendWaitForResponse(e){let{command:t,data:i,timeout:n=5e3,responseCommand:r,commandDesc:o,enableLog:s=!0}=e;return new Promise((e,a)=>{let c=setTimeout(()=>{this.off(r,l);let e=new gb({code:mb.API_CALL_TIMEOUT,message:qO({key:JO.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),a(e);},n),l=t=>{t.data.seq===d&&(clearTimeout(c),this.off(r,l),e(t));};this.on(r,l);let d=this.send(t,i);});}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:n=0,retryTimeout:r=0}=e;return MO({retryFunction:this.sendWaitForResponse,onRetrying:e=>{this._log.warn(\"\".concat(t||i,\" timeout observed, retrying [\").concat(e,\"/\").concat(n,\"]\"));},settings:{retries:n,timeout:r},context:this})(e);}getCurrentState(){return this._currentState;}getSignalInfo(){return this._signalInfo;}stopReconnection(){this.isReconnecting&&(this._reconnectionCount=0,this.clearReconnectionTimer());}close(){this._log.info(\"closed\"),NV.delete(this),this.clearBackupTimer(),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:\"\",signalIp:\"\",relayIp:\"\",relayInnerIp:\"\",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this.unbindAndCloseSocket(LN.MAIN),this.unbindAndCloseSocket(LN.BACKUP),this.emitConnectionStateChanged(ZM);}stopKeepAliveIn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info(\"stopKeepAlive in \".concat(e,\"s\"));let t=setTimeout(()=>{this.keepAlive=!1,this._log.info(\"close due to not used \".concat(e,\"s\")),this.close();},1e3*e),i=e=>{e instanceof xw&&\"join\"===e.action&&(this._log.info(\"stopKeepAlive clear timeout\"),clearTimeout(t),this.room.off(Gw.STATECHANGED,i));};this.room.on(Gw.STATECHANGED,i);}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(\"\".concat(this._currentState,\" -> \").concat(e)),this.emit(qM,{prevState:this._currentState,state:e}),this._currentState=e);}},OV=nb(cb()),wV=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=[],n=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===n&&(i.push(3),n=0),0==e?n++:n=0,i.push(e);break;default:n=0,i.push(e);}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let r=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=r;}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],n=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:n++,i.push(this.dataView.getInt8(o));break;case 3:2!==n&&i.push(this.dataView.getInt8(o)),n=0;break;default:i.push(this.dataView.getInt8(o)),n=0;}let r=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=r;}get isSEI(){return 6===this.dataView.getUint8(4);}get seiPayloadStartIndex(){let e=6;for(let t=6;t{});}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)===LN.VIDEO?this.isRunning?this.restart(e):this.start(e):this.pipeSenderOrReceiver(e));});}catch(HL){this._log.warn(HL);}}pipeSenderOrReceiver(e){let{readable:t,writable:i}=e.createEncodedStreams(),n=new AbortController();this._abortMap.set(e,n),t.pipeTo(i,n).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,n=new DataView(e);for(let r=0;r0&&!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)),n=i.reduce((e,t)=>e+t.dataView.byteLength,0),r=new ArrayBuffer(n+e.data.byteLength),o=new DataView(r),s=new DataView(e.data),a=0;for(let e=0;e{this.onSEIMessage({seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer});});}}catch(sD){this._log.warn(sD);}t.enqueue(e);}encodeSEINalu(e){let t=e.byteLength,i=parseInt(t/255),n=t%255,r=[];r.push(0,0,0,1,6,this._seiPayloadType);for(let s=0;s=3&&xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:\"PeerConnectionReconnect\",error:sN}),sN;}});}initialize(){let e={encodedInsertableStreams:this._enableSEI&&kw,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),VV.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 gb({code:mb.API_CALL_ABORTED,message:\"connection closed\"}));}getDTLSTransportState(){if(!this._peerConnection)return tD;let e=null;if(this._isUplink){if(!Ew()||0===this._peerConnection.getSenders().length)return tD;e=this._peerConnection.getSenders()[0].transport;}else{if(!Tw()||0===this._peerConnection.getReceivers().length)return tD;e=this._peerConnection.getReceivers()[0].transport;}return e?e.state:tD;}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===iD.CONNECTING&&this.emitConnectionStateChangedEvent(\"CONNECTING\"),e.target.connectionState===iD.FAILED||e.target.connectionState===iD.CLOSED){let n=\"connection \".concat(e.target.connectionState,\". ICE Transport state: \").concat(t,\", DTLS Transport state: \").concat(i),r=new gb({message:n,code:mb.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent(\"DISCONNECTED\"),this.startReconnection(),this._isErrorObserved||this._emitter.emit(\"error\",r);}(e.target.connectionState===iD.CONNECTED||e.target.connectionState===iD.COMPLETED)&&(this.logSelectedCandidate(),Qw.logSuccessEvent({userId:this._room.userId,eventType:cD.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent(\"CONNECTED\"));}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(\"CONNECTED\"===e?(LV=0,MV=!1,xV=!0,VV.add(this)):VV.delete(this),xO.emit(FO.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit(\"connection-state-changed\",{prevState:this._currentState,state:e}),this._currentState=e,!0);}getPeerConnection(){return this._peerConnection;}getRoom(){return this._room;}getUserId(){return this.userId;}getTinyId(){return this.tinyId;}logSelectedCandidate(){return ab(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(uw(t)){let i=e.get(t.localCandidateId),n=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)),n&&(this._log.info(\"remote candidate: \".concat(n.candidateType,\" \").concat(n.protocol,\":\").concat(n.ip||n.address,\":\").concat(n.port)),this._remoteAddress=\"\".concat(n.protocol,\":\").concat(n.ip||n.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),r(),e());},n=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),r(),t(new gb({code:mb.API_CALL_ABORTED,message:qO({key:JO.CONNECTION_ABORTED,data:\"leave room\"})})));},r=()=>{xO.off(FO.LEAVE_SUCCESS,n,this),this._emitter.off(\"connection-state-changed\",i,this);},o=setTimeout(()=>{r();let e=new gb({code:mb.API_CALL_TIMEOUT,message:\"connection timeout\"});LV+=1,(e=>LV>2&&!MV&&0===VV.size&&e)(this._signalChannel.isConnected)&&(this._log.warn(\"firewall restrition\"),MV=!0,this._emitter.emit(\"firewall-restriction\")),t(e);},SD);xO.on(FO.LEAVE_SUCCESS,n,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>=oD()){this._log.warn(\"SDK has tried reconnect for \".concat(this._reconnectionCount,\" times, but all failed, please check your network\")),this.stopReconnection();let e=new gb({code:this._isUplink?mb.UPLINK_RECONNECTION_FAILED:mb.DOWNLINK_RECONNECTION_FAILED,message:qO({key:this._isUplink?JO.UPLINK_RECONNECTION_FAILED:JO.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent(\"DISCONNECTED\"),this._emitter.emit(\"error\",e),-1;}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(\"reconnect() trying [\".concat(this._reconnectionCount,\"]\")),1):(this._log.warn(\"reconnect() signal channel is not connected, suspend reconnection until signal is connected\"),this._signalChannel.once(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\"));}},FV=nb(hb()),BV=function(e){return FV.default.parse(e);},HV=function(e){return FV.default.write(e);};function jV(e){return Object.keys(e).filter(t=>e[t]);}var GV=class extends UV{constructor(e){super(eb($C({},e),{isUplink:!1})),ob(this,\"_flag\",0),ob(this,\"role\",\"anchor\"),ob(this,\"remoteAudioTrack\"),ob(this,\"remoteVideoTrack\"),ob(this,\"remoteAuxiliaryTrack\"),ob(this,\"ssrc\",{audio:0,video:0,auxiliary:0}),ob(this,\"_isSDPExchanging\",!1),this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new RL(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new CL(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new bL(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 IO(this.flag,this.userId);}get flag(){return this._flag;}set flag(e){var t,i,n;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(n=this.remoteAuxiliaryTrack)||n.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===LN.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary;}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this);}close(e){super.close(e),this.emitConnectionStateChangedEvent(\"DISCONNECTED\"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents();}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners();}emitConnectionStateChangedEvent(e){var t,i;let n=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&n!==e&&(null==(t=this.remoteVideoTrack)||t.emit(\"connection-state-changed\",{prevState:n,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit(\"connection-state-changed\",{prevState:n,state:e})),r;}onTrack(e){let t=e.streams[0],{track:i}=e,n=t.id===WN?LN.MAIN:LN.AUXILIARY;this._log.debug(\"ontrack \".concat(n,\" \").concat(i.kind));let r=LN.AUDIO;i.kind===LN.VIDEO&&(r=n===LN.MAIN?LN.VIDEO:LN.AUXILIARY);let o=this.remoteAudioTrack;r===LN.VIDEO?o=this.remoteVideoTrack:r===LN.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i);}addRRTRLine(e){let t=e.split(\"\\r\\n\"),i=new Map();t.forEach((e,n)=>{/^a=rtcp-fb:/.test(e)&&t[n+1]&&!/^a=rtcp-fb:/.test(t[n+1])&&i.set(n+1,\"\".concat(e.match(/^a=rtcp-fb:\\d+/)[0],\" rrtr\"));});let n=[...i];for(let r=0;r{e.type===LN.VIDEO&&e.fmtp.forEach(e=>{e.config+=\";sps-pps-idr-in-keyframe=1\";});}),HV(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=BV(e);return i.media.forEach(e=>{!e.ext||(e.ext=e.ext.filter(e=>!t.includes(e.uri)));}),HV(i);}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState);}subscribe(e,t){return ab(this,null,function*(){var i,n;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===iD.NEW||(null==(n=this._peerConnection)?void 0:n.connectionState)===iD.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info(\"subscribe \".concat(t,\" \").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let t=\"subscribe_change\";Object.values(e).find(e=>!0===e)||(t=\"unsubscribe\"),yield this.sendSubscription(t,e);}else this.initialize(),yield this.connect(e);}catch(cN){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(\"\".concat(cN.message,\" \").concat(JSON.stringify(this.muteState))),new gb({code:mb.REMOTE_STREAM_NOT_EXIST,message:\"remote user \".concat(this.userId,\" unpublished stream\")})):cN;}});}unsubscribe(e){return ab(this,arguments,function(e){var t=this;let{remoteTracks:i,streamType:n}=e;return function*(){if(\"CONNECTED\"===t._currentState&&(\"main\"===n&&!t.isMainStreamSubscribed||\"auxiliary\"===n&&!t.isAuxStreamSubscribed))return void t._log.info(\"\".concat(n,\" stream already unsubscribed\"));let e=$C({},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 r=\"subscribe_change\";Object.values(e).find(e=>!0===e)||(r=\"unsubscribe\"),t._log.info(\"\".concat(\"unsubscribe\"===r?r:\"subscribe\",\" \").concat(n,\" [\").concat(jV(e),\"]\")),yield t.sendSubscription(r,e),\"unsubscribe\"===r&&(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},n=pV,r=nV.UNSUBSCRIBE_RESULT;return\"subscribe_change\"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=_V,r=nV.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:i,responseCommand:r,timeout:1e4}).then(t=>{let{data:i}=t;if(0!==i.code){let t=new gb({code:i.code,message:qO({key:JO.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t;}});}connect(){return ab(this,arguments,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(t),yield e.waitForPeerConnectionConnected();}catch(sD){throw e.closePeerConnection(!0),sD;}}();});}exchangeSDP(e){return ab(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info(\"createOffer success, sending offer\");let{type:t,sdp:i}=this._peerConnection.localDescription,n={type:t,sdp:i,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},r=yield this._signalChannel.sendWaitForResponse({command:hV,commandDesc:\"exchange sdp\",data:n,responseCommand:nV.SUBSCRIBE_RESULT,timeout:uD});if(!this._peerConnection){let e=new gb({code:mb.INVALID_OPERATION,message:qO({key:JO.CONNECTION_CLOSED})});throw this._log.warn(e),e;}yield this.onSubscribeResult(r),this._isSDPExchanging=!1;}catch(sD){throw this._isSDPExchanging=!1,sD;}});}createOffer(){return ab(this,null,function*(){let e={voiceActivityDetection:!1};Iw()&&this._sdpSemantics===hD?(this._peerConnection.addTransceiver(LN.AUDIO,{direction:MN.RECVONLY}),this._peerConnection.addTransceiver(LN.VIDEO,{direction:MN.RECVONLY}),this._peerConnection.addTransceiver(LN.VIDEO,{direction:MN.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield sw();e||(this._log.warn(\"remove h264 desc from sdp\"),t.sdp=function(e){let t=BV(e);return t.media.forEach(e=>{var t,i;if(e.type===LN.VIDEO){let n=new Set();e.rtp.forEach(e=>{let{payload:t,codec:i}=e;return\"H264\"===i&&n.add(t);}),e.fmtp.forEach(e=>{let{payload:t,config:i}=e,r=i.match(/apt=(\\d+)/);r&&r[1]&&n.has(Number(r[1]))&&n.add(t);});let r=e=>{let{payload:t}=e;return!n.has(t);};e.rtp=e.rtp.filter(r),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(r),e.fmtp=e.fmtp.filter(r),e.payloads=null==(i=e.payloads)?void 0:i.split(\" \").filter(e=>!n.has(Number(e))).join(\" \");}}),HV(t);}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=BV(e);return t.media.forEach(e=>{e.type===LN.AUDIO&&e.fmtp.forEach(e=>{e.config+=\";sprop-stereo=1;stereo=1\";});}),HV(t);}(t.sdp),this._sdpSemantics===hD&&(t.sdp=this.removeSDESDescription(t.sdp));}yield this._peerConnection.setLocalDescription(t);});}onSubscribeResult(e){return ab(this,null,function*(){let{code:t,message:i=\"\"}=e&&e.data||{},{type:n,sdp:r}=e&&e.data&&e.data.data||{};if(t===_D)throw new gb({code:mb.NOT_SUPPORTED_H264,message:qO({key:JO.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new gb({code:t,message:qO({key:JO.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug(\"accept remote answer: \".concat(r)),yield this._peerConnection.setRemoteDescription({type:n,sdp:r}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=e=>{this._emitter.emit(\"sei-message\",eb($C({},e),{userId:this.userId}));}),this.updateSSRC(r);}catch(qx){throw this._log.error(qx),qx;}});}updateSSRC(e){try{BV(e).media.forEach(e=>{if(e.ssrcs)if(e.type===LN.AUDIO){let t=e.ssrcs.find(e=>{var t;return null==(t=e.value)?void 0:t.includes(WN);});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(WN);}),i=e.ssrcs.find(e=>{var t;return null==(t=e.value)?void 0:t.includes(JN);});t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id));}});}catch(sD){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:\"\";}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:\"\";}reconnect(){return ab(this,null,function*(){if(!(sb(GV.prototype,this,\"beforeReconnect\").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn(\"reconnect() success\");}catch(sD){let t=eO(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;}},WV=GV;rb([iL(e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n{let r=e=>{this._emitter.off(\"closed\",r),n(new gb({code:mb.API_CALL_ABORTED,message:qO({key:JO.CONNECTION_ABORTED,data:e})}));};this._emitter.on(\"closed\",r),e.apply(this,i).then(t,n).finally(()=>{this._emitter.off(\"closed\",r);});});})],WV.prototype,\"subscribe\",1),rb([tL(UV.prototype.afterConnect),eL(UV.prototype.beforeConnect)],WV.prototype,\"connect\",1);var JV=WV,KV={voiceActivityDetection:!1},YV=class extends UV{constructor(e){super(eb($C({},e),{isUplink:!0})),ob(this,\"localMainAudioTrack\",null),ob(this,\"localMainVideoTrack\",null),ob(this,\"localAuxAudioTrack\",null),ob(this,\"localAuxVideoTrack\",null),ob(this,\"ssrc\",{audio:0,video:0,small:0,auxiliary:0}),ob(this,\"_isPublishingAux\",!1),ob(this,\"_publishingLocalAudioTrack\"),ob(this,\"_publishingLocalVideoTrack\"),ob(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}),ob(this,\"_audioManager\"),this._audioManager=e.audioManager;}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack);}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack);}get publishState(){var e,t,i,n;let r={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(Sw()?(r.audio=!(null==(e=o[0])||!e.track),r.bigVideo=!(null==(t=o[1])||!t.track),r.smallVideo=!(null==(i=o[2])||!i.track),r.auxVideo=!(null==(n=o[3])||!n.track)):o.forEach(e=>{e.track&&(e.track.kind===LN.AUDIO?r.audio=!0:(r.bigVideo=!0,this._room.videoManager.hasSmall&&(r.smallVideo=!0)));}));}return r;}initialize(){super.initialize(),this.installEvents();}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents();}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent(\"DISCONNECTED\");}installEvents(){this._emitter.listeners(\"connection-state-changed\").includes(this.handleConnectionStateChange)||this._emitter.on(\"connection-state-changed\",this.handleConnectionStateChange,this);}uninstallEvents(){this._emitter.off(\"connection-state-changed\",this.handleConnectionStateChange,this);}emitConnectionStateChangedEvent(e,t){var i,n,r;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit(\"connection-state-changed\",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit(\"connection-state-changed\",{prevState:o,state:e}),null==(n=this.localAuxVideoTrack)||n.emit(\"connection-state-changed\",{prevState:o,state:e}),null==(r=this._publishingLocalVideoTrack)||r.emit(\"connection-state-changed\",{prevState:o,state:e}))),s;}publish(e){return ab(this,arguments,function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,isAuxiliary:r}=e;return function*(){var e;let o;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),n&&(t._publishingLocalVideoTrack=n),t._isPublishingAux=r,n&&!r&&n.small&&(o=t._room.videoManager.smallTrack),t.sendMediaSettings(),Iw()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:n,smallTrack:o,isAuxiliary:r}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:n,smallTrack:o}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r?(n&&(t.localAuxVideoTrack=n),i&&(t.localAuxAudioTrack=i)):(n&&(t.localMainVideoTrack=n),i&&(t.localMainAudioTrack=i)),null==(e=t._sei)||e.handleEncodedStreams(),t.installTrackMuteEvents(i,n),t.sendMutedFlag();}();});}publishByTransceiver(e){return ab(this,arguments,function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,smallTrack:r,isAuxiliary:o}=e;return function*(){t._log.info(\"publish by transceiver\");let e=new MediaStream(),s=null==n?void 0:n.outMediaTrack,a=t._audioManager.mixedAudioTrack;a&&e.addTrack(a),s&&e.addTrack(s);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||LN.AUDIO,{direction:MN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?LN.VIDEO:s||LN.VIDEO,{direction:MN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(r||LN.VIDEO,{direction:MN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||LN.VIDEO,{direction:MN.SENDONLY,streams:[e]}),yield t.connect();else{let e=[];if(a&&(c[0].sender.track||e.push(0),yield c[0].sender.replaceTrack(a),yield t.setBandwidth({bandwidth:(null==i?void 0:i.profile.bitrate)||40,type:LN.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:n.profile.bitrate,type:LN.VIDEO,videoType:o?LN.AUXILIARY:LN.BIG}),e.push(i),r&&(yield c[2].sender.replaceTrack(r),yield t.setBandwidth({bandwidth:n.small.bitrate,type:LN.VIDEO,videoType:LN.SMALL}),e.push(2));}yield t.setTransceiverDirection(MN.SENDONLY,e),yield t.doPublishChange(),null==n||n.emit(\"connection-state-changed\",{prevState:\"DISCONNECTED\",state:\"CONNECTING\"}),null==n||n.emit(\"connection-state-changed\",{prevState:\"CONNECTING\",state:\"CONNECTED\"});}}();});}publishByAddTrack(e){return ab(this,arguments,function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,smallTrack:r}=e;return function*(){t._log.info(\"publish by addtrack\");let e=null==n?void 0:n.outMediaTrack,o=t._audioManager.mixedAudioTrack;if(t._peerConnection&&\"new\"!==t._peerConnection.connectionState)return o&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(n)));let s=new MediaStream();if(o&&s.addTrack(o),e&&s.addTrack(e),o&&t._peerConnection.addTrack(o,s),e&&(t._peerConnection.addTrack(e,s),r)){let e=new MediaStream();e.addTrack(r),t._peerConnection.addTrack(r,e);}yield t.connect();}();});}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i{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&&(null==e||e.off(\"mute\",this.sendMutedFlag,this),null==e||e.off(\"unmute\",this.sendMutedFlag,this));});}unpublish(e){return ab(this,arguments,function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n}=e;return function*(){if(!Sw())return i&&i.outMediaTrack&&!n&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):n&&n.outMediaTrack&&!i&&t.localMainAudioTrack?(yield t.removeTrack(n),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),void t.emitConnectionStateChangedEvent(\"DISCONNECTED\",n));let e=n&&n===t.localAuxVideoTrack,r=null==n?void 0:n.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(t._audioManager.mixedAudioTrack||(yield o[0].replaceTrack(null),s.push(0)),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),r&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=eb($C({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=eb($C({},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(MN.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),null==n||n.emit(\"connection-state-changed\",{prevState:t._currentState,state:\"DISCONNECTED\"});}();});}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return ab(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:dV,data:t,responseCommand:nV.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:uV,commandDesc:\"unpublish\",responseCommand:nV.UNPUBLISH_RESULT,enableLog:e}).catch(e=>{if(e.getCode()===mb.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:n,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Cw){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0;}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate);}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate;}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info(\"updateMediaSettings: \".concat(JSON.stringify(this._mediaSettings)));}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:yV,data:this._mediaSettings,responseCommand:nV.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{0!==e.data.code&&this._log.warn(e.data.message);}).catch(()=>{});}addTrack(e){return ab(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?LN.AUXILIARY:LN.MAIN,\" stream\")),null==(t=this._sei)||t.handleEncodedStreams(),Iw()?yield this.addTrackByTransceiver(e,i):yield this.addTrackBySender(e);});}addTrackByTransceiver(e,t){return ab(this,null,function*(){var i;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===LN.AUDIO)yield n[0].sender.replaceTrack(this._audioManager.mixedAudioTrack);else{let r=t?3:1;yield n[r].sender.replaceTrack(e.outMediaTrack),1===r&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[r].direction===MN.INACTIVE&&(yield this.setTransceiverDirection(MN.SENDONLY,[r]));}this.updateMediaSettings(),yield this.doPublishChange();});}addTrackBySender(e){return ab(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Sw()&&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 n=t.kind===LN.VIDEO?t:this._audioManager.mixedAudioTrack;if(n&&this._peerConnection.addTrack(t,new MediaStream([n])),t.kind===LN.VIDEO&&e instanceof sL&&e.small){let e=new MediaStream(),t=this._room.videoManager.smallTrack;e.addTrack(t),this._peerConnection.addTrack(t,e);}yield this.updateOffer(\"add\",t);});}isNeedToResetOfferOrder(){if(this._sdpSemantics===pD||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=BV(e);for(let i=0;it.sender&&t.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&iO(t.stop)&&(this._log.info(\"stop transceiver\"),t.stop());}removeTrack(e){return ab(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(\"is removing \".concat(e.kind,\" track from current published local \").concat(t?LN.AUXILIARY:LN.MAIN,\" stream\")),Iw()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e);});}removeTrackByTransceiver(e,t){return ab(this,null,function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===LN.AUDIO)this._audioManager.mixedAudioTrack||(yield i[0].sender.replaceTrack(null));else{let n=t?3:1;yield i[n].sender.replaceTrack(null),1===n&&e.small&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(MN.INACTIVE,[n]);}this.updateMediaSettings(),yield this.doPublishChange();});}setTransceiverDirection(e,t){return ab(this,null,function*(){if(!Ub)return;let i=!1,n=!1;this._log.info(\"setting transceiver \".concat(t.join(\",\"),\" direction to \").concat(e));let r=this._peerConnection.getTransceivers();if(t.forEach(t=>{r[t].direction!==e&&(r[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,s=this._peerConnection.remoteDescription.sdp.split(\"\\r\\n\").map(i=>{if(i.match(new RegExp(\"a=(\".concat(MN.INACTIVE,\"|\").concat(MN.RECVONLY,\"|\").concat(MN.SENDONLY,\")\")))&&o++,t.includes(o)){if(e===MN.INACTIVE&&i.includes(\"a=\".concat(MN.RECVONLY)))return n=!0,\"a=\".concat(e);if(e===MN.SENDONLY&&i.includes(\"a=\".concat(MN.INACTIVE)))return n=!0,\"a=\".concat(MN.RECVONLY);}return i;}).join(\"\\r\\n\");n&&(this._log.info(\"updating answer\"),yield this._peerConnection.setRemoteDescription({type:\"answer\",sdp:s}));});}removeTrackBySender(e){return ab(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===LN.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let t=this._peerConnection.getSenders().find(t=>t.track===e.outMediaTrack);t&&(this.removeSender(t),e.kind===LN.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(e=>{e.track&&e.track.kind===LN.VIDEO&&this.removeSender(e);})),yield this.updateOffer(\"remove\",e.outMediaTrack);});}replaceTrack(e){return ab(this,null,function*(){var t;let i,n=null==(t=this._peerConnection)?void 0:t.getSenders();if(!n||0===n.length||!e.mediaTrack)return;if(i=Iw()?e.kind===LN.AUDIO?n[0]:n[1]:n.find(t=>t.track&&t.track.kind===e.kind),!i)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(\"is replacing \".concat(e.kind,\" track on \").concat(r?LN.AUXILIARY:LN.MAIN,\" stream\")),e.kind===LN.AUDIO?yield i.replaceTrack(this._audioManager.mixedAudioTrack):e.kind===LN.VIDEO&&(r?n[3]&&(yield n[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack));});}updateOffer(e,t){return ab(this,null,function*(){try{let i=yield this._peerConnection.createOffer(KV);Ub&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,\"sendrecv\")),yield this._peerConnection.setLocalDescription(i);let n=this.updateMediaSettings(),r={action:e,trackId:t.id,kind:t.kind===LN.VIDEO?\"bigVideo\":t.kind,type:\"offer\",sdp:this._peerConnection.localDescription.sdp,constraintConfig:n,state:this.publishState};this._log.info(\"createOffer success, sending updated offer to remote server\"),this._log.debug(\"updatedOffer: \".concat(r.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:rV,data:r,responseCommand:nV.UPDATE_OFFER_RESULT,timeout:dD,commandDesc:\"update offer\"}),{code:s,message:a}=o.data;0!==s&&this.checkPublishResultCode(s,a),yield this.acceptAnswer(o.data.data),i.sdp&&this.updateSSRC(i.sdp);}catch(aN){throw this._log.error(aN),aN;}});}setBandwidth(e){return ab(this,arguments,function(e){var t=this;let{bandwidth:i,type:n,videoType:r,sdp:o}=e;return function*(){if(!Rw())return o?n===LN.VIDEO?t.updateVideoBandwidthRestriction(o,i,r):t.updateAudioBandwidthRestriction(o,i):void 0;let e=0;n===LN.VIDEO&&(e=r===LN.SMALL?2:r===LN.AUXILIARY?3:1);let s=t._peerConnection.getSenders()[e];if(s){let e=s.getParameters();(!e.encodings||0===e.encodings.length)&&(e.encodings=[{}]),e.encodings[0].maxBitrate=1e3*i;try{return yield s.setParameters(e),t._log.info(\"\".concat(r||\"\").concat(n,\" bandwidth \").concat(i,\" kbps\")),o;}catch(a){if(t._log.info(\"failed to set bandwidth by setting maxBitrate: \".concat(a)),o)return n===LN.VIDEO?t.updateVideoBandwidthRestriction(o,i,r):t.updateAudioBandwidthRestriction(o,i);}}return o;}();});}updateVideoBandwidthRestriction(e,t,i){let n=\"AS\";Ub&&(n=\"TIAS\",t*=1e3);let r=0,o=-1;return i===LN.SMALL?r=1:i===LN.AUXILIARY&&(r=2),e=e.replace(/m=video (.*)\\r\\nc=IN (.*)\\r\\n/g,e=>(o+=1,o===r?\"\".concat(e,\"b=\").concat(n,\":\").concat(t,\"\\r\\n\"):e));}updateAudioBandwidthRestriction(e,t){let i=\"AS\";return Ub&&(i=\"TIAS\",t*=1e3),e=e.replace(/m=audio (.*)\\r\\nc=IN (.*)\\r\\n/,\"m=audio $1\\r\\nc=IN $2\\r\\nb=\".concat(i,\":\").concat(t,\"\\r\\n\"));}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\\r\\n/,\"\").replace(/b=TIAS:.*\\r\\n/,\"\");}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,\"\");}connect(){return ab(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected();}catch(sN){throw this.closePeerConnection(!0),this.uninstallEvents(),sN;}});}exchangeSDP(){return ab(this,null,function*(){try{yield this.createOffer(),this._log.info(\"createOffer success, sending offer to remote server\"),yield this.doExchangeSDP();}catch(sN){throw sN;}});}createOffer(){return ab(this,null,function*(){try{let e=yield this._peerConnection.createOffer(KV);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp);}catch(sN){throw sN;}});}doExchangeSDP(){let e={command:lV,responseCommand:nV.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof cL||this.localAuxVideoTrack instanceof cL,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:n}=e.data;return 0===t?this.acceptAnswer(n):this.checkPublishResultCode(t,i);});}setSDPDirection(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:\"all\",n=BV(e);return n.media.forEach(e=>{(\"all\"===i||e.type===i)&&(e.direction=t);}),HV(n);}acceptAnswer(e){return ab(this,null,function*(){var t,i,n,r,o;try{let s;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let e=(null==(t=this._publishingLocalVideoTrack)?void 0:t.profile.bitrate)||(null==(i=this.localMainVideoTrack)?void 0:i.profile.bitrate),o=(null==(n=this._publishingLocalAudioTrack)?void 0:n.profile.bitrate)||(null==(r=this.localMainAudioTrack)?void 0:r.profile.bitrate);if(e){let t=this._isPublishingAux?LN.AUXILIARY:LN.BIG;s=yield this.setBandwidth({bandwidth:e,type:LN.VIDEO,sdp:s,videoType:t});}o&&(s=yield this.setBandwidth({bandwidth:o,type:LN.AUDIO,sdp:s}));}if(s=this.removeVideoOrientation(e.sdp),null!=(o=this._publishingLocalVideoTrack)&&o.small){let{smallStreamConfig:e}=this._room;s=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:LN.VIDEO,videoType:LN.SMALL,sdp:s});}let a={type:e.type,sdp:s};yield this._peerConnection.setRemoteDescription(a),this._log.debug(\"accepted answer: \".concat(s));}catch(s){throw this._log.error(\"failed to accept remote answer \".concat(s)),s;}});}sendMutedFlag(e){var t,i,n;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(i=this.localMainVideoTrack)||!i.muted),auxVideo:!(null==(n=this.localAuxVideoTrack)||!n.muted)};this._log.info(\"send muted state: \".concat(JSON.stringify(r))),this._signalChannel.send(cV,r);}getIsReconnecting(){return this._isReconnecting;}reconnect(){return ab(this,null,function*(){if(!(sb(YV.prototype,this,\"beforeReconnect\").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:uV,responseCommand:nV.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(sD){let t=eO(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)&&xO.emit(FO.SEND_FIRST_VIDEO_FRAME,{room:this._room});}updateSSRC(e){try{BV(e).media.forEach((e,t)=>{if(e.type===LN.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id));}else{if(this._sdpSemantics===pD&&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(sD){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:LN.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===LN.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===LN.VIDEO&&t[1]&&t[1].track)return t[1].track.id;}if(this.localMainVideoTrack&&e===LN.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id;}if(this.localAuxVideoTrack&&e===LN.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id;}return\"\";}getSSRC(){return this.ssrc;}checkPublishResultCode(e,t){if(0!==e)throw e===_D?(this._log.error(KO.NOT_SUPPORTED_H264ENCODE),new gb({code:mb.NOT_SUPPORTED_H264,message:qO({key:JO.NOT_SUPPORTED_H264ENCODE})})):new gb({code:mb.UNKNOWN,message:qO({key:JO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:nV.PUBLISH_RESULT,code:e,message:t}})});}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t);}},zV=YV;rb([iL(e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n{let r=e=>{this._emitter.off(\"closed\",r),n(new gb({code:mb.API_CALL_ABORTED,message:qO({key:JO.CONNECTION_ABORTED,data:e})}));};this._emitter.on(\"closed\",r),e.apply(this,i).then(t,n).finally(()=>{this._emitter.off(\"closed\",r);});});})],zV.prototype,\"publish\",1),rb([tL(UV.prototype.afterConnect),eL(UV.prototype.beforeConnect)],zV.prototype,\"connect\",1);var qV=zV,QV=class{constructor(e,t){this.room=e,ob(this,\"_log\"),ob(this,\"_prevReportTime\"),ob(this,\"_prevReport\",{}),ob(this,\"_prevEncoderImplementation\"),ob(this,\"_prevQualityLimitationReason\"),ob(this,\"_prevAuxQualityLimitationReason\"),ob(this,\"_prevDecoderImplementationMap\",new Map()),ob(this,\"totalBytesSent\",0),ob(this,\"totalBytesReceived\",0),ob(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 ab(this,null,function*(){let t={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},i=e.getPeerConnection(),n=e.getSSRC();if(i)try{if((this._spcStats||(yield i.getStats())).forEach(i=>{if(\"outbound-rtp\"===i.type){if((i.mediaType||i.kind)===LN.VIDEO){let r,o;if(i.ssrc===n.video?(r=LN.VIDEO,o=e.localMainVideoTrack):i.ssrc===n.small?r=LN.SMALL:i.ssrc===n.auxiliary&&(o=e.localAuxVideoTrack,r=LN.AUXILIARY),!r)return;t[r].bytesSent=i.bytesSent,t[r].packetsSent=i.packetsSent,t[r].framesEncoded=i.framesEncoded,nO(i.keyFramesEncoded)||(t[r].keyFramesEncoded=i.keyFramesEncoded),nO(i.nackCount)||(t[r].nackCount=i.nackCount),nO(i.pliCount)||(t[r].pliCount=i.pliCount),nO(i.retransmittedPacketsSent)||(t[r].retransmittedPacketsSent=i.retransmittedPacketsSent),nO(i.totalEncodeTime)||(t[r].totalEncodeTime=i.totalEncodeTime),nO(i.totalPacketSendDelay)||(t[r].totalPacketSendDelay=i.totalPacketSendDelay),i.ssrc===n.video?(!nO(i.encoderImplementation)&&this._prevEncoderImplementation!==i.encoderImplementation&&(this._log.info(\"encoderImplementation change to \".concat(i.encoderImplementation)),this._prevEncoderImplementation=i.encoderImplementation),!nO(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info(\"qualityLimitationReason change to \".concat(i.qualityLimitationReason)),this._prevQualityLimitationReason=i.qualityLimitationReason)):i.ssrc===n.auxiliary&&!nO(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevAuxQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info(\"aux qualityLimitationReason change to \".concat(i.qualityLimitationReason)),this._prevAuxQualityLimitationReason=i.qualityLimitationReason);}else t.audio.bytesSent=i.bytesSent,t.audio.packetsSent=i.packetsSent;}else\"candidate-pair\"===i.type?uw(i)&&oO(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesSent=i.bytesSent):\"media-source\"===i.type&&(i.kind===LN.AUDIO?(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0):i.kind===LN.VIDEO&&(i.trackIdentifier===e.getVideoTrackId(LN.VIDEO)?t.video.fpsCapture=i.framesPerSecond:i.trackIdentifier===e.getVideoTrackId(LN.AUXILIARY)?t.auxiliary.fpsCapture=i.framesPerSecond:t.small.fpsCapture=i.framesPerSecond));if(nO(i.audioLevel)||(t.audio.audioLevel=i.audioLevel||0),!nO(i.frameWidth)){let r=LN.SMALL;i.trackIdentifier===e.getVideoTrackId(LN.VIDEO)||i.ssrc===n.video?r=LN.VIDEO:(i.trackIdentifier===e.getVideoTrackId(LN.AUXILIARY)||i.ssrc===n.auxiliary)&&(r=LN.AUXILIARY),t[r].frameWidth=i.frameWidth,t[r].frameHeight=i.frameHeight,t[r].framesSent=i.framesSent;}}),e.localMainAudioTrack){let i=e.localMainAudioTrack.getInternalAudioLevel();t.audio.micAudioLevel=i,0===t.audio.audioLevel&&(t.audio.audioLevel=i);}this.totalBytesSent||(this.totalBytesSent+=t.audio.bytesSent+t.video.bytesSent+t.auxiliary.bytesSent);}catch(r){this._log.warn(\"failed to getStats on sender connection \".concat(r));}return t;});}getReceiverStats(e){return ab(this,null,function*(){let t={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!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:n}=e,{muteState:r,subscribeState:o}=e;(this._spcStats||(yield i.getStats())).forEach(i=>{if(\"inbound-rtp\"===i.type){if((i.mediaType||i.kind)===LN.AUDIO){if(i.ssrc!==n.audio||!r.hasAudio)return;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:o}=e;o.stat.packetsReceived=i.packetsReceived,o.stat.bytesReceived=i.bytesReceived,o.stat.packetsLost=i.packetsLost,i.jitterBufferDelay&&(o.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)),t.hasAudio=!0;}else{if(Ub&&0===i.bytesReceived)return;let s;i.ssrc===n.video&&r.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,s=e.remoteVideoTrack,r.hasSmall&&o.smallVideo&&(t.isSmallSubscribed=!0),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===n.auxiliary&&r.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,s=e.remoteAuxiliaryTrack,t.hasAuxiliary=!0),s&&(s.stat.packetsReceived=i.packetsReceived,s.stat.bytesReceived=i.bytesReceived,s.stat.packetsLost=i.packetsLost,s.stat.framesReceived=i.framesReceived,s.stat.framesDecoded=i.framesDecoded,i.jitterBufferDelay&&(s.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)));}}else\"candidate-pair\"===i.type&&uw(i)&&oO(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesReceived=i.bytesReceived);nO(i.frameWidth)||((i.trackIdentifier===e.getMainStreamVideoTrackId()||i.ssrc===n.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===n.auxiliary)&&(t.auxiliary.frameWidth=i.frameWidth,t.auxiliary.frameHeight=i.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=i.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=i.frameHeight)),nO(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),this.totalBytesReceived||(this.totalBytesReceived+=t.audio.bytesReceived+t.video.bytesReceived+t.auxiliary.bytesReceived);}catch(aN){this._log.warn(\"failed to getStats on receiver connection \".concat(aN));}return t;});}getStats(e,t){return ab(this,null,function*(){let i={},n=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:i,receiverStats:n};let t=yield e.getStats(),r=[],o=new Set([\"inbound-rtp\",\"outbound-rtp\",\"track\",\"candidate-pair\",\"media-source\"]);t.forEach(e=>o.has(e.type)&&r.push(e)),this._spcStats=r;}e&&(i=yield this.getSenderStats(e));for(let[e,r]of t){let e=yield this.getReceiverStats(r);n.push(e);}return{senderStats:i,receiverStats:n};});}getDifferenceValue(e,t){if(xP(e))return t;let i=t-e;return i<0?0:i;}prepareReport(e){let{stats:t,report:i,freezeMap:n}=e;if(!xP(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*xD,uint32_audio_energy:1e6*t.senderStats.audio.totalAudioEnergy,uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(e.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*xD);let n=[];if(t.senderStats.video.bytesSent){let e={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};n.push(e);}if(t.senderStats.small.bytesSent){let e={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};n.push(e);}if(t.senderStats.auxiliary.bytesSent){let e={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};n.push(e);}let r={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:e,msg_video_status:n,msg_network_status:r};}let{statInterval:r}=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=n.get(\"\".concat(e.userId,\"_\").concat(KN)),r=i?i.duration:0,o={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:r,uint32_video_dec_fps:e.video.framesDecoded};t.msg_video_status.push(o);}if(e.hasAuxiliary){let i=n.get(\"\".concat(e.userId,\"_\").concat(YN)),r=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:r,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;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let n=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*n/r),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate;}}let s=o.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach(e=>{let t=s.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 n=0,o=0,a=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(n=t.uint32_video_codec_bitrate,o=t.uint32_video_enc_fps,a=t.uint32_video_codec_fps);let c=this.getDifferenceValue(n,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*c/r),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)/r),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(a,e.uint32_video_codec_fps)/r),_k&&115===wk()&&0===t.uint32_video_width&&0===t.uint32_video_height&&0===t.uint32_video_codec_fps&&(e.uint32_video_codec_fps=e.uint32_video_enc_fps),nO(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),nO(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),nO(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),nO(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),nO(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/r)),nO(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/r));});let a=i.msg_down_stream_info,c=o.msg_down_stream_info;return a.forEach(e=>{let t=c.find(t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid);if(t){if(xP(e.msg_audio_status)||xP(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,n=t.msg_audio_status;i.uint32_audio_origin_lost=this.getDifferenceValue(n.uint32_audio_origin_lost,i.uint32_audio_origin_lost),i.uint32_audio_receive=this.getDifferenceValue(n.uint32_audio_receive,i.uint32_audio_receive),i.uint32_audio_receive+=i.uint32_audio_origin_lost;let o=this.getDifferenceValue(n.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*o/r),i.uint32_audio_total_bitrate=Math.round(8*o/r);}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),n=t.uint32_video_receive,o=t.uint32_video_origin_lost,s=t.uint32_video_codec_bitrate,a=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(o,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(n,e.uint32_video_receive)+e.uint32_video_origin_lost;let l=this.getDifferenceValue(s,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/r);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/r),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/r);});}}}),i;}getStatsReport(e){return ab(this,arguments,function(e){var t=this;let{uplinkConnection:i,downlinkConnections:n,freezeMap:r}=e;return function*(){let e={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:\"\",uint64_tinyid:0},msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_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,n);return\"{}\"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:r}),t._prevReportTime=Date.now(),e;}();});}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation=\"\",this._prevQualityLimitationReason=\"\",this._prevDecoderImplementationMap=new Map();}},XV=nb(cb()),ZV=class extends XV.default{constructor(e){let{signalChannel:t,room:i}=e;super(),ob(this,\"_room\"),ob(this,\"_signalChannel\"),ob(this,\"_log\"),ob(this,\"_uplinkRTT\",0),ob(this,\"_uplinkLoss\",0),ob(this,\"_downlinkRTT\",0),ob(this,\"_downlinkLoss\",0),ob(this,\"_downlinkPrevStatMap\",new Map()),ob(this,\"_downlinkLossAndRTTMap\",new Map()),ob(this,\"_interval\",-1),ob(this,\"_uplinkNetworkQuality\",0),ob(this,\"_downlinkNetworkQuality\",0),this._room=i,this._signalChannel=t,this._log=HO.createLogger({id:\"q\",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize();}get uplinkNetworkQuality(){return this._uplinkNetworkQuality;}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(\"uplink \".concat(this.uplinkNetworkQuality,\" -> \").concat(e,\", rtt: \").concat(this._uplinkRTT,\", loss: \").concat(this._uplinkLoss)),this._uplinkNetworkQuality=e;}get downlinkNetworkQuality(){return this._downlinkNetworkQuality;}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:i}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(\"downlink \".concat(this.downlinkNetworkQuality,\" -> \").concat(e,\", rtt: \").concat(t,\", loss: \").concat(i));}this._downlinkNetworkQuality=e;}initialize(){this._signalChannel.on(nV.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e);}),this._signalChannel.on(qM,this.handleSignalConnectionStateChange.bind(this)),this.start();}handleUplinkNetworkQuality(e){var t,i;if(0!==e.data.code)return;let n=e.data.data;if(n.delay&&this.updateDelay(n.delay),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this._uplinkLoss=0,void(this._uplinkRTT=0);let r=null==(i=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:i.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r))return this.uplinkNetworkQuality=6,this._uplinkLoss=0,void(this._uplinkRTT=0);let o=n.expectAudPkg+n.expectVidPkg,s=n.recvAudPkg+n.recvVidPkg,a=o-s;0===o&&0===s||(this._uplinkLoss=a<=0?0:Math.round(a/o*100),this._uplinkRTT=n.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT));}handleDownlinkNetworkQuality(){return ab(this,null,function*(){if(0===this._room.remotePublishedUserMap.size)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(e=>{var t;return(null==(t=e.getPeerConnection())?void 0:t.connectionState)===iD.CONNECTED;});if(e.filter(e=>this.isPeerConnectionDisconnected(e.getPeerConnection())).length===e.length)return void(this.downlinkNetworkQuality=6);for(let r=0;r{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e));}),0===this._downlinkLossAndRTTMap.size)return;let{rtt:i,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=i,this._downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,i);});}getStat(e){return ab(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Tw())return t;let i=e.getReceivers();try{for(let e=0;e{\"candidate-pair\"===e.type&&oO(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),\"inbound-rtp\"===e.type&&(e.mediaType===LN.AUDIO||e.mediaType===LN.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived);});return t;}catch(n){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===ZM?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state===eV&&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!==iD.DISCONNECTED&&e.connectionState!==iD.FAILED&&e.connectionState!==iD.CLOSED);}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on(\"connection-state-changed\",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0);}start(){-1===this._interval?(this._log.debug(\"start network quality calculating\"),this._interval=zw.run(wD,()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];xO.emit(FO.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(ZV.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.debug(\"stopped\"),-1!==this._interval&&(zw.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:n,audioDelay:r}=e,o=t.get(i);if(o){let e=this._room.remotePublishedUserMap.get(o);null==e||e.setDelay({videoDelay:n,audioDelay:r});}});}},$V=ZV;ob($V,\"EVENT_NETWORK_QUALITY\",\"0\");var ex=new WeakMap();function tx(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:n,onRetryFailed:r}=e;return function(e,o,s){let a=MO({retryFunction:s.value,settings:t,onError(t){let{error:n,retry:r,reject:s,retryFuncArgs:a}=t;i&&i.call(this,n,()=>{var t;null!=(t=ex.get(e))&&t.has(o)?r():s(n);},s,a);},onRetrying:(t,i)=>{var r;iO(n)&&n(t,i),null!=(r=ex.get(e))&&r.has(o)&&(ex.get(e).get(o).stopRetry=i);},onRetryFailed:r});return s.value=function(){let t=ex.get(e);for(var i=arguments.length,n=new Array(i),r=0;r{var t;return null==(t=ex.get(e))?void 0:t.delete(o);});},s;};}function ix(e){let{fnName:t,callback:i,validateArgs:n=!0}=e;return function(e,r,o){let s=o.value;return o.value=function(){for(var r,o,a=arguments.length,c=new Array(a),l=0;lt===e)){a=!1;break;}a&&(i&&i.apply(this,c),r&&r(),null==(o=ex.get(e))||o.delete(t));}return s.apply(this,c);},o;};}var nx=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:\"\",signalIp:\"\",relayIp:\"\",relayInnerIp:\"\",relayPort:0},this._apiSuccessRateMap=new Map(),this._eventMap=new Map(),this._frameWorkType=e.frameWorkType||30,this._component=e.component||0,this.connectionType=e.connectionType||1,this._language=e.language||0,this._room=e.room,this._keyPrefix=\"key_point\",this._log=HO.createLogger({id:\"kpm\",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith(\"handle\")&&iO(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,n=new Array(e),r=0;rHO.error(\"\".concat(t.name,\"() error observed \").concat(e))):o;}catch(sD){HO.error(\"\".concat(t.name,\"() error observed \").concat(sD));}};}({fn:this[e],context:this}));}),this.initData(),this.installEvents(),this._intervalId=zw.run(wD,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:rN,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:kN[GD()],uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map(),this._pathMainAudioMap=new Map(),this._pathAuxiliaryMap=new Map(),this._remoteStreamStatMap=new Map(),this._apiSuccessRateMap.clear(),Zk().then(e=>{this._basicInfo.string_os_version=tN(),e&&(this._basicInfo.string_device_name=e.model);});}addEvent(e,t){return this._eventMap.set(e,t),xO.on(e,t),this;}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener(\"unload\",this.handleUnload),this._room.once(\"banned\",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(FO.JOIN_START,this.handleJoinStart).addEvent(FO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(FO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(FO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(FO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(FO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(FO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(FO.JOIN_FAILED,this.handleJoinFailed).addEvent(FO.LEAVE_START,this.handleLeaveStart).addEvent(FO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(FO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(FO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(FO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(FO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(FO.PUBLISH_START,this.handlePublishStart).addEvent(FO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(FO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(FO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(FO.PLAY_TRACK_START,this.handlePlayStart).addEvent(FO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(FO.PLAYER_STATE_CHANGED,e=>{let{track:t,state:i,type:n}=e;!dO(t)||!this.hitTest(t.room)||\"PLAYING\"===i&&(n===LN.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t));}).addEvent(FO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(FO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(FO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(FO.REMOTE_PUBLISH_STATE_CHANGED,e=>{let{room:t,prevMuteState:i,muteState:n}=e;if(!this.hitTest(t))return;let r=i.hasAudio||i.hasVideo||i.hasSmall,o=i.hasAuxiliary,s=n.hasAudio||n.hasVideo||n.hasSmall,a=n.hasAuxiliary;!r&&s&&this.handleRemoteStreamAdded(n.userId,\"main\"),!o&&a&&this.handleRemoteStreamAdded(n.userId,\"auxiliary\");}).addEvent(FO.API_SUCCESS_RATE,this.handleAPISuccessRate).addEvent(FO.SINGLE_CONNECTION_STAT,e=>{let{room:t,stat:i}=e;this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=i.ice,this._pathJoinRoom.int32_dtls_cost=i.dtls,this._pathJoinRoom.int32_peer_connection_cost=i.peerConnection);});}uninstallEvents(){window.removeEventListener(\"unload\",this.handleUnload),this._eventMap.forEach((e,t)=>xO.off(t,e)),this._eventMap.clear();}destroy(){this.uninstallEvents(),zw.clearTask(this._intervalId);}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId});}handleJoinStart(e){this.hitTest(e.room)&&(0===this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage()),e.params&&(nO(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),nO(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),nO(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)));}handleJoinScheduleSuccess(e){let{room:t,detailCost:i}=e;if(this.hitTest(t)&&i){let{totalCost:e,local:t,dns:n,tcp:r,tls:o,request:s,response:a}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=n,this._pathJoinRoom.int32_schedule_tcp=r,this._pathJoinRoom.int32_schedule_tls=o,this._pathJoinRoom.int32_schedule_request=s,this._pathJoinRoom.int32_schedule_response=a;}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now());}handleSignalConnectionEnd(e){let{room:t,error:i}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=i instanceof gb?Number(i.getExtraCode()||i.getCode()):mb.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret));}handleJoinSendCMD(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now());}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret));}handleJoinSuccess(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo());}handleJoinFailed(e){let{room:t,error:i}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=i.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report();}));}handleReceivedPublishUserList(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[]);}handleSendFirstVideoFrame(e){let{room:t}=e;!this.hitTest(t)||0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now());}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now());}handleLeaveSuccess(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn(\"pathJoinRoom endTime is 0\"),this.report());}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now());}handleRemoteStreamAdded(e,t){var i;let n=\"\".concat(e,\"_\").concat(t);if(!this._remoteStreamStatMap.has(n)){let r={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:eb($C({},sx),{msg_user_info:new ax({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};r.statsToReport.uint32_stream_type=\"main\"===t?2:7,this._remoteStreamStatMap.set(n,r);}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:n,subscribeState:r}=e;if(!this.hitTest(t))return;let{userId:o,tinyId:s,role:a}=i,c=new ax({userId:o,tinyId:s,role:\"anchor\"===a?20:21}),l=Date.now(),d=\"\".concat(o,\"_\").concat(n),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=l),\"main\"===n?(i.muteState.hasVideo&&(r.video||r.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&&r.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&&r.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l});}handleSubscribed(e){let{room:t,remotePublishedUser:i,streamType:n}=e;if(this.hitTest(t)){let e=\"\".concat(i.userId,\"_\").concat(n),t=this._remoteStreamStatMap.get(e);t&&0===t.subscribedTime&&(t.subscribedTime=Date.now());}}handlePlayStart(e){let{track:t}=e;if(!dO(t)||!this.hitTest(t.room))return;let i=\"\".concat(t.userId,\"_\").concat(t.streamType),n=this._remoteStreamStatMap.get(i);0===(null==n?void 0:n.playStreamTime)&&(n.playStreamTime=Date.now());}handleVideoLoadedData(e){let{track:t}=e;if(!dO(t)||!this.hitTest(t.room))return;let i=\"\".concat(t.userId,\"_\").concat(t.streamType),n=this._pathMainVideoMap.get(i);n&&0===n.statsToReport.uint64_combine_first_frame_time&&(n.statsToReport.uint64_combine_first_frame_time=Date.now());}handleVideoPlaying(e){let t=\"\".concat(e.userId,\"_\").concat(e.streamType),i=Date.now(),n=this._pathMainVideoMap.get(t),r=this._remoteStreamStatMap.get(t);if(n&&(0===n.statsToReport.uint64_render_first_frame_time&&(n.statsToReport.uint64_render_first_frame_time=i),r)){let{statsToReport:e,playStreamTime:t,subscribedTime:o}=r;0===e.uint32_video_render_first&&t-o<=100&&(e.uint32_video_render_first=i-n.sendSubscribeCMDTime);}let o=this._pathAuxiliaryMap.get(t);if(o&&r){let{statsToReport:e,playStreamTime:t,subscribedTime:n}=r;0===e.uint32_video_render_first&&t-n<=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:n,videoDelay:r,audioDelay:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(n);if(s)s.totalRTT+=t,s.totalLoss+=i,r&&(s.totalVideoDelay=(s.totalVideoDelay||0)+r,s.videoDelayCount=(s.videoDelayCount||0)+1),o&&(s.totalAudioDelay=(s.totalAudioDelay||0)+o,s.audioDelayCount=(s.audioDelayCount||0)+1),s.count++;else{let e,s,a,c;r&&(s=r,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(n,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a});}}));}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:n,uint32_video_height:r}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=i,this._localStreamStat.totalVideoWidth+=n,this._localStreamStat.totalVideoHeight+=r,this._localStreamStat.videoCount++;}if(t.msg_audio_status){let{uint32_audio_level:e}=t.msg_audio_status;Math.floor(e/xD*100)>0&&(this._localStreamStat.totalAudioLevel+=e/xD,this._localStreamStat.audioLevelCount++);}i.forEach(e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:n}=e,r=t.str_identifier,o=this._room.remotePublishedUserMap.get(r);if(n.forEach(e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,n=\"\".concat(r,\"_\").concat(t?\"main\":\"auxiliary\"),s=this._remoteStreamStatMap.get(n);if(s&&(t&&(null==o?void 0:o.remoteVideoTrack.isSubscribed)||i&&(null==o?void 0:o.remoteAuxiliaryTrack))){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*XC(10,6)));}}),i){let e=\"\".concat(r,\"_\",\"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/xD*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/xD,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&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now());}handleTrackCaptureSuccess(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now());}handleTrackCaptureFailed(e){let{track:t,error:i}=e,n={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof gb?i.getExtraCode()||i.getCode():mb.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=n,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=n,this._pathJoinRoom.uint64_init_camera_end_time=Date.now());}handleAPISuccessRate(e){let{room:t,apiName:i,error:n,cost:r}=e;if(!this.hitTest(t))return;let o=cx[i],s={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(n){let e=n.extraCode||n.code||mb.UNKNOWN;Qw.logFailedEvent({eventType:i,code:e,userId:this._room.userId,error:n});let t={int32_error_code:e,error_count:1};s.msg_error_code.push(t);}else oO(r)&&(Qw.logSuccessEvent({eventType:i,userId:this._room.userId}),s.uint32_avg_value=r,s.uint32_max_value=r,s.uint32_success_count=1);let a=this._apiSuccessRateMap.get(o);a?(a.uint32_success_count+s.uint32_success_count>0&&(a.uint32_avg_value=(a.uint32_avg_value*a.uint32_success_count+s.uint32_avg_value)/(a.uint32_success_count+s.uint32_success_count)),a.uint32_max_value=Math.max(a.uint32_max_value,s.uint32_max_value),a.uint32_request_count+=1,a.uint32_success_count=a.uint32_success_count+s.uint32_success_count,s.msg_error_code.forEach(e=>{let t=a.msg_error_code.find(t=>t.int32_error_code===e.int32_error_code);t?t.error_count+=1:a.msg_error_code.push(e);})):this._apiSuccessRateMap.set(o,s);}hasVideoFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&UN)>=0;}hasAudioFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&HN)>=0;}hasAuxFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&BN)>=0;}hitTest(e){return e===this._room;}checkStorage(){return ab(this,null,function*(){try{let e=GO.getItem(this._storageKey);e&&(yield this.upload(e),GO.deleteItem(this._storageKey));}catch(HL){this._log.warn(HL);}});}setStorage(){this.prepareReport();let e=this.getReportData();0!==e.msg_path_enter_room.uint64_start_time&&GO.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,n=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(n){let{totalLoss:t,count:i,audioDelayCount:r,videoDelayCount:o,totalAudioDelay:s,totalVideoDelay:a}=n;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),r&&s&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(s/r),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/o));}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:r}=this._room;r&&(e.statsToReport.uint32_audio_play_time=r.getDuration(t,LN.AUDIO),e.statsToReport.uint32_video_play_time=r.getDuration(t,LN.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,ox);let{badCaseDetector:o}=this._room,{dataFreeze:s,count:a}=o.getDataFreezeDuration(t),{renderFreeze:c}=o.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=a,e.statsToReport.uint32_video_block_time=Math.min(s,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),o.isBlackStream(t)&&0===e.statsToReport.uint32_video_avg_fps?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0,(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>ox&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+ox):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>ox&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+ox):this._pathMainVideoMap.delete(t);}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>ox&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+ox);}getReportData(){return{uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new ax({userId:this._room.userId,tinyId:this._room.tinyId,role:\"anchor\"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:AO(this._signalInfo.relayIp),uint32_client_ip:AO(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:AO(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,msg_function_request_stats:[...this._apiSuccessRateMap.values()]};}report(){try{this.prepareReport();let e=this.getReportData();this.upload(e),GO.deleteItem(this._storageKey),this.initData();}catch(HL){this._log.warn(HL);}}upload(e){if(Yk||0===e.msg_path_enter_room.uint64_start_time||[_N,mN,fN].findIndex(e=>e===location.host)>=0)return;let t=Number(this._room.sdkAppId),i=BD(t,yN.KEY_POINT),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(i,JSON.stringify(e))),n||PO({url:i,body:JSON.stringify(e)});}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e;}};rb([tx({settings:{timeout:500,retries:3}})],nx.prototype,\"upload\",1);var rx,ox=5e3,sx={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},ax=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role;}},cx=((rx=cx||{})[rx.enterRoom=50001]=\"enterRoom\",rx[rx.exitRoom=50002]=\"exitRoom\",rx[rx.switchRole=50003]=\"switchRole\",rx[rx.destroy=50004]=\"destroy\",rx[rx.startLocalAudio=50005]=\"startLocalAudio\",rx[rx.updateLocalAudio=50006]=\"updateLocalAudio\",rx[rx.stopLocalAudio=50007]=\"stopLocalAudio\",rx[rx.startLocalVideo=50008]=\"startLocalVideo\",rx[rx.updateLocalVideo=50009]=\"updateLocalVideo\",rx[rx.stopLocalVideo=50010]=\"stopLocalVideo\",rx[rx.startScreenShare=50011]=\"startScreenShare\",rx[rx.updateScreenShare=50012]=\"updateScreenShare\",rx[rx.stopScreenShare=50013]=\"stopScreenShare\",rx[rx.enableAudioVolumeEvaluation=50014]=\"enableAudioVolumeEvaluation\",rx[rx.startRemoteVideo=50015]=\"startRemoteVideo\",rx[rx.updateRemoteVideo=50016]=\"updateRemoteVideo\",rx[rx.stopRemoteVideo=50017]=\"stopRemoteVideo\",rx[rx.muteRemoteAudio=50018]=\"muteRemoteAudio\",rx[rx.setRemoteAudioVolume=50019]=\"setRemoteAudioVolume\",rx[rx.startMixTranscode=50020]=\"startMixTranscode\",rx[rx.stopMixTranscode=50021]=\"stopMixTranscode\",rx[rx.startPublishCDNStream=50022]=\"startPublishCDNStream\",rx[rx.stopPublishCDNStream=50023]=\"stopPublishCDNStream\",rx[rx.PeerConnectionConnect=50024]=\"PeerConnectionConnect\",rx[rx.PeerConnectionReconnect=50025]=\"PeerConnectionReconnect\",rx[rx.WebsocketConnect=50026]=\"WebsocketConnect\",rx[rx.WebsocketReconnect=50027]=\"WebsocketReconnect\",rx[rx.schedule=50028]=\"schedule\",rx[rx.SPCConnect=50029]=\"SPCConnect\",rx[rx.SPCReconnect=50030]=\"SPCReconnect\",rx[rx.videoCtxGl=50031]=\"videoCtxGl\",rx[rx.videoCtxGlRecover=50032]=\"videoCtxGlRecover\",rx[rx.videoCtx2d=50033]=\"videoCtx2d\",rx[rx[\"CDNStreaming.startPlugin\"]=50034]=\"CDNStreaming.startPlugin\",rx[rx[\"CDNStreaming.updatePlugin\"]=50035]=\"CDNStreaming.updatePlugin\",rx[rx[\"CDNStreaming.stopPlugin\"]=50036]=\"CDNStreaming.stopPlugin\",rx[rx[\"AIDenoiser.startPlugin\"]=50037]=\"AIDenoiser.startPlugin\",rx[rx[\"AIDenoiser.updatePlugin\"]=50038]=\"AIDenoiser.updatePlugin\",rx[rx[\"AIDenoiser.stopPlugin\"]=50039]=\"AIDenoiser.stopPlugin\",rx[rx[\"AudioMixer.startPlugin\"]=50040]=\"AudioMixer.startPlugin\",rx[rx[\"AudioMixer.updatePlugin\"]=50041]=\"AudioMixer.updatePlugin\",rx[rx[\"AudioMixer.stopPlugin\"]=50042]=\"AudioMixer.stopPlugin\",rx),lx=nx,dx=class{constructor(){ob(this,\"_startTime\"),ob(this,\"_endTime\"),this._startTime=0,this._endTime=0,this.start();}start(){0===this._startTime&&(this._startTime=fO());}stop(){0===this._endTime&&(this._endTime=fO());}getDuration(){return 0===this._endTime?fO()-this._startTime:this._endTime-this._startTime;}get endTime(){return this._endTime;}},ux=class{constructor(e){ob(this,\"_room\",null),ob(this,\"_durationMap\"),ob(this,\"_eventMap\",new Map()),this._room=e.room,this._durationMap=new Map(),this.installEvents();}installEvents(){this._eventMap.set(FO.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(FO.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(FO.REMOTE_PUBLISH_STATE_CHANGED,e=>{let{room:t,prevMuteState:i,muteState:n}=e;var r;let{userId:o}=n;if(!this.hitTest(t))return;i.hasAudio&&!n.hasAudio&&this.stopDurationItem(\"\".concat(o,\"_\",\"main\"),LN.AUDIO),i.hasVideo&&!n.hasVideo&&this.stopDurationItem(\"\".concat(o,\"_\",\"main\"),LN.VIDEO),i.hasAuxiliary&&!n.hasAuxiliary&&this.stopDurationItem(\"\".concat(o,\"_\",\"auxiliary\"),LN.VIDEO);let s=null==(r=this._room)?void 0:r.remotePublishedUserMap.get(o);!s||(!i.hasAudio&&n.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,LN.AUDIO,\"main\"),!i.hasVideo&&n.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,LN.VIDEO,\"main\"),!i.hasAuxiliary&&n.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,LN.VIDEO,\"auxiliary\"));}),this._eventMap.forEach((e,t)=>xO.on(t,e,this));}uninstallEvents(){this._eventMap.forEach((e,t)=>xO.off(t,e,this)),this._eventMap.clear();}handleSubscribed(e){let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o=\"\".concat(r,\"_\").concat(i);if(n.muteState.hasAudio&&\"main\"===i)if(n.remoteAudioTrack.isSubscribed){let e=new dx(),t=this._durationMap.get(o);t?this.isRecording(t.audio)||t.audio.push(e):this._durationMap.set(o,{userId:r,type:i,audio:[e],video:[]});}else this.stopDurationItem(o,LN.AUDIO);if(n.muteState.hasVideo||n.muteState.hasAuxiliary)if(n.remoteVideoTrack.isSubscribed||n.remoteAuxiliaryTrack.isSubscribed){let e=new dx(),t=this._durationMap.get(o);t?this.isRecording(t.video)||t.video.push(e):this._durationMap.set(o,{userId:r,type:i,audio:[],video:[e]});}else this.stopDurationItem(o,LN.VIDEO);}handleStreamStopped(e){let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o=\"\".concat(r,\"_\").concat(i);this.stopDurationItem(o,LN.AUDIO),this.stopDurationItem(o,LN.VIDEO);}isRecording(e){return e.findIndex(e=>0===e.endTime)>=0;}addDuractionItem(e,t,i){let n=\"\".concat(e,\"_\").concat(i),r=new dx(),o=this._durationMap.get(n);o?this.isRecording(o[t])||o[t].push(r):this._durationMap.set(n,{userId:e,type:i,audio:t===LN.AUDIO?[r]:[],video:t===LN.AUDIO?[]:[r]});}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();}},hx=class{constructor(e){ob(this,\"_room\"),ob(this,\"_renderFreezeMap\",new Map()),ob(this,\"_isVideoPlayingEventFiredMap\",new Map()),ob(this,\"_dataFreezeMap\",new Map()),ob(this,\"_monitorFreezeData\",new Map()),ob(this,\"_eventMap\",new Map()),this._room=e.room,this.installEvents();}installEvents(){this._eventMap.set(FO.LEAVE_SUCCESS,e=>{let{room:t}=e;this.hitTest(t)&&this.stop();}).set(FO.PLAY_TRACK_START,this.onPlayTrackStart).set(FO.UNSUBSCRIBE_SUCCESS,e=>{let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o=\"\".concat(r,\"_\").concat(i);this.stopDataFreeze({key:o,userId:r,type:i});}).set(FO.REMOTE_PUBLISH_STATE_CHANGED,e=>{let{room:t,prevMuteState:i,muteState:n}=e;if(!this.hitTest(t))return;let{userId:r}=n;if(i.hasVideo&&!n.hasVideo){let e=\"main\",t=\"\".concat(n.userId,\"_\").concat(e);this.stopDataFreeze({key:t,userId:r,type:e});}if(i.hasAuxiliary&&!n.hasAuxiliary){let e=\"auxiliary\",t=\"\".concat(n.userId,\"_\").concat(e);this.stopDataFreeze({key:t,userId:r,type:e});}}).set(FO.PLAYER_STATE_CHANGED,e=>{let{track:t,state:i,reason:n,type:r}=e;if(dO(t)&&this.hitTest(t.room)&&r===LN.VIDEO){if(\"PLAYING\"===i){let e=\"\".concat(t.userId,\"_\").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0);}n===LN.MUTE?this.onVideoTrackMuted(t):n===LN.UNMUTE&&this.onVideoTrackUnmuted(t);}}).set(FO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((e,t)=>xO.on(t,e,this));}uninstallEvents(){this._eventMap.forEach((e,t)=>xO.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,n=\"\".concat(t,\"_\").concat(i),r=this._dataFreezeMap.get(n),o=new dx();r?r.durationItemList.push(o):this._dataFreezeMap.set(n,{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,n=\"\".concat(t,\"_\").concat(i);this.stopDataFreeze({key:n,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:n}=t;e.msg_video_status.forEach(e=>{2===e.uint32_video_stream_type&&n.hasVideo&&!n.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:\"main\"}),7===e.uint32_video_stream_type&&n.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:\"auxiliary\"});});});}stopDataFreeze(e){let{key:t,userId:i,type:n}=e,r=this._dataFreezeMap.get(t);if(!r||!r.isFreezing())return;let o=r.durationItemList[r.durationItemList.length-1];o.stop();let s=o.getDuration();s>fD?this._monitorFreezeData.set(t,{userId:i,type:n,duration:s}):r.durationItemList.pop();}getTotalDuration(e){return e.reduce((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3);},0);}handleRenderFreeze(e){return ab(this,arguments,function(e){var t=this;let{userId:i,fps:n,type:r}=e;return function*(){let e=\"\".concat(i,\"_\").concat(r),o=t._renderFreezeMap.get(e);if(n<=2){let n=fO();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:n,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(e,{userId:i,type:r,isFreeze:!0,freezeTimeline:[{startTime:n,endTime:0}],renderFreezeTotal:0});}else if(o&&o.isFreeze){o.isFreeze=!1;let e=o.freezeTimeline.pop();if(e){e.endTime=fO();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t);}}}();});}onPlayTrackStart(e){let{track:t}=e;if(!dO(t)||!this.hitTest(t.room)||t.kind!==LN.VIDEO||t.hasFlag)return;let i=\"\".concat(t.userId,\"_\").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(i)||this._isVideoPlayingEventFiredMap.set(i,!1);}getDataFreezeDuration(e){let t={dataFreeze:0,count:0},i=this._dataFreezeMap.get(e);if(i){if(i.isFreezing()){let e=i.durationItemList[i.durationItemList.length-1];e.stop(),e.getDuration(){let o=null;mO([Ix(e=>t.count[0]=e+1,e=>{let{error:i,retry:n}=e;t.msg[0]=i.message,o||n();})(Ex(i,LN.MAIN),e,{get timeout(){return 1e3*$D(2+t.count[0]);}}),Ix(e=>t.count[1]=e+1,e=>{let{error:i,retry:n}=e;t.msg[1]=i.message,o||n();})(Ex(i,LN.BACKUP),e,{get timeout(){return 1e3*$D(2+t.count[1]);}})]).then(e=>{o=e,n(o);}).catch(r);});}(c,e,i);d.config&&(d.config.loggerDomain&&pN(d.config.loggerDomain),sO(d.config.scheduleCache)&&mx(!d.config.scheduleCache)),e.delta=fO()-l;let u=function(e,t,i){let n=performance.getEntriesByType(\"resource\"),r=Ex(e,LN.MAIN),o=Ex(e,LN.BACKUP),s={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};for(let a of n)if(a.startTime>=i&&(a.name===r||a.name===o)&&a.transferSize>0){let e=a.name===r?LN.MAIN:LN.BACKUP,i=Math.round(a.duration),n=Math.round(a.domainLookupStart-a.startTime),o=Math.round(a.domainLookupEnd-a.domainLookupStart),c=Math.round(a.requestStart-a.secureConnectionStart),l=Math.round(a.secureConnectionStart-a.connectStart),d=Math.round(a.responseStart-a.requestStart),u=Math.round(a.responseEnd-a.responseStart),h=[n,o,c,l,d,u];Qw.uploadEvent({log:\"stat-schedule-net:\".concat(i,\"(\").concat(h.join(\"->\"),\") \").concat(e),userId:t}),s=eb($C({},s),{totalCost:i,local:n,dns:o,tcp:l,tls:c,request:d,response:u});break;}return s;}(Number(i),t,l);return px=d,{isCached:!1,result:d,detailCost:u};}catch(c){let e=cO(c)?c[0]:c,t=oO(e.code)?e.code:0,i=\"schedule failed\".concat(e.message?\": \".concat(e.message):\"\"),n=new gb({code:mb.SCHEDULE_FAILED,extraCode:t,message:qO({key:JO.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw HO.error(n),n;}}();});}xO.on(\"28\",()=>mx(!0)),xO.on(\"63\",()=>mx(!0)),xO.on(\"84\",()=>mx(!0)),xO.on(\"201\",e=>{\"RECONNECTING\"===e.state&&mx(!0);}),xO.on(\"202\",e=>{\"RECONNECTING\"===e.state&&mx(!0);});var gx={main:\"\",backup:\"\"};function Tx(e){cO(e)?(gx.main=e[0],gx.backup=e[1]):gx.main=e;}function Ex(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:LN.MAIN;return t=FD(e)?i===LN.MAIN?ID.MAIN_OVERSEA:ID.BACKUP_OVERSEA:i===LN.MAIN?ID.MAIN:ID.BACKUP,\"https://\".concat(gx[i]||t,\"/api/v1/config\");}function Sx(e,t,i){return new Promise((n,r)=>{PO({url:e,body:t,timeout:i.timeout}).then(e=>{0===e.data.code?n(e.data.data):r({code:e.data.code,message:e.data.msg});}).catch(r);});}var Ix=(e,t)=>MO({retryFunction:Sx,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var vx=nb(cb(),1),yx=[-1,-1,-1,1,1,-1,1,1],Ax=[0,0,0,1,1,0,1,1],Rx=class extends Gw{constructor(e,t){super(),this.context=e,ob(this,\"name\"),ob(this,\"input\"),ob(this,\"output\"),ob(this,\"texture\"),ob(this,\"image\"),ob(this,\"ctx2d\",null),ob(this,\"fbo\"),ob(this,\"width\",0),ob(this,\"height\",0),ob(this,\"x\",0),ob(this,\"y\",0),ob(this,\"program\"),ob(this,\"vertexShader\"),ob(this,\"fragmentShader\"),ob(this,\"totalFrames\",0),ob(this,\"dropFrames\",0),ob(this,\"matchInputSize\",!0),ob(this,\"texCoordBuffer\"),ob(this,\"positionBuffer\"),ob(this,\"lastInfo\",{timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),ob(this,\"_canvas\",null),this.context.once(\"disconnect\",()=>{\"closed\"!==this.state&&this.close();}),this.name=t.name,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height;let i=e._gl;if(i)try{!1!==t.createTexture&&(this.texture=i.createTexture()),this.texCoordBuffer=this.createBuffer(Ax),this.positionBuffer=this.createBuffer(yx),this.useTexture(()=>{i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE);}),t.useFbo&&(this.fbo=i.createFramebuffer(),this.useBufferFrame(()=>{this.useTexture(()=>{i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.texture,0);});})),t.useDefaultProgram&&(this.program=this.context.defaultProgam),t.vertexShaderSource&&t.fragmentShaderSource&&(this.vertexShader=e.createShader(i.VERTEX_SHADER,t.vertexShaderSource),this.fragmentShader=e.createShader(i.FRAGMENT_SHADER,t.fragmentShaderSource),this.program=e.createProgram(this.vertexShader,this.fragmentShader));}catch(n){this.context.destroy(\"\".concat(this.name,\" init failed\"),n);}else if(e.ctx2d&&t.create2d){let e=document.createElement(\"canvas\"),t=\"function\"==typeof e.transferControlToOffscreen?e.transferControlToOffscreen():e;t.width=this.width,t.height=this.height,this.ctx2d=t.getContext(\"2d\"),this.image=t,this._canvas=t;}}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;ni.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null)),this.output&&this.output.matchInputSize&&this.output.resize(e,t));}draw2d(e,t,i,n,r){return!(!this.ctx2d||!e)&&(e instanceof ImageData?this.ctx2d.putImageData(e,t,i):this.ctx2d.drawImage(e,t,i,n,r),!0);}getInfo(){var e;let{totalFrames:t,x:i,y:n,width:r,height:o}=this,s=Date.now(),a=(t-this.lastInfo.totalFrames)/((s-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:t,x:i,y:n,width:r,height:o,timestamp:s,fps:a},$C({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo);}};rb([Bw(Gw.INIT,\"connected\")],Rx.prototype,\"connect\",1),rb([Bw(\"connected\",Gw.INIT,{ignoreError:!0})],Rx.prototype,\"disconnect\",1),rb([Bw([],\"closed\")],Rx.prototype,\"close\",1);var Cx=[0,1,0,0,1,1,1,0],bx=class extends Rx{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:\"destination\"},t)),ob(this,\"_intervalId\",0),ob(this,\"_sequence\",0),e._gl?this.setTexBuffer(Cx):e.ctx2d&&(this.ctx2d=e.ctx2d);}start(e){this._intervalId=zw.run(\"intervalInWorker\",()=>{e!==this.context.frameRate&&(zw.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++);let t=this.context._gl;t&&t.getError()!==t.NO_ERROR&&this.context.destroy(\"\".concat(this.name,\" req \").concat(this._sequence,\" render \").concat(this.totalFrames,\" faild \").concat(t.getError()));},{fps:this.context.frameRate});}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useInputTexture(e=>{this.setAttributes({a_position:this.positionBuffer,a_texCoord:this.texCoordBuffer}),e.drawArrays(e.TRIANGLE_STRIP,0,4);}),!0);}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n{let t=()=>this._videoTrack.removeEventListener(e,i),i=()=>{t(),this.context.destroy(\"video track \".concat(e));};this.once(\"closed\",t),this._videoTrack.addEventListener(e,i);};e._gl&&i(\"mute\"),i(\"ended\");}get videoTrack(){return this._videoTrack;}close(){super.close(),this._videoTrack.stop();}resize(e,t){super.resize(e,t),this.context.setSize(e,t);}},Nx=class extends kx{constructor(e,t){super(e,{name:\"smallDestination\"}),this.resolution=t;}resize(e,t){let i,n=e*t,r=this.resolution.width*this.resolution.height;HO.info(\"big res: \".concat(e,\"*\").concat(t,\" small res: \").concat(this.resolution.width,\"*\").concat(this.resolution.height,\" \")),n>r?i=n/r:(HO.warn(\"Small stream resolution is not smaller than big stream, which is invalid. big: \".concat(e,\" * \").concat(t,\" small: \").concat(this.resolution.width,\" * \").concat(this.resolution.height)),i=n/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i));}},Dx=class extends Rx{constructor(e,t){super(e,{name:\"imageSource\"}),this.image=t,ob(this,\"_image\"),ob(this,\"_totalFrames\",0);}_render(e,t){let{width:i,height:n}=this;if(this.image instanceof HTMLVideoElement){if(iO(this.image.getVideoPlaybackQuality)&&!Fk){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames;}({videoWidth:i,videoHeight:n}=this.image);}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if(({width:i,height:n}=this.image),this.image!==this._image)this._image=this.image;else if(i===this.width&&n===this.height)return!1;}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&(({width:i,height:n}=this.image),this._image=this.image);return this.width===i&&this.height===n&&this.totalFrames?t&&this.useTexture(e=>{e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,this.image);}):(t&&this.useTexture(e=>{e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image);}),this.resize(i,n)),!0;}render(e){return this._render(e,!0);}render2d(e){return this._render(e,!1);}},Ox=class extends Dx{constructor(e,t){super(e,document.createElement(\"video\")),this._videoTrack=t,ob(this,\"_mediaStream\"),this.name=\"videoTrackSource\",this._mediaStream=new MediaStream([t]),this.image.srcObject=this._mediaStream,this.image.play();}replaceTrack(e){var t,i;this._videoTrack!==e&&(null==(t=this._mediaStream)||t.removeTrack(this._videoTrack),this._videoTrack=e,null==(i=this._mediaStream)||i.addTrack(this._videoTrack),this.image.play());}close(){super.close(),delete this._mediaStream,this.image.srcObject=null;}},wx=class extends Gw{constructor(e){super(),ob(this,\"frameRate\"),ob(this,\"_canvas\"),ob(this,\"_gl\"),ob(this,\"ctx2d\"),ob(this,\"defaultProgam\"),ob(this,\"log\"),ob(this,\"hasAlpha\",!1),ob(this,\"glFaild\",!1),ob(this,\"name\"),this.name=e.name,this.log=e.logger.createChild({id:\"vc-\".concat(this.name)}),this.frameRate=e.frameRate;}create(e){if(this.glFaild=!1,this.hasAlpha=e.alpha,this._canvas=document.createElement(\"canvas\"),e.use2d)return this.ctx2d=this._canvas.getContext(\"2d\",{alpha:e.alpha}),void this.log.info(\"video context created use 2d\");let t=this._canvas.getContext(\"webgl\",{alpha:e.alpha});if(t){this._gl=t;try{let e=this.createShader(t.VERTEX_SHADER,\"\\n// 顶点着色器\\nattribute vec4 a_position;\\nattribute vec2 a_texCoord;\\nvarying vec2 v_texCoord;\\n\\nvoid main() {\\n gl_Position = a_position;\\n v_texCoord = a_texCoord;\\n}\\n\"),i=this.createShader(t.FRAGMENT_SHADER,\"\\n// 片元着色器\\nprecision mediump float;\\nvarying vec2 v_texCoord;\\nuniform sampler2D u_texture;\\n\\nvoid main() {\\n gl_FragColor = texture2D(u_texture, v_texCoord);\\n} \");this.defaultProgam=this.createProgram(e,i),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this._canvas.addEventListener(\"webglcontextlost\",()=>{this.destroy(\"webglcontextlost\");}),this.log.info(\"video context created use webgl\");}catch(aN){return this.log.warn(\"video context create faild use webgl\"),aN;}}else this.ctx2d=this._canvas.getContext(\"2d\"),this.ctx2d&&this.log.info(\"video context created downgrade to 2d\");!this.ctx2d&&!this._gl&&delete this._canvas;}get available(){return!!this._canvas;}createVideoTrackSource(e){return new Ox(this,e);}createVideoTrackDestination(e){return new kx(this,e);}createVideoImageSource(e){return new Dx(this,e);}set width(e){var t;null==(t=this._gl)||t.viewport(0,0,e,this.height),this._canvas&&(this._canvas.width=e);}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0;}set height(e){var t;null==(t=this._gl)||t.viewport(0,0,this.width,e),this._canvas&&(this._canvas.height=e);}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0;}setSize(e,t){var i;null==(i=this._gl)||i.viewport(0,0,e,t),this._canvas&&(this._canvas.width=e,this._canvas.height=t);}disconnect(){this.emit(\"disconnect\");}destroy(e,t){var i;return this.disconnect(),this.log.info(\"video context destroy \".concat(e?\":\".concat(e):\"\")),null==(i=this._gl)||i.deleteProgram(this.defaultProgam),delete this._gl,delete this.ctx2d,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),[e,t];}createShader(e,t){let i=this._gl,n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n;}createProgram(e,t){let i=this._gl,n=i.createProgram();return i.attachShader(n,e),i.attachShader(n,t),i.linkProgram(n),n;}useTexture(e,t,i){let n=this._gl;n.activeTexture(n.TEXTURE0+(i||0)),n.bindTexture(n.TEXTURE_2D,e),t(n),n.bindTexture(n.TEXTURE_2D,null);}};rb([Bw(Gw.INIT,\"created\")],wx.prototype,\"create\",1),rb([Bw(\"created\",Gw.INIT,{ignoreError:!0,success(e){e[0]&&(this.glFaild=!0,this.emit(\"unavailable\",...e)),this.removeAllListeners();}})],wx.prototype,\"destroy\",1);var Px=[1,0,1,1,0,0,0,1],Lx=class extends Rx{constructor(e){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:\"mirror\"}),e._gl)try{this.setTexBuffer(Px);}catch(sN){e.destroy(\"mirror set texCoords faild\",sN);}else this.ctx2d&&setTimeout(e=>{e.scale(-1,1),e.translate(-this.width,0);},0,this.ctx2d);}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(()=>{this.useInputTexture(e=>{this.setAttributes({a_position:this.positionBuffer,a_texCoord:this.texCoordBuffer}),e.drawArrays(e.TRIANGLE_STRIP,0,4);});}),!0);}},Mx=class{constructor(e,t){this.node=e,this.layout=t,ob(this,\"positionBuffer\");}get x(){return this.layout.x||this.node.x;}get y(){return this.layout.y||this.node.y;}get width(){return this.layout.width||this.node.width;}get height(){return this.layout.height||this.node.height;}get right(){return this.x+this.width;}get bottom(){return this.y+this.height;}},Vx=class extends Rx{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:\"mix\",create2d:!0}),ob(this,\"inputs\",[]);}addInput(e,t){if(this.inputs[t.zIndex])throw new Error(\"input already exists\");let i=new Mx(e,t);this.inputs[t.zIndex]=i;}resize(e,t){let i=this.inputs.reduce((e,t)=>t?Object.assign(e,{width:Math.max(e.width,t.right),height:Math.max(e.height,t.bottom)}):e,{width:0,height:0});super.resize(i.width,i.height),this.context._gl&&this.inputs.forEach(e=>{if(e){let t=this.layout2texCoords(e);e.positionBuffer?this.changeBufferData(e.positionBuffer,t):e.positionBuffer=this.createBuffer(t);}});}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n(null==t?void 0:t.node)===e)]=void 0;}render(e){let t=this.context._gl;return!(this.inputs.reduce((t,i)=>(!i||!i.node.requestFrame(e))&&t,!0)||!t)&&(this.useProgram(),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),this.setAttributes({a_texCoord:this.texCoordBuffer}),this.useBufferFrame(()=>{for(let e=0;e{this.setAttributes({a_position:t.positionBuffer}),e.drawArrays(e.TRIANGLE_STRIP,0,4);});}}),!0);}render2d(e){if(!this.inputs.reduce((t,i)=>(!i||!i.node.requestFrame(e))&&t,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let e=0;e>0;return this.lastInfo={totalFrames:e,x:t,y:i,width:n,height:r,timestamp:o,fps:s},$C({parent:this.inputs.filter(e=>e).map(e=>e.node.getInfo())},this.lastInfo);}close(){super.close(),this.inputs.forEach(e=>{var t;if(e&&(null==(t=e.node)||t.disconnect(),e.positionBuffer&&this.context._gl))try{this.context._gl.deleteBuffer(e.positionBuffer);}catch(aN){}});}},xx=class extends vx.EventEmitter{constructor(e){let{room:t}=e;super(),ob(this,\"videoContext\"),ob(this,\"destination\"),ob(this,\"smallVideoContext\"),ob(this,\"smallDestination\"),ob(this,\"smallTrackSource\"),ob(this,\"smallImageSource\"),ob(this,\"_isMirror\",!1),ob(this,\"cameraTrack\"),ob(this,\"cameraNode\"),ob(this,\"waterMarkNode\"),ob(this,\"mirrorNode\"),ob(this,\"mixNode\"),ob(this,\"screenTrack\"),ob(this,\"screenNode\"),ob(this,\"_isMixScreen\",!1),ob(this,\"_hasWaterMark\",!1),ob(this,\"_log\"),ob(this,\"_checkId\",0),ob(this,\"_room\"),ob(this,\"_use2d\",!0),ob(this,\"_waterMarkOption\"),ob(this,\"_isOpenVirtualBackground\",!1),ob(this,\"_virtualBackgroundTrack\"),ob(this,\"virtualBackgroundInstance\"),this._room=t,this._log=HO.createLogger({id:\"vm\",userId:t.userId,sdkAppId:t.sdkAppId}),this.videoContext=new wx({frameRate:15,logger:this._log,name:\"m\"}),this.videoContext.on(\"unavailable\",(e,t)=>{this.emit(\"error\",{reason:e,error:t}),this._log.warn(\"video context unavailable\",e,t,\"glFaild:\".concat(this.videoContext.glFaild)),xO.emit(\"262\",{room:this._room,apiName:\"videoCtxGl\",error:t||new Error(e)}),this.update();}),this.smallVideoContext=new wx({frameRate:15,logger:this._log,name:\"s\"}),this.enablePrintDetail();}get renderMode(){return this._use2d?\"2d\":\"webgl\";}set renderMode(e){let t=\"2d\"===e;this._use2d!==t&&(this._use2d=t,this.videoContext&&(this.clear(),this.videoContext.destroy(),this.videoContext.create({alpha:this._hasWaterMark,use2d:this._use2d}),this.update()));}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=zw.run(LD,()=>{this.destination&&this._log.debug(this.destination.getInfo());},{delay:e});}destroy(){this.videoContext.destroy(),this.smallVideoContext.destroy(),zw.clearTask(this._checkId);}get active(){return(Jk&&Wk||this._isMixScreen||this._isMirror||this._hasWaterMark)&&this.checkOrCreateVideoContext();}sendCreateResult(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:\"videoCtxGl\",t=arguments.length>1?arguments[1]:void 0;xO.emit(\"262\",{room:this._room,apiName:e,error:t});}checkOrCreateVideoContext(){if(this.videoContext.available){if(this.videoContext.hasAlpha||!this._hasWaterMark)return!0;this.clear(),this.videoContext.destroy();}else this.videoContext.glFaild&&(this.clear(),this._use2d=!0);let e=this.videoContext.create({alpha:this._hasWaterMark,use2d:this._use2d});return this.videoContext._gl?this.sendCreateResult():(this._use2d||(this.emit(\"error\",{reason:\"create\",error:e}),this.sendCreateResult(\"videoCtxGl\",e)),this.sendCreateResult(\"videoCtx2d\",this.videoContext.ctx2d?void 0:new Error(\"create 2d context failed\"))),this.videoContext.available;}get smallTrack(){return this.smallDestination.videoTrack;}get hasSmall(){return!!this.smallTrackSource||!!this.smallImageSource;}get initialTrack(){var e;return this._isOpenVirtualBackground&&this._virtualBackgroundTrack?this._virtualBackgroundTrack:null==(e=this.cameraTrack)?void 0:e.mediaTrack;}_setMainOutput(e){let t=this.cameraTrack,{small:i,settings:n}=t;return i&&(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1,use2d:!0}),this.smallDestination=new Nx(this.smallVideoContext,i)),this.smallVideoContext.frameRate=i.frameRate,this.smallDestination.resolution=i,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))),t.setOutputMediaStreamTrack(e?this.destination.videoTrack:this.initialTrack);}update(){return ab(this,null,function*(){var e,t;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();{let{settings:e,profile:t}=this.cameraTrack;this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:\"mainDestination\"})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack),this.cameraNode.resize(e.width,e.height)),this.videoContext.frameRate=t.frameRate;}let i=this.cameraNode;return i.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new Lx(this.videoContext)),i=i.connect(this.mirrorNode),i.disconnect(),this._log.info(\"start mirror\")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new Vx(this.videoContext),i.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),null==(e=this.waterMarkNode)||e.connect(this.mixNode,{zIndex:2}),this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack)),null==(t=this.screenNode)||t.connect(this.mixNode,{zIndex:0}),i=this.mixNode,this._log.info(\"start mix\",\"\".concat(this.mixNode.width,\"x\").concat(this.mixNode.height))),i.connect(this.destination),this._setMainOutput(this.videoContext._canvas);});}changeInput(e,t){return this._log.info(\"change input\"),e instanceof cL?this.setScreenTrack(e):e instanceof sL?this.setCameraTrack(e):e instanceof CL?e.setOutputMediaStreamTrack(e.mediaTrack):void 0;}removeInput(e){var t;e instanceof cL?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof sL&&(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource));}setCameraTrack(e){return ab(this,null,function*(){return this.cameraTrack=e,this._isOpenVirtualBackground&&(yield this.updateAr()),this.update();});}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack);}loadImage(e){return new Promise((t,i)=>{let n=new Image();n.crossOrigin=\"anonymous\",n.src=e,n.onload=()=>t(n),n.onerror=i;});}setWatermark(e){return ab(this,null,function*(){let t=yield this.loadImage(e.imageUrl),{x:i=0,y:n=0,width:r=t.width,height:o=t.height}=e;this._hasWaterMark=!0,this._waterMarkOption={x:i,y:n,width:r,height:o,image:t},this._log.info(\"start watermark\",JSON.stringify({x:i,y:n,width:r,height:o})),this.update();});}stopWatermark(){var e;!this._hasWaterMark||(this._hasWaterMark=!1,this._log.info(\"stop watermark\"),null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,this.update());}get mixScreen(){return this._isMixScreen;}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update();}set mirror(e){var t;this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update();}get mirror(){return this._isMirror;}enableAr(e){return ab(this,null,function*(){this.virtualBackgroundInstance=e,this._isOpenVirtualBackground=!0,this.virtualBackgroundInstance.ar.enable(this.cameraTrack.mediaTrack.clone()),this.virtualBackgroundInstance.ar.listen(\"output\",this.handleArOutput.bind(this));});}handleArOutput(e){this._virtualBackgroundTrack=e,this.update();}updateAr(){return ab(this,null,function*(){var e;null==(e=this.cameraTrack)||!e.mediaTrack||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()));});}disableAr(){var e;!this._isOpenVirtualBackground||(this._isOpenVirtualBackground=!1,null==(e=this._virtualBackgroundTrack)||e.stop(),this._virtualBackgroundTrack=null,this.update());}clear(){this.videoContext.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode;}},Ux=0,Fx=class extends Gw{constructor(e){super(\"room\"),this.seq=++Ux,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._isUsingCachedSchedule=!1,this._log=HO.createLogger({id:\"r\".concat(this.seq)}),this._joinedTimestamp=0,this._isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,sO(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),sO(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),sO(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this.keyPointManager=new lx({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new ux({room:this}),this.badCaseDetector=new hx({room:this}),this.audioManager=new vL({room:this}),this.videoManager=new xx({room:this});}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1;}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1;}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished;}getLogger(){return this._log;}get isJoined(){return\"joined\"===this.state;}get isLeft(){return\"left\"===this.state;}addTrack(e){return ab(this,null,function*(){return this.publish(e);});}removeTrack(e){return ab(this,null,function*(){return this.unpublish(e);});}replaceTrack(e){return ab(this,null,function*(){});}setEncodedDataProcessingListener(e){throw new Error(\"Method not implemented.\");}enableAIVoice(e){throw new Error(\"Method not implemented.\");}setProxyServer(e){if(rO(e))e.startsWith(\"wss://\")?this.proxy_ws=e:e.startsWith(\"https://\")&&(this.proxy_wt=e);else if(ZD(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:n,scheduleProxy:r,unifiedProxy:o}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=o,o?(Tx([o,o]),pN(\"https://\".concat(o))):(n&&pN(n),r&&Tx(r));}}getRemoteAudioStats(){return ab(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat;}),e;});}getTransportStats(){return ab(this,null,function*(){var e;let t={rtt:(null==(e=this.quality)?void 0:e.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let i of this.quality.downlinkInfo)t.downlinksRTT[i.userId]=i.rtt;return t;});}getRemoteVideoStats(){return ab(this,arguments,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:\"main\";return function*(){let i={};return e.remotePublishedUserMap.forEach(e=>{let n=\"auxiliary\"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;i[e.userId]=n.stat;}),i;}();});}checkDestroy(){if(this._isDestroyed)throw new gb({code:mb.INVALID_OPERATION,message:qO({key:JO.CLIENT_DESTROYED,data:{funName:\"join\"}})});}destroy(){if(this.isJoined)throw this._log.warn(KO.INVALID_DESTROY),new gb({code:mb.INVALID_OPERATION,message:qO({key:JO.INVALID_DESTROY})});this._log.info(\"destroy room\"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this._isDestroyed=!0,xO.emit(FO.ROOM_DESTROY,{room:this});}schedule(e,t,i){return ab(this,null,function*(){var n,r;let o=fO();try{let{isCached:s,result:a,detailCost:c}=yield fx({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:i,userSig:this.userSig,frameWorkType:t});this._isUsingCachedSchedule=s,this._log.info(\"schedule cache:\".concat(+s,\" \").concat(DO(a,{keysToExclude:[\"username\",\"credential\"]}))),s&&xO.once(FO.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=$C($C({},this.scheduleResult),a),oO(null==(n=a.config)?void 0:n.retryCount)&&rD(a.config.retryCount),rO(null==(r=a.config)?void 0:r.loggerDomain)&&pN(a.config.loggerDomain),xO.emit(FO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:c}),xO.emit(FO.API_SUCCESS_RATE,{room:this,apiName:\"schedule\",cost:fO()-o});}catch(s){throw xO.emit(FO.API_SUCCESS_RATE,{room:this,apiName:\"schedule\",error:s}),s;}});}},Bx=new WeakMap(),Hx=new WeakMap();function jx(){return function(e,t,i){let n=i.value,r=e=>{let{fn:t,args:i,context:n,resolve:r,reject:o}=e;t.apply(n,i).then(r,o);};return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i{if(Bx.has(this)){let o=Bx.get(this),{length:s}=o;o.push({fn:n,args:t,context:this,resolve:e,reject:i}),0===s&&r({fn:n,args:t,context:this,resolve:e,reject:i});}else Bx.set(this,[{fn:n,args:t,context:this,resolve:e,reject:i}]),r({fn:n,args:t,context:this,resolve:e,reject:i});}).finally(()=>{let e=Bx.get(this);e&&(e.shift(),e[0]&&r($C({},e[0])));});},i;};}function Gx(e){return function(t,i,n){let r=n.value,o=t=>oO(e)?t[e]:e(...t),s=e=>{let{fn:t,args:i,context:n,resolve:r,reject:a}=e;t.apply(n,i).then(r,a).finally(()=>{if(Hx.has(n)&&Hx.get(n).has(o(i))){let e=Hx.get(n).get(o(i));e&&(e.shift(),e[0]&&s($C({},e[0])));}});};return n.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i{if(Hx.has(this)){if(Hx.get(this).has(o(t))){let n=Hx.get(this).get(o(t));if(n){let{length:o}=n;n.push({fn:r,args:t,context:this,resolve:e,reject:i}),0===o&&s({fn:r,args:t,context:this,resolve:e,reject:i});}}else Hx.get(this).set(o(t),[{fn:r,args:t,context:this,resolve:e,reject:i}]),s({fn:r,args:t,context:this,resolve:e,reject:i});}else{let n=new Map();n.set(o(t),[{fn:r,args:t,context:this,resolve:e,reject:i}]),Hx.set(this,n),s({fn:r,args:t,context:this,resolve:e,reject:i});}});},n;};}var Wx=nb(cb()),Jx=nb(hb()),Kx=e=>{let{serverAbility:t,clientAbility:i,offerSDP:n,enableCustomMessage:r}=e,o=BV(n),s={extmapAllowMixed:\"extmap-allow-mixed\",groups:o.groups,icelite:\"ice-lite\",media:[],msidSemantic:{semantic:\"\",token:\"WMS\"},name:\"-\",origin:{address:\"127.0.0.1\",username:\"-\",sessionId:String(Date.now()),sessionVersion:1,netType:\"IN\",ipVer:4},timing:{start:0,stop:0},version:0},a={candidates:t.candidates.map(e=>({component:1,foundation:\"1\",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type})),connection:{version:4,ip:\"0.0.0.0\"},direction:LN.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map(e=>({value:e.id,uri:e.uri})),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:\"0\",payloads:String(t.audio.codecs[0].payload),port:o.media[0].port,protocol:o.media[0].protocol,type:LN.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map(e=>({payload:t.audio.codecs[0].payload,type:e.id,subtype:e.params[0]})),rtcpMux:\"rtcp-mux\",rtcpRsize:\"rtcp-rsize\",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};return s.media.push(a),[1,2,3].forEach(e=>{s.media.push(Yx({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}));}),r&&s.media.push(o.media.find(e=>\"dc\"===e.mid)),HV(s);},Yx=e=>{let{mid:t,serverAbility:i,clientAbility:n,parsedOffer:r,useAllCodec:o=!1}=e,s={candidates:i.candidates.map(e=>({component:1,foundation:\"1\",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type})),connection:{version:4,ip:\"0.0.0.0\"},direction:LN.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(e=>({value:e.id,uri:e.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(t),payloads:\"\",port:r.media[0].port,protocol:r.media[0].protocol,type:LN.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:\"rtcp-mux\",rtcpRsize:\"rtcp-rsize\",rtp:[]};if(i.video.codecs.length>0){if(o)for(let a=0;ae.codec.toLowerCase()===(i.useVp8?\"vp8\":\"h264\"));zx(s,i.video.codecs[e]);}}else if(o)for(let a=0;a{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 qx,Qx=e=>{let t=Jx.default.parse(e);return t.media.forEach(e=>{var i;(e.type===LN.AUDIO||e.type===LN.VIDEO)&&(function(e){if(!e.rtcpFb)return;let t=[];e.rtcpFb.forEach((i,n)=>{var r;t.push(i),e.rtcpFb&&(null==(r=e.rtcpFb[n+1])?void 0:r.payload)!==i.payload&&\"rrtr\"!==i.type&&t.push({payload:i.payload,type:\"rrtr\"});}),e.rtcpFb=t;}(e),function(e){e.type===LN.VIDEO&&e.fmtp&&e.fmtp.forEach(e=>{e.config.includes(\"apt\")||(e.config+=\";sps-pps-idr-in-keyframe=1\");});}(e),function(e){e.type===LN.AUDIO&&e.fmtp&&e.fmtp.forEach(e=>{e.config+=\";sprop-stereo=1;stereo=1\";});}(e),function(e){let t=new Set([\"urn:ietf:params:rtp-hdrext:sdes:mid\",\"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\",\"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\"]);e.ext&&(e.ext=e.ext.filter(e=>!t.has(e.uri)));}(e)),(null==(i=e.payloads)?void 0:i.includes(\"datachannel\"))&&t.groups&&e.mid&&(t.groups[0].mids=t.groups[0].mids.replace(e.mid,\"dc\"),e.mid=\"dc\");}),Jx.default.write(t);},Xx=((qx=Xx||{}).TRACK=\"track\",qx.DATA_CHANNEL_MESSAGE=\"data_channel_msg\",qx[qx.CONNECTION_STATE_CHANGED=\"connection-state-changed\"]=\"CONNECTION_STATE_CHANGED\",qx[qx.FIREWALL_RESTRICTION=\"firewall-restriction\"]=\"FIREWALL_RESTRICTION\",qx.RECONNECTED=\"spc-reconnected\",qx.RECONNECT_FAILED=\"spc-reconnect-failed\",qx.ERROR=\"error\",qx),Zx=0,$x=!1,eU=new Set(),tU=1,iU=class extends Wx.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:n}=e;super(),ob(this,\"stat\",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),ob(this,\"currentState\",\"DISCONNECTED\"),ob(this,\"_room\"),ob(this,\"_signalChannel\"),ob(this,\"_peerConnection\",null),ob(this,\"_datachannel\",null),ob(this,\"_enableCustomMessage\"),ob(this,\"_log\"),ob(this,\"_downlinkMIDMap\",new Map()),ob(this,\"_reconnectionTimer\",-1),ob(this,\"reconnectionCount\",0),ob(this,\"_clientAbility\",null),ob(this,\"_serverAbility\",null),ob(this,\"addDownlinkQueue\",new Set()),ob(this,\"removeDownlinkQueue\",new Set()),ob(this,\"_parsedAnswer\",null),ob(this,\"_updateSDPPromise\",null),ob(this,\"_waitForPCConnectedPromise\"),ob(this,\"_waitForPCConnectedPromiseReject\",null),ob(this,\"_isSDPLogged\",!1),this._room=i,this._enableCustomMessage=n,this._signalChannel=t,this._log=HO.createLogger({id:\"spc\".concat(tU++),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=BV(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 n;if(e.ssrcs&&!nO(e.ssrcs[0].id)){let r=Number(e.ssrcs[0].id),o=Number(null==(n=e.ssrcs.filter(e=>\"cname\"===e.attribute)[1])?void 0:n.id);switch(t){case 0:i.audioSsrc=r;break;case 1:i.bigVideoSsrc=r,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=r,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=r,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||this.reconnectionCount>0;}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport;}initialize(){return ab(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.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let e=this._peerConnection.iceConnectionState;this._log.debug(\"ice state: \".concat(e)),\"checking\"===e&&0===this.stat.iceStartTime?this.stat.iceStartTime=Date.now():\"connected\"===e&&0===this.stat.iceEndTime&&(this.stat.iceEndTime=Date.now());},this._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 rU(e.data);this.emit(\"data_channel_msg\",{data:t});},this._datachannel.onerror=e=>{this._log.warn(\"datachannel error\",e);}),this._peerConnection.addTransceiver(LN.AUDIO,{direction:LN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(LN.VIDEO,{direction:LN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(LN.VIDEO,{direction:LN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(LN.VIDEO,{direction:LN.TRANSCEIVER_DIRECTION_SENDONLY});let e=yield this._peerConnection.createOffer();return yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;!e||(this._log.debug(\"dtls state: \".concat(e.state)),\"connecting\"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():\"connected\"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()));}),this._clientAbility=((e,t)=>{var i,n;let r=BV(e),o={ice:{ufrag:\"\",password:\"\"},dtls:{hash:\"\",fingerprint:\"\",setup:\"\"},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:t};o.ice.ufrag=String(r.media[0].iceUfrag),o.ice.password=r.media[0].icePwd||\"\",r.fingerprint&&(o.dtls.hash=r.fingerprint.type,o.dtls.fingerprint=r.fingerprint.hash,o.dtls.setup=r.setup||\"\"),r.media[0].fingerprint&&(o.dtls.hash=r.media[0].fingerprint.type,o.dtls.fingerprint=r.media[0].fingerprint.hash),o.dtls.setup=r.media[0].setup||\"\";let s=r.media[0],a=r.media[1];s.ext&&(o.audio.extensions=s.ext.map(e=>({id:e.value,uri:e.uri}))),a.ext&&(o.video.extensions=a.ext.map(e=>({id:e.value,uri:e.uri})));let c={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};null==(i=s.rtcpFb)||i.forEach(e=>{let{payload:t,type:i,subtype:n}=e;if(t===c.payload){let e={id:i,params:[]};n&&e.params.push(n),c.rtcpFb.push(e);}}),o.audio.codecs.push(c);for(let l=0;le.payload===a.rtp[l].payload)[0];o.video.codecs.push({payload:a.rtp[l].payload,codec:a.rtp[l].codec,fmtp:e?e.config:\"\",rate:a.rtp[l].rate,rtx:\"rtx\"===(null==(n=a.rtp[l+1])?void 0:n.codec)?a.rtp[l+1].payload:0,rtcpFb:((null==a?void 0:a.rtcpFb)||[]).filter(e=>e.payload===a.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(sN){throw this._log.error(\"initialize failed \".concat(sN)),sN;}});}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return ab(this,null,function*(){try{if(\"CONNECTED\"===this.currentState)return;let i=fO(),n={type:\"answer\",sdp:Kx({serverAbility:e,clientAbility:this._clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(n),yield this.waitForPeerConnectionConnected(),t||xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:\"SPCConnect\",cost:Math.min(fO()-i,3e4)});}catch(aN){let i=aN instanceof gb&&aN.code===mb.API_CALL_ABORTED;throw i||this._log.error(\"connect failed: \".concat(aN),e),this.reset(),!i&&!this.isReconnecting&&(xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:\"SPCConnect\",error:aN}),this.emitConnectionStateChangedEvent(\"DISCONNECTED\"),this.startReconnection()),aN;}});}reconnect(){return ab(this,null,function*(){if(-1===this._reconnectionTimer){if(!this._signalChannel.isConnected)return this._log.warn(\"reconnect() wait signal channel is connected\"),void this._signalChannel.once(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:AV,responseCommand:nV.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(sN){if(!this.isReconnecting)return;if(null!=sN&&sN.message.includes(\"timeout\")){let e=eO(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(sN)),xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:\"SPCReconnect\",error:sN}),this.reconnectionCount>=oD()&&this._log.warn(\"SDK has tried reconnect for \".concat(oD(),\" times, but all failed, please check your network\")),this.stopReconnection(),this.emitConnectionStateChangedEvent(\"DISCONNECTED\"),this.emit(\"error\");}}else this._log.warn(\"reconnect() is reconnecting, ignore current reconnection\");});}getPeerConnection(){return this._peerConnection;}startReconnection(){return ab(this,null,function*(){this._log.warn(\"start reconnect\"),this.emitConnectionStateChangedEvent(\"RECONNECTING\");let e=fO();yield this.reconnect(),xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:\"SPCReconnect\",cost:Math.min(fO()-e,3e4)});});}stopReconnection(){this.isReconnecting&&(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)===iD.CLOSED&&this.startReconnection();}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1);}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();this._log.info(\"connectionState: \".concat(e.target.connectionState,\" ICE: \").concat(t,\" DTLS: \").concat(i)),e.target.connectionState===iD.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent(\"CONNECTING\")),(e.target.connectionState===iD.FAILED||e.target.connectionState===iD.CLOSED)&&(this.emitConnectionStateChangedEvent(\"DISCONNECTED\"),this.startReconnection()),(e.target.connectionState===iD.CONNECTED||e.target.connectionState===iD.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),xO.emit(FO.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent(\"CONNECTED\"));}getDTLSTransportState(){if(!this._peerConnection)return tD;let e=null;return Ew()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,Tw()&&0!==this._peerConnection.getReceivers().length&&e?e.state:tD):tD;}emitConnectionStateChangedEvent(e){e!==this.currentState&&(\"RECONNECTING\"===this.currentState&&\"CONNECTING\"===e||(this.emit(Xx.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e));}logSelectedCandidate(){return ab(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(uw(i)){let t=e.get(i.localCandidateId),n=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):\"\")),n&&this._log.info(\"remote candidate: \".concat(n.candidateType,\" \").concat(n.protocol,\":\").concat(n.ip||n.address,\":\").concat(n.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),r(),e());},n=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),r(),t(new gb({code:mb.API_CALL_ABORTED,message:qO({key:JO.CONNECTION_ABORTED,data:\"leave room\"})})));},r=()=>{xO.off(FO.LEAVE_SUCCESS,n,this),this.off(Xx.CONNECTION_STATE_CHANGED,i,this);},o=setTimeout(()=>{r();let e=new gb({code:mb.API_CALL_TIMEOUT,message:\"connection timeout\"});Zx+=1,(e=>Zx>2&&!$x&&0===eU.size&&e)(this._signalChannel.isConnected)&&(this._log.warn(\"firewall restrition\"),$x=!0,this.emit(Xx.FIREWALL_RESTRICTION)),t(e);},SD);xO.on(FO.LEAVE_SUCCESS,n,this),this.on(Xx.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 ab(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(sD){this._log.info(\"addDownlink(\".concat(e.userId,\") failed\")),yield this.startReconnection();}});}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,userId:i,tinyId:n}=e;if(!this._peerConnection)return;this._log.info(\"updateLocalAndRemoteSDPConfig \".concat(i,\" \").concat(JSON.stringify(t)));let r,o,s,a=this._peerConnection.getTransceivers().filter(e=>\"inactive\"===e.direction).slice(0,3).map(e=>(e.direction=LN.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid)));if(0===a.length&&(this._peerConnection.addTransceiver(LN.AUDIO,{direction:LN.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(LN.VIDEO,{direction:LN.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(LN.VIDEO,{direction:LN.TRANSCEIVER_DIRECTION_RECVONLY})),this._parsedAnswer||(this._parsedAnswer=BV(this._peerConnection.remoteDescription.sdp)),3===a.length)r=this._parsedAnswer.media.find(e=>Number(e.mid)===Number(a[0])),o=this._parsedAnswer.media.find(e=>Number(e.mid)===Number(a[1])),s=this._parsedAnswer.media.find(e=>Number(e.mid)===Number(a[2]));else{r=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=Yx({mid:1,serverAbility:this._serverAbility,clientAbility:this._clientAbility,parsedOffer:BV(this._peerConnection.localDescription.sdp),useAllCodec:!0});o=JSON.parse(JSON.stringify(e)),s=JSON.parse(JSON.stringify(e)),r.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(r),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s);}r.direction=LN.TRANSCEIVER_DIRECTION_SENDONLY,r.ssrcs=[{id:t.audio,attribute:\"cname\",value:\"\".concat(n)},{id:t.audio,attribute:\"msid\",value:\"\".concat(n,\"-\").concat(LN.MAIN,\" \").concat(n,\"-audio\")}],o.direction=LN.TRANSCEIVER_DIRECTION_SENDONLY,o.ssrcs=[{id:t.video,attribute:\"cname\",value:\"\".concat(n)},{id:t.video,attribute:\"msid\",value:\"\".concat(n,\"-\").concat(LN.MAIN,\" \").concat(n,\"-bigvideo\")},{id:t.videoRtx,attribute:\"cname\",value:\"\".concat(n)},{id:t.videoRtx,attribute:\"msid\",value:\"\".concat(n,\"-\").concat(LN.MAIN,\" \").concat(n,\"-bigvideo\")}],o.ssrcGroups=[{semantics:\"FID\",ssrcs:\"\".concat(t.video,\" \").concat(t.videoRtx)}],s.direction=LN.TRANSCEIVER_DIRECTION_SENDONLY;let c=\"\".concat(n,\"-aux\");s.ssrcs=[{id:t.auxiliary,attribute:\"cname\",value:c},{id:t.auxiliary,attribute:\"msid\",value:\"\".concat(c,\" \").concat(n,\"-aux\").concat(LN.VIDEO)},{id:t.auxiliaryRtx,attribute:\"cname\",value:\"\".concat(c,\" \").concat(n,\"-aux\").concat(LN.VIDEO)},{id:t.auxiliaryRtx,attribute:\"msid\",value:\"\".concat(c,\" \").concat(n,\"-aux\").concat(LN.VIDEO)}],s.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(n,[r.mid,o.mid,s.mid]);}removeDownlink(e,t){return ab(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),n=!1;this._peerConnection.getTransceivers().forEach(e=>{null!=i&&i.includes(Number(e.mid))&&(n=!0,e.direction=\"inactive\");}),this._parsedAnswer||(this._parsedAnswer=BV(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(e=>{null!=i&&i.includes(Number(e.mid))&&(n=!0,e.direction=\"inactive\",e.ssrcs=[],e.ssrcGroups=[]);}),0===this.removeDownlinkQueue.size&&n&&(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 ab(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:n,auxVideo:r}=e;try{if(Rw()){let e=this._peerConnection.getSenders().slice(0,4);for(let o=0;oab(this,null,function*(){var o,s;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:r}),this._updateSDPPromise=null,e();}catch(a){this._log.error(a),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(\"transceivers: \".concat(JSON.stringify(this._peerConnection.getTransceivers().map(e=>{let{mid:t,currentDirection:i,direction:n,stopped:r}=e;return{mid:t,currentDirection:i,direction:n,stopped:r};})))),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(r)||(null==(s=this._peerConnection.remoteDescription)?void 0:s.sdp)),this._isSDPLogged=!0),this._updateSDPPromise=null,n(a);}})),this._updateSDPPromise;}setOffer(e){return this._log.info(\"setting offer\"),this._peerConnection.setLocalDescription({type:\"offer\",sdp:Qx(e.sdp)});}setAnswer(e){return this._log.info(\"setting answer\"),this._room.enableHWEncoder&&e.sdp&&(e.sdp=e.sdp.replaceAll(\"42e01f\",\"42001f\")),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();}};rb([jx()],iU.prototype,\"updateSDP\",1);var nU=class{constructor(e){ob(this,\"tag\"),ob(this,\"len\"),ob(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;}},rU=class{constructor(e){ob(this,\"tinyId\"),ob(this,\"data\");let t=new DataView(e),i=0,n=[];for(;i{1===e.tag?this.tinyId=new TextDecoder().decode(e.data):2===e.tag&&(this.data=e.data);});}},oU=new Set();function sU(){let e=Math.floor(4294967296*Math.random());return oU.has(e)?sU():(oU.add(e),e);}var aU=nb(cb()),cU=class extends aU.default{constructor(e){super(),ob(this,\"userId\"),ob(this,\"tinyId\"),ob(this,\"_sdpSemantics\"),ob(this,\"_isUplink\"),ob(this,\"_room\"),ob(this,\"_log\"),ob(this,\"_signalChannel\"),ob(this,\"_currentState\",\"DISCONNECTED\"),ob(this,\"_prevTime\",-1),ob(this,\"_enableSEI\"),ob(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=HO.createLogger({id:\"n\",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&kw&&(this._sei=new PV(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&&(xO.emit(FO.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\"));}},lU=class extends cU{constructor(e){super(eb($C({},e),{isUplink:!0})),ob(this,\"localMainAudioTrack\",null),ob(this,\"localMainVideoTrack\",null),ob(this,\"localAuxAudioTrack\",null),ob(this,\"localAuxVideoTrack\",null),ob(this,\"_isPublishingAux\",!1),ob(this,\"_publishingLocalAudioTrack\"),ob(this,\"_publishingLocalVideoTrack\"),ob(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}),ob(this,\"_audioManager\"),this._audioManager=e.audioManager,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:n,smallVideoRtxSsrc:r,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:n||0,smallRtx:r||0,auxiliary:o||0,auxiliaryRtx:s||0};}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack);}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack);}get publishState(){var e,t,i,n;let r={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(Sw()?(r.audio=!(null==(e=o[0])||!e.track),r.bigVideo=!(null==(t=o[1])||!t.track),r.smallVideo=!(null==(i=o[2])||!i.track),r.auxVideo=!(null==(n=o[3])||!n.track)):o.forEach(e=>{e.track&&(e.track.kind===LN.AUDIO?r.audio=!0:(r.bigVideo=!0,this._room.videoManager.hasSmall&&(r.smallVideo=!0)));}));}return r;}initialize(){this.installEvents();}reset(){this.uninstallEvents();}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent(\"DISCONNECTED\");}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,n,r;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit(\"connection-state-changed\",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit(\"connection-state-changed\",{prevState:o,state:e}),null==(n=this.localAuxVideoTrack)||n.emit(\"connection-state-changed\",{prevState:o,state:e}),null==(r=this._publishingLocalVideoTrack)||r.emit(\"connection-state-changed\",{prevState:o,state:e}))),s;}publish(e){return ab(this,arguments,function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,isAuxiliary:r}=e;return function*(){var e,o,s,a,c,l;if(!t.singlePC)return;if(yield t.singlePC.waitForPeerConnectionConnected(),i&&(t._publishingLocalAudioTrack=i),n){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new gb({code:mb.NOT_SUPPORTED_H264,message:qO({key:JO.NOT_SUPPORTED_H264ENCODE})});Lb&&115===wk()&&n.profile.width*n.profile.height<=230400&&(t._log.warn(\"fallback video to 480p\"),n.setProfile(wN[\"480p_2\"]),yield n.applyProfile()),t._publishingLocalVideoTrack=n;}let d;t._isPublishingAux=r,n&&!r&&n.small&&(d=t._room.videoManager.smallTrack),Iw()&&(yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:n,smallTrack:d,isAuxiliary:r})),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r?(n&&(t.localAuxVideoTrack=n),i&&(t.localAuxAudioTrack=i)):(n&&(t.localMainVideoTrack=n),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==(s=t.localMainVideoTrack)?void 0:s.profile.bitrate,smallVideo:null==(c=null==(a=t.localMainVideoTrack)?void 0:a.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),yield t._signalChannel.sendWaitForResponse({command:CV,responseCommand:nV.SPC_PUBLISH_RESULT,data:eb($C({},t.singlePC.uplinkSSRC),{state:t.publishState})}),t.sendMediaSettings(),t.installTrackMuteEvents(i,n),t.sendMutedFlag();}();});}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:n,isAuxiliary:r}=e;this._log.info(\"publish by transceiver\");let o=null==i?void 0:i.outMediaTrack,s=this._audioManager.mixedAudioTrack,a=this._peerConnection.getTransceivers(),c=[],l=[];if(s){let e=a[0].sender.replaceTrack(s);l.push(0),c.push(e);}if(o)if(r){let e=a[3].sender.replaceTrack(o);l.push(3),c.push(e);}else{let e=a[1].sender.replaceTrack(o);l.push(1),c.push(e);}if(n){let e=a[2].sender.replaceTrack(n);l.push(2),c.push(e);}let d=this.setTransceiverDirection(MN.SENDONLY,l);return c.push(d),Promise.all(c);}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i{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&&(null==e||e.off(\"mute\",this.sendMutedFlag,this),null==e||e.off(\"unmute\",this.sendMutedFlag,this));});}unpublish(e){return ab(this,arguments,function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n}=e;return function*(){let e=n&&n===t.localAuxVideoTrack,r=null==n?void 0:n.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(t._audioManager.mixedAudioTrack||(yield o[0].replaceTrack(null),s.push(0)),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),r&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=eb($C({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=eb($C({},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(MN.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),null==n||n.emit(\"connection-state-changed\",{prevState:t._currentState,state:\"DISCONNECTED\"});}();});}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return ab(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:dV,data:t,responseCommand:nV.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:uV,commandDesc:\"unpublish\",responseCommand:nV.UNPUBLISH_RESULT,enableLog:e}).catch(e=>{if(e.getCode()===mb.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:n,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Cw){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0;}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate);}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate;}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info(\"updateMediaSettings: \".concat(JSON.stringify(this._mediaSettings)));}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:yV,data:this._mediaSettings,responseCommand:nV.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{0!==e.data.code&&this._log.warn(e.data.message);}).catch(()=>{});}addTrack(e){return ab(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?LN.AUXILIARY:LN.MAIN,\" stream\")),null==(t=this._sei)||t.handleEncodedStreams(),Sw()&&(yield this.addTrackByTransceiver(e,i));});}addTrackByTransceiver(e,t){return ab(this,null,function*(){var i;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===LN.AUDIO)yield n[0].sender.replaceTrack(this._audioManager.mixedAudioTrack);else{let r=t?3:1;yield n[r].sender.replaceTrack(e.outMediaTrack),1===r&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[r].direction===MN.INACTIVE&&(yield this.setTransceiverDirection(MN.SENDONLY,[r]));}this.updateMediaSettings(),yield this.doPublishChange();});}removeTrack(e){return ab(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(\"is removing \".concat(e.kind,\" track from current published local \").concat(t?LN.AUXILIARY:LN.MAIN,\" stream\")),Sw()&&(yield this.removeTrackByTransceiver(e,t));});}removeTrackByTransceiver(e,t){return ab(this,null,function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===LN.AUDIO)this._audioManager.mixedAudioTrack||(yield i[0].sender.replaceTrack(null));else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._room.videoManager.hasSmall&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(MN.INACTIVE,[e]);}this.updateMediaSettings(),yield this.doPublishChange();});}setTransceiverDirection(e,t){return ab(this,null,function*(){if(!Ub)return;let i=!1,n=!1;this._log.info(\"setting transceiver \".concat(t.join(\",\"),\" direction to \").concat(e));let r=this._peerConnection.getTransceivers();if(t.forEach(t=>{r[t].direction!==e&&(r[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,s=this._peerConnection.remoteDescription.sdp.split(\"\\r\\n\").map(i=>{if(i.match(new RegExp(\"a=(\".concat(MN.INACTIVE,\"|\").concat(MN.RECVONLY,\"|\").concat(MN.SENDONLY,\")\")))&&o++,t.includes(o)){if(e===MN.INACTIVE&&i.includes(\"a=\".concat(MN.RECVONLY)))return n=!0,\"a=\".concat(e);if(e===MN.SENDONLY&&i.includes(\"a=\".concat(MN.INACTIVE)))return n=!0,\"a=\".concat(MN.RECVONLY);}return i;}).join(\"\\r\\n\");n&&(this._log.info(\"updating answer\"),yield this._peerConnection.setRemoteDescription({type:\"answer\",sdp:s}));});}replaceTrack(e){return ab(this,null,function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders(),n=e.mediaTrack;if(!i||0===i.length||!n)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(\"is replacing \".concat(n.kind,\" track on \").concat(r?LN.AUXILIARY:LN.MAIN,\" stream\")),n.kind===LN.AUDIO&&i[0]&&(yield i[0].replaceTrack(this._audioManager.mixedAudioTrack)),n.kind===LN.VIDEO&&(!r&&i[1]&&(yield i[1].replaceTrack(e.outMediaTrack||n)),r&&i[3]&&(yield i[3].replaceTrack(e.outMediaTrack)));});}setBandwidth(e){return ab(this,arguments,function(e){var t=this;let{bandwidth:i,type:n,videoType:r}=e;return function*(){if(t.singlePC){let e={};n===LN.AUDIO?e.audio=i:\"big\"===r?e.bigVideo=i:\"small\"===r?e.smallVideo=i:e.auxVideo=i,yield t.singlePC.setBandwidth(e);}}();});}sendMutedFlag(e){var t,i,n;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(i=this.localMainVideoTrack)||!i.muted),auxVideo:!(null==(n=this.localAuxVideoTrack)||!n.muted)};this._log.info(\"send muted state: \".concat(JSON.stringify(r))),this._signalChannel.send(cV,r);}handleConnectionStateChange(e){\"CONNECTED\"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&xO.emit(FO.SEND_FIRST_VIDEO_FRAME,{room:this._room});}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:LN.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===LN.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===LN.VIDEO&&t[1]&&t[1].track)return t[1].track.id;}if(this.localMainVideoTrack&&e===LN.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id;}if(this.localAuxVideoTrack&&e===LN.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id;}return\"\";}getSSRC(){return this.ssrc;}checkPublishResultCode(e,t){if(0!==e)throw e===_D?(this._log.error(KO.NOT_SUPPORTED_H264ENCODE),new gb({code:mb.NOT_SUPPORTED_H264,message:qO({key:JO.NOT_SUPPORTED_H264ENCODE})})):new gb({code:mb.UNKNOWN,message:qO({key:JO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:nV.PUBLISH_RESULT,code:e,message:t}})});}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t);}onSinglePCReconnected(){return ab(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}));});}};function dU(e){return Object.keys(e).filter(t=>e[t]);}var uU=class extends cU{constructor(e){super(eb($C({},e),{isUplink:!1})),ob(this,\"_flag\",0),ob(this,\"role\",\"anchor\"),ob(this,\"remoteAudioTrack\"),ob(this,\"remoteVideoTrack\"),ob(this,\"remoteAuxiliaryTrack\"),ob(this,\"ssrc\",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),this.flag=e.flag,this.remoteAudioTrack=new RL(this._room,this),this.remoteVideoTrack=new CL(this._room,this),this.remoteAuxiliaryTrack=new bL(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 IO(this.flag,this.userId);}get flag(){return this._flag;}set flag(e){var t,i,n;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(n=this.remoteAuxiliaryTrack)||n.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===LN.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary;}initialize(){this.installEvents();}close(e){super.close(e),this.emitConnectionStateChangedEvent(\"DISCONNECTED\"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink();}installEvents(){!this.singlePC||(this.listeners(\"track\").includes(this.onTrack)||this.singlePC.on(\"track\",this.onTrack,this),this.listeners(\"spc-reconnected\").includes(this.onSinglePCReconnected)||this.singlePC.on(\"spc-reconnected\",this.onSinglePCReconnected,this));}uninstallEvents(){!this.singlePC||(this.singlePC.off(\"track\",this.onTrack,this),this.singlePC.off(\"spc-reconnected\",this.onSinglePCReconnected,this));}emitConnectionStateChangedEvent(e){var t,i;let n=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&n!==e&&(null==(t=this.remoteVideoTrack)||t.emit(\"connection-state-changed\",{prevState:n,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit(\"connection-state-changed\",{prevState:n,state:e})),r;}onTrack(e){let t=e.streams[0],{track:i}=e;if(t.id.split(\"-\")[0]!==this.tinyId)return;let n=t.id.includes(\"aux\")?\"auxiliary\":\"main\";this._log.debug(\"ontrack \".concat(n,\" \").concat(i.kind));let r=LN.AUDIO;i.kind===LN.VIDEO&&(r=n===LN.MAIN?LN.VIDEO:LN.AUXILIARY);let o=this.remoteAudioTrack;r===LN.VIDEO?o=this.remoteVideoTrack:r===LN.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i);}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState);}subscribe(e,t){return ab(this,null,function*(){try{if(this.isSubscriptionStateNotChanged(e))return;if(this._log.info(\"subscribe \".concat(t,\" \").concat(dU(e))),this.hasSSRC){let t=\"subscribe_change\";Object.values(e).find(e=>!0===e)||(t=\"unsubscribe\"),yield this.sendSubscription(t,e);}else yield this.doSubscribe(e);}catch(aN){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(\"\".concat(aN.message,\" \").concat(JSON.stringify(this.muteState))),new gb({code:mb.REMOTE_STREAM_NOT_EXIST,message:\"remote user \".concat(this.userId,\" unpublished stream\")})):aN;}});}unsubscribe(e){return ab(this,arguments,function(e){var t=this;let{remoteTracks:i,streamType:n}=e;return function*(){var e;if(\"main\"===n&&!t.isMainStreamSubscribed||\"auxiliary\"===n&&!t.isAuxStreamSubscribed)return void t._log.info(\"\".concat(n,\" stream already unsubscribed\"));let r=$C({},t.subscribeState);i.forEach(e=>{switch(e.mediaType){case 1:r.audio=!1;break;case 4:r.video=!1;break;case 8:r.smallVideo=!1;break;case 2:r.auxiliary=!1;}});let o=\"subscribe_change\";Object.values(r).find(e=>!0===e)||(o=\"unsubscribe\"),t._log.info(\"\".concat(\"unsubscribe\"===o?o:\"subscribe\",\" \").concat(n,\" [\").concat(dU(r),\"]\")),\"unsubscribe\"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,r),\"unsubscribe\"===o&&(yield t.removeDownlink());}();});}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},n=pV,r=nV.UNSUBSCRIBE_RESULT;return\"subscribe_change\"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=_V,r=nV.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:i,responseCommand:r,timeout:1e4}).then(t=>{let{data:i}=t;if(0!==i.code){let t=new gb({code:i.code,message:qO({key:JO.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t;}});}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:\"\";}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:\"\";}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i;}onSinglePCReconnected(){(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 ab(this,arguments,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){if(e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected(),i||!e.hasSSRC){let i={audioSsrc:sU(),bigVideoSsrc:sU(),bigVideoRtxSsrc:sU(),auxVideoSsrc:sU(),auxVideoRtxSsrc:sU()},{audioSsrc:n,bigVideoSsrc:r,bigVideoRtxSsrc:o,auxVideoSsrc:s,auxVideoRtxSsrc:a}=i;e.ssrc={audio:n,video:r,videoRtx:o,auxiliary:s,auxiliaryRtx:a},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});let c=yield e._signalChannel.sendWaitForResponse({command:bV,responseCommand:nV.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!1,ssrc:i}});if(0!==c.data.code)throw yield e.removeDownlink(),new gb({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 ab(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));});}};rb([iL(e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n{let r=e=>{this.off(\"closed\",r),n(new gb({code:mb.API_CALL_ABORTED,message:qO({key:JO.CONNECTION_ABORTED,data:e})}));};this.on(\"closed\",r),e.apply(this,i).then(t,n).finally(()=>{this.off(\"closed\",r);});});})],uU.prototype,\"subscribe\",1);var hU=uU;var{isString:pU,isPlainObject:_U,isUndefined:mU,getNetworkType:fU,getTerminalType:gU,isEmpty:TU}=Ib,EU=class extends Fx{constructor(e){super(e),this.privateMapKey=\"\",this._heartbeat=-1,this._lastHeartBeatTime=-1,this._joinTimeout=-1,this._firstPublishedList=null,this._joinReject=null,this._isRelayChanged=!1,this._signalChannel=null,this.uplinkConnection=null,this.singlePC=null,this.enableSPC=vw,this._changeBigSmallRecords=new Map(),this._networkQuality=null,this._networkType=fU(),this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=0,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this.enableHWEncoder=!1,this._stats=new QV(this,this._log),this.userManager=new KL(this.userId,this._log),this._version=rN,this.sdpSemantics=pD,mU(e.sdpSemantics)?WO.isUnifiedPlanDefault()&&(this.sdpSemantics=hD):this.sdpSemantics=e.sdpSemantics,this._log.info(\"sdpSemantics: \".concat(this.sdpSemantics,\", netType: \").concat(this._networkType)),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!mU(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!mU(e.enableSPC)&&vw&&(this.enableSPC=e.enableSPC),this.enableHWEncoder=e.enableHWEncoder||!1,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 ab(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on(\"1\",e=>{this.emit(\"peer-join\",e);}),this.userManager.on(\"2\",e=>{this.closeDownLinkConnection(e,\"remote user exitRoom\"),this.emit(\"peer-leave\",e);}),this.userManager.on(\"3\",this.createDownlinkConnection,this),this.userManager.on(\"5\",this.closeDownLinkConnection,this),this.userManager.on(\"6\",e=>{var t=((e,t)=>{var i={};for(var n in e)zC.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&KC)for(var n of KC(e))t.indexOf(n)<0&&qC.call(e,n)&&(i[n]=e[n]);return i;})(e,[]);xO.emit(FO.REMOTE_PUBLISH_STATE_CHANGED,$C({room:this},t)),this.emit(\"remote-publish-state-changed\",$C({},t));}),this._joinOptions=e,new Promise((t,i)=>ab(this,null,function*(){this._joinReject=i;try{this.checkDestroy();let i=yield this.initialize();yield this.doJoin(e,i),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}});}catch(qx){i(qx);}this._joinReject=null;}));});}doJoin(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise((i,n)=>ab(this,null,function*(){var r,o,s;let a;if(e.privateMapKey&&(this.privateMapKey=e.privateMapKey),this._signalChannel.once(zM,e=>{this.clearJoinTimeout(),xO.emit(FO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),n(e);}),sO(null==(o=null==(r=this.scheduleResult)?void 0:r.config)?void 0:o.singlePC)&&vw&&(this.enableSPC=this.scheduleResult.config.singlePC),this.enableSPC&&!this.singlePC){this.singlePC=new iU({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.once(\"error\",()=>this.fallbackToMPC());try{a=yield this.singlePC.initialize();}catch(d){this.fallbackToMPC();}}this.keyPointManager.setConnectionType(this.singlePC?1:2);let c={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,trtcRole:e.role,trtcScene:\"live\"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||\"\",terminalType:gU(),netType:kN[this._networkType],bussinessInfo:this._businessInfo,ability:a};t&&(c.userSig=this.userSig),this._log.debug(\"join room signal data: \".concat(JSON.stringify(c)));let l=5e3;(null==(s=this.scheduleResult.config)?void 0:s.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(l=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout(()=>{n(new gb({code:mb.JOIN_ROOM_FAILED,message:qO({key:JO.JOIN_ROOM_TIMEOUT})}));},l),xO.emit(FO.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?RV:oV,c),this._signalChannel.once(nV.JOIN_ROOM_RESULT,e=>{this.clearJoinTimeout();let{code:t,message:r,data:o}=e.data;xO.emit(FO.JOIN_RECEIVED_CMD_RES,{room:this,code:t}),0===t?(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(()=>{}),i()):(this._log.error(\"Join room failed result: \".concat(t,\" error: \").concat(r)),n(new gb({code:mb.JOIN_ROOM_FAILED,extraCode:t,message:qO({key:JO.JOIN_ROOM_FAILED,data:{error:r,code:t}})})));});}));}reJoin(){return ab(this,null,function*(){if(this.isJoined)try{if(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(eb($C({},this._joinOptions),{role:\"anchor\"===this.role?20:21,privateMapKey:this.privateMapKey})),this._log.warn(\"reJoin success\"),Qw.logSuccessEvent({userId:this.userId,eventType:cD.REJOIN}),this.singlePC){let e=t=>{var i;\"CONNECTED\"===t.state&&(null==(i=this.singlePC)||i.off(Xx.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof lU&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach(e=>{e.installEvents(),e.doSubscribe();}));};this.singlePC.on(Xx.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof qV&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection();}}catch(sN){this._log.warn(\"reJoin fail \".concat(sN)),this.reset(),Qw.logFailedEvent({userId:this.userId,eventType:cD.REJOIN,error:sN}),this.emit(\"error\",new gb({code:mb.JOIN_ROOM_FAILED,message:qO({key:JO.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}));}else this._log.warn(\"reJoin abort\");});}initialize(){return ab(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),i=this._signalChannel||function(e){let t=[...NV.values()].find(t=>t.room.userId===e&&!t.room.isJoined);return t||null;}(this.userId),n=!!(i&&i.isConnected&&i.keepAlive);return this._log.info(\"setup signal channel. reuse: \".concat(+n)),n?(i.url=e,i.backupUrl=t,i.room=this,this._signalChannel=i):this._signalChannel=new DV({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this}),this._networkQuality||(this._networkQuality=new $V({signalChannel:this._signalChannel,room:this}),this._networkQuality.on($V.EVENT_NETWORK_QUALITY,e=>{this.emit(\"network-quality\",e);})),SP(this,this._signalChannel).add(qM,e=>{xO.emit(FO.SIGNAL_CONNECTION_STATE_CHANGED,$C({room:this},e)),this.emit(\"signal-connection-state-changed\",e);}).add(XM,e=>{this.reset(),this.emit(\"error\",e);}).add(nV.PEER_JOIN,e=>{let{srcTinyId:t,userId:i,role:n}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:n});}).add(nV.PEER_LEAVE,e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i);}).add(nV.UPDATE_REMOTE_MUTE_STAT,e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data);}).add(nV.CLIENT_BANNED,e=>{let t=e.data.data,{reason:i}=t;if(Qw.uploadEvent({log:\"stat-banned:\".concat(i),userId:this.userId}),\"user_time_out\"===i)return this._log.warn(\"\".concat(i,\" last heart beat time: \").concat(this._lastHeartBeatTime,\" interval: \").concat(Date.now()-this._lastHeartBeatTime,\", visibility: \").concat(document.visibilityState)),void this.reJoin();this._log[\"kick\"===i?\"error\":\"info\"](\"user was banned because of [\".concat(i,\"]\")),this.reset(),this.emit(\"banned\",{reason:i});}),this._signalChannel.once(YM,e=>{this.tinyId=e.signalInfo.tinyId,xO.emit(FO.JOIN_SIGNAL_CONNECTION_END,{room:this});}),xO.emit(FO.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this._signalChannel.connect(this._isUsingCachedSchedule?1e4:void 0),n;});}setSignalChannel(e){this._signalChannel=e,e||IP(this);}leave(){return ab(this,null,function*(){var e;try{yield this.doHeartbeat();}catch(sD){}this._log.info(\"leave() => leaving room\"),xO.emit(FO.LEAVE_SEND_CMD,{room:this}),null==(e=this._signalChannel)||e.send(sV);});}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=zw.run(wD,this.doHeartbeat.bind(this),{delay:2e3}));}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info(\"stopHeartbeat\"),zw.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1);}doHeartbeat(){return ab(this,null,function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});if(this.badCaseDetector.resetMonitor(),null==(e=this._signalChannel)||!e.isConnected)return;let n=this._signalChannel.isConnected?function(e){if(GL.has(e)){let t=GL.get(e).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc}));return GL.delete(e),t;}return[];}(this.userId):[],r=$C({str_sdk_version:nN,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:kN[this._networkType]},msg_event_msg:n,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i);xO.emit(FO.HEARTBEAT_REPORT,{room:this,report:r}),this._signalChannel.send(aV,r),this.emit(\"heartbeat-report\",eb($C({},r),{bytes_sent:this._stats.totalBytesSent+this._signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this._signalChannel.bytesReceived}));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:n}=e,r=this.remotePublishedUserMap.get(t);return r&&this._changeBigSmallRecords.has(t)&&this.checkSubscribeBigSmallVideo(r),{userId:t,tinyId:i,flag:n};});xO.emit(FO.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:n}=e,r=new(this.singlePC?hU:JV)({userId:t,tinyId:i,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:n});this.userManager.addRemotePublishedUser(r),this.installDownlinkEvents(r,t),this.emit(\"remote-published\",r);}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!==mb.ICE_TRANSPORT_ERROR&&(i===mb.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit(\"error\",e));}),e.on(\"connection-state-changed\",t=>{this.emit(\"media-connection-state-changed\",eb($C({},t),{userId:e.userId}));}),e.on(\"firewall-restriction\",()=>{this.emit(\"firewall-restriction\");});}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=zw.run(wD,this.syncUserList.bind(this)));}stopSyncUserListInterval(){zw.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:IV,responseCommand:nV.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(e=>{let{data:t}=e,{code:i,message:n}=t;if(0===i)return(t.data&&t.data.userList||[]).map(e=>{let{userId:t,srcTinyId:i,role:n}=e;return{userId:t,tinyId:i,role:n};});throw qO({key:JO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:nV.USER_LIST_RES,code:i,message:n}});}):Promise.reject(\"not connected\");}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e;}isRelayMaybeFailed(){if(this._signalChannel&&!this._signalChannel.isOnline||!xV)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{if(e instanceof UV&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===iD.CLOSED&&(this._log.warn(\"[\".concat(e.getUserId(),\"] pc is closed but not reconnect\")),e.startReconnection());}});}fallbackToMPC(){return ab(this,null,function*(){var e;if(this._log.warn(\"fallback to multi pc\"),Qw.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 qV({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 JV({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||(this._signalChannel&&(this._log.info(\"destroying SignalChannel\"),this._signalChannel.close(),this._signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new gb({code:mb.INVALID_OPERATION,message:qO({key:JO.CLIENT_DESTROYED,data:{funName:\"join\"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners());}switchRole(e){return ab(this,null,function*(){this.role!==e&&(\"audience\"===e&&this.uplinkConnection&&this.closeUplink(\"you switch role to audience\"),yield this.doSwitchRole(e));});}doSwitchRole(e){let t={command:vV,data:{role:\"anchor\"===e?20:21,privateMapKey:this.privateMapKey},responseCommand:nV.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:n}=t.data;if(0!==i)throw new gb({code:mb.SWITCH_ROLE_FAILED,message:qO({key:JO.SWITCH_ROLE_FAILED,data:{message:n,code:i}})});this.role=e;}).catch(e=>{throw e instanceof gb&&e.getCode()===mb.API_CALL_TIMEOUT&&(e=new gb({code:mb.SWITCH_ROLE_FAILED,message:qO({key:JO.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e;});}publish(){for(var e=arguments.length,t=new Array(e),i=0;i{t instanceof oL&&(t instanceof lL?i.audio=t:e.audio=t),t instanceof sL&&(t instanceof cL&&2===t.mediaType?i.video=t:e.video=t);});let n=TU(e),r=TU(i);(!n||!r)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new lU({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new qV({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\",eb($C({},e),{userId:this.userId}));}),this.uplinkConnection.on(\"firewall-restriction\",()=>{this.emit(\"firewall-restriction\");}),this.uplinkConnection.on(\"error\",e=>{let t=e.getCode();t!==mb.ICE_TRANSPORT_ERROR&&(t===mb.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit(\"error\",e));}));let o=t.map(e=>e.kind).join(\",\");n||(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\")),r||(this._log.info(\"publish() => aux \".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:i.audio,localVideoTrack:i.video,isAuxiliary:!0}),this._log.info(\"aux is published\"));});}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i{!t.mediaTrack||(t instanceof oL&&(t instanceof lL?i.audio=t:e.audio=t),t instanceof sL&&(t instanceof cL&&2===t.mediaType?i.video=t:e.video=t));});try{let n=t.map(e=>e.kind).join(\",\");TU(e)||(this._log.info(\"unpublish() => main \".concat(n)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),TU(i)||(this._log.info(\"unpublish() => aux \".concat(n)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}));}catch(n){}0===this.localTracks.size&&!this.audioManager.mixedAudioTrack&&this.closeUplink(\"you unpublished\");});}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t;}removeTrack(e){return this.uplinkConnection&&e.mediaTrack?this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t)):Promise.resolve();}replaceTrack(e){return this.uplinkConnection&&e.mediaTrack?this.uplinkConnection.replaceTrack(e).then(t=>{xO.emit(FO.LOCAL_TRACK_REPLACED,{track:e});}):Promise.resolve();}setBandWidth(e){return ab(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings());});}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i!e.isSubscribed),0===t.length)return;let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let n=t.find(e=>2===e.mediaType)?\"auxiliary\":\"main\";try{let r=$C({},i.subscribeState);t.forEach(e=>{switch(e.mediaType){case 1:r.audio=!0;break;case 4:r.video=!0;break;case 2:r.auxiliary=!0;}});let o=this._changeBigSmallRecords.get(e);o&&o.options.smallVideo&&i.muteState.hasSmall&&r.video&&(r.video=!1,r.smallVideo=!0),xO.emit(FO.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:i,subscribeState:r}),this._log.info(\"subscribe() => \".concat(e,\" \").concat(n,\" [\").concat(jV(r),\"] prev: [\").concat(jV(i.subscribeState),\"]\")),yield i.subscribe(r,n);for(let e of t)e.mediaTrack||(yield e.waitHasMediaTrack());i.remoteVideoTrack.setMediaType(r.smallVideo?8:4),xO.emit(FO.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:i});}catch(cN){let i=cN instanceof gb?cN.getCode():mb.UNKNOWN,r=cN;throw cN instanceof gb?i===mb.REMOTE_STREAM_NOT_EXIST&&(r=new gb({code:mb.API_CALL_ABORTED,message:qO({key:JO.API_CALL_ABORTED,data:{message:cN.message,userId:e,streamType:n}})}),this._log.warn(r)):(r=new gb({code:i,message:qO({key:JO.SUBSCRIBE_FAILED,data:{message:cN.message,userId:e,streamType:n}})}),this._log.error(r)),r;}});}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i2===e.mediaType)?\"auxiliary\":\"main\";this._log.info(\"unsubscribe() => \".concat(e,\" \").concat(n));try{yield i.unsubscribe({remoteTracks:t,streamType:n});}catch(cN){this._log.warn(\"unsubscribe() => failed \".concat(cN));}t.forEach(e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4);}),xO.emit(FO.UNSUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:i});});}setEncodedDataProcessingListener(e){throw new Error(\"Method not implemented.\");}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1?arguments[1]:void 0;if(e<=0)return this._enableAudioVolumeEvaluation=!1,void zw.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),xO.emit(FO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&zw.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=zw.run(PD,()=>{var e;let t=[];null==(e=this.remotePublishedUserMap)||e.forEach(e=>{if(e.muteState.hasAudio){let i=Math.floor(100*e.remoteAudioTrack.getAudioLevel());t.push({userId:e.userId,volume:i});}}),this.emit(\"audio-volume\",t);},{fps:1e3/e,backgroundTask:t});}getLocalAudioStats(){return ab(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 ab(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:n,framesSent:r,frameWidth:o,frameHeight:s}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:i,framesEncoded:n,framesSent:r,frameWidth:o,frameHeight:s};}return e;});}getTransportStats(){return ab(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt;}for(let[,t]of this.remotePublishedUserMap){let i=yield this._stats.getReceiverStats(t);e.downlinksRTT[i.userId]=i.rtt;}return e;});}getRemoteVideoStats(e){return ab(this,null,function*(){let t={};for(let[i,n]of this.remotePublishedUserMap)\"main\"===e&&n.muteState.hasVideo&&(t[i]=n.remoteVideoTrack.stat),\"auxiliary\"===e&&n.muteState.hasAuxiliary&&(t[i]=n.remoteAuxiliaryTrack.stat);return t;});}getRemoteAudioStats(){return ab(this,null,function*(){let e={};for(let[t,i]of this.remotePublishedUserMap)i.muteState.hasAudio&&(e[t]=i.remoteAudioTrack.stat);return e;});}setTurnServer(e,t){this._log.info(\"set turn server: \".concat(JSON.stringify(e),\" \").concat(t||\"\"));let i=[];Array.isArray(e)?e.forEach(e=>i.push(Ib.getTurnServer(e))):Ib.isPlainObject(e)&&i.push(Ib.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t);}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:EV,data:e,timeout:5e3,responseCommand:nV.START_MIX_TRANSCODE_RES,commandDesc:\"startMixTranscode\"});}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:SV,data:e,timeout:5e3,responseCommand:nV.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?mV:gV,data:e,timeout:5e3,responseCommand:t?nV.START_PUBLISH_TENCENT_CDN_RES:nV.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?fV:TV,data:e,timeout:5e3,responseCommand:t?nV.STOP_PUBLISH_TENCENT_CDN_RES:nV.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:\"stopPublishCDN\"});}sendAbilityStatus(e){var t;null==(t=this._signalChannel)||t.sendWaitForResponse({command:kV,data:e,timeout:5e3,responseCommand:nV.ABILITY_STATUS_REPORT_RESULT,commandDesc:\"ability status report\"}).catch(e=>{});}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=Ib.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())||{clientIp:\"\",relayIp:\"\"};}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink(\"you exitRoom\"),this._signalChannel&&(e&&this._signalChannel.keepAlive&&this._signalChannel.isConnected?this._signalChannel.stopKeepAliveIn(3600):this._signalChannel.close(),this.setSignalChannel(null)),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null};}checkSubscribeBigSmallVideo(e){return ab(this,null,function*(){let 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 n=e.getUserId(),r=this._changeBigSmallRecords.get(n)||{},{subscribeState:o}=e,{options:s,isSubscribing:a,reSubscribeCount:c}=r;if(s.video&&o.video||s.smallVideo&&o.smallVideo&&t||a)return;let l={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:s.video,smallVideo:s.smallVideo};if(t&&e.isBigStreamSubscribed||e.isSmallStreamSubscribed)try{s&&!a&&c>=1&&(r.isSubscribing=!0,r.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(n,\"] to \").concat(l.smallVideo?\"small\":\"big\",\" video successfully. count \").concat(DD-r.reSubscribeCount,\".\")),r.isSubscribing=!1,r.reSubscribeCount=DD);}catch(d){this._log.info(\"change [\".concat(n,\"] to \").concat(l.smallVideo?\"small\":\"big\",\" video failed. count \").concat(DD-r.reSubscribeCount,\".\")),r.isSubscribing=!1,0===c&&this._changeBigSmallRecords.delete(n);}});}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:DD};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(pU(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!mU(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new gb({code:mb.INVALID_PARAMETER,message:qO({key:JO.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode;}if(!mU(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new gb({code:mb.INVALID_PARAMETER,message:qO({key:JO.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId;}if(!mU(e.userDefinePushArgs)){if(!(pU(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new gb({code:mb.INVALID_PARAMETER,message:qO({key:JO.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;}TU(t)||(this._businessInfo=JSON.stringify(t));}sendSEI(e,t){var i;null==(i=this.uplinkConnection)||i.sendSEI(e,t);}};return rb([Bw([\"left\",Gw.INIT],\"joined\"),tx({settings:{retries:1,timeout:0},onError(e,t,i){this._isUsingCachedSchedule&&!this._isDestroyed?(this._log.warn(\"is using cached schedule, retry join\"),mx(!0),this.reset(),t()):this._signalChannel&&this._signalChannel.isConnected&&this._signalChannel.keepAlive?(this._log.warn(\"is using keepAlive ws, retry join\"),this._signalChannel.close(),this.reset(),t()):(this.reset(),this._log.error(e),i(e));}}),iL(e=>{let t=new WM();return function(i,n,r){return ab(this,null,function*(){let o=String(i.roomId||i.strRoomId);if(this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.userSig=i.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=n,i.privateMapKey=i.privateMapKey||\"\",this.isJoined)throw new gb({code:mb.INVALID_OPERATION,message:qO({key:JO.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new gb({code:mb.INVALID_OPERATION,message:qO({key:JO.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:o}),this.role=21===i.role?\"audience\":\"anchor\",this._log.info(\"Join() => joining room: \".concat(o,\" useStringRoomId: \").concat(this.useStringRoomId,\" scene: \").concat(this.scene,\" role: \").concat(this.role)),xO.emit(FO.JOIN_START,{room:this,roomId:o,params:i}),this.checkSystemResult=yield WO.checkSystemRequirementsInternal(),this.checkDestroy();let s=Ib.getEnv();s||(s=AN.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(VN.OLD_CLOUD_LADDER)?s=AN.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(VN.WEBRTC)&&(s=AN.WEBRTC))),Qw.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),JM.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!WO.isWebRTCSupported()||!a&&!c)throw new gb({code:mb.NOT_SUPPORTED,message:qO({key:JO.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Ib.getEnv()&&(yield this.schedule(o,r,rN));let t=yield e.call(this,i,n,r);return this.roomId=o,this._joinedTimestamp=Ib.performanceNow(),xO.emit(FO.JOIN_SUCCESS,{room:this}),Qw.uploadEvent({log:\"stat-conv-\".concat(Number(Yk),\"-\").concat(location.hostname),userId:this.userId}),t;}catch(l){throw t.delete({room:this,roomId:o}),xO.emit(FO.JOIN_FAILED,{room:this,error:l}),l;}});};})],EU.prototype,\"join\",1),rb([Bw(\"joined\",\"left\",{ignoreError:!0,success(){this.reset(!0);}}),iL(e=>function(){return ab(this,null,function*(){xO.emit(FO.LEAVE_START,{room:this}),yield e.call(this),xO.emit(FO.LEAVE_SUCCESS,{room:this,roomId:this.roomId});});}),function(e){return function(t,i,n){let r=n.value;return n.value=function(){var t,i;let n=[];for(var o=arguments.length,s=new Array(o),a=0;an.push(e)),null==(i=Hx.get(this))||i.forEach(e=>e.forEach(e=>n.push(e))),n.forEach(t=>{t.reject(new gb({code:mb.API_CALL_ABORTED,message:e}));}),Bx.delete(this),Hx.delete(this),r.apply(this,s);},n;};}(\"leave room\"),ix({fnName:\"publish\",validateArgs:!1}),ix({fnName:\"unsubscribe\",validateArgs:!1})],EU.prototype,\"leave\",1),rb([jx(),iL(e=>function(){for(var t=arguments.length,i=new Array(t),n=0;ne.outMediaTrack&&\"capture\"===e.state),!i.length))return;xO.emit(\"61\",{room:this}),i.forEach(e=>{\"audio\"===e.kind&&this.audioManager.addAudioTrack(e);});let t=e.apply(this,i);return i.forEach(e=>{var i;e.publish(this,t),\"audio\"===e.kind&&(null==(i=this.audioManager.localMixAudioTrack)||i.publish(this,t));}),t;});}),tx({settings:{retries:oD,timeout:e=>eO(e)},onError(e,t,i){var n;null!=(n=e.message)&&n.includes(\"timeout\")?(this._log.warn(\"publish timeout\"),t()):(this._log.error(\"publish failed: \".concat(e)),i(e),xO.emit(FO.PUBLISH_FAILED,{room:this}));}})],EU.prototype,\"publish\",1),rb([ix({fnName:\"publish\",callback(){for(var e,t=arguments.length,i=new Array(t),n=0;ne.unpublish()));}}),function(e){return function(t,i,n){let r=n.value;return n.value=function(){for(var t=arguments.length,i=new Array(t),n=0;n{if(0===n)return!0;let r=!0;return t.args.forEach(e=>{i.find(t=>t===e)||(r=!1);}),!r||(t.reject(new gb({code:mb.API_CALL_ABORTED,message:e})),!1);});Bx.set(this,t);}return r.apply(this,i);},n;};}(\"api-call\"),jx(),iL(e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n{\"audio\"===e.kind&&this.audioManager.removeAudioTrack(e);});let r=e.apply(this,i);return i.forEach(e=>e.unpublish()),r;})],EU.prototype,\"unpublish\",1),rb([Gx(function(){for(var e=arguments.length,t=new Array(e),i=0;ifunction(){for(var t=arguments.length,i=new Array(t),n=0;n!e.isSubscribed&&e.subscribe(r)),r;}),tx({settings:{retries:oD,timeout:e=>eO(e)},onError(e,t,i,n){e.message.includes(\"timeout\")?(this._log.warn(\"subscribe timeout\"),t()):(this._log.error(\"subscribe failed: \".concat(e)),i(e),xO.emit(FO.SUBSCRIBE_FAILED,{room:this,remoteTracks:n}));}})],EU.prototype,\"subscribe\",1),rb([ix({fnName:\"subscribe\",callback(){for(var e=arguments.length,t=new Array(e),i=0;i{let t=this.remotePublishedUserMap.get(e.userId);t&&!t.isMainStreamSubscribed&&!t.isAuxStreamSubscribed&&t.close(\"you unsubscribed\");});}}),Gx(function(){for(var e=arguments.length,t=new Array(e),i=0;i0&&V[0]<4?1:+(V[0]+V[1])),!x&&X&&(!(V=X.match(/Edge\\/(\\d+)/))||V[1]>=74)&&(V=X.match(/Chrome\\/(\\d+)/))&&(x=+V[1]);var ie=x,ne=ie,re=i,oe=!!Object.getOwnPropertySymbols&&!re((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),se=oe&&!Symbol.sham&&\"symbol\"==typeof Symbol.iterator,ae=b,ce=G,le=z,de=oe,ue=se,he=C.Symbol,pe=ae(\"wks\"),_e=ue?he.for||he:he&&he.withoutSetter||le,me=function(e){return ce(pe,e)||(pe[e]=de&&ce(he,e)?he[e]:_e(\"Symbol.\"+e)),pe[e]},fe=\"object\"==typeof document&&document.all,ge={all:fe,IS_HTMLDDA:void 0===fe&&void 0!==fe},Te=ge.all,Ee=ge.IS_HTMLDDA?function(e){return\"function\"==typeof e||e===Te}:function(e){return\"function\"==typeof e},Se=Ee,Ie=ge.all,ve=ge.IS_HTMLDDA?function(e){return\"object\"==typeof e?null!==e:Se(e)||e===Ie}:function(e){return\"object\"==typeof e?null!==e:Se(e)},ye=ve,Ae=String,Re=TypeError,Ce=function(e){if(ye(e))return e;throw Re(Ae(e)+\" is not an object\")},be={},ke=!i((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),Ne=ke&&i((function(){return 42!=Object.defineProperty((function(){}),\"prototype\",{value:42,writable:!1}).prototype})),De={},Oe=ve,we=C.document,Pe=Oe(we)&&Oe(we.createElement),Le=function(e){return Pe?we.createElement(e):{}},Me=Le,Ve=!ke&&!i((function(){return 7!=Object.defineProperty(Me(\"div\"),\"a\",{get:function(){return 7}}).a})),xe=n,Ue=Function.prototype.call,Fe=xe?Ue.bind(Ue):function(){return Ue.apply(Ue,arguments)},Be=C,He=Ee,je=function(e,t){return arguments.length<2?(i=Be[e],He(i)?i:void 0):Be[e]&&Be[e][t];var i},Ge=c({}.isPrototypeOf),We=je,Je=Ee,Ke=Ge,Ye=Object,ze=se?function(e){return\"symbol\"==typeof e}:function(e){var t=We(\"Symbol\");return Je(t)&&Ke(t.prototype,Ye(e))},qe=String,Qe=function(e){try{return qe(e)}catch(t){return\"Object\"}},Xe=Ee,Ze=Qe,$e=TypeError,et=function(e){if(Xe(e))return e;throw $e(Ze(e)+\" is not a function\")},tt=et,it=T,nt=function(e,t){var i=e[t];return it(i)?void 0:tt(i)},rt=Fe,ot=Ee,st=ve,at=TypeError,ct=Fe,lt=ve,dt=ze,ut=nt,ht=function(e,t){var i,n;if(\"string\"===t&&ot(i=e.toString)&&!st(n=rt(i,e)))return n;if(ot(i=e.valueOf)&&!st(n=rt(i,e)))return n;if(\"string\"!==t&&ot(i=e.toString)&&!st(n=rt(i,e)))return n;throw at(\"Can't convert object to primitive value\")},pt=TypeError,_t=me(\"toPrimitive\"),mt=function(e,t){if(!lt(e)||dt(e))return e;var i,n=ut(e,_t);if(n){if(void 0===t&&(t=\"default\"),i=ct(n,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=mt,gt=ze,Tt=function(e){var t=ft(e,\"string\");return gt(t)?t:t+\"\"},Et=ke,St=Ve,It=Ne,vt=Ce,yt=Tt,At=TypeError,Rt=Object.defineProperty,Ct=Object.getOwnPropertyDescriptor,bt=\"enumerable\",kt=\"configurable\",Nt=\"writable\";De.f=Et?It?function(e,t,i){if(vt(e),t=yt(t),vt(i),\"function\"==typeof e&&\"prototype\"===t&&\"value\"in i&&Nt in i&&!i[Nt]){var n=Ct(e,t);n&&n[Nt]&&(e[t]=i.value,i={configurable:kt in i?i[kt]:n[kt],enumerable:bt in i?i[bt]:n[bt],writable:!1})}return Rt(e,t,i)}:Rt:function(e,t,i){if(vt(e),t=yt(t),vt(i),St)try{return Rt(e,t,i)}catch(n){}if(\"get\"in i||\"set\"in i)throw At(\"Accessors not supported\");return\"value\"in i&&(e[t]=i.value),e};var Dt=Math.ceil,Ot=Math.floor,wt=Math.trunc||function(e){var t=+e;return(t>0?Ot:Dt)(t)},Pt=wt,Lt=function(e){var t=+e;return t!=t||0===t?0:Pt(t)},Mt=Lt,Vt=Math.max,xt=Math.min,Ut=function(e,t){var i=Mt(e);return i<0?Vt(i+t,0):xt(i,t)},Ft=Lt,Bt=Math.min,Ht=function(e){return e>0?Bt(Ft(e),9007199254740991):0},jt=Ht,Gt=function(e){return jt(e.length)},Wt=A,Jt=Ut,Kt=Gt,Yt=function(e){return function(t,i,n){var r,o=Wt(t),s=Kt(o),a=Jt(n,s);if(e&&i!=i){for(;s>a;)if((r=o[a++])!=r)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===i)return e||a||0;return!e&&-1}},zt={includes:Yt(!0),indexOf:Yt(!1)},qt={},Qt=G,Xt=A,Zt=zt.indexOf,$t=qt,ei=c([].push),ti=function(e,t){var i,n=Xt(e),r=0,o=[];for(i in n)!Qt($t,i)&&Qt(n,i)&&ei(o,i);for(;t.length>r;)Qt(n,i=t[r++])&&(~Zt(o,i)||ei(o,i));return o},ii=[\"constructor\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"toLocaleString\",\"toString\",\"valueOf\"],ni=ti,ri=ii,oi=Object.keys||function(e){return ni(e,ri)},si=ke,ai=Ne,ci=De,li=Ce,di=A,ui=oi;be.f=si&&!ai?Object.defineProperties:function(e,t){li(e);for(var i,n=di(t),r=ui(t),o=r.length,s=0;o>s;)ci.f(e,i=r[s++],n[i]);return e};var hi,pi=je(\"document\",\"documentElement\"),_i=z,mi=b(\"keys\"),fi=function(e){return mi[e]||(mi[e]=_i(e))},gi=Ce,Ti=be,Ei=ii,Si=qt,Ii=pi,vi=Le,yi=\"prototype\",Ai=\"script\",Ri=fi(\"IE_PROTO\"),Ci=function(){},bi=function(e){return\"<\"+Ai+\">\"+e+\"\"},ki=function(e){e.write(bi(\"\")),e.close();var t=e.parentWindow.Object;return e=null,t},Ni=function(){try{hi=new ActiveXObject(\"htmlfile\")}catch(r){}var e,t,i;Ni=\"undefined\"!=typeof document?document.domain&&hi?ki(hi):(t=vi(\"iframe\"),i=\"java\"+Ai+\":\",t.style.display=\"none\",Ii.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(bi(\"document.F=Object\")),e.close(),e.F):ki(hi);for(var n=Ei.length;n--;)delete Ni[yi][Ei[n]];return Ni()};Si[Ri]=!0;var Di=Object.create||function(e,t){var i;return null!==e?(Ci[yi]=gi(e),i=new Ci,Ci[yi]=null,i[Ri]=e):i=Ni(),void 0===t?i:Ti.f(i,t)},Oi=me,wi=Di,Pi=De.f,Li=Oi(\"unscopables\"),Mi=Array.prototype;null==Mi[Li]&&Pi(Mi,Li,{configurable:!0,value:wi(null)});var Vi,xi,Ui,Fi=function(e){Mi[Li][e]=!0},Bi={},Hi=Ee,ji=C.WeakMap,Gi=Hi(ji)&&/native code/.test(String(ji)),Wi=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},Ji=De,Ki=Wi,Yi=ke?function(e,t,i){return Ji.f(e,t,Ki(1,i))}:function(e,t,i){return e[t]=i,e},zi=Gi,qi=C,Qi=ve,Xi=Yi,Zi=G,$i=L,en=fi,tn=qt,nn=\"Object already initialized\",rn=qi.TypeError,on=qi.WeakMap;if(zi||$i.state){var sn=$i.state||($i.state=new on);sn.get=sn.get,sn.has=sn.has,sn.set=sn.set,Vi=function(e,t){if(sn.has(e))throw rn(nn);return t.facade=e,sn.set(e,t),t},xi=function(e){return sn.get(e)||{}},Ui=function(e){return sn.has(e)}}else{var an=en(\"state\");tn[an]=!0,Vi=function(e,t){if(Zi(e,an))throw rn(nn);return t.facade=e,Xi(e,an,t),t},xi=function(e){return Zi(e,an)?e[an]:{}},Ui=function(e){return Zi(e,an)}}var cn={set:Vi,get:xi,has:Ui,enforce:function(e){return Ui(e)?xi(e):Vi(e,{})},getterFor:function(e){return function(t){var i;if(!Qi(t)||(i=xi(t)).type!==e)throw rn(\"Incompatible receiver, \"+e+\" required\");return i}}},ln={},dn={},un={}.propertyIsEnumerable,hn=Object.getOwnPropertyDescriptor,pn=hn&&!un.call({1:2},1);dn.f=pn?function(e){var t=hn(this,e);return!!t&&t.enumerable}:un;var _n=ke,mn=Fe,fn=dn,gn=Wi,Tn=A,En=Tt,Sn=G,In=Ve,vn=Object.getOwnPropertyDescriptor;ln.f=_n?vn:function(e,t){if(e=Tn(e),t=En(t),In)try{return vn(e,t)}catch(i){}if(Sn(e,t))return gn(!mn(fn.f,e,t),e[t])};var yn={},An={get exports(){return yn},set exports(e){yn=e}},Rn=ke,Cn=G,bn=Function.prototype,kn=Rn&&Object.getOwnPropertyDescriptor,Nn=Cn(bn,\"name\"),Dn={EXISTS:Nn,PROPER:Nn&&\"something\"===function(){}.name,CONFIGURABLE:Nn&&(!Rn||Rn&&kn(bn,\"name\").configurable)},On=Ee,wn=L,Pn=c(Function.toString);On(wn.inspectSource)||(wn.inspectSource=function(e){return Pn(e)});var Ln=wn.inspectSource,Mn=c,Vn=i,xn=Ee,Un=G,Fn=ke,Bn=Dn.CONFIGURABLE,Hn=Ln,jn=cn.enforce,Gn=cn.get,Wn=String,Jn=Object.defineProperty,Kn=Mn(\"\".slice),Yn=Mn(\"\".replace),zn=Mn([].join),qn=Fn&&!Vn((function(){return 8!==Jn((function(){}),\"length\",{value:8}).length})),Qn=String(String).split(\"String\"),Xn=An.exports=function(e,t,i){\"Symbol(\"===Kn(Wn(t),0,7)&&(t=\"[\"+Yn(Wn(t),/^Symbol\\(([^)]*)\\)/,\"$1\")+\"]\"),i&&i.getter&&(t=\"get \"+t),i&&i.setter&&(t=\"set \"+t),(!Un(e,\"name\")||Bn&&e.name!==t)&&(Fn?Jn(e,\"name\",{value:t,configurable:!0}):e.name=t),qn&&i&&Un(i,\"arity\")&&e.length!==i.arity&&Jn(e,\"length\",{value:i.arity});try{i&&Un(i,\"constructor\")&&i.constructor?Fn&&Jn(e,\"prototype\",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(r){}var n=jn(e);return Un(n,\"source\")||(n.source=zn(Qn,\"string\"==typeof t?t:\"\")),e};Function.prototype.toString=Xn((function(){return xn(this)&&Gn(this).source||Hn(this)}),\"toString\");var Zn=Ee,$n=De,er=yn,tr=O,ir=function(e,t,i,n){n||(n={});var r=n.enumerable,o=void 0!==n.name?n.name:t;if(Zn(i)&&er(i,o,n),n.global)r?e[t]=i:tr(t,i);else{try{n.unsafe?e[t]&&(r=!0):delete e[t]}catch(s){}r?e[t]=i:$n.f(e,t,{value:i,enumerable:!1,configurable:!n.nonConfigurable,writable:!n.nonWritable})}return e},nr={},rr=ti,or=ii.concat(\"length\",\"prototype\");nr.f=Object.getOwnPropertyNames||function(e){return rr(e,or)};var sr={};sr.f=Object.getOwnPropertySymbols;var ar,cr,lr,dr=je,ur=nr,hr=sr,pr=Ce,_r=c([].concat),mr=dr(\"Reflect\",\"ownKeys\")||function(e){var t=ur.f(pr(e)),i=hr.f;return i?_r(t,i(e)):t},fr=G,gr=mr,Tr=ln,Er=De,Sr=function(e,t,i){for(var n=gr(t),r=Er.f,o=Tr.f,s=0;s=t.length?(e.target=void 0,Qo(void 0,!0)):Qo(\"keys\"==i?n:\"values\"==i?t[n]:[n,t[n]],!1)}),\"values\"),is=Ko.Arguments=Ko.Array;if(Jo(\"keys\"),Jo(\"values\"),Jo(\"entries\"),Xo&&\"values\"!==is.name)try{zo(is,\"name\",{value:\"values\"})}catch(SU){}var ns={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},rs=Le(\"span\").classList,os=rs&&rs.constructor&&rs.constructor.prototype,ss=os===Object.prototype?void 0:os,as=C,cs=ns,ls=ss,ds=ts,us=Yi,hs=me,ps=hs(\"iterator\"),_s=hs(\"toStringTag\"),ms=ds.values,fs=function(e,t){if(e){if(e[ps]!==ms)try{us(e,ps,ms)}catch(SU){e[ps]=ms}if(e[_s]||us(e,_s,t),cs[t])for(var i in ds)if(e[i]!==ds[i])try{us(e,i,ds[i])}catch(SU){e[i]=ds[i]}}};for(var gs in cs)fs(as[gs]&&as[gs].prototype,gs);fs(ls,\"DOMTokenList\");var Ts=\"undefined\"!=typeof process&&\"process\"==h(process),Es=yn,Ss=De,Is=function(e,t,i){return i.get&&Es(i.get,t,{getter:!0}),i.set&&Es(i.set,t,{setter:!0}),Ss.f(e,t,i)},vs=je,ys=Is,As=ke,Rs=me(\"species\"),Cs=function(e){var t=vs(e);As&&t&&!t[Rs]&&ys(t,Rs,{configurable:!0,get:function(){return this}})},bs=Ge,ks=TypeError,Ns=function(e,t){if(bs(t,e))return e;throw ks(\"Incorrect invocation\")},Ds={};Ds[me(\"toStringTag\")]=\"z\";var Os=\"[object z]\"===String(Ds),ws=Ee,Ps=h,Ls=me(\"toStringTag\"),Ms=Object,Vs=\"Arguments\"==Ps(function(){return arguments}()),xs=Os?Ps:function(e){var t,i,n;return void 0===e?\"Undefined\":null===e?\"Null\":\"string\"==typeof(i=function(e,t){try{return e[t]}catch(SU){}}(t=Ms(e),Ls))?i:Vs?Ps(t):\"Object\"==(n=Ps(t))&&ws(t.callee)?\"Arguments\":n},Us=c,Fs=i,Bs=Ee,Hs=xs,js=Ln,Gs=function(){},Ws=[],Js=je(\"Reflect\",\"construct\"),Ks=/^\\s*(?:class|function)\\b/,Ys=Us(Ks.exec),zs=!Ks.exec(Gs),qs=function(e){if(!Bs(e))return!1;try{return Js(Gs,Ws,e),!0}catch(SU){return!1}},Qs=function(e){if(!Bs(e))return!1;switch(Hs(e)){case\"AsyncFunction\":case\"GeneratorFunction\":case\"AsyncGeneratorFunction\":return!1}try{return zs||!!Ys(Ks,js(e))}catch(SU){return!0}};Qs.sham=!0;var Xs,Zs,$s,ea,ta=!Js||Fs((function(){var e;return qs(qs.call)||!qs(Object)||!qs((function(){e=!0}))||e}))?Qs:qs,ia=ta,na=Qe,ra=TypeError,oa=function(e){if(ia(e))return e;throw ra(na(e)+\" is not a constructor\")},sa=Ce,aa=oa,ca=T,la=me(\"species\"),da=function(e,t){var i,n=sa(e).constructor;return void 0===n||ca(i=sa(n)[la])?t:aa(i)},ua=n,ha=Function.prototype,pa=ha.apply,_a=ha.call,ma=\"object\"==typeof Reflect&&Reflect.apply||(ua?_a.bind(pa):function(){return _a.apply(pa,arguments)}),fa=h,ga=c,Ta=function(e){if(\"Function\"===fa(e))return ga(e)},Ea=et,Sa=n,Ia=Ta(Ta.bind),va=function(e,t){return Ea(e),void 0===t?e:Sa?Ia(e,t):function(){return e.apply(t,arguments)}},ya=c([].slice),Aa=TypeError,Ra=function(e,t){if(eo;o++)if((a=g(e[o]))&&Td(Ad,a))return a;return new yd(!1)}n=Ed(e,r)}for(c=h?e.next:n.next;!(l=pd(c,n)).done;){try{a=g(l.value)}catch(SU){Id(n,\"throw\",SU)}if(\"object\"==typeof a&&a&&Td(Ad,a))return a}return new yd(!1)},Cd=me(\"iterator\"),bd=!1;try{var kd=0,Nd={next:function(){return{done:!!kd++}},return:function(){bd=!0}};Nd[Cd]=function(){return this},Array.from(Nd,(function(){throw 2}))}catch(SU){}var Dd=function(e,t){if(!t&&!bd)return!1;var i=!1;try{var n={};n[Cd]=function(){return{next:function(){return{done:i=!0}}}},e(n)}catch(SU){}return i},Od=kc,wd=Wc.CONSTRUCTOR||!Dd((function(e){Od.all(e).then(void 0,(function(){}))})),Pd=Fe,Ld=et,Md=Jc,Vd=bc,xd=Rd;xr({target:\"Promise\",stat:!0,forced:wd},{all:function(e){var t=this,i=Md.f(t),n=i.resolve,r=i.reject,o=Vd((function(){var i=Ld(t.resolve),o=[],s=0,a=1;xd(e,(function(e){var c=s++,l=!1;a++,Pd(i,t,e).then((function(e){l||(l=!0,o[c]=e,--a||n(o))}),r)})),--a||n(o)}));return o.error&&r(o.value),i.promise}});var Ud=xr,Fd=Wc.CONSTRUCTOR,Bd=kc,Hd=je,jd=Ee,Gd=ir,Wd=Bd&&Bd.prototype;if(Ud({target:\"Promise\",proto:!0,forced:Fd,real:!0},{catch:function(e){return this.then(void 0,e)}}),jd(Bd)){var Jd=Hd(\"Promise\").prototype.catch;Wd.catch!==Jd&&Gd(Wd,\"catch\",Jd,{unsafe:!0})}var Kd=Fe,Yd=et,zd=Jc,qd=bc,Qd=Rd;xr({target:\"Promise\",stat:!0,forced:wd},{race:function(e){var t=this,i=zd.f(t),n=i.reject,r=qd((function(){var r=Yd(t.resolve);Qd(e,(function(e){Kd(r,t,e).then(i.resolve,n)}))}));return r.error&&n(r.value),i.promise}});var Xd=Fe,Zd=Jc;xr({target:\"Promise\",stat:!0,forced:Wc.CONSTRUCTOR},{reject:function(e){var t=Zd.f(this);return Xd(t.reject,void 0,e),t.promise}});var $d=Ce,eu=ve,tu=Jc,iu=function(e,t){if($d(e),eu(t)&&t.constructor===e)return t;var i=tu.f(e);return(0,i.resolve)(t),i.promise},nu=xr,ru=Wc.CONSTRUCTOR,ou=iu;je(\"Promise\"),nu({target:\"Promise\",stat:!0,forced:ru},{resolve:function(e){return ou(this,e)}});var su=Ee,au=ve,cu=vo,lu=function(e,t,i){var n,r;return cu&&su(n=t.constructor)&&n!==i&&au(r=n.prototype)&&r!==i.prototype&&cu(e,r),e},du=ve,uu=h,hu=me(\"match\"),pu=function(e){var t;return du(e)&&(void 0!==(t=e[hu])?!!t:\"RegExp\"==uu(e))},_u=xs,mu=String,fu=function(e){if(\"Symbol\"===_u(e))throw TypeError(\"Cannot convert a Symbol value to a string\");return mu(e)},gu=Ce,Tu=function(){var e=gu(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},Eu=Fe,Su=G,Iu=Ge,vu=Tu,yu=RegExp.prototype,Au=function(e){var t=e.flags;return void 0!==t||\"flags\"in yu||Su(e,\"flags\")||!Iu(yu,e)?t:Eu(vu,e)},Ru=i,Cu=C.RegExp,bu=Ru((function(){var e=Cu(\"a\",\"y\");return e.lastIndex=2,null!=e.exec(\"abcd\")})),ku=bu||Ru((function(){return!Cu(\"a\",\"y\").sticky})),Nu=bu||Ru((function(){var e=Cu(\"^r\",\"gy\");return e.lastIndex=2,null!=e.exec(\"str\")})),Du={BROKEN_CARET:Nu,MISSED_STICKY:ku,UNSUPPORTED_Y:bu},Ou=De.f,wu=i,Pu=C.RegExp,Lu=wu((function(){var e=Pu(\".\",\"s\");return!(e.dotAll&&e.exec(\"\\n\")&&\"s\"===e.flags)})),Mu=i,Vu=C.RegExp,xu=Mu((function(){var e=Vu(\"(?b)\",\"g\");return\"b\"!==e.exec(\"b\").groups.a||\"bc\"!==\"b\".replace(e,\"$c\")})),Uu=ke,Fu=C,Bu=c,Hu=Nr,ju=lu,Gu=Yi,Wu=nr.f,Ju=Ge,Ku=pu,Yu=fu,zu=Au,qu=Du,Qu=function(e,t,i){i in e||Ou(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Xu=ir,Zu=i,$u=G,eh=cn.enforce,th=Cs,ih=Lu,nh=xu,rh=me(\"match\"),oh=Fu.RegExp,sh=oh.prototype,ah=Fu.SyntaxError,ch=Bu(sh.exec),lh=Bu(\"\".charAt),dh=Bu(\"\".replace),uh=Bu(\"\".indexOf),hh=Bu(\"\".slice),ph=/^\\?<[^\\s\\d!#%&*+<=>@^][^\\s!#%&*+<=>@^]*>/,_h=/a/g,mh=/a/g,fh=new oh(_h)!==_h,gh=qu.MISSED_STICKY,Th=qu.UNSUPPORTED_Y,Eh=Uu&&(!fh||gh||ih||nh||Zu((function(){return mh[rh]=!1,oh(_h)!=_h||oh(mh)==mh||\"/a/i\"!=oh(_h,\"i\")})));if(Hu(\"RegExp\",Eh)){for(var Sh=function(e,t){var i,n,r,o,s,a,c=Ju(sh,this),l=Ku(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Sh)return e;if((l||Ju(sh,e))&&(e=e.source,d&&(t=zu(h))),e=void 0===e?\"\":Yu(e),t=void 0===t?\"\":Yu(t),h=e,ih&&\"dotAll\"in _h&&(n=!!t&&uh(t,\"s\")>-1)&&(t=dh(t,/s/g,\"\")),i=t,gh&&\"sticky\"in _h&&(r=!!t&&uh(t,\"y\")>-1)&&Th&&(t=dh(t,/y/g,\"\")),nh&&(o=function(e){for(var t,i=e.length,n=0,r=\"\",o=[],s={},a=!1,c=!1,l=0,d=\"\";n<=i;n++){if(\"\\\\\"===(t=lh(e,n)))t+=lh(e,++n);else if(\"]\"===t)a=!1;else if(!a)switch(!0){case\"[\"===t:a=!0;break;case\"(\"===t:ch(ph,hh(e,n+1))&&(n+=2,c=!0),r+=t,l++;continue;case\">\"===t&&c:if(\"\"===d||$u(s,d))throw new ah(\"Invalid capture group name\");s[d]=!0,o[o.length]=[d,l],c=!1,d=\"\";continue}c?d+=t:r+=t}return[r,o]}(e),e=o[0],u=o[1]),s=ju(oh(e,t),c?this:sh,Sh),(n||r||u.length)&&(a=eh(s),n&&(a.dotAll=!0,a.raw=Sh(function(e){for(var t,i=e.length,n=0,r=\"\",o=!1;n<=i;n++)\"\\\\\"!==(t=lh(e,n))?o||\".\"!==t?(\"[\"===t?o=!0:\"]\"===t&&(o=!1),r+=t):r+=\"[\\\\s\\\\S]\":r+=t+lh(e,++n);return r}(e),i)),r&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Gu(s,\"source\",\"\"===h?\"(?:)\":h)}catch(SU){}return s},Ih=Wu(oh),vh=0;Ih.length>vh;)Qu(Sh,oh,Ih[vh++]);sh.constructor=Sh,Sh.prototype=sh,Xu(Fu,\"RegExp\",Sh,{constructor:!0})}th(\"RegExp\");var yh=Fe,Ah=c,Rh=fu,Ch=Tu,bh=Du,kh=Di,Nh=cn.get,Dh=Lu,Oh=xu,wh=b(\"native-string-replace\",String.prototype.replace),Ph=RegExp.prototype.exec,Lh=Ph,Mh=Ah(\"\".charAt),Vh=Ah(\"\".indexOf),xh=Ah(\"\".replace),Uh=Ah(\"\".slice),Fh=function(){var e=/a/,t=/b*/g;return yh(Ph,e,\"a\"),yh(Ph,t,\"a\"),0!==e.lastIndex||0!==t.lastIndex}(),Bh=bh.BROKEN_CARET,Hh=void 0!==/()??/.exec(\"\")[1];(Fh||Hh||Bh||Dh||Oh)&&(Lh=function(e){var t,i,n,r,o,s,a,c=this,l=Nh(c),d=Rh(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=yh(Lh,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Bh&&c.sticky,_=yh(Ch,c),m=c.source,f=0,g=d;if(p&&(_=xh(_,\"y\",\"\"),-1===Vh(_,\"g\")&&(_+=\"g\"),g=Uh(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&\"\\n\"!==Mh(d,c.lastIndex-1))&&(m=\"(?: \"+m+\")\",g=\" \"+g,f++),i=new RegExp(\"^(?:\"+m+\")\",_)),Hh&&(i=new RegExp(\"^\"+m+\"$(?!\\\\s)\",_)),Fh&&(n=c.lastIndex),r=yh(Ph,p?i:c,g),p?r?(r.input=Uh(r.input,f),r[0]=Uh(r[0],f),r.index=c.lastIndex,c.lastIndex+=r[0].length):c.lastIndex=0:Fh&&r&&(c.lastIndex=c.global?r.index+r[0].length:n),Hh&&r&&r.length>1&&yh(wh,r[0],i,(function(){for(o=1;oT;T++)if((a||T in m)&&(p=f(h=m[T],T,_),e))if(t)S[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:ip(S,h)}else switch(e){case 4:return!1;case 7:ip(S,h)}return o?-1:n||r?r:S}},rp={forEach:np(0),map:np(1),filter:np(2),some:np(3),every:np(4),find:np(5),findIndex:np(6),filterReject:np(7)},op=i,sp=function(e,t){var i=[][e];return!!i&&op((function(){i.call(null,t||function(){return 1},1)}))},ap=rp.forEach,cp=sp(\"forEach\")?[].forEach:function(e){return ap(this,e,arguments.length>1?arguments[1]:void 0)},lp=C,dp=ns,up=ss,hp=cp,pp=Yi,_p=function(e){if(e&&e.forEach!==hp)try{pp(e,\"forEach\",hp)}catch(SU){e.forEach=hp}};for(var mp in dp)dp[mp]&&_p(lp[mp]&&lp[mp].prototype);_p(up);var fp=et,gp=B,Tp=g,Ep=Gt,Sp=TypeError,Ip=function(e){return function(t,i,n,r){fp(i);var o=gp(t),s=Tp(o),a=Ep(o),c=e?a-1:0,l=e?-1:1;if(n<2)for(;;){if(c in s){r=s[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw Sp(\"Reduce of empty array with no initial value\")}for(;e?c>=0:a>c;c+=l)c in s&&(r=i(r,s[c],c,o));return r}},vp={left:Ip(!1),right:Ip(!0)}.left;xr({target:\"Array\",proto:!0,forced:!Ts&&ie>79&&ie<83||!sp(\"reduce\")},{reduce:function(e){var t=arguments.length;return vp(this,e,t,t>1?arguments[1]:void 0)}});var yp=Ta,Ap=ir,Rp=jh,Cp=i,bp=me,kp=Yi,Np=bp(\"species\"),Dp=RegExp.prototype,Op=c,wp=Lt,Pp=fu,Lp=I,Mp=Op(\"\".charAt),Vp=Op(\"\".charCodeAt),xp=Op(\"\".slice),Up=function(e){return function(t,i){var n,r,o=Pp(Lp(t)),s=wp(i),a=o.length;return s<0||s>=a?e?\"\":void 0:(n=Vp(o,s))<55296||n>56319||s+1===a||(r=Vp(o,s+1))<56320||r>57343?e?Mp(o,s):n:e?xp(o,s,s+2):r-56320+(n-55296<<10)+65536}},Fp={codeAt:Up(!1),charAt:Up(!0)},Bp=Fp.charAt,Hp=c,jp=B,Gp=Math.floor,Wp=Hp(\"\".charAt),Jp=Hp(\"\".replace),Kp=Hp(\"\".slice),Yp=/\\$([$&'`]|\\d{1,2}|<[^>]*>)/g,zp=/\\$([$&'`]|\\d{1,2})/g,qp=function(e,t,i,n,r,o){var s=i+e.length,a=n.length,c=zp;return void 0!==r&&(r=jp(r),c=Yp),Jp(o,c,(function(o,c){var l;switch(Wp(c,0)){case\"$\":return\"$\";case\"&\":return e;case\"`\":return Kp(t,0,i);case\"'\":return Kp(t,s);case\"<\":l=r[Kp(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Gp(d/10);return 0===u?o:u<=a?void 0===n[u-1]?Wp(c,1):n[u-1]+Wp(c,1):o}l=n[d-1]}return void 0===l?\"\":l}))},Qp=Fe,Xp=Ce,Zp=Ee,$p=h,e_=jh,t_=TypeError,i_=ma,n_=Fe,r_=c,o_=function(e,t,i,n){var r=bp(e),o=!Cp((function(){var t={};return t[r]=function(){return 7},7!=\"\"[e](t)})),s=o&&!Cp((function(){var t=!1,i=/a/;return\"split\"===e&&((i={}).constructor={},i.constructor[Np]=function(){return i},i.flags=\"\",i[r]=/./[r]),i.exec=function(){return t=!0,null},i[r](\"\"),!t}));if(!o||!s||i){var a=yp(/./[r]),c=t(r,\"\"[e],(function(e,t,i,n,r){var s=yp(e),c=t.exec;return c===Rp||c===Dp.exec?o&&!r?{done:!0,value:a(t,i,n)}:{done:!0,value:s(i,t,n)}:{done:!1}}));Ap(String.prototype,e,c[0]),Ap(Dp,r,c[1])}n&&kp(Dp[r],\"sham\",!0)},s_=i,a_=Ce,c_=Ee,l_=T,d_=Lt,u_=Ht,h_=fu,p_=I,__=function(e,t,i){return t+(i?Bp(e,t).length:1)},m_=nt,f_=qp,g_=function(e,t){var i=e.exec;if(Zp(i)){var n=Qp(i,e,t);return null!==n&&Xp(n),n}if(\"RegExp\"===$p(e))return Qp(e_,e,t);throw t_(\"RegExp#exec called on incompatible receiver\")},T_=me(\"replace\"),E_=Math.max,S_=Math.min,I_=r_([].concat),v_=r_([].push),y_=r_(\"\".indexOf),A_=r_(\"\".slice),R_=function(e){return void 0===e?e:String(e)},C_=\"$0\"===\"a\".replace(/./,\"$0\"),b_=!!/./[T_]&&\"\"===/./[T_](\"a\",\"$0\"),k_=!s_((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:\"7\"},e},\"7\"!==\"\".replace(e,\"$\")}));o_(\"replace\",(function(e,t,i){var n=b_?\"$\":\"$0\";return[function(e,i){var n=p_(this),r=l_(e)?void 0:m_(e,T_);return r?n_(r,e,n,i):n_(t,h_(n),e,i)},function(e,r){var o=a_(this),s=h_(e);if(\"string\"==typeof r&&-1===y_(r,n)&&-1===y_(r,\"$<\")){var a=i(t,o,s,r);if(a.done)return a.value}var c=c_(r);c||(r=h_(r));var l=o.global;if(l){var d=o.unicode;o.lastIndex=0}for(var u=[];;){var h=g_(o,s);if(null===h)break;if(v_(u,h),!l)break;\"\"===h_(h[0])&&(o.lastIndex=__(s,u_(o.lastIndex),d))}for(var p=\"\",_=0,m=0;m=_&&(p+=A_(s,_,g)+v,_=g+f.length)}return p+A_(s,_)}]}),!k_||!C_||b_);var N_=zt.includes,D_=Fi;xr({target:\"Array\",proto:!0,forced:i((function(){return!Array(1).includes()}))},{includes:function(e){return N_(this,e,arguments.length>1?arguments[1]:void 0)}}),D_(\"includes\");var O_=Lt,w_=fu,P_=I,L_=RangeError,M_=c,V_=Ht,x_=fu,U_=function(e){var t=w_(P_(this)),i=\"\",n=O_(e);if(n<0||Infinity==n)throw L_(\"Wrong number of repetitions\");for(;n>0;(n>>>=1)&&(t+=t))1&n&&(i+=t);return i},F_=I,B_=M_(U_),H_=M_(\"\".slice),j_=Math.ceil,G_=function(e){return function(t,i,n){var r,o,s=x_(F_(t)),a=V_(i),c=s.length,l=void 0===n?\" \":x_(n);return a<=c||\"\"==l?s:((o=B_(l,j_((r=a-c)/l.length))).length>r&&(o=H_(o,0,r)),e?s+o:o+s)}},W_={start:G_(!1),end:G_(!0)},J_=/Version\\/10(?:\\.\\d+){1,2}(?: [\\w./]+)?(?: Mobile\\/\\w+)? Safari\\//.test(q),K_=W_.start;xr({target:\"String\",proto:!0,forced:J_},{padStart:function(e){return K_(this,e,arguments.length>1?arguments[1]:void 0)}});var Y_=i,z_=ke,q_=me(\"iterator\"),Q_=!Y_((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,n){t.delete(\"b\"),i+=n+e})),!t.size&&!z_||!t.sort||\"http://a/c%20d?a=1&c=3\"!==e.href||\"3\"!==t.get(\"c\")||\"a=1\"!==String(new URLSearchParams(\"?a=1\"))||!t[q_]||\"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})),X_=ir,Z_=function(e,t,i){for(var n in t)X_(e,n,t[n],i);return e},$_=Tt,em=De,tm=Wi,im=function(e,t,i){var n=$_(t);n in e?em.f(e,n,tm(0,i)):e[n]=i},nm=Ut,rm=Gt,om=im,sm=Array,am=Math.max,cm=function(e,t,i){for(var n=rm(e),r=nm(t,n),o=nm(void 0===i?n:i,n),s=sm(am(o-r,0)),a=0;r0;)e[n]=e[--n];n!==o++&&(e[n]=i)}return e},pm=function(e,t,i,n){for(var r=t.length,o=i.length,s=0,a=0;s0?arguments[0]:void 0));Em||(this.length=e.entries.length)},Rf=Af.prototype;if(ym(Rf,{append:function(e,t){Fm(arguments.length,2);var i=Jm(this);af(i.entries,{key:Lm(e),value:Lm(t)}),Em||this.length++,i.updateURL()},delete:function(e){Fm(arguments.length,1);for(var t=Jm(this),i=t.entries,n=Lm(e),r=0;rt.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=Jm(this).entries,n=Dm(e,arguments.length>1?arguments[1]:void 0),r=0;r1?kf(arguments[1]):{})}}),km(Qm)){var Nf=function(e){return bm(this,Zm),new Qm(e,arguments.length>1?kf(arguments[1]):{})};Zm.constructor=Nf,Nf.prototype=Zm,mm({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:Nf})}}var Df={URLSearchParams:Af,getState:Jm},Of=\"\\t\\n\\v\\f\\r                 \\u2028\\u2029\\ufeff\",wf=I,Pf=fu,Lf=Of,Mf=c(\"\".replace),Vf=RegExp(\"^[\"+Lf+\"]+\"),xf=RegExp(\"(^|[^\"+Lf+\"])[\"+Lf+\"]+$\"),Uf=function(e){return function(t){var i=Pf(wf(t));return 1&e&&(i=Mf(i,Vf,\"\")),2&e&&(i=Mf(i,xf,\"$1\")),i}},Ff={start:Uf(1),end:Uf(2),trim:Uf(3)},Bf=Dn.PROPER,Hf=i,jf=Of,Gf=Ff.trim;xr({target:\"String\",proto:!0,forced:function(e){return Hf((function(){return!!jf[e]()||\"​…᠎\"!==\"​…᠎\"[e]()||Bf&&jf[e].name!==e}))}(\"trim\")},{trim:function(){return Gf(this)}});var Wf=xr,Jf=ke,Kf=c,Yf=G,zf=Ee,qf=Ge,Qf=fu,Xf=Is,Zf=Sr,$f=C.Symbol,eg=$f&&$f.prototype;if(Jf&&zf($f)&&(!(\"description\"in eg)||void 0!==$f().description)){var tg={},ig=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:Qf(arguments[0]),t=qf(eg,this)?new $f(e):void 0===e?$f():$f(e);return\"\"===e&&(tg[t]=!0),t};Zf(ig,$f),ig.prototype=eg,eg.constructor=ig;var ng=\"Symbol(test)\"==String($f(\"test\")),rg=Kf(eg.valueOf),og=Kf(eg.toString),sg=/^Symbol\\((.*)\\)[^)]+$/,ag=Kf(\"\".replace),cg=Kf(\"\".slice);Xf(eg,\"description\",{configurable:!0,get:function(){var e=rg(this);if(Yf(tg,e))return\"\";var t=og(e),i=ng?cg(t,7,-1):ag(t,sg,\"$1\");return\"\"===i?void 0:i}}),Wf({global:!0,constructor:!0,forced:!0},{Symbol:ig})}var lg=Fp.charAt,dg=fu,ug=cn,hg=jo,pg=Go,_g=\"String Iterator\",mg=ug.set,fg=ug.getterFor(_g);hg(String,\"String\",(function(e){mg(this,{type:_g,string:dg(e),index:0})}),(function(){var e,t=fg(this),i=t.string,n=t.index;return n>=i.length?pg(void 0,!0):(e=lg(i,n),t.index+=e.length,pg(e,!1))}));var gg,Tg=ke,Eg=c,Sg=Fe,Ig=i,vg=oi,yg=sr,Ag=dn,Rg=B,Cg=g,bg=Object.assign,kg=Object.defineProperty,Ng=Eg([].concat),Dg=!bg||Ig((function(){if(Tg&&1!==bg({b:1},bg(kg({},\"a\",{enumerable:!0,get:function(){kg(this,\"b\",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol(),n=\"abcdefghijklmnopqrst\";return e[i]=7,n.split(\"\").forEach((function(e){t[e]=e})),7!=bg({},e)[i]||vg(bg({},t)).join(\"\")!=n}))?function(e,t){for(var i=Rg(e),n=arguments.length,r=1,o=yg.f,s=Ag.f;n>r;)for(var a,c=Cg(arguments[r++]),l=o?Ng(vg(c),o(c)):vg(c),d=l.length,u=0;d>u;)a=l[u++],Tg&&!Sg(s,c,a)||(i[a]=c[a]);return i}:bg,Og=Ce,wg=ud,Pg=va,Lg=Fe,Mg=B,Vg=function(e,t,i,n){try{return n?t(Og(i)[0],i[1]):t(i)}catch(SU){wg(e,\"throw\",SU)}},xg=zl,Ug=ta,Fg=Gt,Bg=im,Hg=ad,jg=ed,Gg=Array,Wg=c,Jg=2147483647,Kg=/[^\\0-\\u007E]/,Yg=/[.\\u3002\\uFF0E\\uFF61]/g,zg=\"Overflow: input needs wider integers to process\",qg=RangeError,Qg=Wg(Yg.exec),Xg=Math.floor,Zg=String.fromCharCode,$g=Wg(\"\".charCodeAt),eT=Wg([].join),tT=Wg([].push),iT=Wg(\"\".replace),nT=Wg(\"\".split),rT=Wg(\"\".toLowerCase),oT=function(e){return e+22+75*(e<26)},sT=function(e,t,i){var n=0;for(e=i?Xg(e/700):e>>1,e+=Xg(e/t);e>455;)e=Xg(e/35),n+=36;return Xg(n+36*e/(e+38))},aT=function(e){var t=[];e=function(e){for(var t=[],i=0,n=e.length;i=55296&&r<=56319&&i=o&&nXg((Jg-s)/u))throw qg(zg);for(s+=(d-o)*u,o=d,i=0;iJg)throw qg(zg);if(n==o){for(var h=s,p=36;;){var _=p<=a?1:p>=a+26?26:p-a;if(h<_)break;var m=h-_,f=36-_;tT(t,Zg(oT(_+m%f))),h=Xg(m/f),p+=36}tT(t,Zg(oT(h))),a=sT(s,u,l==c),s=0,l++}}s++,o++}return eT(t,\"\")},cT=xr,lT=ke,dT=Q_,uT=C,hT=va,pT=c,_T=ir,mT=Is,fT=Ns,gT=G,TT=Dg,ET=function(e){var t=Mg(e),i=Ug(this),n=arguments.length,r=n>1?arguments[1]:void 0,o=void 0!==r;o&&(r=Pg(r,n>2?arguments[2]:void 0));var s,a,c,l,d,u,h=jg(t),p=0;if(!h||this===Gg&&xg(h))for(s=Fg(t),a=i?new this(s):Gg(s);s>p;p++)u=o?r(t[p],p):t[p],Bg(a,p,u);else for(d=(l=Hg(t,h)).next,a=i?new this:[];!(c=Lg(d,l)).done;p++)u=o?Vg(l,r,[c.value,p],!0):c.value,Bg(a,p,u);return a.length=p,a},ST=cm,IT=Fp.codeAt,vT=function(e){var t,i,n=[],r=nT(iT(rT(e),Yg,\".\"),\".\");for(t=0;t?@[\\\\\\]^|]/,sE=/[\\0\\t\\n\\r #/:<>?@[\\\\\\]^|]/,aE=/^[\\u0000-\\u0020]+/,cE=/(^|[^\\u0000-\\u0020])[\\u0000-\\u0020]+$/,lE=/[\\t\\n\\r]/g,dE=function(e){var t,i,n,r;if(\"number\"==typeof e){for(t=[],i=0;i<4;i++)zT(t,e%256),e=MT(e/256);return FT(t,\".\")}if(\"object\"==typeof e){for(t=\"\",n=function(e){for(var t=null,i=1,n=null,r=0,o=0;o<8;o++)0!==e[o]?(r>i&&(t=n,i=r),n=null,r=0):(null===n&&(n=o),++r);return r>i&&(t=n,i=r),t}(e),i=0;i<8;i++)r&&0===e[i]||(r&&(r=!1),n===i?(t+=i?\":\":\"::\",r=!0):(t+=BT(e[i],16),i<7&&(t+=\":\")));return\"[\"+t+\"]\"}return e},uE={},hE=TT({},uE,{\" \":1,'\"':1,\"<\":1,\">\":1,\"`\":1}),pE=TT({},hE,{\"#\":1,\"?\":1,\"{\":1,\"}\":1}),_E=TT({},pE,{\"/\":1,\":\":1,\";\":1,\"=\":1,\"@\":1,\"[\":1,\"\\\\\":1,\"]\":1,\"^\":1,\"|\":1}),mE=function(e,t){var i=IT(e,0);return i>32&&i<127&&!gT(t,e)?e:encodeURIComponent(e)},fE={ftp:21,file:null,http:80,https:443,ws:80,wss:443},gE=function(e,t){var i;return 2==e.length&&UT(ZT,xT(e,0))&&(\":\"==(i=xT(e,1))||!t&&\"|\"==i)},TE=function(e){var t;return e.length>1&&gE(KT(e,0,2))&&(2==e.length||\"/\"===(t=xT(e,2))||\"\\\\\"===t||\"?\"===t||\"#\"===t)},EE=function(e){return\".\"===e||\"%2e\"===YT(e)},SE={},IE={},vE={},yE={},AE={},RE={},CE={},bE={},kE={},NE={},DE={},OE={},wE={},PE={},LE={},ME={},VE={},xE={},UE={},FE={},BE={},HE=function(e,t,i){var n,r,o,s=yT(e);if(t){if(r=this.parse(s))throw PT(r);this.searchParams=null}else{if(void 0!==i&&(n=new HE(i,!0)),r=this.parse(s,null,n))throw PT(r);(o=OT(new DT)).bindURL(this),this.searchParams=o}};HE.prototype={type:\"URL\",parse:function(e,t,i){var n,r,o,s,a,c=this,l=t||SE,d=0,u=\"\",h=!1,p=!1,_=!1;for(e=yT(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=GT(e,aE,\"\"),e=GT(e,cE,\"$1\")),e=GT(e,lE,\"\"),n=ET(e);d<=n.length;){switch(r=n[d],l){case SE:if(!r||!UT(ZT,r)){if(t)return qT;l=vE;continue}u+=YT(r),l=IE;break;case IE:if(r&&(UT($T,r)||\"+\"==r||\"-\"==r||\".\"==r))u+=YT(r);else{if(\":\"!=r){if(t)return qT;u=\"\",l=vE,d=0;continue}if(t&&(c.isSpecial()!=gT(fE,u)||\"file\"==u&&(c.includesCredentials()||null!==c.port)||\"file\"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&fE[c.scheme]==c.port&&(c.port=null));u=\"\",\"file\"==c.scheme?l=PE:c.isSpecial()&&i&&i.scheme==c.scheme?l=yE:c.isSpecial()?l=bE:\"/\"==n[d+1]?(l=AE,d++):(c.cannotBeABaseURL=!0,jT(c.path,\"\"),l=UE)}break;case vE:if(!i||i.cannotBeABaseURL&&\"#\"!=r)return qT;if(i.cannotBeABaseURL&&\"#\"==r){c.scheme=i.scheme,c.path=ST(i.path),c.query=i.query,c.fragment=\"\",c.cannotBeABaseURL=!0,l=BE;break}l=\"file\"==i.scheme?PE:RE;continue;case yE:if(\"/\"!=r||\"/\"!=n[d+1]){l=RE;continue}l=kE,d++;break;case AE:if(\"/\"==r){l=NE;break}l=xE;continue;case RE:if(c.scheme=i.scheme,r==gg)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.query=i.query;else if(\"/\"==r||\"\\\\\"==r&&c.isSpecial())l=CE;else if(\"?\"==r)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.query=\"\",l=FE;else{if(\"#\"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.path.length--,l=xE;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.query=i.query,c.fragment=\"\",l=BE}break;case CE:if(!c.isSpecial()||\"/\"!=r&&\"\\\\\"!=r){if(\"/\"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=xE;continue}l=NE}else l=kE;break;case bE:if(l=kE,\"/\"!=r||\"/\"!=xT(u,d+1))continue;d++;break;case kE:if(\"/\"!=r&&\"\\\\\"!=r){l=NE;continue}break;case NE:if(\"@\"==r){h&&(u=\"%40\"+u),h=!0,o=ET(u);for(var m=0;m65535)return XT;c.port=c.isSpecial()&&T===fE[c.scheme]?null:T,u=\"\"}if(t)return;l=VE;continue}return XT}u+=r;break;case PE:if(c.scheme=\"file\",\"/\"==r||\"\\\\\"==r)l=LE;else{if(!i||\"file\"!=i.scheme){l=xE;continue}if(r==gg)c.host=i.host,c.path=ST(i.path),c.query=i.query;else if(\"?\"==r)c.host=i.host,c.path=ST(i.path),c.query=\"\",l=FE;else{if(\"#\"!=r){TE(FT(ST(n,d),\"\"))||(c.host=i.host,c.path=ST(i.path),c.shortenPath()),l=xE;continue}c.host=i.host,c.path=ST(i.path),c.query=i.query,c.fragment=\"\",l=BE}}break;case LE:if(\"/\"==r||\"\\\\\"==r){l=ME;break}i&&\"file\"==i.scheme&&!TE(FT(ST(n,d),\"\"))&&(gE(i.path[0],!0)?jT(c.path,i.path[0]):c.host=i.host),l=xE;continue;case ME:if(r==gg||\"/\"==r||\"\\\\\"==r||\"?\"==r||\"#\"==r){if(!t&&gE(u))l=xE;else if(\"\"==u){if(c.host=\"\",t)return;l=VE}else{if(s=c.parseHost(u))return s;if(\"localhost\"==c.host&&(c.host=\"\"),t)return;u=\"\",l=VE}continue}u+=r;break;case VE:if(c.isSpecial()){if(l=xE,\"/\"!=r&&\"\\\\\"!=r)continue}else if(t||\"?\"!=r)if(t||\"#\"!=r){if(r!=gg&&(l=xE,\"/\"!=r))continue}else c.fragment=\"\",l=BE;else c.query=\"\",l=FE;break;case xE:if(r==gg||\"/\"==r||\"\\\\\"==r&&c.isSpecial()||!t&&(\"?\"==r||\"#\"==r)){if(\"..\"===(a=YT(a=u))||\"%2e.\"===a||\".%2e\"===a||\"%2e%2e\"===a?(c.shortenPath(),\"/\"==r||\"\\\\\"==r&&c.isSpecial()||jT(c.path,\"\")):EE(u)?\"/\"==r||\"\\\\\"==r&&c.isSpecial()||jT(c.path,\"\"):(\"file\"==c.scheme&&!c.path.length&&gE(u)&&(c.host&&(c.host=\"\"),u=xT(u,0)+\":\"),jT(c.path,u)),u=\"\",\"file\"==c.scheme&&(r==gg||\"?\"==r||\"#\"==r))for(;c.path.length>1&&\"\"===c.path[0];)WT(c.path);\"?\"==r?(c.query=\"\",l=FE):\"#\"==r&&(c.fragment=\"\",l=BE)}else u+=mE(r,pE);break;case UE:\"?\"==r?(c.query=\"\",l=FE):\"#\"==r?(c.fragment=\"\",l=BE):r!=gg&&(c.path[0]+=mE(r,uE));break;case FE:t||\"#\"!=r?r!=gg&&(\"'\"==r&&c.isSpecial()?c.query+=\"%27\":c.query+=\"#\"==r?\"%23\":mE(r,uE)):(c.fragment=\"\",l=BE);break;case BE:r!=gg&&(c.fragment+=mE(r,hE))}d++}},parseHost:function(e){var t,i,n;if(\"[\"==xT(e,0)){if(\"]\"!=xT(e,e.length-1))return QT;if(t=function(e){var t,i,n,r,o,s,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return xT(e,u)};if(\":\"==h()){if(\":\"!=xT(e,1))return;u+=2,d=++l}for(;h();){if(8==l)return;if(\":\"!=h()){for(t=i=0;i<4&&UT(rE,h());)t=16*t+LT(h(),16),u++,i++;if(\".\"==h()){if(0==i)return;if(u-=i,l>6)return;for(n=0;h();){if(r=null,n>0){if(!(\".\"==h()&&n<4))return;u++}if(!UT(eE,h()))return;for(;UT(eE,h());){if(o=LT(h(),10),null===r)r=o;else{if(0==r)return;r=10*r+o}if(r>255)return;u++}c[l]=256*c[l]+r,2!=++n&&4!=n||l++}if(4!=n)return;break}if(\":\"==h()){if(u++,!h())return}else if(h())return;c[l++]=t}else{if(null!==d)return;u++,d=++l}}if(null!==d)for(s=l-d,l=7;0!=l&&s>0;)a=c[l],c[l--]=c[d+s-1],c[d+--s]=a;else if(8!=l)return;return c}(KT(e,1,-1)),!t)return QT;this.host=t}else if(this.isSpecial()){if(e=vT(e),UT(oE,e))return QT;if(t=function(e){var t,i,n,r,o,s,a,c=JT(e,\".\");if(c.length&&\"\"==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],n=0;n1&&\"0\"==xT(r,0)&&(o=UT(tE,r)?16:8,r=KT(r,8==o?1:2)),\"\"===r)s=0;else{if(!UT(10==o?nE:8==o?iE:rE,r))return e;s=LT(r,o)}jT(i,s)}for(n=0;n=VT(256,5-t))return null}else if(s>255)return null;for(a=HT(i),n=0;n1?arguments[1]:void 0,n=kT(t,new HE(e,!1,i));lT||(t.href=n.serialize(),t.origin=n.getOrigin(),t.protocol=n.getProtocol(),t.username=n.getUsername(),t.password=n.getPassword(),t.host=n.getHost(),t.hostname=n.getHostname(),t.port=n.getPort(),t.pathname=n.getPathname(),t.search=n.getSearch(),t.searchParams=n.getSearchParams(),t.hash=n.getHash())},GE=jE.prototype,WE=function(e,t){return{get:function(){return NT(this)[e]()},set:t&&function(e){return NT(this)[t](e)},configurable:!0,enumerable:!0}};if(lT&&(mT(GE,\"href\",WE(\"serialize\",\"setHref\")),mT(GE,\"origin\",WE(\"getOrigin\")),mT(GE,\"protocol\",WE(\"getProtocol\",\"setProtocol\")),mT(GE,\"username\",WE(\"getUsername\",\"setUsername\")),mT(GE,\"password\",WE(\"getPassword\",\"setPassword\")),mT(GE,\"host\",WE(\"getHost\",\"setHost\")),mT(GE,\"hostname\",WE(\"getHostname\",\"setHostname\")),mT(GE,\"port\",WE(\"getPort\",\"setPort\")),mT(GE,\"pathname\",WE(\"getPathname\",\"setPathname\")),mT(GE,\"search\",WE(\"getSearch\",\"setSearch\")),mT(GE,\"searchParams\",WE(\"getSearchParams\")),mT(GE,\"hash\",WE(\"getHash\",\"setHash\"))),_T(GE,\"toJSON\",(function(){return NT(this).serialize()}),{enumerable:!0}),_T(GE,\"toString\",(function(){return NT(this).serialize()}),{enumerable:!0}),wT){var JE=wT.createObjectURL,KE=wT.revokeObjectURL;JE&&_T(jE,\"createObjectURL\",hT(JE,wT)),KE&&_T(jE,\"revokeObjectURL\",hT(KE,wT))}AT(jE,\"URL\"),cT({global:!0,constructor:!0,forced:!dT,sham:!lT},{URL:jE});var YE=\"undefined\"!=typeof ArrayBuffer&&\"undefined\"!=typeof DataView,zE=Lt,qE=Ht,QE=RangeError,XE=function(e){if(void 0===e)return 0;var t=zE(e),i=qE(t);if(t!==i)throw QE(\"Wrong length or index\");return i},ZE=Array,$E=Math.abs,eS=Math.pow,tS=Math.floor,iS=Math.log,nS=Math.LN2,rS={pack:function(e,t,i){var n,r,o,s=ZE(i),a=8*i-t-1,c=(1<>1,d=23===t?eS(2,-24)-eS(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=$E(e))!=e||Infinity===e?(r=e!=e?1:0,n=c):(n=tS(iS(e)/nS),e*(o=eS(2,-n))<1&&(n--,o*=2),(e+=n+l>=1?d/o:d*eS(2,1-l))*o>=2&&(n++,o/=2),n+l>=c?(r=0,n=c):n+l>=1?(r=(e*o-1)*eS(2,t),n+=l):(r=e*eS(2,l-1)*eS(2,t),n=0));t>=8;)s[h++]=255&r,r/=256,t-=8;for(n=n<0;)s[h++]=255&n,n/=256,a-=8;return s[--h]|=128*u,s},unpack:function(e,t){var i,n=e.length,r=8*n-t-1,o=(1<>1,a=r-7,c=n-1,l=e[c--],d=127&l;for(l>>=7;a>0;)d=256*d+e[c--],a-=8;for(i=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)i=256*i+e[c--],a-=8;if(0===d)d=1-s;else{if(d===o)return i?NaN:l?-Infinity:Infinity;i+=eS(2,t),d-=s}return(l?-1:1)*i*eS(2,d-t)}},oS=B,sS=Ut,aS=Gt,cS=function(e){for(var t=oS(this),i=aS(t),n=arguments.length,r=sS(n>1?arguments[1]:void 0,i),o=n>2?arguments[2]:void 0,s=void 0===o?i:sS(o,i);s>r;)t[r++]=e;return t},lS=C,dS=c,uS=ke,hS=YE,pS=Dn,_S=Yi,mS=Is,fS=Z_,gS=i,TS=Ns,ES=Lt,SS=Ht,IS=XE,vS=rS,yS=Kr,AS=vo,RS=nr.f,CS=cS,bS=cm,kS=oo,NS=cn,DS=pS.PROPER,OS=pS.CONFIGURABLE,wS=\"ArrayBuffer\",PS=\"DataView\",LS=\"prototype\",MS=\"Wrong index\",VS=NS.getterFor(wS),xS=NS.getterFor(PS),US=NS.set,FS=lS[wS],BS=FS,HS=BS&&BS[LS],jS=lS[PS],GS=jS&&jS[LS],WS=Object.prototype,JS=lS.Array,KS=lS.RangeError,YS=dS(CS),zS=dS([].reverse),qS=vS.pack,QS=vS.unpack,XS=function(e){return[255&e]},ZS=function(e){return[255&e,e>>8&255]},$S=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},eI=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},tI=function(e){return qS(e,23,4)},iI=function(e){return qS(e,52,8)},nI=function(e,t,i){mS(e[LS],t,{configurable:!0,get:function(){return i(this)[t]}})},rI=function(e,t,i,n){var r=IS(i),o=xS(e);if(r+t>o.byteLength)throw KS(MS);var s=o.bytes,a=r+o.byteOffset,c=bS(s,a,a+t);return n?c:zS(c)},oI=function(e,t,i,n,r,o){var s=IS(i),a=xS(e);if(s+t>a.byteLength)throw KS(MS);for(var c=a.bytes,l=s+a.byteOffset,d=n(+r),u=0;ulI;)(aI=cI[lI++])in BS||_S(BS,aI,FS[aI]);HS.constructor=BS}AS&&yS(GS)!==WS&&AS(GS,WS);var dI=new jS(new BS(2)),uI=dS(GS.setInt8);dI.setInt8(0,2147483648),dI.setInt8(1,2147483649),!dI.getInt8(0)&&dI.getInt8(1)||fS(GS,{setInt8:function(e,t){uI(this,e,t<<24>>24)},setUint8:function(e,t){uI(this,e,t<<24>>24)}},{unsafe:!0})}else HS=(BS=function(e){TS(this,HS);var t=IS(e);US(this,{type:wS,bytes:YS(JS(t),0),byteLength:t}),uS||(this.byteLength=t,this.detached=!1)})[LS],GS=(jS=function(e,t,i){TS(this,GS),TS(e,HS);var n=VS(e),r=n.byteLength,o=ES(t);if(o<0||o>r)throw KS(\"Wrong offset\");if(o+(i=void 0===i?r-o:SS(i))>r)throw KS(\"Wrong length\");US(this,{type:PS,buffer:e,byteLength:i,byteOffset:o,bytes:n.bytes}),uS||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[LS],uS&&(nI(BS,\"byteLength\",VS),nI(jS,\"buffer\",xS),nI(jS,\"byteLength\",xS),nI(jS,\"byteOffset\",xS)),fS(GS,{getInt8:function(e){return rI(this,1,e)[0]<<24>>24},getUint8:function(e){return rI(this,1,e)[0]},getInt16:function(e){var t=rI(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=rI(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return eI(rI(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return eI(rI(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return QS(rI(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return QS(rI(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){oI(this,1,e,XS,t)},setUint8:function(e,t){oI(this,1,e,XS,t)},setInt16:function(e,t){oI(this,2,e,ZS,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){oI(this,2,e,ZS,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){oI(this,4,e,$S,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){oI(this,4,e,$S,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){oI(this,4,e,tI,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){oI(this,8,e,iI,t,arguments.length>2?arguments[2]:void 0)}});kS(BS,wS),kS(jS,PS);var hI={ArrayBuffer:BS,DataView:jS},pI=Cs,_I=\"ArrayBuffer\",mI=hI[_I];xr({global:!0,constructor:!0,forced:C[_I]!==mI},{ArrayBuffer:mI}),pI(_I);var fI=xr,gI=Ta,TI=i,EI=Ce,SI=Ut,II=Ht,vI=da,yI=hI.ArrayBuffer,AI=hI.DataView,RI=AI.prototype,CI=gI(yI.prototype.slice),bI=gI(RI.getUint8),kI=gI(RI.setUint8);fI({target:\"ArrayBuffer\",proto:!0,unsafe:!0,forced:TI((function(){return!new yI(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(CI&&void 0===t)return CI(EI(this),e);for(var i=EI(this).byteLength,n=SI(e,i),r=SI(void 0===t?i:t,i),o=new(vI(this,yI))(II(r-n)),s=new AI(this),a=new AI(o),c=0;n1?arguments[1]:void 0,p=void 0!==h,_=Hv(d);if(_&&!jv(_))for(c=(a=Bv(d,_)).next,d=[];!(s=Vv(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=Mv(h,arguments[2])),i=Fv(d),n=new(Wv(l))(i),r=Gv(n),t=0;i>t;t++)o=p?h(d[t],t):d[t],n[t]=r?Jv(o):+o;return n},fy=rp.forEach,gy=Cs,Ty=Is,Ey=De,Sy=ln,Iy=lu,vy=cn.get,yy=cn.set,Ay=cn.enforce,Ry=Ey.f,Cy=Sy.f,by=Math.round,ky=Yv.RangeError,Ny=Zv.ArrayBuffer,Dy=Ny.prototype,Oy=Zv.DataView,wy=Xv.NATIVE_ARRAY_BUFFER_VIEWS,Py=Xv.TYPED_ARRAY_TAG,Ly=Xv.TypedArray,My=Xv.TypedArrayPrototype,Vy=Xv.aTypedArrayConstructor,xy=Xv.isTypedArray,Uy=\"BYTES_PER_ELEMENT\",Fy=\"Wrong length\",By=function(e,t){Vy(e);for(var i=0,n=t.length,r=new e(n);n>i;)r[i]=t[i++];return r},Hy=function(e,t){Ty(e,t,{configurable:!0,get:function(){return vy(this)[t]}})},jy=function(e){var t;return hy(Dy,e)||\"ArrayBuffer\"==(t=cy(e))||\"SharedArrayBuffer\"==t},Gy=function(e,t){return xy(e)&&!dy(t)&&t in e&&iy(+t)&&t>=0},Wy=function(e,t){return t=sy(t),Gy(e,t)?ey(2,e[t]):Cy(e,t)},Jy=function(e,t,i){return t=sy(t),!(Gy(e,t)&&ly(i)&&ay(i,\"value\"))||ay(i,\"get\")||ay(i,\"set\")||i.configurable||ay(i,\"writable\")&&!i.writable||ay(i,\"enumerable\")&&!i.enumerable?Ry(e,t,i):(e[t]=i.value,e)};qv?(wy||(Sy.f=Wy,Ey.f=Jy,Hy(My,\"buffer\"),Hy(My,\"byteOffset\"),Hy(My,\"byteLength\"),Hy(My,\"length\")),Kv({target:\"Object\",stat:!0,forced:!wy},{getOwnPropertyDescriptor:Wy,defineProperty:Jy}),PI.exports=function(e,t,i){var n=e.match(/\\d+/)[0]/8,r=e+(i?\"Clamped\":\"\")+\"Array\",o=\"get\"+e,s=\"set\"+e,a=Yv[r],c=a,l=c&&c.prototype,d={},u=function(e,t){Ry(e,t,{get:function(){return function(e,t){var i=vy(e);return i.view[o](t*n+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,r){var o=vy(e);i&&(r=(r=by(r))<0?0:r>255?255:255&r),o.view[s](t*n+o.byteOffset,r,!0)}(this,t,e)},enumerable:!0})};wy?Qv&&(c=t((function(e,t,i,r){return $v(e,l),Iy(ly(t)?jy(t)?void 0!==r?new a(t,oy(i,n),r):void 0!==i?new a(t,oy(i,n)):new a(t):xy(t)?By(c,t):zv(my,c,t):new a(ry(t)),e,c)})),py&&py(c,Ly),fy(_y(a),(function(e){e in c||ty(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,r){$v(e,l);var o,s,a,d=0,h=0;if(ly(t)){if(!jy(t))return xy(t)?By(c,t):zv(my,c,t);o=t,h=oy(i,n);var p=t.byteLength;if(void 0===r){if(p%n)throw ky(Fy);if((s=p-h)<0)throw ky(Fy)}else if((s=ny(r)*n)+h>p)throw ky(Fy);a=s/n}else a=ry(t),o=new Ny(s=a*n);for(yy(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new Oy(o)});d1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),Qy((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var eA=C,tA=Fe,iA=mv,nA=Gt,rA=Dv,oA=B,sA=i,aA=eA.RangeError,cA=eA.Int8Array,lA=cA&&cA.prototype,dA=lA&&lA.set,uA=iA.aTypedArray,hA=iA.exportTypedArrayMethod,pA=!sA((function(){var e=new Uint8ClampedArray(2);return tA(dA,e,{length:1,0:3},1),3!==e[1]})),_A=pA&&iA.NATIVE_ARRAY_BUFFER_VIEWS&&sA((function(){var e=new cA(2);return e.set(1),e.set(\"2\",1),0!==e[0]||2!==e[1]}));hA(\"set\",(function(e){uA(this);var t=rA(arguments.length>1?arguments[1]:void 0,1),i=oA(e);if(pA)return tA(dA,this,i,t);var n=this.length,r=nA(i),o=0;if(r+t>n)throw aA(\"Wrong length\");for(;o0&&1/i<0?1:-1:t>i}}(e))}),!PA||wA);var LA=Qe,MA=TypeError,VA=xr,xA=c,UA=et,FA=B,BA=Gt,HA=function(e,t){if(!delete e[t])throw MA(\"Cannot delete property \"+LA(t)+\" of \"+LA(e))},jA=fu,GA=i,WA=_m,JA=sp,KA=fA,YA=gA,zA=ie,qA=EA,QA=[],XA=xA(QA.sort),ZA=xA(QA.push),$A=GA((function(){QA.sort(void 0)})),eR=GA((function(){QA.sort(null)})),tR=JA(\"sort\"),iR=!GA((function(){if(zA)return zA<70;if(!(KA&&KA>3)){if(YA)return!0;if(qA)return qA<603;var e,t,i,n,r=\"\";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(n=0;n<47;n++)QA.push({k:t+n,v:i})}for(QA.sort((function(e,t){return t.v-e.v})),n=0;njA(i)?1:-1}}(e)),i=BA(r),n=0;ne.length?-1:\"\"===t?i:DR(e,t,i)};gR({target:\"String\",proto:!0},{replaceAll:function(e,t){var i,n,r,o,s,a,c,l,d=SR(this),u=0,h=0,p=\"\";if(!vR(e)){if(yR(e)&&(i=AR(SR(CR(e))),!~DR(i,\"g\")))throw NR(\"`.replaceAll` does not allow non-global regexes\");if(n=RR(e,kR))return TR(n,e,d,t)}for(r=AR(d),o=AR(e),(s=IR(t))||(t=AR(t)),a=o.length,c=wR(1,a),u=PR(r,o,0);-1!==u;)l=s?AR(t(o,u,r)):bR(o,r,u,[],void 0,t),p+=OR(r,h,u)+l,h=u+a,u=PR(r,o,u+c);return h=i&&parseInt(n[i],10)}function xR(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const o=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,o),r.apply(this,[e,o])};const o=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.apply(this,arguments);const n=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,n])},Object.defineProperty(n,\"on\"+t,{get(){return this[\"_on\"+t]},set(e){this[\"_on\"+t]&&(this.removeEventListener(t,this[\"_on\"+t]),delete this[\"_on\"+t]),e&&this.addEventListener(t,this[\"_on\"+t]=e)},enumerable:!0,configurable:!0})}function UR(e){return\"boolean\"!=typeof e?new Error(\"Argument type: \"+typeof e+\". Please use a boolean.\"):(LR=e,e?\"adapter.js logging disabled\":\"adapter.js logging enabled\")}function FR(e){return\"boolean\"!=typeof e?new Error(\"Argument type: \"+typeof e+\". Please use a boolean.\"):(MR=!e,\"adapter.js deprecation warnings \"+(e?\"disabled\":\"enabled\"))}function BR(){if(\"object\"==typeof window){if(LR)return;\"undefined\"!=typeof console&&\"function\"==typeof console.log&&console.log.apply(console,arguments)}}function HR(e,t){MR&&console.warn(e+\" is deprecated, please use \"+t+\" instead.\")}function jR(e){return\"[object Object]\"===Object.prototype.toString.call(e)}function GR(e){return jR(e)?Object.keys(e).reduce((function(t,i){const n=jR(e[i]),r=n?GR(e[i]):e[i],o=n&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[i]:r})}),{}):e}function WR(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith(\"Id\")?WR(e,e.get(t[n]),i):n.endsWith(\"Ids\")&&t[n].forEach((t=>{WR(e,e.get(t),i)}))})))}function JR(e,t,i){const n=i?\"outbound-rtp\":\"inbound-rtp\",r=new Map;if(null===t)return r;const o=[];return e.forEach((e=>{\"track\"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&WR(e,i,r)}))})),r}const KR=BR;function YR(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if(\"object\"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if(\"require\"===i||\"advanced\"===i||\"mediaSource\"===i)return;const n=\"object\"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&\"number\"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):\"deviceId\"===t?\"sourceId\":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};\"number\"==typeof n.ideal?(e[r(\"min\",i)]=n.ideal,t.optional.push(e),e={},e[r(\"max\",i)]=n.ideal,t.optional.push(e)):(e[r(\"\",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&\"number\"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r(\"\",i)]=n.exact):[\"min\",\"max\"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&\"object\"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,\"autoGainControl\",\"googAutoGainControl\"),t(e.audio,\"noiseSuppression\",\"googNoiseSuppression\"),e.audio=n(e.audio)}if(e&&\"object\"==typeof e.video){let o=e.video.facingMode;o=o&&(\"object\"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&(\"user\"===o.exact||\"environment\"===o.exact||\"user\"===o.ideal||\"environment\"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,\"environment\"===o.exact||\"environment\"===o.ideal?t=[\"back\",\"rear\"]:\"user\"!==o.exact&&\"user\"!==o.ideal||(t=[\"front\"]),t)return i.mediaDevices.enumerateDevices().then((i=>{i=i.filter((e=>\"videoinput\"===e.kind));let s=i.find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&i.length&&t.includes(\"back\")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=n(e.video),KR(\"chrome: \"+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return KR(\"chrome: \"+JSON.stringify(e)),r(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:\"NotAllowedError\",PermissionDismissedError:\"NotAllowedError\",InvalidStateError:\"NotAllowedError\",DevicesNotFoundError:\"NotFoundError\",ConstraintNotSatisfiedError:\"OverconstrainedError\",TrackStartError:\"NotReadableError\",MediaDeviceFailedDueToShutdown:\"NotAllowedError\",MediaDeviceKillSwitchOn:\"NotAllowedError\",TabCaptureError:\"AbortError\",ScreenCaptureError:\"AbortError\",DeviceCaptureError:\"AbortError\"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&\": \")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(o(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException(\"\",\"NotFoundError\");return e}),(e=>Promise.reject(o(e))))))}}}function zR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function qR(e){if(\"object\"==typeof e&&e.RTCPeerConnection&&!(\"ontrack\"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,\"ontrack\",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener(\"track\",this._ontrack),this.addEventListener(\"track\",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener(\"addtrack\",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const r=new Event(\"track\");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const r=new Event(\"track\");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener(\"addstream\",this._ontrackpoly)),t.apply(this,arguments)}}else xR(e,\"track\",(e=>(e.transceiver||Object.defineProperty(e,\"transceiver\",{value:{receiver:e.receiver}}),e)))}function QR(e){if(\"object\"==typeof e&&e.RTCPeerConnection&&!(\"getSenders\"in e.RTCPeerConnection.prototype)&&\"createDTMFSender\"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&(\"audio\"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if(\"object\"==typeof e&&e.RTCPeerConnection&&\"getSenders\"in e.RTCPeerConnection.prototype&&\"createDTMFSender\"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!(\"dtmf\"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,\"dtmf\",{get(){return void 0===this._dtmf&&(\"audio\"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function XR(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&\"function\"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||\"function\"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:\"local-candidate\",remotecandidate:\"remote-candidate\"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){i(o(r(e)))};return t.apply(this,[n,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(o(r(t)))},i])})).then(i,n)}}function ZR(e){if(!(\"object\"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!(\"getStats\"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>JR(t,e.track,!0)))}}if(!(\"getStats\"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),xR(e,\"track\",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>JR(t,e.track,!1)))}}if(!(\"getStats\"in e.RTCRtpSender.prototype)||!(\"getStats\"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException(\"There are more than one sender or receiver for the track.\",\"InvalidAccessError\")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException(\"There is no sender or receiver for the track.\",\"InvalidAccessError\"))}return t.apply(this,arguments)}}function $R(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException(\"Track already exists.\",\"InvalidAccessError\")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function eC(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return $R(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException(\"Track already exists.\",\"InvalidAccessError\")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.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||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if(\"closed\"===this.signalingState)throw new DOMException(\"The RTCPeerConnection's signalingState is 'closed'.\",\"InvalidStateError\");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException(\"The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.\",\"NotSupportedError\");if(this.getSenders().find((e=>e.track===t)))throw new DOMException(\"Track already exists.\",\"InvalidAccessError\");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event(\"negotiationneeded\"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},[\"createOffer\",\"createAnswer\"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&\"function\"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,\"g\"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,\"localDescription\");Object.defineProperty(e.RTCPeerConnection.prototype,\"localDescription\",{get(){const e=a.get.apply(this);return\"\"===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if(\"closed\"===this.signalingState)throw new DOMException(\"The RTCPeerConnection's signalingState is 'closed'.\",\"InvalidStateError\");if(!e._pc)throw new DOMException(\"Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.\",\"TypeError\");if(!(e._pc===this))throw new DOMException(\"Sender was not created by this connection.\",\"InvalidAccessError\");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event(\"negotiationneeded\")))}}function tC(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&[\"setLocalDescription\",\"setRemoteDescription\",\"addIceCandidate\"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new(\"addIceCandidate\"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function iC(e,t){xR(e,\"negotiationneeded\",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&\"plan-b\"===i.getConfiguration().sdpSemantics)||\"stable\"===i.signalingState)return e}))}var nC=Object.freeze({__proto__:null,shimMediaStream:zR,shimOnTrack:qR,shimGetSendersWithDtmf:QR,shimGetStats:XR,shimSenderReceiverGetStats:ZR,shimAddTrackRemoveTrackWithNative:$R,shimAddTrackRemoveTrack:eC,shimPeerConnection:tC,fixNegotiationNeeded:iC,shimGetUserMedia:YR,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&\"getDisplayMedia\"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(\"function\"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:\"desktop\",chromeMediaSourceId:t,maxFrameRate:o||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error(\"shimGetDisplayMedia: getSourceId argument is not a function\"))}});function rC(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){HR(\"navigator.getUserMedia\",\"navigator.mediaDevices.getUserMedia\"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&\"autoGainControl\"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return\"object\"==typeof i&&\"object\"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,\"autoGainControl\",\"mozAutoGainControl\"),e(i.audio,\"noiseSuppression\",\"mozNoiseSuppression\")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,\"mozAutoGainControl\",\"autoGainControl\"),e(i,\"mozNoiseSuppression\",\"noiseSuppression\"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return\"audio\"===this.kind&&\"object\"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,\"autoGainControl\",\"mozAutoGainControl\"),e(i,\"noiseSuppression\",\"mozNoiseSuppression\")),t.apply(this,[i])}}}}function oC(e){\"object\"==typeof e&&e.RTCTrackEvent&&\"receiver\"in e.RTCTrackEvent.prototype&&!(\"transceiver\"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,\"transceiver\",{get(){return{receiver:this.receiver}}})}function sC(e,t){if(\"object\"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&[\"setLocalDescription\",\"setRemoteDescription\",\"addIceCandidate\"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new(\"addIceCandidate\"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={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(){const[e,r,o]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(sN){if(\"TypeError\"!==sN.name)throw sN;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,o)}}function aC(e){if(\"object\"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&\"getStats\"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function cC(e){if(\"object\"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&\"getStats\"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),xR(e,\"track\",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function lC(e){e.RTCPeerConnection&&!(\"removeStream\"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){HR(\"removeStream\",\"removeTrack\"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function dC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function uC(e){if(\"object\"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if(\"rid\"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError(\"Invalid RID value provided.\")}if(\"scaleResolutionDownBy\"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError(\"scale_resolution_down_by must be >= 1.0\");if(\"maxFramerate\"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError(\"max_framerate must be >= 0.0\")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!(\"encodings\"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function hC(e){if(\"object\"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return\"encodings\"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function pC(e){if(\"object\"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function _C(e){if(\"object\"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var mC=Object.freeze({__proto__:null,shimOnTrack:oC,shimPeerConnection:sC,shimSenderGetStats:aC,shimReceiverGetStats:cC,shimRemoveStream:lC,shimRTCDataChannel:dC,shimAddTransceiver:uC,shimGetParameters:hC,shimCreateOffer:pC,shimCreateAnswer:_C,shimGetUserMedia:rC,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&\"getDisplayMedia\"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException(\"getDisplayMedia without video constraints is undefined\");return e.name=\"NotFoundError\",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function fC(e){if(\"object\"==typeof e&&e.RTCPeerConnection){if(\"getLocalStreams\"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!(\"addStream\"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}\"removeStream\"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function gC(e){if(\"object\"==typeof e&&e.RTCPeerConnection&&(\"getRemoteStreams\"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!(\"onaddstream\"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,\"onaddstream\",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener(\"addstream\",this._onaddstream),this.removeEventListener(\"track\",this._onaddstreampoly)),this.addEventListener(\"addstream\",this._onaddstream=e),this.addEventListener(\"track\",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event(\"addstream\");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener(\"track\",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event(\"addstream\");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function TC(e){if(\"object\"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function EC(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(SC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function SC(e){return e&&void 0!==e.video?Object.assign({},e,{video:GR(e.video)}):e}function IC(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;it.generateCertificate})}function vC(e){\"object\"==typeof e&&e.RTCTrackEvent&&\"receiver\"in e.RTCTrackEvent.prototype&&!(\"transceiver\"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,\"transceiver\",{get(){return{receiver:this.receiver}}})}function yC(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>\"audio\"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?\"sendrecv\"===t.direction?t.setDirection?t.setDirection(\"sendonly\"):t.direction=\"sendonly\":\"recvonly\"===t.direction&&(t.setDirection?t.setDirection(\"inactive\"):t.direction=\"inactive\"):!0!==e.offerToReceiveAudio||t||this.addTransceiver(\"audio\",{direction:\"recvonly\"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>\"video\"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?\"sendrecv\"===i.direction?i.setDirection?i.setDirection(\"sendonly\"):i.direction=\"sendonly\":\"recvonly\"===i.direction&&(i.setDirection?i.setDirection(\"inactive\"):i.direction=\"inactive\"):!0!==e.offerToReceiveVideo||i||this.addTransceiver(\"video\",{direction:\"recvonly\"})}return t.apply(this,arguments)}}function AC(e){\"object\"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var RC=Object.freeze({__proto__:null,shimLocalStreamsAPI:fC,shimRemoteStreamsAPI:gC,shimCallbacksAPI:TC,shimGetUserMedia:EC,shimConstraints:SC,shimRTCIceServerUrls:IC,shimTrackEventTransceiver:vC,shimCreateOfferLegacy:yC,shimAudioContext:AC}),CC={},bC={get exports(){return CC},set exports(e){CC=e}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split(\"\\n\").map((e=>e.trim()))},t.splitSections=function(e){return e.split(\"\\nm=\").map(((e,t)=>(t>0?\"m=\"+e:e).trim()+\"\\r\\n\"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf(\"a=candidate:\")?e.substring(12).split(\" \"):e.substring(10).split(\" \");const i={foundation:t[0],component:{1:\"rtp\",2:\"rtcp\"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let n=8;n0?t[0].split(\"/\")[1]:\"sendrecv\",uri:t[1],attributes:t.slice(2).join(\" \")}},t.writeExtmap=function(e){return\"a=extmap:\"+(e.id||e.preferredId)+(e.direction&&\"sendrecv\"!==e.direction?\"/\"+e.direction:\"\")+\" \"+e.uri+(e.attributes?\" \"+e.attributes:\"\")+\"\\r\\n\"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(\" \")+1).split(\";\");for(let r=0;r{void 0!==e.parameters[t]?n.push(t+\"=\"+e.parameters[t]):n.push(t)})),t+=\"a=fmtp:\"+i+\" \"+n.join(\";\")+\"\\r\\n\"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(\" \")+1).split(\" \");return{type:t.shift(),parameter:t.join(\" \")}},t.writeRtcpFb=function(e){let t=\"\",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+=\"a=rtcp-fb:\"+i+\" \"+e.type+(e.parameter&&e.parameter.length?\" \"+e.parameter:\"\")+\"\\r\\n\"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(\" \"),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(\":\",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(\" \");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,\"a=mid:\")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(\" \");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:\"auto\",fingerprints:t.matchPrefix(e+i,\"a=fingerprint:\").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i=\"a=setup:\"+t+\"\\r\\n\";return e.fingerprints.forEach((e=>{i+=\"a=fingerprint:\"+e.algorithm+\" \"+e.value+\"\\r\\n\"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(\" \");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return\"a=crypto:\"+e.tag+\" \"+e.cryptoSuite+\" \"+(\"object\"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?\" \"+e.sessionParams.join(\" \"):\"\")+\"\\r\\n\"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf(\"inline:\"))return null;const t=e.substring(7).split(\"|\");return{keyMethod:\"inline\",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(\":\")[0]:void 0,mkiLength:t[2]?t[2].split(\":\")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+\":\"+e.keySalt+(e.lifeTime?\"|\"+e.lifeTime:\"\")+(e.mkiValue&&e.mkiLength?\"|\"+e.mkiValue+\":\"+e.mkiLength:\"\")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,\"a=crypto:\").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,\"a=ice-ufrag:\")[0],r=t.matchPrefix(e+i,\"a=ice-pwd:\")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t=\"a=ice-ufrag:\"+e.usernameFragment+\"\\r\\na=ice-pwd:\"+e.password+\"\\r\\n\";return e.iceLite&&(t+=\"a=ice-lite\\r\\n\"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(\" \");i.profile=n[2];for(let o=3;o{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,\"a=rtcp-fb:* \").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n=\"\";n+=\"m=\"+e+\" \",n+=i.codecs.length>0?\"9\":\"0\",n+=\" \"+(i.profile||\"UDP/TLS/RTP/SAVPF\")+\" \",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(\" \")+\"\\r\\n\",n+=\"c=IN IP4 0.0.0.0\\r\\n\",n+=\"a=rtcp:9 IN IP4 0.0.0.0\\r\\n\",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+=\"a=maxptime:\"+r+\"\\r\\n\"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf(\"RED\"),o=-1!==n.fecMechanisms.indexOf(\"ULPFEC\"),s=t.matchPrefix(e,\"a=ssrc:\").map((e=>t.parseSsrcMedia(e))).filter((e=>\"cname\"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const l=t.matchPrefix(e,\"a=ssrc-group:FID\").map((e=>e.substring(17).split(\" \").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===a&&(c=l[0][1]),n.codecs.forEach((e=>{if(\"RTX\"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?\"red+ulpfec\":\"red\"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let d=t.matchPrefix(e,\"b=\");return d.length&&(d=0===d[0].indexOf(\"b=TIAS:\")?parseInt(d[0].substring(7),10):0===d[0].indexOf(\"b=AS:\")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=d}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,\"a=ssrc:\").map((e=>t.parseSsrcMedia(e))).filter((e=>\"cname\"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,\"a=rtcp-rsize\");i.reducedSize=r.length>0,i.compound=0===r.length;const o=t.matchPrefix(e,\"a=rtcp-mux\");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t=\"\";return e.reducedSize&&(t+=\"a=rtcp-rsize\\r\\n\"),e.mux&&(t+=\"a=rtcp-mux\\r\\n\"),void 0!==e.ssrc&&e.cname&&(t+=\"a=ssrc:\"+e.ssrc+\" cname:\"+e.cname+\"\\r\\n\"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,\"a=msid:\");if(1===n.length)return i=n[0].substring(7).split(\" \"),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,\"a=ssrc:\").map((e=>t.parseSsrcMedia(e))).filter((e=>\"msid\"===e.attribute));return r.length>0?(i=r[0].value.split(\" \"),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,\"a=max-message-size:\");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const o=t.matchPrefix(e,\"a=sctp-port:\");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const s=t.matchPrefix(e,\"a=sctpmap:\");if(s.length>0){const e=s[0].substring(10).split(\" \");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i=\"DTLS/SCTP\"!==e.protocol?[\"m=\"+e.kind+\" 9 \"+e.protocol+\" \"+t.protocol+\"\\r\\n\",\"c=IN IP4 0.0.0.0\\r\\n\",\"a=sctp-port:\"+t.port+\"\\r\\n\"]:[\"m=\"+e.kind+\" 9 \"+e.protocol+\" \"+t.port+\"\\r\\n\",\"c=IN IP4 0.0.0.0\\r\\n\",\"a=sctpmap:\"+t.port+\" \"+t.protocol+\" 65535\\r\\n\"],void 0!==t.maxMessageSize&&i.push(\"a=max-message-size:\"+t.maxMessageSize+\"\\r\\n\"),i.join(\"\")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const o=void 0!==i?i:2;r=e||t.generateSessionId();return\"v=0\\r\\no=\"+(n||\"thisisadapterortc\")+\" \"+r+\" \"+o+\" IN IP4 127.0.0.1\\r\\ns=-\\r\\nt=0 0\\r\\n\"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let t=0;t(t.candidate&&Object.defineProperty(t,\"candidate\",{value:new e.RTCIceCandidate(t.candidate),writable:\"false\"}),t)))}function OC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&\"relayProtocol\"in e.RTCIceCandidate.prototype||xR(e,\"icecandidate\",(e=>{if(e.candidate){const t=kC.parseCandidate(e.candidate.candidate);\"relay\"===t.type&&(e.candidate.relayProtocol={0:\"tls\",1:\"tcp\",2:\"udp\"}[t.priority>>24])}return e}))}function wC(e,t){if(!e.RTCPeerConnection)return;\"sctp\"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,\"sctp\",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,\"chrome\"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();\"plan-b\"===e&&Object.defineProperty(this,\"sctp\",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=kC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=kC.parseMLine(e);return t&&\"application\"===t.kind&&-1!==t.protocol.indexOf(\"SCTP\")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return\"firefox\"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;\"firefox\"===t.browser&&57===t.version&&(n=65535);const r=kC.matchPrefix(e.sdp,\"a=max-message-size:\");return r.length>0?n=parseInt(r[0].substring(19),10):\"firefox\"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let r;r=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const o={};Object.defineProperty(o,\"maxMessageSize\",{get:()=>r}),this._sctp=o}return i.apply(this,arguments)}}function PC(e){if(!e.RTCPeerConnection||!(\"createDataChannel\"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if(\"open\"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError(\"Message too large (can send a maximum of \"+t.sctp.maxMessageSize+\" bytes)\");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},xR(e,\"datachannel\",(e=>(t(e.channel,e.target),e)))}function LC(e){if(!e.RTCPeerConnection||\"connectionState\"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,\"connectionState\",{get(){return{completed:\"connected\",checking:\"connecting\"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,\"onconnectionstatechange\",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener(\"connectionstatechange\",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener(\"connectionstatechange\",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),[\"setLocalDescription\",\"setRemoteDescription\"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event(\"connectionstatechange\",e);t.dispatchEvent(i)}return e},this.addEventListener(\"iceconnectionstatechange\",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function MC(e,t){if(!e.RTCPeerConnection)return;if(\"chrome\"===t.browser&&t.version>=71)return;if(\"safari\"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf(\"\\na=extmap-allow-mixed\")){const i=t.sdp.split(\"\\n\").filter((e=>\"a=extmap-allow-mixed\"!==e.trim())).join(\"\\n\");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function VC(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(\"chrome\"===t.browser&&t.version<78||\"firefox\"===t.browser&&t.version<68||\"safari\"===t.browser)&&arguments[0]&&\"\"===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function xC(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if(\"object\"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case\"stable\":case\"have-local-offer\":case\"have-remote-pranswer\":e.type=\"offer\";break;default:e.type=\"answer\"}if(e.sdp||\"offer\"!==e.type&&\"answer\"!==e.type)return i.apply(this,[e]);return(\"offer\"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var UC=Object.freeze({__proto__:null,shimRTCIceCandidate:DC,shimRTCIceCandidateRelayProtocol:OC,shimMaxMessageSize:wC,shimSendThrowTypeError:PC,shimConnectionState:LC,removeExtmapAllowMixed:MC,shimAddIceCandidateNullOrEmpty:VC,shimParameterlessSetLocalDescription:xC});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=BR,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser=\"Not a browser.\",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser=\"firefox\",t.version=VR(i.userAgent,/Firefox\\/(\\d+)\\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser=\"chrome\",t.version=VR(i.userAgent,/Chrom(e|ium)\\/(\\d+)\\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\\/(\\d+)\\./))return t.browser=\"Not a supported browser.\",t;t.browser=\"safari\",t.version=VR(i.userAgent,/AppleWebKit\\/(\\d+)\\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&\"currentDirection\"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:UC,extractVersion:VR,disableLog:UR,disableWarnings:FR,sdp:NC};switch(n.browser){case\"chrome\":if(!nC||!tC||!t.shimChrome)return i(\"Chrome shim is not included in this adapter release.\"),r;if(null===n.version)return i(\"Chrome shim can not determine version, not shimming.\"),r;i(\"adapter.js shimming chrome.\"),r.browserShim=nC,VC(e,n),xC(e),YR(e,n),zR(e),tC(e,n),qR(e),eC(e,n),QR(e),XR(e),ZR(e),iC(e,n),DC(e),OC(e),LC(e),wC(e,n),PC(e),MC(e,n);break;case\"firefox\":if(!mC||!sC||!t.shimFirefox)return i(\"Firefox shim is not included in this adapter release.\"),r;i(\"adapter.js shimming firefox.\"),r.browserShim=mC,VC(e,n),xC(e),rC(e,n),sC(e,n),oC(e),lC(e),aC(e),cC(e),dC(e),uC(e),hC(e),pC(e),_C(e),DC(e),LC(e),wC(e,n),PC(e);break;case\"safari\":if(!RC||!t.shimSafari)return i(\"Safari shim is not included in this adapter release.\"),r;i(\"adapter.js shimming safari.\"),r.browserShim=RC,VC(e,n),xC(e),IC(e),yC(e),TC(e),fC(e),gC(e),vC(e),EC(e),AC(e),DC(e),OC(e),wC(e,n),PC(e),MC(e,n);break;default:i(\"Unsupported browser!\")}}({window:\"undefined\"==typeof window?void 0:window});var FC,BC=Object.create,HC=Object.defineProperty,jC=Object.defineProperties,GC=Object.getOwnPropertyDescriptor,WC=Object.getOwnPropertyDescriptors,JC=Object.getOwnPropertyNames,KC=Object.getOwnPropertySymbols,YC=Object.getPrototypeOf,zC=Object.prototype.hasOwnProperty,qC=Object.prototype.propertyIsEnumerable,QC=Reflect.get,XC=Math.pow,ZC=(e,t,i)=>t in e?HC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,$C=(e,t)=>{for(var i in t||(t={}))zC.call(t,i)&&ZC(e,i,t[i]);if(KC)for(var i of KC(t))qC.call(t,i)&&ZC(e,i,t[i]);return e},eb=(e,t)=>jC(e,WC(t)),tb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ib=(e,t)=>{for(var i in t)HC(e,i,{get:t[i],enumerable:!0})},nb=(e,t,i)=>(i=null!=e?BC(YC(e)):{},((e,t,i,n)=>{if(t&&\"object\"==typeof t||\"function\"==typeof t)for(let r of JC(t))!zC.call(e,r)&&r!==i&&HC(e,r,{get:()=>t[r],enumerable:!(n=GC(t,r))||n.enumerable});return e})(!t&&e&&e.__esModule?i:HC(i,\"default\",{value:e,enumerable:!0}),e)),rb=(e,t,i,n)=>{for(var r,o=n>1?void 0:n?GC(t,i):t,s=e.length-1;s>=0;s--)(r=e[s])&&(o=(n?r(t,i,o):r(o))||o);return n&&o&&HC(t,i,o),o},ob=(e,t,i)=>(ZC(e,\"symbol\"!=typeof t?t+\"\":t,i),i),sb=(e,t,i)=>QC(YC(e),i,t),ab=(e,t,i)=>new Promise(((n,r)=>{var o=e=>{try{a(i.next(e))}catch(t){r(t)}},s=e=>{try{a(i.throw(e))}catch(t){r(t)}},a=e=>e.done?n(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),cb=tb(((e,t)=>{var i=Object.prototype.hasOwnProperty,n=\"~\";function r(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,i,r,s){if(\"function\"!=typeof i)throw new TypeError(\"The listener must be a function\");var a=new o(i,r||e,s),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function c(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),c.prototype.eventNames=function(){var e,t,r=[];if(0===this._eventsCount)return r;for(t in e=this._events)i.call(e,t)&&r.push(n?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},c.prototype.listeners=function(e){var t=n?n+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,o=i.length,s=new Array(o);r{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:%d 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\":\"\")}},{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:\"mid\",reg:/^mid:([^\\s]*)/,format:\"mid:%s\"},{name:\"msid\",reg:/^msid:(.*)/,format:\"msid:%s\"},{name:\"ptime\",reg:/^ptime:(\\d*)/,format:\"ptime:%d\"},{name:\"maxptime\",reg:/^maxptime:(\\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:\"invalid\",names:[\"value\"]}]};Object.keys(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format=\"%s\")}))}))})),db=tb((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:r?i[e.name]:i;(function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var o=0;o1&&(e[n[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=[],n=e.split(\" \").map(t),r=0;r{var i=lb(),n=/%[sdv%]/g,r=function(e){var t=1,i=arguments,r=i.length;return e.replace(n,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case\"%%\":return\"%\";case\"%s\":return String(n);case\"%d\":return Number(n);case\"%v\":return\"\"}}))},o=function(e,t,i){var n=[e+\"=\"+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o{var t=db(),i=ub();e.write=i,e.parse=t.parse,e.parseFmtpConfig=t.parseFmtpConfig,e.parseParams=t.parseParams,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),pb=nb(cb()),_b=((FC=_b||{})[FC.INVALID_PARAMETER=4096]=\"INVALID_PARAMETER\",FC[FC.INVALID_OPERATION=4097]=\"INVALID_OPERATION\",FC[FC.NOT_SUPPORTED=4098]=\"NOT_SUPPORTED\",FC[FC.DEVICE_NOT_FOUND=4099]=\"DEVICE_NOT_FOUND\",FC[FC.INITIALIZE_FAILED=4100]=\"INITIALIZE_FAILED\",FC[FC.SIGNAL_CHANNEL_SETUP_FAILED=16385]=\"SIGNAL_CHANNEL_SETUP_FAILED\",FC[FC.SIGNAL_CHANNEL_ERROR=16386]=\"SIGNAL_CHANNEL_ERROR\",FC[FC.ICE_TRANSPORT_ERROR=16387]=\"ICE_TRANSPORT_ERROR\",FC[FC.JOIN_ROOM_FAILED=16388]=\"JOIN_ROOM_FAILED\",FC[FC.CREATE_OFFER_FAILED=16389]=\"CREATE_OFFER_FAILED\",FC[FC.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]=\"SIGNAL_CHANNEL_RECONNECTION_FAILED\",FC[FC.UPLINK_RECONNECTION_FAILED=16391]=\"UPLINK_RECONNECTION_FAILED\",FC[FC.DOWNLINK_RECONNECTION_FAILED=16392]=\"DOWNLINK_RECONNECTION_FAILED\",FC[FC.REMOTE_STREAM_NOT_EXIST=16400]=\"REMOTE_STREAM_NOT_EXIST\",FC[FC.CLIENT_BANNED=16448]=\"CLIENT_BANNED\",FC[FC.SERVER_TIMEOUT=16449]=\"SERVER_TIMEOUT\",FC[FC.SUBSCRIPTION_TIMEOUT=16450]=\"SUBSCRIPTION_TIMEOUT\",FC[FC.PLAY_NOT_ALLOWED=16451]=\"PLAY_NOT_ALLOWED\",FC[FC.DEVICE_AUTO_RECOVER_FAILED=16452]=\"DEVICE_AUTO_RECOVER_FAILED\",FC[FC.START_PUBLISH_CDN_FAILED=16453]=\"START_PUBLISH_CDN_FAILED\",FC[FC.STOP_PUBLISH_CDN_FAILED=16454]=\"STOP_PUBLISH_CDN_FAILED\",FC[FC.START_MIX_TRANSCODE_FAILED=16455]=\"START_MIX_TRANSCODE_FAILED\",FC[FC.STOP_MIX_TRANSCODE_FAILED=16456]=\"STOP_MIX_TRANSCODE_FAILED\",FC[FC.NOT_SUPPORTED_H264=16457]=\"NOT_SUPPORTED_H264\",FC[FC.SWITCH_ROLE_FAILED=16458]=\"SWITCH_ROLE_FAILED\",FC[FC.API_CALL_TIMEOUT=16459]=\"API_CALL_TIMEOUT\",FC[FC.SCHEDULE_FAILED=16460]=\"SCHEDULE_FAILED\",FC[FC.API_CALL_ABORTED=16461]=\"API_CALL_ABORTED\",FC[FC.UNKNOWN=65535]=\"UNKNOWN\",FC),mb=_b,fb=class extends Error{constructor(e){let{name:t=\"RtcError\",message:i,code:n=mb.UNKNOWN,extraCode:r=0,constraint:o}=e,s=\"<\".concat(function(e){for(let t in mb)if(mb[t]===e)return t;return\"UNKNOWN\"}(n),\" 0x\").concat(n.toString(16),\">\"),a=\"\".concat(i).concat(o?\" constraint: \".concat(o):\"\").concat(null!=i&&i.includes(s)?\"\":\" \".concat(s));super(a),ob(this,\"code\"),ob(this,\"extraCode\"),ob(this,\"message\"),ob(this,\"originMessage\"),ob(this,\"name\"),ob(this,\"constraint\"),this.code=n,this.extraCode=r,this.name=t,this.message=a,this.constraint=o,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},gb=fb,Tb=((new Date).getTime(),0),Eb=function(){return(new Date).getTime()+Tb},Sb=function(){let e=new Date;return e.setTime(Eb()),e.toLocaleString()},Ib={};ib(Ib,{bytes2ms:()=>KD,copyProperties:()=>JD,deepMerge:()=>CO,env:()=>vb,fibonacci:()=>$D,formatedTime:()=>NO,getConstructorName:()=>pO,getContainerFromElement:()=>bO,getEnv:()=>UD,getInternalVersion:()=>TO,getLoggerUrl:()=>BD,getMuteStateFromFlag:()=>IO,getNetworkQuality:()=>vO,getNetworkType:()=>GD,getOSType:()=>jD,getReconnectionTimeout:()=>eO,getStringByteLength:()=>wO,getSysInfo:()=>WD,getTerminalType:()=>HD,getTurnServer:()=>yO,getValueType:()=>tO,glog:()=>QD,ipv4ToUint32:()=>AO,isArray:()=>cO,isArrayOrObject:()=>RO,isAudioWorkletSupported:()=>_O,isBoolean:()=>sO,isConstructor:()=>hO,isEmpty:()=>SO,isFunction:()=>iO,isLangChinese:()=>XD,isMediaStreamTrack:()=>lO,isNumber:()=>oO,isObject:()=>aO,isOverseaSdkAppId:()=>FD,isPlainObject:()=>ZD,isPromise:()=>uO,isRemoteTrack:()=>dO,isString:()=>rO,isUndefined:()=>nO,ms2bytes:()=>zD,ms2samples:()=>qD,performanceNow:()=>fO,promiseAny:()=>mO,samples2ms:()=>YD,stringify:()=>DO,stringifyIncludeValue:()=>OO});var vb={};ib(vb,{ANDROID_VERSION:()=>Mb,CHROME_MAJOR_VERSION:()=>Vk,CHROME_VERSION:()=>xk,EDGE_VERSION:()=>jb,EDG_MAJOR_VERSION:()=>Jb,EDG_VERSION:()=>Wb,FIREFOX_MAJOR_VERSION:()=>Bb,FIREFOX_VERSION:()=>Fb,HUAWEI_VERSION:()=>Rk,IE_VERSION:()=>ik,IOS_MAIN_VERSION:()=>Gk,IOS_VERSION:()=>jk,IPADQQB_VERSION:()=>pk,IS_ANDROID:()=>Lb,IS_ANDROID_WEBVIEW:()=>Hk,IS_ANY_SAFARI:()=>Fk,IS_CHROME:()=>Lk,IS_CHROME_OS:()=>gk,IS_CHROMIUM_BASE:()=>Pk,IS_EDG:()=>Gb,IS_EDGE:()=>Hb,IS_ELECTRON:()=>Sk,IS_FIREFOX:()=>Ub,IS_HEADLESS_CHROME:()=>Mk,IS_HUAWEI:()=>Ak,IS_HUAWEIBROWSER:()=>yk,IS_IE:()=>tk,IS_IE8:()=>ek,IS_IOS:()=>Pb,IS_IOS_13_OR_14:()=>Kk,IS_IOS_15_1:()=>Jk,IS_IPAD:()=>Nb,IS_IPADQQB:()=>hk,IS_IPAD_PRO:()=>Db,IS_IPHONE:()=>Ob,IS_IPOD:()=>wb,IS_LINUX:()=>fk,IS_LOCAL:()=>Yk,IS_MAC:()=>mk,IS_MACQQB:()=>dk,IS_MIBROWSER:()=>Ik,IS_MQQB:()=>sk,IS_NATIVE_ANDROID:()=>xb,IS_OLD_ANDROID:()=>Vb,IS_OPPOBROWSER:()=>kk,IS_SAFARI:()=>Uk,IS_SAFARI_15_1:()=>Wk,IS_SAMSUNGBROWSER:()=>Ck,IS_SOGOU:()=>zb,IS_SOGOUM:()=>Kb,IS_TBS:()=>Qb,IS_UCBROWSER:()=>Ek,IS_VIVOBROWSER:()=>Dk,IS_WECHAT:()=>nk,IS_WIN:()=>_k,IS_WQQB:()=>ck,IS_WX:()=>Tk,IS_X5MQQB:()=>ok,IS_XWEB:()=>Zb,MACQQB_VERSION:()=>uk,MI_VERSION:()=>vk,MQQB_VERSION:()=>ak,OPPO_VERSION:()=>Nk,SAFARI_VERSION:()=>Bk,SAMSUNG_VERSION:()=>bk,SOGOUM_VERSION:()=>Yb,SOGOU_VERSION:()=>qb,TBS_VERSION:()=>Xb,USER_AGENT:()=>yb,VIVO_VERSION:()=>Ok,WECHAT_VERSION:()=>rk,WQQB_VERSION:()=>lk,XWEB_VERSION:()=>$b,browserInfo:()=>qk,getBrowserInfo:()=>Qk,getChromeMajorVersion:()=>wk,getOSName:()=>eN,getOSString:()=>tN,getUserAgentData:()=>Zk,isLocalStorageEnabled:()=>zk});var yb=\"undefined\"==typeof navigator?\"\":navigator.userAgent,Ab=e=>new RegExp(e,\"i\").test(yb),Rb=e=>{if(Ab(e)){let t=new RegExp(\"\".concat(e,\"\\\\/([\\\\d.]+)\")),i=yb.match(t);if(i&&i[1])return i[1]}return\"\"},Cb=e=>{if(Ab(e)){let t=new RegExp(\"\".concat(e,\"\\\\/(\\\\d+)\")),i=yb.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},bb=/AppleWebKit\\/([\\d.]+)/i.exec(yb),kb=bb?parseFloat(bb[1]):NaN,Nb=Ab(\"iPad\"),Db=\"undefined\"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Ab(\"Macintosh\"),Ob=Ab(\"iPhone\")&&!Nb,wb=Ab(\"iPod\"),Pb=Ob||Nb||wb||Db,Lb=Ab(\"Android\"),Mb=function(){if(Lb){let e=yb.match(/Android (\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))*/i);if(e){let t=e[1]&&parseFloat(e[1]),i=e[2]&&parseFloat(e[2]);if(t&&i)return parseFloat(\"\".concat(e[1],\".\").concat(e[2]));if(t)return t}}return NaN}(),Vb=Lb&&Ab(\"webkit\")&&Mb<2.3,xb=Lb&&Mb<5&&kb<537,Ub=Ab(\"Firefox\"),Fb=Rb(\"Firefox\"),Bb=Cb(\"Firefox\"),Hb=Ab(\"Edge\"),jb=Rb(\"Edge\"),Gb=Ab(\"Edg\"),Wb=Rb(\"Edg\"),Jb=Cb(\"Edg\"),Kb=Ab(\"SogouMobileBrowser\"),Yb=Rb(\"SogouMobileBrowser\"),zb=Ab(\"MetaSr\\\\s\"),qb=Rb(\"MetaSr\\\\s\"),Qb=Ab(\"TBS\"),Xb=Rb(\"TBS\"),Zb=Ab(\"XWEB\"),$b=Rb(\"XWEB\"),ek=Ab(\"MSIE\\\\s8\\\\.0\"),tk=Ab(\"MSIE\\\\/\\\\d+\"),ik=function(){if(tk){let e=/MSIE\\s(\\d+)\\.\\d/.exec(yb),t=e&&parseFloat(e[1]);return!t&&/Trident\\/7.0/i.test(yb)&&/rv:11.0/.test(yb)&&(t=11),t}return NaN}(),nk=Ab(\"(micromessenger|webbrowser)\"),rk=Rb(\"MicroMessenger\"),ok=!Qb&&Ab(\"MQQBrowser\")&&Ab(\"COVC\"),sk=!Qb&&Ab(\"MQQBrowser\")&&!Ab(\"COVC\"),ak=sk||ok?Rb(\"MQQBrowser\"):\"\",ck=!Qb&&Ab(\" QQBrowser\"),lk=Rb(\" QQBrowser\"),dk=!Qb&&Ab(\"QQBrowserLite\"),uk=Rb(\"QQBrowserLite\"),hk=!Qb&&Ab(\"MQBHD\"),pk=Rb(\"MQBHD\"),_k=Ab(\"Windows\"),mk=!Pb&&Ab(\"MAC OS X\"),fk=!Lb&&Ab(\"Linux\"),gk=Ab(\"CrOS\"),Tk=Ab(\"MicroMessenger\"),Ek=Ab(\"UCBrowser\"),Sk=Ab(\"Electron\"),Ik=Ab(\"MiuiBrowser\"),vk=Rb(\"MiuiBrowser\"),yk=Ab(\"HuaweiBrowser\"),Ak=Ab(\"Huawei\"),Rk=Rb(\"HuaweiBrowser\"),Ck=Ab(\"SamsungBrowser\"),bk=Rb(\"SamsungBrowser\"),kk=Ab(\"HeyTapBrowser\"),Nk=Rb(\"HeyTapBrowser\"),Dk=Ab(\"VivoBrowser\"),Ok=Rb(\"VivoBrowser\"),wk=()=>Cb(\"Chrome\"),Pk=Ab(\"Chrome\"),Lk=!Hb&&!zb&&!Kb&&!Qb&&!Zb&&!Gb&&!ck&&!Ik&&!yk&&!Ck&&!kk&&!Dk&&Pk,Mk=Ab(\"HeadlessChrome\"),Vk=wk(),xk=Rb(\"Chrome\"),Uk=!Pk&&!sk&&!ok&&!dk&&!hk&&Ab(\"Safari\"),Fk=Uk||Pb,Bk=Rb(\"Version\"),Hk=/Android.*(wv|.0.0.0)/.test(yb),jk=(()=>{if(Db)return Bk;if(Pb){let e=yb.match(/OS (\\d+)_(\\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=\".\".concat(e[2])),t}}return\"\"})(),Gk=Number(jk.split(\".\")[0]),Wk=\"15.1\"===Bk,Jk=\"15.1\"===jk,Kk=(()=>{let e=Number(jk.split(\".\")[0]);return 14===e||13===e})(),Yk=\"undefined\"!=typeof location&&(\"file:\"===location.protocol||\"localhost\"===location.hostname||\"127.0.0.1\"===location.hostname),zk=(()=>{let e;return()=>{if(nO(e))try{e=!!window.localStorage}catch(HL){e=!1}return e}})(),qk=Qk();function Qk(){let e=new Map([[Ub,[\"Firefox\",Fb]],[Gb,[\"Edg\",Wb]],[Lk,[\"Chrome\",xk]],[Uk,[\"Safari\",Bk]],[Qb,[\"TBS\",Xb]],[Zb,[\"XWEB\",$b]],[nk&&Ob,[\"WeChat\",rk]],[ck,[\"QQ(Win)\",lk]],[sk,[\"QQ(Mobile)\",ak]],[ok,[\"QQ(Mobile X5)\",ak]],[dk,[\"QQ(Mac)\",uk]],[hk,[\"QQ(iPad)\",pk]],[Ik,[\"MI\",vk]],[yk,[\"HW\",Rk]],[Ck,[\"Samsung\",bk]],[kk,[\"OPPO\",Nk]],[Dk,[\"VIVO\",Ok]],[Hb,[\"EDGE\",jb]],[Kb,[\"SogouMobile\",Yb]],[zb,[\"Sogou\",qb]]]),t=\"unknown\",i=\"unknown\";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var Xk=null;function Zk(){return ab(this,null,(function*(){if(Xk)return Xk;if(!navigator.userAgentData||!iO(navigator.userAgentData.getHighEntropyValues))return null;try{return Xk=yield navigator.userAgentData.getHighEntropyValues([\"architecture\",\"bitness\",\"model\",\"platformVersion\",\"fullVersionList\"])}catch(BL){return null}}))}var $k=new Map([[Lb,\"Android\"],[Pb,\"iOS\"],[_k,\"Windows\"],[mk,\"MacOS\"],[fk,\"Linux\"],[gk,\"ChromeOS\"]]),eN=function(){return $k.get(!0)?$k.get(!0):Xk?Xk.platform:\"unknown\"},tN=()=>{let e=eN();return e+=\"/\".concat(qk.name,\"/\").concat(Uk?qk.version:qk.version.split(\".\")[0]),null!=Xk&&Xk.platformVersion&&(e+=\"/\".concat(Xk.platformVersion)),null!=Xk&&Xk.architecture&&(e+=\"/\".concat(Xk.architecture)),e},iN={};ib(iN,{AUDIO_MUTE_BIT:()=>jN,AUDIO_STAT_BIT:()=>HN,AUX_STAT_BIT:()=>BN,AUX_STREAM_MSID:()=>JN,BACKEND_ENV:()=>VN,BASE_DOC_URL:()=>TN,BASE_HOST:()=>_N,CAPABILITIES_KEYS:()=>VD,CLASS_NAME:()=>yD,CLOUD_CONSOLE_URL:()=>gN,DATA_FREEZE_TIMING:()=>fD,DOC_URL:()=>EN,DTLS_STATE_UNKNOWN:()=>tD,ENV_NAME:()=>AN,EXCHANGE_SDP_TIMEOUT:()=>uD,INTERVAL:()=>LD,IS_WORKER:()=>lN,IS_WORKLET:()=>dN,KIBANA_EVENT:()=>cD,LOCAL_STREAM_PUBLISH_STATE:()=>mD,LOGGER_CMD_TYPE:()=>yN,LOGGER_DOMAIN:()=>SN,LOGGER_DOMAIN_OVERSEA:()=>IN,LOG_LEVEL:()=>RN,LOG_LEVEL_NAME:()=>kD,MAIN_STREAM_MSID:()=>WN,MICROPHONE_COMMUNICATIONS:()=>bD,MICROPHONE_DEFAULT:()=>RD,NAME:()=>LN,NETWORK_TYPE:()=>kN,NOT_SUPPORTED_H264:()=>_D,PAUSED_RETRY_COUNT:()=>AD,PEERCONNECTION_CONNECTING_TIMEOUT:()=>SD,PEER_CONNECTION_STATE:()=>iD,PEER_LEAVE_REASON:()=>ND,RAF:()=>PD,RECOVER_CAPTURE_INTERVAL:()=>OD,REMOTE_STREAM_TYPE_AUX:()=>YN,REMOTE_STREAM_TYPE_MAIN:()=>KN,RENDER_FREEZE_TIMING:()=>gD,RIC:()=>wD,SCHEDULE_DOMAIN:()=>ID,SCHEDULE_TIMEOUT:()=>vD,SDP_SEMANTICS_PLAN_B:()=>pD,SDP_SEMANTICS_UNIFIED_PLAN:()=>hD,SECOND_HOST:()=>mN,SIGNAL_PING_PONG_INTERVAL:()=>bN,SIGNAL_PING_TIMEOUT:()=>CN,SIGNAL_RECONNECTION_COUNT:()=>aD,SMALL_STAT_BIT:()=>FN,SPEAKER_DEFAULT:()=>CD,STORAGE_EXPIRES_TIME:()=>NN,STREAM_TYPE_BIG:()=>TD,STREAM_TYPE_SMALL:()=>ED,SUBSCRIBE_SMALL_RETRY_COUNT:()=>DD,SYNC_USER_LIST_INTERVAL:()=>lD,Scene:()=>xN,Switch:()=>DN,THIRD_HOST:()=>fN,TIMEOUT:()=>MD,TRANSPORT_DIRECTION:()=>MN,TRTC_ERROR_ASSISTANCE:()=>vN,TRTC_QUALITY_BAD:()=>ZN,TRTC_QUALITY_DISCONNECTED:()=>eD,TRTC_QUALITY_EXCELLENT:()=>qN,TRTC_QUALITY_GOOD:()=>QN,TRTC_QUALITY_POOR:()=>XN,TRTC_QUALITY_UNKNOWN:()=>zN,TRTC_QUALITY_VERY_BAD:()=>$N,UPDATE_OFFER_TIMEOUT:()=>dD,VIDEO_MUTE_BIT:()=>GN,VIDEO_STAT_BIT:()=>UN,audioProfileMap:()=>ON,getRetryCount:()=>oD,getScriptDir:()=>uN,innerVersion:()=>nN,loggerProxy:()=>hN,screenProfileMap:()=>PN,setLoggerProxy:()=>pN,setRetryCount:()=>rD,setVersion:()=>oN,version:()=>rN,videoProfileMap:()=>wN});var nN=\"4.15.00.1600\",rN=\"5.0.0\";function oN(e){rN=e;let[t,i,n]=e.split(\".\").map((e=>parseInt(e,10)));nN=\"\".concat(t,\".\").concat(Math.min(15,i),\".\").concat(Math.min(15,n),\".\").concat(i.toString().padStart(2,\"0\")).concat(n.toString().padStart(2,\"0\"))}var sN,aN,cN,lN=\"undefined\"!=typeof importScripts,dN=\"undefined\"!=typeof registerProcessor,uN=()=>{let e=lN?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf(\"/\")+1)},hN=\"\",pN=e=>hN=e,_N=\"web.sdk.qcloud.com\",mN=\"web.sdk.tencent.cn\",fN=\"web.sdk.cloud.tencent.cn\",gN=\"https://console.cloud.tencent.com/trtc\",TN=\"https://\".concat(_N,\"/trtc/webrtc/v5/doc\"),EN=\"\".concat(TN,\"/zh-cn/\"),SN=\"https://yun.tim.qq.com\",IN=\"https://apisgp.my-imcloud.com\",vN=\"trtc_error_assistance\",yN={LOG:\"jssdk_log\",EVENT:\"jssdk_event\",KEY_POINT:\"jssdk_new_endreport\"},AN={QCLOUD:\"qcloud\",OLD_CLOUD_LADDER:\"trtc\",WEBRTC:\"webrtc\"},RN=((cN=RN||{})[cN.TRACE=0]=\"TRACE\",cN[cN.DEBUG=1]=\"DEBUG\",cN[cN.INFO=2]=\"INFO\",cN[cN.WARN=3]=\"WARN\",cN[cN.ERROR=4]=\"ERROR\",cN[cN.NONE=5]=\"NONE\",cN),CN=18e3,bN=2e3,kN={unknown:0,wifi:1,\"3g\":2,\"2g\":3,\"4g\":4,wired:5},NN=6048e5,DN=((aN=DN||{}).USEAINS=\"useAINS\",aN.ENABLEDEBUG=\"enableDebug\",aN.USEV2=\"useV2\",aN.USEWT=\"useWt\",aN),ON={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}},wN={\"120p\":{width:160,height:120,frameRate:15,bitrate:200},\"120p_2\":{width:160,height:120,frameRate:15,bitrate:100},\"180p\":{width:320,height:180,frameRate:15,bitrate:350},\"180p_2\":{width:320,height:180,frameRate:15,bitrate:150},\"240p\":{width:320,height:240,frameRate:15,bitrate:400},\"240p_2\":{width:320,height:240,frameRate:15,bitrate:200},\"360p\":{width:640,height:360,frameRate:15,bitrate:800},\"360p_2\":{width:640,height:360,frameRate:15,bitrate:400},\"480p\":{width:640,height:480,frameRate:15,bitrate:900},\"480p_2\":{width:640,height:480,frameRate:15,bitrate:500},\"720p\":{width:1280,height:720,frameRate:15,bitrate:1500},\"1080p\":{width:1920,height:1080,frameRate:15,bitrate:2e3},\"1440p\":{width:2560,height:1440,frameRate:30,bitrate:4860},\"4K\":{width:3840,height:2160,frameRate:30,bitrate:9e3}},PN={\"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}},LN={CANVAS:\"canvas\",AUDIO:\"audio\",VIDEO:\"video\",SCREEN:\"screen\",SMALL:\"small\",BIG:\"big\",AUXILIARY:\"auxiliary\",SMALL_VIDEO:\"smallVideo\",FACING_MODE_USER:\"user\",FACING_MODE_ENVIRONMENT:\"environment\",MUTE:\"mute\",UNMUTE:\"unmute\",ENDED:\"ended\",PLAYING:\"playing\",PAUSE:\"pause\",ERROR:\"error\",LOADEDDATA:\"loadeddata\",AUDIO_INPUT:\"audioinput\",VIDEO_INPUT:\"videoinput\",DETAIL:\"detail\",TEXT:\"text\",MAIN:\"main\",BACKUP:\"backup\",BANNED:\"banned\",KICK:\"kick\",USER_TIME_OUT:\"user_time_out\",ROOM_DISBAND:\"room_disband\",SEI_MESSAGE:\"sei-message\",ADD:\"add\",REMOVE:\"remove\",REPLACE:\"replace\",TRACK:\"track\",SUBSCRIBE:\"subscribe\",UNSUBSCRIBE:\"unsubscribe\",TRANSCEIVER_DIRECTION_SENDONLY:\"sendonly\",TRANSCEIVER_DIRECTION_RECVONLY:\"recvonly\",ENTER_PICTURE_IN_PICTURE:\"enterpictureinpicture\",LEAVE_PICTURE_IN_PICTURE:\"leavepictureinpicture\"},MN={INACTIVE:\"inactive\",SENDONLY:\"sendonly\",RECVONLY:\"recvonly\"},VN={OLD_CLOUD_LADDER:\"wss://trtc.rtc.qq.com\",WEBRTC:\"wss://webrtc.qq.com\"},xN=((sN=xN||{}).LIVE=\"live\",sN.RTC=\"rtc\",sN),UN=1,FN=2,BN=4,HN=8,jN=64,GN=16,WN=\"5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV\",JN=\"224d130c-7b5c-415b-aaa2-79c2eb5a6df2\",KN=LN.MAIN,YN=LN.AUXILIARY,zN=0,qN=1,QN=2,XN=3,ZN=4,$N=5,eD=6,tD=\"unknown\",iD={NEW:\"new\",CONNECTING:\"connecting\",FAILED:\"failed\",CLOSED:\"closed\",DISCONNECTED:\"disconnected\",CONNECTED:\"connected\",COMPLETED:\"completed\"},nD=1/0;function rD(e){nD=e}function oD(){return nD}var sD,aD=30,cD={JOIN:\"join\",DELTA_JOIN:\"delta-join\",REJOIN:\"rejoin\",LEAVE:\"leave\",DELTA_LEAVE:\"delta-leave\",PUBLISH:\"publish\",DELTA_PUBLISH:\"delta-publish\",UNPUBLISH:\"unpublish\",SUBSCRIBE:\"subscribe\",UNSUBSCRIBE:\"unsubscribe\",UPLINK_CONNECTION:\"uplink-connection\",UPLINK_RECONNECTION:\"uplink-reconnection\",DOWNLINK_CONNECTION:\"downlink-connection\",DOWNLINK_RECONNECTION:\"downlink-reconnection\",ON_TRACK:\"ontrack\",ICE_CONNECTION_STATE:\"iceConnectionState\",LOCAL_STREAM_INITIALIZE:\"stream-initialize\",SIGNAL_CONNECTION:\"websocketConnectionState\",SIGNAL_RECONNECTION:\"websocketReconnectionState\",UPDATE_STREAM:\"update-stream\",RECOVER_LOCAL_AUDIO_TRACK:\"recover-local-audio-track\",RECOVER_LOCAL_VIDEO_TRACK:\"recover-local-video-track\",RECOVER_SUBSCRIPTION:\"recover-subscription\",START_MIX_TRANSCODE:\"start-mix-transcode\",STOP_MIX_TRANSCODE:\"stop-mix-transcode\",PLAYER_ERROR:\"player-error\",SCHEDULE:\"schedule\",LOAD_WORKLET:\"load-worklet\",VIDEO_FROZEN_COUNT:\"videoFrozenCount\",GET_USER_MEDIA_RETRY:\"getUserMedia-retry\"},lD=1e4,dD=1e4,uD=1e4,hD=\"unified-plan\",pD=\"plan-b\",_D=1028,mD=((sD=mD||{})[sD.UNPUBLISH=-1]=\"UNPUBLISH\",sD[sD.PUBLISHING=0]=\"PUBLISHING\",sD[sD.PUBLISHED=1]=\"PUBLISHED\",sD),fD=500,gD=1e3,TD=LN.BIG,ED=LN.SMALL,SD=1e4,ID={MAIN:\"schedule.rtc.qq.com\",BACKUP:\"schedule.rtc.qcloud.com\",MAIN_OVERSEA:\"schedule.rtc.tencentcloud.com\",BACKUP_OVERSEA:\"schedule-ecdn.rtc.tencentcloud.com\"},vD=2e3,yD={TRTC:\"TRTC\",CLIENT:\"Client\",LOCAL_STREAM:\"LocalStream\",REMOTE_STREAM:\"RemoteStream\",STREAM:\"Stream\"},AD=5,RD=\"default\",CD=RD,bD=\"communications\",kD=Object.keys(RN),ND=[\"normal leave\",\"timeout leave\",\"kick\",\"role change\"],DD=10,OD=2e3,wD=\"ric\",PD=\"raf\",LD=\"interval\",MD=\"timeout\",VD=[\"width\",\"height\",\"frameRate\",\"facingMode\",\"sampleRate\",\"sampleSize\",\"channelCount\",\"deviceId\"],xD=1e8,UD=function(){return new URLSearchParams(location.search).get(\"trtc_env\")||\"\"},FD=e=>Number(e)<14e8,BD=function(e,t){let i;i=hN||(FD(e)?IN:SN);let n=Math.floor(Math.random()*XC(2,31));return\"\".concat(i,\"/v5/AVQualityReportSvc/C2S?random=\").concat(n,\"&sdkappid=\").concat(e,\"&cmdtype=\").concat(t)};function HD(){return Lb?4:Ob?2:Nb?3:mk?12:_k?5:fk?13:1}function jD(){return Lb?\"Android\":Ob?\"iPhone\":Nb?\"iPad\":mk?\"Mac\":_k?\"Windows\":fk?\"Linux\":\"unknown\"}function GD(){let{userAgent:e,connection:t}=navigator,i=(e.match(/NetType\\/\\S+/)||[])[0]||\"\";i=i.toLowerCase().replace(\"nettype/\",\"\"),\"3gnet\"===i&&(i=\"3g\");let n=t&&t.type&&t.type.toLowerCase(),r=t&&t.effectiveType&&t.effectiveType.toLowerCase();\"slow-2\"===r&&(r=\"2g\");let o=i||\"unknown\";if(n)switch(n){case\"cellular\":case\"wimax\":o=r||\"unknown\";break;case\"wifi\":o=\"wifi\";break;case\"ethernet\":o=\"wired\";break;default:o=\"unknown\"}return o}var WD=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:HD(),uint32_device_type:0,str_os_verion:jD(),uint32_link_type:1,str_client_version:nN,uint32_net_type:kN[GD()],ua:navigator.userAgent,version:\"\"}}}};function JD(e,t){for(let i of Reflect.ownKeys(t))if(\"constructor\"!==i&&\"prototype\"!==i&&\"name\"!==i){let n=Object.getOwnPropertyDescriptor(t,i)||\"\";Object.defineProperty(e,i,n)}return e}function KD(e){return YD(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function YD(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function zD(e){return 4*qD(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function qD(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var QD=\"undefined\"!=typeof window&&\"function\"==typeof window.glog?window.glog:()=>{},XD=()=>{let e=navigator.language;return e=e.substring(0,2),\"zh\"===e},ZD=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 $D(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:$D(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function eO(e){return e>8?3e4:1e3*$D(e)}function tO(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\\[object\\s(\\w+)\\]$/,\"$1\").toLowerCase()}var iO=e=>\"function\"==typeof e,nO=e=>void 0===e,rO=e=>\"string\"==typeof e,oO=e=>\"number\"==typeof e,sO=e=>\"boolean\"==typeof e,aO=e=>\"object\"===tO(e),cO=e=>\"array\"===tO(e),lO=e=>tO(e)===\"MediaStreamTrack\".toLowerCase(),dO=e=>e.isRemote,uO=e=>\"promise\"===tO(e),hO=e=>iO(e)&&e.prototype.constructor===e,pO=e=>hO(e)?e.prototype.constructor.name:\"\",_O=\"undefined\"!=typeof AudioWorkletNode;function mO(e){return new Promise(((t,i)=>{let n=[];e.forEach((r=>{r.then(t).catch((t=>{n.push(t),n.length===e.length&&i(n)}))}))}))}function fO(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var gO=e=>+e<10?\"0\".concat(e):e,TO=e=>{let t=e.match(/^\\d+\\.\\d+\\.\\d+/)[0];if(!t)return e;let i=t.split(\".\"),n=gO(i[1])+gO(i[2]);return i[1]-15>0&&(i[1]=\"15\"),i[2]-15>0&&(i[2]=\"15\"),\"\".concat(i.join(\".\"),\".\").concat(n)},EO=Object.prototype.hasOwnProperty;function SO(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(ZD(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(EO.call(e,t))return!1;return!0}return!1}function IO(e,t){return{userId:t,hasAudio:!!(e&HN),hasVideo:!!(e&UN),hasAuxiliary:!!(e&BN),hasSmall:!!(e&FN),audioMuted:!!(e&jN),videoMuted:!!(e&GN),audioAvailable:!(!(e&HN)||e&jN),videoAvailable:!(!(e&UN)||e&GN)}}function vO(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 yO(e){let t={urls:\"turn:\".concat(e.url)};return!nO(e.username)&&!nO(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType=\"password\",nO(e.credentialType)||(t.credentialType=e.credentialType)),t}function AO(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!rO(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 RO=function(e){return cO(e)||aO(e)},CO=function(e,t,i,n){if(!RO(e)||!RO(t))return 0;let r,o=0,s=Object.keys(t);for(let a=0,c=s.length;arO(e)?document.getElementById(e):e,kO=new Intl.DateTimeFormat(\"zh-CN\",{dateStyle:\"short\",timeStyle:\"medium\"}),NO=()=>kO.format(new Date);function DO(e,t){let{keysToInclude:i,keysToExclude:n}=t;try{if(cO(e))return\"[\".concat(e.map((e=>DO(e,{keysToInclude:i,keysToExclude:n}))).join(\",\"),\"]\");if(!ZD(e)||!cO(i)&&!cO(n))return JSON.stringify(e);let t={},r=new Set(i),o=new Set(n);return Object.keys(e).forEach((s=>{(0===o.size&&r.has(s)||0===r.size&&!o.has(s))&&(t[s]=ZD(e[s])||cO(e[s])?JSON.parse(DO(e[s],{keysToExclude:n,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(sD){return\"{}\"}}function OO(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=[];return Object.keys(e).forEach((n=>{t===e[n]&&i.push(n)})),DO(e,{keysToInclude:i})}function wO(e){return e.replace(/[\\u4e00-\\u9fa5]/g,\"aa\").length}function PO(e){let{url:t,body:i,method:n,timeout:r}=e,o=new XMLHttpRequest;return new Promise(((e,s)=>{o.onreadystatechange=()=>{if(4===o.readyState)if(o.status>=200&&o.status<300)try{let t=JSON.parse(o.response);e({data:t})}catch(qx){e({data:o.response})}else s({status:o.status,statusText:o.statusText||\"request failed!\"})},o.timeout=r||5e3,o.open(n||\"POST\",t,!0),o.send(i)}))}var LO,MO=function(e){let{retryFunction:t,settings:i,onError:n,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:a}=e;return function(){for(var e=arguments.length,c=new Array(e),l=0;lab(this,null,(function*(){let l=a||this;try{let i=yield t.apply(l,c);h>0&&s&&s.call(this,h),h=0,e(i)}catch(f){let t=()=>{clearTimeout(p),h=0,_=2,i(f)},s=()=>{2!==_&&h<(iO(d)?d():d)?(h++,_=1,iO(r)&&r.call(this,h,t),p=window.setTimeout((()=>{p=-1,m(e,i)}),iO(u)?u(h):u)):(t(),iO(o)&&o.call(this,f))};iO(n)?n.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retryCount:h}):s()}}));return new Promise(m)}},VO=class{constructor(e){ob(this,\"userId\"),ob(this,\"remoteUserId\"),ob(this,\"id\"),ob(this,\"sdkAppId\"),ob(this,\"type\"),ob(this,\"isLocal\"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!sO(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):\"\",\"]\")),HO.log(e,t,nO(this.userId)||SO(this.userId),this.userId,this.sdkAppId)}info(){for(var e=arguments.length,t=new Array(e),i=0;i{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&RN[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),xO.on(FO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),xO.once(FO.JOIN_FAILED,(()=>{this.startUpload()})),xO.on(FO.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{let{userId:n,sdkAppId:r}=t;e.map.has(n)?e.map.get(n).logs.push(i):e.map.set(n,{userId:n,sdkAppId:r,logs:[i]})}));else if(rO(i.userId)&&oO(i.sdkAppId)){let{userId:t,sdkAppId:n}=i;e.map.has(t)?e.map.get(t).logs.push(i):e.map.set(t,{userId:t,sdkAppId:n,logs:[i]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e}upload(){return ab(this,null,(function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;ee.log)).join(\"\\n\")}),n),r.forEach((e=>e.uploaded=!0))}}catch(aN){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return MO({retryFunction:()=>PO({url:BD(t,yN.LOG),body:e,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;t.setTime(Eb());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(RN[e],\">\")}getLogLevel(){return this._logLevel}setLogLevel(e){nO(RN[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(rO(e))return e;try{return JSON.stringify(e)}catch(sN){return\"\"}}log(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,r=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:n,sdkAppId:r,forAllJoinedClients:i}),e{let t=16*Math.random()|0;return(\"x\"==e?t:3&t|8).toString(16)}))},GO=new class{constructor(){ob(this,\"_prefix\",\"TRTC\"),ob(this,\"_queue\",new Map),this.checkStorage()}getRealKey(e){return\"\".concat(this._prefix,\"_\").concat(e)}checkStorage(){zk()&&(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.expiresInlocalStorage.removeItem(e))))}doFlush(){if(zk())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(HL){HO.warn(HL)}}getItem(e){if(!zk())return null;try{let t=JSON.parse(localStorage.getItem(this.getRealKey(e)));return t&&t.expiresIn>=Date.now()?t.value:null}catch(sN){HO.warn(sN)}}setItem(e,t){if(zk())try{let i={expiresIn:Date.now()+NN,value:t};this._queue.set(this.getRealKey(e),i)}catch(sD){HO.warn(sD)}}deleteItem(e){if(!zk())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(sN){return HO.warn(sN),!1}}clear(){if(zk())try{localStorage.clear()}catch(HL){HO.warn(HL)}}},WO={};ib(WO,{HTTPS_API:()=>dw,IS_GET_CAPABILITIES_SUPPORTED:()=>bw,IS_GET_SETTINGS_SUPPORTED:()=>Cw,IS_SEI_SUPPORTED:()=>kw,IS_SPC_SUPPORTED:()=>vw,basis:()=>Pw,checkSystemRequirementsInternal:()=>aw,decodeSupportStatus:()=>sw,encodeSupportStatus:()=>ow,getBrowserInfo:()=>ZO,getDisplayResolution:()=>hw,isAddTransceiverSupported:()=>Iw,isBrowserSupported:()=>$O,isGetReceiversSupported:()=>Tw,isGetSendersSupported:()=>Ew,isGetTransceiversSupported:()=>Sw,isGetUserMediaSupported:()=>pw,isMediaDevicesSupported:()=>tw,isMediaSessionSupported:()=>Ow,isMediaStreamTrackProcessorSupported:()=>rw,isReplaceTrackSupported:()=>Aw,isScreenCaptureApiAvailable:()=>lw,isSelectedCandidatePair:()=>uw,isSetParametersSupported:()=>Rw,isSmallStreamAPISupported:()=>mw,isSmallStreamSupported:()=>fw,isStopTransceiverSupported:()=>yw,isTRTCSupported:()=>cw,isUnifiedPlanDefault:()=>gw,isUsedInHttpProtocol:()=>nw,isWebAudioSupported:()=>_w,isWebCodecSupported:()=>Dw,isWebCodecsSupported:()=>ew,isWebRTCSupported:()=>Nw,isWebTransportSupported:()=>ww});var JO={AVOID_REPEATED_CALL:\"AVOID_REPEATED_CALL\",INVALID_PARAMETER_REQUIRED:\"INVALID_PARAMETER_REQUIRED\",INVALID_PARAMETER_TYPE:\"INVALID_PARAMETER_TYPE\",INVALID_PARAMETER_EMPTY:\"INVALID_PARAMETER_EMPTY\",INVALID_PARAMETER_INSTANCE:\"INVALID_PARAMETER_INSTANCE\",INVALID_PARAMETER_RANGE:\"INVALID_PARAMETER_RANGE\",INVALID_PARAMETER_MIN:\"INVALID_PARAMETER_MIN\",INVALID_PARAMETER_MAX:\"INVALID_PARAMETER_MAX\",INVALID_PARAMETER_STREAMTYPE:\"INVALID_PARAMETER_STREAMTYPE\",API_CALL_TIMEOUT:\"API_CALL_TIMEOUT\",SIGNAL_CHANNEL_RECONNECTION_FAILED:\"SIGNAL_CHANNEL_RECONNECTION_FAILED\",SIGNAL_CHANNEL_SETUP_FAILED:\"SIGNAL_CHANNEL_SETUP_FAILED\",ERROR_MESSAGE:\"ERROR_MESSAGE\",EXCHANGE_SDP_TIMEOUT:\"EXCHANGE_SDP_TIMEOUT\",DOWNLINK_RECONNECTION_FAILED:\"DOWNLINK_RECONNECTION_FAILED\",EXCHANGE_SDP_FAILED:\"EXCHANGE_SDP_FAILED\",UPDATE_OFFER_TIMEOUT:\"UPDATE_OFFER_TIMEOUT\",UPLINK_RECONNECTION_FAILED:\"UPLINK_RECONNECTION_FAILED\",INVALID_RECORDID:\"INVALID_RECORDID\",INVALID_PURE_AUDIO:\"INVALID_PURE_AUDIO\",INVALID_STREAMID:\"INVALID_STREAMID\",INVALID_USER_DEFINE_RECORDID:\"INVALID_USER_DEFINE_RECORDID\",INVALID_USER_DEFINE_PUSH_ARGS:\"INVALID_USER_DEFINE_PUSH_ARGS\",INVALID_PROXY:\"INVALID_PROXY\",INVALID_JOIN:\"INVALID_JOIN\",INVALID_ROOMID_STRING:\"INVALID_ROOMID_STRING\",INVALID_ROOMID_INTEGER:\"INVALID_ROOMID_INTEGER\",INVALID_SIGNAL_CHANNEL:\"INVALID_SIGNAL_CHANNEL\",JOIN_ROOM_TIMEOUT:\"JOIN_ROOM_TIMEOUT\",JOIN_ROOM_FAILED:\"JOIN_ROOM_FAILED\",REJOIN_ROOM_FAILED:\"REJOIN_ROOM_FAILED\",INVALID_DESTROY:\"INVALID_DESTROY\",INVALID_PUBLISH:\"INVALID_PUBLISH\",INVALID_UNPUBLISH:\"INVALID_UNPUBLISH\",INVALID_AUDIENCE:\"INVALID_AUDIENCE\",INVALID_INITIALIZE:\"INVALID_INITIALIZE\",INVALID_DUPLICATE_PUBLISHING:\"INVALID_DUPLICATE_PUBLISHING\",INVALID_SUBSCRIBE_UNDEFINED:\"INVALID_SUBSCRIBE_UNDEFINED\",INVALID_SUBSCRIBE_LOCAL:\"INVALID_SUBSCRIBE_LOCAL\",INVALID_REMOTE_STREAM:\"INVALID_REMOTE_STREAM\",SUBSCRIBE_FAILED:\"SUBSCRIBE_FAILED\",INVALID_ROLE:\"INVALID_ROLE\",INVALID_PARAMETER_SWITCH_ROLE:\"INVALID_PARAMETER_SWITCH_ROLE\",INVALID_OPERATION_SWITCH_ROLE:\"INVALID_OPERATION_SWITCH_ROLE\",SWITCH_ROLE_TIMEOUT:\"SWITCH_ROLE_TIMEOUT\",SWITCH_ROLE_FAILED:\"SWITCH_ROLE_FAILED\",CLIENT_BANNED:\"CLIENT_BANNED\",INVALID_OPERATION_START_PUBLISH_CDN:\"INVALID_OPERATION_START_PUBLISH_CDN\",INVALID_OPERATION_STOP_PUBLISH_CDN:\"INVALID_OPERATION_STOP_PUBLISH_CDN\",INVALID_STREAM_ID:\"INVALID_STREAM_ID\",START_PUBLISH_CDN_FAILED:\"START_PUBLISH_CDN_FAILED\",STOP_PUBLISH_CDN_FAILED:\"STOP_PUBLISH_CDN_FAILED\",START_MIX_TRANSCODE:\"START_MIX_TRANSCODE\",STOP_MIX_TRANSCODE:\"STOP_MIX_TRANSCODE\",INVALID_AUDIO_VOLUME:\"INVALID_AUDIO_VOLUME\",ENABLE_SMALL_STREAM_PUBLISHED:\"ENABLE_SMALL_STREAM_PUBLISHED\",DISABLE_SMALL_STREAM_PUBLISHED:\"DISABLE_SMALL_STREAM_PUBLISHED\",NOT_SUPPORTED_SMALL_STREAM:\"NOT_SUPPORTED_SMALL_STREAM\",INVALID_SMALL_STREAM_PROFILE:\"INVALID_SMALL_STREAM_PROFILE\",INVALID_PARAMETER_REMOTE_STREAM:\"INVALID_PARAMETER_REMOTE_STREAM\",INVALID_OPERATION_CHANGE_SMALL:\"INVALID_OPERATION_CHANGE_SMALL\",REMOTE_NOT_PUBLISH_SMALL_STREAM:\"REMOTE_NOT_PUBLISH_SMALL_STREAM\",INVALID_SWITCH_DEVICE:\"INVALID_SWITCH_DEVICE\",INVALID_SWITCH_DEVICE_PUBLISHING:\"INVALID_SWITCH_DEVICE_PUBLISHING\",INVALID_REPLACE_TRACK:\"INVALID_REPLACE_TRACK\",INVALID_INITIALIZE_LOCAL_STREAM:\"INVALID_INITIALIZE_LOCAL_STREAM\",INVALID_ADD_TRACK_REPETITIVE:\"INVALID_ADD_TRACK_REPETITIVE\",INVALID_ADD_TRACK_REMOVING:\"INVALID_ADD_TRACK_REMOVING\",INVALID_ADD_TRACK_PUBLISHING:\"INVALID_ADD_TRACK_PUBLISHING\",INVALID_STREAM_INITIALIZED:\"INVALID_STREAM_INITIALIZED\",INVALID_ADD_TRACK_NUMBER:\"INVALID_ADD_TRACK_NUMBER\",INVALID_REMOVE_AUDIO_TRACK:\"INVALID_REMOVE_AUDIO_TRACK\",INVALID_REMOVE_AUDIO_ADDING:\"INVALID_REMOVE_AUDIO_ADDING\",INVALID_REMOVE_AUDIO_ON:\"INVALID_REMOVE_AUDIO_ON\",INVALID_REMOVE_TRACK_PUBLISHING:\"INVALID_REMOVE_TRACK_PUBLISHING\",INVALID_REMOVE_TRACK_NOT_TRACK:\"INVALID_REMOVE_TRACK_NOT_TRACK\",INVALID_REMOVE_TRACK_NUMBER:\"INVALID_REMOVE_TRACK_NUMBER\",INVALID_REPLACE_TRACK_NO_TRACK:\"INVALID_REPLACE_TRACK_NO_TRACK\",REPEAT_JOIN:\"REPEAT_JOIN\",CLIENT_DESTROYED:\"CLIENT_DESTROYED\",NOT_BUG_PACKAGE:\"NOT_BUG_PACKAGE\",START_MIX_TRANSCODE_FAILED:\"START_MIX_TRANSCODE_FAILED\",STOP_MIX_TRANSCODE_FAILED:\"STOP_MIX_TRANSCODE_FAILED\",MIX_TRANSCODE_NOT_STARTED:\"MIX_TRANSCODE_NOT_STARTED\",CANNOT_LESS_THAN_ZERO:\"CANNOT_LESS_THAN_ZERO\",MIX_PARAMS_VIDEO_FRAMERATE:\"MIX_PARAMS_VIDEO_FRAMERATE\",MIX_PARAMS_VIDEO_GOP:\"MIX_PARAMS_VIDEO_GOP\",MIX_PARAMS_AUDIO_BITRATE:\"MIX_PARAMS_AUDIO_BITRATE\",MIX_PARAMS_USER_Z_ORDER:\"MIX_PARAMS_USER_Z_ORDER\",MIX_PARAMS_NOT_SELF:\"MIX_PARAMS_NOT_SELF\",MIX_PARAMS_USER_STREAM:\"MIX_PARAMS_USER_STREAM\",INVALID_PLAY:\"INVALID_PLAY\",INVALID_ELEMENT_ID:\"INVALID_ELEMENT_ID\",INVALID_ELEMENT_ID_TYPE:\"INVALID_ELEMENT_ID_TYPE\",PLAY_FAILED:\"PLAY_FAILED\",INVALID_USERID:\"INVALID_USERID\",INVALID_CREATE_STREAM_SOURCE:\"INVALID_CREATE_STREAM_SOURCE\",INVALID_CREATE_STREAM_SCREEN:\"INVALID_CREATE_STREAM_SCREEN\",INVALID_CREATE_STREAM_AUDIO:\"INVALID_CREATE_STREAM_AUDIO\",INVALID_CREATE_STREAM_SCREEN_AUDIO:\"INVALID_CREATE_STREAM_SCREEN_AUDIO\",NOT_SUPPORTED_HTTP:\"NOT_SUPPORTED_HTTP\",NOT_SUPPORTED_WEBRTC:\"NOT_SUPPORTED_WEBRTC\",NOT_SUPPORTED_PROFILE:\"NOT_SUPPORTED_PROFILE\",NOT_SUPPORTED_MEDIA:\"NOT_SUPPORTED_MEDIA\",NOT_SUPPORTED_H264ENCODE:\"NOT_SUPPORTED_H264ENCODE\",NOT_SUPPORTED_H264DECODE:\"NOT_SUPPORTED_H264DECODE\",NOT_SUPPORTED_TRACK:\"NOT_SUPPORTED_TRACK\",NOT_SUPPORTED_SWITCH_DEVICE:\"NOT_SUPPORTED_SWITCH_DEVICE\",NOT_SUPPORTED_CAPTURE:\"NOT_SUPPORTED_CAPTURE\",NOT_SUPPORTED_AUX:\"NOT_SUPPORTED_AUX\",MICROPHONE_NOT_FOUND:\"MICROPHONE_NOT_FOUND\",CAMERA_NOT_FOUND:\"CAMERA_NOT_FOUND\",SIGNAL_RESPONSE_FAILED:\"SIGNAL_RESPONSE_FAILED\",CATCH_HANDLER_ERROR:\"CATCH_HANDLER_ERROR\",API_NOT_EXIST:\"API_NOT_EXIST\",CONNECTION_CLOSED:\"CONNECTION_CLOSED\",SUBSCRIBE_ALL_FALSE:\"SUBSCRIBE_ALL_FALSE\",SEI_NOT_SUPPORT:\"SEI_NOT_SUPPORT\",SEI_DISABLED:\"SEI_DISABLED\",SEI_EMPTY:\"SEI_EMPTY\",SEI_OVERSIZE:\"SEI_OVERSIZE\",SEI_BEFORE_PUBLISH:\"SEI_BEFORE_PUBLISH\",SEI_NOT_VIDEO:\"SEI_NOT_VIDEO\",CALL_FREQUENCY_LIMIT:\"CALL_FREQUENCY_LIMIT\",CONNECTION_ABORTED:\"CONNECTION_ABORTED\",API_CALL_ABORTED:\"API_CALL_ABORTED\",DUPLICATE_AUX:\"DUPLICATE_AUX\"},KO={AVOID_REPEATED_CALL:e=>\"previous \".concat(e.name,\"() is ongoing, please avoid repeated calls.\"),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:n,value:r}=e;return\"'\".concat(t||i.name,\"' is a required param when calling \").concat(n,\"(), received: \").concat(r,\".\")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:n,value:r}=e,o=\"\".concat(t||i.name),s=\"\";return s=Array.isArray(i.type)?i.type.join(\"|\"):i.type,\"'\".concat(o,\"' must be type of \").concat(s,\" when calling \").concat(n,\"(), received type: \").concat(tO(r),\".\")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:n,value:r}=e;return\"'\".concat(t||i.name,\"' cannot be '\").concat(r,\"' when calling \").concat(n,\"().\")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:n,value:r}=e,o=\"\".concat(t||i.name),s=\"\".concat(i.instanceOf.name||i.instanceOf);return\"'\".concat(o,\"' must be instanceof \").concat(s,\" when calling \").concat(n,\"(), received type: \").concat(tO(r),\".\")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:n,value:r}=e;return\"'\".concat(t||i.name,\"' must be one of \").concat(i.values.join(\"|\"),\" when calling \").concat(n,\"(), received: \").concat(r,\".\")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:n,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,fnName:n,value:r}=e;return\"the max value of \".concat(t||i.name,\" is \").concat(i.max,\", received: \").concat(r,\".\")},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:n}=e;return\"failed to subscribe \".concat(i,\" \").concat(n,\" 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\"),NOT_BUG_PACKAGE:\"You need to buy packages, refer to tencent console.\",START_MIX_TRANSCODE_FAILED:e=>\"startMixTranscode failed, errMsg: \".concat(e.message,\".\"),STOP_MIX_TRANSCODE_FAILED:e=>\"stopMixTranscode failed, errMsg: \".concat(e.message,\".\"),MIX_TRANSCODE_NOT_STARTED:\"mixTranscode has not been started.\",CANNOT_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:n,value:r}=e;return\"'\".concat(t||i.name,\"' cannot be less than 0 when calling \").concat(n,\"().\")},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:n}=e;return\"the element corresponding to '\".concat(t,\"' must be instanceof HTMLElement when calling \").concat(i,\"(), received: \").concat(n,\".\")},PLAY_FAILED:e=>\"\".concat(e.media,\" play failed,browser exception: \").concat(e.error.toString()),INVALID_USERID:\"userId cannot be all spaces.\",INVALID_CREATE_STREAM_SOURCE:\"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.\",INVALID_CREATE_STREAM_SCREEN:\"screen/video cannot be both true.\",INVALID_CREATE_STREAM_AUDIO:\"audio/screenAudio cannot be both true.\",INVALID_CREATE_STREAM_SCREEN_AUDIO:\"when screen is true, screenAudio can be configured.\",NOT_SUPPORTED_HTTP:\"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.\",NOT_SUPPORTED_WEBRTC:\"your browser or environment does not support full WebRTC capabilities.\",NOT_SUPPORTED_PROFILE:\"your browser does not support setVideoProfile.\",NOT_SUPPORTED_MEDIA:\"your browser or environment does not support navigator.mediaDevices.\",NOT_SUPPORTED_H264ENCODE:\"your device does not support H.264 encoding.\",NOT_SUPPORTED_H264DECODE:\"your device does not support H.264 decoding.\",NOT_SUPPORTED_TRACK:e=>\"\".concat(e,\"Track is not supported on your browser.\"),NOT_SUPPORTED_SWITCH_DEVICE:\"switchDevice is not supported on your browser.\",NOT_SUPPORTED_CAPTURE:\"Your browser or environment does not support screen sharing, please check whether the browser version.\",MICROPHONE_NOT_FOUND:\"no microphone detected, please check your microphone.\",CAMERA_NOT_FOUND:\"no camera detected, please check your camera.\",SIGNAL_RESPONSE_FAILED:e=>\"\".concat(e.signalResponse,\" failed, response code is \").concat(e.code,\" , errMsg: \").concat(e.message,\".\"),CATCH_HANDLER_ERROR(e){let{name:t,event:i}=e;return\"an error was caught 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\",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:n,maxSizeInSecond:r}=e;return\"api \".concat(i,\" call \").concat(t?\"size\":\"times\",\" is over \").concat(t?\"\".concat(r,\" bytes\"):n,\" 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,\"()\")},YO=(e,t)=>t?\"\".concat(TN,\"/\").concat(e,\"/\").concat(t):\"\".concat(TN,\"/\").concat(e,\"/index.html\"),zO=()=>{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(vN);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,n=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:n}}return{}};function qO(e){let{key:t,data:i,link:n,addDocLink:r=!0}=e,o=\"\",s=\"\",a=\"\";iO(KO[t])?o=KO[t](i):rO(KO[t])&&(o=KO[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=zO();n?a=\"\".concat(n.className,\".html#\").concat(n.fnName):l&&l[t]&&(iO(l[t])?a=l[t](i):rO(l[t])&&(a=l[t]));let d=o;return XD()&&(c&&c[t]&&(iO(c[t])?s=c[t](i):rO(c[t])&&(s=c[t])),s&&(d=r?\"\".concat(s,\"\\n请查看文档: \").concat(YO(\"zh-cn\",a),\"\\n\\n\"):\"\".concat(s,\"\\n\\n\"),d+=o)),r&&(d+=\" \\nRefer to: \".concat(YO(\"en\",a),\"\\n\")),d}var QO={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},XO=new Map([[Ub,[\"Firefox\",Fb]],[Gb,[\"Edg\",Wb]],[Lk,[\"Chrome\",xk]],[Uk,[\"Safari\",Bk]],[Qb,[\"TBS\",Xb]],[Zb,[\"XWEB\",$b]],[nk&&Ob,[\"WeChat\",rk]],[ck,[\"QQ(Win)\",lk]],[sk,[\"QQ(Mobile)\",ak]],[ok,[\"QQ(Mobile X5)\",ak]],[dk,[\"QQ(Mac)\",uk]],[hk,[\"QQ(iPad)\",pk]],[Ik,[\"MI\",vk]],[yk,[\"HW\",Rk]],[Ck,[\"Samsung\",bk]],[kk,[\"OPPO\",Nk]],[Dk,[\"VIVO\",Ok]],[Hb,[\"EDGE\",jb]],[Kb,[\"SogouMobile\",Yb]],[zb,[\"Sogou\",qb]]]);function ZO(){let e=XO.get(!0);return{browserName:e?e[0]:\"unknown\",browserVersion:e?e[1]:\"unknown\"}}var $O=function(){return!(Ek||Hb||Gb&&Jb<80||Ub&&Bb<56)},ew=function(){return[\"VideoDecoder\",\"VideoEncoder\",\"AudioEncoder\",\"AudioDecoder\",\"MediaStreamTrackGenerator\"].every((e=>e in window))},tw=function(){if(!navigator.mediaDevices)return nw()||HO.error(KO.NOT_SUPPORTED_MEDIA),!1;let e=[\"getUserMedia\",\"enumerateDevices\"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},iw=!1;function nw(){return\"http:\"===location.protocol&&!Yk&&(iw||HO.error(qO({key:JO.NOT_SUPPORTED_HTTP})),iw=!0,!0)}var rw=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},ow=function(){return ab(this,null,(function*(){if(QO.detail.isH264EncodeSupported||QO.detail.isVp8EncodeSupported)return{isH264EncodeSupported:QO.detail.isH264EncodeSupported,isVp8EncodeSupported:QO.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let n=new RTCPeerConnection,r=document.createElement(LN.CANVAS);r.getContext(\"2d\");let o=r.captureStream(0);return n.addTrack(o.getVideoTracks()[0],o),e=yield n.createOffer(),-1!==e.sdp.toLowerCase().indexOf(\"h264\")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf(\"vp8\")&&(i=!0),n.close(),QO.detail.isH264EncodeSupported=t,QO.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:QO.detail.isH264EncodeSupported,isVp8EncodeSupported:QO.detail.isVp8EncodeSupported}}catch(sD){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},sw=function(){return ab(this,null,(function*(){if(QO.detail.isH264DecodeSupported&&QO.detail.isVp8DecodeSupported)return{isH264DecodeSupported:QO.detail.isH264DecodeSupported,isVp8DecodeSupported:QO.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{let n=new RTCPeerConnection;return e=yield n.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf(\"h264\")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf(\"vp8\")&&(i=!0),n.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch(sD){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},aw=function(){return ab(this,null,(function*(){if(QO.result)return QO;let e=$O(),t=Nw(),i=ew(),n=tw(),{isH264EncodeSupported:r,isVp8EncodeSupported:o}=yield ow(),{isH264DecodeSupported:s,isVp8DecodeSupported:a}=yield sw();return QO.result=e&&t&&n&&(r||o)&&(s||a),QO.detail.isBrowserSupported=e,QO.detail.isWebRTCSupported=t,QO.detail.isWebCodecsSupported=i,QO.detail.isMediaDevicesSupported=n,QO.detail.isScreenShareSupported=lw(),QO.detail.isSmallStreamSupported=fw(),QO.detail.isH264EncodeSupported=r,QO.detail.isVp8EncodeSupported=o,QO.detail.isH264DecodeSupported=s,QO.detail.isVp8DecodeSupported=a,QO.result||HO.error(\"\".concat(navigator.userAgent,\" \").concat(OO(QO.detail,!1))),QO}))},cw=function(){return QO.result},lw=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},dw=(e,t,i)=>{\"http:\"===location.protocol&&!Yk&&(e[t]=()=>{throw new gb({code:mb.INVALID_OPERATION,message:KO.NOT_SUPPORTED_HTTP})})},uw=function(e){return!(\"candidate-pair\"!==e.type||!e.nominated||\"in-progress\"!==e.state&&\"succeeded\"!==e.state)&&!(sO(e.selected)&&!e.selected)};function hw(){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 pw(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function _w(){let e={isSupported:!1},t=[\"AudioContext\",\"webkitAudioContext\",\"mozAudioContext\",\"msAudioContext\"];for(let i=0;i=86,Nw=function(){return[\"RTCPeerConnection\",\"webkitRTCPeerConnection\",\"RTCIceGatherer\"].filter((e=>e in window)).length>0};function Dw(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return nO(window.AudioDecoder)||(e.AudioDecoder=!0),nO(window.AudioEncoder)||(e.AudioEncoder=!0),nO(window.VideoDecoder)||(e.VideoDecoder=!0),nO(window.VideoEncoder)||(e.VideoEncoder=!0),nO(window.ImageDecoder)||(e.ImageDecoder=!0),e}function Ow(){return\"mediaSession\"in navigator&&!nO(navigator.mediaSession.setActionHandler)}function ww(){return!nO(window.WebTransport)}function Pw(){let e={browser:\"\".concat(qk.name,\"/\").concat(qk.version),os:eN(),displayResolution:hw(),isScreenShareSupported:lw(),isWebRTCSupported:Nw(),isGetUserMediaSupported:pw(),isWebAudioSupported:_w(),isWebSocketsSupported:\"WebSocket\"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:Dw(),isMediaSessionSupported:Ow(),isWebTransportSupported:ww()};return navigator.userAgent.includes(\"miniProgram\")&&(e.browser=\"mini/\".concat(e.browser)),e}var Lw=nb(cb(),1),Mw=Symbol(\"instance\"),Vw=Symbol(\"cacheResult\"),xw=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,jw.call(e,this.oldState,new Error(\"action '\".concat(this.action,\"' aborted\")))}toString(){return\"\".concat(this.action,\"ing\")}},Uw=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var Fw=new Map;function Bw(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(n,r,o)=>{let s=i.action||r;if(!i.context){let i=Fw.get(n)||[];Fw.has(n)||Fw.set(n,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let n=this;for(var r=arguments.length,o=new Array(r),c=0;c{var r;return n[Vw]=e,u.aborted||(jw.call(n,t),null===(r=i.success)||void 0===r||r.call(this,n[Vw])),e},p=e=>{let t=e instanceof Error?e.message:String(e);if(jw.call(n,d,e),!i.fail){if(i.ignoreError)return e;throw e}i.fail.call(this,new Uw(n._state,\"action '\".concat(s,\"' failed :\").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return\"object\"==typeof e&&e&&\"then\"in e}(e)?e.then(h).catch(p):h(e)}catch(_){p(_)}}}}var Hw=\"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 jw(e,t){let i=this._state;this._state=e;let n=e.toString();e&&this.emit(n,i),this.emit(Gw.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var Gw=class extends Lw.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=Gw.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let n=i[Mw];n?this.name=n.name+\"-\"+n.count++:i[Mw]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=Fw.get(e)||[],i=new Set,n=[],r=[],o=new Set,s=Object.getPrototypeOf(e);Fw.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;\"string\"==typeof t?n.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{n.push({from:e,to:i,action:o})})):r.push({to:i,action:o})})),n.forEach((e=>{let{from:t,to:n,action:r}=e;o.add(t),o.add(n),o.add(r+\"ing\"),i.add(\"\".concat(t,\" --\\x3e \").concat(r,\"ing : \").concat(r)),i.add(\"\".concat(r,\"ing --\\x3e \").concat(n,\" : \").concat(r,\" 🟢\")),i.add(\"\".concat(r,\"ing --\\x3e \").concat(t,\" : \").concat(r,\" 🔴\"))})),r.forEach((e=>{let{to:t,action:n}=e;i.add(\"\".concat(n,\"ing --\\x3e \").concat(t,\" : \").concat(n,\" 🟢\")),o.forEach((e=>{e!==t&&i.add(\"\".concat(e,\" --\\x3e \").concat(n,\"ing : \").concat(n))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return\"string\"==typeof e?(t=Gw.instances.get(e),t||Gw.instances.set(e,t=new Gw(e,void 0,Object.create(Gw.prototype)))):(t=Gw.instances2.get(e),t||Gw.instances2.set(e,t=new Gw(e.constructor.name,void 0,Object.create(Gw.prototype)))),t}static getState(e){var t;return null===(t=Gw.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Hw(Gw.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){jw.call(this,e)}};Gw.STATECHANGED=\"stateChanged\",Gw.UPDATEAFSM=\"updateAFSM\",Gw.INIT=\"[*]\",Gw.ON=\"on\",Gw.OFF=\"off\",Gw.instances=new Map,Gw.instances2=new WeakMap;var Ww=(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)},Jw=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},Kw=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),Yw=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:MD,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=$C(e===LD?{delay:2e3,count:0,backgroundTask:!0}:e===wD?{delay:1e4,count:0}:e===PD?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),aO(t)&&(i=$C($C({},i),t)),iO(e)&&(t=e,e=MD);let n=$C({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i);return this.taskMap.set(n.taskID,n),this[e](n),n.taskID}static interval(e){return e.intervalID=setInterval((()=>{e.callback(),e.loopCount+=1,this.isBreakLoop(e)}),e.delay)}static intervalInWorker(e){e.delay=(1e3/e.fps).toFixed(2);let t=new Worker(URL.createObjectURL(new Blob([\"\\n let timerID = null;\\n self.onmessage = function (e) {\\n if (e.data === 'start') {\\n timerID = setInterval(() => {\\n self.postMessage('tick');\\n }, \".concat(e.delay,\");\\n } else if (e.data === 'stop') {\\n clearInterval(timerID);\\n }\\n };\\n \")])));t.onmessage=i=>{\"tick\"===i.data&&(e.callback(),e.loopCount+=1,this.isBreakLoop(e)&&t.postMessage(\"stop\"))},e.worker=t,t.postMessage(\"start\")}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=fO(),n=()=>{if(t=fO()-i,t>=e.delay&&(i=fO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=Ww(n,{timeout:e.delay})};return e.ricID=Ww(n,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=fO(),n=()=>document.hidden&&e.backgroundTask?(t=fO()-i,i=fO(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(n,e.delay-Math.floor(t%e.delay))):(t=fO()-i,t>=e.delay&&(i=fO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),this.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(n));if(e.rafID=requestAnimationFrame(n),e.backgroundTask){let t=()=>{if(document.hidden){let t=fO()-i;t>=e.delay?n():e.timeoutID=setTimeout(n,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:n,ricID:r,onVisibilitychange:o,worker:s}=this.taskMap.get(e);return s&&s.terminate(),t&&clearInterval(t),i&&clearTimeout(i),n&&Kw(n),r&&Jw(r),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)}};Yw.taskMap=new Map,Yw.currentTaskID=1;var zw=Yw;LN.SEI_MESSAGE;var qw={LOADED_DATA:LN.LOADEDDATA,MEDIA_TRACK_CHANGED:\"media-track-changed\",PLAYER_STATE_CHANGED:\"player-state-changed\"},Qw=new class{constructor(){ob(this,\"_roomIdMap\",new Map),ob(this,\"_configs\"),\"undefined\"==typeof registerProcessor&&(this._configs={sdkAppId:\"\",userId:\"\",version:rN,env:AN.QCLOUD,browserVersion:qk.name+qk.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:i,userId:n,roomId:r}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=n,this._roomIdMap.set(n,String(r))}logSuccessEvent(e){Yk||!HO.isAbleToUpload||this._configs.env===AN.QCLOUD&&this.uploadEventToKibana(eb($C({},e),{result:\"success\"}))}logFailedEvent(e){if(Yk||!HO.isAbleToUpload)return;let{eventType:t,code:i,error:n,userId:r}=e,o={roomId:this._roomIdMap.get(r||this._configs.userId),userId:r,eventType:t,result:\"failed\",code:i||(null==n?void 0:n.extraCode)||(null==n?void 0:n.code)||mb.UNKNOWN};this._configs.env===AN.QCLOUD&&this.uploadEventToKibana(eb($C({},o),{error:n}))}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:n}=e,r={timestamp:Sb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:rN,log:t};n&&(r.errorInfo=n.message),this.sendRequest(BD(this._configs.sdkAppId,yN.LOG),r)}sendRequest(e,t){HO.isAbleToUpload?PO({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},Xw=\"trtc_autoplay\",Zw=\"\".concat(Xw,\"_mask\"),$w=\"\".concat(Xw,\"_wrapper\"),eP=\"\".concat(Xw,\"_header\"),tP=\"\".concat(Xw,\"_content\"),iP=\"\".concat(Xw,\"_action_wrapper\"),nP=\"\".concat(Xw,\"_question\"),rP=\"\".concat(Xw,\"_collapse\"),oP=\"\".concat(Xw,\"_action_confirm\"),sP=\"\".concat(Xw,\"_detail\"),aP=\"#2473E8\",cP=\"dialog\",lP=\"\".concat(cP,\"-show\"),dP=\"\".concat(cP,\"-1\"),uP=\"\".concat(cP,\"-2\"),hP=!1,pP=()=>!!document.querySelector(\".\".concat($w)),_P=\"\".concat(TN,\"/\").concat(XD()?\"zh-cn\":\"en\",\"/tutorial-21-advanced-auto-play-policy.html\"),mP=\"
\").concat(XD()?\"其他方案?\":\"Any other solution?\",\"\"),fP=\"\".concat(XD()?\"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。\".concat(mP):\"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(mP)),gP=class{constructor(){if(ob(this,\"content\",\"音视频播放被浏览器拦截,请点击“恢复播放”。\"),ob(this,\"_dialogNode\",null),ob(this,\"_bodyPosition\",\"\"),ob(this,\"_showDetail\",!1),ob(this,\"_isCollapseClicked\",!1),ob(this,\"_isQuestionClicked\",!1),XD()||(this.content='Media playback failed. Click the \"Resume\" to resume playback.'),!hP){let e=document.createElement(\"style\");e.innerHTML=\".\".concat(Zw,\"{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(Zw,\" div:not(.\").concat(iP,\"){display:block !important;}.\").concat($w,\"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.\").concat($w,\" a{color:\").concat(aP,\";}.\").concat(eP,\"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.\").concat(tP,\"{margin:8px 0;}.\").concat(iP,\"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.\").concat(rP,\"{margin-right:auto;cursor:pointer}.\").concat(nP,\"{height:100%;line-height:16px;cursor:pointer;}.\").concat(oP,\"{margin-left:8px;color:#fff;background:\").concat(aP,\";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.\").concat(oP,\":hover{opacity:0.9;}.\").concat(rP,\",.\").concat(oP,\",.\").concat(tP,\",.\").concat(nP,\"{font-size:14px;}@media screen and (max-width:750px){.\").concat($w,\"{width:80vw;}}\"),document.head.appendChild(e),hP=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement(\"template\");e.innerHTML='
\").concat(location.host,\"
\").concat(this.content,\"
').concat(fP,\"
\").trim();let t=document.createElement(\"button\");t.className=oP,t.innerText=XD()?\"恢复播放\":\"Resume\",t.onclick=this.onConfirm.bind(this);let i=document.createElement(\"div\");i.className=nP,i.innerHTML='\\n \\n \\n \\n \\n \\n ',i.onclick=this.onQuestionClick.bind(this);let n=document.createElement(\"div\");n.className=rP,n.innerText=\"\".concat(XD()?\"详情 >\":\"Detail >\"),n.onclick=this.onCollapseClick.bind(this);let r=e.content.firstChild,o=r.querySelector(\".\".concat(iP));return o.appendChild(n),o.appendChild(i),o.appendChild(t),r}addDiaLog(){pP()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(\".\".concat($w)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position=\"fixed\",HO.info(\"show autoplay dialog\"),Qw.uploadEvent({log:lP}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){HO.warn(\"confirm clicked, try resume stream\"),xO.emit(FO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(\".\".concat(sP));e.style.visibility=\"\".concat(this._showDetail?\"hidden\":\"visible\"),e.style.height=\"\".concat(this._showDetail?0:\"fit-content\"),this._showDetail=!this._showDetail,this._isCollapseClicked||Qw.uploadEvent({log:dP}),this._isCollapseClicked=!0}onQuestionClick(){window.open(_P,\"_blank\"),this._isQuestionClicked||Qw.uploadEvent({log:uP}),this._isQuestionClicked=!0}},TP={};ib(TP,{create:()=>SP,remove:()=>IP});var EP=new WeakMap;function SP(e,t){EP.has(e)||EP.set(e,[]);let i=EP.get(e),n={add:(e,r)=>(\"addEventListener\"in t?(i.push(t.removeEventListener.bind(t,e,r)),t.addEventListener(e,r)):(i.push(t.off.bind(t,e,r)),t.on(e,r)),n)};return n}function IP(e){let t=EP.get(e);t&&(t.forEach((e=>e())),EP.delete(e))}var vP=class extends Gw{constructor(e,t){super(e.id,\"\".concat(t,\"-player\")),this.kind=t,ob(this,\"id\"),ob(this,\"element\",null),ob(this,\"container\",null),ob(this,\"mediaStream\",new MediaStream),ob(this,\"track\"),ob(this,\"url\"),ob(this,\"attr\"),ob(this,\"muted\"),ob(this,\"_log\"),ob(this,\"_pausedRetryCount\"),ob(this,\"_isElementPlayingFired\",!1),ob(this,\"_interval\"),this.id=e.id,this._log=e.log,this.track=e.track,this.container=e.container,this.muted=e.muted,this._pausedRetryCount=AD,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(qw.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 ab(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(sN){let t=qO({key:JO.PLAY_FAILED,data:{media:this.kind,error:sN}});if(this.track&&!this.track.muted&&this._log.warn(sN),t.includes(\"NotAllowedError\"))throw new gb({code:mb.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(LN.ENDED),this._interval>0&&zw.clearTask(this._interval)}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this.isPlaying?Promise.resolve():Jk?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);return SP(this.element,this.element).add(LN.PLAYING,e).add(LN.ENDED,e).add(LN.PAUSE,e).add(LN.ERROR,e).add(LN.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==TP||TP.create(this.track,this.track).add(LN.ENDED,e).add(LN.MUTE,e).add(LN.UNMUTE,e),this.track.readyState===LN.ENDED&&this.handleTrackEvent({type:LN.ENDED}),this.track.muted&&this.handleTrackEvent({type:LN.MUTE})}}bindAutoPlayEvent(){xO.on(FO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&IP(this.track)}unbindEvents(){this.element&&IP(this.element),this.unbindTrackEvents(),xO.off(FO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){var t;switch(e.type){case LN.PLAYING:this._isElementPlayingFired=!0,this._log.info(\"\".concat(this.kind,\" player is playing\")),this.handlePlaying(LN.PLAYING),this._interval&&(zw.clearTask(this._interval),this._interval=-1);break;case LN.ENDED:this._log.info(\"\".concat(this.kind,\" player is ended\")),this.handleStopped(LN.ENDED);break;case LN.PAUSE:this._log.info(\"\".concat(this.kind,\" player is paused\")),this.handlePaused(LN.PAUSE);let e=this.container&&document.getElementById(this.container.id);e||this._log.warn(\"\".concat(this.kind,\" player has been remove, element ID: \").concat(null==(t=this.container)?void 0:t.id));let i=wk();this._pausedRetryCount>0&&(this.kind===LN.VIDEO&&!pP()||this.kind===LN.AUDIO&&(oO(i)&&i<=70||!e))&&(this._log.info(\"\".concat(this.kind,\" player auto resume when paused\")),this.resume(),this._pausedRetryCount--),Pb&&(this._interval=zw.run(MD,(()=>{this.element&&\"PAUSED\"===this._state&&this.resume()}),{delay:3e3}));break;case LN.ERROR:if(this.element&&this.element.error){let{code:e,message:t}=this.element.error;this._log.error(\"\".concat(this.kind,\" player error observed. code: \").concat(e,\" message: \").concat(t,\" userAgent: \").concat(navigator.userAgent)),Qw.uploadEvent({log:\"stat-\".concat(this.kind,\"-\").concat(cD.PLAYER_ERROR,\"-\").concat(e,\"-\").concat(navigator.userAgent),error:this.element.error})}break;case LN.LOADEDDATA:this.kind===LN.VIDEO&&this.emit(qw.LOADED_DATA)}}handleTrackEvent(e){switch(e.type){case LN.ENDED:this._log.info(\"\".concat(this.kind,\" track is ended\")),this.handleStopped(LN.ENDED);break;case LN.MUTE:this._log.info(\"\".concat(this.kind,\" track is unable to provide media output\")),this.handlePaused(LN.MUTE);break;case LN.UNMUTE:this._log.info(\"\".concat(this.kind,\" track is able to provide media output\")),this._isElementPlayingFired&&this.handlePlaying(LN.UNMUTE)}}handlePlaying(e){this.emit(qw.PLAYER_STATE_CHANGED,{type:this.kind,state:\"PLAYING\",reason:e})}handlePaused(e){this.emit(qw.PLAYER_STATE_CHANGED,{type:this.kind,state:\"PAUSED\",reason:e})}handleStopped(e){this.emit(qw.PLAYER_STATE_CHANGED,{type:this.kind,state:\"STOPPED\",reason:e})}getElement(){return this.element}};rb([Bw([],\"PLAYING\")],vP.prototype,\"handlePlaying\",1),rb([Bw(\"PLAYING\",\"PAUSED\",{ignoreError:!0})],vP.prototype,\"handlePaused\",1),rb([Bw([],\"STOPPED\")],vP.prototype,\"handleStopped\",1);var yP=class extends vP{constructor(e){super(e,LN.VIDEO),ob(this,\"mirror\"),ob(this,\"objectFit\"),nO(e.mirror)||(this.mirror=e.mirror),nO(e.objectFit)||(this.objectFit=e.objectFit)}initializeElement(){var e;let t=document.createElement(LN.VIDEO);if(this.track){let e=new MediaStream;e.addTrack(this.track),t.srcObject=e}t.muted=!0;let i=\"width: 100%; height: 100%; object-fit: \".concat(this.objectFit,\";background-color: black;\");this.mirror&&(i+=\"transform: scaleX(-1);\"),t.setAttribute(\"id\",\"video_\".concat(this.id)),t.setAttribute(\"style\",i),t.setAttribute(\"autoplay\",\"autoplay\"),t.setAttribute(\"playsinline\",\"playsinline\"),null==(e=this.container)||e.appendChild(t),this.element=t,this.bindElementEvents()}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(LN.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(LN.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){super.handleElementEvent(e);let t=e.type;if(this.mirror&&this.element){let e=this.element.style.transform;t===LN.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace(\"scaleX(-1)\",\"\"):t===LN.LEAVE_PICTURE_IN_PICTURE&&!e.includes(\"scaleX\")&&(this.element.style.transform=\"\".concat(e,\" scaleX(-1)\"))}}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}},AP=!1,RP=class{constructor(e){ob(this,\"context_\"),ob(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=!1,this.port.onmessage=t=>{let{data:e}=t;switch(e.name){case\"setIntervalTime\":this.intervalTime=e.intervalTime;break;case\"stop\":this.isStop=!0}}}process(t){let e=t[0];if(this.isStop)return!1;if(e.length>0){let i=e[0],s=0;for(let l=0;l{let i=new window.AudioContext(t),n=++kP,r=()=>{\"suspended\"===i.state?(i.resume(),document.addEventListener(\"click\",r)):\"interrupted\"===i.state?i.resume():document.removeEventListener(\"click\",r)};return document.addEventListener(\"click\",r),i.onstatechange=()=>{HO.info(\"\".concat(e,\"-\").concat(n,\" context state: \").concat(i.state)),r()},i},DP=0,OP=class{constructor(e){ob(this,\"_volume\"),ob(this,\"_log\"),ob(this,\"_track\"),ob(this,\"_stream\"),ob(this,\"_audioCtx\"),ob(this,\"_destination\"),ob(this,\"_streamSource\"),ob(this,\"_scriptProcessorNode\"),ob(this,\"_audioWorkletNode\"),ob(this,\"_interval\");let{track:t,log:i}=e;this._volume=0,this._log=i,this._track=t,CP||(CP=NP(\"volume-meter\")),this._audioCtx=CP,this._destination=this._audioCtx.destination;let n=new MediaStream;n.addTrack(this._track),this._streamSource=this._audioCtx.createMediaStreamSource(n),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._interval=200,xO.on(FO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),_O?(xO.on(FO.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),xO.on(FO.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),this.preload()):this.initScriptProcessor(),DP+=1}preload(){bP?bP.initWorkletSuccess&&this.initAudioWorklet():bP=new RP({context:CP})}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(HL){Qw.logFailedEvent({userId:this._log.userId,eventType:cD.LOAD_WORKLET,error:HL}),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 n=0;n0&&(DP-=1),0===DP&&(null==CP||CP.close(),CP=null,bP=null)}resume(){null==CP||CP.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})}},wP=null,PP=0,LP=class extends vP{constructor(e){super(e,LN.AUDIO),ob(this,\"_volumeMeter\"),ob(this,\"_gainedTrack\",null),ob(this,\"_gainNode\",null),ob(this,\"_destination\",null),ob(this,\"_mediaStreamSource\",null),ob(this,\"_sourceElement\",null),ob(this,\"_outputDeviceId\"),ob(this,\"_volume\",1),ob(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 OP({track:this._gainedTrack||e,log:this._log})}initializeElement(){if((\"15.2\"===jk||\"15.3\"===jk||\"15.4\"===jk)&&this.muted)return void this._log.info(\"audioElement is muted.\");let e=document.createElement(LN.AUDIO);this.track&&(e.srcObject=new MediaStream([this._gainedTrack||this.track])),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 ab(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 sb(LP.prototype,this,\"play\").call(this)}))}stop(){this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),this.destroyGain(),super.stop()}resume(){return ab(this,null,(function*(){yield sb(LP.prototype,this,\"resume\").call(this),this._volumeMeter&&this._volumeMeter.resume()}))}setSinkId(e){return ab(this,null,(function*(){this._outputDeviceId!==e&&(this.element&&(yield this.element.setSinkId(e)),this._outputDeviceId=e)}))}setVolume(e){this._volume=e,this._gainNode?this._gainNode.gain.value=e:e>1?this.createGain(e):this.element&&(this.element.volume=e)}createGain(e){wP||(wP=NP(\"player\")),this._log.info(\"create gainNode \".concat(e));let t=wP.createMediaStreamSource(new MediaStream([this.track])),i=wP.createGain(),n=wP.createMediaStreamDestination();t.connect(i),i.connect(n),i.gain.value=e,this._gainNode=i,this._destination=n,this._mediaStreamSource=t,this._gainedTrack=n.stream.getAudioTracks()[0],PP+=1,this.element&&(IP(this.element),this._sourceElement=this.element,this.element.muted=!0,this.element=null),this.play()}destroyGain(){var e,t,i;!this._gainNode||(this._log.info(\"destroy gainNode\"),null==(e=this._gainNode)||e.disconnect(),null==(t=this._destination)||t.disconnect(),null==(i=this._mediaStreamSource)||i.disconnect(),this._gainNode=null,this._destination=null,this._mediaStreamSource=null,this._sourceElement&&(this._sourceElement.srcObject=null,this._sourceElement=null),this._gainedTrack=null,0===(PP-=1)&&wP&&(this._log.info(\"destroy gain audioContext\"),wP.close(),wP=null))}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()}},MP=class extends Gw{constructor(e){let{userId:t,sdkAppId:i,mediaType:n,room:r,isInitPlayer:o=!0}=e;var s;super(),ob(this,\"id\",jO()),ob(this,\"userId\"),ob(this,\"isRemote\"),ob(this,\"mediaType\"),ob(this,\"room\"),ob(this,\"user\"),ob(this,\"_log\"),ob(this,\"_inputTrack\"),ob(this,\"_outputTrack\"),ob(this,\"isPlayCalled\"),ob(this,\"container\",null),ob(this,\"player\"),ob(this,\"subVideoPlayerMap\"),ob(this,\"playerMuted\",!1),ob(this,\"abortCtrl\"),ob(this,\"audioOutputDeviceId\"),ob(this,\"audioVolume\"),ob(this,\"objectFit\",\"cover\"),ob(this,\"mirror\",!1),ob(this,\"gain\"),ob(this,\"isScreen\",!1),ob(this,\"manager\"),nO(t)||(this.userId=t),this.mediaType=n,this._log=HO.createLogger({id:\"\".concat(this.kind[0],\"t\"),userId:null==(s=r||this.room)?void 0:s.userId,remoteUserId:this instanceof nL?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?\"auxiliary\":\"main\",isLocal:this instanceof nL}),o&&this.initPlayer()}get log(){return this._log||HO}get kind(){return 1===this.mediaType?LN.AUDIO:LN.VIDEO}get muted(){return!(!this.outMediaTrack||this.outMediaTrack.enabled)}get strMediaType(){return 4===this.mediaType?LN.VIDEO:2===this.mediaType?LN.SCREEN:LN.AUDIO}play(e,t){return ab(this,null,(function*(){let i=cO(e)?e[0]:e;if(this.isPlayCalled)return this.log.info(\"play update options: \".concat(JSON.stringify(t))),t&&!nO(t.muted)&&this.setPlayerMute(t.muted),t&&!nO(t.objectFit)&&(this.objectFit=t.objectFit),this.isScreen?this.mirror=!1:t&&!nO(t.mirror)&&(this.mirror=t.mirror),void(this.kind===LN.VIDEO&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),cO(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!nO(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===LN.VIDEO)&&this.setPlayerMute(!0),t&&!nO(t.objectFit)&&(this.objectFit=t.objectFit),this.isRemote||(this.mirror=!0),this.isScreen?this.mirror=!1:t&&!nO(t.mirror)&&(this.mirror=t.mirror),this.kind===LN.VIDEO&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror)),this.isPlayCalled=!0,i&&(this.container=i,this.player.setContainer(i)),xO.emit(FO.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info(\"play with options: \".concat(JSON.stringify(t)));try{this.player.setTrack(this._outputTrack),yield this.player.play(),cO(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(n){throw this.handleAutoPlayFailed(),this.emit(\"error\",n),n}}else this.log.info(\"play has not mediaTrack, abort\")}))}playSubContainer(e,t){return ab(this,null,(function*(){if(!this._outputTrack||this.kind===LN.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,i)=>{var n;e.find((e=>i===e))||(t.stop(),t.setContainer(null),null==(n=this.subVideoPlayerMap)||n.delete(i))}));for(let[n,r]of e.entries()){let e=this.subVideoPlayerMap.get(r);e?t&&(nO(t.mirror)||e.setMirror(t.mirror),nO(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(r,new yP({id:this.userId||this.id,track:this.outMediaTrack,container:r,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log.createChild({id:\"vp-sub\".concat(n+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===LN.AUDIO?this.player=new LP({id:this.userId||this.id,track:this.outMediaTrack,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 yP({id:this.userId||this.id,track:this.outMediaTrack,container:this.container||null,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log}),this.player.on(qw.LOADED_DATA,(()=>{xO.emit(FO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(qw.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))}))),this.player.on(qw.PLAYER_STATE_CHANGED,(e=>{xO.emit(FO.PLAYER_STATE_CHANGED,$C({track:this},e)),this.emit(\"player-state-changed\",e)}))}setAudioOutput(e){return ab(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 ab(this,null,(function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info(\"close\"),this.isPlayCalled&&this.stop()}setMute(e){return!!this.outMediaTrack&&(this.outMediaTrack.enabled=!e,this.emit(e?\"mute\":\"unmute\",this),xO.emit(e?FO.TRACK_MUTED:FO.TRACK_UNMUTED,{track:this}),!0)}setPlayerMute(e){this.playerMuted=e,this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}setInputMediaStreamTrack(e){let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.emit(\"input-media-track-changed\",e||null,t||null),this.manager?this.manager.changeInput(this,t):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug(\"setOutputMediaStreamTrack\",e.label):this.log.info(\"setOutputMediaStreamTrack\",(null==(t=e.getSettings)?void 0:t.call(e).deviceId)||e.label),this._outputTrack=e,e.enabled=!this.muted,this.updatePlayingState(!!e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled)if(e){if(this.player.setTrack(this.outMediaTrack),this.player.isStopped)return this.player.play().catch((()=>this.handleAutoPlayFailed())),void this.log.info(\"playing state updated, play \".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(),void this.log.info(\"playing state updated, stop \".concat(this.kind));this.log.debug(\"updatePlayingState abort \".concat(this.isPlayCalled,\" \").concat(e,\" \").concat(this.player.isStopped))}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new gP;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)}}};rb([Bw([],Gw.INIT)],MP.prototype,\"close\",1);var VP=Object.prototype.hasOwnProperty;var xP=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(ZD(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(VP.call(e,t))return!1;return!0}return!1},UP=nb(cb(),1),FP=e=>t=>t.deviceId===e,BP=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"Input\";ob(this,\"kind\"),ob(this,\"type\"),ob(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(FP(e.deviceId))){let i=\"\".concat(this.kind).concat(this.type,\"Added\");HO.warn(\"\".concat(i,\": \").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(FP(e.deviceId))){let i=\"\".concat(this.kind).concat(this.type,\"Removed\");HO.warn(\"\".concat(i,\": \").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},HP=class extends UP.EventEmitter{constructor(){super(),ob(this,\"audioInputs\",new BP(LN.AUDIO)),ob(this,\"videoInputs\",new BP(LN.VIDEO)),ob(this,\"audioOutputs\",new BP(LN.AUDIO,\"Output\")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener(\"devicechange\",this.update.bind(this)),\"ondevicechange\"in navigator.mediaDevices||zw.run(LD,(()=>{this.update()}),{delay:1e4}))}init(){GP().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return ab(this,null,(function*(){let e=yield GP();return this.audioInputs.update(e,this),this.videoInputs.update(e,this),this.audioOutputs.update(e,this),this}))}},jP=dN||lN?null:new HP;function GP(){return ab(this,null,(function*(){return nw()||!tw()?[]:(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&&YP.add(\"\".concat(e.deviceId,\"_\").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}))}function WP(){return jP.update().then((e=>e.audioInputs.devices))}function JP(){return jP.update().then((e=>e.videoInputs.devices))}function KP(){return ab(this,null,(function*(){return jP.update().then((e=>e.audioOutputs.devices))}))}var YP=new Set;function zP(e,t){return ab(this,null,(function*(){let i=(yield WP()).find((e=>e.deviceId===RD));return(null==i?void 0:i.groupId)===e&&i.label===t}))}var qP=MO({retryFunction:function(e){return ab(this,null,(function*(){let t=function(e){return{audio:XP(e),video:ZP(e)}}(e);HO.info(\"getUserMedia with constraints: \".concat(JSON.stringify(t)));let i=[],n=[],r=[\"label\",\"deviceId\"];t.audio&&(i=yield WP(),HO.info(\"microphones: \".concat(DO(i,{keysToInclude:r})))),t.video&&(n=yield JP(),HO.info(\"cameras: \".concat(DO(n,{keysToInclude:r}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return bw&&e.getTracks().forEach((e=>{HO.info(\"\".concat(e.kind,\" capabilities: \").concat(DO(e.getCapabilities(),{keysToInclude:VD})))})),e}catch(o){if(\"NotFoundError\"===o.name){if(e.video&&n&&0===n.length)throw new gb({code:mb.DEVICE_NOT_FOUND,message:qO({key:JO.CAMERA_NOT_FOUND})});if(e.audio&&i&&0===i.length)throw new gb({code:mb.DEVICE_NOT_FOUND,message:qO({key:JO.MICROPHONE_NOT_FOUND})})}throw new gb({code:mb.INITIALIZE_FAILED,name:o.name,message:o.message,constraint:o.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:n,retryFuncArgs:r,retryCount:o}=e;\"NotReadableError\"===t.name?(r[0].video&&(r[0].maxResolution=!1,r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)),2===o&&(r[0].useTrueAsConstraint=!0),i()):n(t),r[0].microphoneId&&QP(r[0].microphoneId,!1),r[0].cameraId&&QP(r[0].cameraId,!0)},onRetrying:e=>{HO.warn(\"getUserMedia NotReadableError observed, retrying [\".concat(e,\"/3]\"))},onRetryFailed:e=>{Qw.logFailedEvent({eventType:cD.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{Qw.logSuccessEvent({eventType:cD.GET_USER_MEDIA_RETRY}),Qw.uploadEvent({log:\"stat-\".concat(cD.GET_USER_MEDIA_RETRY,\"-success-\").concat(e)})}});function QP(e,t){return ab(this,null,(function*(){let i=(t?yield JP():yield WP()).find((t=>t.deviceId===e));i&&iO(i.getCapabilities)&&HO.warn(DO(i.getCapabilities(),{keysToInclude:VD}))}))}function XP(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};return xP(e.microphoneId)||(t.deviceId=e.useExact?{exact:e.microphoneId}:e.microphoneId),oO(e.channelCount)&&e.channelCount>1&&(t.channelCount=e.channelCount),sO(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),sO(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),sO(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!xP(t)||t}function ZP(e){if(!e.video)return!1;if(e.useTrueAsConstraint)return!0;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&&!Ub&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!Ub&&(i.height.max=e.height)),Ub&&mk&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!xP(i)||i}var $P=qP;function eL(e){return iL(((t,i)=>function(){for(var i=arguments.length,n=new Array(i),r=0;rfunction(){for(var i=arguments.length,n=new Array(i),r=0;r1&&void 0!==arguments[1])||arguments[1]}),ob(this,\"isRemote\",!1),ob(this,\"deviceId\"),ob(this,\"groupId\",\"\"),ob(this,\"label\",\"\"),ob(this,\"_isRecapturing\",!1),ob(this,\"_lastRecaptureTime\",0),ob(this,\"_onMuteTimeoutId\",-1),ob(this,\"profile\"),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}installTrackEvent(e){SP(e,e).add(LN.MUTE,this.onTrackMuted).add(LN.UNMUTE,this.onTrackUnmuted).add(LN.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===LN.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){IP(e)}setStateToCapture(){}capture(e){return ab(this,null,(function*(){try{let t;xO.emit(FO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(t=new MediaStream,t.addTrack(e.customSource)):t=yield $P(e);let i=t.getTracks()[0];return yield this.setInputMediaStreamTrack(i),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),xO.emit(FO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this}),t}catch(sD){throw xO.emit(FO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:sD}),this.log.error(\"getUserMedia error observed \".concat(sD)),sD}}))}setInputMediaStreamTrack(e){this.state===Gw.INIT&&this.setStateToCapture(),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack);let t=super.setInputMediaStreamTrack(e);return this.installTrackEvent(e),t}publish(e,t){return this.room=e,this.emit(\"4\",{mediaType:this.strMediaType,state:\"starting\",prevState:\"stopped\"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),xO.emit(FO.LOCAL_TRACK_PUBLISHED,{track:this}),t}unpublish(){this.room&&this.room.localTracks.delete(this),xO.emit(FO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return ab(this,null,(function*(){if(this.mediaTrack&&Cw){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return ab(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:n,oldLabel:r,kind:o}=e;return function*(){return t===i&&(o!==LN.AUDIO||t!==RD||(yield zP(n,r)))}()}))}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=i,t&&(this.groupId=t),GP().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===LN.AUDIO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes(\"mic\")||t.includes(\"麦克风\"))return!0;let i=\"\".concat(((null==e?void 0:e.getSettings())||{}).deviceId,\"_\").concat(LN.AUDIO_INPUT);return!!YP.has(i)}(this.mediaTrack)||this.kind===LN.VIDEO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes(\"camera\")||t.includes(\"webcam\"))return!0;let i=\"\".concat(((null==e?void 0:e.getSettings())||{}).deviceId,\"_\").concat(LN.VIDEO_INPUT);return!!YP.has(i)}(this.mediaTrack)||this._isRecapturing||e&&mk&&Uk)}onTrackMuted(){if(this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTimethis.onTrackMuted()),OD);this._onMuteTimeoutId=setTimeout((()=>ab(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 ab(this,null,(function*(){if(this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTimethis.onTrackEnded()),OD);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return ab(this,null,(function*(){var t;if(this._isRecapturing||!this._inputTrack)return;let i;return this.log.warn(\"recapture trying\"),null==(t=this._inputTrack)||t.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now(),(\"audio\"===this.kind?yield WP():yield JP()).find((t=>t.deviceId===e))&&(i=e),this.capture({deviceId:i,useExact:!0}).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 ab(this,null,(function*(){let{deviceId:e}=this;if(e){let t=(rL.get(e)||0)+1;if(rL.set(e,t),t>=3){let i=\"video\"===this.kind?(yield JP()).find((e=>!rL.has(e.deviceId))):(yield WP()).find((e=>!rL.has(e.deviceId)));i&&(this.log.warn(\"\".concat(e,\" capture fail \").concat(t,\" times, change new \").concat(i.deviceId)),e=i.deviceId)}}return e}))}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),null==(e=this.manager)||e.removeInput(this)}};rb([Bw(Gw.INIT,\"capture\",{ignoreError:!0})],nL.prototype,\"setStateToCapture\",1),rb([Bw(\"capture\",\"publish\",{ignoreError:!0,success(){this.room.localTracks.add(this),this.emit(\"4\",{mediaType:this.strMediaType,state:\"started\",prevState:\"starting\"})},fail(e){let t=\"error\",i=e.cause;i.message.includes(\"timeout\")?t=\"timeout\":i.code===mb.API_CALL_ABORTED&&(t=\"api-call\"),this.emit(\"4\",{mediaType:this.strMediaType,state:\"stopped\",prevState:\"starting\",reason:t,error:i})}})],nL.prototype,\"publish\",1),rb([iL((e=>function(){return ab(this,null,(function*(){let t=\"publish\"===this.state?\"started\":\"starting\";e.call(this),this.emit(\"4\",{mediaType:this.strMediaType,state:\"stopped\",prevState:t,reason:\"api-call\"}),2===this.mediaType&&(this.mediaType=4)}))})),Bw([],\"capture\")],nL.prototype,\"unpublish\",1);var rL=new Map;xO.on(FO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&rL.delete(e.track.deviceId)}));var oL=class extends nL{constructor(e){super(1),ob(this,\"mediaType\",1),ob(this,\"volume\",0),ob(this,\"captureVolume\",1),ob(this,\"profile\",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),ob(this,\"playerMuted\",!0),this.manager=e}getAudioLevel(){return this.volume||super.getAudioLevel()}capture(){let{deviceId:e,customSource:t,useExact:i=!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:i,customSource:t})}switchDevice(e){return ab(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==RD)return;if(yield zP(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)),xO.emit(FO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info(\"switch microphone success\")}catch(sD){throw this.log.error(\"switch microphone failed \".concat(sD)),this.deviceId&&this.recapture(this.deviceId),sD}}}))}listenDeviceChange(){jP&&!jP.listeners(\"audioInputRemoved\").includes(this.handleMicrophoneRemoved)&&jP.on(\"audioInputRemoved\",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return ab(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn(\"current microphone is lost: \".concat(JSON.stringify(e)));let t=yield WP();t[0]?this.recapture(t[0].deviceId):jP.on(\"audioInputAdded\",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn(\"microphone added: \".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return ab(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:n,autoGainControl:r}=e;return function*(){let e=!1;!nO(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!nO(n)&&n!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=n,e=!0),!nO(r)&&r!==t.profile.autoGainControl&&(t.profile.autoGainControl=r,e=!0),e&&t.deviceId&&(yield t.recapture(t.deviceId))}()}))}setCaptureVolume(e){var t;let i=e/100;i!==this.captureVolume&&(null==(t=this.manager)||t.setCaptureVolume(i),this.captureVolume=i)}close(){jP.off(\"audioInputAdded\",this.handleMicrophoneAdded,this),jP.off(\"audioInputRemoved\",this.handleMicrophoneRemoved,this),super.close()}},sL=class extends nL{constructor(e){super(4),ob(this,\"mediaType\",4),ob(this,\"profile\",{width:640,height:480,frameRate:15,bitrate:500}),ob(this,\"states\",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0}),ob(this,\"small\"),ob(this,\"facingMode\"),ob(this,\"isNeedToSetBandwidth\"),this.manager=e;let t=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&\"publish\"===this.state&&this.room.sendAbilityStatus({\"2k4k\":1}):(this.log.warn(\"Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386\"),this.setProfile(eb($C({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on(\"input-media-track-changed\",t),this.on(\"publish\",t)}capture(){let{deviceId:e,facingMode:t,useExact:i=!1,customSource:n}=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:n})}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),null==(t=this.room)?void 0:t.replaceTrack(this)}setProfile(e){!e||(e.bitrate&&(this.isNeedToSetBandwidth=e.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(e):(this.log.warn(\"Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386\"),super.setProfile(eb($C({},this.profile),{width:1920,height:1080}))))}applyProfile(){var e;if(!this.mediaTrack)return;let t=this.settings;return t.height!==this.profile.height||t.width!==this.profile.width||t.frameRate!==this.profile.frameRate?null==(e=this.mediaTrack)?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then((()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&\"publish\"===this.state&&this.room.sendAbilityStatus({\"2k4k\":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:LN.VIDEO,videoType:LN.BIG})})):void 0}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return Cw&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}isAllowed2k4k(e){var t;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||1===(null==(t=this.room.scheduleResult.trtcAutoConf)?void 0:t[\"2k4k\"])}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return ab(this,null,(function*(){let t=e;try{if(!this.isNeedToSwitchDevice(t))return;(t===LN.FACING_MODE_USER||t===LN.FACING_MODE_ENVIRONMENT)&&(this.facingMode=e,t=void 0),this.mediaTrack.stop(),yield this.capture({deviceId:t,useExact:!0}),xO.emit(FO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info(\"switch camera success\")}catch(aN){throw this.log.error(\"switch camera failed \".concat(aN)),this.deviceId&&this.recapture(this.deviceId),aN}}))}listenDeviceChange(){jP&&!jP.listeners(\"audioInputRemoved\").includes(this.handleCameraRemoved)&&jP.on(\"videoInputRemoved\",this.handleCameraRemoved,this)}handleCameraRemoved(e){return ab(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn(\"current camera is lost: \".concat(JSON.stringify(e)));let t=yield JP();t[0]?this.recapture(t[0].deviceId):jP.on(\"videoInputAdded\",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return ab(this,null,(function*(){this.log.warn(\"camera added: \".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}close(){jP.off(\"videoInputAdded\",this.handleCameraAdded,this),jP.off(\"videoInputRemoved\",this.handleCameraRemoved,this),super.close()}};var aL=function(e){return ab(this,null,(function*(){let t=null,i=function(e){let t={systemAudio:\"include\",selfBrowserSurface:\"include\",surfaceSwitching:\"include\"},i={width:Uk?{max:e.width}:{ideal:e.width,max:e.width},height:Uk?{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:n=!1,autoGainControl:r=!1}=e;t.audio={echoCancellation:i,noiseSuppression:n,autoGainControl:r,sampleRate:48e3}}return t}(e);HO.info(\"getDisplayMedia with constraints: \".concat(JSON.stringify(i)));let n=yield navigator.mediaDevices.getDisplayMedia(i);if(e.systemAudio&&0===n.getAudioTracks().length&&(Lk&&Vk<74||Uk||Ub)&&HO.warn(\"Your browser not support capture system audio\"),e.frameRate&&n.getVideoTracks()[0]&&n.getVideoTracks()[0].applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height}).catch((e=>{HO.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 nO(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);HO.info(\"getUserMedia with constraints: \".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),n.addTrack(t.getAudioTracks()[0])}return n}))},cL=class extends sL{constructor(e){super(e),ob(this,\"profile\",{width:1920,height:1080,frameRate:5,bitrate:1600}),ob(this,\"objectFit\",\"contain\"),ob(this,\"isScreen\",!0),this._log.id=\"s-\".concat(this._log.id)}capture(){return ab(this,arguments,(function(){var e=this;let{systemAudio:t=!1,autoGainControl:i,echoCancellation:n,noiseSuppression:r,audioTrack:o,videoTrack:s}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){try{let a;return s||o?(a=new MediaStream,s&&a.addTrack(s),o&&a.addTrack(o)):a=yield aL({audio:!1,systemAudio:t,width:e.profile.width,height:e.profile.height,frameRate:e.profile.frameRate,autoGainControl:i,echoCancellation:n,noiseSuppression:r}),yield e.setInputMediaStreamTrack(a.getVideoTracks()[0]),a}catch(a){throw e.log.error(\"getDisplayMedia error observed \".concat(a)),a instanceof gb?a:new gb({code:mb.INITIALIZE_FAILED,name:a.name,message:a.message})}}()}))}switchDevice(e){return ab(this,null,(function*(){throw new Error(\"Method not implemented.\")}))}},lL=class extends oL{constructor(e){super(e),this._log.id=\"s-\".concat(this._log.id)}},dL=class extends oL{constructor(e){super(e),ob(this,\"_inputs\",new Map),ob(this,\"_destination\"),ob(this,\"audioContext\",NP(\"audio-mixer\")),this._log.id=\"m-\".concat(this._log.id),\"running\"!==this.audioContext.state&&this._log.warn(\"audio mixer context state: \".concat(this.audioContext.state)),this._destination=this.audioContext.createMediaStreamDestination(),this._destination.channelCount=1}setInputMediaStreamTrack(e){this._inputTrack=e;let t=this.audioContext.createMediaStreamSource(new MediaStream([e]));this._inputs.set(e,{sourceNode:t}),t.connect(this._destination),this._outputTrack||(this._outputTrack=this._destination.stream.getAudioTracks()[0],this.setStateToCapture())}setTrackCaptureVolume(e,t){if(!this._inputs.has(e)||!this._destination)return;let i=this._inputs.get(e),{sourceNode:n}=i;i.gainNode||(this._log.info(\"create GainNode\"),i.gainNode=this.audioContext.createGain()),i.gainNode.gain.value=t,n.disconnect(),n.connect(i.gainNode).connect(this._destination)}publish(e,t){return this.room=e,t}unpublish(){delete this.room}replaceTrack(e,t){var i;!this.hasMix||(t&&(null==(i=this._inputs.get(t))||i.sourceNode.disconnect(),this._inputs.delete(t)),this.setInputMediaStreamTrack(e.outMediaTrack))}removeTrack(e){var t;null==(t=this._inputs.get(e))||t.sourceNode.disconnect(),this._inputs.delete(e),0===this._inputs.size&&(delete this._outputTrack,this.unpublish())}close(){this.stop(),this.audioContext.close()}get hasMix(){return!!this._outputTrack}set channelCount(e){this._destination.channelCount=e}};rb([Bw(\"capture\",\"publish\",{ignoreError:!0})],dL.prototype,\"publish\",1),rb([Bw([],\"capture\")],dL.prototype,\"unpublish\",1);var uL=class extends nL{constructor(e,t){super(1),ob(this,\"musicId\"),ob(this,\"mediaType\",1),ob(this,\"volume\",0),ob(this,\"profile\",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),ob(this,\"playerMuted\",!1),ob(this,\"audio\"),ob(this,\"_audioContext\"),ob(this,\"_destination\"),ob(this,\"_source\",null),this.manager=e,this.initAudioContext(),this._destination=this._audioContext.createMediaStreamDestination(),this._destination.channelCount=1,this.audio=document.createElement(\"audio\"),this.audio.src=t.url,this.audio.crossOrigin=\"anonymous\",sO(t.loop)&&this.loop(t.loop),oO(t.volume)&&this.setVolume(t.volume),t.id&&(this.musicId=t.id),this._source=this._audioContext.createMediaElementSource(this.audio),this._source.connect(this._destination),this.setInputMediaStreamTrack(this._destination.stream.getAudioTracks()[0]),this.installPlayerEvent()}play(){return ab(this,null,(function*(){try{yield this.audio.play(),yield sb(uL.prototype,this,\"play\").call(this,null,{muted:!1}),this._log.info(\"music \".concat(this.musicId,\" play success\"))}catch(sN){this._log.error(\"music \".concat(this.musicId,\" play error\"),sN)}}))}installPlayerEvent(){this.audio.addEventListener(\"error\",this.handleAudioError.bind(this))}uninstallPlayerEvent(){this.audio.removeEventListener(\"error\",this.handleAudioError.bind(this))}handleAudioError(e){this._log.warn(\"local music \".concat(this.musicId,\" audio error\"),e)}initAudioContext(){this._audioContext=NP(\"music\"),\"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.uninstallPlayerEvent(),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}seek(e){e<0&&e>this.duration()?this._log.warn(\"Time beyond song duration.\"):this.audio.currentTime=e}getPosition(){return this.audio.currentTime||0}setVolume(e){e>1&&e<0?this.log.warn(\"volume is out of range\"):this.audio.volume=e}getVolume(){return this.audio.volume||0}setPlayBackRate(e){e>8&&e<0?this.log.warn(\"rate is out of range\"):this.audio.playbackRate=e}getPlayBackRate(){return this.audio.playbackRate||0}duration(){return this.audio.duration||0}loop(e){return this.audio&&sO(e)&&(this.audio.loop=e),this.audio.loop||!1}setOperation(e){\"pause\"===e&&this.audio.pause(),\"resume\"===e&&(this.audio.pause(),this.audio.play()),\"stop\"===e&&(this.audio.pause(),this.seek(0))}listenDeviceChange(){}},hL=\"input\",pL=\"output\";var _L=e=>(e=Number(e))>0&&e<14e8;function mL(e){return ab(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:n,timestamp:r}=e;return function*(){let e=\"https://\".concat(function(e){let t;return t=_L(e)?\"intl-schedule.rtc.qq.com\":\"schedule.rtc.qq.com\",t}(t),\"/api/v1/audioAiAuth?sdkAppId=\").concat(t,\"&userId=\").concat(i,\"&userSig=\").concat(n,\"×tamp=\").concat(r),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if(\"1\"===l)return{auth:!0,sign:c,status:l,message:a};let d=\"Init RTCAIDenoiser failed.\",u=\"\";switch(s){case 1:u=\"Please check your params.\";break;case 2:u=\"You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247\";break;case 3:u=\"Server is invalid. Please contact our engineer. \";break;case 4:u=\"Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247\";break;case 5:u=\"Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247\";break;case 6:u=\"Your version is not supported.\"}return{auth:!1,status:l,message:a?\"\".concat(d,\" Reason: \").concat(a,\". \").concat(u):\"\".concat(d,\", \").concat(u)}}()}))}var fL=nb(cb(),1);function gL(e,t){t=t||{};let i,n=e.numberOfChannels,{sampleRate:r}=e,o=t.float32?3:1,s=3===o?32:16;return i=2===n?function(e,t){let i=e.length+t.length,n=new Float32Array(i),r=0,o=0;for(;r{let{type:t,data:i}=e.data;if(\"ondump\"===t&&this.isDumping_){let{inputPCM:e,outputPCM:t}=i;this.dump_.onDump(e,hL),this.dump_.onDump(t,pL)}\"dumped\"===t&&this.dumped()},this.dump_=new EL(this.audioContext_)}dumped(){this.isDumping_=!1;let e=this.dump_.getBlob(hL),t=this.dump_.getBlob(pL);this.emitter_.emit(\"ondumpend\",{blob:e,name:hL}),this.emitter_.emit(\"ondumpend\",{blob:t,name:pL}),this.dumpedWAV(e,hL),this.dumpedWAV(t,pL),this.dump_.reset()}dumpedWAV(e,t){let i=window.URL.createObjectURL(e),n=document.createElement(\"a\");n.href=i,n.download=\"\".concat(t,\"-\").concat(Date.now(),\".wav\"),n.click(),window.URL.revokeObjectURL(i),n.href=\"\"}process(e){return ab(this,null,(function*(){if(this.audioTrack_=e,!this.audioTrack_)throw new Error(\"RTCAIDenoiser: cannot process without audioTrack.\");let t=new MediaStream;t.addTrack(this.audioTrack_),this.source_=this.audioContext_.createMediaStreamSource(t),yield this.source_.connect(this.workletNode_),this.trackConstraint_=this.audioTrack_.getConstraints(),this.trackConstraint_.noiseSuppression=!1,yield this.audioTrack_.applyConstraints(this.trackConstraint_);let i=this.destination_.stream;return this.denoiserTrack_=i.getAudioTracks()[0],this.log_.info(\"RTCAIDenoiser: denoiser process track ID: \".concat(e.id,\" success.\")),this.denoiserTrack_}))}updateTrack(e){return ab(this,null,(function*(){var t;let i=new MediaStream;yield i.addTrack(e);let n=this.audioContext_.createMediaStreamSource(i);this.source_.disconnect(),n.connect(this.workletNode_),null==(t=this.audioTrack_)||t.stop(),this.audioTrack_=e,this.source_=n,this.log_.info(\"RTCAIDenoiser: updateTrack success.\")}))}disable(){return ab(this,null,(function*(){var e,t;return this.enableDenoise_=!1,null==(e=this.workletNode_)||e.port.postMessage({type:\"disable\"}),this.trackConstraint_.noiseSuppression=!0,yield null==(t=this.audioTrack_)?void 0:t.applyConstraints(this.trackConstraint_),this.log_.info(\"RTCAIDenoiser: disable ai denoiser.\"),this.enableDenoise_}))}enable(){return ab(this,null,(function*(){var e,t;return this.enableDenoise_=!0,null==(e=this.workletNode_)||e.port.postMessage({type:\"enable\"}),this.trackConstraint_.noiseSuppression=!1,yield null==(t=this.audioTrack_)?void 0:t.applyConstraints(this.trackConstraint_),this.log_.info(\"RTCAIDenoiser: enable ai denoiser.\"),this.enableDenoise_}))}startDump(){return this.isDumping_?(this.log_.info(\"RTCAIDenoiser: data is currently being dumped.\"),!1):(this.workletNode_.port.postMessage({type:\"startDump\"}),this.dump_?this.dump_.reset():this.dump_=new EL(this.audioContext_),this.isDumping_=!0,this.log_.info(\"RTCAIDenoiser: start dump data.\"),!0)}stopDump(){!this.isDumping_||(this.workletNode_.port.postMessage({type:\"stopDump\"}),this.isDumping_=!1,this.log_.info(\"RTCAIDenoiser: stop dump data.\"))}getAudioTrack(){return this.audioTrack_}getDenoiserTrack(){return this.destination_.stream.getAudioTracks()[0]}get enabled(){return this.enableDenoise_}destroy(){var e,t,i,n,r,o;this.log_.info(\"RTCAIDenoiser: destroy processor.\"),null==(e=this.audioTrack_)||e.stop(),null==(t=this.workletNode_)||t.port.postMessage({type:\"destroy\"}),this.workletNode_.port.onmessage=null,null==(i=this.source_)||i.disconnect(),null==(n=this.destination_)||n.disconnect(),null==(r=this.workletNode_)||r.disconnect(),null==(o=this.dump_)||o.destroy(),this.emitter_.removeAllListeners()}on(e,t,i){this.emitter_.on(e,t,i)}off(e,t,i){\"*\"===e?this.emitter_.removeAllListeners():this.emitter_.off(e,t,i)}},IL=class{constructor(e){let{assetsPath:t,log:i,audioContext:n}=e;this.isLoaded_=!1,this.audioContext_=n,this.log_=i,this.assetsPath_=t}createProcessor(e){return ab(this,null,(function*(){let t=String(Date.now()).slice(0,-3),{auth:i,sign:n,status:r,message:o}=yield mL(eb($C({},e),{timestamp:t}));if(!i)throw this.log_.info(\"RTCAIDenoiser: \".concat(e.userId,\" auth result: \").concat(i,\". Message: \").concat(o)),new Error(o);try{yield this.load()}catch(c){throw new Error(\"Init wasm failed, please check your assetsPath.\")}let s=yield this.initWorklet(),a=new SL(eb($C({},e),{audioContext:this.audioContext_,timestamp:t,sign:n,status:r,worklet:s,logger:this.log_}));return this.log_.info(\"RTCAIDenoiser: \".concat(e.userId,\" create denoiser processor success.\")),a}))}load(){return ab(this,null,(function*(){if(!this.isLoaded_)try{yield this.audioContext_.audioWorklet.addModule(\"\".concat(this.assetsPath_,\"/denoiser-wasm.js\")),this.isLoaded_=!0}catch(HL){throw this.log_.error(\"Init assets from \".concat(this.assetsPath_,\" failed! Reason: \").concat(HL)),HL}}))}initWorklet(){return ab(this,null,(function*(){try{return new AudioWorkletNode(this.audioContext_,\"trtc-denoiser-processor\",{numberOfInputs:1,numberOfOutputs:1})}catch(HL){return yield this.load(),new AudioWorkletNode(this.audioContext_,\"trtc-denoiser-processor\",{numberOfInputs:1,numberOfOutputs:1})}}))}destroy(){var e;null==(e=this.audioContext_)||e.close()}isSupported(){return\"AudioWorklet\"in window&&\"WebAssembly\"in window}},vL=class{constructor(e){let{room:t}=e;ob(this,\"_localAudioTrack\",null),ob(this,\"_localScreenAudioTrack\",null),ob(this,\"localMixAudioTrack\"),ob(this,\"isDenoiserInit\",!1),ob(this,\"isDenoiserEnabled\",!1),ob(this,\"isDenoiserProcessed\",!1),ob(this,\"mixedMusicMap\",new Map),ob(this,\"cacheMusicMap\",new Map),ob(this,\"_log\"),ob(this,\"denoiserTrack\",null),ob(this,\"denoiser\",null),ob(this,\"denoiserProcessor\"),ob(this,\"initProcessorOptions\"),ob(this,\"denoiserContext\"),this._log=HO.createLogger({id:\"am\",userId:t.userId,sdkAppId:t.sdkAppId})}get mixedAudioTrack(){return this.localMixAudioTrack?this.localMixAudioTrack.outMediaTrack:null}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}changeInput(e,t){var i,n,r;return e instanceof lL?(this._localScreenAudioTrack=e,void(e._outputTrack=e.mediaTrack)):e instanceof uL?(e._outputTrack=e.mediaTrack,void(null==(i=this.localMixAudioTrack)||i.replaceTrack(e,t))):e instanceof oL?(this._localAudioTrack=e,this.isDenoiserProcessed&&(null==(n=this.denoiserProcessor)||n.updateTrack(e.mediaTrack)),e.setOutputMediaStreamTrack(this.isDenoiserProcessed?this.denoiserTrack:e.mediaTrack),void(null==(r=this.localMixAudioTrack)||r.replaceTrack(e,t))):e instanceof RL?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}removeInput(e){if(e instanceof oL)return this.removeAudioTrack(e)}addMusicSource(e){return ab(this,null,(function*(){this._log.info(\"add music source, id: \".concat(e.id,\" url: \").concat(e.url));let t,{id:i,url:n,loop:r,volume:o}=e;if(!this.mixedMusicMap.has(i))return t=this.cacheMusicMap.has(i)?this.cacheMusicMap.get(i):new uL(this,e),t.play(),this._log.info(\"start mix audio \".concat(i,\" success.\")),this.mixedMusicMap.set(i,t),this.cacheMusicMap.set(i,t),t}))}updateMusicSource(e){return ab(this,null,(function*(){let{id:t,volume:i,loop:n,operation:r,seekFrom:o}=e;if(this._log.info(\"update music source, \".concat(JSON.stringify(e))),this.mixedMusicMap.has(t)){let e=this.mixedMusicMap.get(t);nO(i)||e.setVolume(i),nO(n)||e.loop(n),nO(r)||e.setOperation(r),nO(o)||e.seek(o)}}))}addAudioTrack(e){return ab(this,null,(function*(){var t;if(this.localMixAudioTrack||(this.localMixAudioTrack=new dL(this)),this._log.info(\"start add audioTrack, userId: \".concat(e.userId)),e===this._localAudioTrack){if(Cw){let i=yield null==(t=e.mediaTrack)?void 0:t.getSettings();this.localMixAudioTrack.channelCount=(null==i?void 0:i.channelCount)||1}this.mixedMusicMap.forEach((e=>{var t;null==(t=this.localMixAudioTrack)||t.setInputMediaStreamTrack(e.outMediaTrack)}))}this.localMixAudioTrack.setInputMediaStreamTrack(e.outMediaTrack),this._localAudioTrack&&1!==this._localAudioTrack.captureVolume&&this.setCaptureVolume(this._localAudioTrack.captureVolume)}))}removeAudioTrack(e){!this.localMixAudioTrack||(e===this._localAudioTrack&&this.mixedMusicMap.forEach((e=>{this.localMixAudioTrack.removeTrack(e.outMediaTrack)})),this.localMixAudioTrack.removeTrack(e.outMediaTrack))}removeMusicSource(e){let{id:t}=e;if(this.localMixAudioTrack){if(this.mixedMusicMap.has(t)){this._log.info(\"remove music source, music id: \".concat(t));let e=this.mixedMusicMap.get(t);e.stop(),this.localMixAudioTrack.removeTrack(e.outMediaTrack),this.mixedMusicMap.delete(t)}\"*\"===t&&this.destroyAllMusic()}}destroyAllMusic(){this._log.info(\"destroy all music source.\"),this.mixedMusicMap.forEach(((e,t)=>{this.removeMusicSource({id:t})}))}destroyAllCache(){this._log.info(\"destroy all music cache.\"),this.cacheMusicMap.forEach((e=>e.stop()))}initDenoiser(e){return ab(this,null,(function*(){let{assetsPath:t,sdkAppId:i,userId:n,userSig:r}=e;try{(!this.denoiserContext||\"closed\"===this.denoiserContext.state)&&(this.denoiserContext=NP(\"denoiser\")),this.denoiser||(this.denoiser=new IL({assetsPath:t,log:this._log,audioContext:this.denoiserContext})),this.denoiserProcessor||(this.denoiserProcessor=yield this.denoiser.createProcessor({sdkAppId:i,userId:n,userSig:r})),this.isDenoiserInit=!0,this.initProcessorOptions=e}catch(cN){throw cN}}))}enableDenoiser(e){return ab(this,null,(function*(){var e,t,i;if(this.isDenoiserEnabled=!0,!this.hasAudioTrack){let e=\"enableDenoiser failed, there is no audio\";throw this._log.error(e),new Error(e)}if(this.isDenoiserProcessed)null==(i=this.denoiserProcessor)||i.enable();else{let i=null==(e=this._localAudioTrack)?void 0:e.mediaTrack;if(!i)return;this.denoiserProcessor||(yield this.initDenoiser(this.initProcessorOptions)),this.denoiserTrack=yield this.denoiserProcessor.process(i),this.isDenoiserProcessed=!0,this._localAudioTrack._outputTrack=this.denoiserTrack,null==(t=this.localMixAudioTrack)||t.replaceTrack(this._localAudioTrack,i)}}))}disableDenoiser(){return ab(this,null,(function*(){var e;this.isDenoiserEnabled&&(null==(e=this.denoiserProcessor)||e.disable(),this.isDenoiserEnabled=!1)}))}setCaptureVolume(e){var t;this.localMixAudioTrack&&this._localAudioTrack&&this._localAudioTrack.mediaTrack&&(null==(t=this.localMixAudioTrack)||t.setTrackCaptureVolume(this._localAudioTrack.mediaTrack,e))}destroyDenoiserProcessor(){var e;this.denoiserProcessor&&(this.denoiserProcessor.destroy(),delete this.denoiserProcessor,this.isDenoiserInit=!1,this.isDenoiserEnabled=!1,this.isDenoiserProcessed=!1,null==(e=this.denoiserTrack)||e.stop(),this.denoiserTrack=null),this.denoiserContext&&(this.denoiserContext.close(),delete this.denoiserContext)}destroy(){var e;this.destroyAllMusic(),this.destroyAllCache(),this.destroyDenoiserProcessor(),null==(e=this.denoiser)||e.destroy(),this.localMixAudioTrack&&(this.localMixAudioTrack.close(),delete this.localMixAudioTrack)}},yL=class extends MP{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,ob(this,\"tinyId\"),ob(this,\"isRemote\",!0),this.tinyId=t.tinyId}setMute(e){return this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once(\"input-media-track-changed\",e)}))}get isSubscribing(){return\"subscribeing\"===this.state.toString()}get isSubscribed(){return this.state===yL.STATE_SUBSCRIBE}get streamType(){return 0==(2&this.mediaType)?\"main\":\"auxiliary\"}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),\"main\"===this.streamType&&\"video\"===this.kind&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack))return void this.log.info(\"abort play, isSubscribed:\".concat(this.isSubscribed,\" hasFlag:\").concat(this.hasFlag,\" hasTrack:\").concat(!!this.outMediaTrack));super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}},AL=yL;ob(AL,\"STATE_SUBSCRIBE\",\"subscribe\"),rb([Bw(Gw.INIT,AL.STATE_SUBSCRIBE,{success(){this.log.info(\"subscribed\"),xO.emit(FO.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0)},ignoreError:!0})],AL.prototype,\"subscribe\",1),rb([Bw(AL.STATE_SUBSCRIBE,Gw.INIT,{success(){this.log.info(\"unsubscribed\"),this.updatePlayingState(!1),xO.emit(FO.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],AL.prototype,\"unsubscribe\",1);var RL=class extends AL{constructor(e,t){super(e,t,1),ob(this,\"volume\",0),ob(this,\"mediaType\",1),ob(this,\"stat\",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}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}},CL=class extends AL{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),ob(this,\"mediaType\",4),ob(this,\"stat\",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager}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}},bL=class extends CL{constructor(e,t){super(e,t,2),ob(this,\"mediaType\",2),ob(this,\"objectFit\",\"contain\")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function kL(){}var NL=e=>e(),DL=()=>\"undefined\"!=typeof __FASTRX_DEVTOOLS__,OL=1,wL=class extends Function{toString(){return\"\".concat(this.name,\"(\").concat(this.args.length?[...this.args].join(\", \"):\"\",\")\")}subscribe(e){let t=new xL(e,this,this.streamId++);return UL.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},PL=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=kL,this.error=kL,this.next=kL,this.dispose=kL,this.subscribe=kL,this.doDefer()}subscribe(e){return e instanceof wL?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(NL),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}},LL=class extends PL{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 ML(e,t,i){if(DL()){let n=Object.defineProperties(Object.setPrototypeOf(e,wL.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}});UL.create(n);for(let e=0;e{UL.defer(this.source,this.id)}))}next(e){UL.next(this.source,this.id,e),this.sink.next(e)}complete(){UL.complete(this.source,this.id),this.sink.complete()}error(e){UL.complete(this.source,this.id,e),this.sink.error(e)}},UL={addSource(e,t){VL(\"addSource\",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){VL(\"next\",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:n}=e;VL(\"subscribe\",{id:i,end:n,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){VL(\"complete\",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){VL(\"defer\",{id:e.id,streamId:t})},pipe(e){VL(\"pipe\",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){VL(\"update\",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=OL++),VL(\"create\",{name:e.toString(),id:e.id})}},FL=class extends PL{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()}};var BL,HL,jL=(BL=class extends LL{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},HL=\"map\",function(){for(var e=arguments.length,t=new Array(e),i=0;i{if(e instanceof wL){let i=ML((n=>{let r=new BL(n,...t);r.sourceId=i.id,r.subscribe(e)}),HL,arguments);return i.source=e,UL.pipe(i),i}return i=>e(new BL(i,...t))}});!function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;nt(e)),e)}(function(e){return ML((t=>{let i=0,n=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(n)})),\"interval\"}),\"interval\",arguments)}(250),jL((()=>performance.now())),function(){return e=>{let t=new FL(e);if(e instanceof wL){let i=ML((e=>{t.add(e)}),\"share\",arguments);return t.sourceId=i.id,i.source=e,UL.pipe(i),i}return ML(t.add.bind(t),\"share\",arguments)}}());var GL=new Map;function WL(e,t){let i=eb($C({},t),{timestamp:Eb()});GL.has(e)?GL.get(e).push(i):GL.set(e,[i])}xO.on(FO.JOIN_SUCCESS,(e=>{let{room:t}=e;WL(t.userId,{eventId:32788,eventDesc:\"join room\"})})),xO.on(FO.LEAVE_START,(e=>{let{room:t}=e;WL(t.userId,{eventId:32789,eventDesc:\"leave room\"})})),xO.on(FO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),WL(t.room.userId,{eventId:e,eventDesc:\"publish \".concat(t.kind)})}})),xO.on(FO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),WL(t.room.userId,{eventId:e,eventDesc:\"unpublish \".concat(t.kind)})}})),xO.on(FO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===LN.AUDIO?WL(t.room.userId,{eventId:t.isRemote?32785:32772,eventDesc:\"mute audio\",remoteUserId:t.isRemote?t.userId:void 0}):WL(t.room.userId,{eventId:t.isRemote?32784:32773,eventDesc:\"mute video\",remoteUserId:t.isRemote?t.userId:void 0}))})),xO.on(FO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===LN.AUDIO?WL(t.room.userId,{eventId:t.isRemote?32787:32774,eventDesc:\"unmute audio\",remoteUserId:t.isRemote?t.userId:void 0}):WL(t.room.userId,{eventId:t.isRemote?32786:32775,eventDesc:\"unmute video\",remoteUserId:t.isRemote?t.userId:void 0}))})),xO.on(FO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&WL(t.room.userId,{eventId:32777,eventDesc:\"\".concat(LN.SUBSCRIBE,\" \").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&WL(t.room.userId,{eventId:32776,eventDesc:\"\".concat(LN.SUBSCRIBE,\" \").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&WL(t.room.userId,{eventId:32803,eventDesc:\"\".concat(LN.SUBSCRIBE,\" \").concat(LN.SMALL_VIDEO),remoteUserId:t.userId}))})),xO.on(FO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&WL(t.room.userId,{eventId:32779,eventDesc:\"\".concat(LN.UNSUBSCRIBE,\" \").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&WL(t.room.userId,{eventId:32778,eventDesc:\"\".concat(LN.UNSUBSCRIBE,\" \").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&WL(t.room.userId,{eventId:32804,eventDesc:\"\".concat(LN.UNSUBSCRIBE,\" \").concat(LN.SMALL_VIDEO),remoteUserId:t.userId}))})),xO.on(FO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&WL(t.room.userId,{eventId:t.kind===LN.VIDEO?32780:32781,eventDesc:\"switch \".concat(t.kind===LN.VIDEO?\"camera\":\"microphone\")})})),xO.on(FO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&WL(t.room.userId,{eventId:t.kind===LN.VIDEO?32782:32783,eventDesc:\"replace \".concat(t.kind)})})),xO.on(FO.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:n,prevState:r,state:o}=e;switch(o){case\"CONNECTED\":\"RECONNECTING\"===r?(t=32795,i=\"signal reconnected\"):(t=32791,i=\"signal connected\");break;case\"DISCONNECTED\":\"RECONNECTING\"===r?(t=32796,i=\"signal reconnect fail\"):(t=32790,i=\"signal disconnected\");break;case\"RECONNECTING\":t=32794,i=\"signal reconnecting\"}t&&i&&WL(n.userId,{eventId:t,eventDesc:i})})),xO.on(FO.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:n,prevState:r,state:o,remoteUserId:s}=e,a=!!s,c=a?\"downlink\":\"uplink\";switch(o){case\"CONNECTED\":\"RECONNECTING\"===r?(t=a?32801:32798,i=\"\".concat(c,\" reconnected\")):(t=a?32793:32792,i=\"\".concat(c,\" connected\"));break;case\"DISCONNECTED\":\"RECONNECTING\"===r&&(t=a?32802:32799,i=\"\".concat(c,\" reconnect fail\"));break;case\"RECONNECTING\":t=a?32800:32797,i=\"\".concat(c,\" reconnecting\")}t&&i&&WL(n.userId,{eventId:t,eventDesc:i,remoteUserId:s})}));var JL=nb(cb(),1),KL=class extends JL.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,ob(this,\"userMap\",new Map),ob(this,\"remotePublishedUserMap\",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:n,role:r}=e;if(this.userMap.has(t))return;let o={userId:i,tinyId:n,role:20===r?\"anchor\":\"audience\"};this.userMap.set(t,o),this.emit(\"1\",o)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let n=\"peer leave [\".concat(e,\"]\");nO(t)||(n+=\":\".concat(ND[t])),this._log.info(n);let r=this.remotePublishedUserMap.get(e);if(r){let t=r.muteState;r.flag=0,this.emit(\"5\",r.userId),this.deleteRemotePublishedUser(e),this.emit(\"6\",{prevMuteState:t,muteState:r.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:n,userId:r,tinyId:o}=e,s=IO(n,r),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==n&&(e.flag=n,this._log.info(\"remote publish updated: \".concat(JSON.stringify(e.muteState))),this.emit(\"6\",{prevMuteState:a,muteState:s,flag:n}))}else this._log.info(\"remote publish. state: \".concat(JSON.stringify(s))),this.addUser({userId:r,tinyId:o,role:20}),this.emit(\"3\",e),this.emit(\"6\",{prevMuteState:IO(0,r),muteState:s,flag:n})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};var YL,zL=!0,qL={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\"},QL={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},XL=((YL=XL||{})[YL.INVALID_PARAMETER=5e3]=\"INVALID_PARAMETER\",YL[YL.INVALID_PARAMETER_REQUIRED=5001]=\"INVALID_PARAMETER_REQUIRED\",YL[YL.INVALID_PARAMETER_TYPE=5002]=\"INVALID_PARAMETER_TYPE\",YL[YL.INVALID_PARAMETER_EMPTY=5003]=\"INVALID_PARAMETER_EMPTY\",YL[YL.INVALID_PARAMETER_INSTANCE=5004]=\"INVALID_PARAMETER_INSTANCE\",YL[YL.INVALID_PARAMETER_RANGE=5005]=\"INVALID_PARAMETER_RANGE\",YL[YL.INVALID_PARAMETER_LESS_THAN_ZERO=5006]=\"INVALID_PARAMETER_LESS_THAN_ZERO\",YL[YL.INVALID_PARAMETER_MIN=5007]=\"INVALID_PARAMETER_MIN\",YL[YL.INVALID_PARAMETER_MAX=5008]=\"INVALID_PARAMETER_MAX\",YL[YL.INVALID_ELEMENT_ID=5009]=\"INVALID_ELEMENT_ID\",YL[YL.INVALID_ELEMENT_ID_TYPE=5010]=\"INVALID_ELEMENT_ID_TYPE\",YL[YL.INVALID_STREAM_ID=5011]=\"INVALID_STREAM_ID\",YL[YL.INVALID_ROOM_ID_STRING=5012]=\"INVALID_ROOM_ID_STRING\",YL[YL.INVALID_ROOM_ID_INTEGER=5013]=\"INVALID_ROOM_ID_INTEGER\",YL[YL.INVALID_STREAM_TYPE=5014]=\"INVALID_STREAM_TYPE\",YL[YL.INVALID_ROOM_ID_REQUIED=5015]=\"INVALID_ROOM_ID_REQUIED\",YL[YL.INVALID_ROOM_ID_INTEGER_STRING=5016]=\"INVALID_ROOM_ID_INTEGER_STRING\",YL[YL.INVALID_OPERATION=5100]=\"INVALID_OPERATION\",YL[YL.INVALID_OPERATION_NOT_JOINED=5101]=\"INVALID_OPERATION_NOT_JOINED\",YL[YL.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]=\"INVALID_OPERATION_REMOTE_USER_NOT_EXIST\",YL[YL.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]=\"INVALID_OPERATION_STREAM_TYPE_NOT_EXIST\",YL[YL.INVALID_OPERATION_REPEAT_CALL=5104]=\"INVALID_OPERATION_REPEAT_CALL\",YL[YL.ENV_NOT_SUPPORTED=5200]=\"ENV_NOT_SUPPORTED\",YL[YL.NOT_SUPPORTED_HTTP=5201]=\"NOT_SUPPORTED_HTTP\",YL[YL.NOT_SUPPORTED_WEBRTC=5202]=\"NOT_SUPPORTED_WEBRTC\",YL[YL.NOT_SUPPORTED_H264_ENCODE=5203]=\"NOT_SUPPORTED_H264_ENCODE\",YL[YL.NOT_SUPPORTED_H264_DECODE=5204]=\"NOT_SUPPORTED_H264_DECODE\",YL[YL.NOT_SUPPORTED_SCREEN_SHARE=5205]=\"NOT_SUPPORTED_SCREEN_SHARE\",YL[YL.NOT_SUPPORTED_SMALL_VIDEO=5206]=\"NOT_SUPPORTED_SMALL_VIDEO\",YL[YL.NOT_SUPPORTED_SEI=5207]=\"NOT_SUPPORTED_SEI\",YL[YL.DEVICE_ERROR=5300]=\"DEVICE_ERROR\",YL[YL.DEVICE_NOT_FOUND_ERROR=5301]=\"DEVICE_NOT_FOUND_ERROR\",YL[YL.DEVICE_NOT_ALLOWED_ERROR=5302]=\"DEVICE_NOT_ALLOWED_ERROR\",YL[YL.DEVICE_NOT_READABLE_ERROR=5303]=\"DEVICE_NOT_READABLE_ERROR\",YL[YL.DEVICE_OVERCONSTRAINED_ERROR=5304]=\"DEVICE_OVERCONSTRAINED_ERROR\",YL[YL.DEVICE_INVALID_STATE_ERROR=5305]=\"DEVICE_INVALID_STATE_ERROR\",YL[YL.DEVICE_SECURITY_ERROR=5306]=\"DEVICE_SECURITY_ERROR\",YL[YL.DEVICE_ABORT_ERROR=5307]=\"DEVICE_ABORT_ERROR\",YL[YL.CAMERA_RECOVER_FAILED=5308]=\"CAMERA_RECOVER_FAILED\",YL[YL.MICROPHONE_RECOVER_FAILED=5309]=\"MICROPHONE_RECOVER_FAILED\",YL[YL.SERVER_ERROR=5400]=\"SERVER_ERROR\",YL[YL.ACCOUNT_NO_MONEY=-100013]=\"ACCOUNT_NO_MONEY\",YL[YL.OPERATION_FAILED=5500]=\"OPERATION_FAILED\",YL[YL.FIREWALL_RESTRICTION=5501]=\"FIREWALL_RESTRICTION\",YL[YL.REJOIN_FAILED=5502]=\"REJOIN_FAILED\",YL[YL.EVENT_HANDLER_ERROR=5503]=\"EVENT_HANDLER_ERROR\",YL[YL.VIDEO_CONTEXT_ERROR=5504]=\"VIDEO_CONTEXT_ERROR\",YL[YL.OPERATION_ABORT=5998]=\"OPERATION_ABORT\",YL[YL.UNKNOWN_ERROR=5999]=\"UNKNOWN_ERROR\",YL);var ZL=eb($C({},KO),{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:n,value:r}=e;return\"'\".concat(t||i.name,\"' is a required param when calling \").concat(n,\"(), received: \").concat(r,\".\")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:n,value:r}=e,o=\"\".concat(t||i.name),s=\"\";return s=Array.isArray(i.type)?i.type.join(\"|\"):i.type,\"'\".concat(o,\"' must be type of \").concat(s,\" when calling \").concat(n,\"(), received type: \").concat(tO(r),\".\")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:n,value:r}=e;return\"'\".concat(t||i.name,\"' cannot be '\").concat(r,\"' when calling \").concat(n,\"().\")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:n,value:r}=e,o=\"\".concat(t||i.name),s=\"\".concat(i.instanceOf.name||i.instanceOf);return\"'\".concat(o,\"' must be instanceof \").concat(s,\" when calling \").concat(n,\"(), received type: \").concat(tO(r),\".\")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:n,value:r}=e;return\"'\".concat(t||i.name,\"' must be one of \").concat(i.values.join(\"|\"),\" when calling \").concat(n,\"(), received: \").concat(r,\".\")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:n}=e;return\"'\".concat(t||i.name,\"' cannot be less than 0 when calling \").concat(n,\"().\")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,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,value:n}=e;return\"the max value of \".concat(t||i.name,\" is \").concat(i.max,\", received: \").concat(n,\".\")},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:n}=e;return\"the element corresponding to '\".concat(t,\"' must be instanceof HTMLElement when calling \").concat(i,\"(), received: \").concat(n,\".\")},INVALID_STREAM_ID(e){let{key:t}=e;return\"'\".concat(t,\"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.\")},INVALID_ROOM_ID_STRING(e){let{key:t}=e;return\"'\".concat(t,\"' must be a valid string.\")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return\"'\".concat(t,\"' must be an integer between [1, 4294967294].\")},INVALID_ROOM_ID_INTEGER_STRING(e){let{key:t}=e;return\"'\".concat(t,\"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.\")},INVALID_ROOM_ID_REQUIED:()=>\"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.\",INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return\"'streamType' is required when 'userId' is not '*', calling \".concat(t,\"()\")},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_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 device exception\").concat(i?\", error: \".concat(i.toString(),\".\"):\".\")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:i=$L(t),error:n}=e;return\"NotFoundError, no \".concat(i,\" detected, please check your device and the configuration on '\").concat(t,\"'\").concat(n?\", error: \".concat(n.toString(),\".\"):\".\")},DEVICE_NOT_ALLOWED_ERROR(e){let{fnName:t,deviceType:i=$L(t),error:n}=e;return\"NotAllowedError, you have disabled \".concat(i,\" access, please allow the current application to use the \").concat(i).concat(n?\", error: \".concat(n.toString(),\".\"):\".\")},DEVICE_NOT_READABLE_ERROR(e){let{fnName:t,deviceType:i=$L(t),error:n}=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=$L(t),error:n}=e;return\"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct\".concat(n?\", error: \".concat(n.toString(),\".\"):\".\")},DEVICE_INVALID_STATE_ERROR(e){let{fnName:t,deviceType:i=$L(t),error:n}=e;return\"InvalidStateError, after the user clicks and interacts with the page, turn on the \".concat(i).concat(n?\", error: \".concat(n.toString(),\".\"):\".\")},DEVICE_SECURITY_ERROR(e){let{fnName:t,deviceType:i=$L(t),error:n}=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(n?\", error: \".concat(n.toString(),\".\"):\".\")},DEVICE_ABORT_ERROR(e){let{fnName:t,deviceType:i=$L(t),error:n}=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(n?\" error: \".concat(n.toString(),\".\"):\".\")},CAMERA_RECOVER_FAILED(e){let{error:t}=e;return\"camera recover capture failed \".concat((null==t?void 0:t.name)||\"\",\": \").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},MICROPHONE_RECOVER_FAILED(e){let{error:t}=e;return\"microphone recover capture failed \".concat((null==t?void 0:t.name)||\"\",\": \").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},OPERATION_FAILED(e){let{fnName:t,error:i}=e;return\"'\".concat(t,\"' failed, reason: \").concat(null==i?void 0:i.toString())},FIREWALL_RESTRICTION:()=>\"media connection failure due to firewall restrictions, please try to change your network.\",EVENT_HANDLER_ERROR(e){let{eventName:t}=e;return\"an error was caught on trtc.on('\".concat(t,\"', handler), please check your code on 'handler'.\")},VIDEO_CONTEXT_ERROR(e){let{reason:t,error:i}=e;return\"video context error \".concat(t,\" \").concat((null==i?void 0:i.name)||\"\",\" \").concat((null==i?void 0:i.message)||\"\")},SERVER_ERROR(e){let{fnName:t,error:i}=e;return\"'\".concat(t,\"' got server error: \").concat(null==i?void 0:i.toString(),\", please check the SDK documentation.\")},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 $L(e){if(!e)return\"camera\";let t=e.toLowerCase();return t.includes(\"screen\")?\"screen share\":t.includes(\"audio\")?\"microphone\":\"camera\"}var eM=class extends Error{constructor(e){let{code:t,extraCode:i,message:n=\"\",messageParams:r,fnName:o=\"\",originError:s}=e;var a;let c;c=n||function(e){let t,{code:i,params:n,enableDocLink:r=!1}=e,s=\"\",a=XL[i];try{t=ZL[a]}catch(o){t=ZL.UNKNOWN_ERROR}return iO(t)?s=t(n):rO(t)&&(s=t),r&&(s+=\" doc:\"),s}({code:i||t,params:$C({fnName:o,error:s},r)}),super(c),ob(this,\"name\",\"RtcError\"),ob(this,\"code\"),ob(this,\"extraCode\"),ob(this,\"functionName\"),ob(this,\"message\"),ob(this,\"handler\"),ob(this,\"originError\"),this.name=XL[t],this.code=t,this.extraCode=i,this.functionName=o,this.originError=s,this.message=c,5302===this.extraCode&&(null==(a=this.originError)?void 0:a.message.includes(\"system\"))&&(this.handler=()=>{let e=document.createElement(\"a\");_k?e.href=\"ms-settings:privacy-\".concat({startLocalVideo:\"webcam\",startLocalAudio:\"microphone\"}[this.functionName]):mk&&(e.href=\"x-apple.systempreferences:com.apple.preference.security?Privacy_\".concat({startLocalVideo:\"Camera\",startLocalAudio:\"Microphone\",startScreenShare:\"ScreenCapture\"}[this.functionName])),e.href.length>0&&e.click()})}static convertFrom(e,t,i){let n=e;if(e instanceof gb){let{stack:r}=e,o={code:QL.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case mb.INVALID_PARAMETER:o.code=QL.INVALID_PARAMETER;break;case mb.INVALID_OPERATION:o.code=QL.INVALID_OPERATION;break;case mb.NOT_SUPPORTED:case mb.NOT_SUPPORTED_H264:o.code=QL.ENV_NOT_SUPPORTED,e.getCode()===mb.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(KO.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case mb.DEVICE_NOT_FOUND:case mb.DEVICE_AUTO_RECOVER_FAILED:o.code=QL.DEVICE_ERROR;break;case mb.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case mb.SERVER_TIMEOUT:case mb.SWITCH_ROLE_FAILED:o.code=QL.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case mb.API_CALL_ABORTED:o.code=QL.OPERATION_ABORT;break;case mb.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 mb.UNKNOWN:break;default:o.code=QL.OPERATION_FAILED}n=new eM(o),r&&(n.stack+=r.substr(r.indexOf(\"\\n\")))}else n=new eM({code:QL.UNKNOWN_ERROR,fnName:t,originError:e});return n}};var tM=eM,iM={type:\"object\",properties:{cameraId:{type:\"string\"},useFrontCamera:{type:\"boolean\"},fillMode:{type:\"string\",values:[\"contain\",\"cover\",\"fill\"]},mirror:{type:\"boolean\"},small:{properties:{width:{type:\"number\"},height:{type:\"number\"},frameRate:{type:\"number\"},bitrate:{type:\"number\"}}},videoTrack:{instanceOf:MediaStreamTrack}}},nM={type:\"object\",properties:{systemAudio:{type:\"boolean\"},fillMode:{type:\"string\",values:[\"contain\",\"cover\",\"fill\"]},profile:{type:[\"string\",\"object\"],properties:{width:{type:\"number\"},height:{type:\"number\"},frameRate:{type:\"number\"},bitrate:{type:\"number\"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},rM={type:[\"string\",HTMLElement,null,\"array\"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(rO(e)){let n=document.getElementById(e);if(!n)throw new tM({code:QL.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}});if(!(n instanceof HTMLElement))throw new tM({code:QL.INVALID_PARAMETER,extraCode:5010,fnName:i,messageParams:{key:t,type:tO(n)}})}}},oM={name:\"userId\",required:!0,type:\"string\"},sM={type:\"object\",properties:{microphoneId:{type:\"string\"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:\"number\",min:0},earMonitorVolume:{type:\"number\",min:0,max:100},echoCancellation:{type:\"boolean\"},autoGainControl:{type:\"boolean\"},noiseSuppression:{type:\"boolean\"}}};function aM(e,t){if(!e)throw new tM({code:QL.INVALID_OPERATION,extraCode:5101,fnName:t})}function cM(e,t,i){if(!e)throw new tM({code:QL.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var lM={create:[{name:\"RoomConfig\",instanceOf:Function},{name:\"CreateConfig\",type:\"object\",properties:{plugins:{type:\"array\",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:\"EnterRoomConfig\",type:\"object\",required:!0,validate(e,t,i){if(this._room.isJoined)throw new tM({code:QL.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(rO(e.roomId))throw new tM({code:QL.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new tM({code:QL.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new tM({code:QL.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\\d\\s!#$%&()+\\-:;<=.>?@[\\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new tM({code:QL.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}})}},properties:{sdkAppId:{required:!0,type:\"number\",allowEmpty:!1},userId:{required:!0,type:\"string\",allowEmpty:!1},userSig:{required:!0,type:\"string\",allowEmpty:!1},scene:{type:\"string\",values:[\"live\",\"rtc\"]},role:{type:\"string\",values:[\"audience\",\"anchor\"]},roomId:{type:[\"string\",\"number\"]},strRoomId:{type:\"string\"},proxy:{type:[\"object\",\"string\"],properties:{websocketProxy:{type:\"string\"},turnServer:{type:[\"object\",\"array\"],properties:{url:{required:!0,type:\"string\"},username:{type:\"string\"},credential:{type:\"string\"},credentialType:{type:\"string\",values:[\"password\"]}}},loggerProxy:{type:\"string\"},webtransportProxy:{type:\"string\"}}},enableAutoPlayDialog:{type:\"boolean\"},userDefineRecordId:{type:\"string\"}}},startLocalVideo:{name:\"LocalVideoConfig\",type:\"object\",properties:{view:rM,publish:{type:\"boolean\"},option:iM},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&nw())throw new tM({code:QL.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:\"updateLocalVideoConfig\",type:\"object\",required:!0,properties:{view:eb($C({},rM),{required:!1}),publish:{type:\"boolean\"},mute:{type:\"boolean\"},option:iM}},startLocalAudio:{name:\"LocalAudioConfig\",type:\"object\",properties:{publish:{type:\"boolean\"},option:sM},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&nw())throw new tM({code:QL.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:\"updateLocalAudioConfig\",type:\"object\",required:!0,properties:{publish:{type:\"boolean\"},mute:{type:\"boolean\"},option:sM}},startScreenShare:{name:\"ScreenShareConfig\",type:\"object\",properties:{view:rM,publish:{type:\"boolean\"},option:nM},validate(e,t,i,n,r){var o;if((null==(o=null==e?void 0:e.option)||!o.videoTrack)&&nw())throw new tM({code:QL.ENV_NOT_SUPPORTED,extraCode:5201});if(!lw())throw new tM({code:QL.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:\"updateScreenShareConfig\",type:\"object\",required:!0,properties:{view:rM,publish:{type:\"boolean\"},option:nM}},muteRemoteAudio:[oM,{name:\"mute\",required:!0,type:\"boolean\"}],setRemoteAudioVolume:[oM,{name:\"volume\",required:!0,type:\"number\",min:0}],startRemoteVideo:{name:\"startRemoteVideoConfig\",type:\"object\",required:!0,properties:{view:rM,userId:{type:\"string\",required:!0},streamType:{values:[\"main\",\"sub\"],required:!0},option:{type:\"object\",properties:{fillMode:{type:\"string\",values:[\"contain\",\"cover\",\"fill\"]},mirror:{type:\"boolean\"}}}},validate(e,t,i){aM(this._room.isJoined,i);let n=this._room.remotePublishedUserMap.get(e.userId);if(cM(!!n,i,e),n&&(\"main\"===e.streamType&&!n.muteState.videoAvailable||\"sub\"===e.streamType&&!n.muteState.hasAuxiliary))throw new tM({code:QL.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:\"updateRemoteVideoConfig\",type:\"object\",required:!0,properties:{view:eb($C({},rM),{required:!1}),userId:{type:\"string\",required:!0},streamType:{values:[\"main\",\"sub\"],required:!0},option:{type:\"object\",properties:{fillMode:{type:\"string\",values:[\"contain\",\"cover\",\"fill\"]},mirror:{type:\"boolean\"}}}},validate(e,t,i){aM(this._room.isJoined,i);let n=this._room.remotePublishedUserMap.get(e.userId);if(cM(!!n,i,e),n&&(\"main\"===e.streamType&&!n.muteState.videoAvailable||\"sub\"===e.streamType&&!n.muteState.hasAuxiliary))throw new tM({code:QL.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},stopRemoteVideo:{name:\"stopRemoteVideoConfig\",type:\"object\",required:!0,properties:{userId:{type:\"string\",required:!0},streamType:{values:[\"main\",\"sub\"]}},validate(e,t,i){if(\"*\"!==e.userId&&nO(e.streamType))throw new tM({code:QL.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:\"role\",required:!0,values:[\"anchor\",\"audience\"],validate(e,t,i){aM(this._room.isJoined,i)}},enableAudioVolumeEvaluation:[{name:\"interval\",type:\"number\"},{name:\"enableInBackground\",type:\"boolean\"}],sendSEIMessage:[{name:\"buffer\",required:!0,instanceOf:ArrayBuffer,validate(e,t,i,n){if(!kw)throw new tM({code:QL.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new tM({code:QL.INVALID_OPERATION,messageParams:{key:JO.SEI_DISABLED}});if(e.byteLength>1e3)throw new tM({code:QL.INVALID_PARAMETER,messageParams:{key:JO.SEI_OVERSIZE,data:e.byteLength}});if(0===e.byteLength)throw new tM({code:QL.INVALID_PARAMETER,messageParams:{key:JO.SEI_EMPTY}});if(aM(this._room.isJoined,i),!this._room.isMainStreamPublished)throw new tM({code:QL.INVALID_PARAMETER,messageParams:{key:JO.SEI_BEFORE_PUBLISH}})}},{name:\"options\",type:\"object\",properties:{seiPayloadType:{type:\"number\",values:[5,243]}}}]},dM={TRTC:lM},uM=class extends Error{};function hM(e,t){let i=[];return CO(i,e),CO(i,t),i}function pM(e){this._resolve=Promise.resolve(e)}function _M(e){this._reject=Promise.reject(e)}var mM=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=hM;let i=mM.instances.get(e);i?i.set(t,this):mM.instances.set(e,new Map([[t,this]]))}static get(e,t){let i=mM.instances.get(e);return i&&i.get(t)||new mM(e,t)}action(e,t,i){let n=t=>{var i;return 0===e?this.started=!0:3===e&&(this.started=!1),this.ops.shift(),null==(i=this.currentOp)||i.action(),t},r=t=>{var i,n;throw this.ops.shift(),0===e&&2===(null==(i=this.currentOp)?void 0:i.type)&&this.ops.shift().reject(new uM(\"start failed\")),null==(n=this.currentOp)||n.action(),t},o={type:e,action:()=>t(...o.args).then(n,r),args:i,resolve:pM,reject:_M};try{switch(this.state){case 1:if(0===e)throw new uM(\"already started\");break;case 4:if(2===e)throw new uM(\"not started\");break;default:return this.cacheOp(o)}}catch(qx){return Promise.reject(qx)}return this.ops.push(o),o.promise=t(...o.args).then(n,r)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new uM(\"already start\");break;case 3:switch(e.type){case 2:throw new uM(\"update not allowed when stopping\");case 3:return this.currentOp.promise}break;default:throw new uM(\"unknown state\")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new uM(\"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 uM(\"update not allowed after stop\")}break;case 0:switch(this.lastOpType){case 2:throw new uM(\"start not allowed after update\");case 0:throw new uM(\"duplicate start\");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new uM(\"keep start\")),new uM(\"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}},fM=mM;fM.instances=new WeakMap;var gM=new WeakMap,TM=(e,t)=>{if(t instanceof uM){let{stack:i}=t;t=new tM({code:QL.OPERATION_ABORT,message:\"\".concat(e,\" abort: \").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf(\"\\n\")))}throw t};function EM(e,t){return iL(((i,n)=>function(){for(var r=arguments.length,o=new Array(r),s=0;sfunction(){for(var o=arguments.length,s=new Array(o),a=0;a{var a,l;let d=null==(a=gM.get(this))?void 0:a.get(i(...s));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout((()=>{if(3===c.state||4===c.state)return n();c.action(2,t.bind(this),s).catch(TM.bind(null,r)).then(n,o)}),e);gM.has(this)?null==(l=gM.get(this))||l.set(i(...s),{timeoutId:u,resolve:n}):gM.set(this,new Map([[i(...s),{timeoutId:u,resolve:n}]]))}))}return c.action(2,t.bind(this),s).catch(TM.bind(null,r))}))}function IM(e){return iL(((t,i)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o{t.startsWith(n)&&(e.started=!1)}))}}}var RM=new WeakMap;function CM(){for(var e=arguments.length,t=new Array(e),i=0;ifunction(){for(var n=arguments.length,r=new Array(n),o=0;ofunction(){for(var n=arguments.length,r=new Array(n),o=0;ohO(e)?pO(e):rO(e)?e:tO(e)))},value:i}})}else if(!nO(t.type)&&tO(i)!==t.type)throw new tM(s(5002));if(!1===t.allowEmpty){let e=oO(i)&&(0===i||Number.isNaN(i)),t=rO(i)&&\"\"===i.trim();if(e||t)throw new tM(s(5003))}if(t.notLessThanZero&&oO(i)&&i<0)throw new tM(s(5006));if(!nO(t.min)&&oO(i)&&it.max)throw new tM(s(5008));if(rO(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new tM(s(5004))}else if(iO(t.instanceOf)&&!(i instanceof t.instanceOf))throw new tM(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new tM(s(5005));let{properties:a}=t;ZD(a)&&aO(i)&&Object.keys(a).forEach((e=>{NM.call(this,{rule:a[e],value:i&&i[e],key:\"\".concat(e),fnName:r,className:o})}));let{arrayItem:c}=t;ZD(c)&&cO(i)&&i.forEach(((e,t)=>{NM.call(this,{rule:c,value:e,key:\"\".concat(n,\"[\").concat(t,\"]\"),fnName:r,className:o})})),iO(t.validate)&&t.validate.call(this,i,n,r,o,this)}function DM(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{namePrefix:t=(()=>\"\"),getRemoteId:i=(()=>\"\")}=e;return iL(((e,n)=>function(){for(var r=arguments.length,o=new Array(r),s=0;s0?c.info(\"\".concat(d,\"() \").concat(JSON.stringify(o,((e,t)=>a(e,t,[\"userSig\",\"privateMapKey\"]))))):c.info(\"\".concat(d,\"()\"));try{let t=e.apply(this,o),n=fO();return uO(t)?t.then((e=>(c.info(\"\".concat(d,\"() success \").concat(i.call(this,...o))),xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:d,cost:fO()-n}),e))).catch((e=>{throw e=tM.convertFrom.call(this,e,d,1===o.length?o[0]:o),c.error(\"\".concat(d,\"() failed \").concat(i.call(this,...o),\" \").concat(e,\" params: \").concat(JSON.stringify(o,a))),xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:d,error:e}),e})):(xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:d,cost:fO()-n}),t)}catch(u){throw u=tM.convertFrom.call(this,u,d),c.error(\"\".concat(d,\"() failed \").concat(u,\" params: \").concat(JSON.stringify(o,a))),xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:d,error:u}),u}}))}var OM=e=>iL(((t,i)=>function(n,r){return ab(this,null,(function*(){let o=this._plugins.get(n);if(o)return kM.call(this,o.getValidateRule(e),[r],i,\"TRTC\"),t.call(this,o,r);this._log.warn(\"plugin \".concat(n,\" is not found\"))}))})),wM=0,PM=class{constructor(e){this.core=e,ob(this,\"log\"),wM+=1,this.log=e.log.createChild({id:\"\".concat(this.getAlias()).concat(wM)}),this.log.info(\"[audioMixer] created id=\".concat(this.getAlias()).concat(wM)),this.core=e}getName(){return\"AudioMixer\"}getAlias(){return\"ax\"}getGroup(e){return null==e?void 0:e.id}getValidateRule(e){switch(e){case\"start\":return PM.startValidateRule;case\"update\":return PM.updateValidateRule;case\"stop\":return PM.stopValidateRule}}start(e){return ab(this,null,(function*(){let{room:t}=this.core;yield t.audioManager.addMusicSource(e)}))}update(e){return ab(this,null,(function*(){let{room:t}=this.core;yield t.audioManager.updateMusicSource(e)}))}stop(e){return ab(this,null,(function*(){let{room:t}=this.core;yield t.audioManager.removeMusicSource(e)}))}},LM=PM;ob(LM,\"startValidateRule\",{name:\"options\",required:!0,type:\"object\",properties:{id:{type:\"string\",required:!0},url:{type:\"string\",required:!0},loop:{type:\"boolean\"},volume:{type:\"number\"}},validate(e,t,i){if(\"*\"!==e.url){let t=[\"mp3\",\"ogg\",\"wav\",\"flac\"],n=e.url.split(\".\").pop(),r=t.indexOf(n)>=0,o=e.url.startsWith(\"blob\"),s=e.url.startsWith(\"data\");if(!(r||o||s))throw new tM({code:QL.INVALID_PARAMETER,message:\"start audioMixer plugin: music url is invalid, please check your file format.\",fnName:i})}}}),ob(LM,\"updateValidateRule\",{name:\"options\",required:!0,type:\"object\",properties:{id:{type:\"string\",required:!0},loop:{type:\"boolean\"},volume:{type:\"number\"},seekFrom:{type:\"number\"},operation:{type:\"string\",values:[\"pause\",\"resume\",\"stop\"]}}}),ob(LM,\"stopValidateRule\",{name:\"options\",type:\"object\",required:!0,properties:{id:{type:\"string\",required:!0}}});var MM=0,VM=class{constructor(e){this.core=e,ob(this,\"log\"),MM+=1,this.log=e.log.createChild({id:\"\".concat(this.getAlias()).concat(MM)}),this.log.info(\"[audioDenoiser] created id=\".concat(this.getAlias()).concat(MM))}getName(){return\"AIDenoiser\"}getAlias(){return\"ad\"}getGroup(e){return\"AIDenoiser_\".concat(Date.now())}getValidateRule(e){switch(e){case\"start\":return VM.startValidateRule;case\"update\":return VM.updateValidateRule;case\"stop\":return VM.stopValidateRule}}start(e){return ab(this,null,(function*(){let{room:t}=this.core,{assetsPath:i,sdkAppId:n,userId:r,userSig:o}=e;if(i&&!t.audioManager.isDenoiserInit)try{yield t.audioManager.initDenoiser({assetsPath:i,sdkAppId:n,userId:r,userSig:o})}catch(qx){if(qx.message)throw new gb({code:mb.INVALID_PARAMETER,message:qx.message})}yield t.audioManager.enableDenoiser(e),t.sendAbilityStatus({ai_denoise:1})}))}update(e){return ab(this,null,(function*(){}))}stop(e){return ab(this,null,(function*(){let{room:e}=this.core;yield e.audioManager.disableDenoiser()}))}},xM=VM;ob(xM,\"startValidateRule\",{name:\"options\",required:!0,type:\"object\",properties:{assetsPath:{type:\"string\",required:!0},sdkAppId:{type:\"number\",required:!0},userId:{type:\"string\",required:!0},userSig:{type:\"string\",required:!0}}}),ob(xM,\"updateValidateRule\",{type:\"object\"}),ob(xM,\"stopValidateRule\",{type:\"object\"});var UM=0,FM=new Set,BM=null;oN(\"5.2.1\");var HM=class extends pb.EventEmitter{constructor(e,t){super(),ob(this,\"_room\"),ob(this,\"_eventListened\",new Set),ob(this,\"_localVideoTrack\",null),ob(this,\"_localAudioTrack\",null),ob(this,\"_localScreenTrack\",null),ob(this,\"_localScreenAudioTrack\",null),ob(this,\"_localVideoConfig\",null),ob(this,\"_localScreenConfig\",null),ob(this,\"_localAudioConfig\",null),ob(this,\"_remoteVideoConfigMap\",new Map),ob(this,\"_remoteAudioConfigMap\",new Map),ob(this,\"_remoteAudioMuteMap\",new Map),ob(this,\"_log\",HO.createLogger({id:\"t\".concat(++UM)})),ob(this,\"_plugins\",new Map),ob(this,\"_networkQuality\",null),this._room=new e($C({logger:this._log,frameWorkType:HM.frameWorkType},t)),t.plugins&&t.plugins.forEach((e=>{let t=new e(AM(this._room));this._plugins.set(t.getName(),t)}));let i=new LM(AM(this._room));this._plugins.set(i.getName(),i);let n=new xM(AM(this._room));this._plugins.set(n.getName(),n),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(vM.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on(\"error\",(e=>{let{reason:t,error:i}=e;this._log.error(new tM({code:QL.OPERATION_FAILED,extraCode:5504,messageParams:{reason:t,error:i}}))})),this.on(vM.REMOTE_AUDIO_UNAVAILABLE,(e=>{let{userId:t}=e;this._stopRemoteAudio({userId:t},!1).catch((()=>{}))})),this.on(vM.REMOTE_VIDEO_UNAVAILABLE,(e=>{let{userId:t,streamType:i}=e;this._stopRemoteVideo({userId:t,streamType:i},!1).catch((()=>{}))})),SP(jP,jP).add(\"audioInputAdded\",(e=>{this.emit(vM.DEVICE_CHANGED,{type:\"microphone\",action:\"add\",device:e})})).add(\"audioInputRemoved\",(e=>{this.emit(vM.DEVICE_CHANGED,{type:\"microphone\",action:\"remove\",device:e})})).add(\"videoInputAdded\",(e=>{this.emit(vM.DEVICE_CHANGED,{type:\"camera\",action:\"add\",device:e})})).add(\"videoInputRemoved\",(e=>{this.emit(vM.DEVICE_CHANGED,{type:\"camera\",action:\"remove\",device:e})})).add(\"audioOutputAdded\",(e=>ab(this,null,(function*(){if(this.emit(vM.DEVICE_CHANGED,{type:\"speaker\",action:\"add\",device:e}),BM&&BM.deviceId===CD){let e=(yield KP()).find((e=>e.deviceId===CD));e&&BM.groupId!==e.groupId&&(BM=e,this.emit(vM.DEVICE_CHANGED,{type:\"speaker\",action:\"active\",device:e}))}})))).add(\"audioOutputRemoved\",(e=>ab(this,null,(function*(){this.emit(vM.DEVICE_CHANGED,{type:\"speaker\",action:\"remove\",device:e});let t=(yield KP())[0];t&&BM&&(BM.deviceId===e.deviceId||BM.deviceId===CD&&BM.groupId!==t.groupId)&&(BM=t,this.emit(vM.DEVICE_CHANGED,{type:\"speaker\",action:\"active\",device:t}))})))),((e,t)=>{let{emit:n}=e;e.emit=function(){for(var r=arguments.length,o=new Array(r),s=0;s{if(e){let t=\"UAData: \".concat(e.platform,\"/\").concat(e.platformVersion);e.architecture&&e.bitness&&(t+=\" \".concat(e.architecture,\"/\").concat(e.bitness)),e.mobile&&(t+=\" mobile\"),e.model&&(t+=\" model: \".concat(e.model)),e.fullVersionList&&(t+=\" \".concat(e.fullVersionList.filter((e=>\"Not/A)Brand\"!==e.brand)).map((e=>\"\".concat(e.brand,\"/\").concat(e.version))).join(\",\"))),HO.info(t)}})))}();let i=new HM(e,t||{});return FM.add(i),BM?i.emit(vM.DEVICE_CHANGED,{type:\"speaker\",action:\"active\",device:BM}):KP().then((e=>{e[0]&&(BM=e[0],i.emit(vM.DEVICE_CHANGED,{type:\"speaker\",action:\"active\",device:e[0]}))})),i}enterRoom(e){return ab(this,null,(function*(){var t,i;let{scene:n=\"rtc\",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:s=!0}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!rO(e.proxy)&&e.proxy.turnServer&&(null==(i=(t=this._room).setTurnServer)||i.call(t,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=s,sO(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,role:\"audience\"===e.role?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||\"\",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};e.strRoomId&&!e.roomId&&(this._room.useStringRoomId=!0),SP(this,this._room).add(\"peer-join\",(e=>{let{userId:t}=e;this.emit(vM.REMOTE_USER_ENTER,{userId:t})})).add(\"peer-leave\",(e=>{this.emit(vM.REMOTE_USER_EXIT,{userId:e})})).add(\"banned\",(e=>{this._exitRoom().then((()=>{this.emit(vM.KICKED_OUT,{reason:e.reason})}))})).add(\"error\",(e=>{this._exitRoom().then((()=>{this.emit(vM.ERROR,tM.convertFrom(e))}))})).add(\"signal-connection-state-changed\",(e=>{this.emit(vM.CONNECTION_STATE_CHANGED,e)})).add(\"network-quality\",(e=>{this._networkQuality=e,this.emit(vM.NETWORK_QUALITY,e)})).add(\"remote-published\",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{SP(t,t).add(\"player-state-changed\",(i=>{let n=eb($C({},i),{userId:e.userId});t.kind===LN.VIDEO&&(n.streamType=function(e){return\"sub\"===e?\"auxiliary\":\"auxiliary\"===e?\"sub\":\"main\"}(t.streamType)),this.emit(t.kind===LN.AUDIO?vM.AUDIO_PLAY_STATE_CHANGED:vM.VIDEO_PLAY_STATE_CHANGED,n)})).add(\"error\",(e=>{e.getCode()===mb.PLAY_NOT_ALLOWED&&this.emit(vM.AUTOPLAY_FAILED,{userId:t.userId})}))}))})).add(\"remote-unpublished\",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{IP(e)}))})).add(\"remote-publish-state-changed\",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:n}=i;this._room.remotePublishedUserMap.get(n);let r=t.audioAvailable,o=t.videoAvailable,{audioAvailable:s,videoAvailable:a}=i;s||this._remoteAudioConfigMap.delete(n),a||this._remoteVideoConfigMap.delete(\"\".concat(n,\"_\",\"main\")),i.hasAuxiliary||this._remoteVideoConfigMap.delete(\"\".concat(n,\"_\",\"sub\")),r!==s&&this.emit(s?vM.REMOTE_AUDIO_AVAILABLE:vM.REMOTE_AUDIO_UNAVAILABLE,{userId:n}),o!==a&&this.emit(a?vM.REMOTE_VIDEO_AVAILABLE:vM.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:\"main\"}),t.hasAuxiliary!==i.hasAuxiliary&&this.emit(i.hasAuxiliary?vM.REMOTE_VIDEO_AVAILABLE:vM.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:\"sub\"})})).add(\"firewall-restriction\",(()=>{this.emit(vM.ERROR,new tM({code:QL.OPERATION_FAILED,extraCode:5501}))})).add(\"sei-message\",(e=>{this.emit(vM.SEI_MESSAGE,e)})).add(\"heartbeat-report\",(e=>{var t,i,n,r,o,s,a;let c={2:\"big\",3:\"small\",7:\"sub\"},l={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(n=this._networkQuality)?void 0:n.downlinkRTT)||0,upLoss:(null==(r=this._networkQuality)?void 0:r.uplinkLoss)||0,downLoss:(null==(o=this._networkQuality)?void 0:o.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/xD},video:e.msg_up_stream_info.msg_video_status.filter((e=>c[e.uint32_video_stream_type])).map((e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_enc_fps,videoType:c[e.uint32_video_stream_type]})))},remoteStatistics:e.msg_down_stream_info.map((e=>({userId:e.msg_user_info.str_identifier,audio:{bitrate:(e.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(e.msg_audio_status.uint32_audio_level||0)/xD},video:e.msg_video_status.map((e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_dec_fps,videoType:c[e.uint32_video_stream_type]})))})))};this.emit(vM.STATISTICS,l)})),this._handleReceiveMode(),yield this._room.join(a,n,HM.frameWorkType),this._checkTrackToPublish()}))}exitRoom(){return ab(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e){return ab(this,null,(function*(){yield this._room.switchRole(e),\"anchor\"===e&&this._checkTrackToPublish()}))}destroy(){IP(jP),this.removeAllListeners(),this._room.destroy(),FM.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare()}startLocalAudio(){return ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn(\"local audio is already started\");let{publish:i=!0,option:n}=t,r=new oL(e._room.audioManager),o={},s={muted:!0};n&&(nO(n.microphoneId)?nO(n.audioTrack)||(o.customSource=n.audioTrack):o.deviceId=n.microphoneId,n&&oO(n.captureVolume)&&r.setCaptureVolume(n.captureVolume),nO(n.profile)||(rO(n.profile)?ON[n.profile]&&r.setProfile(ON[n.profile]):r.setProfile(n.profile)),oO(n.earMonitorVolume)&&(s.muted=!(n.earMonitorVolume>0),s.volume=n.earMonitorVolume),nO(n.echoCancellation)||(r.profile.echoCancellation=n.echoCancellation),nO(n.noiseSuppression)||(r.profile.noiseSuppression=n.noiseSuppression),nO(n.autoGainControl)||(r.profile.autoGainControl=n.autoGainControl)),r.on(\"5\",(t=>{e.emit(vM.ERROR,new tM({code:QL.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),r.on(\"2\",(t=>{e.emit(vM.DEVICE_CHANGED,{type:\"microphone\",action:\"active\",device:t})})),r.on(\"4\",(t=>{let i;t.error&&(i=tM.convertFrom(t.error)),e.emit(vM.PUBLISH_STATE_CHANGED,eb($C({},t),{error:i}))})),yield r.capture(o),SP(r,r).add(\"player-state-changed\",(t=>{e.emit(vM.AUDIO_PLAY_STATE_CHANGED,eb($C({},t),{userId:\"\"}))})),i&&e._room.isJoined&&e._room.publish(r).catch((()=>{})),yield e._updateAudioPlayOption({playOption:s,track:r}),e._localAudioTrack=r,e._localAudioConfig=eb($C({},t),{publish:i})}()}))}updateLocalAudio(e){return ab(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:n}=e,r={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):nO(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),nO(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),nO(n.earMonitorVolume)||(r.muted=!(n.earMonitorVolume>0),r.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!nO(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),nO(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:r,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),CO(this._localAudioConfig,e)}))}stopLocalAudio(){return ab(this,null,(function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),this._localAudioTrack.stop(),this._localAudioTrack.close(),IP(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localVideoTrack)return void e._log.warn(\"local video is already started\");let{view:i,publish:n=!0,option:r}=t,o=new sL(e._room.videoManager),s={},a={};if(r&&(r.cameraId?s.deviceId=r.cameraId:nO(r.useFrontCamera)?nO(r.videoTrack)||(s.customSource=r.videoTrack):s.facingMode=r.useFrontCamera?LN.FACING_MODE_USER:LN.FACING_MODE_ENVIRONMENT,nO(r.profile)||(rO(r.profile)?wN[r.profile]&&o.setProfile(wN[r.profile]):o.setProfile(r.profile)),nO(r.fillMode)||(a.objectFit=r.fillMode),nO(r.mirror)||(a.mirror=r.mirror),nO(r.small)||(fw()?rO(r.small)?o.small=wN[r.small]:o.small=r.small:e._log.warn(\"small stream is not supported\"))),o.on(\"5\",(t=>{e.emit(vM.ERROR,new tM({code:QL.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),o.on(\"2\",(t=>{e.emit(vM.DEVICE_CHANGED,{type:\"camera\",action:\"active\",device:t})})),o.on(\"4\",(t=>{let i;t.error&&(i=tM.convertFrom(t.error)),e.emit(vM.PUBLISH_STATE_CHANGED,eb($C({},t),{error:i}))})),yield o.capture(s),(null==r?void 0:r.qosPreference)&&o.mediaTrack){let e=yM(r.qosPreference);o.mediaTrack.contentHint=e}SP(o,o).add(\"player-state-changed\",(t=>{e.emit(vM.VIDEO_PLAY_STATE_CHANGED,eb($C({},t),{userId:\"\",streamType:\"main\"}))})),n&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),yield e._updateVideoPlayOption({view:i,playOption:a,track:o}),e._localVideoTrack=o,e._localVideoConfig=eb($C({},t),{view:i,publish:n})}()}))}updateLocalVideo(e){return ab(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:n,option:r}=e,o={};if(r&&(nO(r.profile)||(rO(r.profile)?wN[r.profile]&&this._localVideoTrack.setProfile(wN[r.profile]):this._localVideoTrack.setProfile(r.profile),(!r.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(r.cameraId))&&nO(r.useFrontCamera)&&this._localVideoTrack.applyProfile()),r.cameraId?yield this._localVideoTrack.switchDevice(r.cameraId):nO(r.useFrontCamera)?nO(r.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(r.videoTrack)):yield this._localVideoTrack.switchDevice(r.useFrontCamera?LN.FACING_MODE_USER:LN.FACING_MODE_ENVIRONMENT),nO(r.fillMode)||(o.objectFit=r.fillMode),nO(r.mirror)||(o.mirror=r.mirror),r.qosPreference&&this._localVideoTrack.mediaTrack)){let e=yM(r.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e}this._room.isJoined&&!nO(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),nO(n)||this._localVideoTrack.setMute(n),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),CO(this._localVideoConfig,e)}))}stopLocalVideo(){return ab(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),IP(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localScreenTrack)return void e._log.warn(\"screen share is already started\");let{view:i=null,publish:n=!0,option:r}=t,o=new cL(e._room.videoManager);o.on(\"4\",(t=>{let i;t.error&&(i=tM.convertFrom(t.error)),e.emit(vM.PUBLISH_STATE_CHANGED,eb($C({},t),{error:i}))}));let s=null;o.setMediaType(2);let a={},c={};r&&(nO(r.profile)||(rO(r.profile)?PN[r.profile]&&o.setProfile(PN[r.profile]):o.setProfile(r.profile)),r.systemAudio&&(a.systemAudio=!0,a.echoCancellation=r.echoCancellation,a.noiseSuppression=r.noiseSuppression,a.autoGainControl=r.autoGainControl),nO(r.fillMode)||(c.objectFit=r.fillMode),r.videoTrack&&(a.videoTrack=r.videoTrack),r.audioTrack&&(a.audioTrack=r.audioTrack));let l=yield o.capture(a);if(null!=r&&r.qosPreference){let e=yM(r.qosPreference);o.mediaTrack.contentHint=e}if(o.mediaTrack.addEventListener(LN.ENDED,(()=>{e._stopScreenShare(),e.emit(vM.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(s=new lL(e._room.audioManager),s.setInputMediaStreamTrack(l.getAudioTracks()[0])),SP(o,o).add(\"player-state-changed\",(t=>{e.emit(vM.VIDEO_PLAY_STATE_CHANGED,eb($C({},t),{userId:\"\",streamType:\"sub\"}))})),n&&e._room.isJoined){let t=[o];s&&t.push(s),e._room.publish(...t).catch((()=>{}))}yield e._updateVideoPlayOption({view:i,playOption:c,track:o}),e._localScreenTrack=o,e._localScreenAudioTrack=s,e._localScreenConfig=eb($C({},t),{view:i,publish:n})}()}))}updateScreenShare(e){return ab(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:n}=e,r={};if(n&&(nO(n.fillMode)||(r.objectFit=n.fillMode),n.qosPreference)){let e=yM(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}this._room.isJoined&&!nO(i)&&(i&&!this._localScreenConfig.publish&&this._room.publish(this._localScreenTrack).catch((()=>{})),this._localScreenConfig.publish&&!i&&this._room.unpublish(this._localScreenTrack).catch((()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:r,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),CO(this._localScreenConfig,e)}))}stopScreenShare(){return ab(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return ab(this,null,(function*(){let{view:t,userId:i,streamType:n,option:r}=e,o=\"\".concat(i,\"_\").concat(n);if(this._remoteVideoConfigMap.has(o))return void this._log.warn(\"remote video has already started. userId:\".concat(i,\", streamType:\").concat(n));let s=this._room.remotePublishedUserMap.get(i);if(!s)return;let a={},c=\"main\"===n?s.remoteVideoTrack:s.remoteAuxiliaryTrack;r&&(nO(r.fillMode)||(a.objectFit=r.fillMode),nO(r.mirror)||(a.mirror=r.mirror),\"main\"===n&&!nO(r.small)&&this._room.changeType(r.small,c.user)),yield this._room.subscribe(c),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._remoteVideoConfigMap.set(o,e)}))}updateRemoteVideo(e){return ab(this,null,(function*(){let{view:t,userId:i,streamType:n,option:r}=e,o=\"\".concat(i,\"_\").concat(n);if(!this._remoteVideoConfigMap.has(o)||!this._room.remotePublishedUserMap.has(i))return;let s={};r&&(nO(r.fillMode)||(s.objectFit=r.fillMode),nO(r.mirror)||(s.mirror=r.mirror));let a=null,c=this._room.remotePublishedUserMap.get(i);\"main\"===n&&(null==c?void 0:c.muteState.hasVideo)&&(a=c.remoteVideoTrack),\"sub\"===n&&(null==c?void 0:c.muteState.hasAuxiliary)&&(a=c.remoteAuxiliaryTrack);let l=this._remoteVideoConfigMap.get(o);a&&(\"main\"===n&&r&&!nO(r.small)&&this._room.changeType(r.small,a.user),yield this._updateVideoPlayOption({view:t,playOption:s,track:a,prevConfig:l})),CO(l,e)}))}stopRemoteVideo(e){return ab(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return ab(this,null,(function*(){let i=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:t,remoteVideoTrack:r,remoteAuxiliaryTrack:o}=n;\"main\"===e.streamType&&(r.stop(),t.hasVideo&&i.push(r)),\"sub\"===e.streamType&&(o.stop(),t.hasAuxiliary&&i.push(o))}for(let e of i)t&&(yield this._room.unsubscribe(e));this._remoteVideoConfigMap.delete(\"\".concat(e.userId,\"_\").concat(e.streamType))}))}muteRemoteAudio(e,t){return ab(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})}}startPlugin(e,t){return ab(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return ab(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return ab(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){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 ab(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 n=this._room.remotePublishedUserMap.get(t);if(!n)return;let r={};i&&(nO(i.volume)||(r.volume=i.volume));let o=n.remoteAudioTrack;yield this._room.subscribe(o),yield this._updateAudioPlayOption({playOption:r,track:o}),this._remoteAudioConfigMap.set(t,e)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return ab(this,null,(function*(){let i=this._room.remotePublishedUserMap.get(e.userId);i&&(i.remoteAudioTrack.stop(),i.muteState.hasAudio&&t&&(yield this._room.unsubscribe(i.remoteAudioTrack))),this._remoteAudioConfigMap.delete(\"\".concat(e.userId))}))}_updateVideoPlayOption(e){return ab(this,arguments,(function(e){let{view:t,playOption:i,track:n,prevConfig:r}=e;return function*(){if(nO(t)&&r&&r.view&&!SO(i)){let e;e=cO(r.view)?r.view:bO(r.view),e&&(yield n.play(e,i))}if(!nO(t)){let e;e=cO(t)?t:bO(t),e?yield n.play(e,i):n.stop()}}()}))}_updateAudioPlayOption(e){return ab(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:n}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t)}catch(cN){}nO(t.muted)||i.setPlayerMute(t.muted),nO(t.volume)||i.setAudioVolume(t.volume/100)}()}))}_checkTrackToPublish(){var e,t,i;let n=[];if((null==(e=this._localAudioConfig)?void 0:e.publish)&&this._localAudioTrack&&n.push(this._localAudioTrack),(null==(t=this._localVideoConfig)?void 0:t.publish)&&this._localVideoTrack&&n.push(this._localVideoTrack),null!=(i=this._localScreenConfig)&&i.publish&&(this._localScreenTrack&&n.push(this._localScreenTrack),this._localScreenAudioTrack&&n.push(this._localScreenAudioTrack)),0!==n.length)return this._room.publish(...n).catch((()=>{}))}_handleReceiveMode(){this._room.autoReceiveAudio&&SP(this,this).add(vM.REMOTE_AUDIO_AVAILABLE,(e=>ab(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&&SP(this,this).add(vM.REMOTE_VIDEO_AVAILABLE,(e=>{let{userId:t,streamType:i}=e,n=this._room.remotePublishedUserMap.get(t);n&&(\"main\"===i?this._room.subscribe(n.remoteVideoTrack).catch((()=>{})):\"sub\"===i&&this._room.subscribe(n.remoteAuxiliaryTrack).catch((()=>{})))}))}_exitRoom(){return ab(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=>{IP(e.remoteAudioTrack),IP(e.remoteVideoTrack),IP(e.remoteAuxiliaryTrack)})),IP(this)}))}_stopScreenShare(){return ab(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(),IP(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){HO.setLogLevel(e),nO(t)||(t?HO.enableUploadLog():HO.disableUploadLog())}static isSupported(){return aw()}static getCameraList(){return JP()}static getMicrophoneList(){return WP()}static getSpeakerList(){return KP()}static setCurrentSpeaker(e){return ab(this,null,(function*(){(yield KP()).forEach((t=>{t.deviceId===e&&(FM.forEach((i=>{i.setCurrentSpeaker(e),i.emit(vM.DEVICE_CHANGED,{type:\"speaker\",action:\"active\",device:t})})),BM=t)}))}))}},jM=HM;ob(jM,\"_loggerManager\",HO),ob(jM,\"EVENT\",vM),ob(jM,\"ERROR_CODE\",QL),ob(jM,\"TYPE\",qL),ob(jM,\"frameWorkType\",30),rb([CM(dM.TRTC.enterRoom),EM(\"room\",((e,t)=>{let[i]=e,[n]=t;return(i.roomId||i.strRoomId)===(n.roomId||n.strRoomId)&&i.userId===n.userId&&i.sdkAppId===n.sdkAppId})),iL((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t).catch((e=>{throw IP(this),e}))})),DM()],jM.prototype,\"enterRoom\",1),rb([DM()],jM.prototype,\"exitRoom\",1),rb([CM(dM.TRTC.switchRole),SM(\"room\",{merge:(e,t)=>t}),DM()],jM.prototype,\"switchRole\",1),rb([DM()],jM.prototype,\"destroy\",1),rb([CM(dM.TRTC.startLocalAudio),EM(\"audio\",((e,t)=>{let[i]=e,[n]=t;var r,o;return(null==(r=null==i?void 0:i.option)?void 0:r.microphoneId)===(null==(o=null==n?void 0:n.option)?void 0:o.microphoneId)})),DM()],jM.prototype,\"startLocalAudio\",1),rb([CM(dM.TRTC.updateLocalAudio),SM(\"audio\",{debounce:{delay:200,getKey:()=>\"\".concat(UM,\"-localAudio\"),isNeedToDebounce:e=>{var t;return!nO(null==(t=e.option)?void 0:t.captureVolume)}}}),DM()],jM.prototype,\"updateLocalAudio\",1),rb([IM(\"audio\"),DM()],jM.prototype,\"stopLocalAudio\",1),rb([CM(dM.TRTC.startLocalVideo),EM(\"video\",((e,t)=>{let[i]=e,[n]=t;var r,o;return(null==(r=null==i?void 0:i.option)?void 0:r.cameraId)===(null==(o=null==n?void 0:n.option)?void 0:o.cameraId)})),DM()],jM.prototype,\"startLocalVideo\",1),rb([CM(dM.TRTC.updateLocalVideo),SM(\"video\"),DM()],jM.prototype,\"updateLocalVideo\",1),rb([IM(\"video\"),DM()],jM.prototype,\"stopLocalVideo\",1),rb([CM(dM.TRTC.startScreenShare),EM(\"screen\",(()=>!0)),DM()],jM.prototype,\"startScreenShare\",1),rb([CM(dM.TRTC.updateScreenShare),SM(\"screen\"),DM()],jM.prototype,\"updateScreenShare\",1),rb([DM()],jM.prototype,\"stopScreenShare\",1),rb([CM(dM.TRTC.startRemoteVideo),EM((e=>\"v\".concat(e.userId).concat(e.streamType)),(()=>!0)),DM({getRemoteId:e=>\"\".concat(e.userId,\"_\").concat(e.streamType)})],jM.prototype,\"startRemoteVideo\",1),rb([CM(dM.TRTC.updateRemoteVideo),SM((e=>\"v\".concat(e.userId).concat(e.streamType))),DM({getRemoteId:e=>\"\".concat(e.userId,\"_\").concat(e.streamType)})],jM.prototype,\"updateRemoteVideo\",1),rb([CM(dM.TRTC.stopRemoteVideo),iL((e=>function(t){return ab(this,null,(function*(){if(\"*\"===t.userId){let e=[];return this._room.remotePublishedUserMap.forEach((t=>{this._remoteVideoConfigMap.has(\"\".concat(t.userId,\"_\",\"main\"))&&e.push(this.stopRemoteVideo({streamType:\"main\",userId:t.userId}).catch((()=>{}))),this._remoteVideoConfigMap.has(\"\".concat(t.userId,\"_\",\"sub\"))&&e.push(this.stopRemoteVideo({streamType:\"sub\",userId:t.userId}).catch((()=>{})))})),Promise.all(e)}return e.call(this,t)}))})),DM({getRemoteId:e=>\"\".concat(e.userId,\"_\").concat(e.streamType)})],jM.prototype,\"stopRemoteVideo\",1),rb([IM((e=>\"v\".concat(e.userId).concat(e.streamType)))],jM.prototype,\"_stopRemoteVideo\",1),rb([CM(...dM.TRTC.muteRemoteAudio),DM({getRemoteId:e=>e})],jM.prototype,\"muteRemoteAudio\",1),rb([bM(...dM.TRTC.setRemoteAudioVolume),function(e,t){return iL(((i,n)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o0&&clearTimeout(c);let l=window.setTimeout((()=>{i.apply(this,r)}),e);RM.has(this)?null==(a=RM.get(this))||a.set(t(...r),l):RM.set(this,new Map([[t(...r),l]]))}))}(200,(e=>e)),DM({getRemoteId:e=>e})],jM.prototype,\"setRemoteAudioVolume\",1),rb([OM(\"start\"),EM(((e,t)=>e.getAlias()+e.getGroup(t))),DM({namePrefix:e=>e.getName()})],jM.prototype,\"startPlugin\",1),rb([OM(\"update\"),SM(((e,t)=>e.getAlias()+e.getGroup(t))),DM({namePrefix:e=>e.getName()})],jM.prototype,\"updatePlugin\",1),rb([OM(\"stop\"),IM(((e,t)=>e.getAlias()+e.getGroup(t))),DM({namePrefix:e=>e.getName()})],jM.prototype,\"stopPlugin\",1),rb([bM(...dM.TRTC.enableAudioVolumeEvaluation)],jM.prototype,\"enableAudioVolumeEvaluation\",1),rb([EM((e=>\"a\".concat(e.userId)),(()=>!0))],jM.prototype,\"_startRemoteAudio\",1),rb([iL((e=>function(t){return ab(this,null,(function*(){return\"*\"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(eb($C({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),IM((e=>\"a\".concat(e.userId)))],jM.prototype,\"_stopRemoteAudio\",1),rb([IM(\"room\")],jM.prototype,\"_exitRoom\",1),rb([IM(\"screen\")],jM.prototype,\"_stopScreenShare\",1),rb([CM(dM.TRTC.sendSEIMessage),function(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:n}=e;return iL(((e,r)=>{let o=new Map;return xO.on(FO.ROOM_DESTROY,(e=>{let{room:t}=e;return o.delete(t)})),function(){let s=o.get(this);for(var a=arguments.length,c=new Array(a),l=0;l1e3&&(s.timestamp=Date.now(),s.callCountInSecond=0,s.totalSizeInSecond=0),n&&(s.totalSizeInSecond+=n(...c)),0!==s.timestamp&&Date.now()-s.timestamp<1e3&&(s.callCountInSecond>=t||s.totalSizeInSecond>i))throw new gb({code:mb.INVALID_OPERATION,message:qO({key:JO.CALL_FREQUENCY_LIMIT,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>i,name:r,timesInSecond:t,maxSizeInSecond:i}})});s.callCountInSecond++,e.call(this,...c)}}))}({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var e=arguments.length,t=new Array(e),i=0;i0&&this.room.enableSPC&&(this.keepAlive=!0,NV.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=HO.createLogger({id:\"ws\",userId:this.userId,sdkAppId:this.sdkAppId})}get urlParam(){return\"?sdkAppId=\".concat(encodeURIComponent(this.sdkAppId),\"&userId=\").concat(encodeURIComponent(this.userId),\"&userSig=\").concat(encodeURIComponent(this.userSig),\"&keepAlive=\").concat(encodeURIComponent(Number(this.keepAlive)))}get _urlWithParam(){return\"\".concat(this.url).concat(this.urlParam)}get _backupUrlWithParam(){return\"\".concat(this.backupUrl).concat(this.urlParam)}get isConnected(){return this._currentState===eV}get isConnecting(){return this._currentState===$M}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState===eV&&Date.now()-this._lastMessageTime<12e3}connect(e){return this.isConnected?Promise.resolve():new Promise(((t,i)=>{this._prevTime<0&&(this._prevTime=fO()),this._log.info(\"connect to \".concat(this.url).concat(e?\" timeout: \".concat(e):\"\",\" keepAlive: \").concat(Number(this.keepAlive))),this.emitConnectionStateChanged($M),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);let n=-1;e&&(n=setTimeout((()=>{this.close(),i(new gb({code:mb.JOIN_ROOM_FAILED,message:\"join room timeout\"}))}),e)),this.once(QM,(()=>{clearTimeout(n),t()})),this.once(XM,(e=>{clearTimeout(n),i(e)}))}))}tryConnectBackup(){this._backupSocket||(this.unbindAndCloseSocket(LN.MAIN),this._log.debug(\"try to connect to url: \".concat(this._backupUrlWithParam)),this._backupSocket=new WebSocket(this._backupUrlWithParam),this.bindSocket(this._backupSocket))}bindSocket(e){e.onopen=this.onopen.bind(this),e.onclose=this.onclose.bind(this),e.onerror=this.onerror.bind(this),e.onmessage=this.onmessage.bind(this)}unbindSocket(e){this.clearBackupTimer(),e.onopen=()=>{},e.onclose=()=>{},e.onerror=()=>{},e.onmessage=()=>{}}unbindAndCloseSocket(e){if(e===LN.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(sD){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(sD){}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(LN.BACKUP),this._socketInUse=this._socket):(this.unbindAndCloseSocket(LN.MAIN),this._socketInUse=this._backupSocket),this.emitConnectionStateChanged(eV),this.emit(QM))}onclose(e){let{url:t}=e.target,i=e.target===this._socketInUse;if(this._log.info(\"websocket[\".concat(t,\" InUse: \").concat(i,\"] is closed with code: \").concat(e.code)),i&&(this.emitConnectionStateChanged(ZM),!e.wasClean||1e3!==e.code)){this._log.warn(\"onclose code:\".concat(e.code,\" reason:\").concat(e.reason)),this._log.warn(\"close current websocket and schedule a reconnect timeout\"),this._socketInUse.onclose=()=>{},this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this._socket=null,this._backupSocket=null,this._socketInUse=null,this.reconnect(t?LN.BACKUP:LN.MAIN)}}onerror(e){let{url:t}=e.target;if(this._log.error(\"websocket[\".concat(t,\"] error observed\")),this.isConnected){if(e.target===this._socketInUse){this.unbindAndCloseSocket(LN.MAIN),this.unbindAndCloseSocket(LN.BACKUP);let e=this._socketInUse===this._socket;this._socketInUse=null,this.reconnect(e?LN.BACKUP:LN.MAIN)}}else this.isReconnecting||xO.emit(FO.API_SUCCESS_RATE,{room:this.room,apiName:\"WebsocketConnect\",error:new Error(\"ws onerror\")}),e.target==this._socket?(this.unbindAndCloseSocket(LN.MAIN),this.reconnect(LN.BACKUP)):(this.unbindAndCloseSocket(LN.BACKUP),this.reconnect(LN.MAIN))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=wO(e.data);let t=JSON.parse(e.data),{cmd:i,data:n}=t,r=Object.values(tV),o=Object.keys(tV)[r.indexOf(i)],s=nV[o];switch(iV.includes(i)||(this._log.debug(\"received \".concat(i,\" msg: \").concat(e.data)),s&&this._log.info(\"Received event: [ \".concat(s,\" ]\"))),i){case tV.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,this._signalInfo.tinyId=t.tinyId,n.svrTime&&function(e){Tb=e-(new Date).getTime();let t=new Date;t.setTime(e),HO.info(\"baseTime from server: \".concat(t,\" offset: \").concat(Tb))}(n.svrTime),this._log.info(\"ChannelSetup Success\"),xO.emit(FO.API_SUCCESS_RATE,{room:this.room,apiName:\"WebsocketConnect\",cost:fO()-this._prevTime}),this._prevTime=-1,this.emit(YM,{signalInfo:this._signalInfo});else{let e=new gb({code:mb.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:qO({key:JO.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(\"\".concat(t.code,\", \").concat(t.message)),this.close(),xO.emit(FO.API_SUCCESS_RATE,{room:this.room,apiName:\"WebsocketConnect\",error:e}),this.emit(zM,e)}break;case tV.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._log.info(\"signalIp:\".concat(this._signalInfo.signalIp,\" clientIp:\").concat(this._signalInfo.clientIp,\" relayIp: \").concat(this._signalInfo.relayIp))),this.emit(s,{data:t});break;case tV.CHANNEL_RECONNECT_RESULT:0===t.code?(this._log.warn(\"reconnect success\"),this.stopReconnection(),xO.emit(FO.API_SUCCESS_RATE,{room:this.room,apiName:\"WebsocketReconnect\",cost:fO()-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.emit(s,{data:t})}}reconnect(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:LN.MAIN;if(!this.room.isJoined&&this.keepAlive)return void this.close();if(this.isReconnecting)return;if(this._reconnectionCount>=aD){this._log.warn(\"SDK has tried reconnect signal channel for \".concat(aD,\" times, but all failed. please check your network\"));let e=new gb({code:mb.SIGNAL_CHANNEL_RECONNECTION_FAILED,message:qO({key:JO.SIGNAL_CHANNEL_RECONNECTION_FAILED})});return xO.emit(FO.API_SUCCESS_RATE,{room:this.room,apiName:\"WebsocketReconnect\",error:e}),void this.emit(XM,e)}this._reconnectionCount++,this._log.warn(\"reconnect \".concat(e,\" [\").concat(this._reconnectionCount,\"/\").concat(aD,\"]\"));let t=this.getReconnectionUrl(e);this.emitConnectionStateChanged($M),this._prevTime<0&&(this._prevTime=fO()),e===LN.MAIN?(this._socket=new WebSocket(t),this.bindSocket(this._socket)):(this._backupSocket=new WebSocket(t),this.bindSocket(this._backupSocket));let i=eO(this._reconnectionCount);this._reconnectionTimer=setTimeout((()=>{this._log.warn(\"reconnect \".concat(e,\" timeout(\").concat(i/1e3,\"s), try again\")),this.clearReconnectionTimer(),this.unbindAndCloseSocket(LN.MAIN),this.unbindAndCloseSocket(LN.BACKUP),this.reconnect(e===LN.MAIN?LN.BACKUP:LN.MAIN)}),i)}get isReconnecting(){return-1!==this._reconnectionTimer}getReconnectionUrl(e){let t=e===LN.MAIN?this._urlWithParam:this._backupUrlWithParam;if(this._signalInfo.tinyId&&-1===t.indexOf(\"&rc=1\")){let{roomId:e,useStringRoomId:i}=this.room;t+=\"&rc=1&relayInnerIp=\".concat(this._signalInfo.relayInnerIp,\"&relayOuterIp=\").concat(this._signalInfo.relayIp,\"&relayPort=\").concat(this._signalInfo.relayPort,\"&roomId=\").concat(e,\"&useStringRoomId=\").concat(i)}return t}send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let i={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},n=JSON.stringify(i);return this._socketInUse.send(n),this.bytesSent+=wO(n),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:n=5e3,responseCommand:r,commandDesc:o,enableLog:s=!0}=e;return new Promise(((e,a)=>{let c=setTimeout((()=>{this.off(r,l);let e=new gb({code:mb.API_CALL_TIMEOUT,message:qO({key:JO.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),a(e)}),n),l=t=>{t.data.seq===d&&(clearTimeout(c),this.off(r,l),e(t))};this.on(r,l);let d=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:n=0,retryTimeout:r=0}=e;return MO({retryFunction:this.sendWaitForResponse,onRetrying:e=>{this._log.warn(\"\".concat(t||i,\" timeout observed, retrying [\").concat(e,\"/\").concat(n,\"]\"))},settings:{retries:n,timeout:r},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this.isReconnecting&&(this._reconnectionCount=0,this.clearReconnectionTimer())}close(){this._log.info(\"closed\"),NV.delete(this),this.clearBackupTimer(),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:\"\",signalIp:\"\",relayIp:\"\",relayInnerIp:\"\",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this.unbindAndCloseSocket(LN.MAIN),this.unbindAndCloseSocket(LN.BACKUP),this.emitConnectionStateChanged(ZM)}stopKeepAliveIn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info(\"stopKeepAlive in \".concat(e,\"s\"));let t=setTimeout((()=>{this.keepAlive=!1,this._log.info(\"close due to not used \".concat(e,\"s\")),this.close()}),1e3*e),i=e=>{e instanceof xw&&\"join\"===e.action&&(this._log.info(\"stopKeepAlive clear timeout\"),clearTimeout(t),this.room.off(Gw.STATECHANGED,i))};this.room.on(Gw.STATECHANGED,i)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(\"\".concat(this._currentState,\" -> \").concat(e)),this.emit(qM,{prevState:this._currentState,state:e}),this._currentState=e)}},OV=nb(cb()),wV=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=[],n=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===n&&(i.push(3),n=0),0==e?n++:n=0,i.push(e);break;default:n=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let r=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=r}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],n=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:n++,i.push(this.dataView.getInt8(o));break;case 3:2!==n&&i.push(this.dataView.getInt8(o)),n=0;break;default:i.push(this.dataView.getInt8(o)),n=0}let r=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=r}get isSEI(){return 6===this.dataView.getUint8(4)}get seiPayloadStartIndex(){let e=6;for(let t=6;t{}))}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)===LN.VIDEO?this.isRunning?this.restart(e):this.start(e):this.pipeSenderOrReceiver(e))}))}catch(HL){this._log.warn(HL)}}pipeSenderOrReceiver(e){let{readable:t,writable:i}=e.createEncodedStreams(),n=new AbortController;this._abortMap.set(e,n),t.pipeTo(i,n).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,n=new DataView(e);for(let r=0;r0&&!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)),n=i.reduce(((e,t)=>e+t.dataView.byteLength),0),r=new ArrayBuffer(n+e.data.byteLength),o=new DataView(r),s=new DataView(e.data),a=0;for(let e=0;e{this.onSEIMessage({seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer})}))}}catch(sD){this._log.warn(sD)}t.enqueue(e)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(t/255),n=t%255,r=[];r.push(0,0,0,1,6,this._seiPayloadType);for(let s=0;s=3&&xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:\"PeerConnectionReconnect\",error:sN}),sN}}))}initialize(){let e={encodedInsertableStreams:this._enableSEI&&kw,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),VV.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 gb({code:mb.API_CALL_ABORTED,message:\"connection closed\"}))}getDTLSTransportState(){if(!this._peerConnection)return tD;let e=null;if(this._isUplink){if(!Ew()||0===this._peerConnection.getSenders().length)return tD;e=this._peerConnection.getSenders()[0].transport}else{if(!Tw()||0===this._peerConnection.getReceivers().length)return tD;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:tD}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===iD.CONNECTING&&this.emitConnectionStateChangedEvent(\"CONNECTING\"),e.target.connectionState===iD.FAILED||e.target.connectionState===iD.CLOSED){let n=\"connection \".concat(e.target.connectionState,\". ICE Transport state: \").concat(t,\", DTLS Transport state: \").concat(i),r=new gb({message:n,code:mb.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent(\"DISCONNECTED\"),this.startReconnection(),this._isErrorObserved||this._emitter.emit(\"error\",r)}(e.target.connectionState===iD.CONNECTED||e.target.connectionState===iD.COMPLETED)&&(this.logSelectedCandidate(),Qw.logSuccessEvent({userId:this._room.userId,eventType:cD.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent(\"CONNECTED\"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(\"CONNECTED\"===e?(LV=0,MV=!1,xV=!0,VV.add(this)):VV.delete(this),xO.emit(FO.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit(\"connection-state-changed\",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return ab(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(uw(t)){let i=e.get(t.localCandidateId),n=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)),n&&(this._log.info(\"remote candidate: \".concat(n.candidateType,\" \").concat(n.protocol,\":\").concat(n.ip||n.address,\":\").concat(n.port)),this._remoteAddress=\"\".concat(n.protocol,\":\").concat(n.ip||n.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),r(),e())},n=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),r(),t(new gb({code:mb.API_CALL_ABORTED,message:qO({key:JO.CONNECTION_ABORTED,data:\"leave room\"})})))},r=()=>{xO.off(FO.LEAVE_SUCCESS,n,this),this._emitter.off(\"connection-state-changed\",i,this)},o=setTimeout((()=>{r();let e=new gb({code:mb.API_CALL_TIMEOUT,message:\"connection timeout\"});LV+=1,(e=>LV>2&&!MV&&0===VV.size&&e)(this._signalChannel.isConnected)&&(this._log.warn(\"firewall restrition\"),MV=!0,this._emitter.emit(\"firewall-restriction\")),t(e)}),SD);xO.on(FO.LEAVE_SUCCESS,n,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>=oD()){this._log.warn(\"SDK has tried reconnect for \".concat(this._reconnectionCount,\" times, but all failed, please check your network\")),this.stopReconnection();let e=new gb({code:this._isUplink?mb.UPLINK_RECONNECTION_FAILED:mb.DOWNLINK_RECONNECTION_FAILED,message:qO({key:this._isUplink?JO.UPLINK_RECONNECTION_FAILED:JO.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent(\"DISCONNECTED\"),this._emitter.emit(\"error\",e),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(\"reconnect() trying [\".concat(this._reconnectionCount,\"]\")),1):(this._log.warn(\"reconnect() signal channel is not connected, suspend reconnection until signal is connected\"),this._signalChannel.once(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\"))}},FV=nb(hb()),BV=function(e){return FV.default.parse(e)},HV=function(e){return FV.default.write(e)};function jV(e){return Object.keys(e).filter((t=>e[t]))}var GV=class extends UV{constructor(e){super(eb($C({},e),{isUplink:!1})),ob(this,\"_flag\",0),ob(this,\"role\",\"anchor\"),ob(this,\"remoteAudioTrack\"),ob(this,\"remoteVideoTrack\"),ob(this,\"remoteAuxiliaryTrack\"),ob(this,\"ssrc\",{audio:0,video:0,auxiliary:0}),ob(this,\"_isSDPExchanging\",!1),this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new RL(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new CL(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new bL(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 IO(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,n;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(n=this.remoteAuxiliaryTrack)||n.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===LN.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent(\"DISCONNECTED\"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,i;let n=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&n!==e&&(null==(t=this.remoteVideoTrack)||t.emit(\"connection-state-changed\",{prevState:n,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit(\"connection-state-changed\",{prevState:n,state:e})),r}onTrack(e){let t=e.streams[0],{track:i}=e,n=t.id===WN?LN.MAIN:LN.AUXILIARY;this._log.debug(\"ontrack \".concat(n,\" \").concat(i.kind));let r=LN.AUDIO;i.kind===LN.VIDEO&&(r=n===LN.MAIN?LN.VIDEO:LN.AUXILIARY);let o=this.remoteAudioTrack;r===LN.VIDEO?o=this.remoteVideoTrack:r===LN.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}addRRTRLine(e){let t=e.split(\"\\r\\n\"),i=new Map;t.forEach(((e,n)=>{/^a=rtcp-fb:/.test(e)&&t[n+1]&&!/^a=rtcp-fb:/.test(t[n+1])&&i.set(n+1,\"\".concat(e.match(/^a=rtcp-fb:\\d+/)[0],\" rrtr\"))}));let n=[...i];for(let r=0;r{e.type===LN.VIDEO&&e.fmtp.forEach((e=>{e.config+=\";sps-pps-idr-in-keyframe=1\"}))})),HV(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=BV(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),HV(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return ab(this,null,(function*(){var i,n;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===iD.NEW||(null==(n=this._peerConnection)?void 0:n.connectionState)===iD.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info(\"subscribe \".concat(t,\" \").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let t=\"subscribe_change\";Object.values(e).find((e=>!0===e))||(t=\"unsubscribe\"),yield this.sendSubscription(t,e)}else this.initialize(),yield this.connect(e)}catch(cN){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(\"\".concat(cN.message,\" \").concat(JSON.stringify(this.muteState))),new gb({code:mb.REMOTE_STREAM_NOT_EXIST,message:\"remote user \".concat(this.userId,\" unpublished stream\")})):cN}}))}unsubscribe(e){return ab(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:n}=e;return function*(){if(\"CONNECTED\"===t._currentState&&(\"main\"===n&&!t.isMainStreamSubscribed||\"auxiliary\"===n&&!t.isAuxStreamSubscribed))return void t._log.info(\"\".concat(n,\" stream already unsubscribed\"));let e=$C({},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 r=\"subscribe_change\";Object.values(e).find((e=>!0===e))||(r=\"unsubscribe\"),t._log.info(\"\".concat(\"unsubscribe\"===r?r:\"subscribe\",\" \").concat(n,\" [\").concat(jV(e),\"]\")),yield t.sendSubscription(r,e),\"unsubscribe\"===r&&(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},n=pV,r=nV.UNSUBSCRIBE_RESULT;return\"subscribe_change\"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=_V,r=nV.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:i,responseCommand:r,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new gb({code:i.code,message:qO({key:JO.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(t),yield e.waitForPeerConnectionConnected()}catch(sD){throw e.closePeerConnection(!0),sD}}()}))}exchangeSDP(e){return ab(this,null,(function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info(\"createOffer success, sending offer\");let{type:t,sdp:i}=this._peerConnection.localDescription,n={type:t,sdp:i,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},r=yield this._signalChannel.sendWaitForResponse({command:hV,commandDesc:\"exchange sdp\",data:n,responseCommand:nV.SUBSCRIBE_RESULT,timeout:uD});if(!this._peerConnection){let e=new gb({code:mb.INVALID_OPERATION,message:qO({key:JO.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(r),this._isSDPExchanging=!1}catch(sD){throw this._isSDPExchanging=!1,sD}}))}createOffer(){return ab(this,null,(function*(){let e={voiceActivityDetection:!1};Iw()&&this._sdpSemantics===hD?(this._peerConnection.addTransceiver(LN.AUDIO,{direction:MN.RECVONLY}),this._peerConnection.addTransceiver(LN.VIDEO,{direction:MN.RECVONLY}),this._peerConnection.addTransceiver(LN.VIDEO,{direction:MN.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield sw();e||(this._log.warn(\"remove h264 desc from sdp\"),t.sdp=function(e){let t=BV(e);return t.media.forEach((e=>{var t,i;if(e.type===LN.VIDEO){let n=new Set;e.rtp.forEach((e=>{let{payload:t,codec:i}=e;return\"H264\"===i&&n.add(t)})),e.fmtp.forEach((e=>{let{payload:t,config:i}=e,r=i.match(/apt=(\\d+)/);r&&r[1]&&n.has(Number(r[1]))&&n.add(t)}));let r=e=>{let{payload:t}=e;return!n.has(t)};e.rtp=e.rtp.filter(r),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(r),e.fmtp=e.fmtp.filter(r),e.payloads=null==(i=e.payloads)?void 0:i.split(\" \").filter((e=>!n.has(Number(e)))).join(\" \")}})),HV(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=BV(e);return t.media.forEach((e=>{e.type===LN.AUDIO&&e.fmtp.forEach((e=>{e.config+=\";sprop-stereo=1;stereo=1\"}))})),HV(t)}(t.sdp),this._sdpSemantics===hD&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)}))}onSubscribeResult(e){return ab(this,null,(function*(){let{code:t,message:i=\"\"}=e&&e.data||{},{type:n,sdp:r}=e&&e.data&&e.data.data||{};if(t===_D)throw new gb({code:mb.NOT_SUPPORTED_H264,message:qO({key:JO.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new gb({code:t,message:qO({key:JO.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug(\"accept remote answer: \".concat(r)),yield this._peerConnection.setRemoteDescription({type:n,sdp:r}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=e=>{this._emitter.emit(\"sei-message\",eb($C({},e),{userId:this.userId}))}),this.updateSSRC(r)}catch(qx){throw this._log.error(qx),qx}}))}updateSSRC(e){try{BV(e).media.forEach((e=>{if(e.ssrcs)if(e.type===LN.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(WN)}));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(WN)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(JN)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(sD){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:\"\"}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:\"\"}reconnect(){return ab(this,null,(function*(){if(!(sb(GV.prototype,this,\"beforeReconnect\").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn(\"reconnect() success\")}catch(sD){let t=eO(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}},WV=GV;rb([iL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n{let r=e=>{this._emitter.off(\"closed\",r),n(new gb({code:mb.API_CALL_ABORTED,message:qO({key:JO.CONNECTION_ABORTED,data:e})}))};this._emitter.on(\"closed\",r),e.apply(this,i).then(t,n).finally((()=>{this._emitter.off(\"closed\",r)}))}))}))],WV.prototype,\"subscribe\",1),rb([tL(UV.prototype.afterConnect),eL(UV.prototype.beforeConnect)],WV.prototype,\"connect\",1);var JV=WV,KV={voiceActivityDetection:!1},YV=class extends UV{constructor(e){super(eb($C({},e),{isUplink:!0})),ob(this,\"localMainAudioTrack\",null),ob(this,\"localMainVideoTrack\",null),ob(this,\"localAuxAudioTrack\",null),ob(this,\"localAuxVideoTrack\",null),ob(this,\"ssrc\",{audio:0,video:0,small:0,auxiliary:0}),ob(this,\"_isPublishingAux\",!1),ob(this,\"_publishingLocalAudioTrack\"),ob(this,\"_publishingLocalVideoTrack\"),ob(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}),ob(this,\"_audioManager\"),this._audioManager=e.audioManager}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,n;let r={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(Sw()?(r.audio=!(null==(e=o[0])||!e.track),r.bigVideo=!(null==(t=o[1])||!t.track),r.smallVideo=!(null==(i=o[2])||!i.track),r.auxVideo=!(null==(n=o[3])||!n.track)):o.forEach((e=>{e.track&&(e.track.kind===LN.AUDIO?r.audio=!0:(r.bigVideo=!0,this._room.videoManager.hasSmall&&(r.smallVideo=!0)))})))}return r}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent(\"DISCONNECTED\")}installEvents(){this._emitter.listeners(\"connection-state-changed\").includes(this.handleConnectionStateChange)||this._emitter.on(\"connection-state-changed\",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off(\"connection-state-changed\",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var i,n,r;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit(\"connection-state-changed\",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit(\"connection-state-changed\",{prevState:o,state:e}),null==(n=this.localAuxVideoTrack)||n.emit(\"connection-state-changed\",{prevState:o,state:e}),null==(r=this._publishingLocalVideoTrack)||r.emit(\"connection-state-changed\",{prevState:o,state:e}))),s}publish(e){return ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,isAuxiliary:r}=e;return function*(){var e;let o;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),n&&(t._publishingLocalVideoTrack=n),t._isPublishingAux=r,n&&!r&&n.small&&(o=t._room.videoManager.smallTrack),t.sendMediaSettings(),Iw()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:n,smallTrack:o,isAuxiliary:r}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:n,smallTrack:o}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r?(n&&(t.localAuxVideoTrack=n),i&&(t.localAuxAudioTrack=i)):(n&&(t.localMainVideoTrack=n),i&&(t.localMainAudioTrack=i)),null==(e=t._sei)||e.handleEncodedStreams(),t.installTrackMuteEvents(i,n),t.sendMutedFlag()}()}))}publishByTransceiver(e){return ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,smallTrack:r,isAuxiliary:o}=e;return function*(){t._log.info(\"publish by transceiver\");let e=new MediaStream,s=null==n?void 0:n.outMediaTrack,a=t._audioManager.mixedAudioTrack;a&&e.addTrack(a),s&&e.addTrack(s);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||LN.AUDIO,{direction:MN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?LN.VIDEO:s||LN.VIDEO,{direction:MN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(r||LN.VIDEO,{direction:MN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||LN.VIDEO,{direction:MN.SENDONLY,streams:[e]}),yield t.connect();else{let e=[];if(a&&(c[0].sender.track||e.push(0),yield c[0].sender.replaceTrack(a),yield t.setBandwidth({bandwidth:(null==i?void 0:i.profile.bitrate)||40,type:LN.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:n.profile.bitrate,type:LN.VIDEO,videoType:o?LN.AUXILIARY:LN.BIG}),e.push(i),r&&(yield c[2].sender.replaceTrack(r),yield t.setBandwidth({bandwidth:n.small.bitrate,type:LN.VIDEO,videoType:LN.SMALL}),e.push(2))}yield t.setTransceiverDirection(MN.SENDONLY,e),yield t.doPublishChange(),null==n||n.emit(\"connection-state-changed\",{prevState:\"DISCONNECTED\",state:\"CONNECTING\"}),null==n||n.emit(\"connection-state-changed\",{prevState:\"CONNECTING\",state:\"CONNECTED\"})}}()}))}publishByAddTrack(e){return ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,smallTrack:r}=e;return function*(){t._log.info(\"publish by addtrack\");let e=null==n?void 0:n.outMediaTrack,o=t._audioManager.mixedAudioTrack;if(t._peerConnection&&\"new\"!==t._peerConnection.connectionState)return o&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(n)));let s=new MediaStream;if(o&&s.addTrack(o),e&&s.addTrack(e),o&&t._peerConnection.addTrack(o,s),e&&(t._peerConnection.addTrack(e,s),r)){let e=new MediaStream;e.addTrack(r),t._peerConnection.addTrack(r,e)}yield t.connect()}()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i{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&&(null==e||e.off(\"mute\",this.sendMutedFlag,this),null==e||e.off(\"unmute\",this.sendMutedFlag,this))}))}unpublish(e){return ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n}=e;return function*(){if(!Sw())return i&&i.outMediaTrack&&!n&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):n&&n.outMediaTrack&&!i&&t.localMainAudioTrack?(yield t.removeTrack(n),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),void t.emitConnectionStateChangedEvent(\"DISCONNECTED\",n));let e=n&&n===t.localAuxVideoTrack,r=null==n?void 0:n.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(t._audioManager.mixedAudioTrack||(yield o[0].replaceTrack(null),s.push(0)),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),r&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=eb($C({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=eb($C({},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(MN.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),null==n||n.emit(\"connection-state-changed\",{prevState:t._currentState,state:\"DISCONNECTED\"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return ab(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:dV,data:t,responseCommand:nV.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:uV,commandDesc:\"unpublish\",responseCommand:nV.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===mb.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:n,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Cw){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate)}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info(\"updateMediaSettings: \".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:yV,data:this._mediaSettings,responseCommand:nV.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return ab(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?LN.AUXILIARY:LN.MAIN,\" stream\")),null==(t=this._sei)||t.handleEncodedStreams(),Iw()?yield this.addTrackByTransceiver(e,i):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return ab(this,null,(function*(){var i;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===LN.AUDIO)yield n[0].sender.replaceTrack(this._audioManager.mixedAudioTrack);else{let r=t?3:1;yield n[r].sender.replaceTrack(e.outMediaTrack),1===r&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[r].direction===MN.INACTIVE&&(yield this.setTransceiverDirection(MN.SENDONLY,[r]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return ab(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Sw()&&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 n=t.kind===LN.VIDEO?t:this._audioManager.mixedAudioTrack;if(n&&this._peerConnection.addTrack(t,new MediaStream([n])),t.kind===LN.VIDEO&&e instanceof sL&&e.small){let e=new MediaStream,t=this._room.videoManager.smallTrack;e.addTrack(t),this._peerConnection.addTrack(t,e)}yield this.updateOffer(\"add\",t)}))}isNeedToResetOfferOrder(){if(this._sdpSemantics===pD||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=BV(e);for(let i=0;it.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&iO(t.stop)&&(this._log.info(\"stop transceiver\"),t.stop())}removeTrack(e){return ab(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(\"is removing \".concat(e.kind,\" track from current published local \").concat(t?LN.AUXILIARY:LN.MAIN,\" stream\")),Iw()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return ab(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===LN.AUDIO)this._audioManager.mixedAudioTrack||(yield i[0].sender.replaceTrack(null));else{let n=t?3:1;yield i[n].sender.replaceTrack(null),1===n&&e.small&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(MN.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return ab(this,null,(function*(){if(!Ub)return;let i=!1,n=!1;this._log.info(\"setting transceiver \".concat(t.join(\",\"),\" direction to \").concat(e));let r=this._peerConnection.getTransceivers();if(t.forEach((t=>{r[t].direction!==e&&(r[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,s=this._peerConnection.remoteDescription.sdp.split(\"\\r\\n\").map((i=>{if(i.match(new RegExp(\"a=(\".concat(MN.INACTIVE,\"|\").concat(MN.RECVONLY,\"|\").concat(MN.SENDONLY,\")\")))&&o++,t.includes(o)){if(e===MN.INACTIVE&&i.includes(\"a=\".concat(MN.RECVONLY)))return n=!0,\"a=\".concat(e);if(e===MN.SENDONLY&&i.includes(\"a=\".concat(MN.INACTIVE)))return n=!0,\"a=\".concat(MN.RECVONLY)}return i})).join(\"\\r\\n\");n&&(this._log.info(\"updating answer\"),yield this._peerConnection.setRemoteDescription({type:\"answer\",sdp:s}))}))}removeTrackBySender(e){return ab(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===LN.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let t=this._peerConnection.getSenders().find((t=>t.track===e.outMediaTrack));t&&(this.removeSender(t),e.kind===LN.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===LN.VIDEO&&this.removeSender(e)}))),yield this.updateOffer(\"remove\",e.outMediaTrack)}))}replaceTrack(e){return ab(this,null,(function*(){var t;let i,n=null==(t=this._peerConnection)?void 0:t.getSenders();if(!n||0===n.length||!e.mediaTrack)return;if(i=Iw()?e.kind===LN.AUDIO?n[0]:n[1]:n.find((t=>t.track&&t.track.kind===e.kind)),!i)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(\"is replacing \".concat(e.kind,\" track on \").concat(r?LN.AUXILIARY:LN.MAIN,\" stream\")),e.kind===LN.AUDIO?yield i.replaceTrack(this._audioManager.mixedAudioTrack):e.kind===LN.VIDEO&&(r?n[3]&&(yield n[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack))}))}updateOffer(e,t){return ab(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(KV);Ub&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,\"sendrecv\")),yield this._peerConnection.setLocalDescription(i);let n=this.updateMediaSettings(),r={action:e,trackId:t.id,kind:t.kind===LN.VIDEO?\"bigVideo\":t.kind,type:\"offer\",sdp:this._peerConnection.localDescription.sdp,constraintConfig:n,state:this.publishState};this._log.info(\"createOffer success, sending updated offer to remote server\"),this._log.debug(\"updatedOffer: \".concat(r.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:rV,data:r,responseCommand:nV.UPDATE_OFFER_RESULT,timeout:dD,commandDesc:\"update offer\"}),{code:s,message:a}=o.data;0!==s&&this.checkPublishResultCode(s,a),yield this.acceptAnswer(o.data.data),i.sdp&&this.updateSSRC(i.sdp)}catch(aN){throw this._log.error(aN),aN}}))}setBandwidth(e){return ab(this,arguments,(function(e){var t=this;let{bandwidth:i,type:n,videoType:r,sdp:o}=e;return function*(){if(!Rw())return o?n===LN.VIDEO?t.updateVideoBandwidthRestriction(o,i,r):t.updateAudioBandwidthRestriction(o,i):void 0;let e=0;n===LN.VIDEO&&(e=r===LN.SMALL?2:r===LN.AUXILIARY?3:1);let s=t._peerConnection.getSenders()[e];if(s){let e=s.getParameters();(!e.encodings||0===e.encodings.length)&&(e.encodings=[{}]),e.encodings[0].maxBitrate=1e3*i;try{return yield s.setParameters(e),t._log.info(\"\".concat(r||\"\").concat(n,\" bandwidth \").concat(i,\" kbps\")),o}catch(a){if(t._log.info(\"failed to set bandwidth by setting maxBitrate: \".concat(a)),o)return n===LN.VIDEO?t.updateVideoBandwidthRestriction(o,i,r):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let n=\"AS\";Ub&&(n=\"TIAS\",t*=1e3);let r=0,o=-1;return i===LN.SMALL?r=1:i===LN.AUXILIARY&&(r=2),e=e.replace(/m=video (.*)\\r\\nc=IN (.*)\\r\\n/g,(e=>(o+=1,o===r?\"\".concat(e,\"b=\").concat(n,\":\").concat(t,\"\\r\\n\"):e)))}updateAudioBandwidthRestriction(e,t){let i=\"AS\";return Ub&&(i=\"TIAS\",t*=1e3),e=e.replace(/m=audio (.*)\\r\\nc=IN (.*)\\r\\n/,\"m=audio $1\\r\\nc=IN $2\\r\\nb=\".concat(i,\":\").concat(t,\"\\r\\n\"))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\\r\\n/,\"\").replace(/b=TIAS:.*\\r\\n/,\"\")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,\"\")}connect(){return ab(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(sN){throw this.closePeerConnection(!0),this.uninstallEvents(),sN}}))}exchangeSDP(){return ab(this,null,(function*(){try{yield this.createOffer(),this._log.info(\"createOffer success, sending offer to remote server\"),yield this.doExchangeSDP()}catch(sN){throw sN}}))}createOffer(){return ab(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(KV);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(sN){throw sN}}))}doExchangeSDP(){let e={command:lV,responseCommand:nV.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof cL||this.localAuxVideoTrack instanceof cL,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:n}=e.data;return 0===t?this.acceptAnswer(n):this.checkPublishResultCode(t,i)}))}setSDPDirection(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:\"all\",n=BV(e);return n.media.forEach((e=>{(\"all\"===i||e.type===i)&&(e.direction=t)})),HV(n)}acceptAnswer(e){return ab(this,null,(function*(){var t,i,n,r,o;try{let s;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let e=(null==(t=this._publishingLocalVideoTrack)?void 0:t.profile.bitrate)||(null==(i=this.localMainVideoTrack)?void 0:i.profile.bitrate),o=(null==(n=this._publishingLocalAudioTrack)?void 0:n.profile.bitrate)||(null==(r=this.localMainAudioTrack)?void 0:r.profile.bitrate);if(e){let t=this._isPublishingAux?LN.AUXILIARY:LN.BIG;s=yield this.setBandwidth({bandwidth:e,type:LN.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:LN.AUDIO,sdp:s}))}if(s=this.removeVideoOrientation(e.sdp),null!=(o=this._publishingLocalVideoTrack)&&o.small){let{smallStreamConfig:e}=this._room;s=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:LN.VIDEO,videoType:LN.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this._peerConnection.setRemoteDescription(a),this._log.debug(\"accepted answer: \".concat(s))}catch(s){throw this._log.error(\"failed to accept remote answer \".concat(s)),s}}))}sendMutedFlag(e){var t,i,n;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(i=this.localMainVideoTrack)||!i.muted),auxVideo:!(null==(n=this.localAuxVideoTrack)||!n.muted)};this._log.info(\"send muted state: \".concat(JSON.stringify(r))),this._signalChannel.send(cV,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return ab(this,null,(function*(){if(!(sb(YV.prototype,this,\"beforeReconnect\").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:uV,responseCommand:nV.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(sD){let t=eO(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)&&xO.emit(FO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{BV(e).media.forEach(((e,t)=>{if(e.type===LN.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===pD&&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(sD){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:LN.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===LN.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===LN.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===LN.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===LN.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return\"\"}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===_D?(this._log.error(KO.NOT_SUPPORTED_H264ENCODE),new gb({code:mb.NOT_SUPPORTED_H264,message:qO({key:JO.NOT_SUPPORTED_H264ENCODE})})):new gb({code:mb.UNKNOWN,message:qO({key:JO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:nV.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}},zV=YV;rb([iL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n{let r=e=>{this._emitter.off(\"closed\",r),n(new gb({code:mb.API_CALL_ABORTED,message:qO({key:JO.CONNECTION_ABORTED,data:e})}))};this._emitter.on(\"closed\",r),e.apply(this,i).then(t,n).finally((()=>{this._emitter.off(\"closed\",r)}))}))}))],zV.prototype,\"publish\",1),rb([tL(UV.prototype.afterConnect),eL(UV.prototype.beforeConnect)],zV.prototype,\"connect\",1);var qV=zV,QV=class{constructor(e,t){this.room=e,ob(this,\"_log\"),ob(this,\"_prevReportTime\"),ob(this,\"_prevReport\",{}),ob(this,\"_prevEncoderImplementation\"),ob(this,\"_prevQualityLimitationReason\"),ob(this,\"_prevAuxQualityLimitationReason\"),ob(this,\"_prevDecoderImplementationMap\",new Map),ob(this,\"totalBytesSent\",0),ob(this,\"totalBytesReceived\",0),ob(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 ab(this,null,(function*(){let t={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},i=e.getPeerConnection(),n=e.getSSRC();if(i)try{if((this._spcStats||(yield i.getStats())).forEach((i=>{if(\"outbound-rtp\"===i.type)if((i.mediaType||i.kind)===LN.VIDEO){let r,o;if(i.ssrc===n.video?(r=LN.VIDEO,o=e.localMainVideoTrack):i.ssrc===n.small?r=LN.SMALL:i.ssrc===n.auxiliary&&(o=e.localAuxVideoTrack,r=LN.AUXILIARY),!r)return;t[r].bytesSent=i.bytesSent,t[r].packetsSent=i.packetsSent,t[r].framesEncoded=i.framesEncoded,nO(i.keyFramesEncoded)||(t[r].keyFramesEncoded=i.keyFramesEncoded),nO(i.nackCount)||(t[r].nackCount=i.nackCount),nO(i.pliCount)||(t[r].pliCount=i.pliCount),nO(i.retransmittedPacketsSent)||(t[r].retransmittedPacketsSent=i.retransmittedPacketsSent),nO(i.totalEncodeTime)||(t[r].totalEncodeTime=i.totalEncodeTime),nO(i.totalPacketSendDelay)||(t[r].totalPacketSendDelay=i.totalPacketSendDelay),i.ssrc===n.video?(!nO(i.encoderImplementation)&&this._prevEncoderImplementation!==i.encoderImplementation&&(this._log.info(\"encoderImplementation change to \".concat(i.encoderImplementation)),this._prevEncoderImplementation=i.encoderImplementation),!nO(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info(\"qualityLimitationReason change to \".concat(i.qualityLimitationReason)),this._prevQualityLimitationReason=i.qualityLimitationReason)):i.ssrc===n.auxiliary&&!nO(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevAuxQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info(\"aux qualityLimitationReason change to \".concat(i.qualityLimitationReason)),this._prevAuxQualityLimitationReason=i.qualityLimitationReason)}else t.audio.bytesSent=i.bytesSent,t.audio.packetsSent=i.packetsSent;else\"candidate-pair\"===i.type?uw(i)&&oO(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesSent=i.bytesSent):\"media-source\"===i.type&&(i.kind===LN.AUDIO?(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0):i.kind===LN.VIDEO&&(i.trackIdentifier===e.getVideoTrackId(LN.VIDEO)?t.video.fpsCapture=i.framesPerSecond:i.trackIdentifier===e.getVideoTrackId(LN.AUXILIARY)?t.auxiliary.fpsCapture=i.framesPerSecond:t.small.fpsCapture=i.framesPerSecond));if(nO(i.audioLevel)||(t.audio.audioLevel=i.audioLevel||0),!nO(i.frameWidth)){let r=LN.SMALL;i.trackIdentifier===e.getVideoTrackId(LN.VIDEO)||i.ssrc===n.video?r=LN.VIDEO:(i.trackIdentifier===e.getVideoTrackId(LN.AUXILIARY)||i.ssrc===n.auxiliary)&&(r=LN.AUXILIARY),t[r].frameWidth=i.frameWidth,t[r].frameHeight=i.frameHeight,t[r].framesSent=i.framesSent}})),e.localMainAudioTrack){let i=e.localMainAudioTrack.getInternalAudioLevel();t.audio.micAudioLevel=i,0===t.audio.audioLevel&&(t.audio.audioLevel=i)}this.totalBytesSent||(this.totalBytesSent+=t.audio.bytesSent+t.video.bytesSent+t.auxiliary.bytesSent)}catch(r){this._log.warn(\"failed to getStats on sender connection \".concat(r))}return t}))}getReceiverStats(e){return ab(this,null,(function*(){let t={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!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:n}=e,{muteState:r,subscribeState:o}=e;(this._spcStats||(yield i.getStats())).forEach((i=>{if(\"inbound-rtp\"===i.type)if((i.mediaType||i.kind)===LN.AUDIO){if(i.ssrc!==n.audio||!r.hasAudio)return;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:o}=e;o.stat.packetsReceived=i.packetsReceived,o.stat.bytesReceived=i.bytesReceived,o.stat.packetsLost=i.packetsLost,i.jitterBufferDelay&&(o.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)),t.hasAudio=!0}else{if(Ub&&0===i.bytesReceived)return;let s;i.ssrc===n.video&&r.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,s=e.remoteVideoTrack,r.hasSmall&&o.smallVideo&&(t.isSmallSubscribed=!0),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===n.auxiliary&&r.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,s=e.remoteAuxiliaryTrack,t.hasAuxiliary=!0),s&&(s.stat.packetsReceived=i.packetsReceived,s.stat.bytesReceived=i.bytesReceived,s.stat.packetsLost=i.packetsLost,s.stat.framesReceived=i.framesReceived,s.stat.framesDecoded=i.framesDecoded,i.jitterBufferDelay&&(s.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)))}else\"candidate-pair\"===i.type&&uw(i)&&oO(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesReceived=i.bytesReceived);nO(i.frameWidth)||((i.trackIdentifier===e.getMainStreamVideoTrackId()||i.ssrc===n.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===n.auxiliary)&&(t.auxiliary.frameWidth=i.frameWidth,t.auxiliary.frameHeight=i.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=i.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=i.frameHeight)),nO(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),this.totalBytesReceived||(this.totalBytesReceived+=t.audio.bytesReceived+t.video.bytesReceived+t.auxiliary.bytesReceived)}catch(aN){this._log.warn(\"failed to getStats on receiver connection \".concat(aN))}return t}))}getStats(e,t){return ab(this,null,(function*(){let i={},n=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:i,receiverStats:n};let t=yield e.getStats(),r=[],o=new Set([\"inbound-rtp\",\"outbound-rtp\",\"track\",\"candidate-pair\",\"media-source\"]);t.forEach((e=>o.has(e.type)&&r.push(e))),this._spcStats=r}e&&(i=yield this.getSenderStats(e));for(let[e,r]of t){let e=yield this.getReceiverStats(r);n.push(e)}return{senderStats:i,receiverStats:n}}))}getDifferenceValue(e,t){if(xP(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:n}=e;if(!xP(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*xD,uint32_audio_energy:1e6*t.senderStats.audio.totalAudioEnergy,uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(e.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*xD);let n=[];if(t.senderStats.video.bytesSent){let e={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};n.push(e)}if(t.senderStats.small.bytesSent){let e={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};n.push(e)}if(t.senderStats.auxiliary.bytesSent){let e={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};n.push(e)}let r={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:e,msg_video_status:n,msg_network_status:r}}let{statInterval:r}=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=n.get(\"\".concat(e.userId,\"_\").concat(KN)),r=i?i.duration:0,o={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:r,uint32_video_dec_fps:e.video.framesDecoded};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=n.get(\"\".concat(e.userId,\"_\").concat(YN)),r=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:r,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;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let n=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*n/r),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}}let s=o.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=s.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 n=0,o=0,a=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(n=t.uint32_video_codec_bitrate,o=t.uint32_video_enc_fps,a=t.uint32_video_codec_fps);let c=this.getDifferenceValue(n,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*c/r),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)/r),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(a,e.uint32_video_codec_fps)/r),_k&&115===wk()&&0===t.uint32_video_width&&0===t.uint32_video_height&&0===t.uint32_video_codec_fps&&(e.uint32_video_codec_fps=e.uint32_video_enc_fps),nO(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),nO(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),nO(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),nO(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),nO(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/r)),nO(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/r))}));let a=i.msg_down_stream_info,c=o.msg_down_stream_info;return a.forEach((e=>{let t=c.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(t){if(xP(e.msg_audio_status)||xP(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,n=t.msg_audio_status;i.uint32_audio_origin_lost=this.getDifferenceValue(n.uint32_audio_origin_lost,i.uint32_audio_origin_lost),i.uint32_audio_receive=this.getDifferenceValue(n.uint32_audio_receive,i.uint32_audio_receive),i.uint32_audio_receive+=i.uint32_audio_origin_lost;let o=this.getDifferenceValue(n.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*o/r),i.uint32_audio_total_bitrate=Math.round(8*o/r)}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)),n=t.uint32_video_receive,o=t.uint32_video_origin_lost,s=t.uint32_video_codec_bitrate,a=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(o,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(n,e.uint32_video_receive)+e.uint32_video_origin_lost;let l=this.getDifferenceValue(s,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/r);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/r),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/r)}))}}})),i}getStatsReport(e){return ab(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:n,freezeMap:r}=e;return function*(){let e={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:\"\",uint64_tinyid:0},msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_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,n);return\"{}\"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:r}),t._prevReportTime=Date.now(),e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation=\"\",this._prevQualityLimitationReason=\"\",this._prevDecoderImplementationMap=new Map}},XV=nb(cb()),ZV=class extends XV.default{constructor(e){let{signalChannel:t,room:i}=e;super(),ob(this,\"_room\"),ob(this,\"_signalChannel\"),ob(this,\"_log\"),ob(this,\"_uplinkRTT\",0),ob(this,\"_uplinkLoss\",0),ob(this,\"_downlinkRTT\",0),ob(this,\"_downlinkLoss\",0),ob(this,\"_downlinkPrevStatMap\",new Map),ob(this,\"_downlinkLossAndRTTMap\",new Map),ob(this,\"_interval\",-1),ob(this,\"_uplinkNetworkQuality\",0),ob(this,\"_downlinkNetworkQuality\",0),this._room=i,this._signalChannel=t,this._log=HO.createLogger({id:\"q\",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(\"uplink \".concat(this.uplinkNetworkQuality,\" -> \").concat(e,\", rtt: \").concat(this._uplinkRTT,\", loss: \").concat(this._uplinkLoss)),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:i}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(\"downlink \".concat(this.downlinkNetworkQuality,\" -> \").concat(e,\", rtt: \").concat(t,\", loss: \").concat(i))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(nV.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(qM,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,i;if(0!==e.data.code)return;let n=e.data.data;if(n.delay&&this.updateDelay(n.delay),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this._uplinkLoss=0,void(this._uplinkRTT=0);let r=null==(i=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:i.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r))return this.uplinkNetworkQuality=6,this._uplinkLoss=0,void(this._uplinkRTT=0);let o=n.expectAudPkg+n.expectVidPkg,s=n.recvAudPkg+n.recvVidPkg,a=o-s;0===o&&0===s||(this._uplinkLoss=a<=0?0:Math.round(a/o*100),this._uplinkRTT=n.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return ab(this,null,(function*(){if(0===this._room.remotePublishedUserMap.size)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],t=e.filter((e=>{var t;return(null==(t=e.getPeerConnection())?void 0:t.connectionState)===iD.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let r=0;r{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return;let{rtt:i,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=i,this._downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,i)}))}getStat(e){return ab(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Tw())return t;let i=e.getReceivers();try{for(let e=0;e{\"candidate-pair\"===e.type&&oO(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),\"inbound-rtp\"===e.type&&(e.mediaType===LN.AUDIO||e.mediaType===LN.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return t}catch(n){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===ZM?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state===eV&&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!==iD.DISCONNECTED&&e.connectionState!==iD.FAILED&&e.connectionState!==iD.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on(\"connection-state-changed\",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){-1===this._interval?(this._log.debug(\"start network quality calculating\"),this._interval=zw.run(wD,(()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];xO.emit(FO.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(ZV.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.debug(\"stopped\"),-1!==this._interval&&(zw.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:n,audioDelay:r}=e,o=t.get(i);if(o){let e=this._room.remotePublishedUserMap.get(o);null==e||e.setDelay({videoDelay:n,audioDelay:r})}}))}},$V=ZV;ob($V,\"EVENT_NETWORK_QUALITY\",\"0\");var ex=new WeakMap;function tx(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:n,onRetryFailed:r}=e;return function(e,o,s){let a=MO({retryFunction:s.value,settings:t,onError(t){let{error:n,retry:r,reject:s,retryFuncArgs:a}=t;i&&i.call(this,n,(()=>{var t;null!=(t=ex.get(e))&&t.has(o)?r():s(n)}),s,a)},onRetrying:(t,i)=>{var r;iO(n)&&n(t,i),null!=(r=ex.get(e))&&r.has(o)&&(ex.get(e).get(o).stopRetry=i)},onRetryFailed:r});return s.value=function(){let t=ex.get(e);for(var i=arguments.length,n=new Array(i),r=0;r{var t;return null==(t=ex.get(e))?void 0:t.delete(o)}))},s}}function ix(e){let{fnName:t,callback:i,validateArgs:n=!0}=e;return function(e,r,o){let s=o.value;return o.value=function(){for(var r,o,a=arguments.length,c=new Array(a),l=0;lt===e))){a=!1;break}a&&(i&&i.apply(this,c),r&&r(),null==(o=ex.get(e))||o.delete(t))}return s.apply(this,c)},o}}var nx=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:\"\",signalIp:\"\",relayIp:\"\",relayInnerIp:\"\",relayPort:0},this._apiSuccessRateMap=new Map,this._eventMap=new Map,this._frameWorkType=e.frameWorkType||30,this._component=e.component||0,this.connectionType=e.connectionType||1,this._language=e.language||0,this._room=e.room,this._keyPrefix=\"key_point\",this._log=HO.createLogger({id:\"kpm\",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith(\"handle\")&&iO(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,n=new Array(e),r=0;rHO.error(\"\".concat(t.name,\"() error observed \").concat(e)))):o}catch(sD){HO.error(\"\".concat(t.name,\"() error observed \").concat(sD))}}}({fn:this[e],context:this}))})),this.initData(),this.installEvents(),this._intervalId=zw.run(wD,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:rN,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:kN[GD()],uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,this._apiSuccessRateMap.clear(),Zk().then((e=>{this._basicInfo.string_os_version=tN(),e&&(this._basicInfo.string_device_name=e.model)}))}addEvent(e,t){return this._eventMap.set(e,t),xO.on(e,t),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener(\"unload\",this.handleUnload),this._room.once(\"banned\",(()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId}))),this.addEvent(FO.JOIN_START,this.handleJoinStart).addEvent(FO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(FO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(FO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(FO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(FO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(FO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(FO.JOIN_FAILED,this.handleJoinFailed).addEvent(FO.LEAVE_START,this.handleLeaveStart).addEvent(FO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(FO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(FO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(FO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(FO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(FO.PUBLISH_START,this.handlePublishStart).addEvent(FO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(FO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(FO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(FO.PLAY_TRACK_START,this.handlePlayStart).addEvent(FO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(FO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:n}=e;!dO(t)||!this.hitTest(t.room)||\"PLAYING\"===i&&(n===LN.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(FO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(FO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(FO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(FO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;if(!this.hitTest(t))return;let r=i.hasAudio||i.hasVideo||i.hasSmall,o=i.hasAuxiliary,s=n.hasAudio||n.hasVideo||n.hasSmall,a=n.hasAuxiliary;!r&&s&&this.handleRemoteStreamAdded(n.userId,\"main\"),!o&&a&&this.handleRemoteStreamAdded(n.userId,\"auxiliary\")})).addEvent(FO.API_SUCCESS_RATE,this.handleAPISuccessRate).addEvent(FO.SINGLE_CONNECTION_STAT,(e=>{let{room:t,stat:i}=e;this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=i.ice,this._pathJoinRoom.int32_dtls_cost=i.dtls,this._pathJoinRoom.int32_peer_connection_cost=i.peerConnection)}))}uninstallEvents(){window.removeEventListener(\"unload\",this.handleUnload),this._eventMap.forEach(((e,t)=>xO.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),zw.clearTask(this._intervalId)}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(e){this.hitTest(e.room)&&(0===this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage()),e.params&&(nO(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),nO(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),nO(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(e){let{room:t,detailCost:i}=e;if(this.hitTest(t)&&i){let{totalCost:e,local:t,dns:n,tcp:r,tls:o,request:s,response:a}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=n,this._pathJoinRoom.int32_schedule_tcp=r,this._pathJoinRoom.int32_schedule_tls=o,this._pathJoinRoom.int32_schedule_request=s,this._pathJoinRoom.int32_schedule_response=a}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(e){let{room:t,error:i}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=i instanceof gb?Number(i.getExtraCode()||i.getCode()):mb.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}handleJoinFailed(e){let{room:t,error:i}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=i.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout((()=>{this.report()})))}handleReceivedPublishUserList(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;!this.hitTest(t)||0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn(\"pathJoinRoom endTime is 0\"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(e,t){var i;let n=\"\".concat(e,\"_\").concat(t);if(!this._remoteStreamStatMap.has(n)){let r={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:eb($C({},sx),{msg_user_info:new ax({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};r.statsToReport.uint32_stream_type=\"main\"===t?2:7,this._remoteStreamStatMap.set(n,r)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:n,subscribeState:r}=e;if(!this.hitTest(t))return;let{userId:o,tinyId:s,role:a}=i,c=new ax({userId:o,tinyId:s,role:\"anchor\"===a?20:21}),l=Date.now(),d=\"\".concat(o,\"_\").concat(n),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=l),\"main\"===n?(i.muteState.hasVideo&&(r.video||r.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&&r.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&&r.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l})}handleSubscribed(e){let{room:t,remotePublishedUser:i,streamType:n}=e;if(this.hitTest(t)){let e=\"\".concat(i.userId,\"_\").concat(n),t=this._remoteStreamStatMap.get(e);t&&0===t.subscribedTime&&(t.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!dO(t)||!this.hitTest(t.room))return;let i=\"\".concat(t.userId,\"_\").concat(t.streamType),n=this._remoteStreamStatMap.get(i);0===(null==n?void 0:n.playStreamTime)&&(n.playStreamTime=Date.now())}handleVideoLoadedData(e){let{track:t}=e;if(!dO(t)||!this.hitTest(t.room))return;let i=\"\".concat(t.userId,\"_\").concat(t.streamType),n=this._pathMainVideoMap.get(i);n&&0===n.statsToReport.uint64_combine_first_frame_time&&(n.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t=\"\".concat(e.userId,\"_\").concat(e.streamType),i=Date.now(),n=this._pathMainVideoMap.get(t),r=this._remoteStreamStatMap.get(t);if(n&&(0===n.statsToReport.uint64_render_first_frame_time&&(n.statsToReport.uint64_render_first_frame_time=i),r)){let{statsToReport:e,playStreamTime:t,subscribedTime:o}=r;0===e.uint32_video_render_first&&t-o<=100&&(e.uint32_video_render_first=i-n.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(t);if(o&&r){let{statsToReport:e,playStreamTime:t,subscribedTime:n}=r;0===e.uint32_video_render_first&&t-n<=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:n,videoDelay:r,audioDelay:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(n);if(s)s.totalRTT+=t,s.totalLoss+=i,r&&(s.totalVideoDelay=(s.totalVideoDelay||0)+r,s.videoDelayCount=(s.videoDelayCount||0)+1),o&&(s.totalAudioDelay=(s.totalAudioDelay||0)+o,s.audioDelayCount=(s.audioDelayCount||0)+1),s.count++;else{let e,s,a,c;r&&(s=r,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(n,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a})}})))}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:n,uint32_video_height:r}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=i,this._localStreamStat.totalVideoWidth+=n,this._localStreamStat.totalVideoHeight+=r,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:e}=t.msg_audio_status;Math.floor(e/xD*100)>0&&(this._localStreamStat.totalAudioLevel+=e/xD,this._localStreamStat.audioLevelCount++)}i.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:n}=e,r=t.str_identifier,o=this._room.remotePublishedUserMap.get(r);if(n.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,n=\"\".concat(r,\"_\").concat(t?\"main\":\"auxiliary\"),s=this._remoteStreamStatMap.get(n);if(s&&(t&&(null==o?void 0:o.remoteVideoTrack.isSubscribed)||i&&(null==o?void 0:o.remoteAuxiliaryTrack))){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*XC(10,6)))}})),i){let e=\"\".concat(r,\"_\",\"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/xD*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/xD,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&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,n={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof gb?i.getExtraCode()||i.getCode():mb.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=n,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=n,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleAPISuccessRate(e){let{room:t,apiName:i,error:n,cost:r}=e;if(!this.hitTest(t))return;let o=cx[i],s={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(n){let e=n.extraCode||n.code||mb.UNKNOWN;Qw.logFailedEvent({eventType:i,code:e,userId:this._room.userId,error:n});let t={int32_error_code:e,error_count:1};s.msg_error_code.push(t)}else oO(r)&&(Qw.logSuccessEvent({eventType:i,userId:this._room.userId}),s.uint32_avg_value=r,s.uint32_max_value=r,s.uint32_success_count=1);let a=this._apiSuccessRateMap.get(o);a?(a.uint32_success_count+s.uint32_success_count>0&&(a.uint32_avg_value=(a.uint32_avg_value*a.uint32_success_count+s.uint32_avg_value)/(a.uint32_success_count+s.uint32_success_count)),a.uint32_max_value=Math.max(a.uint32_max_value,s.uint32_max_value),a.uint32_request_count+=1,a.uint32_success_count=a.uint32_success_count+s.uint32_success_count,s.msg_error_code.forEach((e=>{let t=a.msg_error_code.find((t=>t.int32_error_code===e.int32_error_code));t?t.error_count+=1:a.msg_error_code.push(e)}))):this._apiSuccessRateMap.set(o,s)}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&UN))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&HN))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&BN))>=0}hitTest(e){return e===this._room}checkStorage(){return ab(this,null,(function*(){try{let e=GO.getItem(this._storageKey);e&&(yield this.upload(e),GO.deleteItem(this._storageKey))}catch(HL){this._log.warn(HL)}}))}setStorage(){this.prepareReport();let e=this.getReportData();0!==e.msg_path_enter_room.uint64_start_time&&GO.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,n=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(n){let{totalLoss:t,count:i,audioDelayCount:r,videoDelayCount:o,totalAudioDelay:s,totalVideoDelay:a}=n;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),r&&s&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(s/r),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/o))}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:r}=this._room;r&&(e.statsToReport.uint32_audio_play_time=r.getDuration(t,LN.AUDIO),e.statsToReport.uint32_video_play_time=r.getDuration(t,LN.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,ox);let{badCaseDetector:o}=this._room,{dataFreeze:s,count:a}=o.getDataFreezeDuration(t),{renderFreeze:c}=o.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=a,e.statsToReport.uint32_video_block_time=Math.min(s,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),o.isBlackStream(t)&&0===e.statsToReport.uint32_video_avg_fps?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0,(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>ox&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+ox):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>ox&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+ox):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>ox&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+ox)}getReportData(){return{uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new ax({userId:this._room.userId,tinyId:this._room.tinyId,role:\"anchor\"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:AO(this._signalInfo.relayIp),uint32_client_ip:AO(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:AO(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,msg_function_request_stats:[...this._apiSuccessRateMap.values()]}}report(){try{this.prepareReport();let e=this.getReportData();this.upload(e),GO.deleteItem(this._storageKey),this.initData()}catch(HL){this._log.warn(HL)}}upload(e){if(Yk||0===e.msg_path_enter_room.uint64_start_time||[_N,mN,fN].findIndex((e=>e===location.host))>=0)return;let t=Number(this._room.sdkAppId),i=BD(t,yN.KEY_POINT),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(i,JSON.stringify(e))),n||PO({url:i,body:JSON.stringify(e)})}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}};rb([tx({settings:{timeout:500,retries:3}})],nx.prototype,\"upload\",1);var rx,ox=5e3,sx={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},ax=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},cx=((rx=cx||{})[rx.enterRoom=50001]=\"enterRoom\",rx[rx.exitRoom=50002]=\"exitRoom\",rx[rx.switchRole=50003]=\"switchRole\",rx[rx.destroy=50004]=\"destroy\",rx[rx.startLocalAudio=50005]=\"startLocalAudio\",rx[rx.updateLocalAudio=50006]=\"updateLocalAudio\",rx[rx.stopLocalAudio=50007]=\"stopLocalAudio\",rx[rx.startLocalVideo=50008]=\"startLocalVideo\",rx[rx.updateLocalVideo=50009]=\"updateLocalVideo\",rx[rx.stopLocalVideo=50010]=\"stopLocalVideo\",rx[rx.startScreenShare=50011]=\"startScreenShare\",rx[rx.updateScreenShare=50012]=\"updateScreenShare\",rx[rx.stopScreenShare=50013]=\"stopScreenShare\",rx[rx.enableAudioVolumeEvaluation=50014]=\"enableAudioVolumeEvaluation\",rx[rx.startRemoteVideo=50015]=\"startRemoteVideo\",rx[rx.updateRemoteVideo=50016]=\"updateRemoteVideo\",rx[rx.stopRemoteVideo=50017]=\"stopRemoteVideo\",rx[rx.muteRemoteAudio=50018]=\"muteRemoteAudio\",rx[rx.setRemoteAudioVolume=50019]=\"setRemoteAudioVolume\",rx[rx.startMixTranscode=50020]=\"startMixTranscode\",rx[rx.stopMixTranscode=50021]=\"stopMixTranscode\",rx[rx.startPublishCDNStream=50022]=\"startPublishCDNStream\",rx[rx.stopPublishCDNStream=50023]=\"stopPublishCDNStream\",rx[rx.PeerConnectionConnect=50024]=\"PeerConnectionConnect\",rx[rx.PeerConnectionReconnect=50025]=\"PeerConnectionReconnect\",rx[rx.WebsocketConnect=50026]=\"WebsocketConnect\",rx[rx.WebsocketReconnect=50027]=\"WebsocketReconnect\",rx[rx.schedule=50028]=\"schedule\",rx[rx.SPCConnect=50029]=\"SPCConnect\",rx[rx.SPCReconnect=50030]=\"SPCReconnect\",rx[rx.videoCtxGl=50031]=\"videoCtxGl\",rx[rx.videoCtxGlRecover=50032]=\"videoCtxGlRecover\",rx[rx.videoCtx2d=50033]=\"videoCtx2d\",rx[rx[\"CDNStreaming.startPlugin\"]=50034]=\"CDNStreaming.startPlugin\",rx[rx[\"CDNStreaming.updatePlugin\"]=50035]=\"CDNStreaming.updatePlugin\",rx[rx[\"CDNStreaming.stopPlugin\"]=50036]=\"CDNStreaming.stopPlugin\",rx[rx[\"AIDenoiser.startPlugin\"]=50037]=\"AIDenoiser.startPlugin\",rx[rx[\"AIDenoiser.updatePlugin\"]=50038]=\"AIDenoiser.updatePlugin\",rx[rx[\"AIDenoiser.stopPlugin\"]=50039]=\"AIDenoiser.stopPlugin\",rx[rx[\"AudioMixer.startPlugin\"]=50040]=\"AudioMixer.startPlugin\",rx[rx[\"AudioMixer.updatePlugin\"]=50041]=\"AudioMixer.updatePlugin\",rx[rx[\"AudioMixer.stopPlugin\"]=50042]=\"AudioMixer.stopPlugin\",rx),lx=nx,dx=class{constructor(){ob(this,\"_startTime\"),ob(this,\"_endTime\"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=fO())}stop(){0===this._endTime&&(this._endTime=fO())}getDuration(){return 0===this._endTime?fO()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},ux=class{constructor(e){ob(this,\"_room\",null),ob(this,\"_durationMap\"),ob(this,\"_eventMap\",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(FO.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(FO.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(FO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;var r;let{userId:o}=n;if(!this.hitTest(t))return;i.hasAudio&&!n.hasAudio&&this.stopDurationItem(\"\".concat(o,\"_\",\"main\"),LN.AUDIO),i.hasVideo&&!n.hasVideo&&this.stopDurationItem(\"\".concat(o,\"_\",\"main\"),LN.VIDEO),i.hasAuxiliary&&!n.hasAuxiliary&&this.stopDurationItem(\"\".concat(o,\"_\",\"auxiliary\"),LN.VIDEO);let s=null==(r=this._room)?void 0:r.remotePublishedUserMap.get(o);!s||(!i.hasAudio&&n.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,LN.AUDIO,\"main\"),!i.hasVideo&&n.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,LN.VIDEO,\"main\"),!i.hasAuxiliary&&n.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,LN.VIDEO,\"auxiliary\"))})),this._eventMap.forEach(((e,t)=>xO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>xO.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o=\"\".concat(r,\"_\").concat(i);if(n.muteState.hasAudio&&\"main\"===i)if(n.remoteAudioTrack.isSubscribed){let e=new dx,t=this._durationMap.get(o);t?this.isRecording(t.audio)||t.audio.push(e):this._durationMap.set(o,{userId:r,type:i,audio:[e],video:[]})}else this.stopDurationItem(o,LN.AUDIO);if(n.muteState.hasVideo||n.muteState.hasAuxiliary)if(n.remoteVideoTrack.isSubscribed||n.remoteAuxiliaryTrack.isSubscribed){let e=new dx,t=this._durationMap.get(o);t?this.isRecording(t.video)||t.video.push(e):this._durationMap.set(o,{userId:r,type:i,audio:[],video:[e]})}else this.stopDurationItem(o,LN.VIDEO)}handleStreamStopped(e){let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o=\"\".concat(r,\"_\").concat(i);this.stopDurationItem(o,LN.AUDIO),this.stopDurationItem(o,LN.VIDEO)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let n=\"\".concat(e,\"_\").concat(i),r=new dx,o=this._durationMap.get(n);o?this.isRecording(o[t])||o[t].push(r):this._durationMap.set(n,{userId:e,type:i,audio:t===LN.AUDIO?[r]:[],video:t===LN.AUDIO?[]:[r]})}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()}},hx=class{constructor(e){ob(this,\"_room\"),ob(this,\"_renderFreezeMap\",new Map),ob(this,\"_isVideoPlayingEventFiredMap\",new Map),ob(this,\"_dataFreezeMap\",new Map),ob(this,\"_monitorFreezeData\",new Map),ob(this,\"_eventMap\",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(FO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(FO.PLAY_TRACK_START,this.onPlayTrackStart).set(FO.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o=\"\".concat(r,\"_\").concat(i);this.stopDataFreeze({key:o,userId:r,type:i})})).set(FO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;if(!this.hitTest(t))return;let{userId:r}=n;if(i.hasVideo&&!n.hasVideo){let e=\"main\",t=\"\".concat(n.userId,\"_\").concat(e);this.stopDataFreeze({key:t,userId:r,type:e})}if(i.hasAuxiliary&&!n.hasAuxiliary){let e=\"auxiliary\",t=\"\".concat(n.userId,\"_\").concat(e);this.stopDataFreeze({key:t,userId:r,type:e})}})).set(FO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:n,type:r}=e;if(dO(t)&&this.hitTest(t.room)&&r===LN.VIDEO){if(\"PLAYING\"===i){let e=\"\".concat(t.userId,\"_\").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}n===LN.MUTE?this.onVideoTrackMuted(t):n===LN.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(FO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>xO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>xO.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,n=\"\".concat(t,\"_\").concat(i),r=this._dataFreezeMap.get(n),o=new dx;r?r.durationItemList.push(o):this._dataFreezeMap.set(n,{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,n=\"\".concat(t,\"_\").concat(i);this.stopDataFreeze({key:n,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:n}=t;e.msg_video_status.forEach((e=>{2===e.uint32_video_stream_type&&n.hasVideo&&!n.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:\"main\"}),7===e.uint32_video_stream_type&&n.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:\"auxiliary\"})}))}))}stopDataFreeze(e){let{key:t,userId:i,type:n}=e,r=this._dataFreezeMap.get(t);if(!r||!r.isFreezing())return;let o=r.durationItemList[r.durationItemList.length-1];o.stop();let s=o.getDuration();s>fD?this._monitorFreezeData.set(t,{userId:i,type:n,duration:s}):r.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return ab(this,arguments,(function(e){var t=this;let{userId:i,fps:n,type:r}=e;return function*(){let e=\"\".concat(i,\"_\").concat(r),o=t._renderFreezeMap.get(e);if(n<=2){let n=fO();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:n,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(e,{userId:i,type:r,isFreeze:!0,freezeTimeline:[{startTime:n,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let e=o.freezeTimeline.pop();if(e){e.endTime=fO();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!dO(t)||!this.hitTest(t.room)||t.kind!==LN.VIDEO||t.hasFlag)return;let i=\"\".concat(t.userId,\"_\").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(i)||this._isVideoPlayingEventFiredMap.set(i,!1)}getDataFreezeDuration(e){let t={dataFreeze:0,count:0},i=this._dataFreezeMap.get(e);if(i){if(i.isFreezing()){let e=i.durationItemList[i.durationItemList.length-1];e.stop(),e.getDuration(){let o=null;mO([Ix((e=>t.count[0]=e+1),(e=>{let{error:i,retry:n}=e;t.msg[0]=i.message,o||n()}))(Ex(i,LN.MAIN),e,{get timeout(){return 1e3*$D(2+t.count[0])}}),Ix((e=>t.count[1]=e+1),(e=>{let{error:i,retry:n}=e;t.msg[1]=i.message,o||n()}))(Ex(i,LN.BACKUP),e,{get timeout(){return 1e3*$D(2+t.count[1])}})]).then((e=>{o=e,n(o)})).catch(r)}))}(c,e,i);d.config&&(d.config.loggerDomain&&pN(d.config.loggerDomain),sO(d.config.scheduleCache)&&mx(!d.config.scheduleCache)),e.delta=fO()-l;let u=function(e,t,i){let n=performance.getEntriesByType(\"resource\"),r=Ex(e,LN.MAIN),o=Ex(e,LN.BACKUP),s={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};for(let a of n)if(a.startTime>=i&&(a.name===r||a.name===o)&&a.transferSize>0){let e=a.name===r?LN.MAIN:LN.BACKUP,i=Math.round(a.duration),n=Math.round(a.domainLookupStart-a.startTime),o=Math.round(a.domainLookupEnd-a.domainLookupStart),c=Math.round(a.requestStart-a.secureConnectionStart),l=Math.round(a.secureConnectionStart-a.connectStart),d=Math.round(a.responseStart-a.requestStart),u=Math.round(a.responseEnd-a.responseStart),h=[n,o,c,l,d,u];Qw.uploadEvent({log:\"stat-schedule-net:\".concat(i,\"(\").concat(h.join(\"->\"),\") \").concat(e),userId:t}),s=eb($C({},s),{totalCost:i,local:n,dns:o,tcp:l,tls:c,request:d,response:u});break}return s}(Number(i),t,l);return px=d,{isCached:!1,result:d,detailCost:u}}catch(c){let e=cO(c)?c[0]:c,t=oO(e.code)?e.code:0,i=\"schedule failed\".concat(e.message?\": \".concat(e.message):\"\"),n=new gb({code:mb.SCHEDULE_FAILED,extraCode:t,message:qO({key:JO.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw HO.error(n),n}}()}))}xO.on(\"28\",(()=>mx(!0))),xO.on(\"63\",(()=>mx(!0))),xO.on(\"84\",(()=>mx(!0))),xO.on(\"201\",(e=>{\"RECONNECTING\"===e.state&&mx(!0)})),xO.on(\"202\",(e=>{\"RECONNECTING\"===e.state&&mx(!0)}));var gx={main:\"\",backup:\"\"};function Tx(e){cO(e)?(gx.main=e[0],gx.backup=e[1]):gx.main=e}function Ex(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:LN.MAIN;return t=FD(e)?i===LN.MAIN?ID.MAIN_OVERSEA:ID.BACKUP_OVERSEA:i===LN.MAIN?ID.MAIN:ID.BACKUP,\"https://\".concat(gx[i]||t,\"/api/v1/config\")}function Sx(e,t,i){return new Promise(((n,r)=>{PO({url:e,body:t,timeout:i.timeout}).then((e=>{0===e.data.code?n(e.data.data):r({code:e.data.code,message:e.data.msg})})).catch(r)}))}var Ix=(e,t)=>MO({retryFunction:Sx,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var vx=nb(cb(),1),yx=[-1,-1,-1,1,1,-1,1,1],Ax=[0,0,0,1,1,0,1,1],Rx=class extends Gw{constructor(e,t){super(),this.context=e,ob(this,\"name\"),ob(this,\"input\"),ob(this,\"output\"),ob(this,\"texture\"),ob(this,\"image\"),ob(this,\"ctx2d\",null),ob(this,\"fbo\"),ob(this,\"width\",0),ob(this,\"height\",0),ob(this,\"x\",0),ob(this,\"y\",0),ob(this,\"program\"),ob(this,\"vertexShader\"),ob(this,\"fragmentShader\"),ob(this,\"totalFrames\",0),ob(this,\"dropFrames\",0),ob(this,\"matchInputSize\",!0),ob(this,\"texCoordBuffer\"),ob(this,\"positionBuffer\"),ob(this,\"lastInfo\",{timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),ob(this,\"_canvas\",null),this.context.once(\"disconnect\",(()=>{\"closed\"!==this.state&&this.close()})),this.name=t.name,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height;let i=e._gl;if(i)try{!1!==t.createTexture&&(this.texture=i.createTexture()),this.texCoordBuffer=this.createBuffer(Ax),this.positionBuffer=this.createBuffer(yx),this.useTexture((()=>{i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE)})),t.useFbo&&(this.fbo=i.createFramebuffer(),this.useBufferFrame((()=>{this.useTexture((()=>{i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.texture,0)}))}))),t.useDefaultProgram&&(this.program=this.context.defaultProgam),t.vertexShaderSource&&t.fragmentShaderSource&&(this.vertexShader=e.createShader(i.VERTEX_SHADER,t.vertexShaderSource),this.fragmentShader=e.createShader(i.FRAGMENT_SHADER,t.fragmentShaderSource),this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(n){this.context.destroy(\"\".concat(this.name,\" init failed\"),n)}else if(e.ctx2d&&t.create2d){let e=document.createElement(\"canvas\"),t=\"function\"==typeof e.transferControlToOffscreen?e.transferControlToOffscreen():e;t.width=this.width,t.height=this.height,this.ctx2d=t.getContext(\"2d\"),this.image=t,this._canvas=t}}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;ni.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null))),this.output&&this.output.matchInputSize&&this.output.resize(e,t))}draw2d(e,t,i,n,r){return!(!this.ctx2d||!e)&&(e instanceof ImageData?this.ctx2d.putImageData(e,t,i):this.ctx2d.drawImage(e,t,i,n,r),!0)}getInfo(){var e;let{totalFrames:t,x:i,y:n,width:r,height:o}=this,s=Date.now(),a=(t-this.lastInfo.totalFrames)/((s-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:t,x:i,y:n,width:r,height:o,timestamp:s,fps:a},$C({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}};rb([Bw(Gw.INIT,\"connected\")],Rx.prototype,\"connect\",1),rb([Bw(\"connected\",Gw.INIT,{ignoreError:!0})],Rx.prototype,\"disconnect\",1),rb([Bw([],\"closed\")],Rx.prototype,\"close\",1);var Cx=[0,1,0,0,1,1,1,0],bx=class extends Rx{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:\"destination\"},t)),ob(this,\"_intervalId\",0),ob(this,\"_sequence\",0),e._gl?this.setTexBuffer(Cx):e.ctx2d&&(this.ctx2d=e.ctx2d)}start(e){this._intervalId=zw.run(\"intervalInWorker\",(()=>{e!==this.context.frameRate&&(zw.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++);let t=this.context._gl;t&&t.getError()!==t.NO_ERROR&&this.context.destroy(\"\".concat(this.name,\" req \").concat(this._sequence,\" render \").concat(this.totalFrames,\" faild \").concat(t.getError()))}),{fps:this.context.frameRate})}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useInputTexture((e=>{this.setAttributes({a_position:this.positionBuffer,a_texCoord:this.texCoordBuffer}),e.drawArrays(e.TRIANGLE_STRIP,0,4)})),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n{let t=()=>this._videoTrack.removeEventListener(e,i),i=()=>{t(),this.context.destroy(\"video track \".concat(e))};this.once(\"closed\",t),this._videoTrack.addEventListener(e,i)};e._gl&&i(\"mute\"),i(\"ended\")}get videoTrack(){return this._videoTrack}close(){super.close(),this._videoTrack.stop()}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},Nx=class extends kx{constructor(e,t){super(e,{name:\"smallDestination\"}),this.resolution=t}resize(e,t){let i,n=e*t,r=this.resolution.width*this.resolution.height;HO.info(\"big res: \".concat(e,\"*\").concat(t,\" small res: \").concat(this.resolution.width,\"*\").concat(this.resolution.height,\" \")),n>r?i=n/r:(HO.warn(\"Small stream resolution is not smaller than big stream, which is invalid. big: \".concat(e,\" * \").concat(t,\" small: \").concat(this.resolution.width,\" * \").concat(this.resolution.height)),i=n/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},Dx=class extends Rx{constructor(e,t){super(e,{name:\"imageSource\"}),this.image=t,ob(this,\"_image\"),ob(this,\"_totalFrames\",0)}_render(e,t){let{width:i,height:n}=this;if(this.image instanceof HTMLVideoElement){if(iO(this.image.getVideoPlaybackQuality)&&!Fk){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}({videoWidth:i,videoHeight:n}=this.image)}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if(({width:i,height:n}=this.image),this.image!==this._image)this._image=this.image;else if(i===this.width&&n===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&(({width:i,height:n}=this.image),this._image=this.image);return this.width===i&&this.height===n&&this.totalFrames?t&&this.useTexture((e=>{e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,this.image)})):(t&&this.useTexture((e=>{e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)})),this.resize(i,n)),!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Ox=class extends Dx{constructor(e,t){super(e,document.createElement(\"video\")),this._videoTrack=t,ob(this,\"_mediaStream\"),this.name=\"videoTrackSource\",this._mediaStream=new MediaStream([t]),this.image.srcObject=this._mediaStream,this.image.play()}replaceTrack(e){var t,i;this._videoTrack!==e&&(null==(t=this._mediaStream)||t.removeTrack(this._videoTrack),this._videoTrack=e,null==(i=this._mediaStream)||i.addTrack(this._videoTrack),this.image.play())}close(){super.close(),delete this._mediaStream,this.image.srcObject=null}},wx=class extends Gw{constructor(e){super(),ob(this,\"frameRate\"),ob(this,\"_canvas\"),ob(this,\"_gl\"),ob(this,\"ctx2d\"),ob(this,\"defaultProgam\"),ob(this,\"log\"),ob(this,\"hasAlpha\",!1),ob(this,\"glFaild\",!1),ob(this,\"name\"),this.name=e.name,this.log=e.logger.createChild({id:\"vc-\".concat(this.name)}),this.frameRate=e.frameRate}create(e){if(this.glFaild=!1,this.hasAlpha=e.alpha,this._canvas=document.createElement(\"canvas\"),e.use2d)return this.ctx2d=this._canvas.getContext(\"2d\",{alpha:e.alpha}),void this.log.info(\"video context created use 2d\");let t=this._canvas.getContext(\"webgl\",{alpha:e.alpha});if(t){this._gl=t;try{let e=this.createShader(t.VERTEX_SHADER,\"\\n// 顶点着色器\\nattribute vec4 a_position;\\nattribute vec2 a_texCoord;\\nvarying vec2 v_texCoord;\\n\\nvoid main() {\\n gl_Position = a_position;\\n v_texCoord = a_texCoord;\\n}\\n\"),i=this.createShader(t.FRAGMENT_SHADER,\"\\n// 片元着色器\\nprecision mediump float;\\nvarying vec2 v_texCoord;\\nuniform sampler2D u_texture;\\n\\nvoid main() {\\n gl_FragColor = texture2D(u_texture, v_texCoord);\\n} \");this.defaultProgam=this.createProgram(e,i),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this._canvas.addEventListener(\"webglcontextlost\",(()=>{this.destroy(\"webglcontextlost\")})),this.log.info(\"video context created use webgl\")}catch(aN){return this.log.warn(\"video context create faild use webgl\"),aN}}else this.ctx2d=this._canvas.getContext(\"2d\"),this.ctx2d&&this.log.info(\"video context created downgrade to 2d\");!this.ctx2d&&!this._gl&&delete this._canvas}get available(){return!!this._canvas}createVideoTrackSource(e){return new Ox(this,e)}createVideoTrackDestination(e){return new kx(this,e)}createVideoImageSource(e){return new Dx(this,e)}set width(e){var t;null==(t=this._gl)||t.viewport(0,0,e,this.height),this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){var t;null==(t=this._gl)||t.viewport(0,0,this.width,e),this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){var i;null==(i=this._gl)||i.viewport(0,0,e,t),this._canvas&&(this._canvas.width=e,this._canvas.height=t)}disconnect(){this.emit(\"disconnect\")}destroy(e,t){var i;return this.disconnect(),this.log.info(\"video context destroy \".concat(e?\":\".concat(e):\"\")),null==(i=this._gl)||i.deleteProgram(this.defaultProgam),delete this._gl,delete this.ctx2d,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),[e,t]}createShader(e,t){let i=this._gl,n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}createProgram(e,t){let i=this._gl,n=i.createProgram();return i.attachShader(n,e),i.attachShader(n,t),i.linkProgram(n),n}useTexture(e,t,i){let n=this._gl;n.activeTexture(n.TEXTURE0+(i||0)),n.bindTexture(n.TEXTURE_2D,e),t(n),n.bindTexture(n.TEXTURE_2D,null)}};rb([Bw(Gw.INIT,\"created\")],wx.prototype,\"create\",1),rb([Bw(\"created\",Gw.INIT,{ignoreError:!0,success(e){e[0]&&(this.glFaild=!0,this.emit(\"unavailable\",...e)),this.removeAllListeners()}})],wx.prototype,\"destroy\",1);var Px=[1,0,1,1,0,0,0,1],Lx=class extends Rx{constructor(e){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:\"mirror\"}),e._gl)try{this.setTexBuffer(Px)}catch(sN){e.destroy(\"mirror set texCoords faild\",sN)}else this.ctx2d&&setTimeout((e=>{e.scale(-1,1),e.translate(-this.width,0)}),0,this.ctx2d)}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame((()=>{this.useInputTexture((e=>{this.setAttributes({a_position:this.positionBuffer,a_texCoord:this.texCoordBuffer}),e.drawArrays(e.TRIANGLE_STRIP,0,4)}))})),!0)}},Mx=class{constructor(e,t){this.node=e,this.layout=t,ob(this,\"positionBuffer\")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},Vx=class extends Rx{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:\"mix\",create2d:!0}),ob(this,\"inputs\",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error(\"input already exists\");let i=new Mx(e,t);this.inputs[t.zIndex]=i}resize(e,t){let i=this.inputs.reduce(((e,t)=>t?Object.assign(e,{width:Math.max(e.width,t.right),height:Math.max(e.height,t.bottom)}):e),{width:0,height:0});super.resize(i.width,i.height),this.context._gl&&this.inputs.forEach((e=>{if(e){let t=this.layout2texCoords(e);e.positionBuffer?this.changeBufferData(e.positionBuffer,t):e.positionBuffer=this.createBuffer(t)}}))}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n(null==t?void 0:t.node)===e))]=void 0}render(e){let t=this.context._gl;return!(this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)||!t)&&(this.useProgram(),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),this.setAttributes({a_texCoord:this.texCoordBuffer}),this.useBufferFrame((()=>{for(let e=0;e{this.setAttributes({a_position:t.positionBuffer}),e.drawArrays(e.TRIANGLE_STRIP,0,4)}))}})),!0)}render2d(e){if(!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let e=0;e>0;return this.lastInfo={totalFrames:e,x:t,y:i,width:n,height:r,timestamp:o,fps:s},$C({parent:this.inputs.filter((e=>e)).map((e=>e.node.getInfo()))},this.lastInfo)}close(){super.close(),this.inputs.forEach((e=>{var t;if(e&&(null==(t=e.node)||t.disconnect(),e.positionBuffer&&this.context._gl))try{this.context._gl.deleteBuffer(e.positionBuffer)}catch(aN){}}))}},xx=class extends vx.EventEmitter{constructor(e){let{room:t}=e;super(),ob(this,\"videoContext\"),ob(this,\"destination\"),ob(this,\"smallVideoContext\"),ob(this,\"smallDestination\"),ob(this,\"smallTrackSource\"),ob(this,\"smallImageSource\"),ob(this,\"_isMirror\",!1),ob(this,\"cameraTrack\"),ob(this,\"cameraNode\"),ob(this,\"waterMarkNode\"),ob(this,\"mirrorNode\"),ob(this,\"mixNode\"),ob(this,\"screenTrack\"),ob(this,\"screenNode\"),ob(this,\"_isMixScreen\",!1),ob(this,\"_hasWaterMark\",!1),ob(this,\"_log\"),ob(this,\"_checkId\",0),ob(this,\"_room\"),ob(this,\"_use2d\",!0),ob(this,\"_waterMarkOption\"),ob(this,\"_isOpenVirtualBackground\",!1),ob(this,\"_virtualBackgroundTrack\"),ob(this,\"virtualBackgroundInstance\"),this._room=t,this._log=HO.createLogger({id:\"vm\",userId:t.userId,sdkAppId:t.sdkAppId}),this.videoContext=new wx({frameRate:15,logger:this._log,name:\"m\"}),this.videoContext.on(\"unavailable\",((e,t)=>{this.emit(\"error\",{reason:e,error:t}),this._log.warn(\"video context unavailable\",e,t,\"glFaild:\".concat(this.videoContext.glFaild)),xO.emit(\"262\",{room:this._room,apiName:\"videoCtxGl\",error:t||new Error(e)}),this.update()})),this.smallVideoContext=new wx({frameRate:15,logger:this._log,name:\"s\"}),this.enablePrintDetail()}get renderMode(){return this._use2d?\"2d\":\"webgl\"}set renderMode(e){let t=\"2d\"===e;this._use2d!==t&&(this._use2d=t,this.videoContext&&(this.clear(),this.videoContext.destroy(),this.videoContext.create({alpha:this._hasWaterMark,use2d:this._use2d}),this.update()))}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=zw.run(LD,(()=>{this.destination&&this._log.debug(this.destination.getInfo())}),{delay:e})}destroy(){this.videoContext.destroy(),this.smallVideoContext.destroy(),zw.clearTask(this._checkId)}get active(){return(Jk&&Wk||this._isMixScreen||this._isMirror||this._hasWaterMark)&&this.checkOrCreateVideoContext()}sendCreateResult(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:\"videoCtxGl\",t=arguments.length>1?arguments[1]:void 0;xO.emit(\"262\",{room:this._room,apiName:e,error:t})}checkOrCreateVideoContext(){if(this.videoContext.available){if(this.videoContext.hasAlpha||!this._hasWaterMark)return!0;this.clear(),this.videoContext.destroy()}else this.videoContext.glFaild&&(this.clear(),this._use2d=!0);let e=this.videoContext.create({alpha:this._hasWaterMark,use2d:this._use2d});return this.videoContext._gl?this.sendCreateResult():(this._use2d||(this.emit(\"error\",{reason:\"create\",error:e}),this.sendCreateResult(\"videoCtxGl\",e)),this.sendCreateResult(\"videoCtx2d\",this.videoContext.ctx2d?void 0:new Error(\"create 2d context failed\"))),this.videoContext.available}get smallTrack(){return this.smallDestination.videoTrack}get hasSmall(){return!!this.smallTrackSource||!!this.smallImageSource}get initialTrack(){var e;return this._isOpenVirtualBackground&&this._virtualBackgroundTrack?this._virtualBackgroundTrack:null==(e=this.cameraTrack)?void 0:e.mediaTrack}_setMainOutput(e){let t=this.cameraTrack,{small:i,settings:n}=t;return i&&(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1,use2d:!0}),this.smallDestination=new Nx(this.smallVideoContext,i)),this.smallVideoContext.frameRate=i.frameRate,this.smallDestination.resolution=i,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))),t.setOutputMediaStreamTrack(e?this.destination.videoTrack:this.initialTrack)}update(){return ab(this,null,(function*(){var e,t;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();{let{settings:e,profile:t}=this.cameraTrack;this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:\"mainDestination\"})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack),this.cameraNode.resize(e.width,e.height)),this.videoContext.frameRate=t.frameRate}let i=this.cameraNode;return i.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new Lx(this.videoContext)),i=i.connect(this.mirrorNode),i.disconnect(),this._log.info(\"start mirror\")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new Vx(this.videoContext),i.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),null==(e=this.waterMarkNode)||e.connect(this.mixNode,{zIndex:2}),this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack)),null==(t=this.screenNode)||t.connect(this.mixNode,{zIndex:0}),i=this.mixNode,this._log.info(\"start mix\",\"\".concat(this.mixNode.width,\"x\").concat(this.mixNode.height))),i.connect(this.destination),this._setMainOutput(this.videoContext._canvas)}))}changeInput(e,t){return this._log.info(\"change input\"),e instanceof cL?this.setScreenTrack(e):e instanceof sL?this.setCameraTrack(e):e instanceof CL?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}removeInput(e){var t;e instanceof cL?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof sL&&(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource))}setCameraTrack(e){return ab(this,null,(function*(){return this.cameraTrack=e,this._isOpenVirtualBackground&&(yield this.updateAr()),this.update()}))}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}loadImage(e){return new Promise(((t,i)=>{let n=new Image;n.crossOrigin=\"anonymous\",n.src=e,n.onload=()=>t(n),n.onerror=i}))}setWatermark(e){return ab(this,null,(function*(){let t=yield this.loadImage(e.imageUrl),{x:i=0,y:n=0,width:r=t.width,height:o=t.height}=e;this._hasWaterMark=!0,this._waterMarkOption={x:i,y:n,width:r,height:o,image:t},this._log.info(\"start watermark\",JSON.stringify({x:i,y:n,width:r,height:o})),this.update()}))}stopWatermark(){var e;!this._hasWaterMark||(this._hasWaterMark=!1,this._log.info(\"stop watermark\"),null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,this.update())}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update()}get mirror(){return this._isMirror}enableAr(e){return ab(this,null,(function*(){this.virtualBackgroundInstance=e,this._isOpenVirtualBackground=!0,this.virtualBackgroundInstance.ar.enable(this.cameraTrack.mediaTrack.clone()),this.virtualBackgroundInstance.ar.listen(\"output\",this.handleArOutput.bind(this))}))}handleArOutput(e){this._virtualBackgroundTrack=e,this.update()}updateAr(){return ab(this,null,(function*(){var e;null==(e=this.cameraTrack)||!e.mediaTrack||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))}))}disableAr(){var e;!this._isOpenVirtualBackground||(this._isOpenVirtualBackground=!1,null==(e=this._virtualBackgroundTrack)||e.stop(),this._virtualBackgroundTrack=null,this.update())}clear(){this.videoContext.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}},Ux=0,Fx=class extends Gw{constructor(e){super(\"room\"),this.seq=++Ux,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._isUsingCachedSchedule=!1,this._log=HO.createLogger({id:\"r\".concat(this.seq)}),this._joinedTimestamp=0,this._isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,sO(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),sO(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),sO(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this.keyPointManager=new lx({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new ux({room:this}),this.badCaseDetector=new hx({room:this}),this.audioManager=new vL({room:this}),this.videoManager=new xx({room:this})}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}getLogger(){return this._log}get isJoined(){return\"joined\"===this.state}get isLeft(){return\"left\"===this.state}addTrack(e){return ab(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return ab(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return ab(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error(\"Method not implemented.\")}enableAIVoice(e){throw new Error(\"Method not implemented.\")}setProxyServer(e){if(rO(e))e.startsWith(\"wss://\")?this.proxy_ws=e:e.startsWith(\"https://\")&&(this.proxy_wt=e);else if(ZD(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:n,scheduleProxy:r,unifiedProxy:o}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=o,o?(Tx([o,o]),pN(\"https://\".concat(o))):(n&&pN(n),r&&Tx(r))}}getRemoteAudioStats(){return ab(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return ab(this,null,(function*(){var e;let t={rtt:(null==(e=this.quality)?void 0:e.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let i of this.quality.downlinkInfo)t.downlinksRTT[i.userId]=i.rtt;return t}))}getRemoteVideoStats(){return ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:\"main\";return function*(){let i={};return e.remotePublishedUserMap.forEach((e=>{let n=\"auxiliary\"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;i[e.userId]=n.stat})),i}()}))}checkDestroy(){if(this._isDestroyed)throw new gb({code:mb.INVALID_OPERATION,message:qO({key:JO.CLIENT_DESTROYED,data:{funName:\"join\"}})})}destroy(){if(this.isJoined)throw this._log.warn(KO.INVALID_DESTROY),new gb({code:mb.INVALID_OPERATION,message:qO({key:JO.INVALID_DESTROY})});this._log.info(\"destroy room\"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this._isDestroyed=!0,xO.emit(FO.ROOM_DESTROY,{room:this})}schedule(e,t,i){return ab(this,null,(function*(){var n,r;let o=fO();try{let{isCached:s,result:a,detailCost:c}=yield fx({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:i,userSig:this.userSig,frameWorkType:t});this._isUsingCachedSchedule=s,this._log.info(\"schedule cache:\".concat(+s,\" \").concat(DO(a,{keysToExclude:[\"username\",\"credential\"]}))),s&&xO.once(FO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=$C($C({},this.scheduleResult),a),oO(null==(n=a.config)?void 0:n.retryCount)&&rD(a.config.retryCount),rO(null==(r=a.config)?void 0:r.loggerDomain)&&pN(a.config.loggerDomain),xO.emit(FO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:c}),xO.emit(FO.API_SUCCESS_RATE,{room:this,apiName:\"schedule\",cost:fO()-o})}catch(s){throw xO.emit(FO.API_SUCCESS_RATE,{room:this,apiName:\"schedule\",error:s}),s}}))}},Bx=new WeakMap,Hx=new WeakMap;function jx(){return function(e,t,i){let n=i.value,r=e=>{let{fn:t,args:i,context:n,resolve:r,reject:o}=e;t.apply(n,i).then(r,o)};return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i{if(Bx.has(this)){let o=Bx.get(this),{length:s}=o;o.push({fn:n,args:t,context:this,resolve:e,reject:i}),0===s&&r({fn:n,args:t,context:this,resolve:e,reject:i})}else Bx.set(this,[{fn:n,args:t,context:this,resolve:e,reject:i}]),r({fn:n,args:t,context:this,resolve:e,reject:i})})).finally((()=>{let e=Bx.get(this);e&&(e.shift(),e[0]&&r($C({},e[0])))}))},i}}function Gx(e){return function(t,i,n){let r=n.value,o=t=>oO(e)?t[e]:e(...t),s=e=>{let{fn:t,args:i,context:n,resolve:r,reject:a}=e;t.apply(n,i).then(r,a).finally((()=>{if(Hx.has(n)&&Hx.get(n).has(o(i))){let e=Hx.get(n).get(o(i));e&&(e.shift(),e[0]&&s($C({},e[0])))}}))};return n.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i{if(Hx.has(this))if(Hx.get(this).has(o(t))){let n=Hx.get(this).get(o(t));if(n){let{length:o}=n;n.push({fn:r,args:t,context:this,resolve:e,reject:i}),0===o&&s({fn:r,args:t,context:this,resolve:e,reject:i})}}else Hx.get(this).set(o(t),[{fn:r,args:t,context:this,resolve:e,reject:i}]),s({fn:r,args:t,context:this,resolve:e,reject:i});else{let n=new Map;n.set(o(t),[{fn:r,args:t,context:this,resolve:e,reject:i}]),Hx.set(this,n),s({fn:r,args:t,context:this,resolve:e,reject:i})}}))},n}}var Wx=nb(cb()),Jx=nb(hb()),Kx=e=>{let{serverAbility:t,clientAbility:i,offerSDP:n,enableCustomMessage:r}=e,o=BV(n),s={extmapAllowMixed:\"extmap-allow-mixed\",groups:o.groups,icelite:\"ice-lite\",media:[],msidSemantic:{semantic:\"\",token:\"WMS\"},name:\"-\",origin:{address:\"127.0.0.1\",username:\"-\",sessionId:String(Date.now()),sessionVersion:1,netType:\"IN\",ipVer:4},timing:{start:0,stop:0},version:0},a={candidates:t.candidates.map((e=>({component:1,foundation:\"1\",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:\"0.0.0.0\"},direction:LN.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:\"0\",payloads:String(t.audio.codecs[0].payload),port:o.media[0].port,protocol:o.media[0].protocol,type:LN.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map((e=>({payload:t.audio.codecs[0].payload,type:e.id,subtype:e.params[0]}))),rtcpMux:\"rtcp-mux\",rtcpRsize:\"rtcp-rsize\",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};return s.media.push(a),[1,2,3].forEach((e=>{s.media.push(Yx({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),r&&s.media.push(o.media.find((e=>\"dc\"===e.mid))),HV(s)},Yx=e=>{let{mid:t,serverAbility:i,clientAbility:n,parsedOffer:r,useAllCodec:o=!1}=e,s={candidates:i.candidates.map((e=>({component:1,foundation:\"1\",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:\"0.0.0.0\"},direction:LN.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(t),payloads:\"\",port:r.media[0].port,protocol:r.media[0].protocol,type:LN.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:\"rtcp-mux\",rtcpRsize:\"rtcp-rsize\",rtp:[]};if(i.video.codecs.length>0)if(o)for(let a=0;ae.codec.toLowerCase()===(i.useVp8?\"vp8\":\"h264\")));zx(s,i.video.codecs[e])}else if(o)for(let a=0;a{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 qx,Qx=e=>{let t=Jx.default.parse(e);return t.media.forEach((e=>{var i;(e.type===LN.AUDIO||e.type===LN.VIDEO)&&(function(e){if(!e.rtcpFb)return;let t=[];e.rtcpFb.forEach(((i,n)=>{var r;t.push(i),e.rtcpFb&&(null==(r=e.rtcpFb[n+1])?void 0:r.payload)!==i.payload&&\"rrtr\"!==i.type&&t.push({payload:i.payload,type:\"rrtr\"})})),e.rtcpFb=t}(e),function(e){e.type===LN.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes(\"apt\")||(e.config+=\";sps-pps-idr-in-keyframe=1\")}))}(e),function(e){e.type===LN.AUDIO&&e.fmtp&&e.fmtp.forEach((e=>{e.config+=\";sprop-stereo=1;stereo=1\"}))}(e),function(e){let t=new Set([\"urn:ietf:params:rtp-hdrext:sdes:mid\",\"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\",\"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}(e)),(null==(i=e.payloads)?void 0:i.includes(\"datachannel\"))&&t.groups&&e.mid&&(t.groups[0].mids=t.groups[0].mids.replace(e.mid,\"dc\"),e.mid=\"dc\")})),Jx.default.write(t)},Xx=((qx=Xx||{}).TRACK=\"track\",qx.DATA_CHANNEL_MESSAGE=\"data_channel_msg\",qx[qx.CONNECTION_STATE_CHANGED=\"connection-state-changed\"]=\"CONNECTION_STATE_CHANGED\",qx[qx.FIREWALL_RESTRICTION=\"firewall-restriction\"]=\"FIREWALL_RESTRICTION\",qx.RECONNECTED=\"spc-reconnected\",qx.RECONNECT_FAILED=\"spc-reconnect-failed\",qx.ERROR=\"error\",qx),Zx=0,$x=!1,eU=new Set,tU=1,iU=class extends Wx.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:n}=e;super(),ob(this,\"stat\",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),ob(this,\"currentState\",\"DISCONNECTED\"),ob(this,\"_room\"),ob(this,\"_signalChannel\"),ob(this,\"_peerConnection\",null),ob(this,\"_datachannel\",null),ob(this,\"_enableCustomMessage\"),ob(this,\"_log\"),ob(this,\"_downlinkMIDMap\",new Map),ob(this,\"_reconnectionTimer\",-1),ob(this,\"reconnectionCount\",0),ob(this,\"_clientAbility\",null),ob(this,\"_serverAbility\",null),ob(this,\"addDownlinkQueue\",new Set),ob(this,\"removeDownlinkQueue\",new Set),ob(this,\"_parsedAnswer\",null),ob(this,\"_updateSDPPromise\",null),ob(this,\"_waitForPCConnectedPromise\"),ob(this,\"_waitForPCConnectedPromiseReject\",null),ob(this,\"_isSDPLogged\",!1),this._room=i,this._enableCustomMessage=n,this._signalChannel=t,this._log=HO.createLogger({id:\"spc\".concat(tU++),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=BV(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 n;if(e.ssrcs&&!nO(e.ssrcs[0].id)){let r=Number(e.ssrcs[0].id),o=Number(null==(n=e.ssrcs.filter((e=>\"cname\"===e.attribute))[1])?void 0:n.id);switch(t){case 0:i.audioSsrc=r;break;case 1:i.bigVideoSsrc=r,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=r,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=r,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||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}initialize(){return ab(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.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let e=this._peerConnection.iceConnectionState;this._log.debug(\"ice state: \".concat(e)),\"checking\"===e&&0===this.stat.iceStartTime?this.stat.iceStartTime=Date.now():\"connected\"===e&&0===this.stat.iceEndTime&&(this.stat.iceEndTime=Date.now())},this._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 rU(e.data);this.emit(\"data_channel_msg\",{data:t})},this._datachannel.onerror=e=>{this._log.warn(\"datachannel error\",e)}),this._peerConnection.addTransceiver(LN.AUDIO,{direction:LN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(LN.VIDEO,{direction:LN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(LN.VIDEO,{direction:LN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(LN.VIDEO,{direction:LN.TRANSCEIVER_DIRECTION_SENDONLY});let e=yield this._peerConnection.createOffer();return yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;!e||(this._log.debug(\"dtls state: \".concat(e.state)),\"connecting\"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():\"connected\"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()))}),this._clientAbility=((e,t)=>{var i,n;let r=BV(e),o={ice:{ufrag:\"\",password:\"\"},dtls:{hash:\"\",fingerprint:\"\",setup:\"\"},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:t};o.ice.ufrag=String(r.media[0].iceUfrag),o.ice.password=r.media[0].icePwd||\"\",r.fingerprint&&(o.dtls.hash=r.fingerprint.type,o.dtls.fingerprint=r.fingerprint.hash,o.dtls.setup=r.setup||\"\"),r.media[0].fingerprint&&(o.dtls.hash=r.media[0].fingerprint.type,o.dtls.fingerprint=r.media[0].fingerprint.hash),o.dtls.setup=r.media[0].setup||\"\";let s=r.media[0],a=r.media[1];s.ext&&(o.audio.extensions=s.ext.map((e=>({id:e.value,uri:e.uri})))),a.ext&&(o.video.extensions=a.ext.map((e=>({id:e.value,uri:e.uri}))));let c={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};null==(i=s.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:n}=e;if(t===c.payload){let e={id:i,params:[]};n&&e.params.push(n),c.rtcpFb.push(e)}})),o.audio.codecs.push(c);for(let l=0;le.payload===a.rtp[l].payload))[0];o.video.codecs.push({payload:a.rtp[l].payload,codec:a.rtp[l].codec,fmtp:e?e.config:\"\",rate:a.rtp[l].rate,rtx:\"rtx\"===(null==(n=a.rtp[l+1])?void 0:n.codec)?a.rtp[l+1].payload:0,rtcpFb:((null==a?void 0:a.rtcpFb)||[]).filter((e=>e.payload===a.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(sN){throw this._log.error(\"initialize failed \".concat(sN)),sN}}))}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return ab(this,null,(function*(){try{if(\"CONNECTED\"===this.currentState)return;let i=fO(),n={type:\"answer\",sdp:Kx({serverAbility:e,clientAbility:this._clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(n),yield this.waitForPeerConnectionConnected(),t||xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:\"SPCConnect\",cost:Math.min(fO()-i,3e4)})}catch(aN){let i=aN instanceof gb&&aN.code===mb.API_CALL_ABORTED;throw i||this._log.error(\"connect failed: \".concat(aN),e),this.reset(),!i&&!this.isReconnecting&&(xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:\"SPCConnect\",error:aN}),this.emitConnectionStateChangedEvent(\"DISCONNECTED\"),this.startReconnection()),aN}}))}reconnect(){return ab(this,null,(function*(){if(-1===this._reconnectionTimer){if(!this._signalChannel.isConnected)return this._log.warn(\"reconnect() wait signal channel is connected\"),void this._signalChannel.once(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:AV,responseCommand:nV.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(sN){if(!this.isReconnecting)return;if(null!=sN&&sN.message.includes(\"timeout\")){let e=eO(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(sN)),xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:\"SPCReconnect\",error:sN}),this.reconnectionCount>=oD()&&this._log.warn(\"SDK has tried reconnect for \".concat(oD(),\" times, but all failed, please check your network\")),this.stopReconnection(),this.emitConnectionStateChangedEvent(\"DISCONNECTED\"),this.emit(\"error\")}}else this._log.warn(\"reconnect() is reconnecting, ignore current reconnection\")}))}getPeerConnection(){return this._peerConnection}startReconnection(){return ab(this,null,(function*(){this._log.warn(\"start reconnect\"),this.emitConnectionStateChangedEvent(\"RECONNECTING\");let e=fO();yield this.reconnect(),xO.emit(FO.API_SUCCESS_RATE,{room:this._room,apiName:\"SPCReconnect\",cost:Math.min(fO()-e,3e4)})}))}stopReconnection(){this.isReconnecting&&(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)===iD.CLOSED&&this.startReconnection()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();this._log.info(\"connectionState: \".concat(e.target.connectionState,\" ICE: \").concat(t,\" DTLS: \").concat(i)),e.target.connectionState===iD.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent(\"CONNECTING\")),(e.target.connectionState===iD.FAILED||e.target.connectionState===iD.CLOSED)&&(this.emitConnectionStateChangedEvent(\"DISCONNECTED\"),this.startReconnection()),(e.target.connectionState===iD.CONNECTED||e.target.connectionState===iD.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),xO.emit(FO.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent(\"CONNECTED\"))}getDTLSTransportState(){if(!this._peerConnection)return tD;let e=null;return Ew()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,Tw()&&0!==this._peerConnection.getReceivers().length&&e?e.state:tD):tD}emitConnectionStateChangedEvent(e){e!==this.currentState&&(\"RECONNECTING\"===this.currentState&&\"CONNECTING\"===e||(this.emit(Xx.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return ab(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(uw(i)){let t=e.get(i.localCandidateId),n=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):\"\")),n&&this._log.info(\"remote candidate: \".concat(n.candidateType,\" \").concat(n.protocol,\":\").concat(n.ip||n.address,\":\").concat(n.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),r(),e())},n=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),r(),t(new gb({code:mb.API_CALL_ABORTED,message:qO({key:JO.CONNECTION_ABORTED,data:\"leave room\"})})))},r=()=>{xO.off(FO.LEAVE_SUCCESS,n,this),this.off(Xx.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{r();let e=new gb({code:mb.API_CALL_TIMEOUT,message:\"connection timeout\"});Zx+=1,(e=>Zx>2&&!$x&&0===eU.size&&e)(this._signalChannel.isConnected)&&(this._log.warn(\"firewall restrition\"),$x=!0,this.emit(Xx.FIREWALL_RESTRICTION)),t(e)}),SD);xO.on(FO.LEAVE_SUCCESS,n,this),this.on(Xx.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 ab(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(sD){this._log.info(\"addDownlink(\".concat(e.userId,\") failed\")),yield this.startReconnection()}}))}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,userId:i,tinyId:n}=e;if(!this._peerConnection)return;this._log.info(\"updateLocalAndRemoteSDPConfig \".concat(i,\" \").concat(JSON.stringify(t)));let r,o,s,a=this._peerConnection.getTransceivers().filter((e=>\"inactive\"===e.direction)).slice(0,3).map((e=>(e.direction=LN.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));if(0===a.length&&(this._peerConnection.addTransceiver(LN.AUDIO,{direction:LN.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(LN.VIDEO,{direction:LN.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(LN.VIDEO,{direction:LN.TRANSCEIVER_DIRECTION_RECVONLY})),this._parsedAnswer||(this._parsedAnswer=BV(this._peerConnection.remoteDescription.sdp)),3===a.length)r=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[0]))),o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[1]))),s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[2])));else{r=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=Yx({mid:1,serverAbility:this._serverAbility,clientAbility:this._clientAbility,parsedOffer:BV(this._peerConnection.localDescription.sdp),useAllCodec:!0});o=JSON.parse(JSON.stringify(e)),s=JSON.parse(JSON.stringify(e)),r.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(r),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s)}r.direction=LN.TRANSCEIVER_DIRECTION_SENDONLY,r.ssrcs=[{id:t.audio,attribute:\"cname\",value:\"\".concat(n)},{id:t.audio,attribute:\"msid\",value:\"\".concat(n,\"-\").concat(LN.MAIN,\" \").concat(n,\"-audio\")}],o.direction=LN.TRANSCEIVER_DIRECTION_SENDONLY,o.ssrcs=[{id:t.video,attribute:\"cname\",value:\"\".concat(n)},{id:t.video,attribute:\"msid\",value:\"\".concat(n,\"-\").concat(LN.MAIN,\" \").concat(n,\"-bigvideo\")},{id:t.videoRtx,attribute:\"cname\",value:\"\".concat(n)},{id:t.videoRtx,attribute:\"msid\",value:\"\".concat(n,\"-\").concat(LN.MAIN,\" \").concat(n,\"-bigvideo\")}],o.ssrcGroups=[{semantics:\"FID\",ssrcs:\"\".concat(t.video,\" \").concat(t.videoRtx)}],s.direction=LN.TRANSCEIVER_DIRECTION_SENDONLY;let c=\"\".concat(n,\"-aux\");s.ssrcs=[{id:t.auxiliary,attribute:\"cname\",value:c},{id:t.auxiliary,attribute:\"msid\",value:\"\".concat(c,\" \").concat(n,\"-aux\").concat(LN.VIDEO)},{id:t.auxiliaryRtx,attribute:\"cname\",value:\"\".concat(c,\" \").concat(n,\"-aux\").concat(LN.VIDEO)},{id:t.auxiliaryRtx,attribute:\"msid\",value:\"\".concat(c,\" \").concat(n,\"-aux\").concat(LN.VIDEO)}],s.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(n,[r.mid,o.mid,s.mid])}removeDownlink(e,t){return ab(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),n=!1;this._peerConnection.getTransceivers().forEach((e=>{null!=i&&i.includes(Number(e.mid))&&(n=!0,e.direction=\"inactive\")})),this._parsedAnswer||(this._parsedAnswer=BV(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((e=>{null!=i&&i.includes(Number(e.mid))&&(n=!0,e.direction=\"inactive\",e.ssrcs=[],e.ssrcGroups=[])})),0===this.removeDownlinkQueue.size&&n&&(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 ab(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:n,auxVideo:r}=e;try{if(Rw()){let e=this._peerConnection.getSenders().slice(0,4);for(let o=0;oab(this,null,(function*(){var o,s;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:r}),this._updateSDPPromise=null,e()}catch(a){this._log.error(a),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(\"transceivers: \".concat(JSON.stringify(this._peerConnection.getTransceivers().map((e=>{let{mid:t,currentDirection:i,direction:n,stopped:r}=e;return{mid:t,currentDirection:i,direction:n,stopped:r}}))))),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(r)||(null==(s=this._peerConnection.remoteDescription)?void 0:s.sdp)),this._isSDPLogged=!0),this._updateSDPPromise=null,n(a)}})))),this._updateSDPPromise}setOffer(e){return this._log.info(\"setting offer\"),this._peerConnection.setLocalDescription({type:\"offer\",sdp:Qx(e.sdp)})}setAnswer(e){return this._log.info(\"setting answer\"),this._room.enableHWEncoder&&e.sdp&&(e.sdp=e.sdp.replaceAll(\"42e01f\",\"42001f\")),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()}};rb([jx()],iU.prototype,\"updateSDP\",1);var nU=class{constructor(e){ob(this,\"tag\"),ob(this,\"len\"),ob(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}},rU=class{constructor(e){ob(this,\"tinyId\"),ob(this,\"data\");let t=new DataView(e),i=0,n=[];for(;i{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},oU=new Set;function sU(){let e=Math.floor(4294967296*Math.random());return oU.has(e)?sU():(oU.add(e),e)}var aU=nb(cb()),cU=class extends aU.default{constructor(e){super(),ob(this,\"userId\"),ob(this,\"tinyId\"),ob(this,\"_sdpSemantics\"),ob(this,\"_isUplink\"),ob(this,\"_room\"),ob(this,\"_log\"),ob(this,\"_signalChannel\"),ob(this,\"_currentState\",\"DISCONNECTED\"),ob(this,\"_prevTime\",-1),ob(this,\"_enableSEI\"),ob(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=HO.createLogger({id:\"n\",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&kw&&(this._sei=new PV(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&&(xO.emit(FO.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\"))}},lU=class extends cU{constructor(e){super(eb($C({},e),{isUplink:!0})),ob(this,\"localMainAudioTrack\",null),ob(this,\"localMainVideoTrack\",null),ob(this,\"localAuxAudioTrack\",null),ob(this,\"localAuxVideoTrack\",null),ob(this,\"_isPublishingAux\",!1),ob(this,\"_publishingLocalAudioTrack\"),ob(this,\"_publishingLocalVideoTrack\"),ob(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}),ob(this,\"_audioManager\"),this._audioManager=e.audioManager,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:n,smallVideoRtxSsrc:r,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:n||0,smallRtx:r||0,auxiliary:o||0,auxiliaryRtx:s||0}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,n;let r={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(Sw()?(r.audio=!(null==(e=o[0])||!e.track),r.bigVideo=!(null==(t=o[1])||!t.track),r.smallVideo=!(null==(i=o[2])||!i.track),r.auxVideo=!(null==(n=o[3])||!n.track)):o.forEach((e=>{e.track&&(e.track.kind===LN.AUDIO?r.audio=!0:(r.bigVideo=!0,this._room.videoManager.hasSmall&&(r.smallVideo=!0)))})))}return r}initialize(){this.installEvents()}reset(){this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent(\"DISCONNECTED\")}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,n,r;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit(\"connection-state-changed\",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit(\"connection-state-changed\",{prevState:o,state:e}),null==(n=this.localAuxVideoTrack)||n.emit(\"connection-state-changed\",{prevState:o,state:e}),null==(r=this._publishingLocalVideoTrack)||r.emit(\"connection-state-changed\",{prevState:o,state:e}))),s}publish(e){return ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,isAuxiliary:r}=e;return function*(){var e,o,s,a,c,l;if(!t.singlePC)return;if(yield t.singlePC.waitForPeerConnectionConnected(),i&&(t._publishingLocalAudioTrack=i),n){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new gb({code:mb.NOT_SUPPORTED_H264,message:qO({key:JO.NOT_SUPPORTED_H264ENCODE})});Lb&&115===wk()&&n.profile.width*n.profile.height<=230400&&(t._log.warn(\"fallback video to 480p\"),n.setProfile(wN[\"480p_2\"]),yield n.applyProfile()),t._publishingLocalVideoTrack=n}let d;t._isPublishingAux=r,n&&!r&&n.small&&(d=t._room.videoManager.smallTrack),Iw()&&(yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:n,smallTrack:d,isAuxiliary:r})),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r?(n&&(t.localAuxVideoTrack=n),i&&(t.localAuxAudioTrack=i)):(n&&(t.localMainVideoTrack=n),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==(s=t.localMainVideoTrack)?void 0:s.profile.bitrate,smallVideo:null==(c=null==(a=t.localMainVideoTrack)?void 0:a.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),yield t._signalChannel.sendWaitForResponse({command:CV,responseCommand:nV.SPC_PUBLISH_RESULT,data:eb($C({},t.singlePC.uplinkSSRC),{state:t.publishState})}),t.sendMediaSettings(),t.installTrackMuteEvents(i,n),t.sendMutedFlag()}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:n,isAuxiliary:r}=e;this._log.info(\"publish by transceiver\");let o=null==i?void 0:i.outMediaTrack,s=this._audioManager.mixedAudioTrack,a=this._peerConnection.getTransceivers(),c=[],l=[];if(s){let e=a[0].sender.replaceTrack(s);l.push(0),c.push(e)}if(o)if(r){let e=a[3].sender.replaceTrack(o);l.push(3),c.push(e)}else{let e=a[1].sender.replaceTrack(o);l.push(1),c.push(e)}if(n){let e=a[2].sender.replaceTrack(n);l.push(2),c.push(e)}let d=this.setTransceiverDirection(MN.SENDONLY,l);return c.push(d),Promise.all(c)}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i{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&&(null==e||e.off(\"mute\",this.sendMutedFlag,this),null==e||e.off(\"unmute\",this.sendMutedFlag,this))}))}unpublish(e){return ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n}=e;return function*(){let e=n&&n===t.localAuxVideoTrack,r=null==n?void 0:n.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(t._audioManager.mixedAudioTrack||(yield o[0].replaceTrack(null),s.push(0)),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),r&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=eb($C({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=eb($C({},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(MN.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),null==n||n.emit(\"connection-state-changed\",{prevState:t._currentState,state:\"DISCONNECTED\"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return ab(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:dV,data:t,responseCommand:nV.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:uV,commandDesc:\"unpublish\",responseCommand:nV.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===mb.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:n,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Cw){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate)}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info(\"updateMediaSettings: \".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:yV,data:this._mediaSettings,responseCommand:nV.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return ab(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?LN.AUXILIARY:LN.MAIN,\" stream\")),null==(t=this._sei)||t.handleEncodedStreams(),Sw()&&(yield this.addTrackByTransceiver(e,i))}))}addTrackByTransceiver(e,t){return ab(this,null,(function*(){var i;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===LN.AUDIO)yield n[0].sender.replaceTrack(this._audioManager.mixedAudioTrack);else{let r=t?3:1;yield n[r].sender.replaceTrack(e.outMediaTrack),1===r&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[r].direction===MN.INACTIVE&&(yield this.setTransceiverDirection(MN.SENDONLY,[r]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return ab(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(\"is removing \".concat(e.kind,\" track from current published local \").concat(t?LN.AUXILIARY:LN.MAIN,\" stream\")),Sw()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return ab(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===LN.AUDIO)this._audioManager.mixedAudioTrack||(yield i[0].sender.replaceTrack(null));else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._room.videoManager.hasSmall&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(MN.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return ab(this,null,(function*(){if(!Ub)return;let i=!1,n=!1;this._log.info(\"setting transceiver \".concat(t.join(\",\"),\" direction to \").concat(e));let r=this._peerConnection.getTransceivers();if(t.forEach((t=>{r[t].direction!==e&&(r[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,s=this._peerConnection.remoteDescription.sdp.split(\"\\r\\n\").map((i=>{if(i.match(new RegExp(\"a=(\".concat(MN.INACTIVE,\"|\").concat(MN.RECVONLY,\"|\").concat(MN.SENDONLY,\")\")))&&o++,t.includes(o)){if(e===MN.INACTIVE&&i.includes(\"a=\".concat(MN.RECVONLY)))return n=!0,\"a=\".concat(e);if(e===MN.SENDONLY&&i.includes(\"a=\".concat(MN.INACTIVE)))return n=!0,\"a=\".concat(MN.RECVONLY)}return i})).join(\"\\r\\n\");n&&(this._log.info(\"updating answer\"),yield this._peerConnection.setRemoteDescription({type:\"answer\",sdp:s}))}))}replaceTrack(e){return ab(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders(),n=e.mediaTrack;if(!i||0===i.length||!n)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(\"is replacing \".concat(n.kind,\" track on \").concat(r?LN.AUXILIARY:LN.MAIN,\" stream\")),n.kind===LN.AUDIO&&i[0]&&(yield i[0].replaceTrack(this._audioManager.mixedAudioTrack)),n.kind===LN.VIDEO&&(!r&&i[1]&&(yield i[1].replaceTrack(e.outMediaTrack||n)),r&&i[3]&&(yield i[3].replaceTrack(e.outMediaTrack)))}))}setBandwidth(e){return ab(this,arguments,(function(e){var t=this;let{bandwidth:i,type:n,videoType:r}=e;return function*(){if(t.singlePC){let e={};n===LN.AUDIO?e.audio=i:\"big\"===r?e.bigVideo=i:\"small\"===r?e.smallVideo=i:e.auxVideo=i,yield t.singlePC.setBandwidth(e)}}()}))}sendMutedFlag(e){var t,i,n;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(i=this.localMainVideoTrack)||!i.muted),auxVideo:!(null==(n=this.localAuxVideoTrack)||!n.muted)};this._log.info(\"send muted state: \".concat(JSON.stringify(r))),this._signalChannel.send(cV,r)}handleConnectionStateChange(e){\"CONNECTED\"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&xO.emit(FO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:LN.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===LN.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===LN.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===LN.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===LN.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return\"\"}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===_D?(this._log.error(KO.NOT_SUPPORTED_H264ENCODE),new gb({code:mb.NOT_SUPPORTED_H264,message:qO({key:JO.NOT_SUPPORTED_H264ENCODE})})):new gb({code:mb.UNKNOWN,message:qO({key:JO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:nV.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}onSinglePCReconnected(){return ab(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}))}))}};function dU(e){return Object.keys(e).filter((t=>e[t]))}var uU=class extends cU{constructor(e){super(eb($C({},e),{isUplink:!1})),ob(this,\"_flag\",0),ob(this,\"role\",\"anchor\"),ob(this,\"remoteAudioTrack\"),ob(this,\"remoteVideoTrack\"),ob(this,\"remoteAuxiliaryTrack\"),ob(this,\"ssrc\",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),this.flag=e.flag,this.remoteAudioTrack=new RL(this._room,this),this.remoteVideoTrack=new CL(this._room,this),this.remoteAuxiliaryTrack=new bL(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 IO(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,n;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(n=this.remoteAuxiliaryTrack)||n.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===LN.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent(\"DISCONNECTED\"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners(\"track\").includes(this.onTrack)||this.singlePC.on(\"track\",this.onTrack,this),this.listeners(\"spc-reconnected\").includes(this.onSinglePCReconnected)||this.singlePC.on(\"spc-reconnected\",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off(\"track\",this.onTrack,this),this.singlePC.off(\"spc-reconnected\",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let n=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&n!==e&&(null==(t=this.remoteVideoTrack)||t.emit(\"connection-state-changed\",{prevState:n,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit(\"connection-state-changed\",{prevState:n,state:e})),r}onTrack(e){let t=e.streams[0],{track:i}=e;if(t.id.split(\"-\")[0]!==this.tinyId)return;let n=t.id.includes(\"aux\")?\"auxiliary\":\"main\";this._log.debug(\"ontrack \".concat(n,\" \").concat(i.kind));let r=LN.AUDIO;i.kind===LN.VIDEO&&(r=n===LN.MAIN?LN.VIDEO:LN.AUXILIARY);let o=this.remoteAudioTrack;r===LN.VIDEO?o=this.remoteVideoTrack:r===LN.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return ab(this,null,(function*(){try{if(this.isSubscriptionStateNotChanged(e))return;if(this._log.info(\"subscribe \".concat(t,\" \").concat(dU(e))),this.hasSSRC){let t=\"subscribe_change\";Object.values(e).find((e=>!0===e))||(t=\"unsubscribe\"),yield this.sendSubscription(t,e)}else yield this.doSubscribe(e)}catch(aN){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(\"\".concat(aN.message,\" \").concat(JSON.stringify(this.muteState))),new gb({code:mb.REMOTE_STREAM_NOT_EXIST,message:\"remote user \".concat(this.userId,\" unpublished stream\")})):aN}}))}unsubscribe(e){return ab(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:n}=e;return function*(){var e;if(\"main\"===n&&!t.isMainStreamSubscribed||\"auxiliary\"===n&&!t.isAuxStreamSubscribed)return void t._log.info(\"\".concat(n,\" stream already unsubscribed\"));let r=$C({},t.subscribeState);i.forEach((e=>{switch(e.mediaType){case 1:r.audio=!1;break;case 4:r.video=!1;break;case 8:r.smallVideo=!1;break;case 2:r.auxiliary=!1}}));let o=\"subscribe_change\";Object.values(r).find((e=>!0===e))||(o=\"unsubscribe\"),t._log.info(\"\".concat(\"unsubscribe\"===o?o:\"subscribe\",\" \").concat(n,\" [\").concat(dU(r),\"]\")),\"unsubscribe\"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,r),\"unsubscribe\"===o&&(yield t.removeDownlink())}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},n=pV,r=nV.UNSUBSCRIBE_RESULT;return\"subscribe_change\"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=_V,r=nV.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:i,responseCommand:r,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new gb({code:i.code,message:qO({key:JO.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:\"\"}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:\"\"}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}onSinglePCReconnected(){(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 ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){if(e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected(),i||!e.hasSSRC){let i={audioSsrc:sU(),bigVideoSsrc:sU(),bigVideoRtxSsrc:sU(),auxVideoSsrc:sU(),auxVideoRtxSsrc:sU()},{audioSsrc:n,bigVideoSsrc:r,bigVideoRtxSsrc:o,auxVideoSsrc:s,auxVideoRtxSsrc:a}=i;e.ssrc={audio:n,video:r,videoRtx:o,auxiliary:s,auxiliaryRtx:a},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});let c=yield e._signalChannel.sendWaitForResponse({command:bV,responseCommand:nV.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!1,ssrc:i}});if(0!==c.data.code)throw yield e.removeDownlink(),new gb({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 ab(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))}))}};rb([iL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n{let r=e=>{this.off(\"closed\",r),n(new gb({code:mb.API_CALL_ABORTED,message:qO({key:JO.CONNECTION_ABORTED,data:e})}))};this.on(\"closed\",r),e.apply(this,i).then(t,n).finally((()=>{this.off(\"closed\",r)}))}))}))],uU.prototype,\"subscribe\",1);var hU=uU;var{isString:pU,isPlainObject:_U,isUndefined:mU,getNetworkType:fU,getTerminalType:gU,isEmpty:TU}=Ib,EU=class extends Fx{constructor(e){super(e),this.privateMapKey=\"\",this._heartbeat=-1,this._lastHeartBeatTime=-1,this._joinTimeout=-1,this._firstPublishedList=null,this._joinReject=null,this._isRelayChanged=!1,this._signalChannel=null,this.uplinkConnection=null,this.singlePC=null,this.enableSPC=vw,this._changeBigSmallRecords=new Map,this._networkQuality=null,this._networkType=fU(),this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=0,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this.enableHWEncoder=!1,this._stats=new QV(this,this._log),this.userManager=new KL(this.userId,this._log),this._version=rN,this.sdpSemantics=pD,mU(e.sdpSemantics)?WO.isUnifiedPlanDefault()&&(this.sdpSemantics=hD):this.sdpSemantics=e.sdpSemantics,this._log.info(\"sdpSemantics: \".concat(this.sdpSemantics,\", netType: \").concat(this._networkType)),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!mU(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!mU(e.enableSPC)&&vw&&(this.enableSPC=e.enableSPC),this.enableHWEncoder=e.enableHWEncoder||!1,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 ab(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on(\"1\",(e=>{this.emit(\"peer-join\",e)})),this.userManager.on(\"2\",(e=>{this.closeDownLinkConnection(e,\"remote user exitRoom\"),this.emit(\"peer-leave\",e)})),this.userManager.on(\"3\",this.createDownlinkConnection,this),this.userManager.on(\"5\",this.closeDownLinkConnection,this),this.userManager.on(\"6\",(e=>{var t=((e,t)=>{var i={};for(var n in e)zC.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&KC)for(var n of KC(e))t.indexOf(n)<0&&qC.call(e,n)&&(i[n]=e[n]);return i})(e,[]);xO.emit(FO.REMOTE_PUBLISH_STATE_CHANGED,$C({room:this},t)),this.emit(\"remote-publish-state-changed\",$C({},t))})),this._joinOptions=e,new Promise(((t,i)=>ab(this,null,(function*(){this._joinReject=i;try{this.checkDestroy();let i=yield this.initialize();yield this.doJoin(e,i),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(qx){i(qx)}this._joinReject=null}))))}))}doJoin(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise(((i,n)=>ab(this,null,(function*(){var r,o,s;let a;if(e.privateMapKey&&(this.privateMapKey=e.privateMapKey),this._signalChannel.once(zM,(e=>{this.clearJoinTimeout(),xO.emit(FO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),n(e)})),sO(null==(o=null==(r=this.scheduleResult)?void 0:r.config)?void 0:o.singlePC)&&vw&&(this.enableSPC=this.scheduleResult.config.singlePC),this.enableSPC&&!this.singlePC){this.singlePC=new iU({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.once(\"error\",(()=>this.fallbackToMPC()));try{a=yield this.singlePC.initialize()}catch(d){this.fallbackToMPC()}}this.keyPointManager.setConnectionType(this.singlePC?1:2);let c={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,trtcRole:e.role,trtcScene:\"live\"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||\"\",terminalType:gU(),netType:kN[this._networkType],bussinessInfo:this._businessInfo,ability:a};t&&(c.userSig=this.userSig),this._log.debug(\"join room signal data: \".concat(JSON.stringify(c)));let l=5e3;(null==(s=this.scheduleResult.config)?void 0:s.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(l=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{n(new gb({code:mb.JOIN_ROOM_FAILED,message:qO({key:JO.JOIN_ROOM_TIMEOUT})}))}),l),xO.emit(FO.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?RV:oV,c),this._signalChannel.once(nV.JOIN_ROOM_RESULT,(e=>{this.clearJoinTimeout();let{code:t,message:r,data:o}=e.data;xO.emit(FO.JOIN_RECEIVED_CMD_RES,{room:this,code:t}),0===t?(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((()=>{})),i()):(this._log.error(\"Join room failed result: \".concat(t,\" error: \").concat(r)),n(new gb({code:mb.JOIN_ROOM_FAILED,extraCode:t,message:qO({key:JO.JOIN_ROOM_FAILED,data:{error:r,code:t}})})))}))}))))}reJoin(){return ab(this,null,(function*(){if(this.isJoined)try{if(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(eb($C({},this._joinOptions),{role:\"anchor\"===this.role?20:21,privateMapKey:this.privateMapKey})),this._log.warn(\"reJoin success\"),Qw.logSuccessEvent({userId:this.userId,eventType:cD.REJOIN}),this.singlePC){let e=t=>{var i;\"CONNECTED\"===t.state&&(null==(i=this.singlePC)||i.off(Xx.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof lU&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.doSubscribe()})))};this.singlePC.on(Xx.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof qV&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(sN){this._log.warn(\"reJoin fail \".concat(sN)),this.reset(),Qw.logFailedEvent({userId:this.userId,eventType:cD.REJOIN,error:sN}),this.emit(\"error\",new gb({code:mb.JOIN_ROOM_FAILED,message:qO({key:JO.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}else this._log.warn(\"reJoin abort\")}))}initialize(){return ab(this,null,(function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),i=this._signalChannel||function(e){let t=[...NV.values()].find((t=>t.room.userId===e&&!t.room.isJoined));return t||null}(this.userId),n=!!(i&&i.isConnected&&i.keepAlive);return this._log.info(\"setup signal channel. reuse: \".concat(+n)),n?(i.url=e,i.backupUrl=t,i.room=this,this._signalChannel=i):this._signalChannel=new DV({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this}),this._networkQuality||(this._networkQuality=new $V({signalChannel:this._signalChannel,room:this}),this._networkQuality.on($V.EVENT_NETWORK_QUALITY,(e=>{this.emit(\"network-quality\",e)}))),SP(this,this._signalChannel).add(qM,(e=>{xO.emit(FO.SIGNAL_CONNECTION_STATE_CHANGED,$C({room:this},e)),this.emit(\"signal-connection-state-changed\",e)})).add(XM,(e=>{this.reset(),this.emit(\"error\",e)})).add(nV.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:n}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:n})})).add(nV.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(nV.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(nV.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(Qw.uploadEvent({log:\"stat-banned:\".concat(i),userId:this.userId}),\"user_time_out\"===i)return this._log.warn(\"\".concat(i,\" last heart beat time: \").concat(this._lastHeartBeatTime,\" interval: \").concat(Date.now()-this._lastHeartBeatTime,\", visibility: \").concat(document.visibilityState)),void this.reJoin();this._log[\"kick\"===i?\"error\":\"info\"](\"user was banned because of [\".concat(i,\"]\")),this.reset(),this.emit(\"banned\",{reason:i})})),this._signalChannel.once(YM,(e=>{this.tinyId=e.signalInfo.tinyId,xO.emit(FO.JOIN_SIGNAL_CONNECTION_END,{room:this})})),xO.emit(FO.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this._signalChannel.connect(this._isUsingCachedSchedule?1e4:void 0),n}))}setSignalChannel(e){this._signalChannel=e,e||IP(this)}leave(){return ab(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(sD){}this._log.info(\"leave() => leaving room\"),xO.emit(FO.LEAVE_SEND_CMD,{room:this}),null==(e=this._signalChannel)||e.send(sV)}))}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=zw.run(wD,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info(\"stopHeartbeat\"),zw.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return ab(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});if(this.badCaseDetector.resetMonitor(),null==(e=this._signalChannel)||!e.isConnected)return;let n=this._signalChannel.isConnected?function(e){if(GL.has(e)){let t=GL.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc})));return GL.delete(e),t}return[]}(this.userId):[],r=$C({str_sdk_version:nN,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:kN[this._networkType]},msg_event_msg:n,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i);xO.emit(FO.HEARTBEAT_REPORT,{room:this,report:r}),this._signalChannel.send(aV,r),this.emit(\"heartbeat-report\",eb($C({},r),{bytes_sent:this._stats.totalBytesSent+this._signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this._signalChannel.bytesReceived}));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:n}=e,r=this.remotePublishedUserMap.get(t);return r&&this._changeBigSmallRecords.has(t)&&this.checkSubscribeBigSmallVideo(r),{userId:t,tinyId:i,flag:n}}));xO.emit(FO.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:n}=e,r=new(this.singlePC?hU:JV)({userId:t,tinyId:i,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:n});this.userManager.addRemotePublishedUser(r),this.installDownlinkEvents(r,t),this.emit(\"remote-published\",r)}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!==mb.ICE_TRANSPORT_ERROR&&(i===mb.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit(\"error\",e))})),e.on(\"connection-state-changed\",(t=>{this.emit(\"media-connection-state-changed\",eb($C({},t),{userId:e.userId}))})),e.on(\"firewall-restriction\",(()=>{this.emit(\"firewall-restriction\")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=zw.run(wD,this.syncUserList.bind(this)))}stopSyncUserListInterval(){zw.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:IV,responseCommand:nV.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((e=>{let{data:t}=e,{code:i,message:n}=t;if(0===i)return(t.data&&t.data.userList||[]).map((e=>{let{userId:t,srcTinyId:i,role:n}=e;return{userId:t,tinyId:i,role:n}}));throw qO({key:JO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:nV.USER_LIST_RES,code:i,message:n}})})):Promise.reject(\"not connected\")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this._signalChannel&&!this._signalChannel.isOnline||!xV)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{if(e instanceof UV&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===iD.CLOSED&&(this._log.warn(\"[\".concat(e.getUserId(),\"] pc is closed but not reconnect\")),e.startReconnection())}}))}fallbackToMPC(){return ab(this,null,(function*(){var e;if(this._log.warn(\"fallback to multi pc\"),Qw.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 qV({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 JV({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||(this._signalChannel&&(this._log.info(\"destroying SignalChannel\"),this._signalChannel.close(),this._signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new gb({code:mb.INVALID_OPERATION,message:qO({key:JO.CLIENT_DESTROYED,data:{funName:\"join\"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return ab(this,null,(function*(){this.role!==e&&(\"audience\"===e&&this.uplinkConnection&&this.closeUplink(\"you switch role to audience\"),yield this.doSwitchRole(e))}))}doSwitchRole(e){let t={command:vV,data:{role:\"anchor\"===e?20:21,privateMapKey:this.privateMapKey},responseCommand:nV.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:n}=t.data;if(0!==i)throw new gb({code:mb.SWITCH_ROLE_FAILED,message:qO({key:JO.SWITCH_ROLE_FAILED,data:{message:n,code:i}})});this.role=e})).catch((e=>{throw e instanceof gb&&e.getCode()===mb.API_CALL_TIMEOUT&&(e=new gb({code:mb.SWITCH_ROLE_FAILED,message:qO({key:JO.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e}))}publish(){for(var e=arguments.length,t=new Array(e),i=0;i{t instanceof oL&&(t instanceof lL?i.audio=t:e.audio=t),t instanceof sL&&(t instanceof cL&&2===t.mediaType?i.video=t:e.video=t)}));let n=TU(e),r=TU(i);(!n||!r)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new lU({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new qV({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\",eb($C({},e),{userId:this.userId}))})),this.uplinkConnection.on(\"firewall-restriction\",(()=>{this.emit(\"firewall-restriction\")})),this.uplinkConnection.on(\"error\",(e=>{let t=e.getCode();t!==mb.ICE_TRANSPORT_ERROR&&(t===mb.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit(\"error\",e))})));let o=t.map((e=>e.kind)).join(\",\");n||(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\")),r||(this._log.info(\"publish() => aux \".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:i.audio,localVideoTrack:i.video,isAuxiliary:!0}),this._log.info(\"aux is published\"))}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i{!t.mediaTrack||(t instanceof oL&&(t instanceof lL?i.audio=t:e.audio=t),t instanceof sL&&(t instanceof cL&&2===t.mediaType?i.video=t:e.video=t))}));try{let n=t.map((e=>e.kind)).join(\",\");TU(e)||(this._log.info(\"unpublish() => main \".concat(n)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),TU(i)||(this._log.info(\"unpublish() => aux \".concat(n)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(n){}0===this.localTracks.size&&!this.audioManager.mixedAudioTrack&&this.closeUplink(\"you unpublished\")}))}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return this.uplinkConnection&&e.mediaTrack?this.uplinkConnection.removeTrack(e).then((t=>(e.unpublish(),t))):Promise.resolve()}replaceTrack(e){return this.uplinkConnection&&e.mediaTrack?this.uplinkConnection.replaceTrack(e).then((t=>{xO.emit(FO.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return ab(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i!e.isSubscribed)),0===t.length)return;let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let n=t.find((e=>2===e.mediaType))?\"auxiliary\":\"main\";try{let r=$C({},i.subscribeState);t.forEach((e=>{switch(e.mediaType){case 1:r.audio=!0;break;case 4:r.video=!0;break;case 2:r.auxiliary=!0}}));let o=this._changeBigSmallRecords.get(e);o&&o.options.smallVideo&&i.muteState.hasSmall&&r.video&&(r.video=!1,r.smallVideo=!0),xO.emit(FO.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:i,subscribeState:r}),this._log.info(\"subscribe() => \".concat(e,\" \").concat(n,\" [\").concat(jV(r),\"] prev: [\").concat(jV(i.subscribeState),\"]\")),yield i.subscribe(r,n);for(let e of t)e.mediaTrack||(yield e.waitHasMediaTrack());i.remoteVideoTrack.setMediaType(r.smallVideo?8:4),xO.emit(FO.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:i})}catch(cN){let i=cN instanceof gb?cN.getCode():mb.UNKNOWN,r=cN;throw cN instanceof gb?i===mb.REMOTE_STREAM_NOT_EXIST&&(r=new gb({code:mb.API_CALL_ABORTED,message:qO({key:JO.API_CALL_ABORTED,data:{message:cN.message,userId:e,streamType:n}})}),this._log.warn(r)):(r=new gb({code:i,message:qO({key:JO.SUBSCRIBE_FAILED,data:{message:cN.message,userId:e,streamType:n}})}),this._log.error(r)),r}}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i2===e.mediaType))?\"auxiliary\":\"main\";this._log.info(\"unsubscribe() => \".concat(e,\" \").concat(n));try{yield i.unsubscribe({remoteTracks:t,streamType:n})}catch(cN){this._log.warn(\"unsubscribe() => failed \".concat(cN))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),xO.emit(FO.UNSUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:i})}))}setEncodedDataProcessingListener(e){throw new Error(\"Method not implemented.\")}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1?arguments[1]:void 0;if(e<=0)return this._enableAudioVolumeEvaluation=!1,void zw.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),xO.emit(FO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&zw.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=zw.run(PD,(()=>{var e;let t=[];null==(e=this.remotePublishedUserMap)||e.forEach((e=>{if(e.muteState.hasAudio){let i=Math.floor(100*e.remoteAudioTrack.getAudioLevel());t.push({userId:e.userId,volume:i})}})),this.emit(\"audio-volume\",t)}),{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return ab(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 ab(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:n,framesSent:r,frameWidth:o,frameHeight:s}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:i,framesEncoded:n,framesSent:r,frameWidth:o,frameHeight:s}}return e}))}getTransportStats(){return ab(this,null,(function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let i=yield this._stats.getReceiverStats(t);e.downlinksRTT[i.userId]=i.rtt}return e}))}getRemoteVideoStats(e){return ab(this,null,(function*(){let t={};for(let[i,n]of this.remotePublishedUserMap)\"main\"===e&&n.muteState.hasVideo&&(t[i]=n.remoteVideoTrack.stat),\"auxiliary\"===e&&n.muteState.hasAuxiliary&&(t[i]=n.remoteAuxiliaryTrack.stat);return t}))}getRemoteAudioStats(){return ab(this,null,(function*(){let e={};for(let[t,i]of this.remotePublishedUserMap)i.muteState.hasAudio&&(e[t]=i.remoteAudioTrack.stat);return e}))}setTurnServer(e,t){this._log.info(\"set turn server: \".concat(JSON.stringify(e),\" \").concat(t||\"\"));let i=[];Array.isArray(e)?e.forEach((e=>i.push(Ib.getTurnServer(e)))):Ib.isPlainObject(e)&&i.push(Ib.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:EV,data:e,timeout:5e3,responseCommand:nV.START_MIX_TRANSCODE_RES,commandDesc:\"startMixTranscode\"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:SV,data:e,timeout:5e3,responseCommand:nV.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?mV:gV,data:e,timeout:5e3,responseCommand:t?nV.START_PUBLISH_TENCENT_CDN_RES:nV.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?fV:TV,data:e,timeout:5e3,responseCommand:t?nV.STOP_PUBLISH_TENCENT_CDN_RES:nV.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:\"stopPublishCDN\"})}sendAbilityStatus(e){var t;null==(t=this._signalChannel)||t.sendWaitForResponse({command:kV,data:e,timeout:5e3,responseCommand:nV.ABILITY_STATUS_REPORT_RESULT,commandDesc:\"ability status report\"}).catch((e=>{}))}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=Ib.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())||{clientIp:\"\",relayIp:\"\"}}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink(\"you exitRoom\"),this._signalChannel&&(e&&this._signalChannel.keepAlive&&this._signalChannel.isConnected?this._signalChannel.stopKeepAliveIn(3600):this._signalChannel.close(),this.setSignalChannel(null)),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return ab(this,null,(function*(){let 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 n=e.getUserId(),r=this._changeBigSmallRecords.get(n)||{},{subscribeState:o}=e,{options:s,isSubscribing:a,reSubscribeCount:c}=r;if(s.video&&o.video||s.smallVideo&&o.smallVideo&&t||a)return;let l={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:s.video,smallVideo:s.smallVideo};if(t&&e.isBigStreamSubscribed||e.isSmallStreamSubscribed)try{s&&!a&&c>=1&&(r.isSubscribing=!0,r.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(n,\"] to \").concat(l.smallVideo?\"small\":\"big\",\" video successfully. count \").concat(DD-r.reSubscribeCount,\".\")),r.isSubscribing=!1,r.reSubscribeCount=DD)}catch(d){this._log.info(\"change [\".concat(n,\"] to \").concat(l.smallVideo?\"small\":\"big\",\" video failed. count \").concat(DD-r.reSubscribeCount,\".\")),r.isSubscribing=!1,0===c&&this._changeBigSmallRecords.delete(n)}}))}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:DD};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(pU(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!mU(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new gb({code:mb.INVALID_PARAMETER,message:qO({key:JO.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!mU(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new gb({code:mb.INVALID_PARAMETER,message:qO({key:JO.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!mU(e.userDefinePushArgs)){if(!(pU(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new gb({code:mb.INVALID_PARAMETER,message:qO({key:JO.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}TU(t)||(this._businessInfo=JSON.stringify(t))}sendSEI(e,t){var i;null==(i=this.uplinkConnection)||i.sendSEI(e,t)}};return rb([Bw([\"left\",Gw.INIT],\"joined\"),tx({settings:{retries:1,timeout:0},onError(e,t,i){this._isUsingCachedSchedule&&!this._isDestroyed?(this._log.warn(\"is using cached schedule, retry join\"),mx(!0),this.reset(),t()):this._signalChannel&&this._signalChannel.isConnected&&this._signalChannel.keepAlive?(this._log.warn(\"is using keepAlive ws, retry join\"),this._signalChannel.close(),this.reset(),t()):(this.reset(),this._log.error(e),i(e))}}),iL((e=>{let t=new WM;return function(i,n,r){return ab(this,null,(function*(){let o=String(i.roomId||i.strRoomId);if(this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.userSig=i.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=n,i.privateMapKey=i.privateMapKey||\"\",this.isJoined)throw new gb({code:mb.INVALID_OPERATION,message:qO({key:JO.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new gb({code:mb.INVALID_OPERATION,message:qO({key:JO.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:o}),this.role=21===i.role?\"audience\":\"anchor\",this._log.info(\"Join() => joining room: \".concat(o,\" useStringRoomId: \").concat(this.useStringRoomId,\" scene: \").concat(this.scene,\" role: \").concat(this.role)),xO.emit(FO.JOIN_START,{room:this,roomId:o,params:i}),this.checkSystemResult=yield WO.checkSystemRequirementsInternal(),this.checkDestroy();let s=Ib.getEnv();s||(s=AN.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(VN.OLD_CLOUD_LADDER)?s=AN.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(VN.WEBRTC)&&(s=AN.WEBRTC))),Qw.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),JM.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!WO.isWebRTCSupported()||!a&&!c)throw new gb({code:mb.NOT_SUPPORTED,message:qO({key:JO.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Ib.getEnv()&&(yield this.schedule(o,r,rN));let t=yield e.call(this,i,n,r);return this.roomId=o,this._joinedTimestamp=Ib.performanceNow(),xO.emit(FO.JOIN_SUCCESS,{room:this}),Qw.uploadEvent({log:\"stat-conv-\".concat(Number(Yk),\"-\").concat(location.hostname),userId:this.userId}),t}catch(l){throw t.delete({room:this,roomId:o}),xO.emit(FO.JOIN_FAILED,{room:this,error:l}),l}}))}}))],EU.prototype,\"join\",1),rb([Bw(\"joined\",\"left\",{ignoreError:!0,success(){this.reset(!0)}}),iL((e=>function(){return ab(this,null,(function*(){xO.emit(FO.LEAVE_START,{room:this}),yield e.call(this),xO.emit(FO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),function(e){return function(t,i,n){let r=n.value;return n.value=function(){var t,i;let n=[];for(var o=arguments.length,s=new Array(o),a=0;an.push(e))),null==(i=Hx.get(this))||i.forEach((e=>e.forEach((e=>n.push(e))))),n.forEach((t=>{t.reject(new gb({code:mb.API_CALL_ABORTED,message:e}))})),Bx.delete(this),Hx.delete(this),r.apply(this,s)},n}}(\"leave room\"),ix({fnName:\"publish\",validateArgs:!1}),ix({fnName:\"unsubscribe\",validateArgs:!1})],EU.prototype,\"leave\",1),rb([jx(),iL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;ne.outMediaTrack&&\"capture\"===e.state)),!i.length))return;xO.emit(\"61\",{room:this}),i.forEach((e=>{\"audio\"===e.kind&&this.audioManager.addAudioTrack(e)}));let t=e.apply(this,i);return i.forEach((e=>{var i;e.publish(this,t),\"audio\"===e.kind&&(null==(i=this.audioManager.localMixAudioTrack)||i.publish(this,t))})),t}))})),tx({settings:{retries:oD,timeout:e=>eO(e)},onError(e,t,i){var n;null!=(n=e.message)&&n.includes(\"timeout\")?(this._log.warn(\"publish timeout\"),t()):(this._log.error(\"publish failed: \".concat(e)),i(e),xO.emit(FO.PUBLISH_FAILED,{room:this}))}})],EU.prototype,\"publish\",1),rb([ix({fnName:\"publish\",callback(){for(var e,t=arguments.length,i=new Array(t),n=0;ne.unpublish())))}}),function(e){return function(t,i,n){let r=n.value;return n.value=function(){for(var t=arguments.length,i=new Array(t),n=0;n{if(0===n)return!0;let r=!0;return t.args.forEach((e=>{i.find((t=>t===e))||(r=!1)})),!r||(t.reject(new gb({code:mb.API_CALL_ABORTED,message:e})),!1)}));Bx.set(this,t)}return r.apply(this,i)},n}}(\"api-call\"),jx(),iL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n{\"audio\"===e.kind&&this.audioManager.removeAudioTrack(e)}));let r=e.apply(this,i);return i.forEach((e=>e.unpublish())),r}))],EU.prototype,\"unpublish\",1),rb([Gx((function(){for(var e=arguments.length,t=new Array(e),i=0;ifunction(){for(var t=arguments.length,i=new Array(t),n=0;n!e.isSubscribed&&e.subscribe(r))),r})),tx({settings:{retries:oD,timeout:e=>eO(e)},onError(e,t,i,n){e.message.includes(\"timeout\")?(this._log.warn(\"subscribe timeout\"),t()):(this._log.error(\"subscribe failed: \".concat(e)),i(e),xO.emit(FO.SUBSCRIBE_FAILED,{room:this,remoteTracks:n}))}})],EU.prototype,\"subscribe\",1),rb([ix({fnName:\"subscribe\",callback(){for(var e=arguments.length,t=new Array(e),i=0;i{let t=this.remotePublishedUserMap.get(e.userId);t&&!t.isMainStreamSubscribed&&!t.isAuxStreamSubscribed&&t.close(\"you unsubscribed\")}))}}),Gx((function(){for(var e=arguments.length,t=new Array(e),i=0;i